-
Notifications
You must be signed in to change notification settings - Fork 2
/
epub.go
104 lines (79 loc) · 1.58 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
package epub
import (
"archive/zip"
"bytes"
"io"
"io/ioutil"
"github.com/wmentor/html"
)
func Open(fn string) (*Book, error) {
fd, err := zip.OpenReader(fn)
if err != nil {
return nil, err
}
bk := Book{fd: fd}
mt, err := bk.readBytes("mimetype")
if err == nil {
bk.Mimetype = string(mt)
err = bk.readXML("META-INF/container.xml", &bk.Container)
}
if err == nil {
err = bk.readXML(bk.Container.Rootfile.Path, &bk.Opf)
}
for _, mf := range bk.Opf.Manifest {
if mf.ID == bk.Opf.Spine.Toc {
err = bk.readXML(bk.filename(mf.Href), &bk.Ncx)
break
}
}
if err != nil {
fd.Close()
return nil, err
}
return &bk, nil
}
func Reader(filename string, onChapter func(chapter string, data []byte) bool) error {
bk, err := Open(filename)
if err != nil {
return err
}
defer bk.Close()
if onChapter == nil {
return nil
}
readerF := func(filename string) ([]byte, error) {
fd, err := bk.Open(filename)
if err != nil {
return nil, err
}
defer fd.Close()
return ioutil.ReadAll(fd)
}
for _, pt := range bk.Ncx.Points {
for _, np := range pt.Points {
name := np.Text
data, err := readerF(np.Content.Src)
if err != nil {
return err
}
if !onChapter(name, data) {
return nil
}
}
}
return nil
}
func ToTxt(filename string, output io.Writer) error {
notFirst := false
return Reader(filename, func(chapter string, data []byte) bool {
parser := html.New()
parser.Parse(bytes.NewReader(data))
if notFirst {
output.Write([]byte("\n\n"))
} else {
notFirst = true
}
output.Write(parser.Text())
return true
})
}