-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
358 lines (309 loc) · 7.73 KB
/
parser.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
package pamphlet
import (
"archive/zip"
"encoding/xml"
"errors"
"fmt"
"github.com/timsims/pamphlet/epub"
"io"
"log"
"strings"
)
const (
// Mimetype of epub file
Mimetype = "application/epub+zip"
NcxMediaType = "application/x-dtbncx+xml"
ContainerFile = "meta-inf/container.xml"
NcxFileExt = ".ncx"
)
var (
ErrRootFileNameNotFound = errors.New("root file name not found")
ErrOpfFileNotFound = errors.New("opf file not found")
ErrNotEpub = errors.New("not epub file")
ErrOpenEpub = errors.New("failed to open epub file")
)
type Parser struct {
// current epub file pointer
zipReader ZipReaderCloser
// root file of epub
rootFile *epub.RootFile
// directory of manifest files, usually same as the root file
manifestPath string
// package struct of epub, parse from xml of root file
opf *epub.Opf
// map of manifest files, key is the id attribute of the item
manifestFiles map[string]ManifestFile
// map of navPoint of chapters, it contains chapter's title, order and src
//key is the src attribute of the navPoint
toc map[string]epub.NavPoint
book *Book
}
type ManifestFile struct {
ID string
mediaType string
Href string
file *zip.File
}
func (p *Parser) parse() error {
if !p.checkMimeType() {
return ErrNotEpub
}
err := p.getRootFile()
if err != nil {
return err
}
err = p.parseRootFile()
if err != nil {
return err
}
p.cacheManifestFiles()
p.parseToc()
p.convertToBook()
return nil
}
func (p *Parser) Close() error {
return p.zipReader.Close()
}
// CheckMimeType check mimetype file of epub file
// check file mimetype exists
// check content of mimetype file is "application/epub+zip"
// return true if file is epub
func (p *Parser) checkMimeType() bool {
isValid := false
for _, f := range p.zipReader.Files() {
if f.Name == "mimetype" {
rc, err := f.Open()
if err != nil {
return isValid
}
mimetype, err := io.ReadAll(rc)
if err != nil {
return isValid
}
if strings.TrimSpace(string(mimetype)) == Mimetype {
isValid = true
}
err = rc.Close()
if err != nil {
return isValid
}
}
}
return isValid
}
// getRootFile get root file of epub
// root file is the file that contains the metadata of the epub,
// META-INF/container.xml is the file that defines the root file's name
func (p *Parser) getRootFile() error {
for _, f := range p.zipReader.Files() {
if strings.ToLower(f.Name) == ContainerFile {
rc, err := f.Open()
if err != nil {
return err
}
content, err := io.ReadAll(rc)
if err != nil {
return err
}
var container epub.Container
err = xml.Unmarshal(content, &container)
if err != nil {
return err
}
err = rc.Close()
if err != nil {
return err
}
if container.RootFile.FullPath == "" {
return ErrRootFileNameNotFound
}
p.rootFile = &container.RootFile
return nil
}
}
return ErrRootFileNameNotFound
}
// parseRootFile parse root file of epub
// root file is the file that contains the metadata of the epub
// we parse xml and get the struct of Opf
// and also determine the path of manifest files
func (p *Parser) parseRootFile() error {
for _, f := range p.zipReader.Files() {
if f.Name == p.rootFile.FullPath {
// get the manifest files path
path := strings.Split(p.rootFile.FullPath, "/")[0]
// in case the manifest files is not in the root directory
if path != p.rootFile.FullPath {
p.manifestPath = path
}
rc, err := f.Open()
if err != nil {
return err
}
content, err := io.ReadAll(rc)
if err != nil {
return err
}
var pack epub.Opf
err = xml.Unmarshal(content, &pack)
if err != nil {
return err
}
err = rc.Close()
if err != nil {
return err
}
p.opf = &pack
return nil
}
}
return ErrOpfFileNotFound
}
// parseToc parse table of content of epub
// we can get the tile of each chapters from the toc file
// toc.ncx is the default toc file name
func (p *Parser) parseToc() {
tocFile := p.getTocFile()
if tocFile != nil {
rc, err := tocFile.Open()
if err != nil {
return
}
content, err := io.ReadAll(rc)
if err != nil {
return
}
// parse toc file
var container epub.TocContainer
err = xml.Unmarshal(content, &container)
if err != nil {
log.Fatal(err)
}
err = rc.Close()
if err != nil {
log.Fatal(err)
}
// get the title of each chapter
for _, navPoint := range container.NavMap.NavPoints {
p.parseNavPoint(navPoint)
}
}
}
// getTocFile get toc file of epub
// due to the toc file can be named differently, we need to guess the toc file
func (p *Parser) getTocFile() *zip.File {
var possibleTocFiles []*zip.File
// guess toc file by media type
for _, f := range p.manifestFiles {
if f.mediaType == NcxMediaType {
return f.file
}
// guess toc file by file extension
if strings.HasSuffix(f.Href, NcxFileExt) {
possibleTocFiles = append(possibleTocFiles, f.file)
}
}
if len(possibleTocFiles) > 0 {
return possibleTocFiles[0]
}
return nil
}
func (p *Parser) parseNavPoint(navPoint epub.NavPoint) {
src := navPoint.Content.Src
// some src will have # after the file name we need to remove it
// eg: src="chapter1.html#chapter1" we need to remove the #chapter1
if strings.Contains(src, "#") {
src = strings.Split(src, "#")[0]
}
p.toc[src] = navPoint
// parse nested nav points
for _, np := range navPoint.NavPoints {
p.parseNavPoint(np)
}
}
// cacheManifestFiles associate the manifest files with the id attribute and zip.File, so we can easily access the file later
func (p *Parser) cacheManifestFiles() {
p.manifestFiles = make(map[string]ManifestFile, len(p.zipReader.Files()))
for _, item := range p.opf.Manifest.Items {
for _, f := range p.zipReader.Files() {
fileName := item.Href
// if manifestPath is not empty, then the file is in a subdirectory
if p.manifestPath != "" {
fileName = fmt.Sprintf("%s/%s", p.manifestPath, item.Href)
}
if f.Name == fileName {
p.manifestFiles[item.ID] = ManifestFile{
ID: item.ID,
mediaType: item.Media,
Href: item.Href,
file: f,
}
}
}
}
}
// convertToBook convert the epub.Opf to Book struct
func (p *Parser) convertToBook() {
meta := p.opf.MetaData
p.book = &Book{
meta.Title,
meta.Creator.Data,
meta.Language,
meta.Identifier,
meta.Publisher,
meta.Description,
meta.Subject,
meta.Date,
p.convertChapters(),
p.convertManifest(),
}
}
// convertChapters convert the epub.Spine to Chapter struct
func (p *Parser) convertChapters() []Chapter {
chapters := make([]Chapter, 0)
for _, item := range p.opf.Spine.ItemRefs {
if f, ok := p.manifestFiles[item.IDRef]; ok {
// not all chapters have reference in toc file,
//so we need to check if the chapter has title
chapterTitle := ""
order := 0
hasToc := false
if navPoint, ok := p.toc[f.Href]; ok {
chapterTitle = navPoint.NavLabel.Text
order = navPoint.PlayOrder
hasToc = true
}
chapter := Chapter{
ID: item.IDRef,
Href: f.Href,
MediaType: f.mediaType,
Title: chapterTitle,
HasToc: hasToc,
ZipFile: ZipFile{f.file},
Order: order,
}
chapters = append(chapters, chapter)
}
}
return chapters
}
// convertManifest convert the epub.Manifest to ManifestItem struct
func (p *Parser) convertManifest() []ManifestItem {
manifestItems := make([]ManifestItem, 0)
for _, item := range p.opf.Manifest.Items {
if f, ok := p.manifestFiles[item.ID]; ok {
manifestItem := ManifestItem{
ZipFile: ZipFile{f.file},
ID: item.ID,
Href: item.Href,
RealPath: f.file.Name,
MediaType: item.Media,
}
manifestItems = append(manifestItems, manifestItem)
}
}
return manifestItems
}
func (p *Parser) GetBook() *Book {
return p.book
}