-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathextras.go
More file actions
568 lines (464 loc) · 12.1 KB
/
Copy pathextras.go
File metadata and controls
568 lines (464 loc) · 12.1 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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
package epub
import (
"bytes"
"errors"
"image"
"image/jpeg"
"image/png"
"net/url"
"regexp"
"slices"
"unicode"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
htmltomarkdown "github.com/JohannesKaufmann/html-to-markdown/v2"
"github.com/raitucarp/epub/pkg"
"golang.org/x/net/html"
"golang.org/x/text/runes"
)
// UID returns the unique identifier of the publication. It resolves the
// package's unique-identifier attribute to the matching dc:identifier entry.
func (r *Reader) UID() (identifier string) {
pkgMetadata := r.CurrentSelectedPackage().Metadata
identifiers := pkgMetadata.Identifiers
for _, uid := range identifiers {
if uid.ID == r.CurrentSelectedPackage().UniqueIdentifier {
return uid.Value
}
}
for _, uid := range identifiers {
if uid.Value != "" {
identifier = uid.Value
}
}
return
}
// Version returns the EPUB specification version of the publication.
func (r *Reader) Version() (version string) {
return r.CurrentSelectedPackage().Version
}
var coverImagePattern = regexp.MustCompile("cover")
func (r *Reader) getCoverInMetadata() (cover *image.Image) {
metadata := r.Metadata()
if meta, ok := metadata["meta"]; ok {
metaMap, ok := meta.(map[string]any)
if !ok {
return
}
for key, value := range metaMap {
if coverImagePattern.MatchString(key) {
if resId, ok := value.(string); ok {
cover = r.ReadImageById(resId)
}
}
}
return
}
return
}
func (r *Reader) getCoverInResources() (cover *image.Image) {
resources := r.Resources()
for _, res := range resources {
if res.Properties == pkg.CoverImageProperty {
cover = r.ReadImageByHref(res.Href)
}
if cover == nil && coverImagePattern.MatchString(res.ID) {
cover = r.ReadImageByHref(res.Href)
}
}
return
}
func (r *Reader) getCoverInSpine() (cover *image.Image) {
for _, item := range r.Spine() {
if !coverImagePattern.MatchString(item.ID) {
continue
}
res := r.SelectResourceById(item.ID)
if res != nil {
cover = r.ReadImageByHref(res.Href)
}
}
return
}
func findFirstImg(n *html.Node) *html.Node {
return FindNode(n, func(node *html.Node) bool {
return node.Type == html.ElementNode && node.Data == "img"
})
}
func getImageSrc(imgNode *html.Node) (href string) {
srcIndex := slices.IndexFunc(imgNode.Attr, func(attr html.Attribute) bool { return attr.Key == "src" })
if srcIndex == -1 {
return
}
href = imgNode.Attr[srcIndex].Val
return
}
func (r *Reader) getCoverFromToc() (cover *image.Image) {
toc, err := r.TableOfContents()
if err != nil {
return
}
for _, item := range toc.Items {
if !coverImagePattern.MatchString(item.Href) {
continue
}
htmlNode := r.ReadContentHTMLByHref(item.Href)
if htmlNode == nil {
continue
}
firstImg := findFirstImg(htmlNode)
href := getImageSrc(firstImg)
cover = r.ReadImageByHref(href)
}
return
}
// Cover returns the publication's cover image if present.
func (r *Reader) Cover() (cover *image.Image) {
cover = r.getCoverInMetadata()
if cover == nil {
cover = r.getCoverInResources()
}
if cover == nil {
cover = r.getCoverInSpine()
}
if cover == nil {
cover = r.getCoverFromToc()
}
return
}
// CoverBytes returns the raw byte representation of the cover image.
// An error is returned if the publication does not define a cover.
func (r *Reader) CoverBytes() (cover []byte, err error) {
coverImage := r.Cover()
if coverImage == nil {
return nil, errors.New("no cover image defined in the publication")
}
buf := new(bytes.Buffer)
err = png.Encode(buf, *coverImage)
if err == nil {
return buf.Bytes(), err
}
buf.Reset()
err = jpeg.Encode(buf, *coverImage, &jpeg.Options{Quality: 70})
if err == nil {
return buf.Bytes(), err
}
return nil, err
}
var titlePattern = regexp.MustCompile("title")
// Title returns the publication's title metadata.
func (r *Reader) Title() []string {
var titles []string
for key, value := range r.Metadata() {
if key == "title" {
titles = append(titles, value.([]string)...)
return titles
}
}
guide := r.CurrentSelectedPackage().Guide
if guide != nil {
for _, ref := range guide.References {
if ref.Type == pkg.GuideRefTitlePage {
res := r.SelectResourceByHref(ref.Href)
if res == nil {
continue
}
htmlNode, err := r.parseHTML(res.Content)
if err != nil {
continue
}
t := getTextByEpubType(htmlNode, "title")
if t != "" {
return []string{t}
}
}
}
}
for _, ref := range r.epub.resources {
if titlePattern.MatchString(ref.ID) || titlePattern.MatchString(ref.Href) {
htmlNode, _ := r.parseHTML(ref.Content)
t := getTextByEpubType(htmlNode, "title")
if t == "" {
t = getTextByEpubType(htmlNode, "fulltitle")
}
if t != "" {
return []string{t}
}
}
}
return titles
}
// Author returns the author (creator) metadata of the publication.
func (r *Reader) Author() []string {
var authors []string
for key, value := range r.Metadata() {
if key == "creator" {
authors = append(authors, value.([]string)...)
return authors
}
}
guide := r.CurrentSelectedPackage().Guide
if guide != nil {
for _, ref := range guide.References {
if ref.Type == pkg.GuideRefTitlePage {
res := r.SelectResourceByHref(ref.Href)
if res == nil {
continue
}
htmlNode, err := r.parseHTML(res.Content)
if err != nil {
continue
}
a := getTextByEpubType(htmlNode, "author")
if a != "" {
return []string{a}
}
}
}
}
for _, ref := range r.epub.resources {
if titlePattern.MatchString(ref.ID) || titlePattern.MatchString(ref.Href) {
htmlNode, _ := r.parseHTML(ref.Content)
a := getTextByEpubType(htmlNode, "author")
if a != "" {
return []string{a}
}
}
}
if len(authors) == 0 {
return []string{"Unknown"}
}
return authors
}
// Language returns the primary language of the publication, as declared
// in the package metadata (dc:language).
func (r *Reader) Language() []string {
desc, descriptionExists := r.epub.metadata["language"]
if descriptionExists {
return desc.([]string)
}
return nil
}
// Identifier returns the primary identifier of the publication as declared
// in the package metadata (often equivalent to UID).
func (r *Reader) Identifier() []string {
desc, descriptionExists := r.epub.metadata["identifiers"]
if descriptionExists {
return desc.([]string)
}
return nil
}
var descriptionPattern = regexp.MustCompile("description")
func extractDescriptionFromMetadata(metadata map[string]any) []string {
desc, descriptionExists := metadata["description"]
if descriptionExists {
return desc.([]string)
}
return nil
}
func extractDescriptionFromOptionalMeta(metadata map[string]any) []string {
meta, metaExists := metadata["meta"]
if !metaExists {
return nil
}
metaMap, isMetaMap := meta.(map[string]any)
if !isMetaMap {
return nil
}
var allDescriptions []string
for key, value := range metaMap {
if !descriptionPattern.MatchString(key) {
continue
}
desc, isSlice := value.([]any)
if !isSlice {
continue
}
for _, d := range desc {
if v, ok := d.(string); ok {
allDescriptions = append(allDescriptions, v)
}
}
}
return allDescriptions
}
func extractDescriptionFromSummaryMeta(metadata map[string]any) []string {
meta, metaExists := metadata["meta"]
if !metaExists {
return nil
}
metaMap, isMetaMap := meta.(map[string]any)
if !isMetaMap {
return nil
}
for key, value := range metaMap {
if key != "summary" {
continue
}
desc, isSlice := value.([]any)
if !isSlice {
continue
}
for _, d := range desc {
if v, ok := d.(string); ok {
return []string{v}
}
}
}
return nil
}
func extractDescriptionFromEpubType(epubType string, htmlNode *html.Node) (description string) {
for desc := range htmlNode.Descendants() {
abstractIndex := slices.IndexFunc(desc.Attr, func(attr html.Attribute) bool {
return attr.Key == "epub:type" && attr.Val == epubType
})
if abstractIndex > -1 {
descByte, err := htmltomarkdown.ConvertNode(desc)
if err != nil {
continue
}
description = string(descByte)
}
}
return
}
var coverPagePattern = regexp.MustCompile("cover")
func (r *Reader) extractDescriptionFromSpine() []string {
spine := r.Spine()
introTypes := []string{"abstract", "foreword", "introduction", "preamble", "preface", "prologue"}
for _, res := range spine {
htmlNode := r.ReadContentHTMLByHref(res.Href)
if htmlNode == nil {
continue
}
for desc := range htmlNode.Descendants() {
abstractIndex := slices.IndexFunc(desc.Attr, func(attr html.Attribute) bool {
return attr.Key == "epub:type" && slices.Contains(introTypes, attr.Val)
})
if abstractIndex > -1 {
descByte, err := htmltomarkdown.ConvertNode(desc)
if err == nil {
return []string{string(descByte)}
}
}
}
}
return nil
}
func getBody(doc *html.Node) *html.Node {
return FindNode(doc, func(n *html.Node) bool {
return n.Type == html.ElementNode && n.Data == "body"
})
}
func (r *Reader) extractDescriptionFromReferences() []string {
refs := r.References()
candidates := []pkg.GuideReferenceType{pkg.GuideRefText, pkg.GuideRefPreface, pkg.GuideRefForeword}
var description string
for _, candidate := range candidates {
if description != "" {
continue
}
if doc, ok := refs[candidate]; ok {
body := getBody(doc)
markdownBody, _ := htmltomarkdown.ConvertNode(body)
description = string(markdownBody)
}
}
if description != "" {
return []string{description}
}
return nil
}
func (r *Reader) extractDescriptionFromFirstFullContentTOCItem() []string {
toc, err := r.TableOfContents()
if err != nil {
return nil
}
var firstContentItem TOC
for _, item := range toc.Items {
if coverPagePattern.MatchString(item.Href) {
continue
}
if firstContentItem.Title == "" {
firstContentItem = item
break
}
}
if firstContentItem.Title == "" {
return nil
}
content := r.ReadContentHTMLByHref(firstContentItem.Href)
body := getBody(content)
markdownBody, _ := htmltomarkdown.ConvertNode(body)
if len(markdownBody) > 0 {
return []string{string(markdownBody)}
}
return nil
}
func convertDescriptionToMd(description string) string {
descriptionTemp := description
newDesc, err := htmltomarkdown.ConvertString(description)
if err != nil {
description = descriptionTemp
}
description = newDesc
t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
description, _, _ = transform.String(t, description)
return description
}
// Description returns the publication's description metadata if defined.
func (r *Reader) Description() []string {
metadata := r.epub.metadata
descriptions := extractDescriptionFromMetadata(metadata)
if len(descriptions) == 0 {
descriptions = extractDescriptionFromOptionalMeta(metadata)
}
if len(descriptions) == 0 {
descriptions = extractDescriptionFromSummaryMeta(metadata)
if len(descriptions) > 0 {
descByte, err := htmltomarkdown.ConvertString(descriptions[0])
if err == nil {
descriptions[0] = string(descByte)
}
}
}
if len(descriptions) == 0 {
descriptions = r.extractDescriptionFromSpine()
}
if len(descriptions) == 0 {
descriptions = r.extractDescriptionFromReferences()
}
if len(descriptions) == 0 {
descriptions = r.extractDescriptionFromFirstFullContentTOCItem()
}
var finalDesc []string
for _, desc := range descriptions {
if desc != "" {
finalDesc = append(finalDesc, convertDescriptionToMd(desc))
}
}
return finalDesc
}
// References returns the structural guide references defined in the package,
// such as "cover", "title-page", "toc", etc. The returned map is keyed by
// reference type and mapped to corresponding HTML content.
func (r *Reader) References() (references map[pkg.GuideReferenceType]*html.Node) {
references = make(map[pkg.GuideReferenceType]*html.Node)
guides := r.epub.SelectedPackage().Guide
if guides == nil {
return
}
for _, ref := range guides.References {
u, err := url.Parse(ref.Href)
if err != nil {
continue
}
// Remove the fragment by setting it to empty string
u.Fragment = ""
// Get the string representation without fragment
cleanHref := u.String()
content := r.ReadContentHTMLByHref(cleanHref)
references[ref.Type] = content
}
return
}