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
.MarkableFileInputStream
;
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
= new HashMap
<String
, Image
>();
96 protected List
<MetaData
> getMetas(Progress pg
) {
97 return new ArrayList
<MetaData
>(getStories(pg
).keySet());
101 public File
getFile(String luid
, Progress pg
) {
102 File
[] files
= getStories(pg
).get(getInfo(luid
));
111 public Image
getCover(String luid
) {
112 MetaData meta
= getInfo(luid
);
114 File
[] files
= getStories(null).get(meta
);
116 File infoFile
= files
[0];
119 meta
= InfoReader
.readMeta(infoFile
, true);
120 return meta
.getCover();
121 } catch (IOException e
) {
122 Instance
.getTraceHandler().error(e
);
131 protected void invalidateInfo(String luid
) {
133 sourceCovers
= new HashMap
<String
, Image
>();
137 protected synchronized int getNextId() {
138 getStories(null); // make sure lastId is set
143 protected void doDelete(String luid
) throws IOException
{
144 for (File file
: getRelatedFiles(luid
)) {
145 // TODO: throw an IOException if we cannot delete the files?
146 IOUtils
.deltree(file
);
147 file
.getParentFile().delete();
152 protected Story
doSave(Story story
, Progress pg
) throws IOException
{
153 MetaData meta
= story
.getMeta();
155 File expectedTarget
= getExpectedFile(meta
);
156 expectedTarget
.getParentFile().mkdirs();
158 BasicOutput it
= BasicOutput
.getOutput(getOutputType(meta
), true, true);
159 it
.process(story
, expectedTarget
.getPath(), pg
);
165 protected synchronized void saveMeta(MetaData meta
, Progress pg
)
167 File newDir
= getExpectedDir(meta
.getSource());
168 if (!newDir
.exists()) {
172 List
<File
> relatedFiles
= getRelatedFiles(meta
.getLuid());
173 for (File relatedFile
: relatedFiles
) {
174 // TODO: this is not safe at all.
175 // We should copy all the files THEN delete them
176 // Maybe also adding some rollback cleanup if possible
177 if (relatedFile
.getName().endsWith(".info")) {
179 String name
= relatedFile
.getName().replaceFirst(
181 InfoCover
.writeInfo(newDir
, name
, meta
);
182 relatedFile
.delete();
183 relatedFile
.getParentFile().delete();
184 } catch (IOException e
) {
185 Instance
.getTraceHandler().error(e
);
188 relatedFile
.renameTo(new File(newDir
, relatedFile
.getName()));
189 relatedFile
.getParentFile().delete();
197 public Image
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 Instance
.getCache().saveAsImage(sourceCovers
.get(source
), cover
,
212 } catch (IOException e
) {
213 Instance
.getTraceHandler().error(e
);
214 sourceCovers
.remove(source
);
219 public void imprt(BasicLibrary other
, String luid
, Progress pg
)
225 // Check if we can simply copy the files instead of the whole process
226 if (other
instanceof LocalLibrary
) {
227 LocalLibrary otherLocalLibrary
= (LocalLibrary
) other
;
229 MetaData meta
= otherLocalLibrary
.getInfo(luid
);
230 String expectedType
= ""
231 + (meta
!= null && meta
.isImageDocument() ? image
: text
);
232 if (meta
!= null && meta
.getType().equals(expectedType
)) {
233 File from
= otherLocalLibrary
.getExpectedDir(meta
.getSource());
234 File to
= this.getExpectedDir(meta
.getSource());
235 List
<File
> sources
= otherLocalLibrary
.getRelatedFiles(luid
);
236 if (!sources
.isEmpty()) {
237 pg
.setMinMax(0, sources
.size());
240 for (File source
: sources
) {
241 File target
= new File(source
.getAbsolutePath().replace(
242 from
.getAbsolutePath(), to
.getAbsolutePath()));
243 if (!source
.equals(target
)) {
244 target
.getParentFile().mkdirs();
245 InputStream in
= null;
247 in
= new FileInputStream(source
);
248 IOUtils
.write(in
, target
);
249 } catch (IOException e
) {
253 } catch (Exception ee
) {
271 super.imprt(other
, luid
, pg
);
277 * Return the {@link OutputType} for this {@link Story}.
280 * the {@link Story} {@link MetaData}
284 private OutputType
getOutputType(MetaData meta
) {
285 if (meta
!= null && meta
.isImageDocument()) {
293 * Get the target {@link File} related to the given <tt>.info</tt>
294 * {@link File} and {@link MetaData}.
299 * the <tt>.info</tt> {@link File}
301 * @return the target {@link File}
303 private File
getTargetFile(MetaData meta
, File infoFile
) {
304 // Replace .info with whatever is needed:
305 String path
= infoFile
.getPath();
306 path
= path
.substring(0, path
.length() - ".info".length());
307 String newExt
= getOutputType(meta
).getDefaultExtension(true);
309 return new File(path
+ newExt
);
313 * The target (full path) where the {@link Story} related to this
314 * {@link MetaData} should be located on disk for a new {@link Story}.
317 * the {@link Story} {@link MetaData}
321 private File
getExpectedFile(MetaData key
) {
322 String title
= key
.getTitle();
326 title
= title
.replaceAll("[^a-zA-Z0-9._+-]", "_");
327 return new File(getExpectedDir(key
.getSource()), key
.getLuid() + "_"
332 * The directory (full path) where the new {@link Story} related to this
333 * {@link MetaData} should be located on disk.
338 * @return the target directory
340 private File
getExpectedDir(String source
) {
341 String sanitizedSource
= source
.replaceAll("[^a-zA-Z0-9._+-]", "_");
342 return new File(baseDir
, sanitizedSource
);
346 * Return the list of files/directories on disk for this {@link Story}.
348 * If the {@link Story} is not found, and empty list is returned.
351 * the {@link Story} LUID
353 * @return the list of {@link File}s
355 * @throws IOException
356 * if the {@link Story} was not found
358 private List
<File
> getRelatedFiles(String luid
) throws IOException
{
359 List
<File
> files
= new ArrayList
<File
>();
361 MetaData meta
= getInfo(luid
);
363 throw new IOException("Story not found: " + luid
);
366 File infoFile
= getStories(null).get(meta
)[0];
367 File targetFile
= getStories(null).get(meta
)[1];
370 files
.add(targetFile
);
372 String readerExt
= getOutputType(meta
).getDefaultExtension(true);
373 String fileExt
= getOutputType(meta
).getDefaultExtension(false);
375 String path
= targetFile
.getAbsolutePath();
376 if (readerExt
!= null && !readerExt
.equals(fileExt
)) {
377 path
= path
.substring(0, path
.length() - readerExt
.length())
379 File relatedFile
= new File(path
);
381 if (relatedFile
.exists()) {
382 files
.add(relatedFile
);
386 String coverExt
= "."
387 + Instance
.getConfig().getString(Config
.IMAGE_FORMAT_COVER
)
389 File coverFile
= new File(path
+ coverExt
);
390 if (!coverFile
.exists()) {
391 coverFile
= new File(path
.substring(0,
392 path
.length() - fileExt
.length())
396 if (coverFile
.exists()) {
397 files
.add(coverFile
);
404 * Fill the list of stories by reading the content of the local directory
405 * {@link LocalLibrary#baseDir}.
407 * Will use a cached list when possible (see
408 * {@link BasicLibrary#invalidateInfo()}).
411 * the optional {@link Progress}
413 * @return the list of stories
415 private synchronized Map
<MetaData
, File
[]> getStories(Progress pg
) {
419 pg
.setMinMax(0, 100);
422 if (stories
== null) {
423 stories
= new HashMap
<MetaData
, File
[]>();
427 File
[] dirs
= baseDir
.listFiles(new FileFilter() {
429 public boolean accept(File file
) {
430 return file
!= null && file
.isDirectory();
435 Progress pgDirs
= new Progress(0, 100 * dirs
.length
);
436 pg
.addProgress(pgDirs
, 100);
438 for (File dir
: dirs
) {
439 File
[] infoFiles
= dir
.listFiles(new FileFilter() {
441 public boolean accept(File file
) {
443 && file
.getPath().toLowerCase()
448 Progress pgFiles
= new Progress(0, infoFiles
.length
);
449 pgDirs
.addProgress(pgFiles
, 100);
450 pgDirs
.setName("Loading from: " + dir
.getName());
452 String source
= null;
453 for (File infoFile
: infoFiles
) {
454 pgFiles
.setName(infoFile
.getName());
456 MetaData meta
= InfoReader
457 .readMeta(infoFile
, false);
458 source
= meta
.getSource();
460 int id
= Integer
.parseInt(meta
.getLuid());
465 stories
.put(meta
, new File
[] { infoFile
,
466 getTargetFile(meta
, infoFile
) });
467 } catch (Exception e
) {
469 throw new IOException(
470 "Cannot understand the LUID of "
473 + (meta
== null ?
"[meta is NULL]"
474 : meta
.getLuid()), e
);
476 } catch (IOException e
) {
477 // We should not have not-supported files in the
479 Instance
.getTraceHandler().error(
481 "Cannot load file from library: "
487 File cover
= new File(dir
, ".cover.png");
488 if (cover
.exists()) {
490 InputStream in
= new FileInputStream(cover
);
492 sourceCovers
.put(source
, new Image(in
));
496 } catch (IOException e
) {
497 Instance
.getTraceHandler().error(e
);
501 pgFiles
.setName(null);
504 pgDirs
.setName("Loading directories");
513 * Fix the source cover to the given story cover.
516 * the source to change
520 void setSourceCover(String source
, Image coverImage
) {
521 sourceCovers
.put(source
, coverImage
);
522 File cover
= new File(getExpectedDir(source
), ".cover.png");
524 Instance
.getCache().saveAsImage(sourceCovers
.get(source
), cover
,
526 } catch (IOException e
) {
527 Instance
.getTraceHandler().error(e
);
528 sourceCovers
.remove(source
);