-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathepub.go
474 lines (429 loc) · 13.9 KB
/
epub.go
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
// Package epub creates ePub v2.0 format ebooks.
//
// An ePub file consists of one or more XHTML files that represent
// the text of your book, the resources those files reference, and the
// optional structured metadata (such as author and publisher) for the
// book.
//
// This library doesn't do validity testing of the book file, so it's
// possible to create invalid books. Testing the output with external
// ePub validators such as ePubCheck
// (https://github.com/IDPF/epubcheck) is advisable.
//
// Structure notes
//
// All files in an ePub should be reachable, directly or indirectly,
// from the spine of the book. Books with unreferenced files are
// technically illegally formatted.
//
// It doesn't matter what order your code calls AddImage, AddXHTML,
// AddJavascript, or AddStylesheet to put files in the ePub book. Nor
// does it matter what order your code calls AddNavpoints to add files
// to the book spine.
//
// ePub files are specially formatted zip archives. You can unzip the
// resulting .epub file and inspect the contents if needed.
//
// Limitations
//
// Currently this package doesn't support adding fonts or JavaScript
// files, nor does it support encrypted or DRM'd books.
//
// By default this package writes out ePub v2.0 format files. You can
// write V3 files either by calling the WriteV3 method directly, or
// setting the epub object's version to v3 by e.SetVersion(3).
package epub
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"log"
"path/filepath"
"strconv"
"strings"
"github.com/gofrs/uuid"
img "image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
)
// EPub holds the contents of the ePub book.
type EPub struct {
version float64
metadata []metadata
images []image
xhtml []xhtml
navpoints []*Navpoint
styles []style
scripts []javascript
fonts []font
lastId map[string]int
uuid string
title string
authors []string
artists []string
// If true then do a bit of preprocessing to xhtml
// files when writing v3 format books.
fixV2XHTML bool
coverID Id
// Some V3 properties
seriesName string // The name of the series this book belongs to, if any
setName string // The name of the set this book belongs to, if any
entry string // The entry number in the series/set
}
type pair struct {
key string
// Key prefix for ePub v2 books
v2prefix string
// Key prefix for ePub v3 books
v3prefix string
value string
// Metadata scheme
scheme string
}
type metadata struct {
kind string
value string
pairs []pair
}
type style struct {
name string
contents string
id Id
}
type javascript struct {
name string
contents string
id Id
}
type font struct {
name string
contents []byte
id Id
}
type xhtml struct {
name string
contents string
id Id
order int // Explicit ordering for file
baseOrder int // Implicit order for file
}
type image struct {
name string
contents []byte
filetype string
id Id
}
// Id holds an identifier for an item that's been added to the book.
type Id string
// Navpoint represents an entry in the book's spine.
type Navpoint struct {
label string
filename string
order int
navpoints []*Navpoint
}
// NamespaceUUID is the namespace we're using for all V5 UUIDs
var NamespaceUUID = uuid.Must(uuid.FromString("443ed275-966f-4099-8bee-5a6e1e474bb4"))
// New creates a new empty ePub file.
func New() *EPub {
ret := &EPub{lastId: make(map[string]int), version: 2, fixV2XHTML: true}
u, err := uuid.NewV4()
if err != nil {
panic(fmt.Sprintf("can't create UUID: %v", err))
}
ret.uuid = "urn:uuid:" + u.String()
ret.metadata = append(ret.metadata, metadata{
kind: "dc:identifier",
value: ret.uuid,
pairs: []pair{{key: "id", value: "BookId"}},
})
return ret
}
// SetVersion sets the default version of the ePub file. Throws an
// error if an unrecognized version is specified; currently only 2 and
// 3 are recognized.
func (e *EPub) SetVersion(version float64) error {
if version != 2 && version != 3 {
return fmt.Errorf("EPub version %v is unsupported", version)
}
e.version = version
return nil
}
func (e *EPub) Version() float64 {
return e.version
}
// UUID returns the currently assigned UUID for this epub.
func (e *EPub) UUID() string {
return strings.TrimPrefix("urn:uuid:", e.uuid)
}
// SetUUID overrides the default UUID assigned to this epub. Since
// many ebook readers use the UUID to identify a book it's usually
// wise to assign the same UUID to different revisions of a book.
func (e *EPub) SetUUID(uu string) error {
u, err := uuid.FromString(uu)
if err != nil {
return err
}
e.uuid = "urn:uuid:" + u.String()
log.Printf("Setting uuid, theoretically %q", e.uuid)
for i, m := range e.metadata {
if m.kind == "dc:identifier" {
log.Printf("Set id to %q", e.uuid)
e.metadata[i].value = e.uuid
}
}
return nil
}
func (e *EPub) nextId(class string) Id {
last, ok := e.lastId[class]
if !ok {
}
last++
e.lastId[class] = last
return Id(class + strconv.Itoa(last))
}
// AddImage adds an image to the ePub book. Path is the relative path
// in the book to the image, and contents is the image itself.
//
// The library will autodetect the filetype for the image from the
// contents. Some ebook reading software infers filetype from the
// filename, so while it isn't required it is prudent to have the file
// extension match the filetype.
func (e *EPub) AddImage(path string, contents []byte) (Id, error) {
_, fmt, err := img.DecodeConfig(bytes.NewReader(contents))
if err != nil {
return "", err
}
i := image{name: path, filetype: fmt, contents: contents, id: e.nextId("img")}
e.images = append(e.images, i)
return i.id, nil
}
// AddImageRegardless adds an image to the ePub book. Path is the
// relative path in the book to the image, and contents is the image
// itself.
//
// Unlike AddImage, AddImageRegardless doesn't check the file contents
// and assumes the type from the extension. This can be an issue, as
// some ebook reading software infers filetype from the filename, so
// while it isn't required it is prudent to have the file extension
// match the filetype.
func (e *EPub) AddImageRegardless(path string, contents []byte) (Id, error) {
fmt := strings.ToLower(filepath.Ext(path))
if len(fmt) > 0 && fmt[0] == '.' {
fmt = fmt[1:]
}
// The mimetype for jpeg files is image/jpeg, so if we got jpg
// (which is legt as an extension) then jpeg it instead.
if fmt == "jpg" {
fmt = "jpeg"
}
i := image{name: path, filetype: fmt, contents: contents, id: e.nextId("img")}
e.images = append(e.images, i)
return i.id, nil
}
// AddImageFile adds an image file to the ePub book. source is the
// name of the file to be added while dest is the name the file should have
// in the ePub book.
//
// Returns the ID of the added file, or an error if something went
// wrong reading the file.
func (e *EPub) AddImageFile(source, dest string) (Id, error) {
c, err := ioutil.ReadFile(source)
if err != nil {
return "", err
}
return e.AddImage(dest, c)
}
// AddJavaScript adds a JavaScript file to the ePub book. Path is the
// relative path in the book to the javascript file, and contents is
// the JavaScript itself.
//
// Returns the ID of the added file, or an error if something went wrong.
func (e *EPub) AddJavaScript(path, contents string) (Id, error) {
j := javascript{name: path, contents: contents, id: e.nextId("js")}
e.scripts = append(e.scripts, j)
return j.id, nil
}
// AddJavaScriptFile adds the named JavaScript file to the ePub
// book. source is the name of the file to be added while dest is the
// name the file should have in the ePub book.
//
// Returns the ID of the added file, or an error if something went
// wrong reading the file.
func (e *EPub) AddJavaScriptFile(source, dest string) (Id, error) {
c, err := ioutil.ReadFile(source)
if err != nil {
return "", err
}
return e.AddJavaScript(dest, string(c))
}
// AddFont adds a font to the ePub book. Path is the relative path in
// the book to the font, and contents is the contents of the font.
//
// Returns the ID of the added file, or an error if something went wrong.
func (e *EPub) AddFont(path string, contents []byte) (Id, error) {
if !strings.HasSuffix(path, ".otf") {
return "", errors.New("Only opentype fonts are supported")
}
f := font{name: path, contents: contents, id: e.nextId("font")}
e.fonts = append(e.fonts, f)
return f.id, nil
}
// AddFontFile adds the named font to the epub book. Source is the
// name of the file to be added while dest is the name the file should
// have in the ePub book.
//
// Returns the ID of the added file, or an error if something went wrong.
func (e *EPub) AddFontFile(source, dest string) (Id, error) {
c, err := ioutil.ReadFile(source)
if err != nil {
return "", err
}
return e.AddFont(dest, c)
}
// AddXHTML adds an xhtml file to the ePub book. Path is the relative
// path to this file in the book, and contents is the contents of the
// xhtml file.
//
// By default each file appears in the book's spine in the order they
// were added. You may, if you wish, optionally specify the
// ordering. (Note that all files without an order specified get an
// implicit order of '0') If multiple files are given the same order
// then they're sub-sorted by the order they were added.
func (e *EPub) AddXHTML(path string, contents string, order ...int) (Id, error) {
if len(order) > 1 {
return "", fmt.Errorf("Too many order parameters given")
}
o := 0
if len(order) == 1 {
o = order[0]
}
x := xhtml{
name: path,
contents: contents,
id: e.nextId("xhtml"),
order: o,
baseOrder: len(e.xhtml),
}
e.xhtml = append(e.xhtml, x)
return x.id, nil
}
// AddXHTMLFile adds an xhtml file currently on-disk to the ePub
// book. source is the name of the file to add, while dest is the name
// the file should have in the ePub book.
//
// Returns the ID of the added file, or an error if something went
// wrong.
func (e *EPub) AddXHTMLFile(source, dest string, order ...int) (Id, error) {
c, err := ioutil.ReadFile(source)
if err != nil {
return "", err
}
return e.AddXHTML(dest, string(c), order...)
}
// AddNavpoint adds a top-level navpoint.
//
// Navpoints are part of the book's table of contents. The label is
// the string that will be shown in the TOC (note that many ereaders
// do *not* do HTML unescaping). Name is the URI of the point in the
// book this navpoint points to. Not every file in a book needs a
// navpoint that points to it -- all navpoints are optional.
//
// Some ereaders do not permit fragment IDs in the URI for top-level navpoints.
//
// The order parameter is used to sort the navpoints when building the
// book's TOC. Navpoints do not need to be added to the book in the
// order they appear in the TOC, the order numbers do not have to
// start from 1, and there may be gaps in the order.
//
// Note that the order that entries appear in the table of contents,
// and the order that files appear in the book, don't have to be
// related.
//
// Also note that some ereader software will elide entries from the
// book's TOC. (iBooks 1.15 on OS X, for example, won't display
// entries labeled "Cover" or "Table of Contents")
func (e *EPub) AddNavpoint(label string, name string, order int) *Navpoint {
n := &Navpoint{label: label, filename: name, order: order}
e.navpoints = append(e.navpoints, n)
return n
}
// AddNavpoint adds a child navpoint. Label is the name that will be
// shown in the TOC, name is the URI of the point in the book this
// navpoint points to, and order is the order of the navpoint in the
// TOC.
//
// Child URIs typically refer to a point in the parent Navpoint's file
// and, indeed, some ereaders require this. That is, if the parent
// navpoint has a file of "foo/bar.xhtml" the child navpoints must be
// fragments inside that file (such as "foo/bar.xhtml#Point3").
func (n *Navpoint) AddNavpoint(label string, name string, order int) *Navpoint {
nn := &Navpoint{label: label, filename: name, order: order}
n.navpoints = append(n.navpoints, nn)
return nn
}
// AddStylesheet adds a CSS stylesheet to the ePub book. Path is the
// relative path to the CSS file in the book, while contents is the
// contents of the stylesheet.
func (e *EPub) AddStylesheet(path, contents string) (Id, error) {
s := style{name: path, contents: contents, id: e.nextId("css")}
e.styles = append(e.styles, s)
return s.id, nil
}
// AddStylesheetFile adds the named file to the ePub as a CSS
// stylesheet. source is the name of the file on disk, while dest is
// the name the stylesheet has in the ePub file.
func (e *EPub) AddStylesheetFile(source, dest string) (Id, error) {
c, err := ioutil.ReadFile(source)
if err != nil {
return "", err
}
return e.AddStylesheet(dest, string(c))
}
// SetCoverImage notes which image is the cover.
//
// ePub readers will generally use this as the image displayed in the
// bookshelf. They generally will not display this image when the book
// is read; if you want the first page of your book to have this cover
// image it's best to generate an XHTML file that references the image
// and set it to be the first entry in your spine.
func (e *EPub) SetCoverImage(id Id) {
m := metadata{
kind: "meta",
pairs: []pair{
{key: "name", value: "cover"},
{key: "content", value: string(id)},
},
}
e.metadata = append(e.metadata, m)
e.coverID = id
}
// Write out the book to the named file. The book will be written
// in whichever version the epub object is tagged with. By default
// this is V2.
func (e *EPub) Write(name string) error {
log.Printf("Writing version %v", e.version)
switch e.version {
case 2:
return e.WriteV2(name)
case 3:
return e.WriteV3(name)
default:
return fmt.Errorf("Unable to write epub version %v files", e.version)
}
}
// Return a serialized version of the epub book as a byte
// slice. Useful in cases where you want the book but don't
// necessarily need a file.
func (e *EPub) Serialize() ([]byte, error) {
switch e.version {
case 2:
return e.SerializeV2()
case 3:
return e.SerializeV3()
default:
return nil, fmt.Errorf("Unable to create epub version %v files", e.version)
}
}