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
.data
.MetaData
;
17 import be
.nikiroo
.fanfix
.data
.Story
;
18 import be
.nikiroo
.fanfix
.output
.BasicOutput
;
19 import be
.nikiroo
.fanfix
.output
.BasicOutput
.OutputType
;
20 import be
.nikiroo
.fanfix
.output
.InfoCover
;
21 import be
.nikiroo
.fanfix
.supported
.InfoReader
;
22 import be
.nikiroo
.utils
.IOUtils
;
23 import be
.nikiroo
.utils
.Image
;
24 import be
.nikiroo
.utils
.Progress
;
25 import be
.nikiroo
.utils
.StringUtils
;
28 * This {@link BasicLibrary} will store the stories locally on disk.
32 public class LocalLibrary
extends BasicLibrary
{
34 private Map
<MetaData
, File
[]> stories
; // Files: [ infoFile, TargetFile ]
35 private Map
<String
, Image
> sourceCovers
;
36 private Map
<String
, Image
> authorCovers
;
39 private OutputType text
;
40 private OutputType image
;
43 * Create a new {@link LocalLibrary} with the given back-end directory.
46 * the directory where to find the {@link Story} objects
48 public LocalLibrary(File baseDir
) {
49 this(baseDir
, Instance
.getConfig().getString(
50 Config
.NON_IMAGES_DOCUMENT_TYPE
), Instance
.getConfig()
51 .getString(Config
.IMAGES_DOCUMENT_TYPE
), false);
55 * Create a new {@link LocalLibrary} with the given back-end directory.
58 * the directory where to find the {@link Story} objects
60 * the {@link OutputType} to use for non-image documents
62 * the {@link OutputType} to use for image documents
63 * @param defaultIsHtml
64 * if the given text or image is invalid, use HTML by default (if
65 * not, it will be INFO_TEXT/CBZ by default)
67 public LocalLibrary(File baseDir
, String text
, String image
,
68 boolean defaultIsHtml
) {
69 this(baseDir
, OutputType
.valueOfAllOkUC(text
,
70 defaultIsHtml ? OutputType
.HTML
: OutputType
.INFO_TEXT
),
71 OutputType
.valueOfAllOkUC(image
,
72 defaultIsHtml ? OutputType
.HTML
: OutputType
.CBZ
));
76 * Create a new {@link LocalLibrary} with the given back-end directory.
79 * the directory where to find the {@link Story} objects
81 * the {@link OutputType} to use for non-image documents
83 * the {@link OutputType} to use for image documents
85 public LocalLibrary(File baseDir
, OutputType text
, OutputType image
) {
86 this.baseDir
= baseDir
;
92 this.sourceCovers
= null;
98 protected List
<MetaData
> getMetas(Progress pg
) {
99 return new ArrayList
<MetaData
>(getStories(pg
).keySet());
103 public File
getFile(String luid
, Progress pg
) {
104 Instance
.getTraceHandler().trace(
105 this.getClass().getSimpleName() + ": get file for " + luid
);
108 String mess
= "no file found for ";
110 MetaData meta
= getInfo(luid
);
111 File
[] files
= getStories(pg
).get(meta
);
113 mess
= "file retrieved for ";
117 Instance
.getTraceHandler().trace(
118 this.getClass().getSimpleName() + ": " + mess
+ luid
+ " ("
119 + meta
.getTitle() + ")");
125 public Image
getCover(String luid
) {
126 MetaData meta
= getInfo(luid
);
128 if (meta
.getCover() != null) {
129 return meta
.getCover();
132 File
[] files
= getStories(null).get(meta
);
134 File infoFile
= files
[0];
137 meta
= InfoReader
.readMeta(infoFile
, true);
138 return meta
.getCover();
139 } catch (IOException e
) {
140 Instance
.getTraceHandler().error(e
);
149 protected synchronized void updateInfo(MetaData meta
) {
154 protected void invalidateInfo(String luid
) {
160 protected synchronized int getNextId() {
161 getStories(null); // make sure lastId is set
166 protected void doDelete(String luid
) throws IOException
{
167 for (File file
: getRelatedFiles(luid
)) {
168 // TODO: throw an IOException if we cannot delete the files?
169 IOUtils
.deltree(file
);
170 file
.getParentFile().delete();
175 protected Story
doSave(Story story
, Progress pg
) throws IOException
{
176 MetaData meta
= story
.getMeta();
178 File expectedTarget
= getExpectedFile(meta
);
179 expectedTarget
.getParentFile().mkdirs();
181 BasicOutput it
= BasicOutput
.getOutput(getOutputType(meta
), true, true);
182 it
.process(story
, expectedTarget
.getPath(), pg
);
188 protected synchronized void saveMeta(MetaData meta
, Progress pg
)
190 File newDir
= getExpectedDir(meta
.getSource());
191 if (!newDir
.exists()) {
195 List
<File
> relatedFiles
= getRelatedFiles(meta
.getLuid());
196 for (File relatedFile
: relatedFiles
) {
197 // TODO: this is not safe at all.
198 // We should copy all the files THEN delete them
199 // Maybe also adding some rollback cleanup if possible
200 if (relatedFile
.getName().endsWith(".info")) {
202 String name
= relatedFile
.getName().replaceFirst(
204 relatedFile
.delete();
205 InfoCover
.writeInfo(newDir
, name
, meta
);
206 relatedFile
.getParentFile().delete();
207 } catch (IOException e
) {
208 Instance
.getTraceHandler().error(e
);
211 relatedFile
.renameTo(new File(newDir
, relatedFile
.getName()));
212 relatedFile
.getParentFile().delete();
220 public synchronized Image
getCustomSourceCover(String source
) {
221 if (sourceCovers
== null) {
222 sourceCovers
= new HashMap
<String
, Image
>();
225 Image img
= sourceCovers
.get(source
);
230 File coverDir
= getExpectedDir(source
);
231 if (coverDir
.isDirectory()) {
232 File cover
= new File(coverDir
, ".cover.png");
233 if (cover
.exists()) {
236 in
= new FileInputStream(cover
);
238 sourceCovers
.put(source
, new Image(in
));
242 } catch (FileNotFoundException e
) {
244 } catch (IOException e
) {
245 Instance
.getTraceHandler().error(
247 "Cannot load the existing custom source cover: "
253 return sourceCovers
.get(source
);
257 public synchronized Image
getCustomAuthorCover(String author
) {
258 if (authorCovers
== null) {
259 authorCovers
= new HashMap
<String
, Image
>();
262 Image img
= authorCovers
.get(author
);
267 File cover
= getAuthorCoverFile(author
);
268 if (cover
.exists()) {
271 in
= new FileInputStream(cover
);
273 authorCovers
.put(author
, new Image(in
));
277 } catch (FileNotFoundException e
) {
279 } catch (IOException e
) {
280 Instance
.getTraceHandler().error(
282 "Cannot load the existing custom author cover: "
287 return authorCovers
.get(author
);
291 public void setSourceCover(String source
, String luid
) {
292 setSourceCover(source
, getCover(luid
));
296 public void setAuthorCover(String author
, String luid
) {
297 setAuthorCover(author
, getCover(luid
));
301 * Set the source cover to the given story cover.
304 * the source to change
308 synchronized void setSourceCover(String source
, Image coverImage
) {
309 File dir
= getExpectedDir(source
);
311 File cover
= new File(dir
, ".cover");
313 Instance
.getCache().saveAsImage(coverImage
, cover
, true);
314 if (sourceCovers
!= null) {
315 sourceCovers
.put(source
, coverImage
);
317 } catch (IOException e
) {
318 Instance
.getTraceHandler().error(e
);
323 * Set the author cover to the given story cover.
326 * the author to change
330 synchronized void setAuthorCover(String author
, Image coverImage
) {
331 File cover
= getAuthorCoverFile(author
);
332 cover
.getParentFile().mkdirs();
334 Instance
.getCache().saveAsImage(coverImage
, cover
, true);
335 if (authorCovers
!= null) {
336 authorCovers
.put(author
, coverImage
);
338 } catch (IOException e
) {
339 Instance
.getTraceHandler().error(e
);
344 public void imprt(BasicLibrary other
, String luid
, Progress pg
)
350 // Check if we can simply copy the files instead of the whole process
351 if (other
instanceof LocalLibrary
) {
352 LocalLibrary otherLocalLibrary
= (LocalLibrary
) other
;
354 MetaData meta
= otherLocalLibrary
.getInfo(luid
);
355 String expectedType
= ""
356 + (meta
!= null && meta
.isImageDocument() ? image
: text
);
357 if (meta
!= null && meta
.getType().equals(expectedType
)) {
358 File from
= otherLocalLibrary
.getExpectedDir(meta
.getSource());
359 File to
= this.getExpectedDir(meta
.getSource());
360 List
<File
> relatedFiles
= otherLocalLibrary
361 .getRelatedFiles(luid
);
362 if (!relatedFiles
.isEmpty()) {
363 pg
.setMinMax(0, relatedFiles
.size());
366 for (File relatedFile
: relatedFiles
) {
367 File target
= new File(relatedFile
.getAbsolutePath()
368 .replace(from
.getAbsolutePath(),
369 to
.getAbsolutePath()));
370 if (!relatedFile
.equals(target
)) {
371 target
.getParentFile().mkdirs();
372 InputStream in
= null;
374 in
= new FileInputStream(relatedFile
);
375 IOUtils
.write(in
, target
);
376 } catch (IOException e
) {
380 } catch (Exception ee
) {
398 super.imprt(other
, luid
, pg
);
402 * Return the {@link OutputType} for this {@link Story}.
405 * the {@link Story} {@link MetaData}
409 private OutputType
getOutputType(MetaData meta
) {
410 if (meta
!= null && meta
.isImageDocument()) {
418 * Return the default {@link OutputType} for this kind of {@link Story}.
420 * @param imageDocument
421 * TRUE for images document, FALSE for text documents
425 public String
getOutputType(boolean imageDocument
) {
427 return image
.toString();
430 return text
.toString();
434 * Get the target {@link File} related to the given <tt>.info</tt>
435 * {@link File} and {@link MetaData}.
440 * the <tt>.info</tt> {@link File}
442 * @return the target {@link File}
444 private File
getTargetFile(MetaData meta
, File infoFile
) {
445 // Replace .info with whatever is needed:
446 String path
= infoFile
.getPath();
447 path
= path
.substring(0, path
.length() - ".info".length());
448 String newExt
= getOutputType(meta
).getDefaultExtension(true);
450 return new File(path
+ newExt
);
454 * The target (full path) where the {@link Story} related to this
455 * {@link MetaData} should be located on disk for a new {@link Story}.
458 * the {@link Story} {@link MetaData}
462 private File
getExpectedFile(MetaData key
) {
463 String title
= key
.getTitle();
467 title
= title
.replaceAll("[^a-zA-Z0-9._+-]", "_");
468 if (title
.length() > 40) {
469 title
= title
.substring(0, 40);
471 return new File(getExpectedDir(key
.getSource()), key
.getLuid() + "_"
476 * The directory (full path) where the new {@link Story} related to this
477 * {@link MetaData} should be located on disk.
482 * @return the target directory
484 private File
getExpectedDir(String source
) {
485 String sanitizedSource
= source
.replaceAll("[^a-zA-Z0-9._+/-]", "_");
487 while (sanitizedSource
.startsWith("/")
488 || sanitizedSource
.startsWith("_")) {
489 if (sanitizedSource
.length() > 1) {
490 sanitizedSource
= sanitizedSource
.substring(1);
492 sanitizedSource
= "";
496 sanitizedSource
= sanitizedSource
.replace("/", File
.separator
);
498 if (sanitizedSource
.isEmpty()) {
499 sanitizedSource
= "_EMPTY";
502 return new File(baseDir
, sanitizedSource
);
506 * Return the full path to the file to use for the custom cover of this
509 * One or more of the parent directories <b>MAY</b> not exist.
514 * @return the custom cover file
516 private File
getAuthorCoverFile(String author
) {
517 File aDir
= new File(baseDir
, "_AUTHORS");
518 String hash
= StringUtils
.getMd5Hash(author
);
519 String ext
= Instance
.getConfig().getString(Config
.IMAGE_FORMAT_COVER
);
520 return new File(aDir
, hash
+ "." + ext
.toLowerCase());
524 * Return the list of files/directories on disk for this {@link Story}.
526 * If the {@link Story} is not found, and empty list is returned.
529 * the {@link Story} LUID
531 * @return the list of {@link File}s
533 * @throws IOException
534 * if the {@link Story} was not found
536 private List
<File
> getRelatedFiles(String luid
) throws IOException
{
537 List
<File
> files
= new ArrayList
<File
>();
539 MetaData meta
= getInfo(luid
);
541 throw new IOException("Story not found: " + luid
);
544 File infoFile
= getStories(null).get(meta
)[0];
545 File targetFile
= getStories(null).get(meta
)[1];
548 files
.add(targetFile
);
550 String readerExt
= getOutputType(meta
).getDefaultExtension(true);
551 String fileExt
= getOutputType(meta
).getDefaultExtension(false);
553 String path
= targetFile
.getAbsolutePath();
554 if (readerExt
!= null && !readerExt
.equals(fileExt
)) {
555 path
= path
.substring(0, path
.length() - readerExt
.length())
557 File relatedFile
= new File(path
);
559 if (relatedFile
.exists()) {
560 files
.add(relatedFile
);
564 String coverExt
= "."
565 + Instance
.getConfig().getString(Config
.IMAGE_FORMAT_COVER
)
567 File coverFile
= new File(path
+ coverExt
);
568 if (!coverFile
.exists()) {
569 coverFile
= new File(path
.substring(0,
570 path
.length() - fileExt
.length())
574 if (coverFile
.exists()) {
575 files
.add(coverFile
);
582 * Fill the list of stories by reading the content of the local directory
583 * {@link LocalLibrary#baseDir}.
585 * Will use a cached list when possible (see
586 * {@link BasicLibrary#invalidateInfo()}).
589 * the optional {@link Progress}
591 * @return the list of stories (for each item, the first {@link File} is the
592 * info file, the second file is the target {@link File})
594 private synchronized Map
<MetaData
, File
[]> getStories(Progress pg
) {
598 pg
.setMinMax(0, 100);
601 if (stories
== null) {
602 stories
= new HashMap
<MetaData
, File
[]>();
606 File
[] dirs
= baseDir
.listFiles(new FileFilter() {
608 public boolean accept(File file
) {
609 return file
!= null && file
.isDirectory();
614 Progress pgDirs
= new Progress(0, 100 * dirs
.length
);
615 pg
.addProgress(pgDirs
, 100);
617 for (File dir
: dirs
) {
618 Progress pgFiles
= new Progress();
619 pgDirs
.addProgress(pgFiles
, 100);
620 pgDirs
.setName("Loading from: " + dir
.getName());
622 addToStories(pgFiles
, dir
);
624 pgFiles
.setName(null);
627 pgDirs
.setName("Loading directories");
635 private void addToStories(Progress pgFiles
, File dir
) {
636 File
[] infoFilesAndSubdirs
= dir
.listFiles(new FileFilter() {
638 public boolean accept(File file
) {
639 boolean info
= file
!= null && file
.isFile()
640 && file
.getPath().toLowerCase().endsWith(".info");
641 boolean dir
= file
!= null && file
.isDirectory();
642 boolean isExpandedHtml
= new File(file
, "index.html").isFile();
643 return info
|| (dir
&& !isExpandedHtml
);
647 if (pgFiles
!= null) {
648 pgFiles
.setMinMax(0, infoFilesAndSubdirs
.length
);
651 for (File infoFileOrSubdir
: infoFilesAndSubdirs
) {
652 if (pgFiles
!= null) {
653 pgFiles
.setName(infoFileOrSubdir
.getName());
656 if (infoFileOrSubdir
.isDirectory()) {
657 addToStories(null, infoFileOrSubdir
);
660 MetaData meta
= InfoReader
661 .readMeta(infoFileOrSubdir
, false);
663 int id
= Integer
.parseInt(meta
.getLuid());
668 stories
.put(meta
, new File
[] { infoFileOrSubdir
,
669 getTargetFile(meta
, infoFileOrSubdir
) });
670 } catch (Exception e
) {
672 throw new IOException("Cannot understand the LUID of "
673 + infoFileOrSubdir
+ ": " + meta
.getLuid(), e
);
675 } catch (IOException e
) {
676 // We should not have not-supported files in the
678 Instance
.getTraceHandler().error(
679 new IOException("Cannot load file from library: "
680 + infoFileOrSubdir
, e
));
684 if (pgFiles
!= null) {