-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter.go
104 lines (89 loc) · 2.02 KB
/
chapter.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 main
import (
"bytes"
"html"
"github.com/zhnxin/mobi"
)
var (
isEscape = true
isParagraph = false
LineFeed = []byte("<br/>")
PStart = []byte("<p>")
PEnd = []byte("</p>")
Blank = []byte{}
)
func SetIsEscape(flag bool) {
isEscape = flag
}
func SetIsParagraph(flag bool) {
isParagraph = flag
}
type chapterContent struct {
Title string
Content []byte
}
func (c *chapterContent) Append(content []byte) {
if !isEscape {
content = []byte(html.EscapeString(string(content)))
}
if isParagraph {
if len(content) > 1 {
c.Content = append(c.Content, bytes.Join([][]byte{PStart, content, PEnd}, Blank)...)
} else {
c.Content = append(c.Content, LineFeed...)
}
} else {
c.Content = append(c.Content, LineFeed...)
if len(content) > 1 {
c.Content = append(c.Content, content...)
}
}
}
func (c *chapterContent) SetTitle(title string) {
c.Title = title
}
func (c *chapterContent) Restore(title string) {
c.Title = title
c.Content = make([]byte, 0)
}
type Chapter struct {
content chapterContent
subChapterList []chapterContent
subLength uint
}
func NewChapter(title string) Chapter {
return Chapter{
content: chapterContent{
Title: title,
Content: []byte{},
},
subChapterList: make([]chapterContent, 0),
}
}
func (c *Chapter) Restore(title string) {
c.subLength = 0
c.content.Title = title
c.content.Content = make([]byte, 0)
c.subChapterList = make([]chapterContent, 0)
}
func (c *Chapter) AddSubChapter(title string) {
subChapter := chapterContent{
Title: title,
Content: make([]byte, 0),
}
c.subChapterList = append(c.subChapterList, subChapter)
c.subLength += 1
}
func (c *Chapter) Append(content []byte) {
if c.subLength < 1 {
c.content.Append(content)
} else {
c.subChapterList[c.subLength-1].Append(content)
}
}
func (c *Chapter) Flush(mobiWriter mobi.Builder) {
chapter := mobiWriter.NewChapter(c.content.Title, c.content.Content)
for _, content := range c.subChapterList {
chapter.AddSubChapter(content.Title, content.Content)
}
}