-
Notifications
You must be signed in to change notification settings - Fork 980
Expand file tree
/
Copy pathapi.js
More file actions
1900 lines (1829 loc) · 72.6 KB
/
api.js
File metadata and controls
1900 lines (1829 loc) · 72.6 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
var exported = {},
requestProcessor = require('../../../api/utils/requestProcessor'),
common = require('../../../api/utils/common.js'),
crypto = require('crypto'),
log = common.log('star-rating:api'),
countlyCommon = require('../../../api/lib/countly.common.js'),
plugins = require('../../pluginManager.js'),
{ validateCreate, validateRead, validateUpdate, validateDelete } = require('../../../api/utils/rights.js'),
countlyFs = require('../../../api/utils/countlyFs.js');
var fetch = require('../../../api/parts/data/fetch.js');
var ejs = require("ejs"),
fs = require('fs'),
path = require('path'),
reportUtils = require('../../reports/api/utils.js');
var cohortsEnabled = plugins.getPlugins().indexOf('cohorts') > -1;
var surveysEnabled = plugins.getPlugins().indexOf('surveys') > -1;
if (cohortsEnabled) {
var cohorts = require('../../cohorts/api/parts/cohorts');
}
if (!surveysEnabled) {
plugins.setConfigs("feedback", {
main_color: "#0166D6",
font_color: "#0166D6",
feedback_logo: ""
});
}
const FEATURE_NAME = 'star_rating';
const widgetProperties = {
popup_header_text: {
required: false,
type: "String"
},
consent: {
required: false,
type: "Boolean"
},
links: {
required: false,
type: "Array"
},
finalText: {
required: false,
type: "String"
},
popup_comment_callout: {
required: false,
type: "String"
},
popup_email_callout: {
required: false,
type: "String"
},
popup_button_callout: {
required: false,
type: "String"
},
popup_thanks_message: {
required: false,
type: "String"
},
trigger_position: {
required: false,
type: "String"
},
trigger_bg_color: {
required: false,
type: "String"
},
trigger_font_color: {
required: false,
type: "String"
},
trigger_button_text: {
required: false,
type: "String"
},
hide_sticker: {
required: false,
type: "Boolean"
},
app_id: {
required: true,
type: "String"
},
contact_enable: {
required: false,
type: "Boolean"
},
comment_enable: {
required: false,
type: "Boolean"
},
trigger_size: {
required: false,
type: "String"
},
targeting: {
required: false,
type: "Object"
},
ratings_texts: {
required: false,
type: "Array"
},
rating_symbol: {
required: false,
type: "String"
},
status: {
required: true,
type: "Boolean"
},
logo: {
required: false,
type: "String"
},
logoType: {
required: false,
type: "String"
},
globalLogo: {
required: false,
type: "Boolean"
},
internalName: {
required: false,
type: "String"
},
appearance: {
required: false,
type: "Object"
},
showPolicy: {
required: false,
type: "String"
},
target_page: {
required: false,
type: "String"
},
target_pages: {
required: false,
type: "Array"
}
};
const widgetPropertyPreprocessors = {
target_pages: function(targetPages) {
try {
return JSON.parse(targetPages);
}
catch (jsonParseError) {
if (Array.isArray(targetPages)) {
return targetPages;
}
else {
return ["/"];
}
}
},
targeting: function(targeting) {
try {
return JSON.parse(targeting);
}
catch (jsonParseError) {
return null;
}
},
links: function(links) {
try {
return JSON.parse(links);
}
catch (jsonParseError) {
if (Array.isArray(links)) {
return links;
}
else {
return [];
}
}
},
ratings_texts: function(ratingsTexts) {
try {
return JSON.parse(ratingsTexts);
}
catch (jsonParseError) {
if (Array.isArray(ratingsTexts)) {
return ratingsTexts;
}
else {
return [
'Very dissatisfied',
'Somewhat dissatisfied',
'Neither satisfied Nor Dissatisfied',
'Somewhat Satisfied',
'Very Satisfied'
];
}
}
},
hide_sticker: function(hideSticker) {
try {
return !!JSON.parse(hideSticker);
}
catch (jsonParseError) {
return !!hideSticker;
}
},
status: function(status) {
try {
return !!JSON.parse(status);
}
catch (jsonParseError) {
return !!status;
}
}
};
/**
* Function to ensure we hav directory to upload files to
* @param {function} callback - callback
**/
function create_upload_dir(callback) {
var dir = path.resolve(__dirname, './../images');
fs.mkdir(dir, function(err) {
if (err) {
if (err.code === 'EEXIST') {
callback(true);
}
else {
callback(false);
}
}
else {
callback(true);
}
});
}
/**
* Used for file upload
* @param {object} myfile - file object(if empty - returns)
* @param {string} id - unique identifier
* @param {function} callback = callback function
**/
function uploadFile(myfile, id, callback) {
if (!myfile) {
callback(true);
return;
}
var tmp_path = myfile.path;
var type = myfile.type;
myfile.name = myfile.name || "png";
if (type !== "image/png" && type !== "image/gif" && type !== "image/jpeg") {
fs.unlink(tmp_path, function() { });
callback("Invalid image format. Must be png or jpeg");
return;
}
var allowedExtensions = ["gif", "jpeg", "jpg", "png"];
var ext = myfile.name.split(".");
ext = ext[ext.length - 1];
if (allowedExtensions.indexOf(ext) === -1) {
callback("Invalid file extension. Must be .png, .jpg, .gif or .jpeg");
return;
}
create_upload_dir(function() {
fs.readFile(tmp_path, (err, data) => {
if (err) {
callback("Failed to upload image");
return;
}
//convert file to data
if (data) {
try {
var pp = path.resolve(__dirname, './../images/' + id + "." + ext);
countlyFs.saveData("star-rating", pp, data, { id: "" + id + "." + ext, writeMode: "overwrite" }, function(err3) {
if (err3) {
callback("Failed to upload image");
}
else {
fs.unlink(tmp_path, function() { });
callback(true, id + "." + ext);
}
});
}
catch (SyntaxError) {
callback("Failed to upload image");
}
}
else {
callback("Failed to upload image");
}
});
});
}
(function() {
plugins.register("/permissions/features", function(ob) {
ob.features.push(FEATURE_NAME);
});
/**
* @api {get} /o/sdk Get ratings widgets
* @apiName GetWidgets
* @apiGroup Ratings
*
* @apiDescription Return feedback widgets as array, only works when surveys plugin disabled
* @apiQuery {String} method which kind feedback widgets requested, it should be 'feedback'
* @apiQuery {String} app_key app key value for related app that can be obtain from countly dashboard
* @apiQuery {String} device_id unique identifier for related device
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "result": [{
* "_id": "62543b95a3a03e229a389a54",
* "type": "rating",
* "showPolicy": "afterPageLoad",
* "appearance": {
* "position": "mleft",
* "bg_color": "#123456",
* "text_color": "#fff",
* "text": "Feedback",
* "size": "m"
* },
* "tg": [
* "/"
* ],
* "name": "What's your opinion about this page?"
* }]
* }
*
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "result": "Missing parameter \"app_key\" or \"device_id\"""
* }
*/
plugins.register("/o/sdk", function(ob) {
var params = ob.params;
// do not respond if this isn't feedback fetch request
// or surveys plugin enabled
if (params.qstring.method !== "feedback" || surveysEnabled) {
return false;
}
return new Promise(function(resolve) {
var widgets = [];
plugins.dispatch("/feedback/widgets", { params: params, widgets: widgets }, function() {
common.returnMessage(params, 200, widgets);
return resolve(true);
});
});
});
/**
* Used for file upload
* @param {string} myname - input name
* @param {object} myfile - file object
* @returns {object} Promise
**/
function uploadFeedbackFile(myname, myfile) {
return new Promise(function(resolve, reject) {
var tmp_path = myfile.path;
var type = myfile.type;
if (myfile.size > 1.5 * 1024 * 1024) {
fs.unlink(tmp_path, function() {});
reject(Error("feedback.image-error"));
}
else {
fs.readFile(tmp_path, (err, data) => {
if (err) {
reject(Error("feedback.imagee-error"));
}
//convert file to data
if (data) {
try {
var data_uri_prefix = "data:" + type + ";base64,";
var buf = Buffer.from(data);
var image = buf.toString('base64');
image = data_uri_prefix + image;
countlyFs.gridfs.saveData("feedback", myname, image, {id: myname, writeMode: "overwrite"}, function(err2) {
fs.unlink(tmp_path, function() {});
if (err2) {
return reject(err2);
}
resolve();
});
}
catch (SyntaxError) {
reject(Error("feedback.imagee-error"));
}
}
else {
reject(Error("feedback.imagee-error"));
}
});
}
});
}
/**
* @api {post} /i/feedback/upload
* @apiName Upload Image
* @apiGroup feedback
*
* @apiDescription Changes in Countly user interfaces logo
* @apiBody {File} logo
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "result": "Success"
* }
*
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "result": "Missing parameter "api_key" or "auth_token""
* }
*/
plugins.register("/i/feedback/upload", function(ob) {
// do not respond if this isn't feedback fetch request
// or surveys plugin enabled
if (surveysEnabled) {
return false;
}
var params = ob.params;
validateUpdate(params, "global_plugins", function() {
var images = ["feedback_logo"];
var flag = 0;
if (params.files) {
for (let i = 0; i < images.length; i++) {
if (params.files[images[i]]) {
flag = 1;
uploadFeedbackFile(images[i], params.files[images[i]]).then(function() {
common.returnOutput(params, {"result": "Success"});
}, function(err) {
common.returnMessage(params, 400, err.message);
});
break;
}
}
if (flag === 0) {
uploadFeedbackFile(params.qstring.name, params.files.file).then(function() {
common.returnOutput(params, {"result": "Success"});
}, function(err) {
common.returnMessage(params, 400, err.message);
});
}
}
});
return true;
});
/*
* internal event that fetch ratings widget
* and push them to passed widgets array.
*/
plugins.register("/feedback/widgets", function(ob) {
return new Promise(function(resolve, reject) {
var params = ob.params;
params.qstring.app_id = params.app_id;
params.app_user = params.app_user || {};
var user = JSON.parse(JSON.stringify(params.app_user));
common.db.collection('feedback_widgets').find({"app_id": params.app_id + "", "status": true, type: "rating"}, {_id: 1, popup_header_text: 1, cohortID: 1, type: 1, appearance: 1, showPolicy: 1, trigger_position: 1, hide_sticker: 1, trigger_bg_color: 1, trigger_font_color: 1, trigger_button_text: 1, trigger_size: 1, target_pages: 1, wv: 1}).toArray(function(err, widgets) {
if (err) {
log.e(err);
reject(err);
}
widgets = widgets.map((widget) => {
widget.appearance = {};
widget.appearance.position = widget.trigger_position;
widget.appearance.bg_color = widget.trigger_bg_color;
widget.appearance.text_color = widget.trigger_font_color;
widget.appearance.text = widget.trigger_button_text;
widget.appearance.size = widget.trigger_size;
if (widget.hide_sticker) {
widget.appearance.hideS = true;
}
widget.tg = widget.target_pages;
widget.name = widget.popup_header_text;
widget.wv = widget.wv?.toString() || null;
// remove this props from response
delete widget.hide_sticker;
delete widget.trigger_position;
delete widget.trigger_bg_color;
delete widget.trigger_font_color;
delete widget.trigger_button_text;
delete widget.trigger_size;
delete widget.target_pages;
delete widget.popup_header_text;
return widget;
});
if (widgets && widgets.length > 0) {
//filter out based on cohorts
if (cohortsEnabled) {
widgets = widgets.filter(function(widget) {
if (widget.cohortID) {
if (user && user.chr && user.chr[widget.cohortID] && user.chr[widget.cohortID].in === 'true') {
delete widget.cohortID; //no need to return more data than needed
return true;
}
else {
delete widget.cohortID; //no need to return more data than needed
return false;
}
}
else {
return true;
}
});
}
// concat with tricky way
ob.widgets.push.apply(ob.widgets, widgets);
}
resolve();
});
});
});
/**
* register internalEvent
*/
plugins.internalEvents.push('[CLY]_star_rating');
plugins.internalDrillEvents.push("[CLY]_star_rating");
plugins.internalOmitSegments["[CLY]_star_rating"] = ["email", "comment", "widget_id", "contactMe"];
var createFeedbackWidget = function(ob) {
var obParams = ob.params;
for (let key in widgetPropertyPreprocessors) {
ob.params.qstring[key] = widgetPropertyPreprocessors[key](ob.params.qstring[key]);
}
var validatedArgs = common.validateArgs(ob.params.qstring, widgetProperties, true);
if (!validatedArgs.result) {
common.returnMessage(ob.params, 400, "Invalid params: " + validatedArgs.errors.join());
return false;
}
var widget = validatedArgs.obj;
var type = "rating";
// yes it should be string, not boolean
widget.is_active = widget.status ? "true" : "false";
widget.type = type;
widget.created_at = Date.now();
widget.timesShown = 0;
widget.ratingsCount = 0;
widget.ratingsSum = 0;
widget.showPolicy = "afterPageLoad";
widget.appearance = {};
widget.target_devices = {
desktop: true,
phone: true,
tablet: true
};
/**
* NOTE: This property is used to help SDK identify if the widget has the new handling for close button and
* allows widget to be fullscreen. Since the server will support this from here on, it can be hardcoded.
*/
widget.wv = 1;
//widget.created_by = common.db.ObjectID(obParams.member._id);
validateCreate(obParams, FEATURE_NAME, function(params) {
common.db.collection("feedback_widgets").insert(widget, function(err, result) {
if (!err) {
if (cohortsEnabled && widget.targeting) {
widget.targeting.app_id = params.app_id + "";//has to be string
// eslint-disable-next-line
createCohort(params, type, result.insertedIds[0], widget.targeting, function(cohortId) { //create cohort using this
if (cohortId) {
//update widget record to have this cohortId
common.db.collection("feedback_widgets").findAndModify({ "_id": result.insertedIds[0] }, {}, { $set: { "cohortID": cohortId } }, function(err1 /*, widget*/) {
if (err1) {
log.e(err1);
}
else {
common.returnMessage(params, 201, "Successfully created " + result.insertedIds[0]);
plugins.dispatch("/systemlogs", {params: params, action: "feedback_widget_created", data: widget});
}
});
}
else {
common.returnMessage(params, 400, { "error": "Failed to set cohort", "widgetId": result.insertedIds[0] });
}
});
}
else {
common.returnMessage(params, 201, "Successfully created " + result.insertedIds[0]);
plugins.dispatch("/systemlogs", {params: params, action: "feedback_widget_created", data: widget});
}
return true;
}
else {
common.returnMessage(ob.params, 500, err.message);
return false;
}
});
});
return true;
};
var removeFeedbackWidget = function(ob) {
var obParams = ob.params;
validateDelete(obParams, FEATURE_NAME, function(params) {
var widgetId = params.qstring.widget_id;
var app = params.qstring.app_id;
var withData = params.qstring.with_data;
var collectionName = "feedback_widgets";
common.db.collection(collectionName).findOne({"_id": common.db.ObjectID(widgetId) }, function(err, widget) {
if (!err && widget) {
common.db.collection(collectionName).remove({
"_id": common.db.ObjectID(widgetId)
}, function(removeWidgetErr) {
if (!removeWidgetErr) {
if (cohortsEnabled && widget.cohortID) {
// eslint-disable-next-line
deleteCohort(widget.cohortID, widget.app_id + "");
}
// remove widget and related data
if (withData) {
removeWidgetData(widgetId, app, function(removeError) {
if (removeError) {
common.returnMessage(ob.params, 500, removeError.message);
return false;
}
else {
common.returnMessage(ob.params, 200, 'Success');
plugins.dispatch("/systemlogs", {params: params, action: "feedback_widget_removed_with_data", data: widget});
return true;
}
});
}
// remove only widget
else {
common.returnMessage(ob.params, 200, 'Success');
plugins.dispatch("/systemlogs", {params: params, action: "feedback_widget_removed", data: widget});
return true;
}
}
else {
common.returnMessage(ob.params, 500, removeWidgetErr.message);
return false;
}
});
}
else {
common.returnMessage(ob.params, 404, "Widget not found");
return false;
}
});
});
return true;
};
var editFeedbackWidget = function(ob) {
var obParams = ob.params;
validateUpdate(obParams, FEATURE_NAME, function(params) {
let widgetId;
var type = "rating";
try {
widgetId = common.db.ObjectID(params.qstring.widget_id);
}
catch (e) {
common.returnMessage(params, 500, 'Invalid widget id.');
return false;
}
for (let key in widgetPropertyPreprocessors) {
ob.params.qstring[key] = widgetPropertyPreprocessors[key](ob.params.qstring[key]);
}
var validatedArgs = common.validateArgs(ob.params.qstring, widgetProperties, true);
if (!validatedArgs.result) {
common.returnMessage(ob.params, 400, "Invalid params: " + validatedArgs.errors.join());
return false;
}
var changes = validatedArgs.obj;
if (changes.status) {
changes.is_active = changes.status ? "true" : "false";
}
common.db.collection("feedback_widgets").findAndModify({"_id": widgetId }, {}, {$set: changes}, function(err, widget) {
if (!err && widget) {
widget = widget.value;
if (cohortsEnabled && ((widget.cohortID && !changes.targeting) || JSON.stringify(changes.targeting) !== JSON.stringify(widget.targeting))) {
if (widget.cohortID) {
if (changes.targeting) { //we are not setting to empty one
//changes.targeting.app_id = widget.app_id + "";
changes.targeting.steps = JSON.parse(changes.targeting.steps);
changes.targeting.user_segmentation = JSON.parse(changes.targeting.user_segmentation);
//changes.targeting = JSON.parse(changes.targeting);
common.db.collection('cohorts').findAndModify({ _id: widget.cohortID }, {}, { $set: changes.targeting }, { new: true }, function(err2, res) {
if (err2) {
common.returnMessage(params, 400, "widget updated. Error to update cohort");
}
else {
common.returnMessage(params, 200, "Success");
plugins.dispatch("/systemlogs", { params: params, action: "cohort_edited", data: { update: changes.targeting } });
cohorts.calculateSteps(params, common, res.value, function() { });
}
});
}
else { //we have to delete that cohort
// eslint-disable-next-line
deleteCohort(widget.cohortID, widget.app_id + "");
common.db.collection("feedback_widgets").findAndModify({"_id": widgetId}, {}, {$unset: {"cohortID": ""}}, function(err4/*, widget*/) { //updating record to do not contain cohortID.
if (err4) {
log.e(err4);
}
common.returnMessage(params, 200, "Success");
});
}
}
else {
if (!changes.targeting) {
changes.targeting = {};
}
if (!changes.targeting.user_segmentation) {
changes.targeting.user_segmentation = '{"query":{},"queryText":""}';
}
if (!changes.targeting.steps) {
changes.targeting.steps = '[]';
}
changes.targeting.app_id = params.app_id + "";//has to be string
// eslint-disable-next-line
createCohort(params, type, widgetId, changes.targeting, function(cohortId) { //create cohort using this
if (cohortId) {
//update widget record to have this cohortId
common.db.collection("feedback_widgets").findAndModify({ "_id": widgetId }, {}, { $set: { "cohortID": cohortId } }, function(/*err, widget*/) {
common.returnMessage(params, 200, "Success");
});
}
else {
common.returnMessage(params, 400, "widget updated. Error to create cohort");
}
});
}
}
else {
common.returnMessage(params, 200, "Success");
}
return true;
}
else if (err) {
common.returnMessage(params, 500, err.message);
return false;
}
else {
common.returnMessage(params, 404, "Widget not found");
return false;
}
});
});
return true;
};
var removeWidgetData = function(widgetId, app, callback) {
var collectionName = "feedback" + app;
common.db.collection(collectionName).remove({
"widget_id": widgetId
}, function(err) {
if (!err) {
callback(null);
}
else {
callback(err);
}
});
};
var increaseWidgetShowCount = function(ob) {
var obParams = ob.params;
var widgetId = obParams.qstring.widget_id;
common.db.collection("feedback_widgets").update({"_id": common.db.ObjectID(widgetId)}, { $inc: { timesShown: 1 } }, function(err, widget) {
if (!err && widget) {
return true;
}
else if (err) {
log.e('increaseWidgetShowCount: ' + err);
return false;
}
else {
log.e('increaseWidgetShowCount: widget not found');
return false;
}
});
return true;
};
var nonChecksumHandler = function(ob) {
try {
var events = JSON.parse(ob.params.qstring.events);
if (events.length !== 1 || events[0].key !== "[CLY]_star_rating") {
common.returnMessage(ob.params, 400, 'invalid_event_request');
return false;
}
else {
var params = {
no_checksum: true,
//providing data in request object
'req': {
url: "/i?" + ob.params.href.split("/i/feedback/input?")[1]
},
//adding custom processing for API responses
'APICallback': function(err, responseData, headers, returnCode) {
//sending response to client
if (returnCode === 200) {
common.returnOutput(ob.params, JSON.parse(responseData));
return true;
}
else {
common.returnMessage(ob.params, returnCode, JSON.parse(responseData).result);
return false;
}
}
};
requestProcessor.processRequest(params);
return true;
}
}
catch (jsonParseError) {
common.returnMessage(ob.params, 400, 'invalid_event_request');
return false;
}
};
/**
* @api {post} /i/feedback/logo Upload logo for ratings widget
* @apiName UploadWidgetLogo
* @apiGroup Ratings
*
* @apiDescription Upload custom logo for feedback widget (Requires CREATE permission for Ratings)
* @apiBody {String} logo Logo file
* @apiQuery {String} identifier Identifier for file that will be uploaded
* @apiQuery {String} api_key' API Key that can be obtained from Countly dashboard
*
* @apiSuccessExample {json} Success-Response
* HTTP/1.1 200 OK
* {
* "result": "identifier.png"
* }
*
* @apiErrorExample {json} Error-Response
* HTTP/1.1 400 Bad Request
* {
* "result": "Missing parameter \"api_key\" or \"auth_token\"""
* }
*/
plugins.register("/i/feedback/logo", function(ob) {
var params = ob.params;
validateCreate(params, FEATURE_NAME, function() {
uploadFile(params.files.logo, params.qstring.identifier, function(good, filename) { //will return as good if no file
if (typeof good === 'boolean' && good) {
common.returnMessage(params, 200, filename);
}
else {
common.returnMessage(params, 400, good);
}
});
});
return true;
});
plugins.register("/i/feedback/input", nonChecksumHandler);
plugins.register("/i", function(ob) {
var params = ob.params;
if (params.qstring.events && params.qstring.events.length && Array.isArray(params.qstring.events)) {
params.qstring.events = params.qstring.events.filter(function(currEvent) {
if (currEvent.key === "[CLY]_star_rating") {
/**
* register for process new rating event data.
* the original event format like:
* { key: '[CLY]_star_rating', count:1, sum:1, segmentation:{ platform:"iOS", version:"3.2", rating:2}
* this function will add a field call "platform_version_rate" in segmentation.
*/
currEvent.segmentation.platform = currEvent.segmentation.platform || "undefined"; //because we have a lot of old data with undefined
currEvent.segmentation.rating = currEvent.segmentation.rating || "undefined";
currEvent.segmentation.ratingSum = Number(currEvent.segmentation.rating) || 0;
currEvent.segmentation.widget_id = currEvent.segmentation.widget_id || "undefined";
currEvent.segmentation.app_version = currEvent.segmentation.app_version || "undefined";
currEvent.segmentation.platform_version_rate = currEvent.segmentation.platform + "**" + currEvent.segmentation.app_version + "**" + currEvent.segmentation.rating + "**" + currEvent.segmentation.widget_id + "**";
// is provided email & comment fields
var collectionName = 'feedback' + ob.params.app._id;
common.db.collection(collectionName).insert({
"email": currEvent.segmentation.email || "No email provided",
"comment": currEvent.segmentation.comment || "No comment provided",
"ts": (currEvent.timestamp) ? common.initTimeObj(params.appTimezone, currEvent.timestamp).timestamp : params.time.timestamp,
"device_id": params.qstring.device_id,
"cd": new Date(),
"uid": params.app_user.uid,
"contact_me": currEvent.segmentation.contactMe,
"rating": currEvent.segmentation.rating,
"platform": currEvent.segmentation.platform,
"app_version": currEvent.segmentation.app_version,
"widget_id": currEvent.segmentation.widget_id
}, function(err) {
if (err) {
return false;
}
});
// increment ratings count for widget
common.db.collection('feedback_widgets').update({
_id: common.db.ObjectID(currEvent.segmentation.widget_id)
}, {
$inc: { ratingsSum: currEvent.segmentation.ratingSum, ratingsCount: 1 }
}, function(err) {
if (err) {
return false;
}
});
}
return true;
});
}
});
/**
* @api {post} /i/feedback/widgets/status Bulk update feedback widgets
* @apiName BulkUpdateWidgetStatus
* @apiGroup Ratings
*
* @apiDescription Update the status (active/inactive) of multiple feedback widgets in a single operation
* @apiPermission Update permission for star_rating feature
* @apiBody {Object} data JSON object where keys are widget IDs and values are boolean status values
*
* @apiSuccessExample {json} Success Response:
* HTTP/1.1 200 OK
* {
* "result": "Success"
* }
*
* @apiErrorExample {json} Error - Invalid Data Format:
* HTTP/1.1 500 Internal Server Error
* {
* "result": "Invalid parameter 'data'"
* }
*/
plugins.register('/i/feedback/widgets/status', function(ob) {
const { params } = ob || {};
validateUpdate(params, FEATURE_NAME, function() {
let data = {};
try {
data = JSON.parse(params.qstring.data);
}
catch (error) {
common.returnMessage(params, 500, "Invalid parameter 'data'");
return false;
}
const hasToUpdate = data && Object.keys(data).length > 0;
if (!hasToUpdate) {
common.returnMessage(params, 400, 'Nothing to update');
return false;
}
const bulk = common.db.collection('feedback_widgets').initializeUnorderedBulkOp();
for (const key in data) {
const newStatusValue = data[key] === true || data[key] === 'true' ? true : false;
bulk.find({ _id: common.db.ObjectID(key) }).updateOne({ $set: { 'status': newStatusValue } });
}
bulk.execute(function(error) {
if (error) {
log.e(error);
common.returnMessage(params, 400, error);
}
else {
common.returnMessage(params, 200, 'Success');
plugins.dispatch('/systemlogs', { params: params, action: 'surveys_widget_status', data: data });
}
});
});
return true;
});
/**
* @api {post} /i/feedback/widgets/create Create new widget
* @apiName CreateRatingsWidget
* @apiGroup Ratings
*
* @apiDescription Create web feedback widget from Countly web application