forked from jbierfeldt/podcast-feed-parser
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
826 lines (696 loc) · 19.5 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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
require('abort-controller/polyfill')
const fetch = require('isomorphic-fetch')
const parseString = require('xml2js').parseString
const ERRORS = exports.ERRORS = {
'requiredError': new Error("One or more required values are missing from feed."),
'optionsError': new Error("Invalid options.")
}
/*
============================================
=== CONSTANTS ===
============================================
*/
const NS = rssFeedNamespaces = {
itunesAuthor: 'itunes:author',
itunesBlock: 'itunes:block',
itunesCategory: 'itunes:category',
itunesComplete: 'itunes:complete',
itunesDuration: 'itunes:duration',
itunesEmail: 'itunes:email',
itunesExplicit: 'itunes:explicit',
itunesImage: 'itunes:image',
itunesKeywords: 'itunes:keywords',
itunesName: 'itunes:name',
itunesOrder: 'itunes:order',
itunesOwner: 'itunes:owner',
itunesSubtitle: 'itunes:subtitle',
itunesSummary: 'itunes:summary',
itunesType: 'itunes:type',
podcastChapters: 'podcast:chapters',
podcastFunding: 'podcast:funding',
podcastLocked: 'podcast:locked',
podcastSoundbite: 'podcast:soundbite',
podcastTranscript: 'podcast:transcript',
podcastValue: 'podcast:value',
podcastValueRecipient: 'podcast:valueRecipient',
podcastValueTimeSplit: "podcast:valueTimeSplit",
podcastRemoteItem: "podcast:remoteItem"
}
/*
============================================
=== DEFAULT OPTIONS and OPTIONS BUILDING ===
============================================
*/
const fieldsMeta = [
'author',
'blocked',
'categories',
'complete',
'description',
'docs',
'editor',
'explicit',
'funding',
'generator',
'guid',
'imageURL',
'keywords',
'language',
'lastBuildDate',
'link',
'locked',
'pubDate',
'owner',
'subtitle',
'summary',
'title',
'type',
'value',
'webMaster'
]
const fieldsEpisodes = [
'author',
'blocked',
'chapters',
'description',
'duration',
'enclosure',
'explicit',
'funding',
'guid',
'imageURL',
'keywords',
'language',
'link',
'order',
'pubDate',
'soundbite',
'subtitle',
'summary',
'title',
'transcript',
'value'
]
const requiredMeta = []
const requiredEpisodes = []
const uncleanedMeta = [
'categories',
'funding',
'guid',
'value'
]
const uncleanedEpisodes = [
'funding',
'guid',
'soundbite',
'transcript',
'value'
]
const DEFAULT = exports.DEFAULT = {
fields: {
meta: fieldsMeta,
episodes: fieldsEpisodes
},
required: {
meta: requiredMeta,
episodes: requiredEpisodes
},
uncleaned: {
meta: uncleanedMeta,
episodes: uncleanedEpisodes
}
}
// 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 {
let options = {
fields: {
meta: fieldsMeta,
episodes: fieldsEpisodes
},
required: {
meta: requiredMeta,
episodes: requiredEpisodes
},
uncleaned: {
meta: uncleanedMeta,
episodes: uncleanedEpisodes
}
}
// 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.indexOf('default') >= 0) {
options.fields.meta = mergeDedupe([DEFAULT.fields.meta, params.fields.meta])
options.fields.meta.splice(options.fields.meta.indexOf('default'), 1)
}
if (options.fields.episodes.indexOf('default') >= 0) {
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 = {
author: function (node) {
if (node.author) {
return node.author
} else if (node[NS.itunesAuthor]) {
return node[NS.itunesAuthor]
}
},
blocked: function (node) {
return node[NS.itunesBlock]
},
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.
const itunesCategories = node["itunes:category"]
if (Array.isArray(itunesCategories)) {
const categoriesArray = itunesCategories.map(item => {
let category = ''
if (item && item['$'] && item['$'].text) {
category += item['$'].text // primary category
if (item[NS.itunesCategory]) { // sub-category
category += '>' + item[NS.itunesCategory][0]['$'].text
}
}
return category
})
return categoriesArray
}
return []
},
chapters: function (node) {
const items = getItemsWithAttrs(node[NS.podcastChapters])
if (items && items[0]) {
return {
type: items[0].attrs.type,
url: items[0].attrs.url
}
}
},
complete: function (node) {
return node[NS.itunesComplete]
},
duration: function (node) {
return node[NS.itunesDuration]
},
editor: function (node) {
return node.managingEditor
},
explicit: function (node) {
return node[NS.itunesExplicit]
},
funding: function (node) {
const items = getItemsWithAttrs(node[NS.podcastFunding])
const finalItems = []
for (const item of items) {
finalItems.push({
value: item.value,
url: item.attrs.url
})
}
return finalItems
},
guid: function (node) {
if (node.guid) {
if (typeof node.guid === 'string') {
return node.guid
} else if (Array.isArray(node.guid) && node.guid[0] && node.guid[0]._) {
return node.guid[0]._
}
}
},
imageURL: function (node) {
if (
node["itunes:image"] &&
node["itunes:image"][0] &&
node["itunes:image"][0]['$'] &&
node["itunes:image"][0]['$'].href
) {
return node["itunes:image"][0]['$'].href
}
if (typeof node["itunes:image"] === 'string') {
return node["itunes:image"]
}
if (
node.image &&
node.image[0] &&
node.image[0].url[0]
) {
return node.image[0].url[0]
}
return undefined
},
/*
NOTE: This is part of the Podcast Index namespace spec.
This is a Phase 2 namespace and has not been formalized at this time.
https://github.com/Podcastindex-org/podcast-namespace/tree/7c9516937e74b8058d7d49e2b389c7c361cc6a48
---
images: function (node) {
const item = getItemsWithAttrs(node['podcast:images'])
if (item[0]) {
const srcset = item.attrs.srcset
const srcSetArray = convertCommaDelimitedStringToArray(srcset)
const parsedSrcSet = []
for (let str of srcSetArray) {
str = str.trim()
const srcSetAttrs = str.split(' ')
if (srcSetAttrs.length === 2) {
parsedSrcSet.push({
url: srcSetAttrs[0],
width: srcSetAttrs[1]
})
}
}
return {
srcset: parsedSrcSet
}
}
},
*/
keywords: function (node) {
return node[NS.itunesKeywords]
},
/*
NOTE: This is part of the Podcast Index namespace spec.
This is a Phase 2 namespace and has not been formalized at this time.
https://github.com/Podcastindex-org/podcast-namespace/tree/7c9516937e74b8058d7d49e2b389c7c361cc6a48
---
location: function (node) {
const item = getItemsWithAttrs(node['podcast:location'])
if (item) {
return {
value: item.value,
latlon: item.attrs.latlon,
osmid: item.attrs.osmid
}
}
},
*/
locked: function (node) {
const items = getItemsWithAttrs(node[NS.podcastLocked])
if (items[0]) {
return {
value: items[0].value,
owner: items[0].attrs.owner
}
}
},
order: function (node) {
return node[NS.itunesOrder]
},
owner: function (node) {
return node[NS.itunesOwner]
},
soundbite: function (node) {
const items = getItemsWithAttrs(node[NS.podcastSoundbite])
const finalItems = []
for (const item of items) {
const duration = parseFloat(item.attrs.duration)
const startTime = parseFloat(item.attrs.startTime)
if (!duration) continue
if (!startTime && startTime !== 0) continue
finalItems.push({
duration,
startTime,
title: item.value
})
}
return finalItems
},
subtitle: function (node) {
return node[NS.itunesSubtitle]
},
summary: function (node) {
return node[NS.itunesSummary]
},
transcript: function (node) {
const items = getItemsWithAttrs(node[NS.podcastTranscript])
const finalItems = []
if (Array.isArray(items)) {
for (const item of items) {
const { language, rel, type, url } = item.attrs
finalItems.push({
language,
rel,
type,
url
})
}
}
return finalItems
},
type: function (node) {
return node[NS.itunesType]
},
/*
NOTE: This is part of the Podcast Index namespace spec.
https://github.com/Podcastindex-org/podcast-namespace/tree/7c9516937e74b8058d7d49e2b389c7c361cc6a48
*/
value: function (node) {
const valueItems = getItemsWithAttrs(node[NS.podcastValue], [NS.podcastValueRecipient, {tag: NS.podcastValueTimeSplit, nestedTags: [NS.podcastRemoteItem]}])
let finalValues = null
if (valueItems && valueItems.length > 0) {
finalValues = []
for (const valueItem of valueItems) {
const { method, suggested, type } = valueItem.attrs
let finalValue = { method, suggested, type }
const valueRecipientItems = valueItem.nestedTags && valueItem.nestedTags[NS.podcastValueRecipient]
if (Array.isArray(valueRecipientItems)) {
const finalRecipients = []
for (const valueRecipientItem of valueRecipientItems) {
const { address, customKey, customValue, fee, name, split, type } = valueRecipientItem.attrs
finalRecipients.push({ address, customKey, customValue, fee, name, split, type })
}
finalValue.recipients = finalRecipients
}
const valueTimeSplits = valueItem.nestedTags && valueItem.nestedTags[NS.podcastValueTimeSplit];
if (Array.isArray(valueTimeSplits)) {
const finalTimeSplits = [];
for (const valueTimeSplit of valueTimeSplits) {
const { startTime, duration, remotePercentage } = valueTimeSplit.attrs;
const remoteItems = valueItem.nestedTags && valueTimeSplit.nestedTags[NS.podcastRemoteItem];
if (Array.isArray(remoteItems)) {
for (const remoteItem of remoteItems) {
const { feedGuid, itemGuid } = remoteItem.attrs;
finalTimeSplits.push({ startTime, duration, remotePercentage, feedGuid, itemGuid });
}
}
}
finalValue.timeSplits = finalTimeSplits;
}
if (Array.isArray(finalValue.recipients) || Array.isArray(finalValue.timeSplits)) {
finalValues.push(finalValue)
}
}
}
return finalValues
}
}
const getDefault = exports.getDefault = function (node, field) {
return (node[field]) ? node[field] : undefined
}
/*
=======================
=== CLEAN FUNCTIONS ===
=======================
*/
const CLEAN = exports.CLEAN = {
author: function (obj) {
return obj
},
blocked: function (string) {
if (string.toLowerCase == 'yes') {
return true
} else {
return false
}
},
complete: function (string) {
if (string[0].toLowerCase == 'yes') {
return true
} else {
return false
}
},
duration: function (arr) {
// gives duration in seconds
let times = arr[0].split(':'),
sum = 0, mul = 1
while (times.length > 0) {
sum += mul * parseInt(times.pop())
mul *= 60
}
return sum
},
enclosure: function (object) {
return {
length: object[0]["$"].length,
type: object[0]["$"].type,
url: object[0]["$"].url
}
},
explicit: function (string) {
if (['yes', 'explicit', 'true'].indexOf(string[0].toLowerCase()) >= 0) {
return true
} else if (['clean', 'no', 'false'].indexOf(string[0].toLowerCase()) >= 0) {
return false
} else {
return undefined
}
},
imageURL: function (string) {
return string
},
owner: function (object) {
let ownerObject = {}
if (object[0].hasOwnProperty(NS.itunesName)) {
ownerObject.name = object[0][NS.itunesName][0]
}
if (object[0].hasOwnProperty(NS.itunesEmail)) {
ownerObject.email = object[0][NS.itunesEmail][0]
}
return ownerObject
}
}
const cleanDefault = exports.cleanDefault = function (node) {
// return first item of array
if (node !== undefined && Array.isArray(node) && 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 = {}
if (Array.isArray(options.fields.meta)) {
options.fields.meta.forEach((field) => {
const obj = {}
var uncleaned = false
if (options.uncleaned && Array.isArray(options.uncleaned.meta)) {
var uncleaned = (options.uncleaned.meta.indexOf(field) >= 0)
}
obj[field] = getInfo(channel, field, uncleaned)
Object.assign(meta, obj)
})
}
if (options.required && Array.isArray(options.required.meta)) {
options.required.meta.forEach((field) => {
if (Object.keys(meta).indexOf(field) < 0) {
throw ERRORS.requiredError
}
})
}
return meta
}
// function builds episode objects from parsed podcast feed
function createEpisodesObjectFromFeed(channel, options) {
let episodes = []
if (channel && Array.isArray(channel.item)) {
channel.item.forEach((item) => {
const episode = {}
if (options.fields && Array.isArray(options.fields.episodes)) {
options.fields.episodes.forEach((field) => {
const obj = {}
var uncleaned = false
if (options.uncleaned && Array.isArray(options.uncleaned.episodes)) {
var uncleaned = (options.uncleaned.episodes.indexOf(field) >= 0)
}
obj[field] = getInfo(item, field, uncleaned)
Object.assign(episode, obj)
})
}
if (options.required && Array.isArray(options.required.episodes)) {
options.required.episodes.forEach((field) => {
if (Object.keys(episode).indexOf(field) < 0) {
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(error) }
resolve(result)
})
})
}
function parseXMLFeed(feedText) {
let feed = {}
parseString(feedText, (error, result) => {
if (error) {
throw error
}
Object.assign(feed, result)
return result
})
return (feed)
}
async function fetchFeed(requestParams) {
try {
const { headers, timeout = 20000 } = requestParams
const abortController = new AbortController()
const signal = abortController.signal
setTimeout(() => {
abortController.abort()
}, timeout)
const feedResponse = await fetch(requestParams.url, { headers, signal })
if (feedResponse.status === 401) {
throw new Error(401)
}
const feedText = await feedResponse.text()
const feedObject = await promiseParseXMLFeed(feedText)
return feedObject
} catch (err) {
throw err
}
}
/*
=======================
=== FINAL FUNCTIONS ===
=======================
*/
const getPodcastFromURL = exports.getPodcastFromURL = async function (requestParams, buildParams) {
try {
const options = buildOptions(buildParams)
const feedResponse = await fetchFeed(requestParams)
const channel = feedResponse.rss.channel[0]
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]
const meta = createMetaObjectFromFeed(channel, options)
const episodes = createEpisodesObjectFromFeed(channel, options)
return { meta, episodes }
}
catch (err) {
throw err
}
}
/*
=======================
=== HELPER FUNCTIONS ===
=======================
*/
const getItemsWithAttrs = (val, nestedTags = []) => {
if (Array.isArray(val)) {
const items = []
for (const item of val) {
if (typeof item === 'string') {
items.push({
value: item,
attrs: {}
})
} else if (item) {
const finalTags = {}
if (nestedTags && nestedTags.length > 0) {
for (const nestedTag of nestedTags) {
if (typeof nestedTag === 'string') {
const nestedItem = getItemsWithAttrs(item[nestedTag])
finalTags[nestedTag] = nestedItem
} else {
const {tag, nestedTags = []} = nestedTag;
const nestedItem = getItemsWithAttrs(item[tag], nestedTags)
finalTags[tag] = nestedItem
}
}
}
items.push({
value: item._,
attrs: item['$'] ? item['$'] : {},
...(Object.keys(finalTags).length > 0) ? { nestedTags: finalTags } : {}
})
}
}
return items
}
return []
}
const convertCommaDelimitedStringToArray = (str) => {
str = str.replace(/(\r\n|\n|\r)/gm, '')
str = str.split(',')
return str
}