-
Notifications
You must be signed in to change notification settings - Fork 329
Expand file tree
/
Copy pathutils.js
More file actions
1197 lines (944 loc) · 35.5 KB
/
utils.js
File metadata and controls
1197 lines (944 loc) · 35.5 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
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as events from 'events';
import { fetchStream, fetchStreamKeepAlive, fetchStreamAuthorized } from './fetch.js';
import iconv from 'iconv-lite';
import * as async from 'async';
import imagesize from 'probe-image-size';
import * as _ from 'underscore';
import * as parseIsoDuration from 'parse-iso-duration';
import * as entities from 'entities';
import { cache } from './cache.js';
import * as htmlUtils from './html-utils.js';
import log from '../logging.js';
import CONFIG from '../config.loader.js';
function prepareEncodedUri(request_options, attr) {
var url = request_options[attr];
if (url && !/%[A-Z0-9]/i.test(url)) {
request_options[attr] = encodeURI(url);
}
}
function fixTTL(ttl) {
if (ttl === 0) {
return ttl;
}
// 'null' converted to 0 - not good fo checking cache_ttl === 0.
// 'undefined' is big NaN for math.max.
// -1 is converted to null to not match cache_ttl === 0.
return ttl || -1;
}
function maxTTL(ttl) {
if (ttl === -1) {
// Convert -1 to null, to not match cache_ttl === 0.
return null;
}
return ttl;
}
export function getMaxCacheTTLOverride(url, options) {
var proxy = null;
if (CONFIG.PROXY || (options && options.proxy)) {
proxy = (options && options.proxy) || CONFIG.PROXY.find(p => {
return p && p.re && p.re.some(re => url.match(re));
});
}
return proxy;
};
export function getMaxCacheTTL(url, options, default_min_ttl) {
var proxy = getMaxCacheTTLOverride(url, options);
var result = Math.max(fixTTL(options && options.cache_ttl), fixTTL(proxy && proxy.cache_ttl), fixTTL(default_min_ttl));
result = maxTTL(result);
// Use `proxy.max_cache_ttl` if needed.
if (proxy
&& proxy.max_cache_ttl
&& (!result || result > proxy.max_cache_ttl)) {
result = proxy.max_cache_ttl;
}
return result;
};
export function prepareRequestOptions(request_options, options) {
if (request_options.url && !request_options.uri) {
request_options.uri = request_options.url;
}
var uri = request_options.uri;
delete request_options.url;
if (CONFIG.PROXY || (options && options.proxy)) {
var proxy = (options && options.proxy) || CONFIG.PROXY.find(p => {
return p && p.re && p.re.some(re => uri.match(re));
});
if (proxy) {
if (proxy.prerender && CONFIG.PRERENDER_URL) {
request_options.uri = CONFIG.PRERENDER_URL + encodeURIComponent(uri);
} else if (proxy.proxy && CONFIG.PROXY_URL) {
request_options.uri = CONFIG.PROXY_URL + encodeURIComponent(uri);
}
if (proxy.proxy_server) {
request_options.proxy = proxy.proxy_server;
}
if (proxy.user_agent) {
request_options.headers = request_options.headers || {};
request_options.headers['User-Agent'] = proxy.user_agent;
}
if (proxy.headers) {
request_options.headers = request_options.headers || {};
_.extend(request_options.headers, proxy.headers)
}
if (proxy.request_options) {
_.extend(request_options, proxy.request_options);
}
if (proxy.disable_http2) {
request_options.disable_http2 = true;
}
}
}
if (options && options.getRequestOptions
&& (options.getRequestOptions('app.name') || options.getRequestOptions('app.ua_extension'))
&& request_options.headers
&& request_options.headers['User-Agent'] === CONFIG.USER_AGENT) {
var ext = options.getRequestOptions('app.name', options.getRequestOptions('app.ua_extension'));
if (ext.length > 1) {
ext = ext[0].toUpperCase() + ext.slice(1)
}
request_options.headers['User-Agent'] += ' ' + ext;
}
var lang = options && options.getProviderOptions && options.getProviderOptions('locale', 'en-US');
if (lang) {
request_options.headers = request_options.headers || {};
request_options.headers['Accept-Language'] = lang.replace('_', '-') + CONFIG.ACCEPT_LANGUAGE_SUFFIX;
}
prepareEncodedUri(request_options, 'uri');
return request_options;
};
/**
* @public
* Do HTTP GET request and handle redirects
* @param url Request uri (parsed object or string)
* @param {Object} options
* @param {Number} [options.maxRedirects]
* @param {Boolean} [options.fullResponse] True if need load full page response. Default: false.
* @param {Function} [callback] The completion callback function or events.EventEmitter object
* @returns {events.EventEmitter} The emitter object which emit error or response event
*/
export function getUrl(url, options, callbacks) {
var options = options || {};
var redirect, follow;
if (options.followRedirect) {
redirect = 'follow';
follow = options.maxRedirects || CONFIG.MAX_REDIRECTS;
}
if (options.followRedirect === false) {
redirect = 'manual';
follow = 0;
}
var request_options = prepareRequestOptions({
// TODO: jar: jar,
// Reviewed.
uri: url,
method: 'GET',
headers: {
'User-Agent': options.user_agent || CONFIG.USER_AGENT,
'Accept': '*/*'
},
timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT,
redirect: redirect,
follow: follow
}, options);
try {
fetchStreamKeepAlive(request_options)
.then(stream => {
if (!options.asBuffer) {
stream.setEncoding("binary");
}
callbacks.onResponse && callbacks.onResponse(stream);
})
.catch(error => {
callbacks.onError && callbacks.onError(error);
});
} catch (ex) {
console.error('Error on getUrl for', url, '.\n Error:' + ex);
callbacks.onError && callbacks.onError(ex);
}
};
export const getUrlFunctional = getUrl;
var getHead = function(url, options, callbacks) {
var options = options || {};
// TODO:
// Store cookies between redirects and requests.
// var jar = options.jar;
// if (!jar) {
// jar = request.jar();
// }
var redirect, follow;
if (options.followRedirect) {
redirect = 'follow';
follow = options.maxRedirects || CONFIG.MAX_REDIRECTS;
}
if (options.followRedirect === false) {
redirect = 'manual';
follow = 0;
}
var request_options = prepareRequestOptions({
// jar: jar,
// Reviewed.
uri: url,
method: 'HEAD',
headers: {
'User-Agent': CONFIG.USER_AGENT
},
timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT,
redirect: redirect,
follow: follow
// No abort controller for head.
}, options);
try {
fetchStreamAuthorized(request_options)
.then(response => {
callbacks.onResponse && callbacks.onResponse(response);
})
.catch(error => {
callbacks.onError && callbacks.onError(error);
});
} catch (ex) {
console.error('Error on getHead for', url, '.\n Error:' + ex);
callbacks.onError && callbacks.onError(ex);
}
};
export const getHeadFunctional = getHead;
export function getCharset(string, doNotParse) {
var charset;
if (doNotParse) {
charset = string.toUpperCase();
} else if (string) {
var m = string && string.match(/charset\s*=\s*([\w_-]+)/i);
charset = m && m[1].toUpperCase();
}
return charset;
};
export function encodeText(charset, text) {
try {
var charset = charset || 'UTF-8';
if (/* v > 0.9 */ Buffer.isEncoding
&& Buffer.isEncoding(charset)) {
var b = Buffer.from(text, 'binary');
text = b.toString(charset);
} else {
var b = iconv.encode(text, "ISO8859-1");
text = iconv.decode(b, charset);
}
// Remove 'REPLACEMENT CHARACTER'.
text = text.replace(/\uFFFD$/ig, '');
// Trim. Available only after decode.
text = text.replace(/^\s+|\s+$/g, '');
return text;
} catch(e) {
return text;
}
};
export function parseJSONSource(text, decode) {
try {
return JSON.parse(decode ? entities.decodeHTML(decode(text)) : entities.decodeHTML(text));
} catch (ex) {
// default parser failed. Let's try to forgive
}
var s = text;
// replace multi-line comments
s = s.replace(/\/\*[^'":{}]+?\*\//g, '');
// and single-line comments at the end
s = s.replace(/(?<!https?:)\/\/[^'":{}]+$/gm, '');
// and single-line comments on the new line
s = s.replace(/^(?:[\s\n\r\t]+)?\/\/.+$/gm, '');
// this is nuts. replace \' with '.
// Ex: https://uncrate.com/mclaren-720s-ride-on-childrens-car/
// Ex: https://perezhilton.com/bachelorette-hannah-brown-sex-windmill-controversy/
s = s.replace(/\\"[^"]+\\"/g, function (match) {
return match.replace(/\\'/g, "'");
});
s = s.replace(/"[^"]+"/g, function (match) {
return match.replace(/\\'/g, "'");
});
// escape apostrophies as in dont't-> don\'t (assumably escapes it properly)
s = s.replace(/"([^"]+)([^\\])'([^"]+)"/g, "\"$1$2\'$3\"");
// replace 'values' with "values" at the end of the lines
s = s.replace(/:(?:[\s\n\r\t]+)?'([^\']+)\'(?:[\s\n\r\t]+)?([\]}])/g, ':"$1"$2');
s = s.replace(/:(?:[\s\t]+)?'([^\']+)\'(?:[\s\t]+)?(,)?(?:[\s\t]+)?$/gm, function (match, p1, p2) {
return ':"' + p1 + '"' + (p2 ? ',' : '');
});
// replace '' with "" for empty values
s = s.replace(/:(?:[\s\n\r\t]+)?''(?:[\s\n\r\t]+)?([\]},])/g, ':""$1');
// take ids into quotes "" for string values
s = s.replace(/(,|{)(?:[\s\n\r\t]+)?(\w+)?:(?:[\s\n\r\t]+)?\"/g, '$1"$2":"');
// semicolon or coma at the end
s = s.replace(/}(?:[\s\n\r\t]+)?[;,](?:[\s\n\r\t]+)?$/g, '}');
// or coma in between
s = s.replace(/,(?:[\s\n\r\t]+)?(\}|\])(?:[\s\n\r\t]+)?([,\]}])/g, '$1$2');
// decode all string values
s = s.replace(/:(?:[\s\n\r\t]+)?\"([^"]+[^\\])\"/g, function (match, p1) {
var str = decode ? entities.decodeHTML(decode(p1)) : entities.decodeHTML(p1);
str = str.replace(/([^\\])"/g, '$1\\"');
str = str.replace(/^"/, '\\"');
return ':"' + str + '"';
});
// and avoid line breaks in text values
s = s.replace(/[\n\r\t]+/g, '');
// : undefined -> 0
s = s.replace(/:(?:[\s\n\r\t]+)?undefined/g, ': 0');
// also, for some reason, many cases with an extra } at the end
var a = (s.match(/{/g) || []).length;
var b = (s.match(/}/g) || []).length;
if (b == a +1) {s = s.replace(/}(?:\s+)?$/, '');}
return JSON.parse(s);
};
/**
* @public
* Get image size and type.
* @param {String} uri Image uri.
* @param {Object} [options] Options.
* @param {Boolean} [options.cache] False to disable cache. Default: true.
* @param {Function} callback Completion callback function. The callback gets two arguments (error, result) where result has:
* - result.format
* - result.width
* - result.height
*
* error == 404 if not found.
* */
export function getImageMetadata(uri, options, callback){
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
cache.withCache("image-meta:" + uri, function(callback) {
var loadImageHead, imageResponseStarted, totalTime, timeout, contentLength;
var abortController;
function finish(error, data) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
} else {
return;
}
// We don't need more data. Abort causes error. timeout === null here so error will be skipped.
abortController && abortController.abort();
if (!error && !data) {
error = 404;
}
data = data || {};
if (options.debug) {
data._time = {
imageResponseStarted: imageResponseStarted || totalTime(),
loadImageHead: loadImageHead && loadImageHead() || 0,
total: totalTime()
};
}
if (error && error.message) {
error = error.message;
}
if ((typeof error === 'string' && error.indexOf('ENOTFOUND') > -1) ||
error === 500) {
error = 404;
}
if (error) {
data.error = error;
}
callback(null, data);
}
timeout = setTimeout(function() {
finish("timeout");
}, options.timeout || CONFIG.RESPONSE_TIMEOUT);
if (options.debug) {
totalTime = createTimer();
}
async.waterfall([
function(cb) {
var imagesizeDone, firstError, firstData, firstSource;
function finishCb(error, data, source) {
// imagesize may call callback twice for http2.
if (imagesizeDone) {
console.error(' -- Double callback call on getImageMetadata for', {
uri: uri,
error: error,
data: data,
source: source,
firstError: firstError,
firstData: firstData,
firstSource: firstSource
});
return;
} else {
firstError = error;
firstData = data;
firstSource = source;
}
imagesizeDone = true;
cb(error, data);
}
getUrlFunctional(uri, {
timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT,
asBuffer: true
}, {
onResponse: function(res) {
abortController = res.abortController;
var content_type = res.headers['content-type'];
if (content_type && content_type !== 'application/octet-stream' && content_type !== 'binary/octet-stream') {
if (content_type.indexOf('image') === -1 && !uri.match(/\.(jpg|png|gif|webp)(\?.*)?$/i)) {
return finishCb('invalid content type: ' + content_type, undefined, 'onResponse content_type');
}
}
if (res.status == 200) {
if (options.debug) {
imageResponseStarted = totalTime();
}
contentLength = parseInt(res.headers['content-length'] || '0', 10);
imagesize(uri)
.then(data => {
if (data && data.type) {
data.format = data.type;
}
finishCb('', data, 'imagesize');
})
.catch(error => finishCb(error, {}, 'imagesize'))
} else {
finishCb(res.status, undefined, 'onResponse !200');
}
},
onError: function(error) {
// TODO: One time I had here Error: Callback was already called.
finishCb(error, undefined, 'onError');
}
});
},
function(data, cb){
if (options.debug) {
loadImageHead = createTimer();
}
if (contentLength) {
data.content_length = contentLength;
}
cb(null, data);
}
], finish);
}, {
// Ignore proxy.cache_ttl, if options.cache_ttl === 0 - do not read from cache.
refresh: options.refresh || options.cache_ttl === 0,
doNotWaitFunctionIfNoCache: options.doNotWaitFunctionIfNoCache,
ttl: getMaxCacheTTL(uri, options, CONFIG.IMAGE_META_CACHE_TTL),
multiCache: options.multiCache
}, callback);
};
export function getUriStatus(uri, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
cache.withCache("status:" + uri, function(cb) {
var time, timeout;
function finish(error, data) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
} else {
return;
}
data = data || {};
if (error) {
data.error = error;
}
if (options.debug) {
data._time = time();
}
cb(null, data);
}
timeout = setTimeout(function() {
finish("timeout");
}, options.timeout || CONFIG.RESPONSE_TIMEOUT);
if (options.debug) {
time = createTimer();
}
getUriStatusPrivate(uri, options, finish);
}, {
// Ignore proxy.cache_ttl, if options.cache_ttl === 0 - do not read from cache.
refresh: options.refresh || options.cache_ttl === 0,
doNotWaitFunctionIfNoCache: options.doNotWaitFunctionIfNoCache,
ttl: getMaxCacheTTL(uri, options, CONFIG.IMAGE_META_CACHE_TTL),
multiCache: options.multiCache
}, callback);
};
export function getContentType(uriForCache, uriOriginal, options, cb) {
cache.withCache("content-type:" + uriForCache, function(cb) {
var timeout, totalTime, abortController;
function finish(error, headers) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
} else {
return;
}
// We don't need more data. Abort causes error. timeout === null here so error will be skipped.
// If 'abortController' not defined, then no request created?
abortController && abortController.abort();
var data = {};
if (options.debug) {
data._time = totalTime();
}
if (error) {
data.error = error;
}
if (data.error && data.error.message) {
// Compact error if 'reason' available.
data.error = data.error.message;
}
if (!error && !headers) {
data.error = 408;
}
if (headers) {
data.type = headers['content-type'];
if (data.type) {
data.type = data.type.split(';')[0]; // may have charset after ;
}
// no need to keep all other headers in cache. List what's needed.
if (headers['x-frame-options']) data.x_frame_options = headers['x-frame-options'];
if (headers['content-security-policy']) data.csp = headers['content-security-policy'];
if (headers['access-control-allow-origin']) data.allow_origin = headers['access-control-allow-origin'];
if (headers['accept-ranges']) data.accept_ranges = headers['accept-ranges'];
if (headers['url'] && headers['url'] !== uriOriginal) data.url = headers['url'];
}
cb(null, data);
}
timeout = setTimeout(function() {
finish("timeout");
}, options.timeout || CONFIG.RESPONSE_TIMEOUT);
if (options.debug) {
totalTime = createTimer();
}
function makeCall(method) {
var methodCaller = method && method === 'GET' ? getUrlFunctional : getHeadFunctional;
methodCaller(uriOriginal, {
timeout: options.timeout || CONFIG.RESPONSE_TIMEOUT
}, {
onResponse: function(res) {
abortController = res.abortController;
var error = res.status && res.status != 200 ? res.status : null;
if (!method
// If method HEAD is not allowed. ex. Amazon S3 (=403)
// Try call with GET.
&& (error === 405
|| error === 403
|| error === 400
|| error >= 500
// Or ClourFront that gobbles up headers when checking CORS.
|| (res.headers && !res.headers['access-control-allow-origin']
&& res.headers['server'] === 'AmazonS3' && !error ))) {
makeCall('GET');
return;
}
// Final destination url if Fetch follows 301/302 re-directs
if (res.url && res.url !== uriOriginal && res.headers) {
res.headers.url = res.url;
}
finish(error, res.headers);
},
onError: function(error) {
finish(error);
}
});
}
// Call HEAD.
makeCall();
}, {
// Ignore proxy.cache_ttl, if options.cache_ttl === 0 - do not read from cache.
refresh: options.refresh || options.cache_ttl === 0,
ttl: getMaxCacheTTL(uriOriginal, options, CONFIG.CACHE_TTL),
}, cb);
};
export function unifyDuration(duration) {
if (duration && typeof duration === 'string') {
if (duration.match(/^\d+$/)) {
return parseInt(duration);
}
try {
var ms = parseIsoDuration(duration);
} catch(ex) {
return null;
}
return Math.round(ms / 1000);
} else {
return duration;
}
};
var NOW = new Date().getTime();
var minDate = new Date(1990, 1);
export function unifyDate(date) {
if (Array.isArray(date)) {
date = date[0];
}
if (typeof date === "string" && date.match(/^\d+$/)) {
date = parseInt(date);
}
if (typeof date === "number") {
if (date === 0) {
return null;
}
// Check if date in seconds, not miliseconds.
if (NOW / date > 100) {
date = date * 1000;
}
date = new Date(date);
if (date < minDate) {
return null;
}
return date.toISOString().replace(/T.+$/, ''); // Remove time (no timezone).
}
// TODO: time in format 'Mon, 29 October 2012 18:15:00' parsed as local timezone anyway.
var timestamp = Date.parse(date);
if (isNaN(timestamp) && date.replace) {
// allow Z at the end which Node doesn't seem to parse into timestamp otherwise
// also allow Oct 15th, 2014
timestamp = Date.parse(date.replace(/Z$/, '').replace(/(\d)(?:th|nd|rd),\s(\d+)$/i, "$1, $2"));
}
if (!isNaN(timestamp) && timestamp > 0) { // check timestamp > 0 to skip likely broken dates like "0001-01-01T00:00:00Z
var dateStr = new Date(timestamp).toISOString();
// Remove time if no timezone specified.
if (!date.match(/Z$/i) // ISO date with Z at and.
&& !date.match(/ \w+$/i) // GMT, UTC, ...
&& !date.match(/\d\d:\d\d.*[\+\-]\d\d(:?\d\d)?$/i)) { // ISO 8601: +1000 -10 (YYYY-MM-DDThh:mm:ss[.sss]±hh:mm)
dateStr = dateStr.replace(/T.+$/, '')
}
return dateStr;
}
// Bad date to parse.
return null;
};
export function lowerCaseKeys(obj) {
for (var k in obj) {
var lowerCaseKey = k.toLowerCase();
if (lowerCaseKey != k) {
obj[lowerCaseKey] = obj[k];
delete obj[k];
k = lowerCaseKey;
}
if (typeof obj[k] == "object") {
lowerCaseKeys(obj[k]);
}
}
};
export function sendLogToWhitelist(uri, context) {
const {meta, oembed, oembedLinks, whitelistRecord} = context;
if (!CONFIG.WHITELIST_LOG_URL) {
return;
}
if (/^(https?:)?\/\/[^\/]+\/?$/i.test(uri)
|| /^(https?:)?\/\/[^\/]+:\d+/.test(uri)) {
// Skip base domain url and urls with port numbers.
return;
}
const ignorelist_re = /test|staging|sex|porn|fuck|gay|xx|nsfw/;
if (ignorelist_re.test(uri) || meta && ignorelist_re.test(meta.title + meta['html-title'] + meta.description + meta.keywords)) {
return;
}
if (context.video_src || context.oembed_domain || context.twitter_domain || whitelistRecord.exclusiveRel || context.whenWBIR) {
// Try and skip hosted
return;
}
var oembedHref = oembedLinks && oembedLinks.length && oembedLinks[0].href;
if (oembedHref && oembedHref.match(/\/wp-json\/oembed\//)) {
return;
}
var data = getWhitelistLogData(meta, oembed);
if (data) {
if (whitelistRecord && !whitelistRecord.isDefault) {
// Check if all detected rels present in whitelist record.
var hasNew = false;
for(var key in data) {
var bits = key.split('_');
var source = bits[0];
var rel = bits[1];
// Skip existing source-rel.
if (!whitelistRecord[source] || !whitelistRecord[source][rel]) {
hasNew = true
}
}
if (!hasNew) {
return hasNew;
}
}
data.uri = uri;
if (oembedHref) {
data.oembed = oembedHref;
}
// TODO: check options
fetchStream({
qs: data,
// Reviewed.
uri: CONFIG.WHITELIST_LOG_URL,
method: 'GET',
})
.then(res => {
if (res.status !== 200) {
console.error('Error logging url:', uri, res.status);
}
})
.catch(error => {
console.error('Error logging url:', uri, error);
});
}
};
export function filterLinks(data, options) {
var links = data.links;
for(var i = 0; i < links.length;) {
var link = links[i];
// SSL.
var isImage = link.type.indexOf('image') === 0;
var isHTML5Video = link.type.indexOf('video/') === 0;
if (options.filterNonSSL) {
var sslProtocol = link.href && link.href.match(/^(https:)?\/\//i);
var hasSSL = link.rel.indexOf('ssl') > -1;
if (sslProtocol || hasSSL || isImage || isHTML5Video) {
// Good: has ssl.
} else {
// Filter non ssl if required.
link.error = true;
}
}
// HTML5.
if (options.filterNonHTML5) {
var hasHTML5 = link.rel.indexOf('html5') > -1;
var isReader = link.rel.indexOf('reader') > -1;
if (hasHTML5 || isImage || isHTML5Video || isReader) {
// Good: is HTML5.
} else {
// Filter non HTML5 if required.
link.error = true;
}
}
// Max-width.
if (options.maxWidth) {
var isImage = link.type.indexOf('image') === 0;
// TODO: force make html5 video responsive?
var isHTML5Video = link.type.indexOf('video/') === 0;
var m = link.media;
if (m && !isImage && !isHTML5Video) {
if (m.width && m.width > options.maxWidth) {
link.error = true;
} else if (m['min-width'] && m['min-width'] > options.maxWidth) {
link.error = true;
}
}
}
if (link.error) {
links.splice(i, 1);
} else {
i++;
}
}
};
function iterateLinks(links, func) {
if (links instanceof Array) {
return links.forEach(func);
} else if (typeof links === 'object') {
for(var id in links) {
var items = links[id];
if (items instanceof Array) {
items.forEach(func);
}
}
}
}
export function generateLinksHtml(data, options) {
// Links may be grouped.
var links = data.links;
options.iframelyData = data;
if (CONFIG.GENERATE_LINK_PARAMS) {
_.extend(options, CONFIG.GENERATE_LINK_PARAMS);
}
iterateLinks(links, function(link) {
if (!link.html && !link.type.match(/^image/)) {
// Force make mp4 video to be autoplay in autoplayMode.
if (options.autoplayMode && link.type.indexOf('video/') === 0 && link.rel.indexOf('autoplay') === -1) {
link.rel.push('autoplay');
}
var html = htmlUtils.generateLinkElementHtml(link, options);
if (html) {
link.html = html;
}
}
});
if (!data.html) {
var links_list = [];
iterateLinks(links, function(link) {
links_list.push(link);
});
var plain_data = _.extend({}, data, {links:links_list});
// Prevent override main html field.
var mainLink = htmlUtils.findMainLink(plain_data, options);
if (mainLink) {
var html = mainLink.html;
if (!html && mainLink.type.match(/^image/)) {
html = htmlUtils.generateLinkElementHtml(mainLink, options);
}
if (html) {
data.rel = mainLink.rel;
data.html = html;
if (mainLink.options) {
data.options = mainLink.options;
}
}
}
}
data.rel = data.rel || [];