-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathindex.js
494 lines (398 loc) · 11.6 KB
/
index.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
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
const fetch = require('isomorphic-fetch')
const parseString = require('xml2js').parseString
const ERRORS = exports.ERRORS = {
'parsingError' : new Error("Parsing error."),
'requiredError' : new Error("One or more required values are missing from feed."),
'fetchingError' : new Error("Fetching error."),
'optionsError' : new Error("Invalid options.")
}
/*
============================================
=== DEFAULT OPTIONS and OPTIONS BUILDING ===
============================================
*/
const DEFAULT = exports.DEFAULT = {
fields: {
meta: ['title', 'description', 'subtitle', 'imageURL', 'lastUpdated', 'link',
'language', 'editor', 'author', 'summary', 'categories', 'owner',
'explicit', 'complete', 'blocked'],
episodes: ['title', 'description', 'subtitle', 'imageURL', 'pubDate',
'link', 'language', 'enclosure', 'duration', 'summary', 'blocked',
'explicit', 'order']
},
required: {
meta: [],
episodes: []
},
uncleaned: {
meta: [],
episodes: []
}
}
// from https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items
function mergeDedupe(arr)
{
return [...new Set([].concat(...arr))];
}
const buildOptions = exports.buildOptions = function (params) {
try {
// default options
// tried to accomplish this by referencing the DEFAULT object,
// but ran into problems with mutation when doing Object.assign(options[key], params[key])
let options = {
fields: {
meta: ['title', 'description', 'subtitle', 'imageURL', 'lastUpdated', 'link',
'language', 'editor', 'author', 'summary', 'categories', 'owner',
'explicit', 'complete', 'blocked'],
episodes: ['title', 'description', 'subtitle', 'imageURL', 'pubDate',
'link', 'language', 'enclosure', 'duration', 'summary', 'blocked',
'explicit', 'order']
},
required: {
meta: [],
episodes: []
},
uncleaned: {
meta: [],
episodes: []
}
}
// if no options parameters given, use default
if (typeof params === 'undefined') {
options = DEFAULT
return options
}
// merge empty options and given options
Object.keys(options).forEach( key => {
if (params[key] !== undefined) {
Object.assign(options[key], params[key])
}
})
// if 'default' given in parameters, merge default options with given custom options
// and dedupe
if (options.fields.meta.includes('default')) {
options.fields.meta = mergeDedupe([DEFAULT.fields.meta, params.fields.meta])
options.fields.meta.splice(options.fields.meta.indexOf('default'), 1)
}
if (options.fields.episodes.includes('default')) {
options.fields.episodes = mergeDedupe([DEFAULT.fields.episodes, params.fields.episodes])
options.fields.episodes.splice(options.fields.episodes.indexOf('default'), 1)
}
return options
} catch (err) {
throw ERRORS.optionsError
}
}
/*
=====================
=== GET FUNCTIONS ===
=====================
*/
const GET = exports.GET = {
imageURL: function (node) {
if (node.image) {
return node.image[0].url[0]
}
if (node["itunes:image"]) {
return node["itunes:image"][0]['$'].href
}
return undefined
},
subtitle: function (node) {
return node['itunes:subtitle']
},
lastUpdated: function (node) {
return node.lastBuildDate
},
editor: function (node) {
return node.managingEditor
},
author: function (node) {
return node['itunes:author']
},
summary: function (node) {
return node['itunes:summary']
},
owner: function (node) {
return node['itunes:owner']
},
explicit: function (node) {
return node['itunes:explicit']
},
complete: function (node) {
return node['itunes:complete']
},
blocked: function (node) {
return node['itunes:block']
},
order: function (node) {
return node['itunes:order']
},
guid: function (node) {
return node.guid && node.guid[0]
},
duration: function (node) {
return node['itunes:duration']
},
categories: function (node) {
// returns categories as an array containing each category/sub-category
// grouping in lists. If there is a sub-category, it is the second element
// of an array.
let categoriesArray = [];
if(node["itunes:category"] && node["itunes:category"].length > 0){
categoriesArray = node["itunes:category"].map( item => {
let category = []
category.push(item['$'].text) // primary category
if (item['itunes:category']) { // sub-category
category.push(item['itunes:category'][0]['$'].text)
}
return category
})
}
return categoriesArray
}
}
const getDefault = exports.getDefault = function (node, field) {
return (node[field]) ? node[field] : undefined
}
/*
=======================
=== CLEAN FUNCTIONS ===
=======================
*/
const CLEAN = exports.CLEAN = {
enclosure: function (object) {
return {
length: object[0]["$"].length,
type: object[0]["$"].type,
url: object[0]["$"].url
}
},
duration: function (string) {
// gives duration in seconds
let times = string[0].split(':'),
sum = 0, mul = 1
while (times.length > 0) {
sum += mul * parseInt(times.pop())
mul *= 60
}
return sum
},
owner: function (object) {
let ownerObject = {}
if (object[0].hasOwnProperty("itunes:name")) {
ownerObject.name = object[0]["itunes:name"][0]
}
if (object[0].hasOwnProperty("itunes:email")) {
ownerObject.email = object[0]["itunes:email"][0]
}
return ownerObject
},
lastUpdated: function (string) {
return new Date(string).toISOString()
},
pubDate: function (string) {
return new Date(string).toISOString()
},
guid: function (string) {
if (typeof string === 'object' && '_' in string) {
return string._
} else {
return string
}
},
complete: function (string) {
if (string[0].toLowerCase == 'yes') {
return true
} else {
return false
}
},
blocked: function (string) {
if (string.toLowerCase == 'yes') {
return true
} else {
return false
}
},
explicit: function (string) {
if (['yes', 'explicit', 'true'].includes(string[0].toLowerCase())) {
return true
} else if (['clean', 'no', 'false'].includes(string[0].toLowerCase())) {
return false
} else {
return undefined
}
},
imageURL: function (string) {
return string
}
}
const cleanDefault = exports.cleanDefault = function (node) {
// return first item of array
if (node !== undefined && node[0]!== undefined) {
return node[0]
} else {
return node
}
}
/*
=================================
=== OBJECT CREATION FUNCTIONS ===
=================================
*/
const getInfo = exports.getInfo = function (node, field, uncleaned) {
// gets relevant info from podcast feed using options:
// @field - string - the desired field name, corresponding with GET and clean
// functions
// @uncleaned - boolean - if field should not be cleaned before returning
var info;
// if field has a GET function, use that
// if not, get default value
info = (GET[field]) ? GET[field].call(this, node) : getDefault(node,field)
// if field is not marked as uncleaned, clean it using CLEAN functions
if (!uncleaned && info !== undefined) {
info = (CLEAN[field]) ? CLEAN[field].call(this, info) : cleanDefault(info)
} else {
}
return info
}
function createMetaObjectFromFeed (channel, options) {
const meta = {}
options.fields.meta.forEach( (field) => {
const obj = {}
var uncleaned = false
if (options.uncleaned && options.uncleaned.meta) {
var uncleaned = (options.uncleaned.meta.includes(field))
}
obj[field] = getInfo(channel, field, uncleaned)
Object.assign(meta, obj)
})
if (options.required && options.required.meta) {
options.required.meta.forEach( (field) => {
if (!Object.keys(meta).includes(field)) {
throw ERRORS.requiredError
}
})
}
return meta
}
// function builds episode objects from parsed podcast feed
function createEpisodesObjectFromFeed (channel, options) {
let episodes = []
channel.item.forEach( (item) => {
const episode = {}
options.fields.episodes.forEach( (field) => {
const obj = {}
var uncleaned = false
if (options.uncleaned && options.uncleaned.episodes) {
var uncleaned = (options.uncleaned.episodes.includes(field))
}
obj[field] = getInfo(item, field, uncleaned)
Object.assign(episode, obj)
})
if (options.required && options.required.episodes) {
options.required.episodes.forEach( (field) => {
if (!Object.keys(episode).includes(field)) {
throw ERRORS.requiredError
}
})
}
episodes.push(episode)
})
episodes.sort(
function (a, b) {
// sorts by order first, if defined, then sorts by date.
// if multiple episodes were published at the same time,
// they are then sorted by title
if (a.order == b.order) {
if (a.pubDate == b.pubDate) {
return a.title > b.title ? -1 : 1
}
return b.pubDate > a.pubDate ? 1 : -1
}
if (a.order && !b.order) {
return 1
}
if (b.order && !a.order) {
return -1
}
return a.order > b.order ? -1 : 1
}
)
return episodes
}
/*
======================
=== FEED FUNCTIONS ===
======================
*/
function promiseParseXMLFeed (feedText) {
return new Promise((resolve, reject) => {
parseString(feedText, (error, result) => {
if (error) { reject(ERRORS.parsingError) }
resolve(result)
})
})
}
function parseXMLFeed (feedText) {
let feed = {}
parseString(feedText, (error, result) => {
if (error) {
throw ERRORS.parsingError
}
Object.assign(feed, result)
return result
})
return (feed)
}
async function fetchFeed (url) {
try {
const feedResponse = await fetch(url)
const feedText = await feedResponse.text()
const feedObject = await promiseParseXMLFeed(feedText)
return feedObject
} catch (err) {
throw ERRORS.fetchingError
}
}
/*
=======================
=== FINAL FUNCTIONS ===
=======================
*/
const getPodcastFromURL = exports.getPodcastFromURL = async function (url, params) {
try {
const options = buildOptions(params)
const feedResponse = await fetchFeed(url)
const channel = feedResponse.rss.channel[0]
if (channel["itunes:new-feed-url"]) {
const newURL = channel["itunes:new-feed-url"][0];
if (newURL != url) {
return await getPodcastFromURL(channel["itunes:new-feed-url"][0], params)
}
}
const meta = createMetaObjectFromFeed(channel, options)
const episodes = createEpisodesObjectFromFeed(channel, options)
return {meta, episodes}
}
catch (err) {
throw err
}
}
const getPodcastFromFeed = exports.getPodcastFromFeed = function (feed, params) {
try {
const options = buildOptions(params)
const feedObject = parseXMLFeed(feed)
const channel = feedObject.rss.channel[0]
if (channel["itunes:new-feed-url"]) {
console.warn("\nWarning: Feed includes \<itunes:new-feed-url\> element, which indicates that the feed being parsed may be outdated.\n")
}
const meta = createMetaObjectFromFeed(channel, options)
const episodes = createEpisodesObjectFromFeed(channel, options)
return {meta, episodes}
}
catch (err) {
throw err
}
}