28c0d1be02613d8840f67ce55426ea7c71c98ad8
[fanfix.git] / src / be / nikiroo / fanfix / searchable / Fanfiction.java
1 package be.nikiroo.fanfix.searchable;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.net.URL;
6 import java.net.URLEncoder;
7 import java.text.SimpleDateFormat;
8 import java.util.ArrayList;
9 import java.util.Date;
10 import java.util.HashMap;
11 import java.util.List;
12 import java.util.Map;
13
14 import org.jsoup.nodes.Document;
15 import org.jsoup.nodes.Element;
16 import org.jsoup.select.Elements;
17
18 import be.nikiroo.fanfix.Instance;
19 import be.nikiroo.fanfix.bundles.StringId;
20 import be.nikiroo.fanfix.data.MetaData;
21 import be.nikiroo.fanfix.supported.SupportType;
22 import be.nikiroo.utils.Image;
23 import be.nikiroo.utils.StringUtils;
24
25 /**
26 * A {@link BasicSearchable} for Fanfiction.NET.
27 *
28 * @author niki
29 */
30 class Fanfiction extends BasicSearchable {
31 static private String BASE_URL = "http://fanfiction.net/";
32
33 /**
34 * Create a new {@link Fanfiction}.
35 *
36 * @param type
37 * {@link SupportType#FANFICTION}
38 */
39 public Fanfiction(SupportType type) {
40 super(type);
41 }
42
43 @Override
44 public List<SearchableTag> getTags() throws IOException {
45 String storiesName = null;
46 String crossoversName = null;
47 Map<String, String> stories = new HashMap<String, String>();
48 Map<String, String> crossovers = new HashMap<String, String>();
49
50 Document mainPage = load(BASE_URL, true);
51 Element menu = mainPage.getElementsByClass("dropdown").first();
52 if (menu != null) {
53 Element ul = menu.getElementsByClass("dropdown-menu").first();
54 if (ul != null) {
55 Map<String, String> currentList = null;
56 for (Element li : ul.getElementsByTag("li")) {
57 if (li.hasClass("disabled")) {
58 if (storiesName == null) {
59 storiesName = li.text();
60 currentList = stories;
61 } else {
62 crossoversName = li.text();
63 currentList = crossovers;
64 }
65 } else if (currentList != null) {
66 Element a = li.getElementsByTag("a").first();
67 if (a != null) {
68 currentList.put(a.absUrl("href"), a.text());
69 }
70 }
71 }
72 }
73 }
74
75 List<SearchableTag> tags = new ArrayList<SearchableTag>();
76
77 if (storiesName != null) {
78 SearchableTag tag = new SearchableTag(null, storiesName, false);
79 for (String id : stories.keySet()) {
80 tag.add(new SearchableTag(id, stories.get(id), false, false));
81 }
82 tags.add(tag);
83 }
84
85 if (crossoversName != null) {
86 SearchableTag tag = new SearchableTag(null, crossoversName, false);
87 for (String id : crossovers.keySet()) {
88 tag.add(new SearchableTag(id, crossovers.get(id), false, false));
89 }
90 tags.add(tag);
91 }
92
93 return tags;
94 }
95
96 @Override
97 public void fillTag(SearchableTag tag) throws IOException {
98 if (tag.getId() == null || tag.isComplete()) {
99 return;
100 }
101
102 Document doc = load(tag.getId(), false);
103 Element list = doc.getElementById("list_output");
104 if (list != null) {
105 Element table = list.getElementsByTag("table").first();
106 if (table != null) {
107 for (Element div : table.getElementsByTag("div")) {
108 Element a = div.getElementsByTag("a").first();
109 Element span = div.getElementsByTag("span").first();
110
111 if (a != null) {
112 String subid = a.absUrl("href");
113 boolean crossoverSubtag = subid
114 .contains("/crossovers/");
115
116 SearchableTag subtag = new SearchableTag(subid,
117 a.text(), !crossoverSubtag, !crossoverSubtag);
118
119 tag.add(subtag);
120 if (span != null) {
121 String nr = span.text();
122 if (nr.startsWith("(")) {
123 nr = nr.substring(1);
124 }
125 if (nr.endsWith(")")) {
126 nr = nr.substring(0, nr.length() - 1);
127 }
128 nr = nr.trim();
129
130 // TODO: fix toNumber/fromNumber
131 nr = nr.replaceAll("\\.[0-9]*", "");
132
133 subtag.setCount(StringUtils.toNumber(nr));
134 }
135 }
136 }
137 }
138 }
139
140 tag.setComplete(true);
141 }
142
143 @Override
144 public List<MetaData> search(String search) throws IOException {
145 String encoded = URLEncoder.encode(search.toLowerCase(), "utf-8");
146 return getStories(BASE_URL + "search/?ready=1&type=story&keywords="
147 + encoded, null, null);
148 }
149
150 @Override
151 public List<MetaData> search(SearchableTag tag, int page)
152 throws IOException {
153 List<MetaData> metas = new ArrayList<MetaData>();
154
155 String url = tag.getId();
156 if (url != null) {
157 if (page > 1) {
158 int pos = url.indexOf("&p=");
159 if (pos >= 0) {
160 url = url.replaceAll("(.*\\&p=)[0-9]*(.*)", "$1\\" + page
161 + "$2");
162 } else {
163 url += "&p=" + page;
164 }
165 }
166
167 Document doc = load(url, false);
168
169 // Update the pages number if needed
170 if (tag.getPages() < 0 && tag.isLeaf()) {
171 tag.setPages(getPages(doc));
172 }
173
174 // Find out the full subjects (including parents)
175 String subjects = "";
176 for (SearchableTag t = tag; t != null; t = t.getParent()) {
177 if (!subjects.isEmpty()) {
178 subjects += ", ";
179 }
180 subjects += t.getName();
181 }
182
183 metas = getStories(url, doc, subjects);
184 }
185
186 return metas;
187 }
188
189 /**
190 * Return the number of pages in this stories result listing.
191 *
192 * @param doc
193 * the document
194 *
195 * @return the number of pages or -1 if unknown
196 *
197 * @throws IOException
198 * in case of I/O errors
199 */
200 private int getPages(Document doc) throws IOException {
201 int pages = -1;
202
203 if (doc != null) {
204 Element center = doc.getElementsByTag("center").first();
205 if (center != null) {
206 for (Element a : center.getElementsByTag("a")) {
207 if (a.absUrl("href").contains("&p=")) {
208 int thisLinkPages = -1;
209 try {
210 String[] tab = a.absUrl("href").split("=");
211 tab = tab[tab.length - 1].split("&");
212 thisLinkPages = Integer
213 .parseInt(tab[tab.length - 1]);
214 } catch (Exception e) {
215 }
216
217 pages = Math.max(pages, thisLinkPages);
218 }
219 }
220 }
221 }
222
223 return pages;
224 }
225
226 /**
227 * Fetch the stories from the given page.
228 *
229 * @param sourceUrl
230 * the url of the document
231 * @param doc
232 * the document to use (if NULL, will be loaded from
233 * <tt>sourceUrl</tt>)
234 * @param mainSubject
235 * the main subject (the anime/book/movie item related to the
236 * stories, like "MLP" or "Doctor Who"), or NULL if none
237 *
238 * @return the stories found in it
239 *
240 * @throws IOException
241 * in case of I/O errors
242 */
243 private List<MetaData> getStories(String sourceUrl, Document doc,
244 String mainSubject) throws IOException {
245 List<MetaData> metas = new ArrayList<MetaData>();
246
247 if (doc == null) {
248 doc = load(sourceUrl, false);
249 }
250
251 for (Element story : doc.getElementsByClass("z-list")) {
252 MetaData meta = new MetaData();
253 meta.setImageDocument(false);
254 meta.setSource(getType().getSourceName());
255
256 // Title, URL, Cover
257 Element stitle = story.getElementsByClass("stitle").first();
258 if (stitle != null) {
259 meta.setTitle(stitle.text());
260 meta.setUrl(stitle.absUrl("href"));
261 Element cover = stitle.getElementsByTag("img").first();
262 if (cover != null) {
263 // note: see data-original if needed?
264 String coverUrl = cover.absUrl("src");
265
266 try {
267 InputStream in = Instance.getCache().open(
268 new URL(coverUrl), getSupport(), true);
269 try {
270 meta.setCover(new Image(in));
271 } finally {
272 in.close();
273 }
274 } catch (Exception e) {
275 Instance.getTraceHandler()
276 .error(new Exception(
277 "Cannot download cover for Fanfiction story in search mode",
278 e));
279 }
280 }
281 }
282
283 // Author
284 Elements as = story.getElementsByTag("a");
285 if (as.size() > 1) {
286 meta.setAuthor(as.get(1).text());
287 }
288
289 // Tags (concatenated text), published date, updated date, Resume
290 String tags = "";
291 List<String> tagList = new ArrayList<String>();
292 Elements divs = story.getElementsByTag("div");
293 if (divs.size() > 1 && divs.get(1).childNodeSize() > 0) {
294 String resume = divs.get(1).text();
295 if (divs.size() > 2) {
296 tags = divs.get(2).text();
297 resume = resume.substring(0,
298 resume.length() - tags.length()).trim();
299
300 for (Element d : divs.get(2).getElementsByAttribute(
301 "data-xutime")) {
302 String secs = d.attr("data-xutime");
303 try {
304 String date = new SimpleDateFormat("yyyy-MM-dd")
305 .format(new Date(
306 Long.parseLong(secs) * 1000));
307 // (updated, ) published
308 if (meta.getDate() != null) {
309 tagList.add("Updated: " + meta.getDate());
310 }
311 meta.setDate(date);
312 } catch (Exception e) {
313 }
314 }
315 }
316
317 meta.setResume(getSupport().makeChapter(new URL(sourceUrl), 0,
318 Instance.getTrans().getString(StringId.DESCRIPTION),
319 resume));
320 }
321
322 // How are the tags ordered?
323 // We have "Rated: xx", then the language, then all other tags
324 // If the subject(s) is/are present, they are before "Rated: xx"
325
326 // ////////////
327 // Examples: //
328 // ////////////
329
330 // Search (Luna) Tags: [Harry Potter, Rated: T, English, Chapters:
331 // 1, Words: 270, Reviews: 2, Published: 2/19/2013, Luna L.]
332
333 // Normal (MLP) Tags: [Rated: T, Spanish, Drama/Suspense, Chapters:
334 // 2, Words: 8,686, Reviews: 1, Favs: 1, Follows: 1, Updated: 4/7,
335 // Published: 4/2]
336
337 // Crossover (MLP/Who) Tags: [Rated: K+, English, Adventure/Romance,
338 // Chapters: 8, Words: 7,788, Reviews: 2, Favs: 2, Follows: 1,
339 // Published: 9/1/2016]
340
341 boolean rated = false;
342 boolean isLang = false;
343 String subject = mainSubject == null ? "" : mainSubject;
344 String[] tab = tags.split(" *- *");
345 for (int i = 0; i < tab.length; i++) {
346 String tag = tab[i];
347 if (tag.startsWith("Rated: ")) {
348 rated = true;
349 }
350
351 if (!rated) {
352 if (!subject.isEmpty()) {
353 subject += ", ";
354 }
355 subject += tag;
356 } else if (isLang) {
357 meta.setLang(tag);
358 isLang = false;
359 } else {
360 if (tag.contains(":")) {
361 // Handle special tags:
362 if (tag.startsWith("Words: ")) {
363 try {
364 meta.setWords(Long.parseLong(tag
365 .substring("Words: ".length())
366 .replace(",", "").trim()));
367 } catch (Exception e) {
368 }
369 } else if (tag.startsWith("Rated: ")) {
370 tagList.add(tag);
371 }
372 } else {
373 // Normal tags are "/"-separated
374 for (String t : tag.split("/")) {
375 tagList.add(t);
376 }
377 }
378
379 if (tag.startsWith("Rated: ")) {
380 isLang = true;
381 }
382 }
383 }
384
385 meta.setSubject(subject);
386 meta.setTags(tagList);
387
388 metas.add(meta);
389 }
390
391 return metas;
392 }
393 }