-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathDocument.cs
More file actions
522 lines (462 loc) · 16.2 KB
/
Document.cs
File metadata and controls
522 lines (462 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
#region Related components
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Xml.Linq;
#endregion
#if !SIGN
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("VIEApps.Components.XUnitTests")]
#endif
namespace net.vieapps.Components.Utility.Epub
{
/// <summary>
/// Represents an .EPUB document
/// </summary>
public class Document
{
internal readonly static XNamespace OpfNS = "http://www.idpf.org/2007/opf";
internal readonly static XNamespace DcNS = "http://purl.org/dc/elements/1.1/";
readonly Metadata _metadata;
readonly Manifest _manifest;
readonly Spine _spine;
readonly Guide _guide;
readonly NCX _ncx;
readonly Container _container;
readonly Dictionary<string, int> _ids;
// several variables is just for convenience
string _tempDirectory;
string _opfDirectory;
string _metaDirectory;
/// <summary>
/// Creates new instance of .EPUB document
/// </summary>
public Document()
{
this._metadata = new Metadata();
this._manifest = new Manifest();
this._spine = new Spine();
this._guide = new Guide();
this._ncx = new NCX();
this._container = new Container();
this._ids = new Dictionary<string, int>();
// setup mandatory TOC file
this._manifest.AddItem("ncx", "toc.ncx", "application/x-dtbncx+xml");
this._spine.SetToc("ncx");
this._container.AddRootFile("OPF/content.opf", "application/oebps-package+xml");
var uuid = $"urn:uuid:{Guid.NewGuid()}";
this._ncx.SetUid(uuid);
this._metadata.AddBookIdentifier("BookId", uuid);
}
/// <summary>
/// Gets the temporary directory
/// </summary>
/// <returns></returns>
public string GetTempDirectory()
{
if (string.IsNullOrWhiteSpace(this._tempDirectory))
{
this._tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(this._tempDirectory);
}
return this._tempDirectory;
}
string GetOpfDirectory()
{
if (string.IsNullOrWhiteSpace(this._opfDirectory))
{
this._opfDirectory = Path.Combine(this.GetTempDirectory(), "OPF");
Directory.CreateDirectory(this._opfDirectory);
}
return this._opfDirectory;
}
string GetMetaDirectory()
{
if (string.IsNullOrWhiteSpace(this._metaDirectory))
{
this._metaDirectory = Path.Combine(this.GetTempDirectory(), "META-INF");
Directory.CreateDirectory(this._metaDirectory);
}
return this._metaDirectory;
}
string GetNextID(string kind)
{
string id;
if (this._ids.Keys.Contains(kind))
{
this._ids[kind] += 1;
id = kind + this._ids[kind].ToString();
}
else
{
id = kind + "1";
this._ids[kind] = 1;
}
return id;
}
/// <summary>
/// Add author of the document
/// </summary>
/// <param name="author">Human-readable full name</param>
public void AddAuthor(string author)
{
this._metadata.AddAuthor(author);
this._ncx.AddAuthor(author);
}
/// <summary>
/// Add title to epub document
/// </summary>
/// <param name="title">document's title</param>
public void AddTitle(string title)
{
this._metadata.AddTitle(title);
this._ncx.AddTitle(title);
}
/// <summary>
/// Add publisher to epub document
/// </summary>
/// <param name="publisher">document's publisher</param>
public void AddPublisher(string publisher)
=> this._metadata.AddPublisher(publisher);
/// <summary>
/// Add document translator
/// </summary>
/// <param name="name">Human-readable full name</param>
public void AddTranslator(string name)
=> this._metadata.AddTranslator(name);
/// <summary>
/// Add document contributor
/// </summary>
/// <param name="name">Human-readable full name</param>
public void AddContributor(string name)
=> this._metadata.AddContributor(name);
/// <summary>
/// Add document subject: phrase or list of keywords
/// </summary>
/// <param name="subject">Document's subject</param>
public void AddSubject(string subject)
=> this._metadata.AddSubject(subject);
/// <summary>
/// Add description of document's content
/// </summary>
/// <param name="description">Document description</param>
public void AddDescription(string description)
=> this._metadata.AddDescription(description);
/// <summary>
/// Add terms describing general categories, functions, genres, or aggregation levels for content.
/// The advised best practice is to select a value from a controlled vocabulary.
/// </summary>
/// <param name="type">document type</param>
public void AddType(string type)
=> this._metadata.AddType(type);
/// <summary>
/// Add media type or dimensions of the resource. Best practice is to use a value from a controlled vocabulary (e.g. MIME media types).
/// </summary>
/// <param name="format">document format</param>
public void AddFormat(string format)
=> this._metadata.AddFormat(format);
/// <summary>
/// Add a language of the intellectual content of the Publication.
/// </summary>
/// <param name="language">RFC3066-complient two-letter language code e.g. "en", "es", "it"</param>
public void AddLanguage(string language)
=> this._metadata.AddLanguage(language);
/// <summary>
/// Add an identifier of an auxiliary resource and its relationship to the publication.
/// </summary>
/// <param name="relation">document relation</param>
public void AddRelation(string relation)
=> this._metadata.AddRelation(relation);
/// <summary>
/// Add a statement about rights, or a reference to one.
/// </summary>
/// <param name="rights">A statement about rights, or a reference to one</param>
public void AddRights(string rights)
=> this._metadata.AddRights(rights);
/// <summary>
/// Add book identifier
/// </summary>
/// <param name="id">A string or number used to uniquely identify the resource</param>
public void AddBookIdentifier(string id)
=> this.AddBookIdentifier(id, string.Empty);
/// <summary>
/// Add book identifier
/// </summary>
/// <param name="id">A string or number used to uniquely identify the resource</param>
/// <param name="scheme">System or authority that generated or assigned the id parameter, for example "ISBN" or "DOI." </param>
public void AddBookIdentifier(string id, string scheme)
=> this._metadata.AddBookIdentifier(GetNextID("id"), id, scheme);
/// <summary>
/// Add generic metadata
/// </summary>
/// <param name="name">meta element name</param>
/// <param name="value">meta element value</param>
public void AddMetaItem(string name, string value)
=> this._metadata.AddItem(name, value);
/// <summary>
/// Add DC metadata
/// </summary>
/// <param name="name">meta element name</param>
/// <param name="value">meta element value</param>
public void AddMetaDCItem(string name, string value)
=> this._metadata.AddDCItem(name, value);
string AddEntry(string path, string type)
{
var id = this.GetNextID("id");
this._manifest.AddItem(id, path, type);
return id;
}
string AddStylesheetEntry(string path)
{
var id = this.GetNextID("stylesheet");
this._manifest.AddItem(id, path, "text/css");
return id;
}
string AddXhtmlEntry(string path, bool linear = true)
{
var id = this.GetNextID("html");
this._manifest.AddItem(id, path, "application/xhtml+xml");
this._spine.AddItemRef(id, linear);
return id;
}
string AddImageEntry(string path)
{
var id = this.GetNextID("img");
var contentType = string.Empty;
var filepath = path.ToLower();
if (filepath.EndsWith(".jpg") || filepath.EndsWith(".jpeg"))
contentType = "image/jpeg";
else if (filepath.EndsWith(".png"))
contentType = "image/png";
else if (filepath.EndsWith(".gif"))
contentType = "image/gif";
else if (filepath.EndsWith(".bmp"))
contentType = "image/bmp";
else if (filepath.EndsWith(".svg"))
contentType = "image/svg+xml";
this._manifest.AddItem(id, path, contentType);
return id;
}
void CopyFile(string path, string epubPath)
{
var fullPath = Path.Combine(this.GetOpfDirectory(), epubPath);
this.EnsureDirectoryExists(fullPath);
File.Copy(path, fullPath);
}
string EnsureDirectoryExists(string path)
{
var directory = Path.GetDirectoryName(path);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
return path;
}
void WriteFile(string epubPath, byte[] content)
{
var fullPath = Path.Combine(this.GetOpfDirectory(), epubPath);
this.EnsureDirectoryExists(fullPath);
File.WriteAllBytes(fullPath, content);
}
void WriteFile(string epubPath, string content)
{
var fullPath = Path.Combine(this.GetOpfDirectory(), epubPath);
this.EnsureDirectoryExists(fullPath);
File.WriteAllText(fullPath, content, Encoding.UTF8);
}
/// <summary>
/// Add image to document's contents
/// </summary>
/// <param name="path">Path to source image file</param>
/// <param name="epubPath">Path to image file in EPUB</param>
/// <returns>id of newly created element</returns>
public string AddImageFile(string path, string epubPath)
{
this.CopyFile(path, epubPath);
return AddImageEntry(epubPath);
}
/// <summary>
/// Add CSS file to document's contents
/// </summary>
/// <param name="path">path to source CSS file</param>
/// <param name="epubPath">path to destination file in EPUB</param>
/// <returns>id of newly created element</returns>
public string AddStylesheetFile(string path, string epubPath)
{
this.CopyFile(path, epubPath);
return this.AddStylesheetEntry(epubPath);
}
/// <summary>
/// Add primary or auxiliary (like notes) XHTML file to document's content
/// </summary>
/// <param name="path">path to source file</param>
/// <param name="epubPath">path in epub</param>
/// <param name="primary">true for primary document, false for auxiliary</param>
/// <returns>id of newly created element</returns>
public string AddXhtmlFile(string path, string epubPath, bool primary = true)
{
this.CopyFile(path, epubPath);
return this.AddXhtmlEntry(epubPath, primary);
}
/// <summary>
/// Add generic file to document's contents
/// </summary>
/// <param name="path">source file path</param>
/// <param name="epubPath">path in EPUB</param>
/// <param name="mediaType">MIME media-type, e.g. "application/octet-stream"</param>
/// <returns>id of newly added file</returns>
public string AddFile(string path, string epubPath, string mediaType)
{
this.CopyFile(path, epubPath);
return this.AddEntry(epubPath, mediaType);
}
// Data versions of AddNNN functions
/// <summary>
/// Add image file to document with specified content. Image type
/// is detected by filename's extension
/// </summary>
/// <param name="epubPath">path in EPUB</param>
/// <param name="content">file content</param>
/// <returns>id of newly added file</returns>
public string AddImageData(string epubPath, byte[] content)
{
this.WriteFile(epubPath, content);
return this.AddImageEntry(epubPath);
}
/// <summary>
/// Add CSS file to document with specified content.
/// </summary>
/// <param name="epubPath">path in EPUB</param>
/// <param name="content">file content</param>
/// <returns>id of newly added file</returns>
public string AddStylesheetData(string epubPath, string content)
{
this.WriteFile(epubPath, content);
return this.AddStylesheetEntry(epubPath);
}
/// <summary>
/// Add primary or auxiliary XHTML file to document with specified content.
/// </summary>
/// <param name="epubPath">path in EPUB</param>
/// <param name="content">file content</param>
/// <param name="primary">true if file is primary, false if auxiliary</param>
/// <returns>identifier of added file</returns>
public string AddXhtmlData(string epubPath, string content, bool primary)
{
this.WriteFile(epubPath, content);
return this.AddXhtmlEntry(epubPath, primary);
}
/// <summary>
/// Add primary XHTML file to document with specified content.
/// </summary>
/// <param name="epubPath">path in EPUB</param>
/// <param name="content">file contents</param>
/// <returns>identifier of added file</returns>
public string AddXhtmlData(string epubPath, string content)
=> this.AddXhtmlData(epubPath, content, true);
/// <summary>
/// Add generic file to document with specified content
/// </summary>
/// <param name="epubPath">path in EPUB</param>
/// <param name="content">file content</param>
/// <param name="mediaType">MIME media-type, e.g. "application/octet-stream"</param>
/// <returns>identifier of added file</returns>
public string AddData(string epubPath, byte[] content, string mediaType)
{
this.WriteFile(epubPath, content);
return this.AddEntry(epubPath, mediaType);
}
void WriteOpf(string opfFilePath)
{
var packageElement = new XElement(Document.OpfNS + "package", new XAttribute("version", "2.0"), new XAttribute("unique-identifier", "BookId"));
packageElement.Add(this._metadata.ToElement());
packageElement.Add(this._manifest.ToElement());
packageElement.Add(this._spine.ToElement());
packageElement.Add(this._guide.ToElement());
packageElement.Save(Path.Combine(this.GetOpfDirectory(), opfFilePath));
}
void WriteNcx(string ncxFilePath)
=> this._ncx.ToXmlDocument().Save(Path.Combine(this.GetOpfDirectory(), ncxFilePath));
void WriteContainer()
=> this._container.ToElement().Save(Path.Combine(this.GetMetaDirectory(), "container.xml"));
void WriteAppleiBooksDisplayOptions()
=> new XElement("display_options", new XElement("platform", new XAttribute("name", "*"), new XElement("option", new XAttribute("name", "specified-fonts"), true))).Save(Path.Combine(this.GetMetaDirectory(), "com.apple.ibooks.display-options.xml"));
/// <summary>
/// Add navigation point to top-level Table of Contents.
/// </summary>
/// <param name="label">Text of TOC entry</param>
/// <param name="content">Link to TOC entry</param>
/// <param name="playOrder">play order counter</param>
/// <returns>newly created NavPoint </returns>
public NavPoint AddNavPoint(string label, string content, int playOrder)
=> this._ncx.AddNavPoint(label, this.GetNextID("navid"), content, playOrder);
/// <summary>
/// Add reference to guide
/// </summary>
/// <param name="href">href of guide reference</param>
/// <param name="type">type of guide reference</param>
public void AddReference(string href, string type)
=> this._guide.AddReference(href, type);
/// <summary>
/// Add reference to guide
/// </summary>
/// <param name="href">href of guide reference</param>
/// <param name="type">type of guide reference</param>
/// <param name="title">title of guide reference</param>
public void AddReference(string href, string type, string title)
=> this._guide.AddReference(href, type, title);
/// <summary>
/// Generate .EPUB document and save into a specified file path
/// </summary>
/// <param name="filePath">The absolute file path to save the .EPUB document</param>
/// <param name="onSuccess">The action to callback when generated successfully</param>
/// <param name="onFailure">The action to callback when got any error</param>
public void Generate(string filePath, Action<string> onSuccess = null, Action<Exception> onFailure = null)
{
try
{
// write contents to temp directory
this.WriteOpf("content.opf");
this.WriteNcx("toc.ncx");
this.WriteContainer();
this.WriteAppleiBooksDisplayOptions();
// check to delete old .EPUB file
if (File.Exists(filePath))
try
{
File.Delete(filePath);
}
catch { }
// zip the temp directory as .EPUB file
ZipFile.CreateFromDirectory(this.GetTempDirectory(), filePath, CompressionLevel.Optimal, false, Encoding.UTF8);
// add MIME type => for working with Apple iBooks
using (var zipArchive = ZipFile.Open(filePath, ZipArchiveMode.Update))
{
var entry = zipArchive.CreateEntry("mimetype", CompressionLevel.NoCompression);
using (var writer = new StreamWriter(entry.Open()))
{
writer.WriteLine("application/epub+zip");
}
}
// callback
onSuccess?.Invoke(filePath);
}
catch (Exception ex)
{
if (onFailure != null)
onFailure(ex);
else
throw;
}
finally
{
// delete the temporary directory
try
{
Directory.Delete(this.GetTempDirectory(), true);
}
catch { }
}
}
}
}