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
);
288 * Return the {@link OutputType} for this {@link Story}.
291 * the {@link Story} {@link MetaData}
295 private OutputType
getOutputType(MetaData meta
) {
296 if (meta
!= null && meta
.isImageDocument()) {
304 * Get the target {@link File} related to the given <tt>.info</tt>
305 * {@link File} and {@link MetaData}.
310 * the <tt>.info</tt> {@link File}
312 * @return the target {@link File}
314 private File
getTargetFile(MetaData meta
, File infoFile
) {
315 // Replace .info with whatever is needed:
316 String path
= infoFile
.getPath();
317 path
= path
.substring(0, path
.length() - ".info".length());
318 String newExt
= getOutputType(meta
).getDefaultExtension(true);
320 return new File(path
+ newExt
);
324 * The target (full path) where the {@link Story} related to this
325 * {@link MetaData} should be located on disk for a new {@link Story}.
328 * the {@link Story} {@link MetaData}
332 private File
getExpectedFile(MetaData key
) {
333 String title
= key
.getTitle();
337 title
= title
.replaceAll("[^a-zA-Z0-9._+-]", "_");
338 return new File(getExpectedDir(key
.getSource()), key
.getLuid() + "_"
343 * The directory (full path) where the new {@link Story} related to this
344 * {@link MetaData} should be located on disk.
349 * @return the target directory
351 private File
getExpectedDir(String source
) {
352 String sanitizedSource
= source
.replaceAll("[^a-zA-Z0-9._+-]", "_");
353 return new File(baseDir
, sanitizedSource
);
357 * Return the list of files/directories on disk for this {@link Story}.
359 * If the {@link Story} is not found, and empty list is returned.
362 * the {@link Story} LUID
364 * @return the list of {@link File}s
366 * @throws IOException
367 * if the {@link Story} was not found
369 private List
<File
> getRelatedFiles(String luid
) throws IOException
{
370 List
<File
> files
= new ArrayList
<File
>();
372 MetaData meta
= getInfo(luid
);
374 throw new IOException("Story not found: " + luid
);
377 File infoFile
= getStories(null).get(meta
)[0];
378 File targetFile
= getStories(null).get(meta
)[1];
381 files
.add(targetFile
);
383 String readerExt
= getOutputType(meta
).getDefaultExtension(true);
384 String fileExt
= getOutputType(meta
).getDefaultExtension(false);
386 String path
= targetFile
.getAbsolutePath();
387 if (readerExt
!= null && !readerExt
.equals(fileExt
)) {
388 path
= path
.substring(0, path
.length() - readerExt
.length())
390 File relatedFile
= new File(path
);
392 if (relatedFile
.exists()) {
393 files
.add(relatedFile
);
397 String coverExt
= "."
398 + Instance
.getConfig().getString(Config
.IMAGE_FORMAT_COVER
)
400 File coverFile
= new File(path
+ coverExt
);
401 if (!coverFile
.exists()) {
402 coverFile
= new File(path
.substring(0,
403 path
.length() - fileExt
.length())
407 if (coverFile
.exists()) {
408 files
.add(coverFile
);
415 * Fill the list of stories by reading the content of the local directory
416 * {@link LocalLibrary#baseDir}.
418 * Will use a cached list when possible (see
419 * {@link BasicLibrary#deleteInfo()}).
422 * the optional {@link Progress}
424 * @return the list of stories
426 private synchronized Map
<MetaData
, File
[]> getStories(Progress pg
) {
430 pg
.setMinMax(0, 100);
433 if (stories
== null) {
434 stories
= new HashMap
<MetaData
, File
[]>();
435 sourceCovers
= new HashMap
<String
, Image
>();
439 File
[] dirs
= baseDir
.listFiles(new FileFilter() {
441 public boolean accept(File file
) {
442 return file
!= null && file
.isDirectory();
447 Progress pgDirs
= new Progress(0, 100 * dirs
.length
);
448 pg
.addProgress(pgDirs
, 100);
450 for (File dir
: dirs
) {
451 File
[] infoFiles
= dir
.listFiles(new FileFilter() {
453 public boolean accept(File file
) {
455 && file
.getPath().toLowerCase()
460 Progress pgFiles
= new Progress(0, infoFiles
.length
);
461 pgDirs
.addProgress(pgFiles
, 100);
462 pgDirs
.setName("Loading from: " + dir
.getName());
464 String source
= null;
465 for (File infoFile
: infoFiles
) {
466 pgFiles
.setName(infoFile
.getName());
468 MetaData meta
= InfoReader
469 .readMeta(infoFile
, false);
470 source
= meta
.getSource();
472 int id
= Integer
.parseInt(meta
.getLuid());
477 stories
.put(meta
, new File
[] { infoFile
,
478 getTargetFile(meta
, infoFile
) });
479 } catch (Exception e
) {
481 throw new IOException(
482 "Cannot understand the LUID of "
484 + meta
.getLuid(), e
);
486 } catch (IOException e
) {
487 // We should not have not-supported files in the
489 Instance
.getTraceHandler().error(
491 "Cannot load file from library: "
497 File cover
= new File(dir
, ".cover.png");
498 if (cover
.exists()) {
500 InputStream in
= new FileInputStream(cover
);
502 sourceCovers
.put(source
, new Image(in
));
506 } catch (IOException e
) {
507 Instance
.getTraceHandler().error(e
);
511 pgFiles
.setName(null);
514 pgDirs
.setName("Loading directories");
523 * Fix the source cover to the given story cover.
526 * the source to change
530 void setSourceCover(String source
, Image coverImage
) {
531 if (sourceCovers
== null) {
535 sourceCovers
.put(source
, coverImage
);
536 File cover
= new File(getExpectedDir(source
), ".cover");
538 Instance
.getCache().saveAsImage(sourceCovers
.get(source
), cover
,
540 } catch (IOException e
) {
541 Instance
.getTraceHandler().error(e
);
542 sourceCovers
.remove(source
);