-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
772 lines (680 loc) · 16.4 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
'use strict'
// Requires
const extendr = require('extendr')
const eachr = require('eachr')
const { TaskGroup } = require('taskgroup')
const typeChecker = require('typechecker')
const safefs = require('safefs')
const safeps = require('safeps')
const pathUtil = require('path')
const request = require('request')
// Define
class Feedr {
// Helpers
static create(...args) {
return new Feedr(...args)
}
// Check to see if the feed === still relevant
// feed={cache}, cache=boolean/`preferred`/number
// metaData={expires, date}
// return boolean
static isFeedCacheStillRelevant(feed, metaData) {
return (
feed.cache && // User always wants to use cache
(feed.cache === 'preferred' ||
// If the cache === still relevant according to the website
(metaData.expires && new Date() < new Date(metaData.expires)) ||
// If the cache === still relevant according to the user
(typeChecker.isNumber(feed.cache) &&
metaData.date &&
new Date() <
new Date(new Date(metaData.date).getTime() + feed.cache)))
)
}
// Constructor
constructor(config = {}) {
// Prepare
const me = this
// Extend and dereference our configuration
this.config = extendr.deep(
{
log: null,
cache: 1000 * 60 * 60 * 24, // one day by default
tmpPath: null,
requestOptions: null,
plugins: null
},
this.config || {},
config
)
// Get the temp path right away
safeps.getTmpPath(function(err, tmpPath) {
if (err) {
console.error(err)
} else {
me.config.tmpPath = tmpPath
}
})
}
// Log
log(...args) {
if (this.config.log) this.config.log(...args)
return this
}
// Read Feeds
// feeds = {feedName:feed}
// next(err,result)
readFeeds(...args) {
// Prepare
const me = this
const failures = []
// Prepare options
let feeds = null
const defaultfeed = {} // what is this?
let next = null
// Extract the configuration from the arguments
args.forEach(function(arg, index) {
if (typeChecker.isFunction(arg)) {
next = arg
} else if (typeChecker.isArray(arg)) {
feeds = arg
} else if (typeChecker.isPlainObject(arg)) {
if (index === 0) {
feeds = arg
} else {
extendr.extend(defaultfeed, arg)
}
}
})
// Extract
const results = {}
// Tasks
const tasks = TaskGroup.create({
concurrency: 0,
abortOnError: false
}).done(function() {
let message = 'Feedr finished fetching'
let err = null
if (failures.length !== 0) {
message +=
`with ${failures.length} failures:\n` +
failures
.map(function(i) {
return i.message
})
.join('\n')
err = new Error(message)
me.log('warn', err)
} else {
me.log('debug', message)
}
next(err, results)
})
// Feeds
eachr(feeds, function(feed, index) {
tasks.addTask(function(complete) {
// Prepare
if (typeChecker.isString(feed)) {
feed = { url: feed }
}
feeds[index] = feed = extendr.deep({}, defaultfeed, feed)
// Read
me.readFeed(feed, function(err, data) {
// Handle
if (err) {
me.log(
'warn',
`Feedr failed to fetch [${feed.url}] to [${feed.path}]`,
err.stack
)
failures.push(err)
} else {
results[index] = data
}
// Complete
complete(err)
})
})
})
// Start
tasks.run()
// Chain
return this
}
// Prepare Feed Details
prepareFeed(feed) {
// Set defaults
if (feed.hash == null)
feed.hash = require('crypto')
.createHash('md5')
.update(`feedr-${JSON.stringify(feed.url)}`)
.digest('hex')
if (feed.basename == null)
feed.basename = pathUtil.basename(feed.url.replace(/[?#].*/, ''))
if (feed.extension == null) feed.extension = pathUtil.extname(feed.basename)
if (feed.name == null) feed.name = feed.hash + feed.extension
if (feed.path == null)
feed.path = pathUtil.join(this.config.tmpPath, feed.name)
if (feed.metaPath == null)
feed.metaPath =
pathUtil.join(this.config.tmpPath, feed.name) + '-meta.json'
if (feed.cache == null) feed.cache = this.config.cache
if (feed.parse == null) feed.parse = true
if (feed.parse === 'raw') feed.parse = false
if (feed.check == null) feed.check = true
if (feed.plugins == null)
feed.plugins = this.config.plugins || 'github xml cson json yaml string'
if (feed.metaData == null) feed.metaData = {}
// Return
return feed
}
// Cleanup response data
cleanData(data) {
// Prepare
const me = this
const keys = []
// Discover the keys inside data, and delve deeper
eachr(data, function(value, key) {
if (typeChecker.isPlainObject(data)) {
data[key] = me.cleanData(value)
}
keys.push(key)
})
// Check if we are a simple rest object
// If so, make it a simple value
if (keys.length === 1 && keys[0] === '_content') {
data = data._content
}
// Return the result
return data
}
// Read Feed
// next(err,data)
readFeed(...args) {
// Prepare
const me = this
let url, feed, next
// Extract the configuration from the arguments
args.forEach(function(arg) {
if (typeChecker.isString(arg)) {
url = arg
} else if (typeChecker.isFunction(arg)) {
next = arg
} else if (typeChecker.isPlainObject(arg)) {
feed = arg
}
})
// Check for url
if (!feed) feed = {}
if (url) feed.url = url
if (!feed.url) {
next(new Error('Feed url was not supplied'))
return this
}
// Check deprecations
if (feed.checkReponse) {
next(new Error('Feed checkResponse option is deprecated for check'))
return this
}
// Ensure optional
feed = this.prepareFeed(feed)
// Plugins
const plugins = {}
if (typeChecker.isString(feed.plugins)) {
feed.plugins = feed.plugins.split(' ')
}
if (typeChecker.isArray(feed.plugins)) {
for (let i = 0; i < feed.plugins.length; ++i) {
const name = feed.plugins[i]
try {
plugins[name] = require('./plugins/' + name)
} catch (err) {
next(err)
return this
}
}
}
// Generators
function generateParser(name, method, opts, complete) {
me.log('debug', `Feedr parse [${feed.url}] with ${name} attempt`)
method(opts, function(err, data) {
if (err) {
complete(err)
return
}
if (data) {
me.log(
'debug',
`Feedr parse [${feed.url}] with ${name} attempt, used`
)
opts.data = data
} else {
me.log(
'debug',
`Feedr parse [${feed.url}] with ${name} attempt, ignored`
)
}
complete(null, data)
})
}
function generateChecker(name, method, opts, complete) {
me.log('debug', `Feedr check [${feed.url}] with ${name} attempt`)
method(opts, function(err, data) {
if (err) {
complete(err)
return
}
me.log(
'debug',
`Feedr check [${feed.url}] with ${name} attempt, success`
)
complete(null, data)
})
}
// ------------------------------
// Parser
let parseResponse = null
// Specific
if (typeChecker.isString(feed.parse)) {
// Exists
if (
typeChecker.isFunction(plugins[feed.parse] && plugins[feed.parse].parse)
) {
parseResponse = generateParser.bind(
null,
feed.parse,
plugins[feed.parse].parse
)
}
// Missing
else {
next(new Error('Invalid parse value: ' + feed.parse))
return this
}
}
// Custom
else if (typeChecker.isFunction(feed.parse)) {
parseResponse = generateParser.bind(null, 'custom', feed.parse)
}
// Auto
else if (feed.parse === true) {
parseResponse = function(opts, parseComplete) {
const checkTasks = new TaskGroup().done(parseComplete)
eachr(plugins, function(value, key) {
if (value.parse != null) {
checkTasks.addTask(function(parseTaskComplete) {
generateParser.bind(
null,
key,
value.parse
)(opts, function(err, data) {
if (data) {
checkTasks.clear()
}
parseTaskComplete(err)
})
})
}
})
checkTasks.run()
}
}
// Raw
else {
parseResponse = function(opts, parseComplete) {
parseComplete()
}
}
// ------------------------------
// Checker
let checkResponse = null
// Specific
if (typeChecker.isString(feed.check)) {
// Exists
if (
typeChecker.isFunction(plugins[feed.check] && plugins[feed.check].check)
) {
checkResponse = generateChecker.bind(
null,
feed.check,
plugins[feed.check].check
)
}
// Missing
else {
next(new Error('Invalid check value: ' + feed.check))
return this
}
}
// Custom
else if (typeChecker.isFunction(feed.check)) {
checkResponse = generateChecker.bind(null, 'custom', feed.check)
}
// Auto
else if (feed.check) {
checkResponse = function(opts, checkComplete) {
const checkTasks = new TaskGroup().done(checkComplete)
eachr(plugins, function(value, key) {
if (value.check != null) {
checkTasks.addTask(function(checkTaskComplete) {
generateChecker.bind(
null,
key,
value.check
)(opts, checkTaskComplete)
})
}
})
checkTasks.run()
}
}
// Raw
else {
checkResponse = function(opts, checkComplete) {
checkComplete()
}
}
// Request options
const requestOptions = extendr.deep(
{
url: feed.url,
timeout: 1 * 60 * 1000,
encoding: null,
headers: {
'User-Agent': 'Wget/1.14 (linux-gnu)'
}
},
me.config.requestOptions || {},
feed.requestOptions || {}
)
// Read a file
function readFile(path, readFileComplete) {
// Log
me.log(
'debug',
`Feedr === reading [${feed.url}] on [${path}], checking exists`
)
// Check the the file exists
safefs.exists(path, function(exists) {
// Check it exists
if (!exists) {
// Log
me.log(
'debug',
`Feedr === reading [${feed.url}] on [${path}], it doesn't exist`
)
// Exit
readFileComplete()
return
}
// Log
me.log(
'debug',
`Feedr === reading [${feed.url}] on [${path}], it exists, now reading`
)
// It does exist, so let's continue to read the cached fie
safefs.readFile(path, null, function(err, rawData) {
// Check
if (err) {
// Log
me.log(
'debug',
`Feedr === reading [${feed.url}] on [${path}], it exists, read failed`,
err.stack
)
// Exit
readFileComplete(err)
return
}
// Log
me.log(
'debug',
`Feedr === reading [${feed.url}] on [${path}], it exists, read completed`
)
// Return the parsed cached data
readFileComplete(null, rawData)
})
})
}
// Parse a file
function readMetaFile(path, readMetaFileComplete) {
// Log
me.log('debug', `Feedr === parsing meta file [${feed.url}] on [${path}]`)
// Parse
readFile(path, function(err, rawData) {
// Check
if (err || !rawData) {
// Log
me.log(
'debug',
`Feedr === parsing meta file [${feed.url}] on [${path}], read failed`,
err && err.stack
)
// Exit
readMetaFileComplete(err)
return
}
// Attempt
let data = null
try {
data = JSON.parse(rawData.toString())
} catch (err) {
// Log
me.log(
'warn',
`Feedr === parsing meta file [${feed.url}] on [${path}], parse failed`,
err.stack
)
// Exit
readMetaFileComplete(err)
return
}
// Log
me.log(
'debug',
`Feedr === parsing meta file [${feed.url}] on [${path}], parse completed`
)
// Exit
readMetaFileComplete(null, data)
})
}
// Write the feed
function writeFeed(response, data, writeFeedComplete) {
// Log
me.log('debug', `Feedr === writing [${feed.url}] to [${feed.path}]`)
// Prepare
const writeTasks = TaskGroup.create({ concurrency: 0 }).done(function(
err
) {
if (err) {
// Log
me.log(
'warn',
`Feedr === writing [${feed.url}] to [${feed.path}], write failed`,
err.stack
)
// Exit
writeFeedComplete(err)
return
}
// Log
me.log(
'debug',
`Feedr === writing [${feed.url}] to [${feed.path}], write completed`
)
// Exit
writeFeedComplete(null, data)
})
writeTasks.addTask('store the meta data in a cache somewhere', function(
writeTaskComplete
) {
const writeData = JSON.stringify(
{
headers: response.headers,
parse: feed.parse
},
null,
' '
)
safefs.writeFile(feed.metaPath, writeData, writeTaskComplete)
})
writeTasks.addTask('store the parsed data in a cache somewhere', function(
writeTaskComplete
) {
const writeData = feed.parse ? JSON.stringify(data) : data
safefs.writeFile(feed.path, writeData, writeTaskComplete)
})
// Fire the write tasks
writeTasks.run()
}
// Get the file via reading the cached copy
// next(err, data, meta)
function viaCache(viaCacheComplete) {
// Log
me.log('debug', `Feedr === remembering [${feed.url}] from cache`)
// Prepare
let meta = null
let data = null
const readTasks = TaskGroup.create().done(function(err) {
viaCacheComplete(err, data, meta && meta.headers)
})
readTasks.addTask('read the meta data in a cache somewhere', function(
viaCacheTaskComplete
) {
readMetaFile(feed.metaPath, function(err, result) {
if (err || !result) {
viaCacheTaskComplete(err)
return
}
meta = result
viaCacheTaskComplete()
})
})
readTasks.addTask('read the parsed data in a cache somewhere', function(
viaCacheTaskComplete
) {
readFile(feed.path, function(err, rawData) {
if (err || !rawData) {
viaCacheTaskComplete(err)
return
}
if (
feed.parse === false ||
(feed.parse === true && meta.parse === false)
) {
data = rawData
} else {
try {
data = JSON.parse(rawData.toString())
} catch (err) {
viaCacheTaskComplete(err)
return
}
}
viaCacheTaskComplete()
})
})
// Fire the write tasks
readTasks.run()
}
// Get the file via performing a fresh request
// next(err, data, meta)
function viaRequest(viaRequestComplete) {
// Log
me.log(
'debug',
`Feedr === fetching [${feed.url}] to [${feed.path}], requesting`
)
// Add etag if we have it
if (feed.cache && feed.metaData.etag) {
if (requestOptions.headers['If-None-Match'] == null) {
requestOptions.headers['If-None-Match'] = feed.metaData.etag
}
}
// Fetch and Save
request(requestOptions, function(err, response, data) {
// Log
const opts = { feedr: me, feed, response, data }
me.log(
'debug',
`Feedr === fetching [${feed.url}] to [${feed.path}], requested`
)
// What should happen if an error occurs
function handleError(err) {
// Log
me.log(
'warn',
`Feedr === fetching [${feed.url}] to [${feed.path}], failed`,
err.stack
)
// Exit
if (feed.cache) {
viaCache(next)
return
}
viaRequestComplete(err, opts.data, requestOptions.headers)
}
// Check error
if (err) {
handleError(err)
return
}
// Check cache
if (feed.cache && response.statusCode === 304) {
viaCache(next)
return
}
// Determine Parse Type
parseResponse(opts, function(err) {
if (err) {
handleError(err)
return
}
// Log
me.log(
'debug',
`Feedr === fetching [${feed.url}] to [${feed.path}], requested, checking`
)
// Exit
checkResponse(opts, function(err) {
if (err) {
handleError(err)
return
}
writeFeed(response, opts.data, function(err) {
viaRequestComplete(err, opts.data, requestOptions.headers)
})
})
})
})
}
// Refresh if we don't want to use the cache
if (feed.cache === false) {
viaRequest(next)
return this
}
// Fetch the latest cache data to check if it === still valid
readMetaFile(feed.metaPath, function(err, metaData) {
// There isn't a cache file
if (err || !metaData) {
viaRequest(next)
return
}
// Apply to the feed details
feed.metaData = metaData
// There === an expires header and it === still valid
// cache preferred, use cache if exists, otherwise fall back to relevant
// cache number, use cache if within number, otherwise fall back to relevant
if (Feedr.isFeedCacheStillRelevant(feed, metaData)) {
viaCache(next)
return
}
// There was no expires header
viaRequest(next)
})
// Chain
return this
}
}
// Exports
module.exports = Feedr