-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
456 lines (391 loc) · 14.7 KB
/
server.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
// server.js
// where your node app starts
// init project
const express = require('express');
const fs = require('fs');
const hbs = require('hbs');
const os = require('os');
const rp = require('request-promise-native');
const request = require('request');
const bodyParser = require('body-parser');
const async = require('async');
const minio = require('minio');
const multer = require('multer');
const puppeteer = require('puppeteer');
const Readable = require('stream').Readable;
const { URL } = require('url');
const geturls = require('get-urls');
const yaml = require('js-yaml');
const psl = require('psl');
const cheerio = require('cheerio');
const { DateTime } = require('luxon');
// hack for nodejs SSL error: https://github.com/nodejs/node/issues/16196
require("tls").DEFAULT_ECDH_CURVE = "auto";
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
//app.use(express.static('static'));
app.set('view engine', 'hbs');
app.set('views', './templates');
app.use(express.static('static'));
hbs.registerPartial("above", fs.readFileSync("./partials/above.hbs", "utf-8"));
hbs.registerPartial("below", fs.readFileSync("./partials/below.hbs", "utf-8"));
hbs.registerHelper('isUrl', function(url, options) { return this.url == url || this.url.startsWith(url + "?") ? options.fn(this) : '';});
hbs.registerHelper('isParam', function(param, value, options) { return options.data.root[param] == value ? options.fn(this) : options.inverse(this);});
hbs.registerHelper('toJSON', function(object){ return JSON.stringify(object);}); //NOTE: use new hbs.SafeString() if you need to avoid HTML encoding
hbs.registerHelper('hasAlternate', function(site, options) { return ('alt' + site) in options.data.root.metadata && options.data.root.metadata['alt' + site].length > 1; });
hbs.registerHelper('getAlternates', function(site, options) { return options.data.root.metadata['alt' + site]; });
const USER_AGENT = "vlz-meta-maker";
const minioClient = new minio.Client({
endPoint: 's3.amazonaws.com',
secure: true,
accessKey: process.env.S3_ACCESS_KEY,
secretKey: process.env.S3_SECRET_KEY
});
function getStatus() {
const retVal = {};
retVal["success"] = true;
retVal["message"] = "OK";
retVal["timestamp"] = new Date().toISOString();
retVal["lastmod"] = process.env.LASTMOD || null;
retVal["commit"] = process.env.COMMIT || null;
retVal["tech"] = "NodeJS " + process.version;
retVal["__dirname"] = __dirname;
retVal["__filename"] = __filename;
retVal["os.hostname"] = os.hostname();
retVal["os.type"] = os.type();
retVal["os.platform"] = os.platform();
retVal["os.arch"] = os.arch();
retVal["os.release"] = os.release();
retVal["os.uptime"] = os.uptime();
retVal["os.loadavg"] = os.loadavg();
retVal["os.totalmem"] = os.totalmem();
retVal["os.freemem"] = os.freemem();
retVal["os.cpus.length"] = os.cpus().length;
// too much junk: retVal["os.networkInterfaces"] = os.networkInterfaces();
retVal["process.arch"] = process.arch;
retVal["process.cwd"] = process.cwd();
retVal["process.execPath"] = process.execPath;
retVal["process.memoryUsage"] = process.memoryUsage();
retVal["process.platform"] = process.platform;
retVal["process.release"] = process.release;
retVal["process.title"] = process.title;
retVal["process.uptime"] = process.uptime();
retVal["process.version"] = process.version;
retVal["process.versions"] = process.versions;
retVal["process.installPrefix"] = process.installPrefix;
return retVal;
}
function checkForDuplicates(url) {
const retVal = [];
//retVal.push("This is a test: " + url.host);
const domain = psl.parse(url.host).domain;
if (domain in existing) {
for (row of existing[domain]) {
if (row.website == url.href) {
retVal.push("Exact match with " + row.name);
} else {
retVal.push("Possible duplicate: " + row.name + " (" + row.website + ")");
}
}
}
return retVal;
}
let existing = {};
async function loadExisting() {
const options = {
url: "https://www.vectorlogo.zone/util/apidata.json",
//encoding: null,
json: true,
headers: {
'User-Agent': USER_AGENT
},
resolveWithFullResponse: true,
timeout: 10000 // in millis
};
const data = await rp(options);
console.log({ count: data.body.length }, "existing data loaded");
for (row of data.body) {
parsed = psl.parse(new URL(row.website).host);
//console.log(parsed.domain);
if (parsed.domain in existing) {
existing[parsed.domain].push(row);
} else {
existing[parsed.domain] = [ row ];
}
}
}
function isBlog(url) {
if (url.host.startsWith("blog.") || url.host == "medium.com" || url.pathname.endsWith("/blog") || url.pathname.endsWith("/blog/") || url.pathname.startsWith("/blog/")) {
return true;
}
return false;
}
function isFacebook(url) {
if (url.host.endsWith("facebook.com")) {
if (url.pathname == '/'
|| url.pathname == '/tr'
|| url.pathname.endsWith("/fbml")
|| url.pathname.startsWith("/sharer")
) {
return false;
}
return true;
}
return false;
}
function isGithub(url) {
if (url.host.endsWith("github.com") == false) {
return false;
}
if (url.pathname.match("^/[-A-Za-z0-9]+(/[-A-Za-z0-9]+)?$")) {
return true;
}
return false;
}
function isLinkedIn(url) {
if (url.hostname != "linkedin.com" && url.hostname != "www.linkedin.com") {
return false;
}
if (url.pathname == '/' || url.pathname == '/shareArticle') {
return false;
}
return true;
}
function isTwitter(url) {
if (!url.host.endsWith("twitter.com")) {
return false;
}
if (url.host == "platform.twitter.com") {
return false;
}
if (url.pathname == '/' || url.pathname.startsWith("/intent/")) {
return false;
}
return true;
}
function onlyPathname(url) {
return url.pathname.substring(1);
}
const socialSites = [
{ id: "blog", fn: isBlog },
{ id: "dribbble", fn: function(url) { return url.hostname == "dribbble.com" } },
{ id: "facebook", fn: isFacebook },
{ id: "flickr", fn: function(url) { return url.hostname == "www.flickr.com" } },
{ id: "github", fn: isGithub, cleanup: onlyPathname },
{ id: "googleplus", fn: function(url) { return url.hostname == "plus.google.com" } },
{ id: "instagram", fn: function(url) { return url.hostname == "instagram.com" || url.hostname == "www.instagram.com" } },
{ id: "linkedin", fn: isLinkedIn },
{ id: "pinterest", fn: function(url) { return url.hostname == "pinterest.com" || url.hostname == "www.pinterest.com" } },
{ id: "reddit", fn: function(url) { return url.hostname == "www.reddit.com" } },
{ id: "tumblr", fn: function(url) { return url.hostname == "www.tumblr.com" } },
{ id: "twitter", fn: isTwitter, cleanup: onlyPathname },
{ id: "wikipedia", fn: function(url) { return url.hostname == "en.wikipedia.org" } },
{ id: "youtube", fn: function(url) { return (url.hostname == "youtube.com" || url.hostname == "www.youtube.com") && url.pathname != '/' } },
];
app.get('/status.json', function(req, res) {
res.writeHead(200, {
"Content-Type": "text/plain",
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET',
'Access-Control-Max-Age': '604800',
});
sendJson(req, res, getStatus());
});
const asyncMiddleware = fn =>
(req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(next);
};
app.get('/robots.txt', function(req, res) {
res.setHeader("content-type", "text/plain; charset=utf-8");
res.write("User-Agent: *\n");
res.write("Disallow: /\n");
res.end();
});
app.get('/', function(req, res) {
res.render("index", { step: "url", recaptcha: process.env.RECAPTCHA_SITEKEY });
return;
});
app.post('/', multer({ storage: multer.memoryStorage() }).single('file'), asyncMiddleware(async (req, res, next) => {
if (req.body["step"] == "confirm") {
var logodata = Object.assign({}, req.body);
var keys = Object.keys(logodata);
keys.forEach(function(key) {
logodata[key] = logodata[key].trim()
if (logodata[key] == "") {
delete logodata[key];
}
});
delete logodata["step"];
console.log("logodata=" + JSON.stringify(logodata));
var s = new Readable;
s.push(yaml.safeDump(logodata, { lineWidth: 4096, noRefs: true, sortKeys: true }));
s.push(null);
try {
var s3path = DateTime.utc().toFormat("yyyy/MM/dd/yyyy-MM-dd-HHmmss") + "-" + logodata.logohandle + ".yaml";
await minioClient.putObject(process.env.S3_BUCKET, s3path, s);
res.render("index", { step: "url", recaptcha: process.env.RECAPTCHA_SITEKEY, url: "", msgtype: "success", msgtext: "Metadata for '" + logodata.logohandle + "' saved!" });
} catch (err) {
console.error(err);
res.write("FAILED: " + err.message);
res.end();
}
return;
}
const url = req.body["url"];
if (url == null || url.length === 0) {
res.render("index", { step: "url", recaptcha: process.env.RECAPTCHA_SITEKEY, msgtype: "danger", msgtext: "URL is required" });
return;
}
var recaptchaSecret = process.env.RECAPTCHA_SECRET;
if (recaptchaSecret) {
const recaptchaStr = await rp({
url: "https://www.google.com/recaptcha/api/siteverify",
method: "POST",
form: {secret: recaptchaSecret, response: req.body["g-recaptcha-response"]},
timeout: 10000,
});
const recaptcha = JSON.parse(recaptchaStr);
if (!recaptcha.success) {
console.log("INFO: body=" + JSON.stringify(req.body));
console.log("INFO: recaptcha=" + JSON.stringify(recaptcha));
res.render("index", {
step: "url",
recaptcha: process.env.RECAPTCHA_SITEKEY,
url: url,
msgtype: "danger",
msgtext: "Sorry, reCaptcha things you are a bot. Maybe try again?"
});
return;
}
if (recaptcha.hostname != "localhost" && recaptcha.hostname != process.env.RECAPTCHA_HOSTNAME) {
console.log("INFO: body=" + JSON.stringify(req.body));
console.log("INFO: recaptcha=" + JSON.stringify(recaptcha));
res.render("index", {
step: "url",
recaptcha: process.env.RECAPTCHA_SITEKEY,
url: url,
msgtype: "danger",
msgtext: "That's funny: reCaptcha thinks you are solving on '" + recaptcha.hostname + "'. Why is that?"
});
return;
}
}
let messages = [];
const metadata = {};
const mainURL = new URL(url);
messages = messages.concat(checkForDuplicates(mainURL));
let buf = "";
const useChrome = req.body["use_chrome"];
if (useChrome === "Y") {
const browser = await puppeteer.launch({
args: ['--no-sandbox' ],
executablePath: '/usr/bin/chromium-browser'
});
const page = await browser.newPage();
const response = await page.goto(url, { waitUntil: "networkidle2"});
metadata.website = response.url();
if (url != response.url()) {
metadata.originalurl = url;
}
buf = await page.content();
} else {
const options = {
url: url,
//encoding: null,
headers: {
'User-Agent': USER_AGENT
},
resolveWithFullResponse: true,
timeout: 10000 // in millis
};
const response = await rp(options);
buf = response.body;
metadata.website = response.request.uri.href;
if (url != response.request.uri.href) {
metadata.originalurl = url;
}
}
const match = buf.match(new RegExp("<title>([\\s\\S]*?)</title>"));
if (match != null) {
metadata.title = match[1];
metadata.alttitle = [ metadata.title ];
if (match[1].indexOf(" - ") > 0) {
metadata.alttitle = metadata.alttitle.concat(match[1].split(" - "));
}
if (match[1].indexOf(" | ") > 0) {
metadata.alttitle = metadata.alttitle.concat(match[1].split(" | "));
}
if (match[1].indexOf(": ") > 0) {
metadata.alttitle = metadata.alttitle.concat(match[1].split(": "));
}
} else {
messages.push("WARNING: no title");
}
const urls = geturls(buf);
urls.forEach(function(strURL) {
//res.write("url=" + strURL + "\n");
try {
if (strURL.endsWith("%27")) {
strURL = strURL.slice(0, -3);
}
const theURL = new URL(strURL);
socialSites.forEach(function (theSite) {
if (theSite.fn(theURL)) {
const siteURL = theSite.cleanup ? theSite.cleanup(theURL) : theURL.href;
if (metadata[theSite.id]) {
metadata['alt' + theSite.id].push(siteURL);
}
else {
metadata[theSite.id] = siteURL;
metadata['alt' + theSite.id] = [ siteURL ];
}
}
});
}
catch (err) {
messages.push("ERROR: " + err);
}
});
const parsed = psl.parse(mainURL.host);
metadata.sort = parsed.sld;
if (parsed.tld == "com" || parsed.tld == "org") {
metadata.logohandle = parsed.sld
}
else {
metadata.logohandle = parsed.domain.replace('.', '');
}
if (req.body["step"] == "url") {
res.render("confirm", { messages, metadata, socialsites: socialSites, step: "confirm" });
}
}));
app.use(function (req, res, next) {
res.setHeader("content-type", "text/plain; charset=utf-8");
res.status(404).send("404: unable to find file '" + req.url + "'");
});
app.use(function (err, req, res, next) {
console.error(err.stack);
res.setHeader("content-type", "text/plain; charset=utf-8");
res.status(500).send("500: " + err);
});
function sendJson(req, res, jsonObj) {
if ('callback' in req.query)
{
res.write(req.query["callback"]);
res.write("(");
res.write(JSON.stringify(jsonObj));
res.write(");");
}
else
{
res.write(JSON.stringify(jsonObj));
}
res.end();
}
async function main() {
await loadExisting();
const listener = app.listen(process.env.PORT || 4000, function () {
console.log('Listening on port ' + listener.address().port);
});
}
main();