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 File
[] files
= getStories(pg
).get(getInfo(luid
));
110 public Image
getCover(String luid
) {
111 MetaData meta
= getInfo(luid
);
113 File
[] files
= getStories(null).get(meta
);
115 File infoFile
= files
[0];
118 meta
= InfoReader
.readMeta(infoFile
, true);
119 return meta
.getCover();
120 } catch (IOException e
) {
121 Instance
.getTraceHandler().error(e
);
130 protected synchronized void updateInfo(MetaData meta
) {
135 protected void deleteInfo(String luid
) {
141 protected synchronized int getNextId() {
142 getStories(null); // make sure lastId is set
147 protected void doDelete(String luid
) throws IOException
{
148 for (File file
: getRelatedFiles(luid
)) {
149 // TODO: throw an IOException if we cannot delete the files?
150 IOUtils
.deltree(file
);
151 file
.getParentFile().delete();
156 protected Story
doSave(Story story
, Progress pg
) throws IOException
{
157 MetaData meta
= story
.getMeta();
159 File expectedTarget
= getExpectedFile(meta
);
160 expectedTarget
.getParentFile().mkdirs();
162 BasicOutput it
= BasicOutput
.getOutput(getOutputType(meta
), true, true);
163 it
.process(story
, expectedTarget
.getPath(), pg
);
169 protected synchronized void saveMeta(MetaData meta
, Progress pg
)
171 File newDir
= getExpectedDir(meta
.getSource());
172 if (!newDir
.exists()) {
176 List
<File
> relatedFiles
= getRelatedFiles(meta
.getLuid());
177 for (File relatedFile
: relatedFiles
) {
178 // TODO: this is not safe at all.
179 // We should copy all the files THEN delete them
180 // Maybe also adding some rollback cleanup if possible
181 if (relatedFile
.getName().endsWith(".info")) {
183 String name
= relatedFile
.getName().replaceFirst(
185 InfoCover
.writeInfo(newDir
, name
, meta
);
186 relatedFile
.delete();
187 relatedFile
.getParentFile().delete();
188 } catch (IOException e
) {
189 Instance
.getTraceHandler().error(e
);
192 relatedFile
.renameTo(new File(newDir
, relatedFile
.getName()));
193 relatedFile
.getParentFile().delete();
201 public Image
getSourceCover(String source
) {
202 if (sourceCovers
== null) {
206 if (!sourceCovers
.containsKey(source
)) {
207 sourceCovers
.put(source
, super.getSourceCover(source
));
210 return sourceCovers
.get(source
);
214 public void setSourceCover(String source
, String luid
) {
215 if (sourceCovers
== null) {
219 sourceCovers
.put(source
, getCover(luid
));
220 File cover
= new File(getExpectedDir(source
), ".cover");
222 Instance
.getCache().saveAsImage(sourceCovers
.get(source
), cover
,
224 } catch (IOException e
) {
225 Instance
.getTraceHandler().error(e
);
226 sourceCovers
.remove(source
);
231 public void imprt(BasicLibrary other
, String luid
, Progress pg
)
237 // Check if we can simply copy the files instead of the whole process
238 if (other
instanceof LocalLibrary
) {
239 LocalLibrary otherLocalLibrary
= (LocalLibrary
) other
;
241 MetaData meta
= otherLocalLibrary
.getInfo(luid
);
242 String expectedType
= ""
243 + (meta
!= null && meta
.isImageDocument() ? image
: text
);
244 if (meta
!= null && meta
.getType().equals(expectedType
)) {
245 File from
= otherLocalLibrary
.getExpectedDir(meta
.getSource());
246 File to
= this.getExpectedDir(meta
.getSource());
247 List
<File
> sources
= otherLocalLibrary
.getRelatedFiles(luid
);
248 if (!sources
.isEmpty()) {
249 pg
.setMinMax(0, sources
.size());
252 for (File source
: sources
) {
253 File target
= new File(source
.getAbsolutePath().replace(
254 from
.getAbsolutePath(), to
.getAbsolutePath()));
255 if (!source
.equals(target
)) {
256 target
.getParentFile().mkdirs();
257 InputStream in
= null;
259 in
= new FileInputStream(source
);
260 IOUtils
.write(in
, target
);
261 } catch (IOException e
) {
265 } catch (Exception ee
) {
283 super.imprt(other
, luid
, pg
);
287 * Return the {@link OutputType} for this {@link Story}.
290 * the {@link Story} {@link MetaData}
294 private OutputType
getOutputType(MetaData meta
) {
295 if (meta
!= null && meta
.isImageDocument()) {
303 * Get the target {@link File} related to the given <tt>.info</tt>
304 * {@link File} and {@link MetaData}.
309 * the <tt>.info</tt> {@link File}
311 * @return the target {@link File}
313 private File
getTargetFile(MetaData meta
, File infoFile
) {
314 // Replace .info with whatever is needed:
315 String path
= infoFile
.getPath();
316 path
= path
.substring(0, path
.length() - ".info".length());
317 String newExt
= getOutputType(meta
).getDefaultExtension(true);
319 return new File(path
+ newExt
);
323 * The target (full path) where the {@link Story} related to this
324 * {@link MetaData} should be located on disk for a new {@link Story}.
327 * the {@link Story} {@link MetaData}
331 private File
getExpectedFile(MetaData key
) {
332 String title
= key
.getTitle();
336 title
= title
.replaceAll("[^a-zA-Z0-9._+-]", "_");
337 return new File(getExpectedDir(key
.getSource()), key
.getLuid() + "_"
342 * The directory (full path) where the new {@link Story} related to this
343 * {@link MetaData} should be located on disk.
348 * @return the target directory
350 private File
getExpectedDir(String source
) {
351 String sanitizedSource
= source
.replaceAll("[^a-zA-Z0-9._+-]", "_");
352 return new File(baseDir
, sanitizedSource
);
356 * Return the list of files/directories on disk for this {@link Story}.
358 * If the {@link Story} is not found, and empty list is returned.
361 * the {@link Story} LUID
363 * @return the list of {@link File}s
365 * @throws IOException
366 * if the {@link Story} was not found
368 private List
<File
> getRelatedFiles(String luid
) throws IOException
{
369 List
<File
> files
= new ArrayList
<File
>();
371 MetaData meta
= getInfo(luid
);
373 throw new IOException("Story not found: " + luid
);
376 File infoFile
= getStories(null).get(meta
)[0];
377 File targetFile
= getStories(null).get(meta
)[1];
380 files
.add(targetFile
);
382 String readerExt
= getOutputType(meta
).getDefaultExtension(true);
383 String fileExt
= getOutputType(meta
).getDefaultExtension(false);
385 String path
= targetFile
.getAbsolutePath();
386 if (readerExt
!= null && !readerExt
.equals(fileExt
)) {
387 path
= path
.substring(0, path
.length() - readerExt
.length())
389 File relatedFile
= new File(path
);
391 if (relatedFile
.exists()) {
392 files
.add(relatedFile
);
396 String coverExt
= "."
397 + Instance
.getConfig().getString(Config
.IMAGE_FORMAT_COVER
)
399 File coverFile
= new File(path
+ coverExt
);
400 if (!coverFile
.exists()) {
401 coverFile
= new File(path
.substring(0,
402 path
.length() - fileExt
.length())
406 if (coverFile
.exists()) {
407 files
.add(coverFile
);
414 * Fill the list of stories by reading the content of the local directory
415 * {@link LocalLibrary#baseDir}.
417 * Will use a cached list when possible (see
418 * {@link BasicLibrary#deleteInfo()}).
421 * the optional {@link Progress}
423 * @return the list of stories
425 private synchronized Map
<MetaData
, File
[]> getStories(Progress pg
) {
429 pg
.setMinMax(0, 100);
432 if (stories
== null) {
433 stories
= new HashMap
<MetaData
, File
[]>();
434 sourceCovers
= new HashMap
<String
, Image
>();
438 File
[] dirs
= baseDir
.listFiles(new FileFilter() {
440 public boolean accept(File file
) {
441 return file
!= null && file
.isDirectory();
446 Progress pgDirs
= new Progress(0, 100 * dirs
.length
);
447 pg
.addProgress(pgDirs
, 100);
449 for (File dir
: dirs
) {
450 File
[] infoFiles
= dir
.listFiles(new FileFilter() {
452 public boolean accept(File file
) {
454 && file
.getPath().toLowerCase()
459 Progress pgFiles
= new Progress(0, infoFiles
.length
);
460 pgDirs
.addProgress(pgFiles
, 100);
461 pgDirs
.setName("Loading from: " + dir
.getName());
463 String source
= null;
464 for (File infoFile
: infoFiles
) {
465 pgFiles
.setName(infoFile
.getName());
467 MetaData meta
= InfoReader
468 .readMeta(infoFile
, false);
469 source
= meta
.getSource();
471 int id
= Integer
.parseInt(meta
.getLuid());
476 stories
.put(meta
, new File
[] { infoFile
,
477 getTargetFile(meta
, infoFile
) });
478 } catch (Exception e
) {
480 throw new IOException(
481 "Cannot understand the LUID of "
483 + meta
.getLuid(), e
);
485 } catch (IOException e
) {
486 // We should not have not-supported files in the
488 Instance
.getTraceHandler().error(
490 "Cannot load file from library: "
496 File cover
= new File(dir
, ".cover.png");
497 if (cover
.exists()) {
499 InputStream in
= new FileInputStream(cover
);
501 sourceCovers
.put(source
, new Image(in
));
505 } catch (IOException e
) {
506 Instance
.getTraceHandler().error(e
);
510 pgFiles
.setName(null);
513 pgDirs
.setName("Loading directories");
522 * Fix the source cover to the given story cover.
525 * the source to change
529 void setSourceCover(String source
, Image coverImage
) {
530 if (sourceCovers
== null) {
534 sourceCovers
.put(source
, coverImage
);
535 File cover
= new File(getExpectedDir(source
), ".cover");
537 Instance
.getCache().saveAsImage(sourceCovers
.get(source
), cover
,
539 } catch (IOException e
) {
540 Instance
.getTraceHandler().error(e
);
541 sourceCovers
.remove(source
);