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 * the {@link OutputType} to save the text-focused stories into
51 * the {@link OutputType} to save the images-focused stories into
53 public LocalLibrary(File baseDir
, OutputType text
, OutputType image
) {
54 this.baseDir
= baseDir
;
60 this.sourceCovers
= new HashMap
<String
, BufferedImage
>();
66 protected List
<MetaData
> getMetas(Progress pg
) {
67 return new ArrayList
<MetaData
>(getStories(pg
).keySet());
71 public File
getFile(String luid
) {
72 File
[] files
= getStories(null).get(getInfo(luid
));
81 public BufferedImage
getCover(String luid
) {
82 MetaData meta
= getInfo(luid
);
84 File
[] files
= getStories(null).get(meta
);
86 File infoFile
= files
[0];
89 meta
= InfoReader
.readMeta(infoFile
, true);
90 return meta
.getCover();
91 } catch (IOException e
) {
101 protected void clearCache() {
103 sourceCovers
= new HashMap
<String
, BufferedImage
>();
107 protected synchronized int getNextId() {
108 getStories(null); // make sure lastId is set
113 protected void doDelete(String luid
) throws IOException
{
114 for (File file
: getRelatedFiles(luid
)) {
115 // TODO: throw an IOException if we cannot delete the files?
116 IOUtils
.deltree(file
);
121 protected Story
doSave(Story story
, Progress pg
) throws IOException
{
122 MetaData meta
= story
.getMeta();
124 File expectedTarget
= getExpectedFile(meta
);
125 expectedTarget
.getParentFile().mkdirs();
127 BasicOutput it
= BasicOutput
.getOutput(getOutputType(meta
), true);
128 it
.process(story
, expectedTarget
.getPath(), pg
);
134 protected synchronized void saveMeta(MetaData meta
, Progress pg
)
136 File newDir
= getExpectedDir(meta
.getSource());
137 if (!newDir
.exists()) {
141 List
<File
> relatedFiles
= getRelatedFiles(meta
.getLuid());
142 for (File relatedFile
: relatedFiles
) {
143 // TODO: this is not safe at all.
144 // We should copy all the files THEN delete them
145 // Maybe also adding some rollback cleanup if possible
146 if (relatedFile
.getName().endsWith(".info")) {
148 String name
= relatedFile
.getName().replaceFirst(
150 InfoCover
.writeInfo(newDir
, name
, meta
);
151 relatedFile
.delete();
152 } catch (IOException e
) {
156 relatedFile
.renameTo(new File(newDir
, relatedFile
.getName()));
164 public BufferedImage
getSourceCover(String source
) {
165 if (!sourceCovers
.containsKey(source
)) {
166 sourceCovers
.put(source
, super.getSourceCover(source
));
169 return sourceCovers
.get(source
);
173 public void setSourceCover(String source
, String luid
) {
174 sourceCovers
.put(source
, getCover(luid
));
175 File cover
= new File(getExpectedDir(source
), ".cover.png");
177 ImageIO
.write(sourceCovers
.get(source
), "png", cover
);
178 } catch (IOException e
) {
180 sourceCovers
.remove(source
);
185 public void imprt(BasicLibrary other
, String luid
, Progress pg
)
191 // Check if we can simply copy the files instead of the whole process
192 if (other
instanceof LocalLibrary
) {
193 LocalLibrary otherLibrary
= (LocalLibrary
) other
;
194 MetaData meta
= otherLibrary
.getInfo(luid
);
195 String expectedType
= "" + (meta
.isImageDocument() ? image
: text
);
196 if (meta
.getType().equals(expectedType
)) {
197 File from
= otherLibrary
.getExpectedDir(meta
.getSource());
198 File to
= this.getExpectedDir(meta
.getSource());
199 List
<File
> sources
= otherLibrary
.getRelatedFiles(luid
);
200 if (!sources
.isEmpty()) {
201 pg
.setMinMax(0, sources
.size());
204 for (File source
: sources
) {
205 File target
= new File(source
.getAbsolutePath().replace(
206 from
.getAbsolutePath(), to
.getAbsolutePath()));
207 if (!source
.equals(target
)) {
208 InputStream in
= null;
210 in
= new FileInputStream(source
);
211 IOUtils
.write(in
, target
);
212 } catch (IOException e
) {
216 } catch (Exception ee
) {
234 super.imprt(other
, luid
, pg
);
238 * Return the {@link OutputType} for this {@link Story}.
241 * the {@link Story} {@link MetaData}
245 private OutputType
getOutputType(MetaData meta
) {
246 if (meta
!= null && meta
.isImageDocument()) {
254 * Get the target {@link File} related to the given <tt>.info</tt>
255 * {@link File} and {@link MetaData}.
260 * the <tt>.info</tt> {@link File}
262 * @return the target {@link File}
264 private File
getTargetFile(MetaData meta
, File infoFile
) {
265 // Replace .info with whatever is needed:
266 String path
= infoFile
.getPath();
267 path
= path
.substring(0, path
.length() - ".info".length());
268 String newExt
= getOutputType(meta
).getDefaultExtension(true);
270 return new File(path
+ newExt
);
274 * The target (full path) where the {@link Story} related to this
275 * {@link MetaData} should be located on disk for a new {@link Story}.
278 * the {@link Story} {@link MetaData}
282 private File
getExpectedFile(MetaData key
) {
283 String title
= key
.getTitle();
287 title
= title
.replaceAll("[^a-zA-Z0-9._+-]", "_");
288 return new File(getExpectedDir(key
.getSource()), key
.getLuid() + "_"
293 * The directory (full path) where the new {@link Story} related to this
294 * {@link MetaData} should be located on disk.
299 * @return the target directory
301 private File
getExpectedDir(String type
) {
302 String source
= type
.replaceAll("[^a-zA-Z0-9._+-]", "_");
303 return new File(baseDir
, source
);
307 * Return the list of files/directories on disk for this {@link Story}.
309 * If the {@link Story} is not found, and empty list is returned.
312 * the {@link Story} LUID
314 * @return the list of {@link File}s
316 * @throws IOException
317 * if the {@link Story} was not found
319 private List
<File
> getRelatedFiles(String luid
) throws IOException
{
320 List
<File
> files
= new ArrayList
<File
>();
322 MetaData meta
= getInfo(luid
);
324 throw new IOException("Story not found: " + luid
);
327 File infoFile
= getStories(null).get(meta
)[0];
328 File targetFile
= getStories(null).get(meta
)[1];
331 files
.add(targetFile
);
333 String readerExt
= getOutputType(meta
).getDefaultExtension(true);
334 String fileExt
= getOutputType(meta
).getDefaultExtension(false);
336 String path
= targetFile
.getAbsolutePath();
337 if (readerExt
!= null && !readerExt
.equals(fileExt
)) {
338 path
= path
.substring(0, path
.length() - readerExt
.length())
340 File relatedFile
= new File(path
);
342 if (relatedFile
.exists()) {
343 files
.add(relatedFile
);
347 String coverExt
= "."
348 + Instance
.getConfig().getString(Config
.IMAGE_FORMAT_COVER
);
349 File coverFile
= new File(path
+ coverExt
);
350 if (!coverFile
.exists()) {
351 coverFile
= new File(path
.substring(0,
352 path
.length() - fileExt
.length())
356 if (coverFile
.exists()) {
357 files
.add(coverFile
);
364 * Fill the list of stories by reading the content of the local directory
365 * {@link LocalLibrary#baseDir}.
367 * Will use a cached list when possible (see
368 * {@link BasicLibrary#clearCache()}).
371 * the optional {@link Progress}
373 * @return the list of stories
375 private synchronized Map
<MetaData
, File
[]> getStories(Progress pg
) {
379 pg
.setMinMax(0, 100);
382 if (stories
== null) {
383 stories
= new HashMap
<MetaData
, File
[]>();
387 File
[] dirs
= baseDir
.listFiles(new FileFilter() {
389 public boolean accept(File file
) {
390 return file
!= null && file
.isDirectory();
394 Progress pgDirs
= new Progress(0, 100 * dirs
.length
);
395 pg
.addProgress(pgDirs
, 100);
397 for (File dir
: dirs
) {
398 File
[] infoFiles
= dir
.listFiles(new FileFilter() {
400 public boolean accept(File file
) {
402 && file
.getPath().toLowerCase()
407 Progress pgFiles
= new Progress(0, infoFiles
.length
);
408 pgDirs
.addProgress(pgFiles
, 100);
409 pgDirs
.setName("Loading from: " + dir
.getName());
411 String source
= null;
412 for (File infoFile
: infoFiles
) {
413 pgFiles
.setName(infoFile
.getName());
415 MetaData meta
= InfoReader
.readMeta(infoFile
, false);
416 source
= meta
.getSource();
418 int id
= Integer
.parseInt(meta
.getLuid());
423 stories
.put(meta
, new File
[] { infoFile
,
424 getTargetFile(meta
, infoFile
) });
425 } catch (Exception e
) {
427 throw new IOException(
428 "Cannot understand the LUID of "
431 + (meta
== null ?
"[meta is NULL]"
432 : meta
.getLuid()), e
);
434 } catch (IOException e
) {
435 // We should not have not-supported files in the
437 Instance
.syserr(new IOException(
438 "Cannot load file from library: " + infoFile
, e
));
443 File cover
= new File(dir
, ".cover.png");
444 if (cover
.exists()) {
446 InputStream in
= new MarkableFileInputStream(
447 new FileInputStream(cover
));
449 sourceCovers
.put(source
, ImageUtils
.fromStream(in
));
453 } catch (IOException e
) {
458 pgFiles
.setName(null);
461 pgDirs
.setName("Loading directories");