-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
254 lines (225 loc) · 7.44 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
var request = require('request-promise');
var requestAsync = require('request');
var cheerio = require('cheerio');
var FeedParser = require('feedparser');
var Promise = require('bluebird');
var fs = require('fs');
var path = require('path');
var FileCookieStore = require("tough-cookie-filestore");
var config = require('./config.json');
var cookieFile = path.resolve(__dirname, "./cookies.json");
// create the cookie store file if it does not exist
fs.closeSync(fs.openSync(cookieFile, 'a'));
var jar = request.jar(new FileCookieStore(cookieFile));
function login() {
return request({
url: "https://www.cubecraft.net/login/login",
jar: jar
}).then(function () {
return request({
url: "https://www.cubecraft.net/login/login",
method: 'POST',
form: {
login: config.credentials.username,
password: config.credentials.password,
cookie_check: '1',
register: '0',
remember: '1'
},
followAllRedirects: true,
jar: jar
})
});
}
var threadIdMatcher = /^.*threads\/.*?.?([0-9]+)\/?$/;
var reports = [];
function queryReportIdsRss() {
// todo: ensure user is logged in
// also the promise is never rejected
return new Promise(function (resolve, reject) {
var reportList = [];
var req = requestAsync({
url: "https://www.cubecraft.net/forums/report-a-player.24/index.rss",
jar: jar
});
var feedparser = new FeedParser();
req.on('error', console.error);
req.on('response', function (res) {
var stream = this, err;
if (res.statusCode != 200) {
err = new Error('Api returned a bad status code');
reject(err);
return this.emit('error', err);
}
stream.pipe(feedparser);
});
feedparser.on('error', console.error);
feedparser.on('readable', function () {
var stream = this, item;
while (item = stream.read()) {
reportList.push({
id: threadIdMatcher.exec(item.link)[1],
createdAt: item.pubdate
});
}
});
feedparser.on('end', function () {
reportList.sort(function (a, b) {
return -(a.createdAt - b.createdAt);
});
resolve(reportList.map(function (report) {
return parseInt(report.id, 10);
}));
});
});
}
function queryReportIdsHtml() {
function queryReports(page) {
return request({
url: "https://www.cubecraft.net/forums/report-a-player.24/page-" + page,
qs: {order: 'post_date', direction: 'asc'},
jar: jar,
transform: function (body) {
return cheerio.load(body);
}
});
}
function ensureLogin($) {
if ($('html').hasClass('LoggedOut')) {
console.log("not logged in, trying to log in...");
return login().then(queryReports(1));
} else {
return Promise.resolve($);
}
}
function extractReportIds($) {
return $('a.PreviewTooltip').map(function (i, a) {
if (!$(a).closest('.discussionListItem').hasClass('locked')) {
return parseInt(threadIdMatcher.exec($(a).attr('href'))[1], 10);
}
}).get();
}
return queryReports(1)
.then(ensureLogin)
.then(function ($) {
var pageNum = $('div.PageNav').data('last') || 1;
var pages = [extractReportIds($)];
for (var i = 2; i <= pageNum; ++i) {
pages.push(
queryReports(i)
.then(extractReportIds)
.catch(function (err) {
console.error("unable to retrieve page", err.stack);
return [];
})
);
}
return pages;
})
.spread(Array.prototype.concat.bind([]));
}
queryReportIdsRss().then(function (reportList) {
reports = reportList;
console.log(reports.join());
return queryReportIdsHtml();
}).then(function (reportList) {
reports = reportList;
console.log(reports.join());
}).catch(logError);
function logError(err) {
console.error(err.stack);
}
function redirectToNext(req, res) {
var referer = req.headers.referer;
queryReportIdsRss().then(function (reports) {
var match = threadIdMatcher.exec(referer);
var fromId, nextId;
if (match) {
fromId = match[1];
reports.forEach(function (id) {
if (id > fromId && !(id > nextId)) {
nextId = id;
}
});
}
if (!nextId && reports.length > 0) {
nextId = Math.min.apply(null, reports);
}
if (nextId) {
res.writeHead(302, {
'Location': 'https://www.cubecraft.net/threads/' + nextId
});
res.end();
} else {
res.end('No more open reports!');
}
}).catch(function (err) {
console.error(err);
res.writeHead(500, 'Internal Server Error');
res.end('Sorry, there was an error :/');
});
}
function logRequest(req) {
var now = new Date();
console.log('%d-%d-%d %d:%d %s %s', now.getFullYear(), now.getMonth(), now.getDate(),
now.getHours(), now.getMinutes(), req.method, req.url);
}
function showAll(req, res) {
queryReportIdsHtml().then(function (reportIds) {
var reportListHtml =
'<!DOCTYPE html>' +
'<html>' +
'<head>' +
'<title>Open Reports of ' + config.credentials.username + '</title>' +
'</head>' +
'<body>' +
reportIds.sort().map(function (id) {
var url = 'https://www.cubecraft.net/threads/' + id;
return '<p><a href="' + url + '">' + url + '</a></p>'
}).join('\n') +
'</body>' +
'</html>';
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': reportListHtml.length,
'Expires': new Date().toUTCString()
});
res.end(reportListHtml);
}).catch(function (err) {
console.error(err);
res.writeHead(500, 'Internal Server Error');
res.end('Sorry, there was an error :/');
});
}
function handleRequest(req, res) {
logRequest(req);
switch (req.url) {
case '/next':
return redirectToNext(req, res);
case '/all':
return showAll(req, res);
default:
res.writeHead(404, 'Not found');
res.end('This page does not exist');
}
}
function startServer() {
var secure = "tls" in config;
var server, options;
if (secure) {
options = {
key: fs.readFileSync(config.tls.keyFile),
cert: fs.readFileSync(config.tls.certFile)
};
server = require('https').createServer(options, handleRequest);
} else {
server = require('http').createServer(handleRequest);
}
server.listen(config.net.port, function () {
console.log("Server listening on: %s://localhost:%s", (secure ? 'https' : 'http'), config.net.port);
});
}
if (require.main === module) {
startServer();
}
module.exports = startServer;