-
Notifications
You must be signed in to change notification settings - Fork 976
/
Copy pathpluginManager.js
2904 lines (2704 loc) · 108 KB
/
pluginManager.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
var pluginDependencies = require('./pluginDependencies.js'),
path = require('path'),
plugins = pluginDependencies.getFixedPluginList(require('./plugins.json', 'dont-enclose'), {
"discoveryStrategy": "disableChildren",
"overwrite": path.resolve(__dirname, './plugins.json')
}),
pluginsApis = {},
mongodb = require('mongodb'),
cluster = require('cluster'),
countlyConfig = require('../frontend/express/config', 'dont-enclose'),
apiCountlyConfig = require('../api/config', 'dont-enclose'),
utils = require('../api/utils/utils.js'),
fs = require('fs'),
url = require('url'),
querystring = require('querystring'),
cp = require('child_process'),
async = require("async"),
_ = require('underscore'),
crypto = require('crypto'),
Promise = require("bluebird"),
log = require('../api/utils/log.js'),
logDbRead = log('db:read'),
logDbWrite = log('db:write'),
logDriverDb = log('driver:db'),
exec = cp.exec,
spawn = cp.spawn,
configextender = require('../api/configextender');
var pluginConfig = {};
/**
* This module handles communicaton with plugins
* @module "plugins/pluginManager"
*/
/** @lends module:plugins/pluginManager */
var pluginManager = function pluginManager() {
var events = {};
var plugs = [];
var methodCache = {};
var methodPromiseCache = {};
var configs = {};
var defaultConfigs = {};
var configsOnchanges = {};
var excludeFromUI = {plugins: true};
var finishedSyncing = true;
var expireList = [];
var masking = {};
var fullPluginsMap = {};
var coreList = ["api", "core"];
var dependencyMap = {};
/**
* Registered app types
*/
this.appTypes = [];
/**
* Events prefixed with [CLY]_ that should be recorded in core as standard data model
*/
this.internalEvents = [];
/**
* Events prefixed with [CLY]_ that should be recorded in drill
*/
this.internalDrillEvents = ["[CLY]_session"];
/**
* Segments for events prefixed with [CLY]_ that should be omitted
*/
this.internalOmitSegments = {};
/**
* Custom configuration files for different databases
*/
this.dbConfigFiles = {
countly_drill: "./drill/config.js",
countly_out: "../api/configs/config.db_out.js",
countly_fs: "../api/configs/config.db_fs.js"
};
/**
* Custom configuration files for different databases for docker env
*/
this.dbConfigEnvs = {
countly_drill: "PLUGINDRILL",
countly_out: "PLUGINOUT",
countly_fs: "PLUGINFS"
};
this.loadDependencyMap = function() {
var pluginNames = [];
var pluginsList = fs.readdirSync(path.resolve(__dirname, './')); //all plugins in folder
//filter out just folders
for (var z = 0; z < pluginsList.length; z++) {
var p = fs.lstatSync(path.resolve(__dirname, './' + pluginsList[z]));
if (p.isDirectory() || p.isSymbolicLink()) {
pluginNames.push(pluginsList[z]);
}
}
dependencyMap = pluginDependencies.getDependencies(pluginNames, {});
};
/**
* Initialize api side plugins
**/
this.init = function() {
var pluginNames = [];
var pluginsList = fs.readdirSync(path.resolve(__dirname, './')); //all plugins in folder
//filter out just folders
for (var z = 0; z < pluginsList.length; z++) {
var p = fs.lstatSync(path.resolve(__dirname, './' + pluginsList[z]));
if (p.isDirectory() || p.isSymbolicLink()) {
pluginNames.push(pluginsList[z]);
}
}
dependencyMap = pluginDependencies.getDependencies(pluginNames, {});
for (let i = 0, l = pluginNames.length; i < l; i++) {
fullPluginsMap[pluginNames[i]] = true;
try {
pluginsApis[pluginNames[i]] = require("./" + pluginNames[i] + "/api/api");
}
catch (ex) {
console.log('Skipping plugin ' + pluginNames[i] + ' as we could not load it because of errors.');
console.error(ex.stack);
console.log("Saving this plugin as disabled in db");
}
}
};
this.updatePluginsInDb = function(db, params, callback) {
try {
params.qstring.plugin = JSON.parse(params.qstring.plugin);
}
catch (err) {
console.log('Error parsing plugins');
}
if (params.qstring.plugin && typeof params.qstring.plugin === 'object') {
var self = this;
var before = {};
var fordb = {};
var arr = self.getPlugins();
for (var i in params.qstring.plugin) {
fordb['plugins.' + i] = params.qstring.plugin[i];
if (arr.indexOf(i) === -1) {
before[i] = false;
}
else {
before[i] = true;
}
}
db.collection('plugins').updateOne({'_id': 'plugins'}, {'$set': fordb}, function(err1) {
if (err1) {
log.e(err1);
}
else {
self.dispatch("/systemlogs", {params: params, action: "change_plugins", data: {before: before, update: params.qstring.plugin}});
// process.send({ cmd: "startPlugins" });
self.loadConfigs(db, function() {
callback();
});
}
});
}
};
this.initPlugin = function(pluginName) {
try {
pluginsApis[pluginName] = require("./" + pluginName + "/api/api");
fullPluginsMap[pluginName] = true;
}
catch (ex) {
console.error(ex.stack);
}
};
this.installMissingPlugins = function(db, callback) {
console.log("Checking if any plugins are missing");
var self = this;
var installPlugins = [];
db.collection("plugins").findOne({_id: "plugins"}, function(err, res) {
res = res || {};
pluginConfig = res.plugins || {}; //currently enabled plugins
//list of plugin folders
var pluginNames = [];
var pluginsList = fs.readdirSync(path.resolve(__dirname, './'));
//filter out just folders
for (var z = 0; z < pluginsList.length; z++) {
var p = fs.lstatSync(path.resolve(__dirname, './' + pluginsList[z]));
if (p.isDirectory() || p.isSymbolicLink()) {
pluginNames.push(pluginsList[z]);
}
}
for (var zz = 0; zz < pluginNames.length; zz++) {
if (typeof pluginConfig[pluginNames[zz]] === 'undefined') {
installPlugins.push(pluginNames[zz]);
}
}
if (installPlugins.length > 0) {
console.log("Plugins to install: " + JSON.stringify(installPlugins));
}
Promise.each(installPlugins, function(name) {
return new Promise(function(resolve) {
var obb = {'name': name};
if (plugins.indexOf(name) === -1) {
obb.enable = false;
}
else {
obb.enable = true;
}
self.processPluginInstall(db, obb, function() {
resolve();
});
});
}).then(function() {
if (callback) {
callback();
}
}).catch(function(rejection) {
console.log(rejection);
if (callback) {
callback();
}
});
});
};
this.reloadEnabledPluginList = function(db, callback) {
this.loadDependencyMap();
db.collection("plugins").findOne({_id: "plugins"}, function(err, res) {
if (err) {
console.log(err);
}
res = res || {};
if (Object.keys(fullPluginsMap).length > 0) {
for (var pp in res.plugins) {
if (!fullPluginsMap[pp]) {
delete res.plugins[pp];
}
}
}
pluginConfig = res.plugins || {}; //currently enabled plugins
if (callback) {
callback();
}
});
};
/**
* Load configurations from database
* @param {object} db - database connection for countly db
* @param {function} callback - function to call when configs loaded
* @param {boolean} api - was the call made from api process
**/
this.loadConfigs = function(db, callback/*, api*/) {
var self = this;
db.collection("plugins").findOne({_id: "plugins"}, function(err, res) {
if (err) {
console.log(err);
}
var pluginNames = [];
var pluginsList = fs.readdirSync(path.resolve(__dirname, './'));
for (var z = 0; z < pluginsList.length; z++) {
var p = fs.lstatSync(path.resolve(__dirname, './' + pluginsList[z]));
if (p.isDirectory() || p.isSymbolicLink()) {
pluginNames.push(pluginsList[z]);
}
}
for (let i = 0, l = pluginNames.length; i < l; i++) {
fullPluginsMap[pluginNames[i]] = true;
}
if (err) {
console.log(err);
}
if (!err) {
res = res || {};
for (let ns in configsOnchanges) {
if (configs && res && (!configs[ns] || !res[ns] || !_.isEqual(configs[ns], res[ns]))) {
configs[ns] = res[ns];
configsOnchanges[ns](configs[ns]);
}
}
configs = res;
delete configs._id;
pluginConfig = res.plugins || {}; //currently enabled plugins
self.checkConfigs(db, configs, defaultConfigs, function() {
var installPlugins = [];
for (var z1 = 0; z1 < plugins.length; z1++) {
if (typeof pluginConfig[plugins[z1]] === 'undefined') {
pluginConfig[plugins[z1]] = true;
//installPlugins.push(plugins[z]);
}
}
Promise.each(installPlugins, function(name) {
return new Promise(function(resolve) {
self.processPluginInstall(db, name, function() {
resolve();
});
});
}).then(function() {
if (callback) {
callback();
}
}).catch(function(rejection) {
console.log(rejection);
if (callback) {
callback();
}
});
/*if (api && self.getConfig("api").sync_plugins) {
self.checkPlugins(db);
}*/
if (self.getConfig("data-manager").enableDataMasking) {
self.fetchMaskingConf({"db": db});
}
});
}
else if (callback) {
callback();
}
});
};
/**
* Set default configurations
* @param {string} namespace - namespace of configuration, usually plugin name
* @param {object} conf - object with key/values default configurations
* @param {boolean} exclude - should these configurations be excluded from dashboard UI
* @param {function} onchange - function to call when configurations change
**/
this.setConfigs = function(namespace, conf, exclude, onchange) {
if (!defaultConfigs[namespace]) {
defaultConfigs[namespace] = conf;
}
else {
for (let i in conf) {
defaultConfigs[namespace][i] = conf[i];
}
}
if (exclude) {
excludeFromUI[namespace] = true;
}
if (onchange) {
configsOnchanges[namespace] = onchange;
}
};
/**
* Add collection to expire list
* @param {string} collection - collection name
**/
this.addCollectionToExpireList = function(collection) {
expireList.push(collection);
};
/**
* Get expire list array
* @returns {array} expireList - expireList array that created from plugins
**/
this.getExpireList = function() {
return expireList;
};
/**
* Set user level default configurations
* @param {string} namespace - namespace of configuration, usually plugin name
* @param {object} conf - object with key/values default configurations
**/
this.setUserConfigs = function(namespace, conf) {
if (!defaultConfigs[namespace]) {
defaultConfigs[namespace] = {};
}
if (!defaultConfigs[namespace]._user) {
defaultConfigs[namespace]._user = {};
}
for (let i in conf) {
defaultConfigs[namespace]._user[i] = conf[i];
}
};
/**
* Get configuration from specific namespace and populate empty values with provided defaults
* @param {string} namespace - namespace of configuration, usually plugin name
* @param {object} userSettings - possible other level configuration like user or app level to overwrite configs
* @param {boolean} override - if true, would simply override configs with userSettings, if false, would check if configs should be overridden
* @returns {object} copy of configs for provided namespace
**/
this.getConfig = function(namespace, userSettings, override) {
var ob = {};
if (configs[namespace]) {
for (let i in configs[namespace]) {
if (i === "_user") {
ob[i] = {};
for (let j in configs[namespace][i]) {
ob[i][j] = configs[namespace][i][j];
}
}
else {
ob[i] = configs[namespace][i];
}
}
}
else if (defaultConfigs[namespace]) {
for (let i in defaultConfigs[namespace]) {
if (i === "_user") {
ob[i] = {};
for (let j in defaultConfigs[namespace][i]) {
ob[i][j] = defaultConfigs[namespace][i][j];
}
}
else {
ob[i] = defaultConfigs[namespace][i];
}
}
}
//overwrite server settings by other level settings
if (override && userSettings && userSettings[namespace]) {
for (let i in userSettings[namespace]) {
//over write it
ob[i] = userSettings[namespace][i];
}
}
else if (!override) {
//use db logic to check if overwrite
if (userSettings && userSettings[namespace] && ob._user) {
for (let i in ob._user) {
//check if this config is allowed to be overwritten
if (ob._user[i]) {
//over write it
ob[i] = userSettings[namespace][i];
}
}
}
}
return ob;
};
/**
* Get all configs for all namespaces
* @returns {object} copy of all configs
**/
this.getAllConfigs = function() {
//get unique namespaces
var a = Object.keys(configs);
var b = Object.keys(defaultConfigs);
var c = a.concat(b.filter(function(item) {
return a.indexOf(item) < 0;
}));
var ret = {};
for (let i = 0; i < c.length; i++) {
if (!excludeFromUI[c[i]] && (plugins.indexOf(c[i]) === -1 || pluginConfig[c[i]])) {
ret[c[i]] = this.getConfig(c[i]);
}
}
return ret;
};
/**
* Get all configs for all namespaces overwritted by user settings
* @param {object} userSettings - possible other level configuration like user or app level to overwrite configs
* @returns {object} copy of all configs
**/
this.getUserConfigs = function(userSettings) {
userSettings = userSettings || {};
//get unique namespaces
var a = Object.keys(configs);
var b = Object.keys(defaultConfigs);
var c = a.concat(b.filter(function(item) {
return a.indexOf(item) < 0;
}));
var ret = {};
for (let i = 0; i < c.length; i++) {
if (!excludeFromUI[c[i]]) {
var conf = this.getConfig(c[i], userSettings);
for (let name in conf) {
if (conf._user && conf._user[name]) {
if (!ret[c[i]]) {
ret[c[i]] = {};
}
ret[c[i]][name] = conf[name];
}
}
}
}
return ret;
};
/**
* Check if there are changes in configs ans store the changes
* @param {object} db - database connection for countly db
* @param {object} current - current configs we have
* @param {object} provided - provided configs
* @param {function} callback - function to call when checking finished
**/
this.checkConfigs = function(db, current, provided, callback) {
var diff = getObjectDiff(current, provided);
if (Object.keys(diff).length > 0) {
db.collection("plugins").findAndModify({_id: "plugins"}, {}, {$set: flattenObject(diff)}, {upsert: true, new: true}, function(err, res) {
if (!err && res && res.value) {
for (var i in diff) {
if (res.value[i]) {
current[i] = res.value[i];
}
}
}
if (callback) {
callback();
}
});
}
else if (callback) {
callback();
}
};
/**
* Update existing configs, when syncing between servers
* @param {object} db - database connection for countly db
* @param {string} namespace - namespace of configuration, usually plugin name
* @param {object} conf - provided config
* @param {function} callback - function to call when updating finished
**/
this.updateConfigs = function(db, namespace, conf, callback) {
var update = {};
if (namespace === "_id") {
if (callback) {
callback();
}
}
else {
update[namespace] = conf;
db.collection("plugins").update({_id: "plugins"}, {$set: flattenObject(update)}, {upsert: true}, function(err) {
if (err) {
console.log(err);
}
if (callback) {
callback();
}
});
}
};
/**
* Update existing application level configuration
* @param {object} db -database connection for countly db
* @param {string} appId - id of application
* @param {string} namespace - name of plugin
* @param {object} config - new configuration object for selected plugin
* @param {function} callback - function that is called when updating has finished
**/
this.updateApplicationConfigs = function(db, appId, namespace, config, callback) {
var pluginName = 'plugins.'.concat(namespace);
db.collection('apps').updateOne({_id: appId}, {$set: {[pluginName]: config}}, function(error, result) {
if (error) {
log.e('Error updating application level %s plugin configuration.Got error:%j', namespace, error);
}
if (callback) {
if (error) {
callback(error, null);
}
else {
callback(null, result);
}
}
});
};
var preventKillingNumberType = function(configsPointer, changes) {
for (var k in changes) {
if (!Object.prototype.hasOwnProperty.call(configsPointer, k) || !Object.prototype.hasOwnProperty.call(changes, k)) {
continue;
}
if (changes[k] !== null && configsPointer[k] !== null) {
if (typeof changes[k] === 'object' && typeof configsPointer[k] === 'object') {
preventKillingNumberType(configsPointer[k], changes[k]);
}
else if (typeof configsPointer[k] === 'number' && typeof changes[k] !== 'number') {
try {
changes[k] = parseInt(changes[k], 10);
changes[k] = changes[k] || 0;
}
catch (e) {
changes[k] = 2147483647;
}
}
else if (typeof configsPointer[k] === 'string' && typeof changes[k] === 'number') {
changes[k] = changes[k] + "";
}
}
}
};
/**
* Update all configs with provided changes
* @param {object} db - database connection for countly db
* @param {object} changes - provided changes
* @param {function} callback - function to call when updating finished
**/
this.updateAllConfigs = function(db, changes, callback) {
if (changes.api) {
//country data tracking is changed
if (changes.api.country_data) {
//user disabled country data tracking while city data tracking is enabled
if (changes.api.country_data === false && configs.api.city_data === true) {
//disable city data tracking
changes.api.city_data = false;
}
}
//city data tracking is changed
if (changes.api.city_data) {
//user enabled city data tracking while country data tracking is disabled
if (changes.api.city_data === true && configs.api.country_data === false) {
//enable country data tracking
changes.api.country_data = true;
}
}
}
for (let k in changes) {
preventKillingNumberType(configs[k], changes[k]);
_.extend(configs[k], changes[k]);
if (k in configsOnchanges) {
configsOnchanges[k](configs[k]);
}
}
db.collection("plugins").update({_id: "plugins"}, {$set: flattenObject(configs)}, {upsert: true}, function() {
if (callback) {
callback();
}
});
};
/**
* Update user configs with provided changes
* @param {object} db - database connection for countly db
* @param {object} changes - provided changes
* @param {string} user_id - user for which to update settings
* @param {function} callback - function to call when updating finished
**/
this.updateUserConfigs = function(db, changes, user_id, callback) {
db.collection("members").findOne({ _id: db.ObjectID(user_id) }, function(err, member) {
var update = {};
for (let k in changes) {
update[k] = {};
_.extend(update[k], configs[k], changes[k]);
if (member.settings && member.settings[k]) {
_.extend(update[k], member.settings[k], changes[k]);
}
}
db.collection("members").update({ _id: db.ObjectID(user_id) }, { $set: flattenObject(update, "settings") }, { upsert: true }, function() {
if (callback) {
callback();
}
});
});
};
/**
* Allow extending object module is exporting by using extend folders in countly
* @param {string} name - filename to extend
* @param {object} object - object to extend
**/
this.extendModule = function(name, object) {
//plugin specific extend
for (let i = 0, l = plugins.length; i < l; i++) {
try {
require("./" + plugins[i] + "/extend/" + name)(object);
}
catch (ex) {
//silent error, not extending or no module
if (!ex.code || ex.code !== "MODULE_NOT_FOUND") {
console.log(ex);
}
}
}
//global extend
try {
require("../extend/" + name)(object);
}
catch (ex) {
//silent error, not extending or no module
if (!ex.code || ex.code !== "MODULE_NOT_FOUND") {
console.log(ex);
}
}
};
this.isPluginOn = function(name) {
if (coreList.indexOf(name) === -1) { //is one of plugins
if (pluginConfig[name]) {
return true;
}
else {
return false;
}
}
else {
return true;
}
};
this.getFeatureName = function() {
var stack = new Error('test').stack;
stack = stack.split('\n');
//0 - error, 1 - this function, 2 - pluginmanager, 3 - right path)
if (stack && stack[3]) {
stack = stack[3];
stack = stack.split('/');
for (var z = 0; z < stack.length - 3; z++) {
if (stack[z] === 'plugins') {
return stack[z + 1];
}
}
}
};
/**
* Register listening to new event on api side
* @param {string} event - event to listen to
* @param {function} callback - function to call, when event happens
* @param {boolean} unshift - whether to register a high-priority callback (unshift it to the listeners array)
* @param {string} featureName - name of plugin
**/
this.register = function(event, callback, unshift = false, featureName) {
if (!events[event]) {
events[event] = [];
}
//{"cb":callback, "plugin":
if (!featureName) {
featureName = this.getFeatureName();
featureName = featureName || 'core';
}
events[event][unshift ? 'unshift' : 'push']({"cb": callback, "name": featureName});
};
// TODO: Remove this function and all it calls when moving to Node 12.
var promiseAllSettledBluebirdToStandard = function(bluebirdResults) {
return bluebirdResults.map((bluebirdResult) => {
const isFulfilled = bluebirdResult.isFulfilled();
const status = isFulfilled ? 'fulfilled' : 'rejected';
const value = isFulfilled ? bluebirdResult.value() : undefined;
const reason = isFulfilled ? undefined : bluebirdResult.reason();
return { status, value, reason };
});
};
/**
* Dispatch specific event on api side
* @param {string} event - event to dispatch
* @param {object} params - object with parameters to pass to event
* @param {function} callback - function to call, when all event handlers that return Promise finished processing
* @returns {boolean} true if any one responded to event
**/
this.dispatch = function(event, params, callback) {
var used = false,
promises = [];
var promise;
if (events[event]) {
try {
for (let i = 0, l = events[event].length; i < l; i++) {
var isEnabled = true;
if (fullPluginsMap[events[event][i].name] && pluginConfig[events[event][i].name] === false) {
isEnabled = false;
}
if (events[event][i] && events[event][i].cb && isEnabled) {
try {
promise = events[event][i].cb.call(null, params);
}
catch (error) {
promise = Promise.reject(error);
console.error(error.stack);
}
if (promise) {
used = true;
}
promises.push(promise);
}
}
}
catch (ex) {
console.error(ex.stack);
}
//should we create a promise for this dispatch
if (params && params.params && params.params.promises) {
params.params.promises.push(new Promise(function(resolve) {
Promise.allSettled(promises).then(function(results) {
resolve();
if (callback) {
callback(null, promiseAllSettledBluebirdToStandard(results));
}
});
}));
}
else if (callback) {
Promise.allSettled(promises).then(function(results) {
callback(null, promiseAllSettledBluebirdToStandard(results));
});
}
}
else if (callback) {
callback();
}
return used;
};
/**
* Dispatch specific event on api side and wait until all event handlers have processed the event (legacy)
* @param {string} event - event to dispatch
* @param {object} params - object with parameters to pass to event
* @param {function} callback - function to call, when all event handlers that return Promise finished processing
* @returns {boolean} true if any one responded to event
**/
this.dispatchAllSettled = function(event, params, callback) {
return this.dispatch(event, params, callback);
};
/**
* Dispatch specific event on api side
*
* @param {string} event - event to dispatch
* @param {object} params - object with parameters to pass to event
* @returns {Promise} which resolves to array of objects returned by events if any or error
*/
this.dispatchAsPromise = function(event, params) {
return new Promise((res, rej) => {
this.dispatch(event, params, (err, results) => {
if (err) {
rej(err);
}
else {
res(results || []);
}
});
});
};
/**
* Load plugins frontend app.js and expose static paths for plugins
* @param {object} app - express app
* @param {object} countlyDb - connection to countly database
* @param {object} express - reference to express js
**/
this.loadAppStatic = function(app, countlyDb, express) {
var pluginNames = [];
var pluginsList = fs.readdirSync(path.resolve(__dirname, './')); //all plugins in folder
//filter out just folders
for (var z = 0; z < pluginsList.length; z++) {
var p = fs.lstatSync(path.resolve(__dirname, './' + pluginsList[z]));
if (p.isDirectory() || p.isSymbolicLink()) {
pluginNames.push(pluginsList[z]);
}
}
for (let i = 0, l = pluginNames.length; i < l; i++) {
try {
var plugin = require("./" + pluginNames[i] + "/frontend/app");
plugs.push({'name': pluginNames[i], "plugin": plugin});
app.use(countlyConfig.path + '/' + pluginNames[i], express.static(__dirname + '/' + pluginNames[i] + "/frontend/public", { maxAge: 31557600000 }));
if (plugin.staticPaths) {
plugin.staticPaths(app, countlyDb, express);
}
}
catch (ex) {
console.log("skipping plugin because of errors:" + pluginNames[i]);
console.error(ex.stack);
}
}
};
/**
* Call init method of plugin's frontend app.js modules
* @param {object} app - express app
* @param {object} countlyDb - connection to countly database
* @param {object} express - reference to express js
**/
this.loadAppPlugins = function(app, countlyDb, express) {
for (let i = 0; i < plugs.length; i++) {
try {
//plugs[i].init(app, countlyDb, express);
if (plugs[i] && plugs[i].plugin && plugs[i].plugin.init && typeof plugs[i].plugin.init === 'function') {
plugs[i].plugin.init({
name: plugs[i].name,
get: function(pathTo, callback) {
var pluginName = this.name;
if (!callback) {
app.get(pathTo);
}
else {
app.get(pathTo, function(req, res, next) {
if (pluginConfig[pluginName]) {
callback(req, res, next);
}
else {
next();
}
});
}
},
post: function(pathTo, callback) {
var pluginName = this.name;
app.post(pathTo, function(req, res, next) {
if (pluginConfig[pluginName] && callback && typeof callback === 'function') {
callback(req, res, next);
}
else {
next();
}
});
},
use: function(pathTo, callback) {
if (!callback) {
callback = pathTo;
pathTo = '/';//fallback to default
}
var pluginName = this.name;
app.use(pathTo, function(req, res, next) {
if (pluginConfig[pluginName] && callback && typeof callback === 'function') {
callback(req, res, next);
}
else {
next();
}
});
},
all: function(pathTo, callback) {
if (!callback) {
callback = pathTo;
pathTo = '/';//fallback to default
}
var pluginName = this.name;
app.all(pathTo, function(req, res, next) {
if (pluginConfig[pluginName] && callback && typeof callback === 'function') {
callback(req, res, next);
}
else {
next();
}
});
}
}, countlyDb, express);
}
}
catch (ex) {
console.error(ex.stack);
}
}
};
/**
* Call specific predefined methods of plugin's frontend app.js modules
* @param {string} method - method name
* @param {object} params - object with arguments
* @returns {boolean} if any of plugins had that method
**/
this.callMethod = function(method, params) {
var res = false;
if (methodCache[method]) {
if (methodCache[method].length > 0) {
for (let i = 0; i < methodCache[method].length; i++) {
try {
if (methodCache[method][i][method](params)) {
res = true;
}
}
catch (ex) {
console.error(ex.stack);
}
}
}
}
else {
methodCache[method] = [];
for (let i = 0; i < plugs.length; i++) {
try {
if (plugs[i].plugin && plugs[i].plugin[method]) {
methodCache[method].push(plugs[i].plugin);
if (plugs[i].plugin[method](params)) {
res = true;
}