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