-
Notifications
You must be signed in to change notification settings - Fork 0
/
episode.go
426 lines (362 loc) · 10.6 KB
/
episode.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
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
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
// Episode represents internal data related to each episode of the podcast.
type Episode struct {
// Show information
showTitle string
showArtist string
showImage string
// Episode information
Title string `xml:"title"`
Season string `xml:"season"`
Number string `xml:"episode"`
Image string `xml:"image,href"`
Desc string `xml:"description"`
Date string `xml:"pubDate"`
Enclosure struct {
URL string `xml:"url,attr"`
Size string `xml:"length,attr"`
Type string `xml:"type,attr"`
} `xml:"enclosure"`
// Objects to handle reading/writing
meta *Meta // Metadata object
w io.Writer // Writer that will handle writing the file.
}
// Download downloads the episode. The bytes will stream through this path from web to disk:
// Internet -> http object -> Episode object -> Disk
// \-> Progress object \-> Meta object
func (e *Episode) Download(showDir string) error {
if showDir == "" {
return fmt.Errorf("missing download directory")
}
if err := e.validateData(); err != nil {
return err
}
filename := e.buildFilename(showDir)
Debug("Saving episode to", filename)
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
resp, err := http.Get(e.Enclosure.URL)
if err != nil {
os.Remove(filename)
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
os.Remove(filename)
return fmt.Errorf("%v", resp.Status)
}
bar := Progress{total: int(resp.ContentLength), totalString: Reduce(int(resp.ContentLength))}
tee := io.TeeReader(resp.Body, &bar)
// Connect the episode on both ends of the flow.
e.meta = NewMeta(nil)
e.w = file
Debug("Beginning download process")
_, err = io.Copy(e, tee)
if err != nil {
Debug("I/O Copy error:", err)
os.Remove(filename)
bar.Finish()
return err
}
return bar.Finish()
}
// Write first constructs and then writes the episode's metadata and then passes all remaining data on to the next layer.
func (e *Episode) Write(p []byte) (int, error) {
if e == nil {
return 0, fmt.Errorf("invalid episode object")
} else if e.w == nil {
return 0, fmt.Errorf("invalid writer")
}
consumed := 0
if !e.meta.Buffered() {
// Continue buffering metadata.
n, err := e.meta.Write(p)
if err != io.EOF {
// Either more data is needed or there was an error writing the metadata.
return n, err
}
// All metadata has been written. The rest of the bytes are filedata.
consumed = n
// Now that we have all of the metadata, let's build it with the additional data from the episode and write
// everything to disk.
e.addFrames()
metadata := e.meta.Build()
if n, err := e.w.Write(metadata); err != nil {
return consumed, err
} else if n != len(metadata) {
return consumed, fmt.Errorf("failed to write complete metadata")
}
// Metadata has been written. At this point, the next bytes are audio data. Let's do a quick sanity check that
// they start with 0x00 like they should.
if consumed < len(p) && p[consumed] != 0x00 {
Debug("Possible data corruption: Audio data does not start with 0x00")
}
}
// If we're here, then all metadata has been successfully written. We can resume with writing the file data now.
n, err := e.w.Write(p[consumed:])
return consumed + n, err
}
// SetShowTitle sets the title of the episode's show.
func (e *Episode) SetShowTitle(title string) {
if e != nil {
e.showTitle = title
}
}
// SetShowArtist sets the artist of the episode's show.
func (e *Episode) SetShowArtist(artist string) {
if e != nil {
e.showArtist = artist
}
}
// SetShowImage sets the image link of the episode's show. If no image is found for the episode, it will default to the
// value set here.
func (e *Episode) SetShowImage(image string) {
if e != nil {
e.showImage = image
}
}
// NumberFormatted parses the season and episode numbers and (if present) formats them according to
// the configured minimum width prefix (if any).
func (e *Episode) NumberFormatted() string {
if e == nil {
return ""
}
s := e.Season
if e.Number != "" {
if n, err := strconv.ParseInt(e.Number, 10, 0); err == nil {
formatted := fmt.Sprintf("%0*v", PrefixMinWidth, n)
if s == "" {
s = formatted
} else {
s += "-" + formatted
}
} else {
Debug("Error parsing episode number:", err)
}
}
return s
}
// addFrames fleshes out the metadata with information from the episode. If a frame already exists in the metadata, it
// will not be overwritten with data from the RSS feed. The only exceptions to this rule are the show and episode
// titles, which must match the data from the RSS feed to sync properly.
func (e *Episode) addFrames() {
Debug("Building metadata frames")
// Get the version, defaulting to ID3v2.3.
version := e.meta.Version()
switch version {
case 2, 3, 4:
// All good.
case 0:
version = 3
default:
Debug("Version", version, "is not currently supported")
return
}
// Always use the show and episode title from the RSS feed.
if e.meta.Version() == 2 {
e.meta.SetValue("TAL", []byte(e.showTitle), false)
e.meta.SetValue("TT2", []byte(e.Title), false)
} else {
e.meta.SetValue("TALB", []byte(e.showTitle), false)
e.meta.SetValue("TIT2", []byte(e.Title), false)
}
// Get the episode's timestamp.
ts := parseDate(e.Date)
frames := []struct {
idv2 string // ID3v2.2 frame ID
idv3 string // ID3v2.3 frame ID
idv4 string // ID3v2.4 frame ID
value string
}{
// Show information
{"TP1", "TPE1", "TPE1", e.showArtist}, // Artist
{"TP2", "TPE2", "TPE2", e.showArtist}, // Album Artist
// Episode information
{"TPA", "TPOS", "TPOS", e.Season}, // Season number
{"TRK", "TRCK", "TRCK", e.Number}, // Episode number
{"TT3", "TDES", "TDES", e.Desc}, // Description
{"WAF", "WOAF", "WOAF", e.Enclosure.URL}, // Download link
// Dates
{"TYE", "TYER", "", ts.Format("2006")}, // YYYY
{"TDA", "TDAT", "", ts.Format("0201")}, // DDMM
{"TIM", "TIME", "", ts.Format("1504")}, // HHMM
{"", "", "TDRC", ts.Format("20060102T150405")}, // YYYYMMDDTHHMMSS
// Defaults
{"TT1", "TCON", "TCON", "Podcast"},
{"", "PCST", "PCST", "1"},
}
// Set these frames from the table above if a value is not already present.
for _, frame := range frames {
var id string
switch version := e.meta.Version(); version {
case 2:
id = frame.idv2
case 3:
id = frame.idv3
case 4:
id = frame.idv4
}
if id == "" || frame.value == "" {
continue
}
if values := e.meta.GetValues(id); values == nil || len(values) == 0 {
e.meta.SetValue(id, []byte(frame.value), false)
}
}
// If the episode has an image, we'll add that. Otherwise, we'll try to get the default image of the show.
imageID := "APIC"
if version == 2 {
imageID = "PIC"
}
if values := e.meta.GetValues(imageID); values == nil || len(values) == 0 {
image := e.downloadImage()
if image != nil {
e.meta.SetValue(imageID, image, false)
}
}
}
// validateData checks that we have all of the required fields from the RSS feed.
func (e *Episode) validateData() error {
if e == nil {
return fmt.Errorf("cannot validata data: bad episode object")
}
Debug("Validating episode title:", e.Title)
if e.Title == "" {
return fmt.Errorf("missing episode title")
}
Debug("Validating episode link:", e.Enclosure.URL)
if e.Enclosure.URL == "" {
return fmt.Errorf("missing download link")
}
Debug("Validating episode number:", e.Number)
if e.Number == "" {
Debug("No episode number found")
}
return nil
}
// buildFilename pieces together the different components of the episode into one absolute-path filename.
// TODO: Add better logic to determine if the episode/season number is already present.
func (e *Episode) buildFilename(path string) string {
// Get the name of this episode.
base := SanitizeTitle(e.Title)
// Add an episode/season number prefix if not already present.
if prefix := e.NumberFormatted(); prefix != "" {
if !strings.HasPrefix(base, prefix) {
base = prefix + " " + base
}
}
// Add a filetype suffix if not already present.
ext := mimeToExt(e.Enclosure.Type)
if !strings.HasSuffix(base, ext) {
base += ext
}
return filepath.Join(path, base)
}
// parseDate parses the provided publish date and converts it into a timestamp.
func parseDate(date string) time.Time {
if date == "" {
return time.Time{}
}
formats := []string{
"Mon, 02 Jan 2006 15:04:05 -0700",
"Mon, 02 Jan 2006 15:04:05 MST",
}
for i, format := range formats {
if ts, err := time.Parse(format, date); err != nil {
Debug("Error parsing time with format", i, "-", err)
} else {
return ts
}
}
// If we're here, then none of the formats worked.
Debug("Failed to match format to date:", date)
return time.Time{}
}
// downloadImage downloads either the episode (preferred) or show (fallback) image and build the APIC tag with the data.
// If no link exists or there's any trouble downloading the image, this return nil.
func (e *Episode) downloadImage() []byte {
if e == nil {
return nil
}
Debug("Downloading image")
var u *url.URL
var err error
if e.Image != "" {
u, err = url.Parse(e.Image)
} else if e.showImage != "" {
u, err = url.Parse(e.showImage)
} else {
Debug("No episode or show image to download")
return nil
}
if u == nil || err != nil {
Debug("Error parsing episode/show image link")
return nil
}
resp, err := http.Get(u.String())
if err != nil {
Debug("Error getting image information:", err)
return nil
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
Debug("Error accessing image:", resp.StatusCode)
return nil
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
Debug("Error retrieving image:", err)
return nil
}
buf := new(bytes.Buffer)
// MIME type. We are going to explicitly not set this so that the image can set its own type internally.
buf.WriteByte(0x00)
// Picture type (hardcoded as "Cover (front)")
buf.WriteByte(0x03)
// Description (skipped)
buf.WriteByte(0x00)
// Picture data
buf.Write(data)
return buf.Bytes()
}
// mimeToExt finds the appropriate file extension based on the MIME type.
func mimeToExt(mime string) string {
var ext string
switch mime {
case "audio/aac":
ext = ".aac"
case "audio/midi", "audio/x-midi":
ext = ".midi"
case "audio/mpeg", "audio/mp3":
ext = ".mp3"
case "audio/ogg":
ext = ".oga"
case "audio/opus":
ext = ".opus"
case "audio/wav":
ext = ".wav"
case "audio/webm":
ext = ".weba"
default:
// If we can't match a specific type, we'll default to mp3.
ext = ".mp3"
}
Debug("Mapping MIME type", mime, "to extension", ext)
return ext
}