1 package be
.nikiroo
.fanfix
.supported
;
3 import java
.awt
.image
.BufferedImage
;
4 import java
.io
.BufferedReader
;
5 import java
.io
.ByteArrayInputStream
;
7 import java
.io
.IOException
;
8 import java
.io
.InputStream
;
9 import java
.io
.InputStreamReader
;
10 import java
.net
.MalformedURLException
;
12 import java
.util
.ArrayList
;
13 import java
.util
.Date
;
14 import java
.util
.HashMap
;
15 import java
.util
.List
;
17 import java
.util
.Map
.Entry
;
18 import java
.util
.Scanner
;
20 import be
.nikiroo
.fanfix
.Instance
;
21 import be
.nikiroo
.fanfix
.bundles
.Config
;
22 import be
.nikiroo
.fanfix
.bundles
.StringId
;
23 import be
.nikiroo
.fanfix
.data
.Chapter
;
24 import be
.nikiroo
.fanfix
.data
.MetaData
;
25 import be
.nikiroo
.fanfix
.data
.Paragraph
;
26 import be
.nikiroo
.fanfix
.data
.Paragraph
.ParagraphType
;
27 import be
.nikiroo
.fanfix
.data
.Story
;
28 import be
.nikiroo
.utils
.ImageUtils
;
29 import be
.nikiroo
.utils
.Progress
;
30 import be
.nikiroo
.utils
.StringUtils
;
33 * This class is the base class used by the other support classes. It can be
34 * used outside of this package, and have static method that you can use to get
35 * access to the correct support class.
37 * It will be used with 'resources' (usually web pages or files).
41 public abstract class BasicSupport
{
43 * The supported input types for which we can get a {@link BasicSupport}
48 public enum SupportType
{
49 /** EPUB files created with this program */
51 /** Pure text file with some rules */
53 /** TEXT but with associated .info file */
55 /** My Little Pony fanfictions */
57 /** Fanfictions from a lot of different universes */
59 /** Website with lots of Mangas */
61 /** Furry website with comics support */
63 /** Furry website with stories */
65 /** Comics and images groups, mostly but not only NSFW */
73 * A description of this support type (more information than the
74 * {@link BasicSupport#getSourceName()}).
76 * @return the description
78 public String
getDesc() {
79 String desc
= Instance
.getTrans().getStringX(StringId
.INPUT_DESC
,
83 desc
= Instance
.getTrans().getString(StringId
.INPUT_DESC
, this);
90 * The name of this support type (a short version).
94 public String
getSourceName() {
95 BasicSupport support
= BasicSupport
.getSupport(this);
96 if (support
!= null) {
97 return support
.getSourceName();
104 public String
toString() {
105 return super.toString().toLowerCase();
109 * Call {@link SupportType#valueOf(String)} after conversion to upper
113 * the possible type name
115 * @return NULL or the type
117 public static SupportType
valueOfUC(String typeName
) {
118 return SupportType
.valueOf(typeName
== null ?
null : typeName
123 * Call {@link SupportType#valueOf(String)} after conversion to upper
124 * case but return NULL for NULL instead of raising exception.
127 * the possible type name
129 * @return NULL or the type
131 public static SupportType
valueOfNullOkUC(String typeName
) {
132 if (typeName
== null) {
136 return SupportType
.valueOfUC(typeName
);
140 * Call {@link SupportType#valueOf(String)} after conversion to upper
141 * case but return NULL in case of error instead of raising an
145 * the possible type name
147 * @return NULL or the type
149 public static SupportType
valueOfAllOkUC(String typeName
) {
151 return SupportType
.valueOfUC(typeName
);
152 } catch (Exception e
) {
158 private InputStream in
;
159 private SupportType type
;
160 private URL currentReferer
; // with only one 'r', as in 'HTTP'...
163 private char openQuote
= Instance
.getTrans().getCharacter(
164 StringId
.OPEN_SINGLE_QUOTE
);
165 private char closeQuote
= Instance
.getTrans().getCharacter(
166 StringId
.CLOSE_SINGLE_QUOTE
);
167 private char openDoubleQuote
= Instance
.getTrans().getCharacter(
168 StringId
.OPEN_DOUBLE_QUOTE
);
169 private char closeDoubleQuote
= Instance
.getTrans().getCharacter(
170 StringId
.CLOSE_DOUBLE_QUOTE
);
173 * The name of this support class.
177 protected abstract String
getSourceName();
180 * Check if the given resource is supported by this {@link BasicSupport}.
183 * the resource to check for
185 * @return TRUE if it is
187 protected abstract boolean supports(URL url
);
190 * Return TRUE if the support will return HTML encoded content values for
191 * the chapters content.
193 * @return TRUE for HTML
195 protected abstract boolean isHtml();
198 * Return the {@link MetaData} of this story.
201 * the source of the story
203 * the input (the main resource)
205 * @return the associated {@link MetaData}
207 * @throws IOException
208 * in case of I/O error
210 protected abstract MetaData
getMeta(URL source
, InputStream in
)
214 * Return the story description.
217 * the source of the story
219 * the input (the main resource)
221 * @return the description
223 * @throws IOException
224 * in case of I/O error
226 protected abstract String
getDesc(URL source
, InputStream in
)
230 * Return the list of chapters (name and resource).
233 * the source of the story
235 * the input (the main resource)
237 * the optional progress reporter
239 * @return the chapters
241 * @throws IOException
242 * in case of I/O error
244 protected abstract List
<Entry
<String
, URL
>> getChapters(URL source
,
245 InputStream in
, Progress pg
) throws IOException
;
248 * Return the content of the chapter (possibly HTML encoded, if
249 * {@link BasicSupport#isHtml()} is TRUE).
252 * the source of the story
254 * the input (the main resource)
258 * the optional progress reporter
260 * @return the content
262 * @throws IOException
263 * in case of I/O error
265 protected abstract String
getChapterContent(URL source
, InputStream in
,
266 int number
, Progress pg
) throws IOException
;
269 * Log into the support (can be a no-op depending upon the support).
271 * @throws IOException
272 * in case of I/O error
274 public void login() throws IOException
{
279 * Return the list of cookies (values included) that must be used to
280 * correctly fetch the resources.
282 * You are expected to call the super method implementation if you override
285 * @return the cookies
287 * @throws IOException
288 * in case of I/O error
290 public Map
<String
, String
> getCookies() throws IOException
{
291 return new HashMap
<String
, String
>();
295 * Return the canonical form of the main {@link URL}.
298 * the source {@link URL}
300 * @return the canonical form of this {@link URL}
302 * @throws IOException
303 * in case of I/O error
305 public URL
getCanonicalUrl(URL source
) throws IOException
{
310 * Process the given story resource into a partially filled {@link Story}
311 * object containing the name and metadata, except for the description.
316 * @return the {@link Story}
318 * @throws IOException
319 * in case of I/O error
321 public Story
processMeta(URL url
) throws IOException
{
322 return processMeta(url
, true, false, null);
326 * Process the given story resource into a partially filled {@link Story}
327 * object containing the name and metadata.
332 * close "this" and "in" when done
334 * retrieve the description of the story, or not
336 * the optional progress reporter
338 * @return the {@link Story}
340 * @throws IOException
341 * in case of I/O error
343 protected Story
processMeta(URL url
, boolean close
, boolean getDesc
,
344 Progress pg
) throws IOException
{
348 pg
.setMinMax(0, 100);
354 url
= getCanonicalUrl(url
);
356 setCurrentReferer(url
);
364 preprocess(url
, getInput());
367 Story story
= new Story();
368 MetaData meta
= getMeta(url
, getInput());
369 if (meta
.getCreationDate() == null
370 || meta
.getCreationDate().isEmpty()) {
371 meta
.setCreationDate(StringUtils
.fromTime(new Date().getTime()));
377 if (meta
.getCover() == null) {
378 meta
.setCover(getDefaultCover(meta
.getSubject()));
384 String descChapterName
= Instance
.getTrans().getString(
385 StringId
.DESCRIPTION
);
386 story
.getMeta().setResume(
387 makeChapter(url
, 0, descChapterName
,
388 getDesc(url
, getInput()), null));
397 } catch (IOException e
) {
406 setCurrentReferer(null);
411 * Process the given story resource into a fully filled {@link Story}
417 * the optional progress reporter
419 * @return the {@link Story}
421 * @throws IOException
422 * in case of I/O error
424 public Story
process(URL url
, Progress pg
) throws IOException
{
428 pg
.setMinMax(0, 100);
431 url
= getCanonicalUrl(url
);
434 Progress pgMeta
= new Progress();
435 pg
.addProgress(pgMeta
, 10);
436 Story story
= processMeta(url
, false, true, pgMeta
);
437 if (!pgMeta
.isDone()) {
438 pgMeta
.setProgress(pgMeta
.getMax()); // 10%
446 pg
.setName("Retrieving " + story
.getMeta().getTitle());
448 setCurrentReferer(url
);
450 Progress pgGetChapters
= new Progress();
451 pg
.addProgress(pgGetChapters
, 10);
452 story
.setChapters(new ArrayList
<Chapter
>());
453 List
<Entry
<String
, URL
>> chapters
= getChapters(url
, getInput(),
455 if (!pgGetChapters
.isDone()) {
456 pgGetChapters
.setProgress(pgGetChapters
.getMax()); // 20%
459 if (chapters
!= null) {
460 Progress pgChaps
= new Progress("Extracting chapters", 0,
461 chapters
.size() * 300);
462 pg
.addProgress(pgChaps
, 80);
466 for (Entry
<String
, URL
> chap
: chapters
) {
467 pgChaps
.setName("Extracting chapter " + i
);
468 setCurrentReferer(chap
.getValue());
469 InputStream chapIn
= Instance
.getCache().open(
470 chap
.getValue(), this, true);
471 pgChaps
.setProgress(i
* 100);
473 Progress pgGetChapterContent
= new Progress();
474 Progress pgMakeChapter
= new Progress();
475 pgChaps
.addProgress(pgGetChapterContent
, 100);
476 pgChaps
.addProgress(pgMakeChapter
, 100);
478 String content
= getChapterContent(url
, chapIn
, i
,
479 pgGetChapterContent
);
480 if (!pgGetChapterContent
.isDone()) {
481 pgGetChapterContent
.setProgress(pgGetChapterContent
485 Chapter cc
= makeChapter(url
, i
, chap
.getKey(),
486 content
, pgMakeChapter
);
487 if (!pgMakeChapter
.isDone()) {
488 pgMakeChapter
.setProgress(pgMakeChapter
.getMax());
491 words
+= cc
.getWords();
492 story
.getChapters().add(cc
);
493 if (story
.getMeta() != null) {
494 story
.getMeta().setWords(words
);
503 pgChaps
.setName("Extracting chapters");
513 } catch (IOException e
) {
521 setCurrentReferer(null);
530 public SupportType
getType() {
535 * The current referer {@link URL} (only one 'r', as in 'HTML'...), i.e.,
536 * the current {@link URL} we work on.
538 * @return the referer
540 public URL
getCurrentReferer() {
541 return currentReferer
;
545 * The current referer {@link URL} (only one 'r', as in 'HTML'...), i.e.,
546 * the current {@link URL} we work on.
548 * @param currentReferer
551 protected void setCurrentReferer(URL currentReferer
) {
552 this.currentReferer
= currentReferer
;
563 protected BasicSupport
setType(SupportType type
) {
569 * Prepare the support if needed before processing.
572 * the source of the story
574 * the input (the main resource)
576 * @throws IOException
579 @SuppressWarnings("unused")
580 protected void preprocess(URL source
, InputStream in
) throws IOException
{
584 * Now that we have processed the {@link Story}, close the resources if any.
586 * @throws IOException
589 protected void close() throws IOException
{
593 * Create a {@link Chapter} object from the given information, formatting
594 * the content as it should be.
597 * the source of the story
603 * the chapter content
605 * the optional progress reporter
607 * @return the {@link Chapter}
609 * @throws IOException
610 * in case of I/O error
612 protected Chapter
makeChapter(URL source
, int number
, String name
,
613 String content
, Progress pg
) throws IOException
{
614 // Chapter name: process it correctly, then remove the possible
615 // redundant "Chapter x: " in front of it, or "-" (as in
616 // "Chapter 5: - Fun!" after the ": " was automatically added)
617 String chapterName
= processPara(name
).getContent().trim();
618 for (String lang
: Instance
.getConfig().getString(Config
.CHAPTER
)
620 String chapterWord
= Instance
.getConfig().getStringX(
621 Config
.CHAPTER
, lang
);
622 if (chapterName
.startsWith(chapterWord
)) {
623 chapterName
= chapterName
.substring(chapterWord
.length())
629 if (chapterName
.startsWith(Integer
.toString(number
))) {
630 chapterName
= chapterName
.substring(
631 Integer
.toString(number
).length()).trim();
634 while (chapterName
.startsWith(":") || chapterName
.startsWith("-")) {
635 chapterName
= chapterName
.substring(1).trim();
639 Chapter chap
= new Chapter(number
, chapterName
);
641 if (content
!= null) {
642 List
<Paragraph
> paras
= makeParagraphs(source
, content
, pg
);
644 for (Paragraph para
: paras
) {
645 words
+= para
.getWords();
647 chap
.setParagraphs(paras
);
648 chap
.setWords(words
);
656 * Convert the given content into {@link Paragraph}s.
659 * the source URL of the story
661 * the textual content
663 * the optional progress reporter
665 * @return the {@link Paragraph}s
667 * @throws IOException
668 * in case of I/O error
670 protected List
<Paragraph
> makeParagraphs(URL source
, String content
,
671 Progress pg
) throws IOException
{
677 // Special <HR> processing:
678 content
= content
.replaceAll("(<hr [^>]*>)|(<hr/>)|(<hr>)",
682 List
<Paragraph
> paras
= new ArrayList
<Paragraph
>();
684 if (content
!= null && !content
.trim().isEmpty()) {
686 String
[] tab
= content
.split("(<p>|</p>|<br>|<br/>)");
687 pg
.setMinMax(0, tab
.length
);
689 for (String line
: tab
) {
690 if (line
.startsWith("[") && line
.endsWith("]")) {
691 pg
.setName("Extracting image " + i
);
693 paras
.add(makeParagraph(source
, line
.trim()));
698 List
<String
> lines
= new ArrayList
<String
>();
699 BufferedReader buff
= null;
701 buff
= new BufferedReader(
702 new InputStreamReader(new ByteArrayInputStream(
703 content
.getBytes("UTF-8")), "UTF-8"));
704 for (String line
= buff
.readLine(); line
!= null; line
= buff
706 lines
.add(line
.trim());
714 pg
.setMinMax(0, lines
.size());
716 for (String line
: lines
) {
717 if (line
.startsWith("[") && line
.endsWith("]")) {
718 pg
.setName("Extracting image " + i
);
720 paras
.add(makeParagraph(source
, line
));
726 // Check quotes for "bad" format
727 List
<Paragraph
> newParas
= new ArrayList
<Paragraph
>();
728 for (Paragraph para
: paras
) {
729 newParas
.addAll(requotify(para
));
733 // Remove double blanks/brks
734 fixBlanksBreaks(paras
);
741 * Convert the given line into a single {@link Paragraph}.
744 * the source URL of the story
746 * the textual content of the paragraph
748 * @return the {@link Paragraph}
750 private Paragraph
makeParagraph(URL source
, String line
) {
752 if (line
.startsWith("[") && line
.endsWith("]")) {
753 image
= getImageUrl(this, source
,
754 line
.substring(1, line
.length() - 1).trim());
758 return new Paragraph(image
);
761 return processPara(line
);
765 * Fix the {@link ParagraphType#BLANK}s and {@link ParagraphType#BREAK}s of
766 * those {@link Paragraph}s.
768 * The resulting list will not contain a starting or trailing blank/break
769 * nor 2 blanks or breaks following each other.
772 * the list of {@link Paragraph}s to fix
774 protected void fixBlanksBreaks(List
<Paragraph
> paras
) {
775 boolean space
= false;
777 for (int i
= 0; i
< paras
.size(); i
++) {
778 Paragraph para
= paras
.get(i
);
779 boolean thisSpace
= para
.getType() == ParagraphType
.BLANK
;
780 boolean thisBrk
= para
.getType() == ParagraphType
.BREAK
;
782 if (i
> 0 && space
&& thisBrk
) {
785 } else if ((space
|| brk
) && (thisSpace
|| thisBrk
)) {
794 // Remove blank/brk at start
796 && (paras
.get(0).getType() == ParagraphType
.BLANK
|| paras
.get(
797 0).getType() == ParagraphType
.BREAK
)) {
801 // Remove blank/brk at end
802 int last
= paras
.size() - 1;
804 && (paras
.get(last
).getType() == ParagraphType
.BLANK
|| paras
805 .get(last
).getType() == ParagraphType
.BREAK
)) {
811 * Get the default cover related to this subject (see <tt>.info</tt> files).
816 * @return the cover if any, or NULL
818 static BufferedImage
getDefaultCover(String subject
) {
819 if (subject
!= null && !subject
.isEmpty()
820 && Instance
.getCoverDir() != null) {
822 File fileCover
= new File(Instance
.getCoverDir(), subject
);
823 return getImage(null, fileCover
.toURI().toURL(), subject
);
824 } catch (MalformedURLException e
) {
832 * Return the list of supported image extensions.
834 * @param emptyAllowed
835 * TRUE to allow an empty extension on first place, which can be
836 * used when you may already have an extension in your input but
837 * are not sure about it
839 * @return the extensions
841 static String
[] getImageExt(boolean emptyAllowed
) {
843 return new String
[] { "", ".png", ".jpg", ".jpeg", ".gif", ".bmp" };
846 return new String
[] { ".png", ".jpg", ".jpeg", ".gif", ".bmp" };
850 * Check if the given resource can be a local image or a remote image, then
851 * refresh the cache with it if it is.
856 * the resource to check
858 * @return the image if found, or NULL
861 static BufferedImage
getImage(BasicSupport support
, URL source
, String line
) {
862 URL url
= getImageUrl(support
, source
, line
);
864 InputStream in
= null;
866 in
= Instance
.getCache().open(url
, getSupport(url
), true);
867 return ImageUtils
.fromStream(in
);
868 } catch (IOException e
) {
873 } catch (IOException e
) {
883 * Check if the given resource can be a local image or a remote image, then
884 * refresh the cache with it if it is.
889 * the resource to check
891 * @return the image URL if found, or NULL
894 static URL
getImageUrl(BasicSupport support
, URL source
, String line
) {
899 if (source
!= null) {
902 String relPath
= null;
903 String absPath
= null;
905 String path
= new File(source
.getFile()).getParent();
906 relPath
= new File(new File(path
), line
.trim())
908 } catch (Exception e
) {
909 // Cannot be converted to path (one possibility to take
910 // into account: absolute path on Windows)
913 absPath
= new File(line
.trim()).getAbsolutePath();
914 } catch (Exception e
) {
915 // Cannot be converted to path (at all)
918 for (String ext
: getImageExt(true)) {
919 if (absPath
!= null && new File(absPath
+ ext
).exists()) {
920 url
= new File(absPath
+ ext
).toURI().toURL();
921 } else if (relPath
!= null
922 && new File(relPath
+ ext
).exists()) {
923 url
= new File(relPath
+ ext
).toURI().toURL();
926 } catch (Exception e
) {
927 // Should not happen since we control the correct arguments
934 for (String ext
: getImageExt(true)) {
935 if (Instance
.getCache().check(new URL(line
+ ext
))) {
936 url
= new URL(line
+ ext
);
943 for (String ext
: getImageExt(true)) {
945 url
= new URL(line
+ ext
);
946 Instance
.getCache().refresh(url
, support
, true);
948 } catch (IOException e
) {
949 // no image with this ext
954 } catch (MalformedURLException e
) {
959 // refresh the cached file
962 Instance
.getCache().refresh(url
, support
, true);
963 } catch (IOException e
) {
964 // woops, broken image
974 * Open the input file that will be used through the support.
977 * the source {@link URL}
979 * @return the {@link InputStream}
981 * @throws IOException
982 * in case of I/O error
984 protected InputStream
openInput(URL source
) throws IOException
{
985 return Instance
.getCache().open(source
, this, false);
989 * Reset the given {@link InputStream} and return it.
992 * the {@link InputStream} to reset
994 * @return the same {@link InputStream} after reset
996 protected InputStream
reset(InputStream in
) {
999 } catch (IOException e
) {
1005 * Reset then return {@link BasicSupport#in}.
1007 * @return {@link BasicSupport#in}
1009 protected InputStream
getInput() {
1014 * Fix the author name if it is prefixed with some "by" {@link String}.
1017 * the author with a possible prefix
1019 * @return the author without prefixes
1021 protected String
fixAuthor(String author
) {
1022 if (author
!= null) {
1023 for (String suffix
: new String
[] { " ", ":" }) {
1024 for (String byString
: Instance
.getConfig()
1025 .getString(Config
.BYS
).split(",")) {
1027 if (author
.toUpperCase().startsWith(byString
.toUpperCase())) {
1028 author
= author
.substring(byString
.length()).trim();
1033 // Special case (without suffix):
1034 if (author
.startsWith("©")) {
1035 author
= author
.substring(1);
1043 * Check quotes for bad format (i.e., quotes with normal paragraphs inside)
1044 * and requotify them (i.e., separate them into QUOTE paragraphs and other
1045 * paragraphs (quotes or not)).
1048 * the paragraph to requotify (not necessarily a quote)
1050 * @return the correctly (or so we hope) quotified paragraphs
1052 protected List
<Paragraph
> requotify(Paragraph para
) {
1053 List
<Paragraph
> newParas
= new ArrayList
<Paragraph
>();
1055 if (para
.getType() == ParagraphType
.QUOTE
1056 && para
.getContent().length() > 2) {
1057 String line
= para
.getContent();
1058 boolean singleQ
= line
.startsWith("" + openQuote
);
1059 boolean doubleQ
= line
.startsWith("" + openDoubleQuote
);
1061 // Do not try when more than one quote at a time
1062 // (some stories are not easily readable if we do)
1064 && line
.indexOf(closeQuote
, 1) < line
1065 .lastIndexOf(closeQuote
)) {
1070 && line
.indexOf(closeDoubleQuote
, 1) < line
1071 .lastIndexOf(closeDoubleQuote
)) {
1077 if (!singleQ
&& !doubleQ
) {
1078 line
= openDoubleQuote
+ line
+ closeDoubleQuote
;
1079 newParas
.add(new Paragraph(ParagraphType
.QUOTE
, line
, para
1082 char open
= singleQ ? openQuote
: openDoubleQuote
;
1083 char close
= singleQ ? closeQuote
: closeDoubleQuote
;
1086 boolean inQuote
= false;
1088 for (char car
: line
.toCharArray()) {
1091 } else if (car
== close
) {
1093 } else if (car
== '.' && !inQuote
) {
1101 String rest
= line
.substring(posDot
+ 1).trim();
1102 line
= line
.substring(0, posDot
+ 1).trim();
1104 for (char car
: line
.toCharArray()) {
1109 newParas
.add(new Paragraph(ParagraphType
.QUOTE
, line
, words
));
1110 if (!rest
.isEmpty()) {
1111 newParas
.addAll(requotify(processPara(rest
)));
1125 * Process a {@link Paragraph} from a raw line of text.
1127 * Will also fix quotes and HTML encoding if needed.
1132 * @return the processed {@link Paragraph}
1134 protected Paragraph
processPara(String line
) {
1135 line
= ifUnhtml(line
).trim();
1137 boolean space
= true;
1139 boolean quote
= false;
1140 boolean tentativeCloseQuote
= false;
1145 StringBuilder builder
= new StringBuilder();
1146 for (char car
: line
.toCharArray()) {
1148 if (dashCount
> 0) {
1149 // dash, ndash and mdash: - – —
1150 // currently: always use mdash
1151 builder
.append(dashCount
== 1 ?
'-' : '—');
1156 if (tentativeCloseQuote
) {
1157 tentativeCloseQuote
= false;
1158 if (Character
.isLetterOrDigit(car
)) {
1159 builder
.append("'");
1161 // handle double-single quotes as double quotes
1163 builder
.append(closeDoubleQuote
);
1167 builder
.append(closeQuote
);
1172 case ' ': // note: unbreakable space
1175 case '\n': // just in case
1176 case '\r': // just in case
1177 if (builder
.length() > 0
1178 && builder
.charAt(builder
.length() - 1) != ' ') {
1181 builder
.append(' ');
1185 if (space
|| (brk
&& quote
)) {
1187 // handle double-single quotes as double quotes
1189 builder
.deleteCharAt(builder
.length() - 1);
1190 builder
.append(openDoubleQuote
);
1192 builder
.append(openQuote
);
1194 } else if (prev
== ' ' || prev
== car
) {
1195 // handle double-single quotes as double quotes
1197 builder
.deleteCharAt(builder
.length() - 1);
1198 builder
.append(openDoubleQuote
);
1200 builder
.append(openQuote
);
1203 // it is a quote ("I'm off") or a 'quote' ("This
1204 // 'good' restaurant"...)
1205 tentativeCloseQuote
= true;
1210 if (space
|| (brk
&& quote
)) {
1212 builder
.append(openDoubleQuote
);
1213 } else if (prev
== ' ') {
1214 builder
.append(openDoubleQuote
);
1216 builder
.append(closeDoubleQuote
);
1241 builder
.append(car
);
1250 if (space
|| (brk
&& quote
)) {
1252 builder
.append(openQuote
);
1254 // handle double-single quotes as double quotes
1256 builder
.deleteCharAt(builder
.length() - 1);
1257 builder
.append(openDoubleQuote
);
1259 builder
.append(openQuote
);
1273 // handle double-single quotes as double quotes
1275 builder
.deleteCharAt(builder
.length() - 1);
1276 builder
.append(closeDoubleQuote
);
1278 builder
.append(closeQuote
);
1287 if (space
|| (brk
&& quote
)) {
1289 builder
.append(openDoubleQuote
);
1291 builder
.append(openDoubleQuote
);
1304 builder
.append(closeDoubleQuote
);
1310 builder
.append(car
);
1317 if (tentativeCloseQuote
) {
1318 tentativeCloseQuote
= false;
1319 builder
.append(closeQuote
);
1322 line
= builder
.toString().trim();
1324 ParagraphType type
= ParagraphType
.NORMAL
;
1326 type
= ParagraphType
.BLANK
;
1328 type
= ParagraphType
.BREAK
;
1330 type
= ParagraphType
.QUOTE
;
1333 return new Paragraph(type
, line
, words
);
1337 * Remove the HTML from the input <b>if</b> {@link BasicSupport#isHtml()} is
1343 * @return the no html version if needed
1345 private String
ifUnhtml(String input
) {
1346 if (isHtml() && input
!= null) {
1347 return StringUtils
.unhtml(input
);
1354 * Return a {@link BasicSupport} implementation supporting the given
1355 * resource if possible.
1358 * the story resource
1360 * @return an implementation that supports it, or NULL
1362 public static BasicSupport
getSupport(URL url
) {
1367 // TEXT and INFO_TEXT always support files (not URLs though)
1368 for (SupportType type
: SupportType
.values()) {
1369 if (type
!= SupportType
.TEXT
&& type
!= SupportType
.INFO_TEXT
) {
1370 BasicSupport support
= getSupport(type
);
1371 if (support
!= null && support
.supports(url
)) {
1377 for (SupportType type
: new SupportType
[] { SupportType
.INFO_TEXT
,
1378 SupportType
.TEXT
}) {
1379 BasicSupport support
= getSupport(type
);
1380 if (support
!= null && support
.supports(url
)) {
1389 * Return a {@link BasicSupport} implementation supporting the given type.
1394 * @return an implementation that supports it, or NULL
1396 public static BasicSupport
getSupport(SupportType type
) {
1399 return new Epub().setType(type
);
1401 return new InfoText().setType(type
);
1403 return new Fimfiction().setType(type
);
1405 return new Fanfiction().setType(type
);
1407 return new Text().setType(type
);
1409 return new MangaFox().setType(type
);
1411 return new E621().setType(type
);
1413 return new YiffStar().setType(type
);
1415 return new EHentai().setType(type
);
1417 return new Cbz().setType(type
);
1419 return new Html().setType(type
);
1426 * Return the first line from the given input which correspond to the given
1432 * a string that must be found inside the target line (also
1433 * supports "^" at start to say "only if it starts with" the
1435 * @param relativeLine
1436 * the line to return based upon the target line position (-1 =
1437 * the line before, 0 = the target line...)
1441 static String
getLine(InputStream in
, String needle
, int relativeLine
) {
1442 return getLine(in
, needle
, relativeLine
, true);
1446 * Return a line from the given input which correspond to the given
1452 * a string that must be found inside the target line (also
1453 * supports "^" at start to say "only if it starts with" the
1455 * @param relativeLine
1456 * the line to return based upon the target line position (-1 =
1457 * the line before, 0 = the target line...)
1459 * takes the first result (as opposed to the last one, which will
1460 * also always spend the input)
1464 static String
getLine(InputStream in
, String needle
, int relativeLine
,
1470 } catch (IOException e
) {
1474 List
<String
> lines
= new ArrayList
<String
>();
1475 @SuppressWarnings("resource")
1476 Scanner scan
= new Scanner(in
, "UTF-8");
1478 scan
.useDelimiter("\\n");
1479 while (scan
.hasNext()) {
1480 lines
.add(scan
.next());
1483 if (needle
.startsWith("^")) {
1484 if (lines
.get(lines
.size() - 1).startsWith(
1485 needle
.substring(1))) {
1486 index
= lines
.size() - 1;
1490 if (lines
.get(lines
.size() - 1).contains(needle
)) {
1491 index
= lines
.size() - 1;
1496 if (index
>= 0 && index
+ relativeLine
< lines
.size()) {
1497 rep
= lines
.get(index
+ relativeLine
);
1508 * Return the text between the key and the endKey (and optional subKey can
1509 * be passed, in this case we will look for the key first, then take the
1510 * text between the subKey and the endKey).
1512 * Will only match the first line with the given key if more than one are
1513 * possible. Which also means that if the subKey or endKey is not found on
1514 * that line, NULL will be returned.
1519 * the key to match (also supports "^" at start to say
1520 * "only if it starts with" the key)
1522 * the sub key or NULL if none
1524 * the end key or NULL for "up to the end"
1525 * @return the text or NULL if not found
1527 static String
getKeyLine(InputStream in
, String key
, String subKey
,
1529 String result
= null;
1531 String line
= getLine(in
, key
, 0);
1532 if (line
!= null && line
.contains(key
)) {
1533 line
= line
.substring(line
.indexOf(key
) + key
.length());
1534 if (subKey
== null || subKey
.isEmpty() || line
.contains(subKey
)) {
1535 if (subKey
!= null) {
1536 line
= line
.substring(line
.indexOf(subKey
)
1539 if (endKey
== null || line
.contains(endKey
)) {
1540 if (endKey
!= null) {
1541 line
= line
.substring(0, line
.indexOf(endKey
));