FimfictionApi: improve bbcode description handling
[nikiroo-utils.git] / src / be / nikiroo / fanfix / supported / FimfictionApi.java
CommitLineData
315f14ae
NR
1package be.nikiroo.fanfix.supported;
2
3import java.io.IOException;
4import java.io.InputStream;
5import java.net.URL;
6import java.util.ArrayList;
7import java.util.HashMap;
8import java.util.List;
9import java.util.Map;
10import java.util.Map.Entry;
11
12import be.nikiroo.fanfix.Instance;
13import be.nikiroo.fanfix.bundles.Config;
14import be.nikiroo.fanfix.data.MetaData;
15import be.nikiroo.utils.IOUtils;
16import be.nikiroo.utils.Progress;
17
18/**
19 * Support class for <a href="http://www.fimfiction.net/">FimFiction.net</a>
20 * stories, a website dedicated to My Little Pony.
21 * <p>
22 * This version uses the new, official API of FimFiction.
23 *
24 * @author niki
25 */
26class FimfictionApi extends BasicSupport {
27 private String oauth;
28 private String storyId;
29 private String json;
30
31 private Map<Integer, String> chapterNames;
32 private Map<Integer, String> chapterContents;
33
34 public FimfictionApi() throws IOException {
35 if (Instance.getConfig().getBoolean(
36 Config.LOGIN_FIMFICTION_APIKEY_FORCE_HTML, false)) {
37 throw new IOException(
38 "Configuration is set to force HTML scrapping");
39 }
40
41 String oauth = Instance.getConfig().getString(
42 Config.LOGIN_FIMFICTION_APIKEY_TOKEN);
43
44 if (oauth == null || oauth.isEmpty()) {
45 String clientId = Instance.getConfig().getString(
46 Config.LOGIN_FIMFICTION_APIKEY_CLIENT_ID)
47 + "";
48 String clientSecret = Instance.getConfig().getString(
49 Config.LOGIN_FIMFICTION_APIKEY_CLIENT_SECRET)
50 + "";
51
52 if (clientId.trim().isEmpty() || clientSecret.trim().isEmpty()) {
53 throw new IOException("API key required for the beta API v2");
54 }
55
56 oauth = generateOAuth(clientId, clientSecret);
57
58 Instance.getConfig().setString(
59 Config.LOGIN_FIMFICTION_APIKEY_TOKEN, oauth);
60 Instance.getConfig().updateFile();
61 }
62
63 this.oauth = oauth;
64 }
65
66 @Override
67 public String getOAuth() {
68 return oauth;
69 }
70
71 @Override
72 protected boolean isHtml() {
73 return true;
74 }
75
76 @Override
77 public String getSourceName() {
78 return "FimFiction.net";
79 }
80
81 @Override
82 protected void preprocess(URL source, InputStream in) throws IOException {
83 // extract the ID from:
84 // https://www.fimfiction.net/story/123456/name-of-story
85 storyId = getKeyText(source.toString(), "/story/", null, "/");
86
87 // Selectors, so to download all I need and only what I need
88 String storyContent = "fields[story]=title,description,date_published,cover_image";
89 String authorContent = "fields[author]=name";
90 String chapterContent = "fields[chapter]=chapter_number,title,content,authors_note";
91 String contentContent = "fields[content]=html";
92 String authorsNoteContent = "fields[authors_note]=html";
93 String includes = "author,chapters,tags";
94
95 String urlString = String.format(
96 "https://www.fimfiction.net/api/v2/stories/%s?" //
97 + "%s&%s&"//
98 + "%s&%s&%s&" //
99 + "include=%s", //
100 storyId, //
101 storyContent, authorContent, //
102 chapterContent, contentContent, authorsNoteContent,//
103 includes);
104
105 // URL params must be URL-encoded: "[ ]" <-> "%5B %5D"
106 urlString = urlString.replace("[", "%5B").replace("]", "%5D");
107
108 URL url = new URL(urlString);
109 InputStream jsonIn = Instance.getCache().open(url, this, false);
110 try {
111 json = IOUtils.readSmallStream(jsonIn);
112 } finally {
113 jsonIn.close();
114 }
115 }
116
117 @Override
118 protected InputStream openInput(URL source) throws IOException {
119 return null;
120 }
121
122 @Override
123 protected MetaData getMeta(URL source, InputStream in) throws IOException {
124 MetaData meta = new MetaData();
125
126 meta.setTitle(getKeyJson(json, 0, "type", "story", "title"));
127 meta.setAuthor(getKeyJson(json, 0, "type", "user", "name"));
128 meta.setDate(getKeyJson(json, 0, "type", "story", "date_published"));
129 meta.setTags(getTags());
130 meta.setSource(getSourceName());
131 meta.setUrl(source.toString());
132 meta.setPublisher(getSourceName());
133 meta.setUuid(source.toString());
134 meta.setLuid("");
135 meta.setLang("EN");
136 meta.setSubject("MLP");
137 meta.setType(getType().toString());
138 meta.setImageDocument(false);
139 meta.setCover(getImage(this, null,
140 getKeyJson(json, 0, "type", "story", "cover_image", "full")));
141
142 return meta;
143 }
144
145 private List<String> getTags() {
146 List<String> tags = new ArrayList<String>();
147 tags.add("MLP");
148
149 int pos = 0;
150 while (pos >= 0) {
151 pos = indexOfJsonAfter(json, pos, "type", "story_tag");
152 if (pos >= 0) {
153 tags.add(getKeyJson(json, pos, "name"));
154 }
155 }
156
157 return tags;
158 }
159
160 @Override
161 protected String getDesc(URL source, InputStream in) {
d9a94285
NR
162 String desc = getKeyJson(json, 0, "type", "story", "description");
163
164 // TODO: if the description becomes available in html, use it
165 desc = desc.replace("\\r\\n", "<br/>");
166 desc = desc.replace("[i]", "_").replace("[/i]", "_")
167 .replace("[b]", "*").replace("[/b]", "*");
168 desc = desc.replaceAll("\\[[^\\]]*\\]", "");
169
170 return desc;
315f14ae
NR
171 }
172
173 @Override
174 protected List<Entry<String, URL>> getChapters(URL source, InputStream in,
175 Progress pg) {
176 List<Entry<String, URL>> urls = new ArrayList<Entry<String, URL>>();
177
178 chapterNames = new HashMap<Integer, String>();
179 chapterContents = new HashMap<Integer, String>();
180
181 int pos = 0;
182 while (pos >= 0) {
183 pos = indexOfJsonAfter(json, pos, "type", "chapter");
184 if (pos >= 0) {
185 int posNumber = indexOfJsonAfter(json, pos, "chapter_number");
186 int posComa = json.indexOf(",", posNumber);
187 final int number = Integer.parseInt(json.substring(posNumber,
188 posComa).trim());
189 final String title = getKeyJson(json, pos, "title");
190 String notes = getKeyJson(json, pos, "authors_note", "html");
191 String content = getKeyJson(json, pos, "content", "html");
192
193 chapterNames.put(number, title);
194 chapterContents
195 .put(number, content + "<br/>* * *<br/>" + notes);
196
197 urls.add(new Entry<String, URL>() {
198 @Override
199 public URL setValue(URL value) {
200 return null;
201 }
202
203 @Override
204 public String getKey() {
205 return title;
206 }
207
208 @Override
209 public URL getValue() {
210 return null;
211 }
212 });
213 }
214 }
215
216 return urls;
217 }
218
219 @Override
220 protected String getChapterContent(URL source, InputStream in, int number,
221 Progress pg) {
222 return chapterContents.get(number);
223 }
224
225 @Override
226 protected boolean supports(URL url) {
227 return "fimfiction.net".equals(url.getHost())
228 || "www.fimfiction.net".equals(url.getHost());
229 }
230
231 static private String generateOAuth(String clientId, String clientSecret)
232 throws IOException {
233 URL url = new URL("https://www.fimfiction.net/api/v2/token");
234 Map<String, String> params = new HashMap<String, String>();
235 params.put("client_id", clientId);
236 params.put("client_secret", clientSecret);
237 params.put("grant_type", "client_credentials");
238 InputStream in = Instance.getCache().openNoCache(url, null, params,
239 null, null);
240
241 String jsonToken = IOUtils.readSmallStream(in);
242
243 // Extract token type and token from: {
244 // token_type = "bearer",
245 // access_token = "xxxxxxxxxxxxxx"
246 // }
247
248 String token = getKeyText(jsonToken, "\"access_token\"", "\"", "\"");
249 String tokenType = getKeyText(jsonToken, "\"token_type\"", "\"", "\"");
250
251 // TODO: remove this once the bug is fixed on the server side
252 if ("bearer".equals(tokenType)) {
253 tokenType = "Bearer";
254 }
255
256 return tokenType + " " + token;
257 }
258
259 // afters: [name, value] pairs (or "" for any of them), can end without
260 // value
261 static private int indexOfJsonAfter(String json, int startAt,
262 String... afterKeys) {
263 ArrayList<String> afters = new ArrayList<String>();
264 boolean name = true;
265 for (String key : afterKeys) {
266 if (key != null && !key.isEmpty()) {
267 afters.add("\"" + key + "\"");
268 } else {
269 afters.add("\"");
270 afters.add("\"");
271 }
272
273 if (name) {
274 afters.add(":");
275 }
276
277 name = !name;
278 }
279
280 return indexOfAfter(json, startAt, afters.toArray(new String[] {}));
281 }
282
283 // afters: [name, value] pairs (or "" for any of them), can end without
284 // value
285 static private String getKeyJson(String json, int startAt,
286 String... afterKeys) {
287 int pos = indexOfJsonAfter(json, startAt, afterKeys);
288 if (pos < 0) {
289 return null;
290 }
291
37fdbdef
NR
292 String result = null;
293 String wip = json.substring(pos);
294
295 pos = nextUnescapedQuote(wip, 0);
296 if (pos >= 0) {
297 wip = wip.substring(pos + 1);
298 pos = nextUnescapedQuote(wip, 0);
299 if (pos >= 0) {
300 result = wip.substring(0, pos);
301 }
302 }
303
304 return result;
305 }
306
307 // next " but don't take \" into account
308 static private int nextUnescapedQuote(String result, int pos) {
309 while (pos >= 0) {
310 pos = result.indexOf("\"", pos);
311 if (pos == 0 || (pos > 0 && result.charAt(pos - 1) != '\\')) {
312 break;
313 }
314
315 if (pos < result.length()) {
316 pos++;
317 }
318 }
319
320 return pos;
315f14ae
NR
321 }
322}