forked from itteco/iframely
-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.js
397 lines (291 loc) · 12.7 KB
/
utils.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
(function() {
GLOBAL.CONFIG = require('./config');
var async = require('async');
var cache = require('./lib/cache');
var ejs = require('ejs');
var fs = require('fs');
var crypto = require('crypto');
var moment = require('moment');
var _ = require('underscore');
var urlLib = require('url');
var whitelist = require('./lib/whitelist');
var pluginLoader = require('./lib/loader/pluginLoader');
function NotFound(message) {
if (typeof message === 'object') {
this.meta = message;
message = JSON.stringify(message, null, 4);
}
Error.call(this); //super constructor
Error.captureStackTrace(this, this.constructor); //super helper method to include stack trace in error object
this.name = this.constructor.name; //set our function’s name as error name.
this.message = message; //set the error message
};
NotFound.prototype.__proto__ = Error.prototype;
exports.NotFound = NotFound;
var send = require('send')
, utils = require('connect/lib/utils')
, parse = utils.parseUrl
, url = require('url');
exports.static = function(root, options){
options = options || {};
// root required
if (!root) throw new Error('static() root path required');
// default redirect
var redirect = false !== options.redirect;
return function static(req, res, next) {
if ('GET' != req.method && 'HEAD' != req.method) return next();
var path = parse(options.path ? {url: options.path} : req).pathname;
var pause = utils.pause(req);
function resume() {
next();
pause.resume();
}
function directory() {
if (!redirect) return resume();
var pathname = url.parse(req.originalUrl).pathname;
res.statusCode = 301;
res.setHeader('Location', pathname + '/');
res.end('Redirecting to ' + utils.escape(pathname) + '/');
}
function error(err) {
if (404 == err.status) return resume();
next(err);
}
send(req, path)
.maxage(options.maxAge || 0)
.root(root)
.hidden(options.hidden)
.on('error', error)
.on('directory', directory)
.pipe(res);
};
};
var version = require('./package.json').version;
function log() {
var args = _.compact(Array.prototype.slice.apply(arguments));
args.splice(0, 0, "--", moment().utc().format("\\[YY-MM-DD HH:mm:ss\\]"));
console.log.apply(console, args);
}
var etag = function(value) {
return '"' + crypto.createHash('md5').update(value).digest("hex") + '"';
};
function prepareUri(uri) {
if (!uri) {
return uri;
}
if (uri.match(/^\/\//i)) {
return "http:" + uri;
}
if (!uri.match(/^https?:\/\//i)) {
return "http://" + uri;
}
return uri;
}
function getKeyForUri(uri) {
if (!uri) {
return;
}
var result = 0;
var whitelistRecord = whitelist.findRawWhitelistRecordFor(uri);
if (whitelistRecord) {
result += new Date(whitelistRecord.date).getTime();
}
var plugin = pluginLoader.findDomainPlugin(uri);
if (plugin) {
result += plugin.getPluginLastModifiedDate().getTime();
}
if (result) {
result = Math.round(result / 1000);
}
return result || null;
}
function getUnifiedCacheUrl(req) {
// Remove 'refresh' param and order keys.
var urlObj = urlLib.parse(req.url, true);
var query = urlObj.query;
delete query.refresh;
// Remove jsonp params.
// TODO: remove all except possible params.
delete query._;
delete query[req.app.get('jsonp callback name')];
delete query.fingerprint;
delete query.lang;
delete query.access_token;
delete urlObj.search;
var newQuery = {};
var keys = _.keys(query);
keys.sort();
keys.forEach(function(key) {
newQuery[key] = query[key];
});
urlObj.query = newQuery;
return urlLib.format(urlObj);
}
function setResponseToCache(code, content_type, req, res, body, ttl) {
if (!res.get('ETag')) {
res.set('ETag', etag(body));
}
var url = getUnifiedCacheUrl(req);
var head = {
statusCode: code,
headers: {
'Content-Type': content_type
},
etag: res.get('ETag')
};
var data = JSON.stringify(head) + '::' + body;
var linkValidationKey, uri = prepareUri(req.query.uri || req.query.url);
if (uri) {
linkValidationKey = getKeyForUri(uri);
}
cache.set('urlcache:' + version + (linkValidationKey || '') + ':' + url, data, {ttl: ttl});
}
exports.cacheMiddleware = function(req, res, next) {
async.waterfall([
function(cb) {
var refresh = req.query.refresh === "true" || req.query.refresh === "1";
if (!refresh) {
var url = getUnifiedCacheUrl(req);
var linkValidationKey, uri = prepareUri(req.query.uri || req.query.url);
if (uri) {
linkValidationKey = getKeyForUri(uri);
}
cache.get('urlcache:' + version + (linkValidationKey || '') + ':' + url, function(error, data) {
if (error) {
console.error('Error getting response from cache', url, error);
}
if (data) {
var index = data.indexOf("::");
if (index > -1) {
var head;
var headStr = data.substring(0, index);
try {
head = JSON.parse(headStr);
} catch(ex) {
console.error('Error parsing response status from cache', url, headStr);
}
if (head) {
log("Using cache for", req.url.replace(/\?.+/, ''), req.query.uri || req.query.url);
var requestedEtag = req.headers['if-none-match'];
var jsonpCallback = req.query[req.app.get('jsonp callback name')];
if (jsonpCallback) {
// jsonp case.
var body = data.substring(index + 2);
body = body
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
jsonpCallback = jsonpCallback.replace(/[^\[\]\w$.]/g, '');
body = jsonpCallback + ' && ' + jsonpCallback + '(' + body + ');';
var realEtag = etag(body);
if (realEtag === requestedEtag) {
res.writeHead(304);
res.end();
} else {
this.charset = this.charset || 'utf-8';
res.set('ETag', realEtag);
res.set('Content-Type', 'text/javascript');
res.writeHead(head.statusCode || 200, head.headers);
res.end(body);
}
} else {
// Common case.
if (head.etag === requestedEtag) {
res.writeHead(304);
res.end();
} else {
this.charset = this.charset || 'utf-8';
if (head.etag) {
res.set('ETag', head.etag);
}
res.writeHead(head.statusCode || 200, head.headers);
res.end(data.substring(index + 2));
}
}
} else {
cb();
}
}
} else {
cb();
}
});
} else {
cb();
}
}
], function() {
// Copy from source.
res.renderCached = function(view, context, headers) {
if (!fs.existsSync(view)) {
view = __dirname + '/views/' + view;
}
var template = fs.readFileSync(view, 'utf8');
var body = ejs.render(template, context);
setResponseToCache(200, 'text/html', req, res, body);
this.charset = this.charset || 'utf-8';
this.writeHead(200, headers);
this.end(body);
};
// Copy from source.
res.jsonpCached = function(obj) {
// settings
var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);
// content-type
this.charset = this.charset || 'utf-8';
this.set('Content-Type', 'application/json');
// Cache without jsonp callback.
setResponseToCache(200, 'application/json', req, res, body);
// jsonp
var callback = this.req.query[app.get('jsonp callback name')];
if (callback) {
body = body
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
this.set('Content-Type', 'text/javascript');
var cb = callback.replace(/[^\[\]\w$.]/g, '');
body = cb + ' && ' + cb + '(' + body + ');';
}
this.send(body);
};
res.tryCacheError = function(error) {
if (typeof error === "number" && Math.floor(error / 100) === 4) {
var value;
if (error === 404) {
value = 'Page not found';
} else {
value = 'Requested page error: ' + error;
}
setResponseToCache(error, 'text/html', req, res, value);
} else if (typeof error === "string" && error.match(/^timeout/)) {
setResponseToCache(408, 'text/html', req, res, 'Requested page error: ' + error, CONFIG.CACHE_TTL_PAGE_TIMEOUT);
}
};
res.sendCached = function(content_type, body) {
setResponseToCache(200, content_type, req, res, body);
this.charset = this.charset || 'utf-8';
this.writeHead(200, {'Content-Type': content_type});
this.end(body);
};
res.sendJsonCached = function(obj) {
var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);
// content-type
this.charset = this.charset || 'utf-8';
this.set('Content-Type', 'application/json');
setResponseToCache(200, 'application/json', req, res, body);
this.send(body);
};
next();
});
};
exports.log = function() {
var args = Array.prototype.slice.apply(arguments);
args.splice(0, 0, "--", moment().utc().format("\\[YY-MM-DD HH:mm:ss\\]"));
console.log.apply(console, args);
}
})();