1 package be
.nikiroo
.fanfix
.supported
;
3 import java
.io
.IOException
;
4 import java
.io
.InputStream
;
6 import java
.util
.ArrayList
;
7 import java
.util
.HashMap
;
10 import java
.util
.Map
.Entry
;
12 import be
.nikiroo
.fanfix
.Instance
;
13 import be
.nikiroo
.fanfix
.bundles
.Config
;
14 import be
.nikiroo
.fanfix
.data
.MetaData
;
15 import be
.nikiroo
.utils
.IOUtils
;
16 import be
.nikiroo
.utils
.Progress
;
19 * Support class for <a href="http://www.fimfiction.net/">FimFiction.net</a>
20 * stories, a website dedicated to My Little Pony.
22 * This version uses the new, official API of FimFiction.
26 class FimfictionApi
extends BasicSupport
{
28 private String storyId
;
31 private Map
<Integer
, String
> chapterNames
;
32 private Map
<Integer
, String
> chapterContents
;
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");
41 String oauth
= Instance
.getConfig().getString(
42 Config
.LOGIN_FIMFICTION_APIKEY_TOKEN
);
44 if (oauth
== null || oauth
.isEmpty()) {
45 String clientId
= Instance
.getConfig().getString(
46 Config
.LOGIN_FIMFICTION_APIKEY_CLIENT_ID
)
48 String clientSecret
= Instance
.getConfig().getString(
49 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
.getConfig().setString(
59 Config
.LOGIN_FIMFICTION_APIKEY_TOKEN
, oauth
);
60 Instance
.getConfig().updateFile();
67 public String
getOAuth() {
72 protected boolean isHtml() {
77 public String
getSourceName() {
78 return "FimFiction.net";
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, "/");
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";
95 String urlString
= String
.format(
96 "https://www.fimfiction.net/api/v2/stories/%s?" //
101 storyContent
, authorContent
, //
102 chapterContent
, contentContent
, authorsNoteContent
,//
105 // URL params must be URL-encoded: "[ ]" <-> "%5B %5D"
106 urlString
= urlString
.replace("[", "%5B").replace("]", "%5D");
108 URL url
= new URL(urlString
);
109 InputStream jsonIn
= Instance
.getCache().open(url
, this, false);
111 json
= IOUtils
.readSmallStream(jsonIn
);
118 protected InputStream
openInput(URL source
) throws IOException
{
123 protected MetaData
getMeta(URL source
, InputStream in
) throws IOException
{
124 MetaData meta
= new MetaData();
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());
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")));
145 private List
<String
> getTags() {
146 List
<String
> tags
= new ArrayList
<String
>();
151 pos
= indexOfJsonAfter(json
, pos
, "type", "story_tag");
153 tags
.add(getKeyJson(json
, pos
, "name"));
161 protected String
getDesc(URL source
, InputStream in
) {
162 return getKeyJson(json
, 0, "type", "story", "description");
166 protected List
<Entry
<String
, URL
>> getChapters(URL source
, InputStream in
,
168 List
<Entry
<String
, URL
>> urls
= new ArrayList
<Entry
<String
, URL
>>();
170 chapterNames
= new HashMap
<Integer
, String
>();
171 chapterContents
= new HashMap
<Integer
, String
>();
175 pos
= indexOfJsonAfter(json
, pos
, "type", "chapter");
177 int posNumber
= indexOfJsonAfter(json
, pos
, "chapter_number");
178 int posComa
= json
.indexOf(",", posNumber
);
179 final int number
= Integer
.parseInt(json
.substring(posNumber
,
181 final String title
= getKeyJson(json
, pos
, "title");
182 String notes
= getKeyJson(json
, pos
, "authors_note", "html");
183 String content
= getKeyJson(json
, pos
, "content", "html");
185 chapterNames
.put(number
, title
);
187 .put(number
, content
+ "<br/>* * *<br/>" + notes
);
189 urls
.add(new Entry
<String
, URL
>() {
191 public URL
setValue(URL value
) {
196 public String
getKey() {
201 public URL
getValue() {
212 protected String
getChapterContent(URL source
, InputStream in
, int number
,
214 return chapterContents
.get(number
);
218 protected boolean supports(URL url
) {
219 return "fimfiction.net".equals(url
.getHost())
220 || "www.fimfiction.net".equals(url
.getHost());
223 static private String
generateOAuth(String clientId
, String clientSecret
)
225 URL url
= new URL("https://www.fimfiction.net/api/v2/token");
226 Map
<String
, String
> params
= new HashMap
<String
, String
>();
227 params
.put("client_id", clientId
);
228 params
.put("client_secret", clientSecret
);
229 params
.put("grant_type", "client_credentials");
230 InputStream in
= Instance
.getCache().openNoCache(url
, null, params
,
233 String jsonToken
= IOUtils
.readSmallStream(in
);
235 // Extract token type and token from: {
236 // token_type = "bearer",
237 // access_token = "xxxxxxxxxxxxxx"
240 String token
= getKeyText(jsonToken
, "\"access_token\"", "\"", "\"");
241 String tokenType
= getKeyText(jsonToken
, "\"token_type\"", "\"", "\"");
243 // TODO: remove this once the bug is fixed on the server side
244 if ("bearer".equals(tokenType
)) {
245 tokenType
= "Bearer";
248 return tokenType
+ " " + token
;
251 // afters: [name, value] pairs (or "" for any of them), can end without
253 static private int indexOfJsonAfter(String json
, int startAt
,
254 String
... afterKeys
) {
255 ArrayList
<String
> afters
= new ArrayList
<String
>();
257 for (String key
: afterKeys
) {
258 if (key
!= null && !key
.isEmpty()) {
259 afters
.add("\"" + key
+ "\"");
272 return indexOfAfter(json
, startAt
, afters
.toArray(new String
[] {}));
275 // afters: [name, value] pairs (or "" for any of them), can end without
277 static private String
getKeyJson(String json
, int startAt
,
278 String
... afterKeys
) {
279 int pos
= indexOfJsonAfter(json
, startAt
, afterKeys
);
284 String result
= null;
285 String wip
= json
.substring(pos
);
287 pos
= nextUnescapedQuote(wip
, 0);
289 wip
= wip
.substring(pos
+ 1);
290 pos
= nextUnescapedQuote(wip
, 0);
292 result
= wip
.substring(0, pos
);
299 // next " but don't take \" into account
300 static private int nextUnescapedQuote(String result
, int pos
) {
302 pos
= result
.indexOf("\"", pos
);
303 if (pos
== 0 || (pos
> 0 && result
.charAt(pos
- 1) != '\\')) {
307 if (pos
< result
.length()) {