-
Notifications
You must be signed in to change notification settings - Fork 308
/
Copy pathcore.js
1509 lines (1167 loc) · 51.1 KB
/
core.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
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
(function(core) {
var _ = require('underscore'),
request = require('request'),
urlLib = require('url');
var pluginUtils = require('./loader/utils'),
utils = require('./utils'),
sysUtils = require('../logging'),
oembedUtils = require('./oembed'),
pluginLoader = require('./loader/pluginLoader'),
requestWrapper = require('./request');
var plugins = pluginLoader._plugins,
providedParamsDict = pluginLoader._providedParamsDict,
pluginsList = pluginLoader._pluginsList,
usedParamsDict = pluginLoader._usedParamsDict,
postPluginsList = pluginLoader._postPluginsList,
PLUGIN_METHODS = pluginUtils.PLUGIN_METHODS;
/*
* Recursively finds plugin methods to run, including 'mixins' and dependencies (up and down by tree).
* */
function findPluginMethods(pluginId, loadedParams, pluginsUrlMatches, usedMethods, usedParams, methods, scannedPluginsIds, usedDomains, mandatoryParams) {
/*
* Params:
*
*
* pluginId - id of plugin where methods to run will be found.
*
*
* loadedParams - list of currently loaded params keys.
* var loadedParams = _.keys(context);
* loadedParams = ['cb', 'uri', 'title', 'meta']
*
*
* pluginsUrlMatches - dict of urlMatches for specific plugins.
* pluginsUrlMatches = {
* pluginId: matchObj
* }
*
*
* usedMethods - global dict with registered to run, or finished methods.
* This is used control each async function state.
* usedMethods = {
* pluginId: {
* methodName1: false, // - method registered to run.
* methodName2: true, // - method finished.
* }
* }
*
*
* usedParams - global dict of params used or asked to use in searched plugins.
* This dict used to determine new params (mandatory params), which could be used in some new plugins.
* E.g. plugin can return 'youtube_data' param. And then core will find plugins which will use 'youtube_data' to provide embed code.
* This is used for "go down by tree" algorithm.
* usedParams = {
* paramName: true
* }
*
*
* methods - result methods to run list. This is main returned value.
* methods = [{
* pluginId: pluginId,
* name: methodName,
* handle: <function>
* }]
*
*
* scannedPluginsIds - all plugins scanned in one 'runPlugins' iteration with single loadedParams set.
* Used to prevent recursion in one iteration.
* scannedPluginsIds = {
* pluginId: true
* }
*
*
* mandatoryParams - list of new params not used by plugins. Core will find what can use them.
* 'mandatoryParams' enables mandatory mode: function will use _only_ methods which has this input 'mandatoryParams'.
* This is used for "go down by tree" algorithm.
* var mandatoryParams = _.difference(loadedParams, _.keys(usedParams));
* mandatoryParams = [
* paramName
* ]
*
* */
// Do not process plugin twice (if recursive dependency).
if (pluginId in scannedPluginsIds) {
return;
}
var plugin = plugins[pluginId];
if (!plugin) {
return;
}
// Register result array.
scannedPluginsIds[plugin.id] = true;
// Process all mixins.
if (!mandatoryParams) {
var mixins = plugin.module.mixins;
if (mixins) {
for(var i = 0; i < mixins.length; i++) {
findPluginMethods(mixins[i], loadedParams, pluginsUrlMatches, usedMethods, usedParams, methods, scannedPluginsIds, usedDomains);
}
}
}
var usedPluginMethods = usedMethods[plugin.id] = usedMethods[plugin.id] || {};
// Check each plugin method.
for(var i = 0; i < PLUGIN_METHODS.length; i++) {
var method = PLUGIN_METHODS[i];
if (method in plugin.methods) {
// Skip used method.
if (usedPluginMethods && (method in usedPluginMethods)) {
continue;
}
var params = plugin.methods[method];
// If mandatory params mode.
if (mandatoryParams && mandatoryParams.length > 0) {
if (_.intersection(params, mandatoryParams).length === 0) {
// Skip method if its not using mandatory params.
continue;
}
}
var absentParams = _.difference(params, loadedParams);
// If "__" super mandatory params are absent - skip plugin.
var hasMandatoryParams = false;
for(var j = 0; j < absentParams.length && !hasMandatoryParams; j++) {
var param = absentParams[j];
if (param.substr(0, 2) === "__") {
hasMandatoryParams = true;
}
}
if (hasMandatoryParams) {
continue;
}
// 'ulrMatch' workaround.
// Each plugin can have own match, or no match at all.
var urlMatchParamIdx = absentParams.indexOf('urlMatch');
if (urlMatchParamIdx > -1) {
if (pluginsUrlMatches[pluginId]) {
// If 'urlMatch' for plugin found - remove from 'absentParams'.
absentParams.splice(urlMatchParamIdx, 1);
} else {
// Skip method with 'urlMatch' required. Match not found for that plugin.
continue;
}
}
if (absentParams.length > 0) {
// This branch finds methods in upper dependencies tree.
var pluginsId = findPluginsForAbsentParams(absentParams, usedDomains, usedParams);
// Find absent params in other plugins 'provides' attribute.
for(var j = 0; j < pluginsId.length; j++) {
var foundPluginId = pluginsId[j];
findPluginMethods(foundPluginId, loadedParams, pluginsUrlMatches, usedMethods, usedParams, methods, scannedPluginsIds, usedDomains);
}
} else {
// This branch goes down by the tree.
// Mark method used but not finished.
usedPluginMethods[method] = 1;
// Method will run, store in result set.
methods.push({
pluginId: pluginId,
name: method,
handle: plugin.module[method]
});
}
}
}
}
/*
* Run list of methods.
* */
function runMethods(methods, context, pluginsUrlMatches, options, asyncMethodCb) {
// Sync results list.
var results = [];
for(var i = 0; i < methods.length; i++) {
(function() {
var method = methods[i];
var plugin = plugins[method.pluginId];
var params = plugin.methods[method.name];
var args = [];
if (options.debug) {
var methodTimer = utils.createTimer();
}
var asyncMethod = false;
var timeout;
// Result callback for both sync and async methods.
var callback = function(error, data) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
} else if (asyncMethod) {
return;
}
if (data) {
for(var key in data) {
var v = data[key];
if (v === null || (typeof v === 'undefined') || (typeof v === 'number' && isNaN(v))) {
delete data[key];
}
}
}
var result = {
method: method,
data: data
};
if (options.debug) {
result.time = methodTimer();
}
if (error) {
if (error.code) {
var statusCode = error.code;
error = {};
error[SYS_ERRORS.responseStatusCode] = statusCode;
}
if (error instanceof Error) {
error = error.toString();
}
result.error = error;
}
// TODO: rerun plugins check.
if (asyncMethod) {
// Grant real async if callback was called before function return.
process.nextTick(function() {
asyncMethodCb(null, [result]);
});
} else {
// Mark method finished - later, on results callback.
results.push(result);
}
};
// Prepare specific params (cb, urlMatch).
for(var j = 0; j < params.length; j++) {
var param = params[j];
if (param === 'cb') {
// Generate callback param.
asyncMethod = true;
args.push(callback);
continue;
} else if (param === 'urlMatch') {
// Generate 'urlMatch' param depending on plugin.
args.push(pluginsUrlMatches[method.pluginId]);
continue;
}
args.push(context[param]);
}
try {
// TODO: check timeout for async method.
if (asyncMethod) {
timeout = setTimeout(function() {
// In case of async timeout - call 'callback' with error param.
callback(SYS_ERRORS.timeout);
}, options.timeout || CONFIG.RESPONSE_TIMEOUT);
}
// Call method.
var result = method.handle.apply(plugin.module, args);
} catch(ex) {
// Immediately stop method with error.
callback(ex);
if (!asyncMethod) {
// Prevent run sync callback.
asyncMethod = true;
}
}
// Sync callback.
if (!asyncMethod) {
callback(null, result);
}
})();
}
// Call sync methods result in next tick (imitate real async).
if (results.length) {
process.nextTick(function() {
asyncMethodCb(null, results);
});
}
}
/*
* Single iteration of run plugins wave.
* */
function runPluginsIteration(requiredPlugins, context, pluginsUrlMatches, usedMethods, usedParams, usedDomains, options, asyncMethodCb) {
var loadedParams = _.keys(context);
var mandatoryParams = _.difference(loadedParams, _.keys(usedParams));
// Reset scanned plugins for each iteration.
var scannedPluginsIds = {};
// Methods to run will be here.
var methods = [];
// Find methods in each required plugin.
for(var i = 0; i < requiredPlugins.length; i++) {
var plugin = requiredPlugins[i];
findPluginMethods(plugin.id, loadedParams, pluginsUrlMatches, usedMethods, usedParams, methods, scannedPluginsIds, usedDomains);
}
// If has new unused params (mandatoryParams) - then find plugins which can use them.
if (mandatoryParams && mandatoryParams.length > 0) {
var secondaryPlugins = findPluginsForMandatoryParams(mandatoryParams, usedDomains);
// Find methods in plugins, which can use mandatory params.
for(var i = 0; i < secondaryPlugins.length; i++) {
var pluginId = secondaryPlugins[i];
findPluginMethods(pluginId, loadedParams, pluginsUrlMatches, usedMethods, usedParams, methods, scannedPluginsIds, usedDomains, mandatoryParams);
}
}
// Run found methods.
runMethods(methods, context, pluginsUrlMatches, options, asyncMethodCb);
return methods.length;
}
function getPluginsSet(uri, options, usedParams) {
var initialPlugins = [],
usedDomains,
isDomainPluginsMode = false,
pluginsUrlMatches = {};
if (options.fetchParam) {
var paramPlugins = providedParamsDict[options.fetchParam];
if (paramPlugins && paramPlugins.length) {
// Store dependency param. Need to determine mandatory params in feature.
usedParams[options.fetchParam] = true;
for(var k = 0; k < paramPlugins.length; k++) {
var foundPluginId = paramPlugins[k];
initialPlugins.push(plugins[foundPluginId]);
}
}
} else {
var domain = uri.split('/')[2].replace(/^www\./i, "").toLowerCase();
var pluginMatchesByDomains = {};
function registerDomainPlugin(plugin, match) {
usedDomains = usedDomains || {};
usedDomains[plugin.domain] = true;
var domainPlugins = pluginMatchesByDomains[plugin.domain] = pluginMatchesByDomains[plugin.domain] || {};
domainPlugins[plugin.id] = !!match;
if (plugin.mixinAllGeneric) {
options.mixAllWithDomainPlugin = true;
}
}
if (!options.useOnlyGenericPlugins) {
for(var i = 0; i < pluginsList.length; i++) {
var plugin = pluginsList[i];
if (plugin.domain) {
// Match only by regexp. Used in specific cases where domain changes (like national domain).
var match = null, j = 0, res = plugin.re;
while (!match && j < res.length) {
match = uri.match(res[j]);
j++;
}
if (match) {
// Store match for plugin.
registerDomainPlugin(plugin, match);
pluginsUrlMatches[plugin.id] = match;
continue;
} else if (res.length) {
// Skip plugin with unmatched re.
continue;
}
// Straight match by domain.
// Positive match on plugin.domain="domain.com", domain="sub.domain.com"
// Positive match on plugin.domain="domain.com", domain="domain.com"
var idx = domain.indexOf(plugin.domain);
if (idx === -1 || ((idx > 0) && domain.charAt(idx - 1) !== '.')) {
// Break if not found, or not dot separation.
continue;
}
if (idx > 0) {
var subdomain = domain.substring(0, idx - 1);
if (subdomain === 'blog') {
// Skip "blog.*.*" blog page for domain plugin without re.
continue;
}
}
var match = (idx + plugin.domain.length) === domain.length;
if (match) {
registerDomainPlugin(plugin, null);
}
}
}
}
function addAllGeneric() {
// Use all generic plugins.
for(var i = 0; i < pluginsList.length; i++) {
var plugin = pluginsList[i];
if (!plugin.domain && !plugin.custom) {
initialPlugins.push(plugin);
}
}
}
// In domain debug: add all plugins before domain plugins to make them low priority.
if (options.mixAllWithDomainPlugin) {
addAllGeneric();
}
for(var domain in pluginMatchesByDomains) {
var domainPlugins = pluginMatchesByDomains[domain];
var matchedPluginsNames = [];
// Find domain plugins with re match.
for(var pluginId in domainPlugins) {
var match = domainPlugins[pluginId];
if (match) {
matchedPluginsNames.push(pluginId);
}
}
// Add all domain plugins without re.
// Old: If no re match - use only non-re domain plugins.
//if (matchedPluginsNames.length === 0) {
for(var pluginId in domainPlugins) {
var plugin = plugins[pluginId];
if (!plugin.re.length) {
matchedPluginsNames.push(pluginId);
}
}
//}
for(var i = 0; i < matchedPluginsNames.length; i++) {
var pluginId = matchedPluginsNames[i];
isDomainPluginsMode = true;
initialPlugins.push(plugins[pluginId]);
}
}
// If not domain or no domain plugins - fill with generic.
if (initialPlugins.length === 0) {
addAllGeneric();
}
if (options.forceParams) {
// TODO: replace forEach
options.forceParams.forEach(function(param) {
var paramPlugins = providedParamsDict[param];
if (paramPlugins && paramPlugins.length) {
// Store dependency param. Need to determine mandatory params in feature.
usedParams[param] = true;
for(var k = 0; k < paramPlugins.length; k++) {
var foundPluginId = paramPlugins[k];
var exists = _.find(initialPlugins, function(plugin) {
return plugin.id === foundPluginId;
});
if (!exists) {
initialPlugins.push(plugins[foundPluginId]);
}
}
}
});
}
}
return {
initialPlugins: initialPlugins,
pluginsUrlMatches: pluginsUrlMatches,
usedDomains: usedDomains,
isDomainPluginsMode: isDomainPluginsMode
};
}
/*
* Find plugins which can use 'mandatoryParams'.
*
* Find only generic plugins or plugins from matched domain.
* */
function findPluginsForMandatoryParams(mandatoryParams, usedDomains) {
var foundPluginsDict = {},
result = [];
// TODO: gether secondaryPlugins by dict, who uses mandatory params. Not full for-loop.
for(var i = 0; i < mandatoryParams.length; i++) {
var pluginsIds = usedParamsDict[mandatoryParams[i]];
if (pluginsIds) {
for(var j = 0; j < pluginsIds.length; j++) {
var pluginId = pluginsIds[j];
var plugin = plugins[pluginId];
// Prevent duplicates.
// Find only generic plugins or plugins from matched domain.
// Skip custom plugins.
if (!(pluginId in foundPluginsDict) && !plugin.custom && (!plugin.domain || (usedDomains && (plugin.domain in usedDomains)))) {
foundPluginsDict[pluginId] = true;
result.push(pluginId);
}
}
}
}
return result;
}
/*
* Find plugins which can produce 'absentParams'.
*
* Find only generic plugins or plugins from matched domain.
* */
function findPluginsForAbsentParams(absentParams, usedDomains, usedParams) {
var foundPluginsDict = {},
result = [];
for(var i = 0; i < absentParams.length; i++) {
var param = absentParams[i];
// Find absent params in other plugins 'provides' attribute.
var paramPlugins = providedParamsDict[param];
if (paramPlugins && paramPlugins.length) {
for (var j = 0; j < paramPlugins.length; j++) {
var pluginId = paramPlugins[j];
var plugin = plugins[pluginId];
// Prevent duplicates.
// Find only generic plugins or plugins from matched domain.
if (!(pluginId in foundPluginsDict) && (!plugin.domain || (usedDomains && (plugin.domain in usedDomains)))) {
usedParams[param] = true;
foundPluginsDict[pluginId] = true;
result.push(pluginId);
}
}
}
}
return result;
}
function runPostPluginsIterationCall(methodName, iterationPluginContexts) {
for(var i = 0; i < postPluginsList.length; i++) {
(function() {
var plugin = postPluginsList[i];
var handle = plugin.module[methodName];
if (!handle) {
return;
}
var iterationPluginContext = iterationPluginContexts[plugin.id] = iterationPluginContexts[plugin.id] || {};
try {
handle.apply(plugin.module, [iterationPluginContext]);
} catch(ex) {
console.error(" -- Post plugin error in", plugin.id + "." + methodName, ex);
}
})();
}
}
function runPostPlugins(link, dataRecord, usedMethods, context, pluginsContexts, iterationPluginContexts, options, asyncMethodCb) {
// Sync results list.
var results = [];
for(var i = 0; i < postPluginsList.length; i++) {
(function() {
// This will prevent lower priority plugins if previous _sync_ plugin placed link.error.
if (link.error) {
return;
}
var plugin = postPluginsList[i];
var method = {
pluginId: plugin.id,
name: 'prepareLink',
handle: plugin.module['prepareLink']
};
var params = plugin.methods[method.name];
var args = [];
var asyncMethod = false;
var timeout;
// Result callback for both sync and async methods.
var callback = function(error, data) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
} else if (asyncMethod) {
return;
}
var result = {
method: method,
data: data
};
if (error) {
if (error instanceof Error) {
error = error.toString();
}
console.error(" -- Post plugin error in", plugin.id + "." + method.name, error);
}
if (asyncMethod) {
// Grant real async if callback was called before function return.
process.nextTick(function() {
// Call 'asyncMethodCb' only for async post plugin, because core must wait it.
asyncMethodCb(null, [result]);
});
} else {
// Mark method finished - later, on results callback.
results.push(result);
}
};
// Prepare specific params (cb, urlMatch).
for(var j = 0; j < params.length; j++) {
var param = params[j];
if (param === 'cb') {
// Generate callback param.
asyncMethod = true;
args.push(callback);
continue;
} else if (param === 'link') {
// Generate 'link' param.
args.push(link);
continue;
} else if (param === 'pluginContext') {
var pluginContext = pluginsContexts[plugin.id] = pluginsContexts[plugin.id] || {};
// Generate 'pluginContext' param.
args.push(pluginContext);
continue;
} else if (param === 'iterationPluginContext') {
var iterationPluginContext = iterationPluginContexts[plugin.id] = iterationPluginContexts[plugin.id] || {};
// Generate 'pluginContext' param.
args.push(iterationPluginContext);
continue;
} else if (param === 'pluginId') {
args.push(dataRecord.method.pluginId);
continue;
}
args.push(context[param]);
}
var usedPluginMethods = usedMethods[plugin.id] = usedMethods[plugin.id] || {};
usedPluginMethods[method.name] = (usedPluginMethods[method.name] || 0) + 1;
try {
// TODO: check timeout for async method.
if (asyncMethod) {
timeout = setTimeout(function() {
// In case of async timeout - call 'callback' with error param.
callback(SYS_ERRORS.timeout);
}, options.timeout || CONFIG.RESPONSE_TIMEOUT);
}
// Call method.
var result = method.handle.apply(plugin.module, args);
} catch(ex) {
// Immediately stop method with error.
callback(ex);
if (!asyncMethod) {
// Prevent run sync callback again.
asyncMethod = true;
}
}
// Sync callback.
if (!asyncMethod) {
callback(null, result);
}
})();
}
// Call sync methods result in next tick (imitate real async).
if (results.length) {
process.nextTick(function() {
asyncMethodCb(null, results);
});
}
}
function useResult(usedMethods, context, pluginsContexts, allResults, result, options, asyncMethodCb) {
if (!result) {
return false;
}
var hasNewData = false;
for(var i = 0; i < result.length; i++) {
var r = result[i];
// Mark method finished.
// Mark synced to asyncMethodCb call.
var method = r.method;
var usedPluginMethods = usedMethods[method.pluginId];
usedPluginMethods[method.name] = usedPluginMethods[method.name] - 1;
if (result.error) {
console.error(" -- Plugin error", method.pluginId, method.name, result.error);
}
// Collect total result.
allResults.allData.push(r);
if (r.data && r.data.title && !context.title) {
// Store title.
context.title = r.data.title;
}
// Merge data to context.
if (r.data) {
if (!(r.data instanceof Object)) {
// Check if method result is Object.
console.error('Non object returned in', r.method.pluginId, r.method.name);
r.error = 'Non object returned';
} else if (r.method.name === 'getData') {
// Extend context with 'getData' result.
for(var key in r.data) {
// First data has priority, do not override it.
// whitelistRecord - exception for oembed plugin.
if (!(key in context) || key === 'whitelistRecord') {
context[key] = r.data[key];
hasNewData = true;
}
}
} else if (r.method.name === "getMeta") {
// Extend unified meta.
for(var key in r.data) {
var v = r.data[key];
// TODO: postprocessing meta plugins.
if (key === 'date') {
v = utils.unifyDate(v);
if (!v) {
// Disable invalid date.
r.data[key] = v;
}
}
if (key === 'duration') {
v = utils.unifyDuration(v);
if (!v) {
// Disable invalid duration.
r.data[key] = v;
}
}
if (key === 'title' || key === 'canonical') {
if (v instanceof Array) {
v = v[0];
}
}
if (key === 'author' && v.match && v.match(/^https?:\/\//)) {
key = 'author_url';
}
if (v !== '' && v !== null && (typeof v === 'string' || typeof v === 'number')) {
// Check meta plugins order.
allResults.meta._sources = allResults.meta._sources || {};
var prevOrder = null, nextOrder = null, pluginId = allResults.meta._sources[key];
if (pluginId && plugins[pluginId] && plugins[r.method.pluginId]) {
prevOrder = plugins[pluginId].order;
nextOrder = plugins[r.method.pluginId].order;
}
if (!prevOrder || !nextOrder || prevOrder < nextOrder) {
allResults.meta[key] = v;
allResults.meta._sources[key] = r.method.pluginId;
}
}
}
}
}
}
// After new context received - launch link post plugins.
for(var i = 0; i < result.length; i++) {
var r = result[i];
if (r.data && !r.error && r.method.name === 'getLink' || r.method.name === 'getLinks' || r.method.name === 'prepareLink') {
var links;
if (r.method.name === 'prepareLink') {
links = r.data && r.data.addLink;
} else {
links = r.data;
}
if (!links) {
continue;
}
if (!(links instanceof Array)) {
links = [links];
}
links = _.compact(links);
var iterationPluginContexts = {};
runPostPluginsIterationCall('startIteration', iterationPluginContexts);
for(var j = 0; j < links.length; j++) {
var link = links[j];
allResults.links.push(link);
runPostPlugins(link, r, usedMethods, context, pluginsContexts, iterationPluginContexts, options, asyncMethodCb);
}
runPostPluginsIterationCall('finishIteration', iterationPluginContexts);
}
}
return hasNewData;
}
function isEmpty(obj) {
for (var key in obj) {
return false;
}
return true;
}
function resultsHasDomainData(requiredPlugins, allData) {
var hasDomainData = false;
// Mark required plugin without methods as it is have data.
for(var i = 0; i < requiredPlugins.length && !hasDomainData; i++) {
var plugin = requiredPlugins[i];
// TODO: Optimize?
if (isEmpty(plugin.methods)) {
hasDomainData = true;
}
}
// Check if some domain plugin returned some links.
// Also see if getData returned safe_html.
for(var i = 0; i < allData.length && !hasDomainData; i++) {
var r = allData[i];
var plugin = plugins[r.method.pluginId];
if (plugin.domain && r.data && !r.error) {
var hasGetLinkMethod = plugin.methods.getLink || plugin.methods.getLinks;
var getLinkMethodUsed = r.method.name === 'getLink' || r.method.name === 'getLinks';
if ((hasGetLinkMethod && getLinkMethodUsed)
|| (r.method.name === 'getData' && r.data.safe_html)
|| (!hasGetLinkMethod && r.method.name === 'getMeta')) {
hasDomainData = true;
}
}
}
return hasDomainData;
}
var BIG_CONTEXT = ['htmlparser', 'readability', 'decode'];