-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
221 lines (212 loc) · 7.76 KB
/
Copy pathindex.js
File metadata and controls
221 lines (212 loc) · 7.76 KB
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
'use strict';
const Mercury = require('@postlight/mercury-parser');
const Parser = require('rss-parser');
const url = require('url');
const _ = require('lodash');
const pify = require('util').promisify;
const writeFile = pify(require('fs').writeFile);
const readFile = pify(require('fs').readFile);
const randomUA = require('random-ua');
const defaultConf = require('./config.json');
const escpos = require('escpos');
const moment = require('moment');
const EventEmitter = require('events');
const stringSim = require('string-similarity');
const saveEmitter = new EventEmitter();
const parsePage = (url, item, articles, config) => {
const strictMatch = new RegExp(`[^?.!:; \\s]*[a-z ']*${config.matchPhrase} [^?.!;]*[?.!;]["']?`, 'ig');
const coarseMatch = new RegExp(`[^?.!:; \\s]*[a-z ']*${config.matchPhrase} [^?.!;]*`, 'ig');
const sessionUA = randomUA.generate();
// see if we have anything from the google supplied title
const titleMatch = item.title.replace(/<b>|<\/b>/gi, '').match(strictMatch) ||
item.title.replace(/<b>|<\/b>/gi, '').match(coarseMatch);
let googleTitle;
if (titleMatch) {
googleTitle = titleMatch[0].trim();
}
return Mercury.parse(url, {
headers: {
'User-Agent': sessionUA
},
contentType: 'text'
}
).then((article) => {
const title = article.title.match(strictMatch) || article.title.match(coarseMatch);
const content = article.content.match(strictMatch);
const matchArr = _.union(
title || [],
content || []
).reduce((memo, match) => {
if (match.length < 104) {
match = match.replace(/^['"“”‘’(]|['"“”‘’)]$/ig, '').trim();
if (memo.every((elem) => {
return stringSim.compareTwoStrings(elem.toLowerCase(), match.toLowerCase()) < (config.matchTolerance || 0.85);
})) {
memo.push(match);
}
}
return memo;
}, []);
// articles[item.id] = { article: item, matches: matchArr };
return { url: item.link, id: item.id, matches: matchArr, date: item.isoDate };
})
.catch((err) => {
// console.error(JSON.stringify({ article: item, error: err.message }));
if (googleTitle &&
googleTitle.length < 110 && googleTitle.search(/[^a-zA-Z\d\s?.!:;,'"“”‘’$]/g) === -1
) {
// our crawler cant access, but we have something from goog
return { url: item.link, id: item.id, matches: [googleTitle], date: item.isoDate, error: err.message };
}
throw Object.assign({}, err, { id: item.id, url: item.link });
});
};
const checkFeed = (articles, dbPath, config) => {
const parser = new Parser();
return parser.parseURL(config.feedURL)
.then((feed) => {
const promArr = [];
feed.items.forEach((item) => {
if (!articles[item.id]) {
promArr.push(parsePage(url.parse(item.link, true).query.url, item, articles, config));
}
});
return Promise.all(promArr.map(p => p.catch(e => e)));
}).then((articleResults) => {
// do pruning
articles = Object.assign(articles, articleResults.reduce((memo, article) => {
memo[article.id] = article; return memo;
}, {}));
console.log('Saving articles');
saveEmitter.emit('saving');
return new Promise(resolve => setTimeout(resolve, 5000))
.then(() => {
return writeFile(dbPath, JSON.stringify(articles, null, 2))
.then(() => saveEmitter.emit('saved'));
});
});
};
module.exports = {
start (dbPath, inputConfig) {
const config = Object.assign({}, defaultConf, inputConfig);
return readFile(dbPath, { flag: 'a+' })
.then((articleDB) => {
let articles = {};
if (articleDB) {
try {
articles = JSON.parse(articleDB);
} catch (e) {}
}
if (process.argv[2]) {
console.log('replaying result...');
const article = articles[process.argv[2]];
if (article) {
return parsePage(url.parse(article.url, true).query.url, {
title: '',
link: article.url,
id: article.id,
isoDate: article.date
}, article, config)
.then((res) => {
console.log(res);
});
}
console.error('No such article stored');
} else {
const printEmitter = new EventEmitter();
let printer;
let device;
if (!config.dryRun) {
device = new escpos.USB();
printer = new escpos.Printer(device);
}
const printArticle = (article) => {
if (!config.dryRun) {
article.matches.forEach(match => {
printer.font('a').text(match);
console.log(match);
});
printer.control('FF');
printer.close(() => printEmitter.emit('print'));
} else {
article.matches.forEach(match => {
console.log(match);
printEmitter.emit('print');
});
}
};
let printed = [];
const print = () => {
const randPrintTime = config.printInterval * 60 +
Math.floor(config.printInterval * 60 * (Math.random() * 2 - 1) / 5);
setTimeout(() => {
new Promise(function (resolve, reject) {
if (!config.dryRun) {
device.open(() => {
resolve(printer);
});
} else {
resolve();
}
})
.then((printer) => {
const timeConf = config.fromTimeAgo.split(' ');
const diffTime = moment().subtract(timeConf[0], timeConf[1]);
const articleIds = Object.keys(articles);
let i = 0;
let article;
if (articleIds.every(elem => printed.includes(elem)) && !config.noRepeat) printed = [];
while (i < articleIds.length) {
if (!printed.includes(articleIds[i]) &&
articles[articleIds[i]].matches &&
articles[articleIds[i]].matches.length !== 0 &&
moment(articles[articleIds[i]].date).isAfter(diffTime)
) {
article = articles[articleIds[i]];
printed.push(articleIds[i]);
break;
} else {
printed.push(articleIds[i]);
}
i += 1;
}
if (article) {
console.log(`Printing article....`);
printArticle(article);
} else {
printEmitter.emit('print');
}
});
}, randPrintTime * 1000);
};
printEmitter.on('print', () => {
// stack safety
process.nextTick(print);
});
print();
// check the rss feed erry minute
return checkFeed(articles, dbPath, config).then(() => {
return new Promise((resolve, reject) => {
setInterval(() => {
checkFeed(articles, dbPath, config)
.catch((e) => {
console.error(`Feed Error: ${e}`);
});
}, 60000);
});
}).catch((e) => {
console.error(`Initial Feed Error: ${e}`);
return new Promise((resolve, reject) => {
setInterval(() => {
checkFeed(articles, dbPath, config)
.catch((e) => {
console.error(`Feed Error: ${e}`);
});
}, 60000);
});
});
}
});
},
saveEmitter
};