1 package be
.nikiroo
.fanfix
.library
;
3 import java
.awt
.image
.BufferedImage
;
5 import java
.io
.FileFilter
;
6 import java
.io
.FileInputStream
;
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 javax
.imageio
.ImageIO
;
16 import be
.nikiroo
.fanfix
.Instance
;
17 import be
.nikiroo
.fanfix
.bundles
.Config
;
18 import be
.nikiroo
.fanfix
.data
.MetaData
;
19 import be
.nikiroo
.fanfix
.data
.Story
;
20 import be
.nikiroo
.fanfix
.output
.BasicOutput
;
21 import be
.nikiroo
.fanfix
.output
.BasicOutput
.OutputType
;
22 import be
.nikiroo
.fanfix
.output
.InfoCover
;
23 import be
.nikiroo
.fanfix
.supported
.InfoReader
;
24 import be
.nikiroo
.utils
.IOUtils
;
25 import be
.nikiroo
.utils
.ImageUtils
;
26 import be
.nikiroo
.utils
.MarkableFileInputStream
;
27 import be
.nikiroo
.utils
.Progress
;
30 * This {@link BasicLibrary} will store the stories locally on disk.
34 public class LocalLibrary
extends BasicLibrary
{
36 private Map
<MetaData
, File
[]> stories
; // Files: [ infoFile, TargetFile ]
37 private Map
<String
, BufferedImage
> sourceCovers
;
40 private OutputType text
;
41 private OutputType image
;
44 * Create a new {@link LocalLibrary} with the given back-end directory.
47 * the directory where to find the {@link Story} objects
49 public LocalLibrary(File baseDir
) {
50 this(baseDir
, Instance
.getConfig().getString(
51 Config
.NON_IMAGES_DOCUMENT_TYPE
), Instance
.getConfig()
52 .getString(Config
.IMAGES_DOCUMENT_TYPE
), false);
56 * Create a new {@link LocalLibrary} with the given back-end directory.
59 * the directory where to find the {@link Story} objects
61 * the {@link OutputType} to use for non-image documents
63 * the {@link OutputType} to use for image documents
64 * @param defaultIsHtml
65 * if the given text or image is invalid, use HTML by default (if
66 * not, it will be INFO_TEXT/CBZ by default)
68 public LocalLibrary(File baseDir
, String text
, String image
,
69 boolean defaultIsHtml
) {
70 this(baseDir
, OutputType
.valueOfAllOkUC(text
,
71 defaultIsHtml ? OutputType
.HTML
: OutputType
.INFO_TEXT
),
72 OutputType
.valueOfAllOkUC(image
,
73 defaultIsHtml ? OutputType
.HTML
: OutputType
.CBZ
));
77 * Create a new {@link LocalLibrary} with the given back-end directory.
80 * the directory where to find the {@link Story} objects
82 * the {@link OutputType} to use for non-image documents
84 * the {@link OutputType} to use for image documents
86 public LocalLibrary(File baseDir
, OutputType text
, OutputType image
) {
87 this.baseDir
= baseDir
;
93 this.sourceCovers
= new HashMap
<String
, BufferedImage
>();
99 protected List
<MetaData
> getMetas(Progress pg
) {
100 return new ArrayList
<MetaData
>(getStories(pg
).keySet());
104 public File
getFile(String luid
, Progress pg
) {
105 File
[] files
= getStories(pg
).get(getInfo(luid
));
114 public BufferedImage
getCover(String luid
) {
115 MetaData meta
= getInfo(luid
);
117 File
[] files
= getStories(null).get(meta
);
119 File infoFile
= files
[0];
122 meta
= InfoReader
.readMeta(infoFile
, true);
123 return meta
.getCover();
124 } catch (IOException e
) {
134 protected void clearCache() {
136 sourceCovers
= new HashMap
<String
, BufferedImage
>();
140 protected synchronized int getNextId() {
141 getStories(null); // make sure lastId is set
146 protected void doDelete(String luid
) throws IOException
{
147 for (File file
: getRelatedFiles(luid
)) {
148 // TODO: throw an IOException if we cannot delete the files?
149 IOUtils
.deltree(file
);
154 protected Story
doSave(Story story
, Progress pg
) throws IOException
{
155 MetaData meta
= story
.getMeta();
157 File expectedTarget
= getExpectedFile(meta
);
158 expectedTarget
.getParentFile().mkdirs();
160 BasicOutput it
= BasicOutput
.getOutput(getOutputType(meta
), true);
161 it
.process(story
, expectedTarget
.getPath(), pg
);
167 protected synchronized void saveMeta(MetaData meta
, Progress pg
)
169 File newDir
= getExpectedDir(meta
.getSource());
170 if (!newDir
.exists()) {
174 List
<File
> relatedFiles
= getRelatedFiles(meta
.getLuid());
175 for (File relatedFile
: relatedFiles
) {
176 // TODO: this is not safe at all.
177 // We should copy all the files THEN delete them
178 // Maybe also adding some rollback cleanup if possible
179 if (relatedFile
.getName().endsWith(".info")) {
181 String name
= relatedFile
.getName().replaceFirst(
183 InfoCover
.writeInfo(newDir
, name
, meta
);
184 relatedFile
.delete();
185 } catch (IOException e
) {
189 relatedFile
.renameTo(new File(newDir
, relatedFile
.getName()));
197 public BufferedImage
getSourceCover(String source
) {
198 if (!sourceCovers
.containsKey(source
)) {
199 sourceCovers
.put(source
, super.getSourceCover(source
));
202 return sourceCovers
.get(source
);
206 public void setSourceCover(String source
, String luid
) {
207 sourceCovers
.put(source
, getCover(luid
));
208 File cover
= new File(getExpectedDir(source
), ".cover.png");
210 ImageIO
.write(sourceCovers
.get(source
), "png", cover
);
211 } catch (IOException e
) {
213 sourceCovers
.remove(source
);
218 public void imprt(BasicLibrary other
, String luid
, Progress pg
)
224 // Check if we can simply copy the files instead of the whole process
225 if (other
instanceof LocalLibrary
) {
226 LocalLibrary otherLocalLibrary
= (LocalLibrary
) other
;
228 MetaData meta
= otherLocalLibrary
.getInfo(luid
);
229 String expectedType
= ""
230 + (meta
!= null && meta
.isImageDocument() ? image
: text
);
231 if (meta
!= null && meta
.getType().equals(expectedType
)) {
232 File from
= otherLocalLibrary
.getExpectedDir(meta
.getSource());
233 File to
= this.getExpectedDir(meta
.getSource());
234 List
<File
> sources
= otherLocalLibrary
.getRelatedFiles(luid
);
235 if (!sources
.isEmpty()) {
236 pg
.setMinMax(0, sources
.size());
239 for (File source
: sources
) {
240 File target
= new File(source
.getAbsolutePath().replace(
241 from
.getAbsolutePath(), to
.getAbsolutePath()));
242 if (!source
.equals(target
)) {
243 target
.getParentFile().mkdirs();
244 InputStream in
= null;
246 in
= new FileInputStream(source
);
247 IOUtils
.write(in
, target
);
248 } catch (IOException e
) {
252 } catch (Exception ee
) {
270 super.imprt(other
, luid
, pg
);
276 * Return the {@link OutputType} for this {@link Story}.
279 * the {@link Story} {@link MetaData}
283 private OutputType
getOutputType(MetaData meta
) {
284 if (meta
!= null && meta
.isImageDocument()) {
292 * Get the target {@link File} related to the given <tt>.info</tt>
293 * {@link File} and {@link MetaData}.
298 * the <tt>.info</tt> {@link File}
300 * @return the target {@link File}
302 private File
getTargetFile(MetaData meta
, File infoFile
) {
303 // Replace .info with whatever is needed:
304 String path
= infoFile
.getPath();
305 path
= path
.substring(0, path
.length() - ".info".length());
306 String newExt
= getOutputType(meta
).getDefaultExtension(true);
308 return new File(path
+ newExt
);
312 * The target (full path) where the {@link Story} related to this
313 * {@link MetaData} should be located on disk for a new {@link Story}.
316 * the {@link Story} {@link MetaData}
320 private File
getExpectedFile(MetaData key
) {
321 String title
= key
.getTitle();
325 title
= title
.replaceAll("[^a-zA-Z0-9._+-]", "_");
326 return new File(getExpectedDir(key
.getSource()), key
.getLuid() + "_"
331 * The directory (full path) where the new {@link Story} related to this
332 * {@link MetaData} should be located on disk.
337 * @return the target directory
339 private File
getExpectedDir(String source
) {
340 String sanitizedSource
= source
.replaceAll("[^a-zA-Z0-9._+-]", "_");
341 return new File(baseDir
, sanitizedSource
);
345 * Return the list of files/directories on disk for this {@link Story}.
347 * If the {@link Story} is not found, and empty list is returned.
350 * the {@link Story} LUID
352 * @return the list of {@link File}s
354 * @throws IOException
355 * if the {@link Story} was not found
357 private List
<File
> getRelatedFiles(String luid
) throws IOException
{
358 List
<File
> files
= new ArrayList
<File
>();
360 MetaData meta
= getInfo(luid
);
362 throw new IOException("Story not found: " + luid
);
365 File infoFile
= getStories(null).get(meta
)[0];
366 File targetFile
= getStories(null).get(meta
)[1];
369 files
.add(targetFile
);
371 String readerExt
= getOutputType(meta
).getDefaultExtension(true);
372 String fileExt
= getOutputType(meta
).getDefaultExtension(false);
374 String path
= targetFile
.getAbsolutePath();
375 if (readerExt
!= null && !readerExt
.equals(fileExt
)) {
376 path
= path
.substring(0, path
.length() - readerExt
.length())
378 File relatedFile
= new File(path
);
380 if (relatedFile
.exists()) {
381 files
.add(relatedFile
);
385 String coverExt
= "."
386 + Instance
.getConfig().getString(Config
.IMAGE_FORMAT_COVER
);
387 File coverFile
= new File(path
+ coverExt
);
388 if (!coverFile
.exists()) {
389 coverFile
= new File(path
.substring(0,
390 path
.length() - fileExt
.length())
394 if (coverFile
.exists()) {
395 files
.add(coverFile
);
402 * Fill the list of stories by reading the content of the local directory
403 * {@link LocalLibrary#baseDir}.
405 * Will use a cached list when possible (see
406 * {@link BasicLibrary#clearCache()}).
409 * the optional {@link Progress}
411 * @return the list of stories
413 private synchronized Map
<MetaData
, File
[]> getStories(Progress pg
) {
417 pg
.setMinMax(0, 100);
420 if (stories
== null) {
421 stories
= new HashMap
<MetaData
, File
[]>();
425 File
[] dirs
= baseDir
.listFiles(new FileFilter() {
427 public boolean accept(File file
) {
428 return file
!= null && file
.isDirectory();
432 Progress pgDirs
= new Progress(0, 100 * dirs
.length
);
433 pg
.addProgress(pgDirs
, 100);
435 for (File dir
: dirs
) {
436 File
[] infoFiles
= dir
.listFiles(new FileFilter() {
438 public boolean accept(File file
) {
440 && file
.getPath().toLowerCase()
445 Progress pgFiles
= new Progress(0, infoFiles
.length
);
446 pgDirs
.addProgress(pgFiles
, 100);
447 pgDirs
.setName("Loading from: " + dir
.getName());
449 String source
= null;
450 for (File infoFile
: infoFiles
) {
451 pgFiles
.setName(infoFile
.getName());
453 MetaData meta
= InfoReader
.readMeta(infoFile
, false);
454 source
= meta
.getSource();
456 int id
= Integer
.parseInt(meta
.getLuid());
461 stories
.put(meta
, new File
[] { infoFile
,
462 getTargetFile(meta
, infoFile
) });
463 } catch (Exception e
) {
465 throw new IOException(
466 "Cannot understand the LUID of "
469 + (meta
== null ?
"[meta is NULL]"
470 : meta
.getLuid()), e
);
472 } catch (IOException e
) {
473 // We should not have not-supported files in the
475 Instance
.syserr(new IOException(
476 "Cannot load file from library: " + infoFile
, e
));
481 File cover
= new File(dir
, ".cover.png");
482 if (cover
.exists()) {
484 InputStream in
= new MarkableFileInputStream(
485 new FileInputStream(cover
));
487 sourceCovers
.put(source
, ImageUtils
.fromStream(in
));
491 } catch (IOException e
) {
496 pgFiles
.setName(null);
499 pgDirs
.setName("Loading directories");
506 * Fix the source cover to the given story cover.
509 * the source to change
513 void setSourceCover(String source
, BufferedImage coverImage
) {
514 sourceCovers
.put(source
, coverImage
);
515 File cover
= new File(getExpectedDir(source
), ".cover.png");
517 ImageIO
.write(sourceCovers
.get(source
), "png", cover
);
518 } catch (IOException e
) {
520 sourceCovers
.remove(source
);