1 package be
.nikiroo
.fanfix
.library
;
4 import java
.io
.FileFilter
;
5 import java
.io
.FileInputStream
;
6 import java
.io
.FileNotFoundException
;
7 import java
.io
.IOException
;
8 import java
.io
.InputStream
;
9 import java
.util
.ArrayList
;
10 import java
.util
.HashMap
;
11 import java
.util
.List
;
14 import be
.nikiroo
.fanfix
.Instance
;
15 import be
.nikiroo
.fanfix
.bundles
.Config
;
16 import be
.nikiroo
.fanfix
.bundles
.ConfigBundle
;
17 import be
.nikiroo
.fanfix
.data
.MetaData
;
18 import be
.nikiroo
.fanfix
.data
.Story
;
19 import be
.nikiroo
.fanfix
.output
.BasicOutput
;
20 import be
.nikiroo
.fanfix
.output
.BasicOutput
.OutputType
;
21 import be
.nikiroo
.fanfix
.output
.InfoCover
;
22 import be
.nikiroo
.fanfix
.supported
.InfoReader
;
23 import be
.nikiroo
.utils
.IOUtils
;
24 import be
.nikiroo
.utils
.Image
;
25 import be
.nikiroo
.utils
.Progress
;
26 import be
.nikiroo
.utils
.StringUtils
;
29 * This {@link BasicLibrary} will store the stories locally on disk.
33 public class LocalLibrary
extends BasicLibrary
{
35 private Object lock
= new Object();
36 private Map
<MetaData
, File
[]> stories
; // Files: [ infoFile, TargetFile ]
37 private Map
<String
, Image
> sourceCovers
;
38 private Map
<String
, Image
> authorCovers
;
41 private OutputType text
;
42 private OutputType image
;
45 * Create a new {@link LocalLibrary} with the given back-end directory.
48 * the directory where to find the {@link Story} objects
50 * the configuration used to know which kind of default
51 * {@link OutputType} to use for images and non-images stories
53 public LocalLibrary(File baseDir
, ConfigBundle config
) {
55 config
.getString(Config
.FILE_FORMAT_NON_IMAGES_DOCUMENT_TYPE
),
56 config
.getString(Config
.FILE_FORMAT_IMAGES_DOCUMENT_TYPE
),
61 * Create a new {@link LocalLibrary} with the given back-end directory.
64 * the directory where to find the {@link Story} objects
66 * the {@link OutputType} to use for non-image documents
68 * the {@link OutputType} to use for image documents
69 * @param defaultIsHtml
70 * if the given text or image is invalid, use HTML by default (if
71 * not, it will be INFO_TEXT/CBZ by default)
73 public LocalLibrary(File baseDir
, String text
, String image
,
74 boolean defaultIsHtml
) {
76 OutputType
.valueOfAllOkUC(text
,
77 defaultIsHtml ? OutputType
.HTML
: OutputType
.INFO_TEXT
),
78 OutputType
.valueOfAllOkUC(image
,
79 defaultIsHtml ? OutputType
.HTML
: OutputType
.CBZ
));
83 * Create a new {@link LocalLibrary} with the given back-end directory.
86 * the directory where to find the {@link Story} objects
88 * the {@link OutputType} to use for non-image documents
90 * the {@link OutputType} to use for image documents
92 public LocalLibrary(File baseDir
, OutputType text
, OutputType image
) {
93 this.baseDir
= baseDir
;
99 this.sourceCovers
= null;
105 protected List
<MetaData
> getMetas(Progress pg
) {
106 return new ArrayList
<MetaData
>(getStories(pg
).keySet());
110 public File
getFile(String luid
, Progress pg
) throws IOException
{
111 Instance
.getInstance().getTraceHandler().trace(
112 this.getClass().getSimpleName() + ": get file for " + luid
);
115 String mess
= "no file found for ";
117 MetaData meta
= getInfo(luid
);
119 File
[] files
= getStories(pg
).get(meta
);
121 mess
= "file retrieved for ";
126 Instance
.getInstance().getTraceHandler()
127 .trace(this.getClass().getSimpleName() + ": " + mess
+ luid
128 + " (" + meta
.getTitle() + ")");
134 public Image
getCover(String luid
) throws IOException
{
135 MetaData meta
= getInfo(luid
);
137 if (meta
.getCover() != null) {
138 return meta
.getCover();
141 File
[] files
= getStories(null).get(meta
);
143 File infoFile
= files
[0];
146 meta
= InfoReader
.readMeta(infoFile
, true);
147 return meta
.getCover();
148 } catch (IOException e
) {
149 Instance
.getInstance().getTraceHandler().error(e
);
158 protected void updateInfo(MetaData meta
) {
163 protected void invalidateInfo(String luid
) {
164 synchronized (lock
) {
171 protected int getNextId() {
172 getStories(null); // make sure lastId is set
174 synchronized (lock
) {
180 protected void doDelete(String luid
) throws IOException
{
181 for (File file
: getRelatedFiles(luid
)) {
182 // TODO: throw an IOException if we cannot delete the files?
183 IOUtils
.deltree(file
);
184 file
.getParentFile().delete();
189 protected Story
doSave(Story story
, Progress pg
) throws IOException
{
190 MetaData meta
= story
.getMeta();
192 File expectedTarget
= getExpectedFile(meta
);
193 expectedTarget
.getParentFile().mkdirs();
195 BasicOutput it
= BasicOutput
.getOutput(getOutputType(meta
), true, true);
196 it
.process(story
, expectedTarget
.getPath(), pg
);
202 protected synchronized void saveMeta(MetaData meta
, Progress pg
)
204 File newDir
= getExpectedDir(meta
.getSource());
205 if (!newDir
.exists()) {
209 List
<File
> relatedFiles
= getRelatedFiles(meta
.getLuid());
210 for (File relatedFile
: relatedFiles
) {
211 // TODO: this is not safe at all.
212 // We should copy all the files THEN delete them
213 // Maybe also adding some rollback cleanup if possible
214 if (relatedFile
.getName().endsWith(".info")) {
216 String name
= relatedFile
.getName().replaceFirst("\\.info$",
218 relatedFile
.delete();
219 InfoCover
.writeInfo(newDir
, name
, meta
);
220 relatedFile
.getParentFile().delete();
221 } catch (IOException e
) {
222 Instance
.getInstance().getTraceHandler().error(e
);
225 relatedFile
.renameTo(new File(newDir
, relatedFile
.getName()));
226 relatedFile
.getParentFile().delete();
234 public Image
getCustomSourceCover(String source
) {
235 synchronized (lock
) {
236 if (sourceCovers
== null) {
237 sourceCovers
= new HashMap
<String
, Image
>();
241 synchronized (lock
) {
242 Image img
= sourceCovers
.get(source
);
248 File coverDir
= getExpectedDir(source
);
249 if (coverDir
.isDirectory()) {
250 File cover
= new File(coverDir
, ".cover.png");
251 if (cover
.exists()) {
254 in
= new FileInputStream(cover
);
256 synchronized (lock
) {
257 sourceCovers
.put(source
, new Image(in
));
262 } catch (FileNotFoundException e
) {
264 } catch (IOException e
) {
265 Instance
.getInstance().getTraceHandler()
266 .error(new IOException(
267 "Cannot load the existing custom source cover: "
274 synchronized (lock
) {
275 return sourceCovers
.get(source
);
280 public Image
getCustomAuthorCover(String author
) {
281 synchronized (lock
) {
282 if (authorCovers
== null) {
283 authorCovers
= new HashMap
<String
, Image
>();
287 synchronized (lock
) {
288 Image img
= authorCovers
.get(author
);
294 File cover
= getAuthorCoverFile(author
);
295 if (cover
.exists()) {
298 in
= new FileInputStream(cover
);
300 synchronized (lock
) {
301 authorCovers
.put(author
, new Image(in
));
306 } catch (FileNotFoundException e
) {
308 } catch (IOException e
) {
309 Instance
.getInstance().getTraceHandler()
310 .error(new IOException(
311 "Cannot load the existing custom author cover: "
317 synchronized (lock
) {
318 return authorCovers
.get(author
);
323 public void setSourceCover(String source
, String luid
) throws IOException
{
324 setSourceCover(source
, getCover(luid
));
328 public void setAuthorCover(String author
, String luid
) throws IOException
{
329 setAuthorCover(author
, getCover(luid
));
333 * Set the source cover to the given story cover.
336 * the source to change
340 void setSourceCover(String source
, Image coverImage
) {
341 File dir
= getExpectedDir(source
);
343 File cover
= new File(dir
, ".cover");
345 Instance
.getInstance().getCache().saveAsImage(coverImage
, cover
,
347 synchronized (lock
) {
348 if (sourceCovers
!= null) {
349 sourceCovers
.put(source
, coverImage
);
352 } catch (IOException e
) {
353 Instance
.getInstance().getTraceHandler().error(e
);
358 * Set the author cover to the given story cover.
361 * the author to change
365 void setAuthorCover(String author
, Image coverImage
) {
366 File cover
= getAuthorCoverFile(author
);
367 cover
.getParentFile().mkdirs();
369 Instance
.getInstance().getCache().saveAsImage(coverImage
, cover
,
371 synchronized (lock
) {
372 if (authorCovers
!= null) {
373 authorCovers
.put(author
, coverImage
);
376 } catch (IOException e
) {
377 Instance
.getInstance().getTraceHandler().error(e
);
382 public void imprt(BasicLibrary other
, String luid
, Progress pg
)
388 // Check if we can simply copy the files instead of the whole process
389 if (other
instanceof LocalLibrary
) {
390 LocalLibrary otherLocalLibrary
= (LocalLibrary
) other
;
392 MetaData meta
= otherLocalLibrary
.getInfo(luid
);
393 String expectedType
= ""
394 + (meta
!= null && meta
.isImageDocument() ? image
: text
);
395 if (meta
!= null && meta
.getType().equals(expectedType
)) {
396 File from
= otherLocalLibrary
.getExpectedDir(meta
.getSource());
397 File to
= this.getExpectedDir(meta
.getSource());
398 List
<File
> relatedFiles
= otherLocalLibrary
399 .getRelatedFiles(luid
);
400 if (!relatedFiles
.isEmpty()) {
401 pg
.setMinMax(0, relatedFiles
.size());
404 for (File relatedFile
: relatedFiles
) {
405 File target
= new File(relatedFile
.getAbsolutePath()
406 .replace(from
.getAbsolutePath(),
407 to
.getAbsolutePath()));
408 if (!relatedFile
.equals(target
)) {
409 target
.getParentFile().mkdirs();
410 InputStream in
= null;
412 in
= new FileInputStream(relatedFile
);
413 IOUtils
.write(in
, target
);
414 } catch (IOException e
) {
418 } catch (Exception ee
) {
436 super.imprt(other
, luid
, pg
);
440 * Return the {@link OutputType} for this {@link Story}.
443 * the {@link Story} {@link MetaData}
447 private OutputType
getOutputType(MetaData meta
) {
448 if (meta
!= null && meta
.isImageDocument()) {
456 * Return the default {@link OutputType} for this kind of {@link Story}.
458 * @param imageDocument
459 * TRUE for images document, FALSE for text documents
463 public String
getOutputType(boolean imageDocument
) {
465 return image
.toString();
468 return text
.toString();
472 * Get the target {@link File} related to the given <tt>.info</tt>
473 * {@link File} and {@link MetaData}.
478 * the <tt>.info</tt> {@link File}
480 * @return the target {@link File}
482 private File
getTargetFile(MetaData meta
, File infoFile
) {
483 // Replace .info with whatever is needed:
484 String path
= infoFile
.getPath();
485 path
= path
.substring(0, path
.length() - ".info".length());
486 String newExt
= getOutputType(meta
).getDefaultExtension(true);
488 return new File(path
+ newExt
);
492 * The target (full path) where the {@link Story} related to this
493 * {@link MetaData} should be located on disk for a new {@link Story}.
496 * the {@link Story} {@link MetaData}
500 private File
getExpectedFile(MetaData key
) {
501 String title
= key
.getTitle();
505 title
= title
.replaceAll("[^a-zA-Z0-9._+-]", "_");
506 if (title
.length() > 40) {
507 title
= title
.substring(0, 40);
509 return new File(getExpectedDir(key
.getSource()),
510 key
.getLuid() + "_" + title
);
514 * The directory (full path) where the new {@link Story} related to this
515 * {@link MetaData} should be located on disk.
520 * @return the target directory
522 private File
getExpectedDir(String source
) {
523 String sanitizedSource
= source
.replaceAll("[^a-zA-Z0-9._+/-]", "_");
525 while (sanitizedSource
.startsWith("/")
526 || sanitizedSource
.startsWith("_")) {
527 if (sanitizedSource
.length() > 1) {
528 sanitizedSource
= sanitizedSource
.substring(1);
530 sanitizedSource
= "";
534 sanitizedSource
= sanitizedSource
.replace("/", File
.separator
);
536 if (sanitizedSource
.isEmpty()) {
537 sanitizedSource
= "_EMPTY";
540 return new File(baseDir
, sanitizedSource
);
544 * Return the full path to the file to use for the custom cover of this
547 * One or more of the parent directories <b>MAY</b> not exist.
552 * @return the custom cover file
554 private File
getAuthorCoverFile(String author
) {
555 File aDir
= new File(baseDir
, "_AUTHORS");
556 String hash
= StringUtils
.getMd5Hash(author
);
557 String ext
= Instance
.getInstance().getConfig()
558 .getString(Config
.FILE_FORMAT_IMAGE_FORMAT_COVER
);
559 return new File(aDir
, hash
+ "." + ext
.toLowerCase());
563 * Return the list of files/directories on disk for this {@link Story}.
565 * If the {@link Story} is not found, and empty list is returned.
568 * the {@link Story} LUID
570 * @return the list of {@link File}s
572 * @throws IOException
573 * if the {@link Story} was not found
575 private List
<File
> getRelatedFiles(String luid
) throws IOException
{
576 List
<File
> files
= new ArrayList
<File
>();
578 MetaData meta
= getInfo(luid
);
580 throw new IOException("Story not found: " + luid
);
583 File infoFile
= getStories(null).get(meta
)[0];
584 File targetFile
= getStories(null).get(meta
)[1];
587 files
.add(targetFile
);
589 String readerExt
= getOutputType(meta
).getDefaultExtension(true);
590 String fileExt
= getOutputType(meta
).getDefaultExtension(false);
592 String path
= targetFile
.getAbsolutePath();
593 if (readerExt
!= null && !readerExt
.equals(fileExt
)) {
594 path
= path
.substring(0, path
.length() - readerExt
.length())
596 File relatedFile
= new File(path
);
598 if (relatedFile
.exists()) {
599 files
.add(relatedFile
);
603 String coverExt
= "." + Instance
.getInstance().getConfig()
604 .getString(Config
.FILE_FORMAT_IMAGE_FORMAT_COVER
).toLowerCase();
605 File coverFile
= new File(path
+ coverExt
);
606 if (!coverFile
.exists()) {
607 coverFile
= new File(
608 path
.substring(0, path
.length() - fileExt
.length())
612 if (coverFile
.exists()) {
613 files
.add(coverFile
);
620 * Fill the list of stories by reading the content of the local directory
621 * {@link LocalLibrary#baseDir}.
623 * Will use a cached list when possible (see
624 * {@link BasicLibrary#invalidateInfo()}).
627 * the optional {@link Progress}
629 * @return the list of stories (for each item, the first {@link File} is the
630 * info file, the second file is the target {@link File})
632 private Map
<MetaData
, File
[]> getStories(Progress pg
) {
636 pg
.setMinMax(0, 100);
639 Map
<MetaData
, File
[]> stories
= this.stories
;
640 if (stories
== null) {
641 stories
= getStoriesDo(pg
);
642 synchronized (lock
) {
643 if (this.stories
== null)
644 this.stories
= stories
;
646 stories
= this.stories
;
656 * Actually do the work of {@link LocalLibrary#getStories(Progress)} (i.e.,
657 * do not retrieve the cache).
660 * the optional {@link Progress}
662 * @return the list of stories (for each item, the first {@link File} is the
663 * info file, the second file is the target {@link File})
665 private synchronized Map
<MetaData
, File
[]> getStoriesDo(Progress pg
) {
669 pg
.setMinMax(0, 100);
672 Map
<MetaData
, File
[]> stories
= new HashMap
<MetaData
, File
[]>();
674 File
[] dirs
= baseDir
.listFiles(new FileFilter() {
676 public boolean accept(File file
) {
677 return file
!= null && file
.isDirectory();
682 Progress pgDirs
= new Progress(0, 100 * dirs
.length
);
683 pg
.addProgress(pgDirs
, 100);
685 for (File dir
: dirs
) {
686 Progress pgFiles
= new Progress();
687 pgDirs
.addProgress(pgFiles
, 100);
688 pgDirs
.setName("Loading from: " + dir
.getName());
690 addToStories(stories
, pgFiles
, dir
);
692 pgFiles
.setName(null);
695 pgDirs
.setName("Loading directories");
703 private void addToStories(Map
<MetaData
, File
[]> stories
, Progress pgFiles
,
705 File
[] infoFilesAndSubdirs
= dir
.listFiles(new FileFilter() {
707 public boolean accept(File file
) {
708 boolean info
= file
!= null && file
.isFile()
709 && file
.getPath().toLowerCase().endsWith(".info");
710 boolean dir
= file
!= null && file
.isDirectory();
711 boolean isExpandedHtml
= new File(file
, "index.html").isFile();
712 return info
|| (dir
&& !isExpandedHtml
);
716 if (pgFiles
!= null) {
717 pgFiles
.setMinMax(0, infoFilesAndSubdirs
.length
);
720 for (File infoFileOrSubdir
: infoFilesAndSubdirs
) {
721 if (infoFileOrSubdir
.isDirectory()) {
722 addToStories(stories
, null, infoFileOrSubdir
);
725 MetaData meta
= InfoReader
.readMeta(infoFileOrSubdir
,
728 int id
= Integer
.parseInt(meta
.getLuid());
733 stories
.put(meta
, new File
[] { infoFileOrSubdir
,
734 getTargetFile(meta
, infoFileOrSubdir
) });
735 } catch (Exception e
) {
737 throw new IOException("Cannot understand the LUID of "
738 + infoFileOrSubdir
+ ": " + meta
.getLuid(), e
);
740 } catch (IOException e
) {
741 // We should not have not-supported files in the
743 Instance
.getInstance().getTraceHandler().error(
744 new IOException("Cannot load file from library: "
745 + infoFileOrSubdir
, e
));
749 if (pgFiles
!= null) {