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