/
epub.go
179 lines (150 loc) · 4.57 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
package epubgen
import (
"errors"
"os"
"path"
"sync"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/bmaupin/go-epub"
"github.com/go-shiori/go-readability"
"github.com/nikhil1raghav/kindle-send/config"
"github.com/nikhil1raghav/kindle-send/util"
)
type epubmaker struct {
Epub *epub.Epub
downloads map[string]string
}
func NewEpubmaker(title string) *epubmaker {
downloadMap := make(map[string]string)
return &epubmaker{
Epub: epub.NewEpub(title),
downloads: downloadMap,
}
}
func fetchReadable(url string) (readability.Article, error) {
return readability.FromURL(url, 30*time.Second)
}
//Point remote image link to downloaded image
func (e *epubmaker) changeRefs(i int, img *goquery.Selection) {
img.RemoveAttr("loading")
img.RemoveAttr("srcset")
imgSrc, exists := img.Attr("src")
if exists {
if _, ok := e.downloads[imgSrc]; ok {
util.Green.Printf("Setting img src from %s to %s \n", imgSrc, e.downloads[imgSrc])
img.SetAttr("src", e.downloads[imgSrc])
}
}
}
//Download images and add to epub zip
func (e *epubmaker) downloadImages(i int, img *goquery.Selection) {
util.CyanBold.Println("Downloading Images")
imgSrc, exists := img.Attr("src")
if exists {
//don't download same thing twice
if _, ok := e.downloads[imgSrc]; ok {
return
}
//pass unique and safe image names here, then it will not crash on windows
//use murmur hash to generate file name
imageFileName:=util.GetHash(imgSrc)
imgRef, err := e.Epub.AddImage(imgSrc, imageFileName)
if err != nil {
util.Red.Printf("Couldn't add image %s : %s\n", imgSrc, err)
return
} else {
util.Green.Printf("Downloaded image %s\n", imgSrc)
e.downloads[imgSrc] = imgRef
}
}
}
//Fetches images in article and then embeds them into epub
func (e *epubmaker) embedImages(wg *sync.WaitGroup, article *readability.Article) {
util.Cyan.Println("Embedding images in ", article.Title)
defer wg.Done()
//TODO: Compress images before embedding to improve size
doc := goquery.NewDocumentFromNode(article.Node)
//download all images
doc.Find("img").Each(e.downloadImages)
//Change all refs, doing it in two phases to download repeated images only once
doc.Find("img").Each(e.changeRefs)
content, err := doc.Html()
if err != nil {
util.Red.Printf("Error converting modified %s to HTML, it will be transferred without images : %s \n", article.Title, err)
} else {
article.Content = content
}
}
//TODO: Look for better formatting, this is bare bones
func prepare(article *readability.Article) string {
return "<h1>" + article.Title + "</h1>" + article.Content
}
//Add articles to epub
func (e *epubmaker) addContent(articles *[]readability.Article) error {
added := 0
for _, article := range *articles {
_, err := e.Epub.AddSection(prepare(&article), article.Title, "", "")
if err != nil {
util.Red.Printf("Couldn't add %s to epub : %s", article.Title, err)
} else {
added++
}
}
util.Green.Printf("Added %d articles\n", added)
if added == 0 {
return errors.New("No article was added, epub creation failed")
}
return nil
}
//Generates a single epub from a slice of urls, returns file path
func Make(pageUrls []string, title string) (string, error) {
//TODO: Parallelize fetching pages
//Get readable article from urls
readableArticles := make([]readability.Article, 0)
for _, pageUrl := range pageUrls {
article, err := fetchReadable(pageUrl)
if err != nil {
util.Red.Printf("Couldn't convert %s because %s", pageUrl, err)
util.Magenta.Println("SKIPPING ", pageUrl)
continue
}
util.Green.Printf("Fetched %s --> %s\n", pageUrl, article.Title)
readableArticles = append(readableArticles, article)
}
if len(readableArticles) == 0 {
return "", errors.New("No readable url given, exiting without creating epub")
}
if len(title) == 0 {
title = readableArticles[0].Title
util.Magenta.Printf("No title supplied, inheriting title of first readable article : %s \n", title)
}
book := NewEpubmaker(title)
//get images and embed them
var wg sync.WaitGroup
for i := 0; i < len(readableArticles); i++ {
wg.Add(1)
go book.embedImages(&wg, &readableArticles[i])
}
wg.Wait()
err := book.addContent(&readableArticles)
if err != nil {
return "", err
}
var storeDir string
if len(config.GetInstance().StorePath) == 0 {
storeDir, err = os.Getwd()
if err != nil {
util.Red.Println("Error getting current directory, trying fallback")
storeDir = "./"
}
} else {
storeDir = config.GetInstance().StorePath
}
filename := path.Join(storeDir, title+".epub")
err = book.Epub.Write(filename)
if err != nil {
return "", err
}
return filename, nil
}