-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpcd.go
322 lines (268 loc) · 7.37 KB
/
pcd.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
// Copyright © 2018 Kristof Vannotten <kristof@vannotten.be>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package pcd
import (
"bytes"
"encoding/base64"
"encoding/gob"
"fmt"
"github.com/kvannotten/pcd/rand"
"github.com/kvannotten/pcd/rss"
"github.com/pkg/errors"
"html/template"
"io"
"log"
"net/http"
"net/url"
"os"
urlpath "path"
"path/filepath"
"regexp"
"strings"
"time"
)
type Podcast struct {
ID int
Name string
Feed string
Path string
FilenameTemplate string
// Login data if there's authentication involved
Username string
Password string
// List of episodes
Episodes []Episode
}
type Episode struct {
ID int
Title string
Date string
URL string
}
var (
ErrCouldNotSync = errors.New("Could not sync podcast")
ErrRequestFailed = errors.New("Could not perform request")
ErrAccessDenied = errors.New("Access denied to feed")
ErrFilesystemError = errors.New("Could not do filesystem request")
ErrParserIssue = errors.New("Could not parse feed")
ErrEncodeError = errors.New("Could not encode feed")
ErrFeedNotFound = errors.New("Could not find feed (404)")
ErrCouldNotDownload = errors.New("Could not download episode")
ErrCouldNotReadFromCache = errors.New("Could not read episodes from cache. Perform a sync and try again.")
ErrCouldNotParseContent = errors.New("Could not parse the content from the feed")
)
func (p *Podcast) Sync() error {
client := &http.Client{}
req, err := http.NewRequest("GET", p.Feed, nil)
if err != nil {
log.Print(err)
return ErrCouldNotSync
}
if p.Username != "" {
req.SetBasicAuth(p.Username, p.Password)
}
resp, err := client.Do(req)
if err != nil {
log.Print(err)
return ErrRequestFailed
}
switch resp.StatusCode {
case http.StatusOK: // NOOP
case http.StatusForbidden, http.StatusUnauthorized:
return ErrAccessDenied
case http.StatusNotFound:
return ErrFeedNotFound
case http.StatusInternalServerError:
return ErrRequestFailed
default:
return ErrRequestFailed
}
defer resp.Body.Close()
p.Episodes, err = parseEpisodes(resp.Body)
if err != nil {
log.Print(err)
return ErrParserIssue
}
if err := os.MkdirAll(p.Path, os.ModePerm); err != nil {
log.Print(err)
return ErrFilesystemError
}
path := filepath.Join(p.Path, ".feed")
f, err := os.Create(path)
if err != nil {
log.Print(err)
return ErrFilesystemError
}
defer f.Close()
blob, err := toGOB64(p.Episodes)
if err != nil {
log.Print(err)
return ErrEncodeError
}
if _, err := io.Copy(f, blob); err != nil {
log.Print(err)
return ErrFilesystemError
}
return nil
}
func (p *Podcast) Load() error {
path := filepath.Join(p.Path, ".feed")
f, err := os.Open(path)
if err != nil {
log.Printf("Could not open feed file: %#v", err)
return ErrCouldNotReadFromCache
}
defer f.Close()
p.Episodes, err = fromGOB64(f)
if err != nil {
log.Printf("Could not decode episodes: %#v", err)
return ErrCouldNotReadFromCache
}
return nil
}
const (
titleLength = 60
)
func (p *Podcast) String() string {
var sb strings.Builder
sb.WriteString(fmt.Sprintf("All episodes of %s (id: %d)\n", p.Name, p.ID))
// find longest episode title to see if title length is smaller than titleLength
tl := 0
for _, episode := range p.Episodes {
if len(episode.Title) > tl {
tl = len(episode.Title)
}
}
if tl > titleLength {
tl = titleLength
}
for index, episode := range p.Episodes {
title := episode.Title
if len(episode.Title) > titleLength {
title = fmt.Sprintf("%s...", episode.Title[0:(titleLength-4)])
}
formatStr := fmt.Sprintf("%%-4d %%-%ds %%20s\n", tl)
sb.WriteString(fmt.Sprintf(formatStr, index+1, title, episode.Date))
}
return sb.String()
}
// Download downloads an episode in 'path'. The writer argument is optional
// and will just mirror everything written into it (useful for tracking the speed)
func (e *Episode) Download(path string, writer io.Writer, filenameTemplate string) error {
u, err := url.Parse(e.URL)
if err != nil {
log.Printf("Parse episode url failed: %#v", err)
return ErrCouldNotDownload
}
if u.Path == "" {
return ErrFilesystemError
}
// remove the query string from filename
q := u.Query()
for k := range q {
q.Del(k)
}
filename := parseFilenameTemplate(filenameTemplate, e, urlpath.Base(u.Path))
fpath := filepath.Join(path, filename)
if _, err := os.Stat(fpath); !os.IsNotExist(err) {
return ErrFilesystemError
}
res, err := http.Get(e.URL)
if err != nil {
log.Printf("Could not download episode: %#v", err)
return ErrCouldNotDownload
}
defer res.Body.Close()
if res.StatusCode != 200 {
log.Printf("Could not download episode: %#v", err)
return ErrCouldNotDownload
}
f, err := os.Create(fpath)
if err != nil {
log.Printf("Could not create file: %#v", err)
return ErrCouldNotDownload
}
defer f.Close()
var mw io.Writer
if writer != nil {
mw = io.MultiWriter(f, writer)
} else {
mw = f
}
if _, err := io.Copy(mw, res.Body); err != nil {
log.Printf("Could not write to file: %#v", err)
return ErrCouldNotDownload
}
return nil
}
func parseEpisodes(content io.Reader) ([]Episode, error) {
feed, err := rss.Parse(content)
if err != nil {
return nil, ErrCouldNotParseContent
}
var episodes []Episode
for i, item := range feed.Channel.Items {
episode := Episode{
ID: i + 1,
Title: item.Title.Title,
Date: item.Date.Date,
URL: item.Enclosure.URL,
}
episodes = append(episodes, episode)
}
return episodes, nil
}
var reservedChars = regexp.MustCompile(`[\\/<>|:&%*;]`)
func parseFilenameTemplate(filenameTemplate string, episode *Episode, parsedTitle string) string {
if filenameTemplate == "" {
filenameTemplate = "{{ .name }}"
}
templ := template.Must(template.New("filename").Parse(filenameTemplate))
b := bytes.Buffer{}
err := templ.Execute(&b, map[string]interface{}{
"name": parsedTitle,
"date": episode.Date,
"title": template.HTML(episode.Title),
"current_date": time.Now().Format("20060102150405"),
"rand": rand.String(8),
"ext": urlpath.Ext(parsedTitle),
"episode_id": episode.ID,
})
if err != nil {
return "podcast_episode"
}
return reservedChars.ReplaceAllString(b.String(), "_")
}
func toGOB64(episodes []Episode) (io.Reader, error) {
b := bytes.Buffer{}
e := gob.NewEncoder(&b)
if err := e.Encode(episodes); err != nil {
return nil, err
}
dst := bytes.Buffer{}
encoder := base64.NewEncoder(base64.StdEncoding, &dst)
encoder.Write(b.Bytes())
defer encoder.Close()
return &dst, nil
}
func fromGOB64(content io.Reader) ([]Episode, error) {
var episodes []Episode
decoder := base64.NewDecoder(base64.StdEncoding, content)
d := gob.NewDecoder(decoder)
if err := d.Decode(&episodes); err != nil {
return nil, err
}
return episodes, nil
}