Merge branch 'master' into subtree
[nikiroo-utils.git] / supported / FimfictionApi.java
1 package be.nikiroo.fanfix.supported;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.net.URL;
6 import java.util.AbstractMap;
7 import java.util.ArrayList;
8 import java.util.HashMap;
9 import java.util.List;
10 import java.util.Map;
11 import java.util.Map.Entry;
12 import java.util.TreeMap;
13
14 import org.jsoup.nodes.Document;
15
16 import be.nikiroo.fanfix.Instance;
17 import be.nikiroo.fanfix.bundles.Config;
18 import be.nikiroo.fanfix.data.MetaData;
19 import be.nikiroo.fanfix.data.Story;
20 import be.nikiroo.utils.IOUtils;
21 import be.nikiroo.utils.Image;
22 import be.nikiroo.utils.Progress;
23
24 /**
25 * Support class for <a href="http://www.fimfiction.net/">FimFiction.net</a>
26 * stories, a website dedicated to My Little Pony.
27 * <p>
28 * This version uses the new, official API of FimFiction.
29 *
30 * @author niki
31 */
32 class FimfictionApi extends BasicSupport {
33 private String oauth;
34 private String json;
35
36 private Map<Integer, String> chapterNames;
37 private Map<Integer, String> chapterContents;
38
39 public FimfictionApi() throws IOException {
40 if (Instance.getInstance().getConfig().getBoolean(Config.LOGIN_FIMFICTION_APIKEY_FORCE_HTML, false)) {
41 throw new IOException("Configuration is set to force HTML scrapping");
42 }
43
44 String oauth = Instance.getInstance().getConfig().getString(Config.LOGIN_FIMFICTION_APIKEY_TOKEN);
45
46 if (oauth == null || oauth.isEmpty()) {
47 String clientId = Instance.getInstance().getConfig().getString(Config.LOGIN_FIMFICTION_APIKEY_CLIENT_ID)
48 + "";
49 String clientSecret = Instance.getInstance().getConfig()
50 .getString(Config.LOGIN_FIMFICTION_APIKEY_CLIENT_SECRET) + "";
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.getInstance().getConfig().setString(Config.LOGIN_FIMFICTION_APIKEY_TOKEN, oauth);
59 Instance.getInstance().getConfig().updateFile();
60 }
61
62 this.oauth = oauth;
63 }
64
65 @Override
66 protected Document loadDocument(URL source) throws IOException {
67 json = getJsonData();
68 return null;
69 }
70
71 @Override
72 public String getOAuth() {
73 return oauth;
74 }
75
76 @Override
77 protected boolean isHtml() {
78 return true;
79 }
80
81 /**
82 * Extract the full JSON data we will later use to build the {@link Story}.
83 *
84 * @return the data in a JSON format
85 *
86 * @throws IOException
87 * in case of I/O error
88 */
89 private String getJsonData() throws IOException {
90 // extract the ID from:
91 // https://www.fimfiction.net/story/123456/name-of-story
92 String storyId = getKeyText(getSource().toString(), "/story/", null,
93 "/");
94
95 // Selectors, so to download all I need and only what I need
96 String storyContent = "fields[story]=title,description,date_published,cover_image";
97 String authorContent = "fields[author]=name";
98 String chapterContent = "fields[chapter]=chapter_number,title,content_html,authors_note_html";
99 String includes = "author,chapters,tags";
100
101 String urlString = String.format(
102 "https://www.fimfiction.net/api/v2/stories/%s?" //
103 + "%s&%s&%s&" //
104 + "include=%s", //
105 storyId, //
106 storyContent, authorContent, chapterContent,//
107 includes);
108
109 // URL params must be URL-encoded: "[ ]" <-> "%5B %5D"
110 urlString = urlString.replace("[", "%5B").replace("]", "%5D");
111
112 URL url = new URL(urlString);
113 InputStream jsonIn = Instance.getInstance().getCache().open(url, this, false);
114 try {
115 return IOUtils.readSmallStream(jsonIn);
116 } finally {
117 jsonIn.close();
118 }
119 }
120
121 @Override
122 protected MetaData getMeta() throws IOException {
123 MetaData meta = new MetaData();
124
125 meta.setTitle(getKeyJson(json, 0, "type", "story", "title"));
126 meta.setAuthor(getKeyJson(json, 0, "type", "user", "name"));
127 meta.setDate(bsHelper.formatDate(
128 getKeyJson(json, 0, "type", "story", "date_published")));
129 meta.setTags(getTags());
130 meta.setUrl(getSource().toString());
131 meta.setUuid(getSource().toString());
132 meta.setLuid("");
133 meta.setLang("en");
134 meta.setSubject("MLP");
135 meta.setImageDocument(false);
136
137 String coverImageLink = getKeyJson(json, 0, "type", "story",
138 "cover_image", "full");
139 if (!coverImageLink.trim().isEmpty()) {
140 URL coverImageUrl = new URL(coverImageLink.trim());
141
142 // No need to use the oauth, cookies... for the cover
143 // Plus: it crashes on Android because of the referer
144 try {
145 InputStream in = Instance.getInstance().getCache().open(coverImageUrl, null, true);
146 try {
147 Image img = new Image(in);
148 if (img.getSize() == 0) {
149 img.close();
150 throw new IOException(
151 "Empty image not accepted");
152 }
153 meta.setCover(img);
154 } finally {
155 in.close();
156 }
157 } catch (IOException e) {
158 Instance.getInstance().getTraceHandler()
159 .error(new IOException("Cannot get the story cover, ignoring...", e));
160 }
161 }
162
163 return meta;
164 }
165
166 private List<String> getTags() {
167 List<String> tags = new ArrayList<String>();
168 tags.add("MLP");
169
170 int pos = 0;
171 while (pos >= 0) {
172 pos = indexOfJsonAfter(json, pos, "type", "story_tag");
173 if (pos >= 0) {
174 tags.add(getKeyJson(json, pos, "name").trim());
175 }
176 }
177
178 return tags;
179 }
180
181 @Override
182 protected String getDesc() {
183 String desc = getKeyJson(json, 0, "type", "story", "description");
184 return unbbcode(desc);
185 }
186
187 @Override
188 protected List<Entry<String, URL>> getChapters(Progress pg) {
189 chapterNames = new TreeMap<Integer, String>();
190 chapterContents = new TreeMap<Integer, String>();
191
192 int pos = 0;
193 while (pos >= 0) {
194 pos = indexOfJsonAfter(json, pos, "type", "chapter");
195 if (pos >= 0) {
196 int posNumber = indexOfJsonAfter(json, pos, "chapter_number");
197 int posComa = json.indexOf(",", posNumber);
198 final int number = Integer.parseInt(json.substring(posNumber,
199 posComa).trim());
200 final String title = getKeyJson(json, pos, "title");
201 String notes = getKeyJson(json, pos, "authors_note_html");
202 String content = getKeyJson(json, pos, "content_html");
203
204 if (!notes.trim().isEmpty()) {
205 notes = "<br/>* * *<br/>" + notes;
206 }
207
208 chapterNames.put(number, title);
209 chapterContents.put(number, content + notes);
210 }
211 }
212
213 List<Entry<String, URL>> urls = new ArrayList<Entry<String, URL>>();
214 for (String title : chapterNames.values()) {
215 urls.add(new AbstractMap.SimpleEntry<String, URL>(title, null));
216 }
217
218 return urls;
219 }
220
221 @Override
222 protected String getChapterContent(URL source, int number, Progress pg) {
223 return chapterContents.get(number);
224 }
225
226 @Override
227 protected boolean supports(URL url) {
228 return "fimfiction.net".equals(url.getHost())
229 || "www.fimfiction.net".equals(url.getHost());
230 }
231
232 /**
233 * Generate a new token from the client ID and secret.
234 * <p>
235 * Note that those tokens are long-lived, and it would be badly seen to
236 * create a lot of them without due cause.
237 * <p>
238 * So, please cache and re-use them.
239 *
240 * @param clientId
241 * the client ID offered on FimFiction
242 * @param clientSecret
243 * the client secret that goes with it
244 *
245 * @return a new generated token linked to that client ID
246 *
247 * @throws IOException
248 * in case of I/O errors
249 */
250 static private String generateOAuth(String clientId, String clientSecret)
251 throws IOException {
252 URL url = new URL("https://www.fimfiction.net/api/v2/token");
253 Map<String, String> params = new HashMap<String, String>();
254 params.put("client_id", clientId);
255 params.put("client_secret", clientSecret);
256 params.put("grant_type", "client_credentials");
257 InputStream in = Instance.getInstance().getCache().openNoCache(url, null, params, null, null);
258
259 String jsonToken = IOUtils.readSmallStream(in);
260 in.close();
261
262 // Extract token type and token from: {
263 // token_type = "Bearer",
264 // access_token = "xxxxxxxxxxxxxx"
265 // }
266
267 String tokenType = getKeyText(jsonToken, "\"token_type\"", "\"", "\"");
268 String token = getKeyText(jsonToken, "\"access_token\"", "\"", "\"");
269
270 return tokenType + " " + token;
271 }
272
273 // afters: [name, value] pairs (or "" for any of them), can end without
274 // value
275 static private int indexOfJsonAfter(String json, int startAt,
276 String... afterKeys) {
277 ArrayList<String> afters = new ArrayList<String>();
278 boolean name = true;
279 for (String key : afterKeys) {
280 if (key != null && !key.isEmpty()) {
281 afters.add("\"" + key + "\"");
282 } else {
283 afters.add("\"");
284 afters.add("\"");
285 }
286
287 if (name) {
288 afters.add(":");
289 }
290
291 name = !name;
292 }
293
294 return indexOfAfter(json, startAt, afters.toArray(new String[] {}));
295 }
296
297 // afters: [name, value] pairs (or "" for any of them), can end without
298 // value but will then be empty, not NULL
299 static private String getKeyJson(String json, int startAt,
300 String... afterKeys) {
301 int pos = indexOfJsonAfter(json, startAt, afterKeys);
302 if (pos < 0) {
303 return "";
304 }
305
306 String result = "";
307 String wip = json.substring(pos);
308
309 pos = nextUnescapedQuote(wip, 0);
310 if (pos >= 0) {
311 wip = wip.substring(pos + 1);
312 pos = nextUnescapedQuote(wip, 0);
313 if (pos >= 0) {
314 result = wip.substring(0, pos);
315 }
316 }
317
318 result = result.replace("\\t", "\t").replace("\\\"", "\"");
319
320 return result;
321 }
322
323 // next " but don't take \" into account
324 static private int nextUnescapedQuote(String result, int pos) {
325 while (pos >= 0) {
326 pos = result.indexOf("\"", pos);
327 if (pos == 0 || (pos > 0 && result.charAt(pos - 1) != '\\')) {
328 break;
329 }
330
331 if (pos < result.length()) {
332 pos++;
333 }
334 }
335
336 return pos;
337 }
338
339 // quick & dirty filter
340 static private String unbbcode(String bbcode) {
341 String text = bbcode.replace("\\r\\n", "<br/>") //
342 .replace("[i]", "_").replace("[/i]", "_") //
343 .replace("[b]", "*").replace("[/b]", "*") //
344 .replaceAll("\\[[^\\]]*\\]", "");
345 return text;
346 }
347
348 /**
349 * Return the text between the key and the endKey (and optional subKey can
350 * be passed, in this case we will look for the key first, then take the
351 * text between the subKey and the endKey).
352 *
353 * @param in
354 * the input
355 * @param key
356 * the key to match (also supports "^" at start to say
357 * "only if it starts with" the key)
358 * @param subKey
359 * the sub key or NULL if none
360 * @param endKey
361 * the end key or NULL for "up to the end"
362 * @return the text or NULL if not found
363 */
364 static private String getKeyText(String in, String key, String subKey,
365 String endKey) {
366 String result = null;
367
368 String line = in;
369 if (line != null && line.contains(key)) {
370 line = line.substring(line.indexOf(key) + key.length());
371 if (subKey == null || subKey.isEmpty() || line.contains(subKey)) {
372 if (subKey != null) {
373 line = line.substring(line.indexOf(subKey)
374 + subKey.length());
375 }
376 if (endKey == null || line.contains(endKey)) {
377 if (endKey != null) {
378 line = line.substring(0, line.indexOf(endKey));
379 result = line;
380 }
381 }
382 }
383 }
384
385 return result;
386 }
387
388 /**
389 * Return the first index after all the given "afters" have been found in
390 * the {@link String}, or -1 if it was not possible.
391 *
392 * @param in
393 * the input
394 * @param startAt
395 * start at this position in the string
396 * @param afters
397 * the sub-keys to find before checking for key/endKey
398 *
399 * @return the text or NULL if not found
400 */
401 static private int indexOfAfter(String in, int startAt, String... afters) {
402 int pos = -1;
403 if (in != null && !in.isEmpty()) {
404 pos = startAt;
405 if (afters != null) {
406 for (int i = 0; pos >= 0 && i < afters.length; i++) {
407 String subKey = afters[i];
408 if (!subKey.isEmpty()) {
409 pos = in.indexOf(subKey, pos);
410 if (pos >= 0) {
411 pos += subKey.length();
412 }
413 }
414 }
415 }
416 }
417
418 return pos;
419 }
420 }