1 package be
.nikiroo
.fanfix
.library
;
4 import java
.io
.FileFilter
;
5 import java
.io
.FileInputStream
;
6 import java
.io
.IOException
;
7 import java
.io
.InputStream
;
8 import java
.util
.ArrayList
;
9 import java
.util
.HashMap
;
10 import java
.util
.List
;
13 import be
.nikiroo
.fanfix
.Instance
;
14 import be
.nikiroo
.fanfix
.bundles
.Config
;
15 import be
.nikiroo
.fanfix
.data
.MetaData
;
16 import be
.nikiroo
.fanfix
.data
.Story
;
17 import be
.nikiroo
.fanfix
.output
.BasicOutput
;
18 import be
.nikiroo
.fanfix
.output
.BasicOutput
.OutputType
;
19 import be
.nikiroo
.fanfix
.output
.InfoCover
;
20 import be
.nikiroo
.fanfix
.supported
.InfoReader
;
21 import be
.nikiroo
.utils
.IOUtils
;
22 import be
.nikiroo
.utils
.Image
;
23 import be
.nikiroo
.utils
.Progress
;
26 * This {@link BasicLibrary} will store the stories locally on disk.
30 public class LocalLibrary
extends BasicLibrary
{
32 private Map
<MetaData
, File
[]> stories
; // Files: [ infoFile, TargetFile ]
33 private Map
<String
, Image
> sourceCovers
;
36 private OutputType text
;
37 private OutputType image
;
40 * Create a new {@link LocalLibrary} with the given back-end directory.
43 * the directory where to find the {@link Story} objects
45 public LocalLibrary(File baseDir
) {
46 this(baseDir
, Instance
.getConfig().getString(
47 Config
.NON_IMAGES_DOCUMENT_TYPE
), Instance
.getConfig()
48 .getString(Config
.IMAGES_DOCUMENT_TYPE
), false);
52 * Create a new {@link LocalLibrary} with the given back-end directory.
55 * the directory where to find the {@link Story} objects
57 * the {@link OutputType} to use for non-image documents
59 * the {@link OutputType} to use for image documents
60 * @param defaultIsHtml
61 * if the given text or image is invalid, use HTML by default (if
62 * not, it will be INFO_TEXT/CBZ by default)
64 public LocalLibrary(File baseDir
, String text
, String image
,
65 boolean defaultIsHtml
) {
66 this(baseDir
, OutputType
.valueOfAllOkUC(text
,
67 defaultIsHtml ? OutputType
.HTML
: OutputType
.INFO_TEXT
),
68 OutputType
.valueOfAllOkUC(image
,
69 defaultIsHtml ? OutputType
.HTML
: OutputType
.CBZ
));
73 * Create a new {@link LocalLibrary} with the given back-end directory.
76 * the directory where to find the {@link Story} objects
78 * the {@link OutputType} to use for non-image documents
80 * the {@link OutputType} to use for image documents
82 public LocalLibrary(File baseDir
, OutputType text
, OutputType image
) {
83 this.baseDir
= baseDir
;
89 this.sourceCovers
= null;
95 protected List
<MetaData
> getMetas(Progress pg
) {
96 return new ArrayList
<MetaData
>(getStories(pg
).keySet());
100 public File
getFile(String luid
, Progress pg
) {
101 Instance
.getTraceHandler().trace(
102 this.getClass().getSimpleName() + ": get file for " + luid
);
105 String mess
= "no file found for ";
107 MetaData meta
= getInfo(luid
);
108 File
[] files
= getStories(pg
).get(meta
);
110 mess
= "file retrieved for ";
114 Instance
.getTraceHandler().trace(
115 this.getClass().getSimpleName() + ": " + mess
+ luid
+ " ("
116 + meta
.getTitle() + ")");
122 public Image
getCover(String luid
) {
123 MetaData meta
= getInfo(luid
);
125 File
[] files
= getStories(null).get(meta
);
127 File infoFile
= files
[0];
130 meta
= InfoReader
.readMeta(infoFile
, true);
131 return meta
.getCover();
132 } catch (IOException e
) {
133 Instance
.getTraceHandler().error(e
);
142 protected synchronized void updateInfo(MetaData meta
) {
147 protected void deleteInfo(String luid
) {
153 protected synchronized int getNextId() {
154 getStories(null); // make sure lastId is set
159 protected void doDelete(String luid
) throws IOException
{
160 for (File file
: getRelatedFiles(luid
)) {
161 // TODO: throw an IOException if we cannot delete the files?
162 IOUtils
.deltree(file
);
163 file
.getParentFile().delete();
168 protected Story
doSave(Story story
, Progress pg
) throws IOException
{
169 MetaData meta
= story
.getMeta();
171 File expectedTarget
= getExpectedFile(meta
);
172 expectedTarget
.getParentFile().mkdirs();
174 BasicOutput it
= BasicOutput
.getOutput(getOutputType(meta
), true, true);
175 it
.process(story
, expectedTarget
.getPath(), pg
);
181 protected synchronized void saveMeta(MetaData meta
, Progress pg
)
183 File newDir
= getExpectedDir(meta
.getSource());
184 if (!newDir
.exists()) {
188 List
<File
> relatedFiles
= getRelatedFiles(meta
.getLuid());
189 for (File relatedFile
: relatedFiles
) {
190 // TODO: this is not safe at all.
191 // We should copy all the files THEN delete them
192 // Maybe also adding some rollback cleanup if possible
193 if (relatedFile
.getName().endsWith(".info")) {
195 String name
= relatedFile
.getName().replaceFirst(
197 InfoCover
.writeInfo(newDir
, name
, meta
);
198 relatedFile
.delete();
199 relatedFile
.getParentFile().delete();
200 } catch (IOException e
) {
201 Instance
.getTraceHandler().error(e
);
204 relatedFile
.renameTo(new File(newDir
, relatedFile
.getName()));
205 relatedFile
.getParentFile().delete();
213 public Image
getSourceCover(String source
) {
214 if (sourceCovers
== null) {
218 if (!sourceCovers
.containsKey(source
)) {
219 sourceCovers
.put(source
, super.getSourceCover(source
));
222 return sourceCovers
.get(source
);
226 public void setSourceCover(String source
, String luid
) {
227 if (sourceCovers
== null) {
231 sourceCovers
.put(source
, getCover(luid
));
232 File cover
= new File(getExpectedDir(source
), ".cover");
234 Instance
.getCache().saveAsImage(sourceCovers
.get(source
), cover
,
236 } catch (IOException e
) {
237 Instance
.getTraceHandler().error(e
);
238 sourceCovers
.remove(source
);
243 public void imprt(BasicLibrary other
, String luid
, Progress pg
)
249 // Check if we can simply copy the files instead of the whole process
250 if (other
instanceof LocalLibrary
) {
251 LocalLibrary otherLocalLibrary
= (LocalLibrary
) other
;
253 MetaData meta
= otherLocalLibrary
.getInfo(luid
);
254 String expectedType
= ""
255 + (meta
!= null && meta
.isImageDocument() ? image
: text
);
256 if (meta
!= null && meta
.getType().equals(expectedType
)) {
257 File from
= otherLocalLibrary
.getExpectedDir(meta
.getSource());
258 File to
= this.getExpectedDir(meta
.getSource());
259 List
<File
> sources
= otherLocalLibrary
.getRelatedFiles(luid
);
260 if (!sources
.isEmpty()) {
261 pg
.setMinMax(0, sources
.size());
264 for (File source
: sources
) {
265 File target
= new File(source
.getAbsolutePath().replace(
266 from
.getAbsolutePath(), to
.getAbsolutePath()));
267 if (!source
.equals(target
)) {
268 target
.getParentFile().mkdirs();
269 InputStream in
= null;
271 in
= new FileInputStream(source
);
272 IOUtils
.write(in
, target
);
273 } catch (IOException e
) {
277 } catch (Exception ee
) {
295 super.imprt(other
, luid
, pg
);
299 * Return the {@link OutputType} for this {@link Story}.
302 * the {@link Story} {@link MetaData}
306 private OutputType
getOutputType(MetaData meta
) {
307 if (meta
!= null && meta
.isImageDocument()) {
315 * Get the target {@link File} related to the given <tt>.info</tt>
316 * {@link File} and {@link MetaData}.
321 * the <tt>.info</tt> {@link File}
323 * @return the target {@link File}
325 private File
getTargetFile(MetaData meta
, File infoFile
) {
326 // Replace .info with whatever is needed:
327 String path
= infoFile
.getPath();
328 path
= path
.substring(0, path
.length() - ".info".length());
329 String newExt
= getOutputType(meta
).getDefaultExtension(true);
331 return new File(path
+ newExt
);
335 * The target (full path) where the {@link Story} related to this
336 * {@link MetaData} should be located on disk for a new {@link Story}.
339 * the {@link Story} {@link MetaData}
343 private File
getExpectedFile(MetaData key
) {
344 String title
= key
.getTitle();
348 title
= title
.replaceAll("[^a-zA-Z0-9._+-]", "_");
349 return new File(getExpectedDir(key
.getSource()), key
.getLuid() + "_"
354 * The directory (full path) where the new {@link Story} related to this
355 * {@link MetaData} should be located on disk.
360 * @return the target directory
362 private File
getExpectedDir(String source
) {
363 String sanitizedSource
= source
.replaceAll("[^a-zA-Z0-9._+-]", "_");
364 return new File(baseDir
, sanitizedSource
);
368 * Return the list of files/directories on disk for this {@link Story}.
370 * If the {@link Story} is not found, and empty list is returned.
373 * the {@link Story} LUID
375 * @return the list of {@link File}s
377 * @throws IOException
378 * if the {@link Story} was not found
380 private List
<File
> getRelatedFiles(String luid
) throws IOException
{
381 List
<File
> files
= new ArrayList
<File
>();
383 MetaData meta
= getInfo(luid
);
385 throw new IOException("Story not found: " + luid
);
388 File infoFile
= getStories(null).get(meta
)[0];
389 File targetFile
= getStories(null).get(meta
)[1];
392 files
.add(targetFile
);
394 String readerExt
= getOutputType(meta
).getDefaultExtension(true);
395 String fileExt
= getOutputType(meta
).getDefaultExtension(false);
397 String path
= targetFile
.getAbsolutePath();
398 if (readerExt
!= null && !readerExt
.equals(fileExt
)) {
399 path
= path
.substring(0, path
.length() - readerExt
.length())
401 File relatedFile
= new File(path
);
403 if (relatedFile
.exists()) {
404 files
.add(relatedFile
);
408 String coverExt
= "."
409 + Instance
.getConfig().getString(Config
.IMAGE_FORMAT_COVER
)
411 File coverFile
= new File(path
+ coverExt
);
412 if (!coverFile
.exists()) {
413 coverFile
= new File(path
.substring(0,
414 path
.length() - fileExt
.length())
418 if (coverFile
.exists()) {
419 files
.add(coverFile
);
426 * Fill the list of stories by reading the content of the local directory
427 * {@link LocalLibrary#baseDir}.
429 * Will use a cached list when possible (see
430 * {@link BasicLibrary#deleteInfo()}).
433 * the optional {@link Progress}
435 * @return the list of stories (for each item, the first {@link File} is the
436 * info file, the second file is the target {@link File})
438 private synchronized Map
<MetaData
, File
[]> getStories(Progress pg
) {
442 pg
.setMinMax(0, 100);
445 if (stories
== null) {
446 stories
= new HashMap
<MetaData
, File
[]>();
447 sourceCovers
= new HashMap
<String
, Image
>();
451 File
[] dirs
= baseDir
.listFiles(new FileFilter() {
453 public boolean accept(File file
) {
454 return file
!= null && file
.isDirectory();
459 Progress pgDirs
= new Progress(0, 100 * dirs
.length
);
460 pg
.addProgress(pgDirs
, 100);
462 for (File dir
: dirs
) {
463 File
[] infoFiles
= dir
.listFiles(new FileFilter() {
465 public boolean accept(File file
) {
467 && file
.getPath().toLowerCase()
472 Progress pgFiles
= new Progress(0, infoFiles
.length
);
473 pgDirs
.addProgress(pgFiles
, 100);
474 pgDirs
.setName("Loading from: " + dir
.getName());
476 String source
= null;
477 for (File infoFile
: infoFiles
) {
478 pgFiles
.setName(infoFile
.getName());
480 MetaData meta
= InfoReader
481 .readMeta(infoFile
, false);
482 source
= meta
.getSource();
484 int id
= Integer
.parseInt(meta
.getLuid());
489 stories
.put(meta
, new File
[] { infoFile
,
490 getTargetFile(meta
, infoFile
) });
491 } catch (Exception e
) {
493 throw new IOException(
494 "Cannot understand the LUID of "
496 + meta
.getLuid(), e
);
498 } catch (IOException e
) {
499 // We should not have not-supported files in the
501 Instance
.getTraceHandler().error(
503 "Cannot load file from library: "
509 File cover
= new File(dir
, ".cover.png");
510 if (cover
.exists()) {
512 InputStream in
= new FileInputStream(cover
);
514 sourceCovers
.put(source
, new Image(in
));
518 } catch (IOException e
) {
519 Instance
.getTraceHandler().error(e
);
523 pgFiles
.setName(null);
526 pgDirs
.setName("Loading directories");
535 * Fix the source cover to the given story cover.
538 * the source to change
542 void setSourceCover(String source
, Image coverImage
) {
543 if (sourceCovers
== null) {
547 sourceCovers
.put(source
, coverImage
);
548 File cover
= new File(getExpectedDir(source
), ".cover");
550 Instance
.getCache().saveAsImage(sourceCovers
.get(source
), cover
,
552 } catch (IOException e
) {
553 Instance
.getTraceHandler().error(e
);
554 sourceCovers
.remove(source
);