1 package be
.nikiroo
.fanfix
.supported
;
3 import java
.io
.IOException
;
4 import java
.io
.InputStream
;
6 import java
.util
.AbstractMap
;
7 import java
.util
.ArrayList
;
8 import java
.util
.HashMap
;
11 import java
.util
.Map
.Entry
;
12 import java
.util
.TreeMap
;
14 import org
.jsoup
.nodes
.Document
;
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
;
25 * Support class for <a href="http://www.fimfiction.net/">FimFiction.net</a>
26 * stories, a website dedicated to My Little Pony.
28 * This version uses the new, official API of FimFiction.
32 class FimfictionApi
extends BasicSupport
{
36 private Map
<Integer
, String
> chapterNames
;
37 private Map
<Integer
, String
> chapterContents
;
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");
44 String oauth
= Instance
.getInstance().getConfig().getString(Config
.LOGIN_FIMFICTION_APIKEY_TOKEN
);
46 if (oauth
== null || oauth
.isEmpty()) {
47 String clientId
= Instance
.getInstance().getConfig().getString(Config
.LOGIN_FIMFICTION_APIKEY_CLIENT_ID
)
49 String clientSecret
= Instance
.getInstance().getConfig()
50 .getString(Config
.LOGIN_FIMFICTION_APIKEY_CLIENT_SECRET
) + "";
52 if (clientId
.trim().isEmpty() || clientSecret
.trim().isEmpty()) {
53 throw new IOException("API key required for the beta API v2");
56 oauth
= generateOAuth(clientId
, clientSecret
);
58 Instance
.getInstance().getConfig().setString(Config
.LOGIN_FIMFICTION_APIKEY_TOKEN
, oauth
);
59 Instance
.getInstance().getConfig().updateFile();
66 protected Document
loadDocument(URL source
) throws IOException
{
72 public String
getOAuth() {
77 protected boolean isHtml() {
82 * Extract the full JSON data we will later use to build the {@link Story}.
84 * @return the data in a JSON format
87 * in case of I/O error
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,
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";
101 String urlString
= String
.format(
102 "https://www.fimfiction.net/api/v2/stories/%s?" //
106 storyContent
, authorContent
, chapterContent
,//
109 // URL params must be URL-encoded: "[ ]" <-> "%5B %5D"
110 urlString
= urlString
.replace("[", "%5B").replace("]", "%5D");
112 URL url
= new URL(urlString
);
113 InputStream jsonIn
= Instance
.getInstance().getCache().open(url
, this, false);
115 return IOUtils
.readSmallStream(jsonIn
);
122 protected MetaData
getMeta() throws IOException
{
123 MetaData meta
= new MetaData();
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());
135 meta
.setSubject("MLP");
136 meta
.setType(getType().toString());
137 meta
.setImageDocument(false);
139 String coverImageLink
= getKeyJson(json
, 0, "type", "story",
140 "cover_image", "full");
141 if (!coverImageLink
.trim().isEmpty()) {
142 URL coverImageUrl
= new URL(coverImageLink
.trim());
144 // No need to use the oauth, cookies... for the cover
145 // Plus: it crashes on Android because of the referer
147 InputStream in
= Instance
.getInstance().getCache().open(coverImageUrl
, null, true);
149 meta
.setCover(new Image(in
));
153 } catch (IOException e
) {
154 Instance
.getInstance().getTraceHandler()
155 .error(new IOException("Cannot get the story cover, ignoring...", e
));
162 private List
<String
> getTags() {
163 List
<String
> tags
= new ArrayList
<String
>();
168 pos
= indexOfJsonAfter(json
, pos
, "type", "story_tag");
170 tags
.add(getKeyJson(json
, pos
, "name").trim());
178 protected String
getDesc() {
179 String desc
= getKeyJson(json
, 0, "type", "story", "description");
180 return unbbcode(desc
);
184 protected List
<Entry
<String
, URL
>> getChapters(Progress pg
) {
185 chapterNames
= new TreeMap
<Integer
, String
>();
186 chapterContents
= new TreeMap
<Integer
, String
>();
190 pos
= indexOfJsonAfter(json
, pos
, "type", "chapter");
192 int posNumber
= indexOfJsonAfter(json
, pos
, "chapter_number");
193 int posComa
= json
.indexOf(",", posNumber
);
194 final int number
= Integer
.parseInt(json
.substring(posNumber
,
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");
200 if (!notes
.trim().isEmpty()) {
201 notes
= "<br/>* * *<br/>" + notes
;
204 chapterNames
.put(number
, title
);
205 chapterContents
.put(number
, content
+ notes
);
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));
218 protected String
getChapterContent(URL source
, int number
, Progress pg
) {
219 return chapterContents
.get(number
);
223 protected boolean supports(URL url
) {
224 return "fimfiction.net".equals(url
.getHost())
225 || "www.fimfiction.net".equals(url
.getHost());
229 * Generate a new token from the client ID and secret.
231 * Note that those tokens are long-lived, and it would be badly seen to
232 * create a lot of them without due cause.
234 * So, please cache and re-use them.
237 * the client ID offered on FimFiction
238 * @param clientSecret
239 * the client secret that goes with it
241 * @return a new generated token linked to that client ID
243 * @throws IOException
244 * in case of I/O errors
246 static private String
generateOAuth(String clientId
, String clientSecret
)
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);
255 String jsonToken
= IOUtils
.readSmallStream(in
);
258 // Extract token type and token from: {
259 // token_type = "Bearer",
260 // access_token = "xxxxxxxxxxxxxx"
263 String tokenType
= getKeyText(jsonToken
, "\"token_type\"", "\"", "\"");
264 String token
= getKeyText(jsonToken
, "\"access_token\"", "\"", "\"");
266 return tokenType
+ " " + token
;
269 // afters: [name, value] pairs (or "" for any of them), can end without
271 static private int indexOfJsonAfter(String json
, int startAt
,
272 String
... afterKeys
) {
273 ArrayList
<String
> afters
= new ArrayList
<String
>();
275 for (String key
: afterKeys
) {
276 if (key
!= null && !key
.isEmpty()) {
277 afters
.add("\"" + key
+ "\"");
290 return indexOfAfter(json
, startAt
, afters
.toArray(new String
[] {}));
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
);
303 String wip
= json
.substring(pos
);
305 pos
= nextUnescapedQuote(wip
, 0);
307 wip
= wip
.substring(pos
+ 1);
308 pos
= nextUnescapedQuote(wip
, 0);
310 result
= wip
.substring(0, pos
);
314 result
= result
.replace("\\t", "\t").replace("\\\"", "\"");
319 // next " but don't take \" into account
320 static private int nextUnescapedQuote(String result
, int pos
) {
322 pos
= result
.indexOf("\"", pos
);
323 if (pos
== 0 || (pos
> 0 && result
.charAt(pos
- 1) != '\\')) {
327 if (pos
< result
.length()) {
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("\\[[^\\]]*\\]", "");
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).
352 * the key to match (also supports "^" at start to say
353 * "only if it starts with" the key)
355 * the sub key or NULL if none
357 * the end key or NULL for "up to the end"
358 * @return the text or NULL if not found
360 static private String
getKeyText(String in
, String key
, String subKey
,
362 String result
= null;
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
)
372 if (endKey
== null || line
.contains(endKey
)) {
373 if (endKey
!= null) {
374 line
= line
.substring(0, line
.indexOf(endKey
));
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.
391 * start at this position in the string
393 * the sub-keys to find before checking for key/endKey
395 * @return the text or NULL if not found
397 static private int indexOfAfter(String in
, int startAt
, String
... afters
) {
399 if (in
!= null && !in
.isEmpty()) {
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
);
407 pos
+= subKey
.length();