gui: fix ChangeSTA, fix [unknown] author
[fanfix.git] / src / be / nikiroo / fanfix / output / Epub.java
1 package be.nikiroo.fanfix.output;
2
3 import java.io.BufferedWriter;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.OutputStream;
10 import java.io.OutputStreamWriter;
11 import java.util.zip.ZipEntry;
12 import java.util.zip.ZipOutputStream;
13
14 import be.nikiroo.fanfix.Instance;
15 import be.nikiroo.fanfix.bundles.Config;
16 import be.nikiroo.fanfix.bundles.StringId;
17 import be.nikiroo.fanfix.data.Chapter;
18 import be.nikiroo.fanfix.data.MetaData;
19 import be.nikiroo.fanfix.data.Paragraph;
20 import be.nikiroo.fanfix.data.Paragraph.ParagraphType;
21 import be.nikiroo.fanfix.data.Story;
22 import be.nikiroo.utils.IOUtils;
23 import be.nikiroo.utils.StringUtils;
24
25 class Epub extends BasicOutput {
26 private File tmpDir;
27 private BufferedWriter writer;
28 private boolean inDialogue = false;
29 private boolean inNormal = false;
30 private File images;
31 private boolean nextParaIsCover = true;
32
33 @Override
34 public File process(Story story, File targetDir, String targetName)
35 throws IOException {
36 String targetNameOrig = targetName;
37 targetName += getDefaultExtension(false);
38
39 tmpDir = Instance.getTempFiles().createTempDir("fanfic-reader-epub");
40 tmpDir.delete();
41
42 if (!tmpDir.mkdir()) {
43 throw new IOException(
44 "Cannot create a temporary directory: no space left on device?");
45 }
46
47 super.process(story, targetDir, targetNameOrig);
48
49 File epub = null;
50 try {
51 // "Originals"
52 File data = new File(tmpDir, "DATA");
53 data.mkdir();
54 BasicOutput.getOutput(OutputType.TEXT, isWriteInfo(),
55 isWriteCover()).process(story, data, targetNameOrig);
56 InfoCover.writeInfo(data, targetNameOrig, story.getMeta());
57 IOUtils.writeSmallFile(data, "version", "3.0");
58
59 // zip/epub
60 epub = new File(targetDir, targetName);
61 IOUtils.zip(tmpDir, epub, true);
62
63 OutputStream out = new FileOutputStream(epub);
64 try {
65 ZipOutputStream zip = new ZipOutputStream(out);
66 try {
67 // "mimetype" MUST be the first element and not compressed
68 zip.setLevel(ZipOutputStream.STORED);
69 File mimetype = new File(tmpDir, "mimetype");
70 IOUtils.writeSmallFile(tmpDir, "mimetype",
71 "application/epub+zip");
72 ZipEntry entry = new ZipEntry("mimetype");
73 entry.setExtra(new byte[] {});
74 zip.putNextEntry(entry);
75 FileInputStream in = new FileInputStream(mimetype);
76 try {
77 IOUtils.write(in, zip);
78 } finally {
79 in.close();
80 }
81 IOUtils.deltree(mimetype);
82 zip.setLevel(ZipOutputStream.DEFLATED);
83 //
84
85 IOUtils.zip(zip, "", tmpDir, true);
86 } finally {
87 zip.close();
88 }
89 } finally {
90 out.close();
91 }
92 } finally {
93 IOUtils.deltree(tmpDir);
94 tmpDir = null;
95 }
96
97 return epub;
98 }
99
100 @Override
101 public String getDefaultExtension(boolean readerTarget) {
102 return ".epub";
103 }
104
105 @Override
106 protected void writeStoryHeader(Story story) throws IOException {
107 File ops = new File(tmpDir, "OPS");
108 ops.mkdirs();
109 File css = new File(ops, "css");
110 css.mkdirs();
111 images = new File(ops, "images");
112 images.mkdirs();
113 File metaInf = new File(tmpDir, "META-INF");
114 metaInf.mkdirs();
115
116 // META-INF
117 String containerContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
118 + "<container xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\" version=\"1.0\">\n"
119 + "\t<rootfiles>\n"
120 + "\t\t<rootfile full-path=\"OPS/epb.opf\" media-type=\"application/oebps-package+xml\"/>\n"
121 + "\t</rootfiles>\n" + "</container>\n";
122
123 IOUtils.writeSmallFile(metaInf, "container.xml", containerContent);
124
125 // OPS/css
126 InputStream inStyle = getClass().getResourceAsStream("epub.style.css");
127 if (inStyle == null) {
128 throw new IOException("Cannot find style.css resource");
129 }
130 try {
131 IOUtils.write(inStyle, new File(css, "style.css"));
132 } finally {
133 inStyle.close();
134 }
135
136 // OPS/images
137 if (story.getMeta() != null && story.getMeta().getCover() != null) {
138 File file = new File(images, "cover");
139 Instance.getCache().saveAsImage(story.getMeta().getCover(), file,
140 true);
141 }
142
143 // OPS/* except chapters
144 IOUtils.writeSmallFile(ops, "epb.ncx", generateNcx(story));
145 IOUtils.writeSmallFile(ops, "epb.opf", generateOpf(story));
146 IOUtils.writeSmallFile(ops, "title.xhtml", generateTitleXml(story));
147
148 // Resume
149 if (story.getMeta() != null && story.getMeta().getResume() != null) {
150 writeChapter(story.getMeta().getResume());
151 }
152 }
153
154 @Override
155 protected void writeChapterHeader(Chapter chap) throws IOException {
156 String filename = String.format("%s%03d%s", "chapter-",
157 chap.getNumber(), ".xhtml");
158 writer = new BufferedWriter(new OutputStreamWriter(
159 new FileOutputStream(new File(tmpDir + File.separator + "OPS",
160 filename)), "UTF-8"));
161 inDialogue = false;
162 inNormal = false;
163 try {
164 String title = "Chapter " + chap.getNumber();
165 String nameOrNum = Integer.toString(chap.getNumber());
166 if (chap.getName() != null && !chap.getName().isEmpty()) {
167 title += ": " + chap.getName();
168 nameOrNum = chap.getName();
169 }
170
171 writer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
172 writer.append("\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">");
173 writer.append("\n<html xmlns=\"http://www.w3.org/1999/xhtml\">");
174 writer.write("\n<head>");
175 writer.write("\n <title>" + StringUtils.xmlEscape(title)
176 + "</title>");
177 writer.write("\n <link rel='stylesheet' href='css/style.css' type='text/css'/>");
178 writer.write("\n</head>");
179 writer.write("\n<body>");
180 writer.write("\n <h2>");
181 writer.write("\n <span class='chap'>Chapter <span class='chapnumber'>"
182 + chap.getNumber() + "</span>:</span> ");
183 writer.write("\n <span class='chaptitle'>"
184 + StringUtils.xmlEscape(nameOrNum) + "</span>");
185 writer.write("\n </h2>");
186 writer.write("\n ");
187 writer.write("\n <div class='chapter_content'>\n");
188 } catch (Exception e) {
189 writer.close();
190 throw new IOException(e);
191 }
192 }
193
194 @Override
195 protected void writeChapterFooter(Chapter chap) throws IOException {
196 try {
197 if (inDialogue) {
198 writer.write(" </div>\n");
199 inDialogue = false;
200 }
201 if (inNormal) {
202 writer.write(" </div>\n");
203 inNormal = false;
204 }
205 writer.write(" </div>\n</body>\n</html>\n");
206 } finally {
207 writer.close();
208 writer = null;
209 }
210 }
211
212 @Override
213 protected void writeParagraphHeader(Paragraph para) throws IOException {
214 if (para.getType() == ParagraphType.QUOTE && !inDialogue) {
215 writer.write(" <div class='dialogues'>\n");
216 inDialogue = true;
217 } else if (para.getType() != ParagraphType.QUOTE && inDialogue) {
218 writer.write(" </div>\n");
219 inDialogue = false;
220 }
221
222 if (para.getType() == ParagraphType.NORMAL && !inNormal) {
223 writer.write(" <div class='normals'>\n");
224 inNormal = true;
225 } else if (para.getType() != ParagraphType.NORMAL && inNormal) {
226 writer.write(" </div>\n");
227 inNormal = false;
228 }
229
230 switch (para.getType()) {
231 case BLANK:
232 writer.write(" <div class='blank'></div>");
233 break;
234 case BREAK:
235 writer.write(" <hr class='break'/>");
236 break;
237 case NORMAL:
238 writer.write(" <span class='normal'>");
239 break;
240 case QUOTE:
241 writer.write(" <div class='dialogue'>&mdash; ");
242 break;
243 case IMAGE:
244 File file = new File(images, getCurrentImageBestName(false));
245 Instance.getCache().saveAsImage(para.getContentImage(), file,
246 nextParaIsCover);
247 writer.write(" <img alt='page image' class='page-image' src='images/"
248 + getCurrentImageBestName(false) + "'/>");
249 break;
250 }
251
252 nextParaIsCover = false;
253 }
254
255 @Override
256 protected void writeParagraphFooter(Paragraph para) throws IOException {
257 switch (para.getType()) {
258 case NORMAL:
259 writer.write("</span>\n");
260 break;
261 case QUOTE:
262 writer.write("</div>\n");
263 break;
264 default:
265 writer.write("\n");
266 break;
267 }
268 }
269
270 @Override
271 protected void writeTextLine(ParagraphType type, String line)
272 throws IOException {
273 switch (type) {
274 case QUOTE:
275 case NORMAL:
276 writer.write(decorateText(StringUtils.xmlEscape(line)));
277 break;
278 default:
279 break;
280 }
281 }
282
283 @Override
284 protected String enbold(String word) {
285 return "<strong>" + word + "</strong>";
286 }
287
288 @Override
289 protected String italize(String word) {
290 return "<emph>" + word + "</emph>";
291 }
292
293 private String generateNcx(Story story) {
294 StringBuilder builder = new StringBuilder();
295
296 String title = "";
297 String uuid = "";
298 String author = "";
299 if (story.getMeta() != null) {
300 MetaData meta = story.getMeta();
301 uuid = meta.getUuid();
302 author = meta.getAuthor();
303 title = meta.getTitle();
304 }
305
306 builder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
307 builder.append("\n<!DOCTYPE ncx");
308 builder.append("\nPUBLIC \"-//NISO//DTD ncx 2005-1//EN\" \"http://www.daisy.org/z3986/2005/ncx-2005-1.dtd\">");
309 builder.append("\n<ncx xmlns=\"http://www.daisy.org/z3986/2005/ncx/\" version=\"2005-1\">");
310 builder.append("\n <head>");
311 builder.append("\n <!--The following four metadata items are required for all");
312 builder.append("\n NCX documents, including those conforming to the relaxed");
313 builder.append("\n constraints of OPS 2.0-->");
314 builder.append("\n <meta name=\"dtb:uid\" content=\""
315 + StringUtils.xmlEscapeQuote(uuid) + "\"/>");
316 builder.append("\n <meta name=\"dtb:depth\" content=\"1\"/>");
317 builder.append("\n <meta name=\"dtb:totalPageCount\" content=\"0\"/>");
318 builder.append("\n <meta name=\"dtb:maxPageNumber\" content=\"0\"/>");
319 builder.append("\n <meta name=\"epub-creator\" content=\""
320 + StringUtils.xmlEscapeQuote(EPUB_CREATOR) + "\"/>");
321 builder.append("\n </head>");
322 builder.append("\n <docTitle>");
323 builder.append("\n <text>" + StringUtils.xmlEscape(title) + "</text>");
324 builder.append("\n </docTitle>");
325 builder.append("\n <docAuthor>");
326
327 builder.append("\n <text>" + StringUtils.xmlEscape(author) + "</text>");
328 builder.append("\n </docAuthor>");
329 builder.append("\n <navMap>");
330 builder.append("\n <navPoint id=\"navpoint-1\" playOrder=\"1\">");
331 builder.append("\n <navLabel>");
332 builder.append("\n <text>Title Page</text>");
333 builder.append("\n </navLabel>");
334 builder.append("\n <content src=\"title.xhtml\"/>");
335 builder.append("\n </navPoint>");
336
337 int navPoint = 2; // 1 is above
338
339 if (story.getMeta() != null & story.getMeta().getResume() != null) {
340 Chapter chap = story.getMeta().getResume();
341 generateNcx(chap, builder, navPoint++);
342 }
343
344 for (Chapter chap : story) {
345 generateNcx(chap, builder, navPoint++);
346 }
347
348 builder.append("\n </navMap>");
349 builder.append("\n</ncx>\n");
350
351 return builder.toString();
352 }
353
354 private void generateNcx(Chapter chap, StringBuilder builder, int navPoint) {
355 String name;
356 if (chap.getName() != null && !chap.getName().isEmpty()) {
357 name = Instance.getTrans().getString(StringId.CHAPTER_NAMED,
358 chap.getNumber(), chap.getName());
359 } else {
360 name = Instance.getTrans().getString(StringId.CHAPTER_UNNAMED,
361 chap.getNumber());
362 }
363
364 String nnn = String.format("%03d", (navPoint - 2));
365
366 builder.append("\n <navPoint id=\"navpoint-" + navPoint
367 + "\" playOrder=\"" + navPoint + "\">");
368 builder.append("\n <navLabel>");
369 builder.append("\n <text>" + name + "</text>");
370 builder.append("\n </navLabel>");
371 builder.append("\n <content src=\"chapter-" + nnn + ".xhtml\"/>");
372 builder.append("\n </navPoint>\n");
373 }
374
375 private String generateOpf(Story story) {
376 StringBuilder builder = new StringBuilder();
377
378 String title = "";
379 String uuid = "";
380 String author = "";
381 String date = "";
382 String publisher = "";
383 String subject = "";
384 String source = "";
385 String lang = "";
386 if (story.getMeta() != null) {
387 MetaData meta = story.getMeta();
388 title = meta.getTitle();
389 uuid = meta.getUuid();
390 author = meta.getAuthor();
391 date = meta.getDate();
392 publisher = meta.getPublisher();
393 subject = meta.getSubject();
394 source = meta.getSource();
395 lang = meta.getLang();
396 }
397
398 builder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
399 builder.append("\n<package xmlns=\"http://www.idpf.org/2007/opf\" unique-identifier=\"BookId\" version=\"2.0\">");
400 builder.append("\n <metadata xmlns:opf=\"http://www.idpf.org/2007/opf\"");
401 builder.append("\n xmlns:dc=\"http://purl.org/dc/elements/1.1/\">");
402 builder.append("\n <dc:title>" + StringUtils.xmlEscape(title)
403 + "</dc:title>");
404 builder.append("\n <dc:creator opf:role=\"aut\" opf:file-as=\""
405 + StringUtils.xmlEscapeQuote(author) + "\">"
406 + StringUtils.xmlEscape(author) + "</dc:creator>");
407 builder.append("\n <dc:date opf:event=\"original-publication\">"
408 + StringUtils.xmlEscape(date) + "</dc:date>");
409 builder.append("\n <dc:publisher>"
410 + StringUtils.xmlEscape(publisher) + "</dc:publisher>");
411 builder.append("\n <dc:date opf:event=\"epub-publication\"></dc:date>");
412 builder.append("\n <dc:subject>" + StringUtils.xmlEscape(subject)
413 + "</dc:subject>");
414 builder.append("\n <dc:source>" + StringUtils.xmlEscape(source)
415 + "</dc:source>");
416 builder.append("\n <dc:rights>Not for commercial use.</dc:rights>");
417 builder.append("\n <dc:identifier id=\"BookId\" opf:scheme=\"URI\">"
418 + StringUtils.xmlEscape(uuid) + "</dc:identifier>");
419 builder.append("\n <dc:language>" + StringUtils.xmlEscape(lang)
420 + "</dc:language>");
421 builder.append("\n </metadata>");
422 builder.append("\n <manifest>");
423 builder.append("\n <!-- Content Documents -->");
424 builder.append("\n <item id=\"titlepage\" href=\"title.xhtml\" media-type=\"application/xhtml+xml\"/>");
425 for (int i = 0; i <= story.getChapters().size(); i++) {
426 String name = String.format("%s%03d", "chapter-", i);
427 builder.append("\n <item id=\""
428 + StringUtils.xmlEscapeQuote(name) + "\" href=\""
429 + StringUtils.xmlEscapeQuote(name)
430 + ".xhtml\" media-type=\"application/xhtml+xml\"/>");
431 }
432
433 builder.append("\n <!-- CSS Style Sheets -->");
434 builder.append("\n <item id=\"style-css\" href=\"css/style.css\" media-type=\"text/css\"/>");
435
436 builder.append("\n <!-- Images -->");
437
438 if (story.getMeta() != null && story.getMeta().getCover() != null) {
439 String format = Instance.getConfig()
440 .getString(Config.IMAGE_FORMAT_COVER).toLowerCase();
441 builder.append("\n <item id=\"cover\" href=\"images/cover."
442 + format + "\" media-type=\"image/png\"/>");
443 }
444
445 builder.append("\n <!-- NCX -->");
446 builder.append("\n <item id=\"ncx\" href=\"epb.ncx\" media-type=\"application/x-dtbncx+xml\"/>");
447 builder.append("\n </manifest>");
448 builder.append("\n <spine toc=\"ncx\">");
449 builder.append("\n <itemref idref=\"titlepage\" linear=\"yes\"/>");
450 for (int i = 0; i <= story.getChapters().size(); i++) {
451 String name = String.format("%s%03d", "chapter-", i);
452 builder.append("\n <itemref idref=\""
453 + StringUtils.xmlEscapeQuote(name) + "\" linear=\"yes\"/>");
454 }
455 builder.append("\n </spine>");
456 builder.append("\n</package>\n");
457
458 return builder.toString();
459 }
460
461 private String generateTitleXml(Story story) {
462 StringBuilder builder = new StringBuilder();
463
464 String title = "";
465 String tags = "";
466 String author = "";
467 if (story.getMeta() != null) {
468 MetaData meta = story.getMeta();
469 title = meta.getTitle();
470 if (meta.getTags() != null) {
471 for (String tag : meta.getTags()) {
472 if (!tags.isEmpty()) {
473 tags += ", ";
474 }
475 tags += tag;
476 }
477
478 if (!tags.isEmpty()) {
479 tags = "(" + tags + ")";
480 }
481 }
482 author = meta.getAuthor();
483 }
484
485 String format = Instance.getConfig()
486 .getString(Config.IMAGE_FORMAT_COVER).toLowerCase();
487
488 builder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
489 builder.append("\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">");
490 builder.append("\n<html xmlns=\"http://www.w3.org/1999/xhtml\">");
491 builder.append("\n<head>");
492 builder.append("\n <title>" + StringUtils.xmlEscape(title) + "</title>");
493 builder.append("\n <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\"/>");
494 builder.append("\n</head>");
495 builder.append("\n<body>");
496 builder.append("\n <div class=\"titlepage\">");
497 builder.append("\n <h1>" + StringUtils.xmlEscape(title) + "</h1>");
498 builder.append("\n <div class=\"type\">"
499 + StringUtils.xmlEscape(tags) + "</div>");
500 builder.append("\n <div class=\"cover\">");
501 builder.append("\n <img alt=\"cover image\" src=\"images/cover."
502 + format + "\"></img>");
503 builder.append("\n </div>");
504 builder.append("\n <div class=\"author\">"
505 + StringUtils.xmlEscape(author) + "</div>");
506 builder.append("\n </div>");
507 builder.append("\n</body>");
508 builder.append("\n</html>\n");
509
510 return builder.toString();
511 }
512 }