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
= new HashMap
<String
, Image
>();
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
) {
137 sourceCovers
= new HashMap
<String
, Image
>();
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
.containsKey(source
)) {
203 sourceCovers
.put(source
, super.getSourceCover(source
));
206 return sourceCovers
.get(source
);
210 public void setSourceCover(String source
, String luid
) {
211 sourceCovers
.put(source
, getCover(luid
));
212 File cover
= new File(getExpectedDir(source
), ".cover");
214 Instance
.getCache().saveAsImage(sourceCovers
.get(source
), cover
,
216 } catch (IOException e
) {
217 Instance
.getTraceHandler().error(e
);
218 sourceCovers
.remove(source
);
223 public void imprt(BasicLibrary other
, String luid
, Progress pg
)
229 // Check if we can simply copy the files instead of the whole process
230 if (other
instanceof LocalLibrary
) {
231 LocalLibrary otherLocalLibrary
= (LocalLibrary
) other
;
233 MetaData meta
= otherLocalLibrary
.getInfo(luid
);
234 String expectedType
= ""
235 + (meta
!= null && meta
.isImageDocument() ? image
: text
);
236 if (meta
!= null && meta
.getType().equals(expectedType
)) {
237 File from
= otherLocalLibrary
.getExpectedDir(meta
.getSource());
238 File to
= this.getExpectedDir(meta
.getSource());
239 List
<File
> sources
= otherLocalLibrary
.getRelatedFiles(luid
);
240 if (!sources
.isEmpty()) {
241 pg
.setMinMax(0, sources
.size());
244 for (File source
: sources
) {
245 File target
= new File(source
.getAbsolutePath().replace(
246 from
.getAbsolutePath(), to
.getAbsolutePath()));
247 if (!source
.equals(target
)) {
248 target
.getParentFile().mkdirs();
249 InputStream in
= null;
251 in
= new FileInputStream(source
);
252 IOUtils
.write(in
, target
);
253 } catch (IOException e
) {
257 } catch (Exception ee
) {
275 super.imprt(other
, luid
, pg
);
281 * Return the {@link OutputType} for this {@link Story}.
284 * the {@link Story} {@link MetaData}
288 private OutputType
getOutputType(MetaData meta
) {
289 if (meta
!= null && meta
.isImageDocument()) {
297 * Get the target {@link File} related to the given <tt>.info</tt>
298 * {@link File} and {@link MetaData}.
303 * the <tt>.info</tt> {@link File}
305 * @return the target {@link File}
307 private File
getTargetFile(MetaData meta
, File infoFile
) {
308 // Replace .info with whatever is needed:
309 String path
= infoFile
.getPath();
310 path
= path
.substring(0, path
.length() - ".info".length());
311 String newExt
= getOutputType(meta
).getDefaultExtension(true);
313 return new File(path
+ newExt
);
317 * The target (full path) where the {@link Story} related to this
318 * {@link MetaData} should be located on disk for a new {@link Story}.
321 * the {@link Story} {@link MetaData}
325 private File
getExpectedFile(MetaData key
) {
326 String title
= key
.getTitle();
330 title
= title
.replaceAll("[^a-zA-Z0-9._+-]", "_");
331 return new File(getExpectedDir(key
.getSource()), key
.getLuid() + "_"
336 * The directory (full path) where the new {@link Story} related to this
337 * {@link MetaData} should be located on disk.
342 * @return the target directory
344 private File
getExpectedDir(String source
) {
345 String sanitizedSource
= source
.replaceAll("[^a-zA-Z0-9._+-]", "_");
346 return new File(baseDir
, sanitizedSource
);
350 * Return the list of files/directories on disk for this {@link Story}.
352 * If the {@link Story} is not found, and empty list is returned.
355 * the {@link Story} LUID
357 * @return the list of {@link File}s
359 * @throws IOException
360 * if the {@link Story} was not found
362 private List
<File
> getRelatedFiles(String luid
) throws IOException
{
363 List
<File
> files
= new ArrayList
<File
>();
365 MetaData meta
= getInfo(luid
);
367 throw new IOException("Story not found: " + luid
);
370 File infoFile
= getStories(null).get(meta
)[0];
371 File targetFile
= getStories(null).get(meta
)[1];
374 files
.add(targetFile
);
376 String readerExt
= getOutputType(meta
).getDefaultExtension(true);
377 String fileExt
= getOutputType(meta
).getDefaultExtension(false);
379 String path
= targetFile
.getAbsolutePath();
380 if (readerExt
!= null && !readerExt
.equals(fileExt
)) {
381 path
= path
.substring(0, path
.length() - readerExt
.length())
383 File relatedFile
= new File(path
);
385 if (relatedFile
.exists()) {
386 files
.add(relatedFile
);
390 String coverExt
= "."
391 + Instance
.getConfig().getString(Config
.IMAGE_FORMAT_COVER
)
393 File coverFile
= new File(path
+ coverExt
);
394 if (!coverFile
.exists()) {
395 coverFile
= new File(path
.substring(0,
396 path
.length() - fileExt
.length())
400 if (coverFile
.exists()) {
401 files
.add(coverFile
);
408 * Fill the list of stories by reading the content of the local directory
409 * {@link LocalLibrary#baseDir}.
411 * Will use a cached list when possible (see
412 * {@link BasicLibrary#deleteInfo()}).
415 * the optional {@link Progress}
417 * @return the list of stories
419 private synchronized Map
<MetaData
, File
[]> getStories(Progress pg
) {
423 pg
.setMinMax(0, 100);
426 if (stories
== null) {
427 stories
= new HashMap
<MetaData
, File
[]>();
431 File
[] dirs
= baseDir
.listFiles(new FileFilter() {
433 public boolean accept(File file
) {
434 return file
!= null && file
.isDirectory();
439 Progress pgDirs
= new Progress(0, 100 * dirs
.length
);
440 pg
.addProgress(pgDirs
, 100);
442 for (File dir
: dirs
) {
443 File
[] infoFiles
= dir
.listFiles(new FileFilter() {
445 public boolean accept(File file
) {
447 && file
.getPath().toLowerCase()
452 Progress pgFiles
= new Progress(0, infoFiles
.length
);
453 pgDirs
.addProgress(pgFiles
, 100);
454 pgDirs
.setName("Loading from: " + dir
.getName());
456 String source
= null;
457 for (File infoFile
: infoFiles
) {
458 pgFiles
.setName(infoFile
.getName());
460 MetaData meta
= InfoReader
461 .readMeta(infoFile
, false);
462 source
= meta
.getSource();
464 int id
= Integer
.parseInt(meta
.getLuid());
469 stories
.put(meta
, new File
[] { infoFile
,
470 getTargetFile(meta
, infoFile
) });
471 } catch (Exception e
) {
473 throw new IOException(
474 "Cannot understand the LUID of "
476 + meta
.getLuid(), e
);
478 } catch (IOException e
) {
479 // We should not have not-supported files in the
481 Instance
.getTraceHandler().error(
483 "Cannot load file from library: "
489 File cover
= new File(dir
, ".cover.png");
490 if (cover
.exists()) {
492 InputStream in
= new FileInputStream(cover
);
494 sourceCovers
.put(source
, new Image(in
));
498 } catch (IOException e
) {
499 Instance
.getTraceHandler().error(e
);
503 pgFiles
.setName(null);
506 pgDirs
.setName("Loading directories");
515 * Fix the source cover to the given story cover.
518 * the source to change
522 void setSourceCover(String source
, Image coverImage
) {
523 sourceCovers
.put(source
, coverImage
);
524 File cover
= new File(getExpectedDir(source
), ".cover");
526 Instance
.getCache().saveAsImage(sourceCovers
.get(source
), cover
,
528 } catch (IOException e
) {
529 Instance
.getTraceHandler().error(e
);
530 sourceCovers
.remove(source
);