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 invalidateInfo(String luid
) {
132 sourceCovers
= new HashMap
<String
, Image
>();
136 protected synchronized int getNextId() {
137 getStories(null); // make sure lastId is set
142 protected void doDelete(String luid
) throws IOException
{
143 for (File file
: getRelatedFiles(luid
)) {
144 // TODO: throw an IOException if we cannot delete the files?
145 IOUtils
.deltree(file
);
146 file
.getParentFile().delete();
151 protected Story
doSave(Story story
, Progress pg
) throws IOException
{
152 MetaData meta
= story
.getMeta();
154 File expectedTarget
= getExpectedFile(meta
);
155 expectedTarget
.getParentFile().mkdirs();
157 BasicOutput it
= BasicOutput
.getOutput(getOutputType(meta
), true, true);
158 it
.process(story
, expectedTarget
.getPath(), pg
);
164 protected synchronized void saveMeta(MetaData meta
, Progress pg
)
166 File newDir
= getExpectedDir(meta
.getSource());
167 if (!newDir
.exists()) {
171 List
<File
> relatedFiles
= getRelatedFiles(meta
.getLuid());
172 for (File relatedFile
: relatedFiles
) {
173 // TODO: this is not safe at all.
174 // We should copy all the files THEN delete them
175 // Maybe also adding some rollback cleanup if possible
176 if (relatedFile
.getName().endsWith(".info")) {
178 String name
= relatedFile
.getName().replaceFirst(
180 InfoCover
.writeInfo(newDir
, name
, meta
);
181 relatedFile
.delete();
182 relatedFile
.getParentFile().delete();
183 } catch (IOException e
) {
184 Instance
.getTraceHandler().error(e
);
187 relatedFile
.renameTo(new File(newDir
, relatedFile
.getName()));
188 relatedFile
.getParentFile().delete();
196 public Image
getSourceCover(String source
) {
197 if (!sourceCovers
.containsKey(source
)) {
198 sourceCovers
.put(source
, super.getSourceCover(source
));
201 return sourceCovers
.get(source
);
205 public void setSourceCover(String source
, String luid
) {
206 sourceCovers
.put(source
, getCover(luid
));
207 File cover
= new File(getExpectedDir(source
), ".cover");
209 Instance
.getCache().saveAsImage(sourceCovers
.get(source
), cover
,
211 } catch (IOException e
) {
212 Instance
.getTraceHandler().error(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
)
388 File coverFile
= new File(path
+ coverExt
);
389 if (!coverFile
.exists()) {
390 coverFile
= new File(path
.substring(0,
391 path
.length() - fileExt
.length())
395 if (coverFile
.exists()) {
396 files
.add(coverFile
);
403 * Fill the list of stories by reading the content of the local directory
404 * {@link LocalLibrary#baseDir}.
406 * Will use a cached list when possible (see
407 * {@link BasicLibrary#invalidateInfo()}).
410 * the optional {@link Progress}
412 * @return the list of stories
414 private synchronized Map
<MetaData
, File
[]> getStories(Progress pg
) {
418 pg
.setMinMax(0, 100);
421 if (stories
== null) {
422 stories
= new HashMap
<MetaData
, File
[]>();
426 File
[] dirs
= baseDir
.listFiles(new FileFilter() {
428 public boolean accept(File file
) {
429 return file
!= null && file
.isDirectory();
434 Progress pgDirs
= new Progress(0, 100 * dirs
.length
);
435 pg
.addProgress(pgDirs
, 100);
437 for (File dir
: dirs
) {
438 File
[] infoFiles
= dir
.listFiles(new FileFilter() {
440 public boolean accept(File file
) {
442 && file
.getPath().toLowerCase()
447 Progress pgFiles
= new Progress(0, infoFiles
.length
);
448 pgDirs
.addProgress(pgFiles
, 100);
449 pgDirs
.setName("Loading from: " + dir
.getName());
451 String source
= null;
452 for (File infoFile
: infoFiles
) {
453 pgFiles
.setName(infoFile
.getName());
455 MetaData meta
= InfoReader
456 .readMeta(infoFile
, false);
457 source
= meta
.getSource();
459 int id
= Integer
.parseInt(meta
.getLuid());
464 stories
.put(meta
, new File
[] { infoFile
,
465 getTargetFile(meta
, infoFile
) });
466 } catch (Exception e
) {
468 throw new IOException(
469 "Cannot understand the LUID of "
471 + meta
.getLuid(), e
);
473 } catch (IOException e
) {
474 // We should not have not-supported files in the
476 Instance
.getTraceHandler().error(
478 "Cannot load file from library: "
484 File cover
= new File(dir
, ".cover.png");
485 if (cover
.exists()) {
487 InputStream in
= new FileInputStream(cover
);
489 sourceCovers
.put(source
, new Image(in
));
493 } catch (IOException e
) {
494 Instance
.getTraceHandler().error(e
);
498 pgFiles
.setName(null);
501 pgDirs
.setName("Loading directories");
510 * Fix the source cover to the given story cover.
513 * the source to change
517 void setSourceCover(String source
, Image coverImage
) {
518 sourceCovers
.put(source
, coverImage
);
519 File cover
= new File(getExpectedDir(source
), ".cover");
521 Instance
.getCache().saveAsImage(sourceCovers
.get(source
), cover
,
523 } catch (IOException e
) {
524 Instance
.getTraceHandler().error(e
);
525 sourceCovers
.remove(source
);