61a4500759bccb26366d23ade04f07053c169dcb
1 package be
.nikiroo
.fanfix
.supported
;
3 import java
.awt
.image
.BufferedImage
;
4 import java
.io
.ByteArrayInputStream
;
6 import java
.io
.IOException
;
7 import java
.io
.InputStream
;
8 import java
.net
.MalformedURLException
;
10 import java
.util
.ArrayList
;
11 import java
.util
.HashMap
;
12 import java
.util
.List
;
14 import java
.util
.Map
.Entry
;
15 import java
.util
.Scanner
;
17 import javax
.imageio
.ImageIO
;
19 import be
.nikiroo
.fanfix
.Instance
;
20 import be
.nikiroo
.fanfix
.bundles
.Config
;
21 import be
.nikiroo
.fanfix
.bundles
.StringId
;
22 import be
.nikiroo
.fanfix
.data
.Chapter
;
23 import be
.nikiroo
.fanfix
.data
.MetaData
;
24 import be
.nikiroo
.fanfix
.data
.Paragraph
;
25 import be
.nikiroo
.fanfix
.data
.Paragraph
.ParagraphType
;
26 import be
.nikiroo
.fanfix
.data
.Story
;
27 import be
.nikiroo
.utils
.StringUtils
;
30 * This class is the base class used by the other support classes. It can be
31 * used outside of this package, and have static method that you can use to get
32 * access to the correct support class.
34 * It will be used with 'resources' (usually web pages or files).
38 public abstract class BasicSupport
{
40 * The supported input types for which we can get a {@link BasicSupport}
45 public enum SupportType
{
46 /** EPUB files created with this program */
48 /** Pure text file with some rules */
50 /** TEXT but with associated .info file */
52 /** My Little Pony fanfictions */
54 /** Fanfictions from a lot of different universes */
56 /** Website with lots of Mangas */
58 /** Furry website with comics support */
64 * A description of this support type (more information than the
65 * {@link BasicSupport#getSourceName()}).
67 * @return the description
69 public String
getDesc() {
70 String desc
= Instance
.getTrans().getStringX(StringId
.INPUT_DESC
,
74 desc
= Instance
.getTrans().getString(StringId
.INPUT_DESC
, this);
81 * The name of this support type (a short version).
85 public String
getSourceName() {
86 BasicSupport support
= BasicSupport
.getSupport(this);
87 if (support
!= null) {
88 return support
.getSourceName();
95 public String
toString() {
96 return super.toString().toLowerCase();
100 * Call {@link SupportType#valueOf(String.toUpperCase())}.
103 * the possible type name
105 * @return NULL or the type
107 public static SupportType
valueOfUC(String typeName
) {
108 return SupportType
.valueOf(typeName
== null ?
null : typeName
113 * Call {@link SupportType#valueOf(String.toUpperCase())} but return
114 * NULL for NULL instead of raising exception.
117 * the possible type name
119 * @return NULL or the type
121 public static SupportType
valueOfNullOkUC(String typeName
) {
122 if (typeName
== null) {
126 return SupportType
.valueOfUC(typeName
);
130 * Call {@link SupportType#valueOf(String.toUpperCase())} but return
131 * NULL in case of error instead of raising an exception.
134 * the possible type name
136 * @return NULL or the type
138 public static SupportType
valueOfAllOkUC(String typeName
) {
140 return SupportType
.valueOfUC(typeName
);
141 } catch (Exception e
) {
147 private InputStream in
;
148 private SupportType type
;
149 private URL currentReferer
; // with on 'r', as in 'HTTP'...
152 private char openQuote
= Instance
.getTrans().getChar(
153 StringId
.OPEN_SINGLE_QUOTE
);
154 private char closeQuote
= Instance
.getTrans().getChar(
155 StringId
.CLOSE_SINGLE_QUOTE
);
156 private char openDoubleQuote
= Instance
.getTrans().getChar(
157 StringId
.OPEN_DOUBLE_QUOTE
);
158 private char closeDoubleQuote
= Instance
.getTrans().getChar(
159 StringId
.CLOSE_DOUBLE_QUOTE
);
162 * The name of this support class.
166 protected abstract String
getSourceName();
169 * Check if the given resource is supported by this {@link BasicSupport}.
172 * the resource to check for
174 * @return TRUE if it is
176 protected abstract boolean supports(URL url
);
179 * Return TRUE if the support will return HTML encoded content values for
180 * the chapters content.
182 * @return TRUE for HTML
184 protected abstract boolean isHtml();
186 protected abstract MetaData
getMeta(URL source
, InputStream in
)
190 * Return the story description.
193 * the source of the story
195 * the input (the main resource)
197 * @return the description
199 * @throws IOException
200 * in case of I/O error
202 protected abstract String
getDesc(URL source
, InputStream in
)
206 * Return the list of chapters (name and resource).
209 * the source of the story
211 * the input (the main resource)
213 * @return the chapters
215 * @throws IOException
216 * in case of I/O error
218 protected abstract List
<Entry
<String
, URL
>> getChapters(URL source
,
219 InputStream in
) throws IOException
;
222 * Return the content of the chapter (possibly HTML encoded, if
223 * {@link BasicSupport#isHtml()} is TRUE).
226 * the source of the story
228 * the input (the main resource)
232 * @return the content
234 * @throws IOException
235 * in case of I/O error
237 protected abstract String
getChapterContent(URL source
, InputStream in
,
238 int number
) throws IOException
;
241 * Return the list of cookies (values included) that must be used to
242 * correctly fetch the resources.
244 * You are expected to call the super method implementation if you override
247 * @return the cookies
249 public Map
<String
, String
> getCookies() {
250 return new HashMap
<String
, String
>();
254 * Process the given story resource into a partially filled {@link Story}
255 * object containing the name and metadata, except for the description.
260 * @return the {@link Story}
262 * @throws IOException
263 * in case of I/O error
265 public Story
processMeta(URL url
) throws IOException
{
266 return processMeta(url
, true, false);
270 * Process the given story resource into a partially filled {@link Story}
271 * object containing the name and metadata.
277 * close "this" and "in" when done
279 * @return the {@link Story}
281 * @throws IOException
282 * in case of I/O error
284 protected Story
processMeta(URL url
, boolean close
, boolean getDesc
)
286 in
= Instance
.getCache().open(url
, this, false);
292 preprocess(url
, getInput());
294 Story story
= new Story();
295 MetaData meta
= getMeta(url
, getInput());
298 if (meta
!= null && meta
.getCover() == null) {
299 meta
.setCover(getDefaultCover(meta
.getSubject()));
303 String descChapterName
= Instance
.getTrans().getString(
304 StringId
.DESCRIPTION
);
305 story
.getMeta().setResume(
306 makeChapter(url
, 0, descChapterName
,
307 getDesc(url
, getInput())));
315 } catch (IOException e
) {
327 * Process the given story resource into a fully filled {@link Story}
333 * @return the {@link Story}
335 * @throws IOException
336 * in case of I/O error
338 public Story
process(URL url
) throws IOException
{
339 setCurrentReferer(url
);
342 Story story
= processMeta(url
, false, true);
347 story
.setChapters(new ArrayList
<Chapter
>());
349 List
<Entry
<String
, URL
>> chapters
= getChapters(url
, getInput());
351 if (chapters
!= null) {
352 for (Entry
<String
, URL
> chap
: chapters
) {
353 setCurrentReferer(chap
.getValue());
354 InputStream chapIn
= Instance
.getCache().open(
355 chap
.getValue(), this, true);
357 story
.getChapters().add(
358 makeChapter(url
, i
, chap
.getKey(),
359 getChapterContent(url
, chapIn
, i
)));
373 } catch (IOException e
) {
381 currentReferer
= null;
390 public SupportType
getType() {
395 * The current referer {@link URL} (only one 'r', as in 'HTML'...), i.e.,
396 * the current {@link URL} we work on.
398 * @return the referer
400 public URL
getCurrentReferer() {
401 return currentReferer
;
405 * The current referer {@link URL} (only one 'r', as in 'HTML'...), i.e.,
406 * the current {@link URL} we work on.
408 * @param currentReferer
411 protected void setCurrentReferer(URL currentReferer
) {
412 this.currentReferer
= currentReferer
;
423 protected BasicSupport
setType(SupportType type
) {
429 * Prepare the support if needed before processing.
432 * the source of the story
434 * the input (the main resource)
436 * @throws IOException
439 protected void preprocess(URL source
, InputStream in
) throws IOException
{
443 * Now that we have processed the {@link Story}, close the resources if any.
445 * @throws IOException
448 protected void close() throws IOException
{
452 * Create a {@link Chapter} object from the given information, formatting
453 * the content as it should be.
460 * the chapter content
462 * @return the {@link Chapter}
464 * @throws IOException
465 * in case of I/O error
467 protected Chapter
makeChapter(URL source
, int number
, String name
,
468 String content
) throws IOException
{
470 // Chapter name: process it correctly, then remove the possible
471 // redundant "Chapter x: " in front of it
472 String chapterName
= processPara(name
).getContent().trim();
473 for (String lang
: Instance
.getConfig().getString(Config
.CHAPTER
)
475 String chapterWord
= Instance
.getConfig().getStringX(
476 Config
.CHAPTER
, lang
);
477 if (chapterName
.startsWith(chapterWord
)) {
478 chapterName
= chapterName
.substring(chapterWord
.length())
484 if (chapterName
.startsWith(Integer
.toString(number
))) {
485 chapterName
= chapterName
.substring(
486 Integer
.toString(number
).length()).trim();
489 if (chapterName
.startsWith(":")) {
490 chapterName
= chapterName
.substring(1).trim();
494 Chapter chap
= new Chapter(number
, chapterName
);
496 if (content
== null) {
501 // Special <HR> processing:
502 content
= content
.replaceAll("(<hr [^>]*>)|(<hr/>)|(<hr>)",
506 InputStream in
= new ByteArrayInputStream(content
.getBytes("UTF-8"));
508 @SuppressWarnings("resource")
509 Scanner scan
= new Scanner(in
, "UTF-8");
510 scan
.useDelimiter("(\\n|</p>)"); // \n for test, </p> for html
512 List
<Paragraph
> paras
= new ArrayList
<Paragraph
>();
513 while (scan
.hasNext()) {
514 String line
= scan
.next().trim();
515 boolean image
= false;
516 if (line
.startsWith("[") && line
.endsWith("]")) {
517 URL url
= getImageUrl(this, source
,
518 line
.substring(1, line
.length() - 1).trim());
520 paras
.add(new Paragraph(url
));
526 paras
.add(processPara(line
));
530 // Check quotes for "bad" format
531 List
<Paragraph
> newParas
= new ArrayList
<Paragraph
>();
532 for (Paragraph para
: paras
) {
533 newParas
.addAll(requotify(para
));
537 // Remove double blanks/brks
538 boolean space
= false;
540 for (int i
= 0; i
< paras
.size(); i
++) {
541 Paragraph para
= paras
.get(i
);
542 boolean thisSpace
= para
.getType() == ParagraphType
.BLANK
;
543 boolean thisBrk
= para
.getType() == ParagraphType
.BREAK
;
545 if (space
&& thisBrk
) {
548 } else if ((space
|| brk
) && (thisSpace
|| thisBrk
)) {
557 // Remove blank/brk at start
559 && (paras
.get(0).getType() == ParagraphType
.BLANK
|| paras
560 .get(0).getType() == ParagraphType
.BREAK
)) {
564 // Remove blank/brk at end
565 int last
= paras
.size() - 1;
567 && (paras
.get(last
).getType() == ParagraphType
.BLANK
|| paras
568 .get(last
).getType() == ParagraphType
.BREAK
)) {
572 chap
.setParagraphs(paras
);
580 static BufferedImage
getDefaultCover(String subject
) {
581 if (subject
!= null && !subject
.isEmpty()
582 && Instance
.getCoverDir() != null) {
584 File fileCover
= new File(Instance
.getCoverDir(), subject
);
585 return getImage(null, fileCover
.toURI().toURL(), subject
);
586 } catch (MalformedURLException e
) {
594 * Return the list of supported image extensions.
596 * @return the extensions
598 static String
[] getImageExt(boolean emptyAllowed
) {
600 return new String
[] { "", ".png", ".jpg", ".jpeg", ".gif", ".bmp" };
602 return new String
[] { ".png", ".jpg", ".jpeg", ".gif", ".bmp" };
606 static BufferedImage
getImage(BasicSupport support
, URL source
, String line
) {
607 URL url
= getImageUrl(support
, source
, line
);
609 InputStream in
= null;
611 in
= Instance
.getCache().open(url
, getSupport(url
), true);
612 return ImageIO
.read(in
);
613 } catch (IOException e
) {
618 } catch (IOException e
) {
628 * Check if the given resource can be a local image or a remote image, then
629 * refresh the cache with it if it is.
634 * the resource to check
636 * @return the image URL if found, or NULL
639 static URL
getImageUrl(BasicSupport support
, URL source
, String line
) {
645 if (source
!= null) {
646 path
= new File(source
.getFile()).getParent();
648 String basePath
= new File(new File(path
), line
.trim())
650 for (String ext
: getImageExt(true)) {
651 if (new File(basePath
+ ext
).exists()) {
652 url
= new File(basePath
+ ext
).toURI().toURL();
655 } catch (Exception e
) {
656 // Nothing to do here
663 for (String ext
: getImageExt(true)) {
664 if (Instance
.getCache().check(new URL(line
+ ext
))) {
665 url
= new URL(line
+ ext
);
672 for (String ext
: getImageExt(true)) {
674 url
= new URL(line
+ ext
);
675 Instance
.getCache().refresh(url
, support
, true);
677 } catch (IOException e
) {
678 // no image with this ext
683 } catch (MalformedURLException e
) {
688 // refresh the cached file
691 Instance
.getCache().refresh(url
, support
, true);
692 } catch (IOException e
) {
693 // woops, broken image
702 protected InputStream
reset(InputStream in
) {
705 } catch (IOException e
) {
711 * Reset then return {@link BasicSupport#in}.
713 * @return {@link BasicSupport#in}
715 protected InputStream
getInput() {
720 * Fix the author name if it is prefixed with some "by" {@link String}.
723 * the author with a possible prefix
725 * @return the author without prefixes
727 protected String
fixAuthor(String author
) {
728 if (author
!= null) {
729 for (String suffix
: new String
[] { " ", ":" }) {
730 for (String byString
: Instance
.getConfig()
731 .getString(Config
.BYS
).split(",")) {
733 if (author
.toUpperCase().startsWith(byString
.toUpperCase())) {
734 author
= author
.substring(byString
.length()).trim();
739 // Special case (without suffix):
740 if (author
.startsWith("©")) {
741 author
= author
.substring(1);
749 * Check quotes for bad format (i.e., quotes with normal paragraphs inside)
750 * and requotify them (i.e., separate them into QUOTE paragraphs and other
751 * paragraphs (quotes or not)).
754 * the paragraph to requotify (not necessaraly a quote)
756 * @return the correctly (or so we hope) quotified paragraphs
758 private List
<Paragraph
> requotify(Paragraph para
) {
759 List
<Paragraph
> newParas
= new ArrayList
<Paragraph
>();
761 if (para
.getType() == ParagraphType
.QUOTE
762 && para
.getContent().length() > 2) {
763 String line
= para
.getContent();
764 boolean singleQ
= line
.startsWith("" + openQuote
);
765 boolean doubleQ
= line
.startsWith("" + openDoubleQuote
);
767 if (!singleQ
&& !doubleQ
) {
768 line
= openDoubleQuote
+ line
+ closeDoubleQuote
;
769 newParas
.add(new Paragraph(ParagraphType
.QUOTE
, line
));
771 char open
= singleQ ? openQuote
: openDoubleQuote
;
772 char close
= singleQ ? closeQuote
: closeDoubleQuote
;
775 boolean inQuote
= false;
777 for (char car
: line
.toCharArray()) {
780 } else if (car
== close
) {
782 } else if (car
== '.' && !inQuote
) {
790 String rest
= line
.substring(posDot
+ 1).trim();
791 line
= line
.substring(0, posDot
+ 1).trim();
792 newParas
.add(new Paragraph(ParagraphType
.QUOTE
, line
));
793 if (!rest
.isEmpty()) {
794 newParas
.addAll(requotify(processPara(rest
)));
808 * Process a {@link Paragraph} from a raw line of text.
810 * Will also fix quotes and HTML encoding if needed.
815 * @return the processed {@link Paragraph}
817 private Paragraph
processPara(String line
) {
818 line
= ifUnhtml(line
).trim();
820 boolean space
= true;
822 boolean quote
= false;
823 boolean tentativeCloseQuote
= false;
827 StringBuilder builder
= new StringBuilder();
828 for (char car
: line
.toCharArray()) {
831 // dash, ndash and mdash: - – —
832 // currently: always use mdash
833 builder
.append(dashCount
== 1 ?
'-' : '—');
838 if (tentativeCloseQuote
) {
839 tentativeCloseQuote
= false;
840 if ((car
>= 'a' && car
<= 'z') || (car
>= 'A' && car
<= 'Z')
841 || (car
>= '0' && car
<= '9')) {
844 builder
.append(closeQuote
);
849 case ' ': // note: unbreakable space
852 case '\n': // just in case
853 case '\r': // just in case
858 if (space
|| (brk
&& quote
)) {
860 builder
.append(openQuote
);
861 } else if (prev
== ' ') {
862 builder
.append(openQuote
);
864 // it is a quote ("I'm off") or a 'quote' ("This
865 // 'good' restaurant"...)
866 tentativeCloseQuote
= true;
871 if (space
|| (brk
&& quote
)) {
873 builder
.append(openDoubleQuote
);
874 } else if (prev
== ' ') {
875 builder
.append(openDoubleQuote
);
877 builder
.append(closeDoubleQuote
);
911 if (space
|| (brk
&& quote
)) {
913 builder
.append(openQuote
);
915 builder
.append(openQuote
);
928 builder
.append(closeQuote
);
936 if (space
|| (brk
&& quote
)) {
938 builder
.append(openDoubleQuote
);
940 builder
.append(openDoubleQuote
);
953 builder
.append(closeDoubleQuote
);
966 if (tentativeCloseQuote
) {
967 tentativeCloseQuote
= false;
968 builder
.append(closeQuote
);
971 line
= builder
.toString().trim();
973 ParagraphType type
= ParagraphType
.NORMAL
;
975 type
= ParagraphType
.BLANK
;
977 type
= ParagraphType
.BREAK
;
979 type
= ParagraphType
.QUOTE
;
982 return new Paragraph(type
, line
);
986 * Remove the HTML from the inpit <b>if</b> {@link BasicSupport#isHtml()} is
992 * @return the no html version if needed
994 private String
ifUnhtml(String input
) {
995 if (isHtml() && input
!= null) {
996 return StringUtils
.unhtml(input
);
1003 * Return a {@link BasicSupport} implementation supporting the given
1004 * resource if possible.
1007 * the story resource
1009 * @return an implementation that supports it, or NULL
1011 public static BasicSupport
getSupport(URL url
) {
1016 // TEXT and INFO_TEXT always support files (not URLs though)
1017 for (SupportType type
: SupportType
.values()) {
1018 if (type
!= SupportType
.TEXT
&& type
!= SupportType
.INFO_TEXT
) {
1019 BasicSupport support
= getSupport(type
);
1020 if (support
!= null && support
.supports(url
)) {
1026 for (SupportType type
: new SupportType
[] { SupportType
.TEXT
,
1027 SupportType
.INFO_TEXT
}) {
1028 BasicSupport support
= getSupport(type
);
1029 if (support
!= null && support
.supports(url
)) {
1038 * Return a {@link BasicSupport} implementation supporting the given type.
1043 * @return an implementation that supports it, or NULL
1045 public static BasicSupport
getSupport(SupportType type
) {
1048 return new Epub().setType(type
);
1050 return new InfoText().setType(type
);
1052 return new Fimfiction().setType(type
);
1054 return new Fanfiction().setType(type
);
1056 return new Text().setType(type
);
1058 return new MangaFox().setType(type
);
1060 return new E621().setType(type
);
1062 return new Cbz().setType(type
);
1069 * Return the first line from the given input which correspond to the given
1075 * a string that must be found inside the target line (also
1076 * supports "^" at start to say "only if it starts with" the
1078 * @param relativeLine
1079 * the line to return based upon the target line position (-1 =
1080 * the line before, 0 = the target line...)
1084 static String
getLine(InputStream in
, String needle
, int relativeLine
) {
1085 return getLine(in
, needle
, relativeLine
, true);
1089 * Return a line from the given input which correspond to the given
1095 * a string that must be found inside the target line (also
1096 * supports "^" at start to say "only if it starts with" the
1098 * @param relativeLine
1099 * the line to return based upon the target line position (-1 =
1100 * the line before, 0 = the target line...)
1102 * takes the first result (as opposed to the last one, which will
1103 * also always spend the input)
1107 static String
getLine(InputStream in
, String needle
, int relativeLine
,
1113 } catch (IOException e
) {
1117 List
<String
> lines
= new ArrayList
<String
>();
1118 @SuppressWarnings("resource")
1119 Scanner scan
= new Scanner(in
, "UTF-8");
1121 scan
.useDelimiter("\\n");
1122 while (scan
.hasNext()) {
1123 lines
.add(scan
.next());
1126 if (needle
.startsWith("^")) {
1127 if (lines
.get(lines
.size() - 1).startsWith(
1128 needle
.substring(1))) {
1129 index
= lines
.size() - 1;
1133 if (lines
.get(lines
.size() - 1).contains(needle
)) {
1134 index
= lines
.size() - 1;
1139 if (index
>= 0 && index
+ relativeLine
< lines
.size()) {
1140 rep
= lines
.get(index
+ relativeLine
);