-
Notifications
You must be signed in to change notification settings - Fork 1
/
bgService.js
51 lines (46 loc) · 1.64 KB
/
bgService.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
#!/usr/bin/env node
'use strict';
const chalk = require('chalk');
const error = chalk.bold.red;
const success = chalk.bold.green;
const info = chalk.bold.blue;
const logSymbols = require('log-symbols');
const _ = require('lodash');
const sleep = require('thread-sleep');
const RateLimiter = require('limiter').RateLimiter;
const limiter = new RateLimiter(10, 'second');
const config = require('./config');
const channels = require('./lib/channels');
const channelData = require('./lib/channelData');
let start = () => {
/*
Fetch all channels, grab the latest videos, and submit if needed.
*/
channels.fetchChannels().then((storedChannels) => {
_.forEach(storedChannels, (channel) => {
limiter.removeTokens(1, (errd, remainingRequests) => {
if(errd || remainingRequests === 0) {
sleep(1000);
} else {
console.log(info("Fetching " + channel.name));
fetch(channel.id)
.then(channelData.submitToReddit)
.then((videos) => {
channels.insertNewVideos(videos, channel.id)
})
.catch((err) => {
console.error(err);
});
}
});
});
});
};
function fetch(id) {
return Promise.all([channelData.grabAllFromYouTube(id), channels.getAllStoredVideos(id)]).then((values) => {
return _.differenceBy(values[0], values[1], 'id');
})
}
console.log(success(logSymbols.success , 'Background Service is running.'));
start();
setInterval(start, config.bgInterval);