/
request.js
394 lines (324 loc) · 13.4 KB
/
request.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
'use strict';
const http = require('http');
const https = require('https');
const axios = require('axios');
const { XMLParser } = require('fast-xml-parser');
const global = require('./helper/helper_global');
const fs = require('fs');
const axiosInstance = axios.create({
// fixes issue with proxy mode due to how electron apps are packaged
adapter: 'http',
headers: {
'Accept': 'application/xml, text/xml'
}
});
const eRequest = {
http: 1,
https: 2
};
/** @deprecated */
function makeRequest(_Options, _FallbackOptions, _Callback, _eRequest) {
// NOTE: Give the result JSON string to the given _Callback methode
// NOTE: The _Callback methode need one argument to catch the JSON result string
let Req = undefined;
switch (_eRequest) {
case eRequest.http:
Req = http.request(_Options, function (_Res) {
let Chunks = [];
_Res.on('data', function (_Chunk) {
Chunks.push(_Chunk);
});
updateFeedURLStatus(true, _Options);
});
break;
case eRequest.https:
default:
Req = https.request(_Options, function (_Res) {
let Chunks = [];
_Res.on('data', function (_Chunk) {
Chunks.push(_Chunk);
});
_Res.on('end', function () {
_Callback(Buffer.concat(Chunks).toString().trim(), _eRequest, _Options);
});
// updateFeedURLStatus(true, _Options);
});
break;
}
// NOTE: In case of any error try the given fallback options (can be proxy settings)
if (Req !== undefined) {
Req.on('error', function(_Error) {
console.log('Problem with request: ' + _Error.message);
updateFeedURLStatus(false, _Options);
if (_FallbackOptions !== null) {
console.log('Use fallback options: ' + _FallbackOptions);
makeRequest(_FallbackOptions, null, _Callback, _eRequest);
updateFeedURLStatus(false, _Options);
}
});
Req.end();
}
}
/**
* Request the entire RSS feed for a given podcast URL.
* @param {string} feedUrl RSS URL of the podcast feed.
* @param {boolean} returnRawData Whether the response should be parsed from xml into a podcast JSON object.
* @returns RSS feed in JSON format. If returnRawData is true, returns unparsed data.
*/
function requestPodcastFeed(feedUrl, returnRawData) {
return new Promise((resolve, reject) => {
let requestConfig = {};
// if proxy is not enabled, explicitly disable for axios
if (!global.isProxySet()) {
requestConfig = {
proxy: false
};
}
// NOTE: Allow URLs with expired SSL certificate. Do not reject them.
// TODO: Could be a config option for the user to enable/disable more security
const agent = new https.Agent({
rejectUnauthorized: false
});
requestConfig['httpsAgent'] = agent;
axiosInstance
.get(feedUrl, requestConfig)
.then(function (response) {
updateFeedStatus(feedUrl, response.status);
if (response.status >= 400) {
reject(`Feed request to ${feedUrl} failed with status code ${response.status}.`);
}
if (returnRawData === undefined || returnRawData === false) {
resolve(parseXmlToJson(response.data));
} else {
resolve(response.data);
}
})
.catch(function (error) {
console.log(feedUrl);
updateFeedStatus(feedUrl, 503);
reject(error);
});
});
}
module.exports.requestPodcastFeed = requestPodcastFeed;
/** @deprecated */
// TODO: Remove because it is not being used
// eslint-disable-next-line no-unused-vars
function makeFeedRequest(_Feed, _Callback) {
if (_Feed instanceof Object) {
makeRequest(_Feed, null, _Callback, eRequest.http);
} else {
if (_Feed.includes('https')) {
makeRequest(_Feed, getFeedProxyOptions(_Feed), _Callback, eRequest.https);
} else {
makeRequest(_Feed, getFeedProxyOptions(_Feed), _Callback, eRequest.http);
}
}
}
// ---------------------------------------------------------------------------------------------------------------------
/** @deprecated */
// TODO: Remove because it is not being used
// eslint-disable-next-line no-unused-vars
function getITunesOptions(_SearchTerm) {
let Options = {
host: 'itunes.apple.com',
method: 'GET',
path: '/search?term=' + _SearchTerm + '&media=podcast',
port: 443
};
return Options;
}
/** @deprecated */
// TODO: Remove because it is not being used
// eslint-disable-next-line no-unused-vars
function getITunesProxyOptions(_SearchTerm) {
let Options = {
host: 'proxy',
method: 'GET',
path: 'http://itunes.apple.com/search?term=' + _SearchTerm + '&media=podcast',
port: 8080
};
return Options;
}
function getFeedProxyOptions(_Url) {
let Options = {
host: 'proxy',
method: 'GET',
path: _Url,
port: 8080
};
return Options;
}
function parseXmlToJson(xml) {
let rss = { items: [] };
const parser = new XMLParser({
ignoreAttributes: false
});
const result = parser.parse(xml);
let channel = result.rss && result.rss.channel ? result.rss.channel : result.feed;
if (Array.isArray(channel)) channel = channel[0];
if (channel.title) {
rss.title = channel.title;
}
if (channel.description) {
rss.description = channel.description;
}
rss.link = channel.link && channel.link.href ? channel.link.href : channel.link;
rss.category = channel.category || [];
if (channel.image) {
rss.image = channel.image.url;
}
if (!rss.image && channel['itunes:image']) {
rss.image = channel['itunes:image'].href;
}
let items = channel.item !== undefined ? channel.item : channel.entry;
if (items && !Array.isArray(items)) {
// the main 'items' code block below expects the items variable to be an Array of Objects
// but if in the originating XML the channel element contains only a single item, the items
// variable is set to a literal Object instead of an Array of Objects of length 1. It is fixed
// here so the items variable behaves the same whether it contains 1 or many items
items = [items];
}
if (Array.isArray(items)) {
items.forEach(val => {
// TODO: Update podcast episode object keys to use camelcase.
// This will require updating the names in other files.
/* eslint-disable camelcase */
let obj = {};
obj.title = val['itunes:title'] !== undefined ? val['itunes:title'] : val.title;
obj.id = val.guid && val.guid.$t ? val.guid.$t : val.id;
obj.description = val.summary && val.summary.$t ? val.summary.$t : val.description;
if (val.enclosure === undefined) {
// skip processing this episode because it is missing a link
return;
}
obj.url = val.enclosure['@_url'];
obj.type = val.enclosure['@_type'];
obj.link = obj.url;
obj.author = val.author && val.author.name ? val.author.name : val['dc:creator'];
obj.published = val.created ? Date.parse(val.created) : val.pubDate ? Date.parse(val.pubDate) : Date.now();
obj.created = val.updated ? Date.parse(val.updated) : val.pubDate ? Date.parse(val.pubDate) : val.created ? Date.parse(val.created) : Date.now;
obj.category = val.category || [];
obj.content = val.content && val.content.$t ? val.content.$t : null;
// Medium Support via @sstrubberg
if (val['content:encoded']) {
obj.content_encoded = val['content:encoded'];
obj.content = obj.content_encoded;
}
// Captivate Support via @cvburgess
if (val['podcast:transcript']) {
obj.podcast_transcript = val['podcast:transcript'].url;
}
if (val['itunes:subtitle']) {
obj.itunes_subtitle = val['itunes:subtitle'];
}
if (val['itunes:summary']) {
obj.itunes_summary = val['itunes:summary'];
}
if (val['itunes:author']) {
obj.itunes_author = val['itunes:author'];
}
if (val['itunes:explicit']) {
obj.itunes_explicit = val['itunes:explicit'];
}
if (val['itunes:duration']) {
obj.itunes_duration = val['itunes:duration'];
}
if (val['itunes:season']) {
obj.itunes_season = val['itunes:season'];
}
if (val['itunes:episode']) {
obj.itunes_episode = val['itunes:episode'];
}
if (val['itunes:episodeType']) {
obj.itunes_episode_type = val['itunes:episodeType'];
}
if (val['itunes:image']) {
obj.itunes_image = val['itunes:image'].href;
}
obj.duration = obj.itunes_duration || '';
obj.duration = String(obj.duration); // duration is sometimes a number instead of string
let duration_formatted = '';
if (obj.duration !== '' && typeof obj.duration === 'string') {
const timeObject = global.parseFeedEpisodeDuration(obj.duration.split(':'));
if (timeObject.hours === '0' && timeObject.minutes === '0') {
duration_formatted = '';
} else if (timeObject !== {}) {
duration_formatted = (timeObject.hours !== '0' ? timeObject.hours + 'h ' : '') + timeObject.minutes + 'min';
}
}
obj.duration_formatted = obj.duration === '' ? 'unknown' : duration_formatted;
obj.description = obj.itunes_subtitle || val['description'];
obj.enclosures = val.enclosure ? Array.isArray(val.enclosure) ? val.enclosure : [val.enclosure] : [];
if (val['media:thumbnail']) {
obj.media = val.media || {};
obj.media.thumbnail = val['media:thumbnail'];
obj.enclosures.push(val['media:thumbnail']);
}
if (val['media:content']) {
obj.media = val.media || {};
obj.media.content = val['media:content'];
obj.enclosures.push(val['media:content']);
}
if (val['media:group']) {
if (val['media:group']['media:title'])
obj.title = val['media:group']['media:title'];
if (val['media:group']['media:description'])
obj.description = val['media:group']['media:description'];
if (val['media:group']['media:thumbnail'])
obj.enclosures.push(val['media:group']['media:thumbnail'].url);
}
rss.items.push(obj);
/* eslint-enable camelcase */
});
}
return rss;
}
function updateFeedStatus(feedUrl, status) {
// Check if JSON with feeds exists
if (fs.readFileSync(global.saveFilePath, 'utf-8') !== '') {
const JsonContentOld = JSON.parse(fs.readFileSync(global.saveFilePath, 'utf-8'));
let JsonContentNew = JSON.parse(fs.readFileSync(global.saveFilePath, 'utf-8'));
for (let i = 0; i < JsonContentNew.length; i++) {
// Find feed item that's returning error
if (feedUrl === JsonContentNew[i].feedUrl) {
// Update feedUrlStatus prop
JsonContentNew[i].feedUrlStatus = status;
// don't continue loop (assumes no duplicate urls)
break;
}
}
// Update JSON with feeds if there are changes
if (JsonContentOld !== JsonContentNew) {
fs.writeFileSync(global.saveFilePath, JSON.stringify(JsonContentNew));
}
}
}
/** @deprecated */
function updateFeedURLStatus(isURLWorking, _Options) {
if (_Options) {
let feedURL = null;
if (typeof _Options === 'object' && _Options.path) {
feedURL = _Options.path;
} else {
feedURL = _Options;
}
feedURL = feedURL.replace(/(http|https):\/\//, '').replace('.xml', '');
// Check if JSON with feeds exists
if (fs.readFileSync(global.saveFilePath, 'utf-8') !== '') {
let JsonContentOld = JSON.parse(fs.readFileSync(global.saveFilePath, 'utf-8'));
let JsonContentNew = JSON.parse(fs.readFileSync(global.saveFilePath, 'utf-8'));
for (let i = 0; i < JsonContentNew.length; i++) {
// Find feed item that's returning error
if (feedURL === JsonContentNew[i].feedUrl.replace(/(http|https):\/\//, '').replace('.xml', '')) {
// Update feedUrlStatus prop
JsonContentNew[i].feedUrlStatus = !isURLWorking ? 500 : 200;
}
}
// Update JSON with feeds if there are changes
if (JsonContentOld !== JsonContentNew) {
fs.writeFileSync(global.saveFilePath, JSON.stringify(JsonContentNew));
}
}
}
}