6d44c047d6dccf89907a4345e80b03a670c22ad5
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
)));
372 } catch (IOException e
) {
380 currentReferer
= null;
389 public SupportType
getType() {
394 * The current referer {@link URL} (only one 'r', as in 'HTML'...), i.e.,
395 * the current {@link URL} we work on.
397 * @return the referer
399 public URL
getCurrentReferer() {
400 return currentReferer
;
404 * The current referer {@link URL} (only one 'r', as in 'HTML'...), i.e.,
405 * the current {@link URL} we work on.
407 * @param currentReferer
410 protected void setCurrentReferer(URL currentReferer
) {
411 this.currentReferer
= currentReferer
;
422 protected BasicSupport
setType(SupportType type
) {
428 * Prepare the support if needed before processing.
431 * the source of the story
433 * the input (the main resource)
435 * @throws IOException
438 protected void preprocess(URL source
, InputStream in
) throws IOException
{
442 * Now that we have processed the {@link Story}, close the resources if any.
444 * @throws IOException
447 protected void close() throws IOException
{
451 * Create a {@link Chapter} object from the given information, formatting
452 * the content as it should be.
459 * the chapter content
461 * @return the {@link Chapter}
463 * @throws IOException
464 * in case of I/O error
466 protected Chapter
makeChapter(URL source
, int number
, String name
,
467 String content
) throws IOException
{
469 // Chapter name: process it correctly, then remove the possible
470 // redundant "Chapter x: " in front of it
471 String chapterName
= processPara(name
).getContent().trim();
472 for (String lang
: Instance
.getConfig().getString(Config
.CHAPTER
)
474 String chapterWord
= Instance
.getConfig().getStringX(
475 Config
.CHAPTER
, lang
);
476 if (chapterName
.startsWith(chapterWord
)) {
477 chapterName
= chapterName
.substring(chapterWord
.length())
483 if (chapterName
.startsWith(Integer
.toString(number
))) {
484 chapterName
= chapterName
.substring(
485 Integer
.toString(number
).length()).trim();
488 if (chapterName
.startsWith(":")) {
489 chapterName
= chapterName
.substring(1).trim();
493 Chapter chap
= new Chapter(number
, chapterName
);
495 if (content
== null) {
500 // Special <HR> processing:
501 content
= content
.replaceAll("(<hr [^>]*>)|(<hr/>)|(<hr>)",
505 InputStream in
= new ByteArrayInputStream(content
.getBytes("UTF-8"));
507 @SuppressWarnings("resource")
508 Scanner scan
= new Scanner(in
, "UTF-8");
509 scan
.useDelimiter("(\\n|</p>)"); // \n for test, </p> for html
511 List
<Paragraph
> paras
= new ArrayList
<Paragraph
>();
512 while (scan
.hasNext()) {
513 String line
= scan
.next().trim();
514 boolean image
= false;
515 if (line
.startsWith("[") && line
.endsWith("]")) {
516 URL url
= getImageUrl(source
,
517 line
.substring(1, line
.length() - 1).trim());
519 paras
.add(new Paragraph(url
));
525 paras
.add(processPara(line
));
529 // Check quotes for "bad" format
530 List
<Paragraph
> newParas
= new ArrayList
<Paragraph
>();
531 for (Paragraph para
: paras
) {
532 newParas
.addAll(requotify(para
));
536 // Remove double blanks/brks
537 boolean space
= false;
539 for (int i
= 0; i
< paras
.size(); i
++) {
540 Paragraph para
= paras
.get(i
);
541 boolean thisSpace
= para
.getType() == ParagraphType
.BLANK
;
542 boolean thisBrk
= para
.getType() == ParagraphType
.BREAK
;
544 if (space
&& thisBrk
) {
547 } else if ((space
|| brk
) && (thisSpace
|| thisBrk
)) {
556 // Remove blank/brk at start
558 && (paras
.get(0).getType() == ParagraphType
.BLANK
|| paras
559 .get(0).getType() == ParagraphType
.BREAK
)) {
563 // Remove blank/brk at end
564 int last
= paras
.size() - 1;
566 && (paras
.get(last
).getType() == ParagraphType
.BLANK
|| paras
567 .get(last
).getType() == ParagraphType
.BREAK
)) {
571 chap
.setParagraphs(paras
);
579 static BufferedImage
getDefaultCover(String subject
) {
580 if (subject
!= null && !subject
.isEmpty()
581 && Instance
.getCoverDir() != null) {
583 File fileCover
= new File(Instance
.getCoverDir(), subject
);
584 return getImage(fileCover
.toURI().toURL(), subject
);
585 } catch (MalformedURLException e
) {
593 * Return the list of supported image extensions.
595 * @return the extensions
597 static String
[] getImageExt(boolean emptyAllowed
) {
599 return new String
[] { "", ".png", ".jpg", ".jpeg", ".gif", ".bmp" };
601 return new String
[] { ".png", ".jpg", ".jpeg", ".gif", ".bmp" };
605 static BufferedImage
getImage(URL source
, String line
) {
606 URL url
= getImageUrl(source
, line
);
608 InputStream in
= null;
610 in
= Instance
.getCache().open(url
, getSupport(url
), true);
611 return ImageIO
.read(in
);
612 } catch (IOException e
) {
617 } catch (IOException e
) {
627 * Check if the given resource can be a local image or a remote image, then
628 * refresh the cache with it if it is.
633 * the resource to check
635 * @return the image URL if found, or NULL
638 static URL
getImageUrl(URL source
, String line
) {
644 if (source
!= null) {
645 path
= new File(source
.getFile()).getParent();
647 String urlBase
= new File(new File(path
), line
.trim())
648 .toURI().toURL().toString();
649 for (String ext
: getImageExt(true)) {
650 if (new File(urlBase
+ ext
).exists()) {
651 url
= new File(urlBase
+ ext
).toURI().toURL();
654 } catch (Exception e
) {
655 // Nothing to do here
662 for (String ext
: getImageExt(true)) {
663 if (Instance
.getCache().check(new URL(line
+ ext
))) {
664 url
= new URL(line
+ ext
);
670 for (String ext
: getImageExt(true)) {
672 url
= new URL(line
+ ext
);
673 Instance
.getCache().refresh(url
,
674 getSupport(url
), true);
676 } catch (IOException e
) {
677 // no image with this ext
682 } catch (MalformedURLException e
) {
687 // refresh the cached file
690 Instance
.getCache().refresh(url
, getSupport(url
), true);
691 } catch (IOException e
) {
692 // woops, broken image
701 protected InputStream
reset(InputStream in
) {
704 } catch (IOException e
) {
710 * Reset then return {@link BasicSupport#in}.
712 * @return {@link BasicSupport#in}
714 protected InputStream
getInput() {
719 * Fix the author name if it is prefixed with some "by" {@link String}.
722 * the author with a possible prefix
724 * @return the author without prefixes
726 protected String
fixAuthor(String author
) {
727 if (author
!= null) {
728 for (String suffix
: new String
[] { " ", ":" }) {
729 for (String byString
: Instance
.getConfig()
730 .getString(Config
.BYS
).split(",")) {
732 if (author
.toUpperCase().startsWith(byString
.toUpperCase())) {
733 author
= author
.substring(byString
.length()).trim();
738 // Special case (without suffix):
739 if (author
.startsWith("©")) {
740 author
= author
.substring(1);
748 * Check quotes for bad format (i.e., quotes with normal paragraphs inside)
749 * and requotify them (i.e., separate them into QUOTE paragraphs and other
750 * paragraphs (quotes or not)).
753 * the paragraph to requotify (not necessaraly a quote)
755 * @return the correctly (or so we hope) quotified paragraphs
757 private List
<Paragraph
> requotify(Paragraph para
) {
758 List
<Paragraph
> newParas
= new ArrayList
<Paragraph
>();
760 if (para
.getType() == ParagraphType
.QUOTE
761 && para
.getContent().length() > 2) {
762 String line
= para
.getContent();
763 boolean singleQ
= line
.startsWith("" + openQuote
);
764 boolean doubleQ
= line
.startsWith("" + openDoubleQuote
);
766 if (!singleQ
&& !doubleQ
) {
767 line
= openDoubleQuote
+ line
+ closeDoubleQuote
;
768 newParas
.add(new Paragraph(ParagraphType
.QUOTE
, line
));
770 char close
= singleQ ? closeQuote
: closeDoubleQuote
;
771 int posClose
= line
.indexOf(close
, 1);
772 int posDot
= line
.indexOf(".");
773 while (posDot
>= 0 && posDot
< posClose
) {
774 posDot
= line
.indexOf(".", posDot
+ 1);
778 String rest
= line
.substring(posDot
+ 1).trim();
779 line
= line
.substring(0, posDot
+ 1).trim();
780 newParas
.add(new Paragraph(ParagraphType
.QUOTE
, line
));
781 if (!rest
.isEmpty()) {
782 newParas
.addAll(requotify(processPara(rest
)));
796 * Process a {@link Paragraph} from a raw line of text.
798 * Will also fix quotes and HTML encoding if needed.
803 * @return the processed {@link Paragraph}
805 private Paragraph
processPara(String line
) {
806 line
= ifUnhtml(line
).trim();
808 boolean space
= true;
810 boolean quote
= false;
811 boolean tentativeCloseQuote
= false;
815 StringBuilder builder
= new StringBuilder();
816 for (char car
: line
.toCharArray()) {
819 // dash, ndash and mdash: - – —
820 // currently: always use mdash
821 builder
.append(dashCount
== 1 ?
'-' : '—');
826 if (tentativeCloseQuote
) {
827 tentativeCloseQuote
= false;
828 if ((car
>= 'a' && car
<= 'z') || (car
>= 'A' && car
<= 'Z')
829 || (car
>= '0' && car
<= '9')) {
832 builder
.append(closeQuote
);
837 case ' ': // note: unbreakable space
840 case '\n': // just in case
841 case '\r': // just in case
846 if (space
|| (brk
&& quote
)) {
848 builder
.append(openQuote
);
849 } else if (prev
== ' ') {
850 builder
.append(openQuote
);
852 // it is a quote ("I'm off") or a 'quote' ("This
853 // 'good' restaurant"...)
854 tentativeCloseQuote
= true;
859 if (space
|| (brk
&& quote
)) {
861 builder
.append(openDoubleQuote
);
862 } else if (prev
== ' ') {
863 builder
.append(openDoubleQuote
);
865 builder
.append(closeDoubleQuote
);
899 if (space
|| (brk
&& quote
)) {
901 builder
.append(openQuote
);
903 builder
.append(openQuote
);
916 builder
.append(closeQuote
);
924 if (space
|| (brk
&& quote
)) {
926 builder
.append(openDoubleQuote
);
928 builder
.append(openDoubleQuote
);
941 builder
.append(closeDoubleQuote
);
954 if (tentativeCloseQuote
) {
955 tentativeCloseQuote
= false;
956 builder
.append(closeQuote
);
959 line
= builder
.toString().trim();
961 ParagraphType type
= ParagraphType
.NORMAL
;
963 type
= ParagraphType
.BLANK
;
965 type
= ParagraphType
.BREAK
;
967 type
= ParagraphType
.QUOTE
;
970 return new Paragraph(type
, line
);
974 * Remove the HTML from the inpit <b>if</b> {@link BasicSupport#isHtml()} is
980 * @return the no html version if needed
982 private String
ifUnhtml(String input
) {
983 if (isHtml() && input
!= null) {
984 return StringUtils
.unhtml(input
);
991 * Return a {@link BasicSupport} implementation supporting the given
992 * resource if possible.
997 * @return an implementation that supports it, or NULL
999 public static BasicSupport
getSupport(URL url
) {
1004 // TEXT and INFO_TEXT always support files (not URLs though)
1005 for (SupportType type
: SupportType
.values()) {
1006 if (type
!= SupportType
.TEXT
&& type
!= SupportType
.INFO_TEXT
) {
1007 BasicSupport support
= getSupport(type
);
1008 if (support
!= null && support
.supports(url
)) {
1014 for (SupportType type
: new SupportType
[] { SupportType
.TEXT
,
1015 SupportType
.INFO_TEXT
}) {
1016 BasicSupport support
= getSupport(type
);
1017 if (support
!= null && support
.supports(url
)) {
1026 * Return a {@link BasicSupport} implementation supporting the given type.
1031 * @return an implementation that supports it, or NULL
1033 public static BasicSupport
getSupport(SupportType type
) {
1036 return new Epub().setType(type
);
1038 return new InfoText().setType(type
);
1040 return new Fimfiction().setType(type
);
1042 return new Fanfiction().setType(type
);
1044 return new Text().setType(type
);
1046 return new MangaFox().setType(type
);
1048 return new E621().setType(type
);
1050 return new Cbz().setType(type
);
1057 * Return the first line from the given input which correspond to the given
1063 * a string that must be found inside the target line (also
1064 * supports "^" at start to say "only if it starts with" the
1066 * @param relativeLine
1067 * the line to return based upon the target line position (-1 =
1068 * the line before, 0 = the target line...)
1072 static String
getLine(InputStream in
, String needle
, int relativeLine
) {
1073 return getLine(in
, needle
, relativeLine
, true);
1077 * Return a line from the given input which correspond to the given
1083 * a string that must be found inside the target line (also
1084 * supports "^" at start to say "only if it starts with" the
1086 * @param relativeLine
1087 * the line to return based upon the target line position (-1 =
1088 * the line before, 0 = the target line...)
1090 * takes the first result (as opposed to the last one, which will
1091 * also always spend the input)
1095 static String
getLine(InputStream in
, String needle
, int relativeLine
,
1101 } catch (IOException e
) {
1105 List
<String
> lines
= new ArrayList
<String
>();
1106 @SuppressWarnings("resource")
1107 Scanner scan
= new Scanner(in
, "UTF-8");
1109 scan
.useDelimiter("\\n");
1110 while (scan
.hasNext()) {
1111 lines
.add(scan
.next());
1114 if (needle
.startsWith("^")) {
1115 if (lines
.get(lines
.size() - 1).startsWith(
1116 needle
.substring(1))) {
1117 index
= lines
.size() - 1;
1121 if (lines
.get(lines
.size() - 1).contains(needle
)) {
1122 index
= lines
.size() - 1;
1127 if (index
>= 0 && index
+ relativeLine
< lines
.size()) {
1128 rep
= lines
.get(index
+ relativeLine
);