Merge branch 'subtree'
[fanfix.git] / src / be / nikiroo / fanfix / 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(getKeyJson(json, 0, "type", "story", "date_published"));
128 meta.setTags(getTags());
129 meta.setSource(getType().getSourceName());
130 meta.setUrl(getSource().toString());
131 meta.setPublisher(getType().getSourceName());
132 meta.setUuid(getSource().toString());
133 meta.setLuid("");
134 meta.setLang("en");
135 meta.setSubject("MLP");
136 meta.setType(getType().toString());
137 meta.setImageDocument(false);
138
139 String coverImageLink = getKeyJson(json, 0, "type", "story",
140 "cover_image", "full");
141 if (!coverImageLink.trim().isEmpty()) {
142 URL coverImageUrl = new URL(coverImageLink.trim());
143
144 // No need to use the oauth, cookies... for the cover
145 // Plus: it crashes on Android because of the referer
146 try {
147 InputStream in = Instance.getInstance().getCache().open(coverImageUrl, null, true);
148 try {
149 meta.setCover(new Image(in));
150 } finally {
151 in.close();
152 }
153 } catch (IOException e) {
154 Instance.getInstance().getTraceHandler()
155 .error(new IOException("Cannot get the story cover, ignoring...", e));
156 }
157 }
158
159 return meta;
160 }
161
162 private List<String> getTags() {
163 List<String> tags = new ArrayList<String>();
164 tags.add("MLP");
165
166 int pos = 0;
167 while (pos >= 0) {
168 pos = indexOfJsonAfter(json, pos, "type", "story_tag");
169 if (pos >= 0) {
170 tags.add(getKeyJson(json, pos, "name").trim());
171 }
172 }
173
174 return tags;
175 }
176
177 @Override
178 protected String getDesc() {
179 String desc = getKeyJson(json, 0, "type", "story", "description");
180 return unbbcode(desc);
181 }
182
183 @Override
184 protected List<Entry<String, URL>> getChapters(Progress pg) {
185 chapterNames = new TreeMap<Integer, String>();
186 chapterContents = new TreeMap<Integer, String>();
187
188 int pos = 0;
189 while (pos >= 0) {
190 pos = indexOfJsonAfter(json, pos, "type", "chapter");
191 if (pos >= 0) {
192 int posNumber = indexOfJsonAfter(json, pos, "chapter_number");
193 int posComa = json.indexOf(",", posNumber);
194 final int number = Integer.parseInt(json.substring(posNumber,
195 posComa).trim());
196 final String title = getKeyJson(json, pos, "title");
197 String notes = getKeyJson(json, pos, "authors_note_html");
198 String content = getKeyJson(json, pos, "content_html");
199
200 if (!notes.trim().isEmpty()) {
201 notes = "<br/>* * *<br/>" + notes;
202 }
203
204 chapterNames.put(number, title);
205 chapterContents.put(number, content + notes);
206 }
207 }
208
209 List<Entry<String, URL>> urls = new ArrayList<Entry<String, URL>>();
210 for (String title : chapterNames.values()) {
211 urls.add(new AbstractMap.SimpleEntry<String, URL>(title, null));
212 }
213
214 return urls;
215 }
216
217 @Override
218 protected String getChapterContent(URL source, int number, Progress pg) {
219 return chapterContents.get(number);
220 }
221
222 @Override
223 protected boolean supports(URL url) {
224 return "fimfiction.net".equals(url.getHost())
225 || "www.fimfiction.net".equals(url.getHost());
226 }
227
228 /**
229 * Generate a new token from the client ID and secret.
230 * <p>
231 * Note that those tokens are long-lived, and it would be badly seen to
232 * create a lot of them without due cause.
233 * <p>
234 * So, please cache and re-use them.
235 *
236 * @param clientId
237 * the client ID offered on FimFiction
238 * @param clientSecret
239 * the client secret that goes with it
240 *
241 * @return a new generated token linked to that client ID
242 *
243 * @throws IOException
244 * in case of I/O errors
245 */
246 static private String generateOAuth(String clientId, String clientSecret)
247 throws IOException {
248 URL url = new URL("https://www.fimfiction.net/api/v2/token");
249 Map<String, String> params = new HashMap<String, String>();
250 params.put("client_id", clientId);
251 params.put("client_secret", clientSecret);
252 params.put("grant_type", "client_credentials");
253 InputStream in = Instance.getInstance().getCache().openNoCache(url, null, params, null, null);
254
255 String jsonToken = IOUtils.readSmallStream(in);
256 in.close();
257
258 // Extract token type and token from: {
259 // token_type = "Bearer",
260 // access_token = "xxxxxxxxxxxxxx"
261 // }
262
263 String tokenType = getKeyText(jsonToken, "\"token_type\"", "\"", "\"");
264 String token = getKeyText(jsonToken, "\"access_token\"", "\"", "\"");
265
266 return tokenType + " " + token;
267 }
268
269 // afters: [name, value] pairs (or "" for any of them), can end without
270 // value
271 static private int indexOfJsonAfter(String json, int startAt,
272 String... afterKeys) {
273 ArrayList<String> afters = new ArrayList<String>();
274 boolean name = true;
275 for (String key : afterKeys) {
276 if (key != null && !key.isEmpty()) {
277 afters.add("\"" + key + "\"");
278 } else {
279 afters.add("\"");
280 afters.add("\"");
281 }
282
283 if (name) {
284 afters.add(":");
285 }
286
287 name = !name;
288 }
289
290 return indexOfAfter(json, startAt, afters.toArray(new String[] {}));
291 }
292
293 // afters: [name, value] pairs (or "" for any of them), can end without
294 // value but will then be empty, not NULL
295 static private String getKeyJson(String json, int startAt,
296 String... afterKeys) {
297 int pos = indexOfJsonAfter(json, startAt, afterKeys);
298 if (pos < 0) {
299 return "";
300 }
301
302 String result = "";
303 String wip = json.substring(pos);
304
305 pos = nextUnescapedQuote(wip, 0);
306 if (pos >= 0) {
307 wip = wip.substring(pos + 1);
308 pos = nextUnescapedQuote(wip, 0);
309 if (pos >= 0) {
310 result = wip.substring(0, pos);
311 }
312 }
313
314 result = result.replace("\\t", "\t").replace("\\\"", "\"");
315
316 return result;
317 }
318
319 // next " but don't take \" into account
320 static private int nextUnescapedQuote(String result, int pos) {
321 while (pos >= 0) {
322 pos = result.indexOf("\"", pos);
323 if (pos == 0 || (pos > 0 && result.charAt(pos - 1) != '\\')) {
324 break;
325 }
326
327 if (pos < result.length()) {
328 pos++;
329 }
330 }
331
332 return pos;
333 }
334
335 // quick & dirty filter
336 static private String unbbcode(String bbcode) {
337 String text = bbcode.replace("\\r\\n", "<br/>") //
338 .replace("[i]", "_").replace("[/i]", "_") //
339 .replace("[b]", "*").replace("[/b]", "*") //
340 .replaceAll("\\[[^\\]]*\\]", "");
341 return text;
342 }
343
344 /**
345 * Return the text between the key and the endKey (and optional subKey can
346 * be passed, in this case we will look for the key first, then take the
347 * text between the subKey and the endKey).
348 *
349 * @param in
350 * the input
351 * @param key
352 * the key to match (also supports "^" at start to say
353 * "only if it starts with" the key)
354 * @param subKey
355 * the sub key or NULL if none
356 * @param endKey
357 * the end key or NULL for "up to the end"
358 * @return the text or NULL if not found
359 */
360 static private String getKeyText(String in, String key, String subKey,
361 String endKey) {
362 String result = null;
363
364 String line = in;
365 if (line != null && line.contains(key)) {
366 line = line.substring(line.indexOf(key) + key.length());
367 if (subKey == null || subKey.isEmpty() || line.contains(subKey)) {
368 if (subKey != null) {
369 line = line.substring(line.indexOf(subKey)
370 + subKey.length());
371 }
372 if (endKey == null || line.contains(endKey)) {
373 if (endKey != null) {
374 line = line.substring(0, line.indexOf(endKey));
375 result = line;
376 }
377 }
378 }
379 }
380
381 return result;
382 }
383
384 /**
385 * Return the first index after all the given "afters" have been found in
386 * the {@link String}, or -1 if it was not possible.
387 *
388 * @param in
389 * the input
390 * @param startAt
391 * start at this position in the string
392 * @param afters
393 * the sub-keys to find before checking for key/endKey
394 *
395 * @return the text or NULL if not found
396 */
397 static private int indexOfAfter(String in, int startAt, String... afters) {
398 int pos = -1;
399 if (in != null && !in.isEmpty()) {
400 pos = startAt;
401 if (afters != null) {
402 for (int i = 0; pos >= 0 && i < afters.length; i++) {
403 String subKey = afters[i];
404 if (!subKey.isEmpty()) {
405 pos = in.indexOf(subKey, pos);
406 if (pos >= 0) {
407 pos += subKey.length();
408 }
409 }
410 }
411 }
412 }
413
414 return pos;
415 }
416 }