-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFeed.js
69 lines (50 loc) · 1.49 KB
/
Feed.js
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
import request from 'request'
import sanitize from 'sanitize-filename'
import path from 'path'
import fs from 'fs'
import moment from 'moment'
import FeedConfig from './FeedConfig'
import podcastXML from './request'
export default class Feed {
constructor( url, folder ) {
this.url = url
this.folder = folder
}
async download() {
let config = new FeedConfig(this.folder)
let podcast = await podcastXML(this.url)
for (var i = 0; i < podcast.episodes.length; i++) {
var current = podcast.episodes[i]
if (config.isDownloaded(current.guid)) {
//console.log("skip " + current.guid)
continue
}
let media = await this.downloadAudio(current.enclosure.url)
let filename = this.buildFilename(current)
this.saveFile(media, filename)
console.log("save " + filename)
config.add({ ...current, filename })
}
config.save()
}
buildFilename(episode) {
let dt = moment(episode.published.getTime()).format('YYYY-MM-DD')
return dt + ' ' + sanitize(episode.title) + '.mp3'
}
downloadAudio(url) {
return new Promise((resolve, reject) => {
request({
url,
encoding: null
}, (err, res, data) => {
err ? reject(err) : resolve(data)
})
})
}
saveFile(data, filename) {
let fpath = path.join(this.folder, filename)
fs.writeFileSync(fpath, data, (err) => {
console.error(err)
})
}
}