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
;
27 * This {@link BasicLibrary} will store the stories locally on disk.
31 public class LocalLibrary
extends BasicLibrary
{
33 private Map
<MetaData
, File
[]> stories
; // Files: [ infoFile, TargetFile ]
34 private Map
<String
, Image
> sourceCovers
;
37 private OutputType text
;
38 private OutputType image
;
41 * Create a new {@link LocalLibrary} with the given back-end directory.
44 * the directory where to find the {@link Story} objects
46 public LocalLibrary(File baseDir
) {
47 this(baseDir
, Instance
.getConfig().getString(
48 Config
.NON_IMAGES_DOCUMENT_TYPE
), Instance
.getConfig()
49 .getString(Config
.IMAGES_DOCUMENT_TYPE
), false);
53 * Create a new {@link LocalLibrary} with the given back-end directory.
56 * the directory where to find the {@link Story} objects
58 * the {@link OutputType} to use for non-image documents
60 * the {@link OutputType} to use for image documents
61 * @param defaultIsHtml
62 * if the given text or image is invalid, use HTML by default (if
63 * not, it will be INFO_TEXT/CBZ by default)
65 public LocalLibrary(File baseDir
, String text
, String image
,
66 boolean defaultIsHtml
) {
67 this(baseDir
, OutputType
.valueOfAllOkUC(text
,
68 defaultIsHtml ? OutputType
.HTML
: OutputType
.INFO_TEXT
),
69 OutputType
.valueOfAllOkUC(image
,
70 defaultIsHtml ? OutputType
.HTML
: OutputType
.CBZ
));
74 * Create a new {@link LocalLibrary} with the given back-end directory.
77 * the directory where to find the {@link Story} objects
79 * the {@link OutputType} to use for non-image documents
81 * the {@link OutputType} to use for image documents
83 public LocalLibrary(File baseDir
, OutputType text
, OutputType image
) {
84 this.baseDir
= baseDir
;
90 this.sourceCovers
= null;
96 protected List
<MetaData
> getMetas(Progress pg
) {
97 return new ArrayList
<MetaData
>(getStories(pg
).keySet());
101 public File
getFile(String luid
, Progress pg
) {
102 Instance
.getTraceHandler().trace(
103 this.getClass().getSimpleName() + ": get file for " + luid
);
106 String mess
= "no file found for ";
108 MetaData meta
= getInfo(luid
);
109 File
[] files
= getStories(pg
).get(meta
);
111 mess
= "file retrieved for ";
115 Instance
.getTraceHandler().trace(
116 this.getClass().getSimpleName() + ": " + mess
+ luid
+ " ("
117 + meta
.getTitle() + ")");
123 public Image
getCover(String luid
) {
124 MetaData meta
= getInfo(luid
);
126 File
[] files
= getStories(null).get(meta
);
128 File infoFile
= files
[0];
131 meta
= InfoReader
.readMeta(infoFile
, true);
132 return meta
.getCover();
133 } catch (IOException e
) {
134 Instance
.getTraceHandler().error(e
);
143 protected synchronized void updateInfo(MetaData meta
) {
148 protected void deleteInfo(String luid
) {
154 protected synchronized int getNextId() {
155 getStories(null); // make sure lastId is set
160 protected void doDelete(String luid
) throws IOException
{
161 for (File file
: getRelatedFiles(luid
)) {
162 // TODO: throw an IOException if we cannot delete the files?
163 IOUtils
.deltree(file
);
164 file
.getParentFile().delete();
169 protected Story
doSave(Story story
, Progress pg
) throws IOException
{
170 MetaData meta
= story
.getMeta();
172 File expectedTarget
= getExpectedFile(meta
);
173 expectedTarget
.getParentFile().mkdirs();
175 BasicOutput it
= BasicOutput
.getOutput(getOutputType(meta
), true, true);
176 it
.process(story
, expectedTarget
.getPath(), pg
);
182 protected synchronized void saveMeta(MetaData meta
, Progress pg
)
184 File newDir
= getExpectedDir(meta
.getSource());
185 if (!newDir
.exists()) {
189 List
<File
> relatedFiles
= getRelatedFiles(meta
.getLuid());
190 for (File relatedFile
: relatedFiles
) {
191 // TODO: this is not safe at all.
192 // We should copy all the files THEN delete them
193 // Maybe also adding some rollback cleanup if possible
194 if (relatedFile
.getName().endsWith(".info")) {
196 String name
= relatedFile
.getName().replaceFirst(
198 InfoCover
.writeInfo(newDir
, name
, meta
);
199 relatedFile
.delete();
200 relatedFile
.getParentFile().delete();
201 } catch (IOException e
) {
202 Instance
.getTraceHandler().error(e
);
205 relatedFile
.renameTo(new File(newDir
, relatedFile
.getName()));
206 relatedFile
.getParentFile().delete();
214 public synchronized Image
getCustomSourceCover(String source
) {
215 if (sourceCovers
== null) {
216 sourceCovers
= new HashMap
<String
, Image
>();
219 Image img
= sourceCovers
.get(source
);
224 File coverDir
= new File(baseDir
, source
);
225 if (coverDir
.isDirectory()) {
226 File cover
= new File(coverDir
, ".cover.png");
229 in
= new FileInputStream(cover
);
231 sourceCovers
.put(source
, new Image(in
));
235 } catch (FileNotFoundException e
) {
237 } catch (IOException e
) {
242 return sourceCovers
.get(source
);
246 public void setSourceCover(String source
, String luid
) {
247 setSourceCover(source
, getCover(luid
));
251 * Fix the source cover to the given story cover.
254 * the source to change
258 synchronized void setSourceCover(String source
, Image coverImage
) {
259 File cover
= new File(getExpectedDir(source
), ".cover");
261 Instance
.getCache().saveAsImage(coverImage
, cover
, true);
262 if (sourceCovers
!= null) {
263 sourceCovers
.put(source
, coverImage
);
265 } catch (IOException e
) {
266 Instance
.getTraceHandler().error(e
);
271 public void imprt(BasicLibrary other
, String luid
, Progress pg
)
277 // Check if we can simply copy the files instead of the whole process
278 if (other
instanceof LocalLibrary
) {
279 LocalLibrary otherLocalLibrary
= (LocalLibrary
) other
;
281 MetaData meta
= otherLocalLibrary
.getInfo(luid
);
282 String expectedType
= ""
283 + (meta
!= null && meta
.isImageDocument() ? image
: text
);
284 if (meta
!= null && meta
.getType().equals(expectedType
)) {
285 File from
= otherLocalLibrary
.getExpectedDir(meta
.getSource());
286 File to
= this.getExpectedDir(meta
.getSource());
287 List
<File
> sources
= otherLocalLibrary
.getRelatedFiles(luid
);
288 if (!sources
.isEmpty()) {
289 pg
.setMinMax(0, sources
.size());
292 for (File source
: sources
) {
293 File target
= new File(source
.getAbsolutePath().replace(
294 from
.getAbsolutePath(), to
.getAbsolutePath()));
295 if (!source
.equals(target
)) {
296 target
.getParentFile().mkdirs();
297 InputStream in
= null;
299 in
= new FileInputStream(source
);
300 IOUtils
.write(in
, target
);
301 } catch (IOException e
) {
305 } catch (Exception ee
) {
323 super.imprt(other
, luid
, pg
);
327 * Return the {@link OutputType} for this {@link Story}.
330 * the {@link Story} {@link MetaData}
334 private OutputType
getOutputType(MetaData meta
) {
335 if (meta
!= null && meta
.isImageDocument()) {
343 * Get the target {@link File} related to the given <tt>.info</tt>
344 * {@link File} and {@link MetaData}.
349 * the <tt>.info</tt> {@link File}
351 * @return the target {@link File}
353 private File
getTargetFile(MetaData meta
, File infoFile
) {
354 // Replace .info with whatever is needed:
355 String path
= infoFile
.getPath();
356 path
= path
.substring(0, path
.length() - ".info".length());
357 String newExt
= getOutputType(meta
).getDefaultExtension(true);
359 return new File(path
+ newExt
);
363 * The target (full path) where the {@link Story} related to this
364 * {@link MetaData} should be located on disk for a new {@link Story}.
367 * the {@link Story} {@link MetaData}
371 private File
getExpectedFile(MetaData key
) {
372 String title
= key
.getTitle();
376 title
= title
.replaceAll("[^a-zA-Z0-9._+-]", "_");
377 return new File(getExpectedDir(key
.getSource()), key
.getLuid() + "_"
382 * The directory (full path) where the new {@link Story} related to this
383 * {@link MetaData} should be located on disk.
388 * @return the target directory
390 private File
getExpectedDir(String source
) {
391 String sanitizedSource
= source
.replaceAll("[^a-zA-Z0-9._+-]", "_");
392 return new File(baseDir
, sanitizedSource
);
396 * Return the list of files/directories on disk for this {@link Story}.
398 * If the {@link Story} is not found, and empty list is returned.
401 * the {@link Story} LUID
403 * @return the list of {@link File}s
405 * @throws IOException
406 * if the {@link Story} was not found
408 private List
<File
> getRelatedFiles(String luid
) throws IOException
{
409 List
<File
> files
= new ArrayList
<File
>();
411 MetaData meta
= getInfo(luid
);
413 throw new IOException("Story not found: " + luid
);
416 File infoFile
= getStories(null).get(meta
)[0];
417 File targetFile
= getStories(null).get(meta
)[1];
420 files
.add(targetFile
);
422 String readerExt
= getOutputType(meta
).getDefaultExtension(true);
423 String fileExt
= getOutputType(meta
).getDefaultExtension(false);
425 String path
= targetFile
.getAbsolutePath();
426 if (readerExt
!= null && !readerExt
.equals(fileExt
)) {
427 path
= path
.substring(0, path
.length() - readerExt
.length())
429 File relatedFile
= new File(path
);
431 if (relatedFile
.exists()) {
432 files
.add(relatedFile
);
436 String coverExt
= "."
437 + Instance
.getConfig().getString(Config
.IMAGE_FORMAT_COVER
)
439 File coverFile
= new File(path
+ coverExt
);
440 if (!coverFile
.exists()) {
441 coverFile
= new File(path
.substring(0,
442 path
.length() - fileExt
.length())
446 if (coverFile
.exists()) {
447 files
.add(coverFile
);
454 * Fill the list of stories by reading the content of the local directory
455 * {@link LocalLibrary#baseDir}.
457 * Will use a cached list when possible (see
458 * {@link BasicLibrary#deleteInfo()}).
461 * the optional {@link Progress}
463 * @return the list of stories (for each item, the first {@link File} is the
464 * info file, the second file is the target {@link File})
466 private synchronized Map
<MetaData
, File
[]> getStories(Progress pg
) {
470 pg
.setMinMax(0, 100);
473 if (stories
== null) {
474 stories
= new HashMap
<MetaData
, File
[]>();
478 File
[] dirs
= baseDir
.listFiles(new FileFilter() {
480 public boolean accept(File file
) {
481 return file
!= null && file
.isDirectory();
486 Progress pgDirs
= new Progress(0, 100 * dirs
.length
);
487 pg
.addProgress(pgDirs
, 100);
489 for (File dir
: dirs
) {
490 File
[] infoFiles
= dir
.listFiles(new FileFilter() {
492 public boolean accept(File file
) {
494 && file
.getPath().toLowerCase()
499 Progress pgFiles
= new Progress(0, infoFiles
.length
);
500 pgDirs
.addProgress(pgFiles
, 100);
501 pgDirs
.setName("Loading from: " + dir
.getName());
503 for (File infoFile
: infoFiles
) {
504 pgFiles
.setName(infoFile
.getName());
506 MetaData meta
= InfoReader
507 .readMeta(infoFile
, false);
509 int id
= Integer
.parseInt(meta
.getLuid());
514 stories
.put(meta
, new File
[] { infoFile
,
515 getTargetFile(meta
, infoFile
) });
516 } catch (Exception e
) {
518 throw new IOException(
519 "Cannot understand the LUID of "
521 + meta
.getLuid(), e
);
523 } catch (IOException e
) {
524 // We should not have not-supported files in the
526 Instance
.getTraceHandler().error(
528 "Cannot load file from library: "
534 pgFiles
.setName(null);
537 pgDirs
.setName("Loading directories");