Try 3
[fanfix.git] / src / be / nikiroo / fanfix / library / LocalLibrary.java
CommitLineData
e42573a0 1package be.nikiroo.fanfix.library;
68e2c6d2 2
68e2c6d2
NR
3import java.io.File;
4import java.io.FileFilter;
14b57448 5import java.io.FileInputStream;
68e2c6d2 6import java.io.IOException;
14b57448 7import java.io.InputStream;
68e2c6d2
NR
8import java.util.ArrayList;
9import java.util.HashMap;
10import java.util.List;
11import java.util.Map;
12
e42573a0 13import be.nikiroo.fanfix.Instance;
68e2c6d2
NR
14import be.nikiroo.fanfix.bundles.Config;
15import be.nikiroo.fanfix.data.MetaData;
16import be.nikiroo.fanfix.data.Story;
17import be.nikiroo.fanfix.output.BasicOutput;
18import be.nikiroo.fanfix.output.BasicOutput.OutputType;
19import be.nikiroo.fanfix.output.InfoCover;
20import be.nikiroo.fanfix.supported.InfoReader;
21import be.nikiroo.utils.IOUtils;
16a81ef7 22import be.nikiroo.utils.Image;
68e2c6d2
NR
23import be.nikiroo.utils.Progress;
24
25/**
26 * This {@link BasicLibrary} will store the stories locally on disk.
27 *
28 * @author niki
29 */
30public class LocalLibrary extends BasicLibrary {
31 private int lastId;
32 private Map<MetaData, File[]> stories; // Files: [ infoFile, TargetFile ]
16a81ef7 33 private Map<String, Image> sourceCovers;
68e2c6d2
NR
34
35 private File baseDir;
36 private OutputType text;
37 private OutputType image;
38
e604986c
NR
39 /**
40 * Create a new {@link LocalLibrary} with the given back-end directory.
41 *
42 * @param baseDir
43 * the directory where to find the {@link Story} objects
44 */
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);
49 }
50
51 /**
52 * Create a new {@link LocalLibrary} with the given back-end directory.
53 *
54 * @param baseDir
55 * the directory where to find the {@link Story} objects
ff05b828
NR
56 * @param text
57 * the {@link OutputType} to use for non-image documents
58 * @param image
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)
e604986c
NR
63 */
64 public LocalLibrary(File baseDir, String text, String image,
65 boolean defaultIsHtml) {
ff05b828 66 this(baseDir, OutputType.valueOfAllOkUC(text,
e604986c 67 defaultIsHtml ? OutputType.HTML : OutputType.INFO_TEXT),
ff05b828 68 OutputType.valueOfAllOkUC(image,
e604986c
NR
69 defaultIsHtml ? OutputType.HTML : OutputType.CBZ));
70 }
71
68e2c6d2
NR
72 /**
73 * Create a new {@link LocalLibrary} with the given back-end directory.
74 *
75 * @param baseDir
76 * the directory where to find the {@link Story} objects
77 * @param text
e604986c 78 * the {@link OutputType} to use for non-image documents
68e2c6d2 79 * @param image
e604986c 80 * the {@link OutputType} to use for image documents
68e2c6d2
NR
81 */
82 public LocalLibrary(File baseDir, OutputType text, OutputType image) {
83 this.baseDir = baseDir;
84 this.text = text;
85 this.image = image;
86
87 this.lastId = 0;
88 this.stories = null;
b56c9d60 89 this.sourceCovers = null;
68e2c6d2
NR
90
91 baseDir.mkdirs();
92 }
93
94 @Override
95 protected List<MetaData> getMetas(Progress pg) {
96 return new ArrayList<MetaData>(getStories(pg).keySet());
97 }
98
99 @Override
ff05b828
NR
100 public File getFile(String luid, Progress pg) {
101 File[] files = getStories(pg).get(getInfo(luid));
68e2c6d2
NR
102 if (files != null) {
103 return files[1];
104 }
105
106 return null;
107 }
108
109 @Override
16a81ef7 110 public Image getCover(String luid) {
68e2c6d2
NR
111 MetaData meta = getInfo(luid);
112 if (meta != null) {
113 File[] files = getStories(null).get(meta);
114 if (files != null) {
115 File infoFile = files[0];
116
117 try {
118 meta = InfoReader.readMeta(infoFile, true);
119 return meta.getCover();
120 } catch (IOException e) {
62c63b07 121 Instance.getTraceHandler().error(e);
68e2c6d2
NR
122 }
123 }
124 }
125
126 return null;
127 }
128
129 @Override
efa3c511
NR
130 protected synchronized void updateInfo(MetaData meta) {
131 deleteInfo();
132 }
133
134 @Override
135 protected void deleteInfo(String luid) {
68e2c6d2 136 stories = null;
b56c9d60 137 sourceCovers = null;
68e2c6d2
NR
138 }
139
140 @Override
141 protected synchronized int getNextId() {
14b57448 142 getStories(null); // make sure lastId is set
68e2c6d2
NR
143 return ++lastId;
144 }
145
146 @Override
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);
e272f05f 151 file.getParentFile().delete();
68e2c6d2
NR
152 }
153 }
154
155 @Override
156 protected Story doSave(Story story, Progress pg) throws IOException {
157 MetaData meta = story.getMeta();
158
159 File expectedTarget = getExpectedFile(meta);
160 expectedTarget.getParentFile().mkdirs();
161
925298fd 162 BasicOutput it = BasicOutput.getOutput(getOutputType(meta), true, true);
68e2c6d2
NR
163 it.process(story, expectedTarget.getPath(), pg);
164
165 return story;
166 }
167
168 @Override
169 protected synchronized void saveMeta(MetaData meta, Progress pg)
170 throws IOException {
171 File newDir = getExpectedDir(meta.getSource());
172 if (!newDir.exists()) {
173 newDir.mkdir();
174 }
175
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")) {
182 try {
183 String name = relatedFile.getName().replaceFirst(
184 "\\.info$", "");
185 InfoCover.writeInfo(newDir, name, meta);
186 relatedFile.delete();
e272f05f 187 relatedFile.getParentFile().delete();
68e2c6d2 188 } catch (IOException e) {
62c63b07 189 Instance.getTraceHandler().error(e);
68e2c6d2
NR
190 }
191 } else {
192 relatedFile.renameTo(new File(newDir, relatedFile.getName()));
e272f05f 193 relatedFile.getParentFile().delete();
68e2c6d2
NR
194 }
195 }
196
efa3c511 197 deleteInfo();
68e2c6d2
NR
198 }
199
14b57448 200 @Override
16a81ef7 201 public Image getSourceCover(String source) {
b56c9d60
NR
202 if (sourceCovers == null) {
203 getStories(null);
204 }
205
14b57448
NR
206 if (!sourceCovers.containsKey(source)) {
207 sourceCovers.put(source, super.getSourceCover(source));
208 }
209
210 return sourceCovers.get(source);
211 }
212
213 @Override
214 public void setSourceCover(String source, String luid) {
b56c9d60
NR
215 if (sourceCovers == null) {
216 getStories(null);
217 }
218
14b57448 219 sourceCovers.put(source, getCover(luid));
ecfb936e 220 File cover = new File(getExpectedDir(source), ".cover");
14b57448 221 try {
16a81ef7
NR
222 Instance.getCache().saveAsImage(sourceCovers.get(source), cover,
223 true);
14b57448 224 } catch (IOException e) {
62c63b07 225 Instance.getTraceHandler().error(e);
14b57448
NR
226 sourceCovers.remove(source);
227 }
228 }
229
b89dfb6e
NR
230 @Override
231 public void imprt(BasicLibrary other, String luid, Progress pg)
232 throws IOException {
233 if (pg == null) {
234 pg = new Progress();
235 }
236
ff05b828 237 // Check if we can simply copy the files instead of the whole process
b89dfb6e 238 if (other instanceof LocalLibrary) {
ff05b828 239 LocalLibrary otherLocalLibrary = (LocalLibrary) other;
e604986c 240
e604986c
NR
241 MetaData meta = otherLocalLibrary.getInfo(luid);
242 String expectedType = ""
243 + (meta != null && meta.isImageDocument() ? image : text);
244 if (meta != null && meta.getType().equals(expectedType)) {
245 File from = otherLocalLibrary.getExpectedDir(meta.getSource());
b89dfb6e 246 File to = this.getExpectedDir(meta.getSource());
e604986c 247 List<File> sources = otherLocalLibrary.getRelatedFiles(luid);
b89dfb6e
NR
248 if (!sources.isEmpty()) {
249 pg.setMinMax(0, sources.size());
250 }
251
252 for (File source : sources) {
253 File target = new File(source.getAbsolutePath().replace(
254 from.getAbsolutePath(), to.getAbsolutePath()));
255 if (!source.equals(target)) {
e604986c 256 target.getParentFile().mkdirs();
b89dfb6e
NR
257 InputStream in = null;
258 try {
259 in = new FileInputStream(source);
260 IOUtils.write(in, target);
261 } catch (IOException e) {
262 if (in != null) {
263 try {
264 in.close();
265 } catch (Exception ee) {
266 }
267 }
268
269 pg.done();
270 throw e;
271 }
272 }
273
274 pg.add(1);
275 }
276
efa3c511 277 deleteInfo();
b89dfb6e
NR
278 pg.done();
279 return;
280 }
281 }
282
283 super.imprt(other, luid, pg);
efa3c511 284 deleteInfo();
b89dfb6e
NR
285 }
286
68e2c6d2
NR
287 /**
288 * Return the {@link OutputType} for this {@link Story}.
289 *
290 * @param meta
291 * the {@link Story} {@link MetaData}
292 *
293 * @return the type
294 */
295 private OutputType getOutputType(MetaData meta) {
296 if (meta != null && meta.isImageDocument()) {
297 return image;
68e2c6d2 298 }
211f7ddb
NR
299
300 return text;
68e2c6d2
NR
301 }
302
303 /**
304 * Get the target {@link File} related to the given <tt>.info</tt>
305 * {@link File} and {@link MetaData}.
306 *
307 * @param meta
308 * the meta
309 * @param infoFile
310 * the <tt>.info</tt> {@link File}
311 *
312 * @return the target {@link File}
313 */
314 private File getTargetFile(MetaData meta, File infoFile) {
315 // Replace .info with whatever is needed:
316 String path = infoFile.getPath();
317 path = path.substring(0, path.length() - ".info".length());
318 String newExt = getOutputType(meta).getDefaultExtension(true);
319
320 return new File(path + newExt);
321 }
322
323 /**
324 * The target (full path) where the {@link Story} related to this
325 * {@link MetaData} should be located on disk for a new {@link Story}.
326 *
327 * @param key
328 * the {@link Story} {@link MetaData}
329 *
330 * @return the target
331 */
332 private File getExpectedFile(MetaData key) {
333 String title = key.getTitle();
334 if (title == null) {
335 title = "";
336 }
337 title = title.replaceAll("[^a-zA-Z0-9._+-]", "_");
338 return new File(getExpectedDir(key.getSource()), key.getLuid() + "_"
339 + title);
340 }
341
342 /**
343 * The directory (full path) where the new {@link Story} related to this
344 * {@link MetaData} should be located on disk.
345 *
085a2f9a 346 * @param source
68e2c6d2
NR
347 * the type (source)
348 *
349 * @return the target directory
350 */
085a2f9a
NR
351 private File getExpectedDir(String source) {
352 String sanitizedSource = source.replaceAll("[^a-zA-Z0-9._+-]", "_");
353 return new File(baseDir, sanitizedSource);
68e2c6d2
NR
354 }
355
356 /**
357 * Return the list of files/directories on disk for this {@link Story}.
358 * <p>
359 * If the {@link Story} is not found, and empty list is returned.
360 *
361 * @param luid
362 * the {@link Story} LUID
363 *
364 * @return the list of {@link File}s
365 *
366 * @throws IOException
367 * if the {@link Story} was not found
368 */
369 private List<File> getRelatedFiles(String luid) throws IOException {
370 List<File> files = new ArrayList<File>();
371
372 MetaData meta = getInfo(luid);
373 if (meta == null) {
374 throw new IOException("Story not found: " + luid);
211f7ddb 375 }
68e2c6d2 376
211f7ddb
NR
377 File infoFile = getStories(null).get(meta)[0];
378 File targetFile = getStories(null).get(meta)[1];
68e2c6d2 379
211f7ddb
NR
380 files.add(infoFile);
381 files.add(targetFile);
68e2c6d2 382
211f7ddb
NR
383 String readerExt = getOutputType(meta).getDefaultExtension(true);
384 String fileExt = getOutputType(meta).getDefaultExtension(false);
68e2c6d2 385
211f7ddb
NR
386 String path = targetFile.getAbsolutePath();
387 if (readerExt != null && !readerExt.equals(fileExt)) {
388 path = path.substring(0, path.length() - readerExt.length())
389 + fileExt;
390 File relatedFile = new File(path);
68e2c6d2 391
211f7ddb
NR
392 if (relatedFile.exists()) {
393 files.add(relatedFile);
68e2c6d2 394 }
211f7ddb 395 }
68e2c6d2 396
211f7ddb 397 String coverExt = "."
2a25f781
NR
398 + Instance.getConfig().getString(Config.IMAGE_FORMAT_COVER)
399 .toLowerCase();
211f7ddb
NR
400 File coverFile = new File(path + coverExt);
401 if (!coverFile.exists()) {
402 coverFile = new File(path.substring(0,
403 path.length() - fileExt.length())
404 + coverExt);
405 }
406
407 if (coverFile.exists()) {
408 files.add(coverFile);
68e2c6d2
NR
409 }
410
411 return files;
412 }
413
414 /**
415 * Fill the list of stories by reading the content of the local directory
416 * {@link LocalLibrary#baseDir}.
417 * <p>
418 * Will use a cached list when possible (see
efa3c511 419 * {@link BasicLibrary#deleteInfo()}).
68e2c6d2
NR
420 *
421 * @param pg
422 * the optional {@link Progress}
423 *
424 * @return the list of stories
425 */
426 private synchronized Map<MetaData, File[]> getStories(Progress pg) {
427 if (pg == null) {
428 pg = new Progress();
429 } else {
430 pg.setMinMax(0, 100);
431 }
432
433 if (stories == null) {
434 stories = new HashMap<MetaData, File[]>();
b56c9d60 435 sourceCovers = new HashMap<String, Image>();
68e2c6d2
NR
436
437 lastId = 0;
438
439 File[] dirs = baseDir.listFiles(new FileFilter() {
211f7ddb 440 @Override
68e2c6d2
NR
441 public boolean accept(File file) {
442 return file != null && file.isDirectory();
443 }
444 });
445
b4f9071c
NR
446 if (dirs != null) {
447 Progress pgDirs = new Progress(0, 100 * dirs.length);
448 pg.addProgress(pgDirs, 100);
449
450 for (File dir : dirs) {
451 File[] infoFiles = dir.listFiles(new FileFilter() {
452 @Override
453 public boolean accept(File file) {
454 return file != null
455 && file.getPath().toLowerCase()
456 .endsWith(".info");
457 }
458 });
459
460 Progress pgFiles = new Progress(0, infoFiles.length);
461 pgDirs.addProgress(pgFiles, 100);
462 pgDirs.setName("Loading from: " + dir.getName());
463
464 String source = null;
465 for (File infoFile : infoFiles) {
466 pgFiles.setName(infoFile.getName());
68e2c6d2 467 try {
b4f9071c
NR
468 MetaData meta = InfoReader
469 .readMeta(infoFile, false);
470 source = meta.getSource();
471 try {
472 int id = Integer.parseInt(meta.getLuid());
473 if (id > lastId) {
474 lastId = id;
475 }
68e2c6d2 476
b4f9071c
NR
477 stories.put(meta, new File[] { infoFile,
478 getTargetFile(meta, infoFile) });
479 } catch (Exception e) {
480 // not normal!!
481 throw new IOException(
482 "Cannot understand the LUID of "
fd25eddc
NR
483 + infoFile + ": "
484 + meta.getLuid(), e);
b4f9071c
NR
485 }
486 } catch (IOException e) {
487 // We should not have not-supported files in the
488 // library
489 Instance.getTraceHandler().error(
490 new IOException(
491 "Cannot load file from library: "
492 + infoFile, e));
68e2c6d2 493 }
b4f9071c 494 pgFiles.add(1);
68e2c6d2 495 }
68e2c6d2 496
b4f9071c
NR
497 File cover = new File(dir, ".cover.png");
498 if (cover.exists()) {
14b57448 499 try {
b4f9071c
NR
500 InputStream in = new FileInputStream(cover);
501 try {
502 sourceCovers.put(source, new Image(in));
503 } finally {
504 in.close();
505 }
506 } catch (IOException e) {
507 Instance.getTraceHandler().error(e);
14b57448 508 }
14b57448 509 }
b4f9071c
NR
510
511 pgFiles.setName(null);
14b57448
NR
512 }
513
b4f9071c 514 pgDirs.setName("Loading directories");
68e2c6d2 515 }
68e2c6d2
NR
516 }
517
b4f9071c 518 pg.done();
68e2c6d2
NR
519 return stories;
520 }
085a2f9a
NR
521
522 /**
523 * Fix the source cover to the given story cover.
524 *
525 * @param source
526 * the source to change
527 * @param coverImage
528 * the cover image
529 */
16a81ef7 530 void setSourceCover(String source, Image coverImage) {
b56c9d60
NR
531 if (sourceCovers == null) {
532 getStories(null);
533 }
534
085a2f9a 535 sourceCovers.put(source, coverImage);
ecfb936e 536 File cover = new File(getExpectedDir(source), ".cover");
085a2f9a 537 try {
16a81ef7
NR
538 Instance.getCache().saveAsImage(sourceCovers.get(source), cover,
539 true);
085a2f9a 540 } catch (IOException e) {
62c63b07 541 Instance.getTraceHandler().error(e);
085a2f9a
NR
542 sourceCovers.remove(source);
543 }
544 }
68e2c6d2 545}