-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy pathModuleFeedback.java
More file actions
1015 lines (865 loc) · 47.1 KB
/
ModuleFeedback.java
File metadata and controls
1015 lines (865 loc) · 47.1 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
package ly.count.android.sdk;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.webkit.WebSettings;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ModuleFeedback extends ModuleBase {
public enum FeedbackWidgetType {survey, nps, rating}
public static class CountlyFeedbackWidget implements Serializable {
public String widgetId;
public FeedbackWidgetType type;
public String name;
public String[] tags;
public String widgetVersion;
}
final static String NPS_EVENT_KEY = "[CLY]_nps";
final static String SURVEY_EVENT_KEY = "[CLY]_survey";
final static String RATING_EVENT_KEY = "[CLY]_star_rating";
final String cachedAppVersion;
ImmediateRequestGenerator iRGenerator;
Feedback feedbackInterface = null;
private Activity currentActivity;
ContentOverlayView feedbackOverlay;
ModuleFeedback(Countly cly, CountlyConfig config) {
super(cly, config);
L.v("[ModuleFeedback] Initialising");
cachedAppVersion = deviceInfo.mp.getAppVersion(config.context);
iRGenerator = config.immediateRequestGenerator;
feedbackInterface = new Feedback();
}
@Override
void onInitialActivitySeeded(@NonNull Activity activity) {
L.d("[ModuleFeedback] onInitialActivitySeeded, activity: [" + activity.getClass().getSimpleName() + "]");
currentActivity = activity;
}
@Override
void onActivityStarted(Activity activity, int updatedActivityCount) {
if (activity == null) {
return;
}
currentActivity = activity;
// Move existing feedback overlay to the new activity
if (feedbackOverlay != null && !activity.isFinishing() && !activity.isDestroyed()) {
try {
feedbackOverlay.attachToActivity(activity);
} catch (Exception ex) {
L.w("[ModuleFeedback] onActivityStarted, failed to attach feedback overlay to activity", ex);
}
}
}
@Override
void onActivityStopped(int updatedActivityCount) {
if (updatedActivityCount == 0 && feedbackOverlay != null) {
L.d("[ModuleFeedback] onActivityStopped, no activities visible, detaching overlay from window");
feedbackOverlay.detachFromWindow();
}
}
public interface RetrieveFeedbackWidgets {
void onFinished(List<CountlyFeedbackWidget> retrievedWidgets, String error);
}
public interface RetrieveFeedbackWidgetData {
void onFinished(JSONObject retrievedWidgetData, String error);
}
public interface FeedbackCallback {
void onClosed();
void onFinished(String error);
}
void getAvailableFeedbackWidgetsInternal(final RetrieveFeedbackWidgets devCallback) {
L.d("[ModuleFeedback] calling 'getAvailableFeedbackWidgetsInternal', callback set:[" + (devCallback != null) + "]");
if (devCallback == null) {
L.e("[ModuleFeedback] available feedback widget list can't be retrieved without a callback");
return;
}
if (!consentProvider.getConsent(Countly.CountlyFeatureNames.feedback)) {
devCallback.onFinished(null, "Consent is not granted");
return;
}
if (deviceIdProvider.isTemporaryIdEnabled()) {
L.e("[ModuleFeedback] available feedback widget list can't be retrieved when in temporary device ID mode");
devCallback.onFinished(null, "[ModuleFeedback] available feedback widget list can't be retrieved when in temporary device ID mode");
return;
}
ConnectionProcessor cp = requestQueueProvider.createConnectionProcessor();
final boolean networkingIsEnabled = cp.configProvider_.getNetworkingEnabled();
String requestData = requestQueueProvider.prepareFeedbackListRequest();
iRGenerator.CreateImmediateRequestMaker().doWork(requestData, "/o/sdk", cp, false, networkingIsEnabled, new ImmediateRequestMaker.InternalImmediateRequestCallback() {
@Override public void callback(JSONObject checkResponse) {
if (checkResponse == null) {
L.d("[ModuleFeedback] Not possible to retrieve widget list. Probably due to lack of connection to the server");
devCallback.onFinished(null, "Not possible to retrieve widget list. Probably due to lack of connection to the server");
return;
}
L.d("[ModuleFeedback] Retrieved request: [" + checkResponse.toString() + "]");
List<CountlyFeedbackWidget> feedbackEntries = parseFeedbackList(checkResponse);
devCallback.onFinished(feedbackEntries, null);
}
}, L);
}
static List<CountlyFeedbackWidget> parseFeedbackList(JSONObject requestResponse) {
Countly.sharedInstance().L.d("[ModuleFeedback] calling 'parseFeedbackList'");
List<CountlyFeedbackWidget> parsedRes = new ArrayList<>();
try {
if (requestResponse != null) {
JSONArray jArray = requestResponse.optJSONArray("result");
if (jArray == null) {
Countly.sharedInstance().L.w("[ModuleFeedback] parseFeedbackList, response does not have a valid 'result' entry. No widgets retrieved.");
return parsedRes;
}
for (int a = 0; a < jArray.length(); a++) {
try {
JSONObject jObj = jArray.getJSONObject(a);
String valId = jObj.optString("_id", "");
String valType = jObj.optString("type", "");
String valName = jObj.optString("name", "");
String widgetVersion = jObj.isNull("wv") ? null : jObj.optString("wv", null);
List<String> valTagsArr = new ArrayList<String>();
JSONArray jTagArr = jObj.optJSONArray("tg");
if (jTagArr == null) {
Countly.sharedInstance().L.w("[ModuleFeedback] parseFeedbackList, no tags received");
} else {
for (int in = 0; in < jTagArr.length(); in++) {
valTagsArr.add(jTagArr.getString(in));
}
}
if (valId.isEmpty()) {
Countly.sharedInstance().L.e("[ModuleFeedback] parseFeedbackList, retrieved invalid entry with null or empty widget id, dropping");
continue;
}
if (valType.isEmpty()) {
Countly.sharedInstance().L.e("[ModuleFeedback] parseFeedbackList, retrieved invalid entry with null or empty widget type, dropping");
continue;
}
FeedbackWidgetType plannedType;
if (valType.equals("survey")) {
plannedType = FeedbackWidgetType.survey;
} else if (valType.equals("nps")) {
plannedType = FeedbackWidgetType.nps;
} else if (valType.equals("rating")) {
plannedType = FeedbackWidgetType.rating;
} else {
Countly.sharedInstance().L.e("[ModuleFeedback] parseFeedbackList, retrieved unknown widget type, dropping");
continue;
}
CountlyFeedbackWidget se = new CountlyFeedbackWidget();
se.type = plannedType;
se.widgetId = valId;
se.name = valName;
se.tags = valTagsArr.toArray(new String[0]);
se.widgetVersion = widgetVersion;
parsedRes.add(se);
} catch (Exception ex) {
Countly.sharedInstance().L.e("[ModuleFeedback] parseFeedbackList, failed to parse json, [" + ex.toString() + "]");
}
}
}
} catch (Exception ex) {
Countly.sharedInstance().L.e("[ModuleFeedback] parseFeedbackList, Encountered exception while parsing feedback list, [" + ex.toString() + "]");
}
return parsedRes;
}
void presentFeedbackWidgetInternal(@Nullable final CountlyFeedbackWidget widgetInfo, @Nullable final Context context, @Nullable final String closeButtonText, @Nullable final FeedbackCallback devCallback) {
if (widgetInfo == null) {
L.e("[ModuleFeedback] Can't present widget with null widget info");
if (devCallback != null) {
devCallback.onFinished("Can't present widget with null widget info");
}
return;
}
L.d("[ModuleFeedback] presentFeedbackWidgetInternal, callback set:[" + (devCallback != null) + ", widget id:[" + widgetInfo.widgetId + "], widget type:[" + widgetInfo.type + "]");
if (context == null) {
L.e("[ModuleFeedback] Can't show feedback, provided context is null");
if (devCallback != null) {
devCallback.onFinished("Can't show feedback, provided context is null");
}
return;
}
if (!consentProvider.getConsent(Countly.CountlyFeatureNames.feedback)) {
if (devCallback != null) {
devCallback.onFinished("Consent is not granted");
}
return;
}
if (deviceIdProvider.isTemporaryIdEnabled()) {
L.e("[ModuleFeedback] available feedback widget list can't be retrieved when in temporary device ID mode");
if (devCallback != null) {
devCallback.onFinished("[ModuleFeedback] available feedback widget list can't be retrieved when in temporary device ID mode");
}
return;
}
StringBuilder widgetListUrl = new StringBuilder();
switch (widgetInfo.type) {
case survey:
//'/o/feedback/nps/widget?widget_ids=' + nps[0]._id
//https://xxxx.count.ly/feedback/nps?widget_id=5f8445c4eecf2a6de4dcb53e
widgetListUrl.append(baseInfoProvider.getServerURL());
widgetListUrl.append("/feedback/survey?widget_id=");
widgetListUrl.append(UtilsNetworking.urlEncodeString(widgetInfo.widgetId));
break;
case nps:
widgetListUrl.append(baseInfoProvider.getServerURL());
widgetListUrl.append("/feedback/nps?widget_id=");
widgetListUrl.append(UtilsNetworking.urlEncodeString(widgetInfo.widgetId));
break;
case rating:
widgetListUrl.append(baseInfoProvider.getServerURL());
widgetListUrl.append("/feedback/rating?widget_id=");
widgetListUrl.append(UtilsNetworking.urlEncodeString(widgetInfo.widgetId));
break;
}
widgetListUrl.append("&device_id=");
widgetListUrl.append(UtilsNetworking.urlEncodeString(deviceIdProvider.getDeviceId()));
widgetListUrl.append("&app_key=");
widgetListUrl.append(UtilsNetworking.urlEncodeString(baseInfoProvider.getAppKey()));
widgetListUrl.append("&sdk_version=");
widgetListUrl.append(Countly.sharedInstance().COUNTLY_SDK_VERSION_STRING);
widgetListUrl.append("&sdk_name=");
widgetListUrl.append(Countly.sharedInstance().COUNTLY_SDK_NAME);
widgetListUrl.append("&platform=android");
// TODO: this will be the base for the custom segmentation users can send while presenting a widget
JSONObject customObjectToSendWithTheWidget = new JSONObject();
try {
customObjectToSendWithTheWidget.put("tc", 1);
// these are used only in case of a widget with a version
if (!Utils.isNullOrEmpty(widgetInfo.widgetVersion)) {
customObjectToSendWithTheWidget.put("rw", 1);
customObjectToSendWithTheWidget.put("xb", 1);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
widgetListUrl.append("&custom=");
widgetListUrl.append(customObjectToSendWithTheWidget);
String preparedWidgetUrl = widgetListUrl.toString();
L.d("[ModuleFeedback] Using following url for widget:[" + preparedWidgetUrl + "]");
if (!Utils.isNullOrEmpty(widgetInfo.widgetVersion)) {
L.d("[ModuleFeedback] Will use content overlay for displaying the widget");
showFeedbackWidget_newActivity(context, preparedWidgetUrl, widgetInfo, devCallback);
} else {
iRGenerator.CreatePreflightRequestMaker().doWork(preparedWidgetUrl, null, requestQueueProvider.createConnectionProcessor(), false, true, preflightResponse -> {
if (preflightResponse == null) {
L.e("[ModuleFeedback] Failed to do preflight check for the widget url");
if (devCallback != null) {
devCallback.onFinished("Failed to do preflight check for the widget url");
}
return;
}
L.d("[ModuleFeedback] Will use dialog for displaying the widget");
//enable for chrome debugging
// WebView.setWebContentsDebuggingEnabled(true);
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
L.d("[ModuleFeedback] Calling on main thread");
try {
showFeedbackWidget(context, widgetInfo, closeButtonText, devCallback, preparedWidgetUrl);
if (devCallback != null) {
devCallback.onFinished(null);
}
} catch (Exception ex) {
L.e("[ModuleFeedback] Failed at displaying feedback widget dialog, [" + ex.toString() + "]");
if (devCallback != null) {
devCallback.onFinished("Failed at displaying feedback widget dialog, [" + ex.toString() + "]");
}
}
}
});
}, L);
}
}
private void showFeedbackWidget(Context context, CountlyFeedbackWidget widgetInfo, String closeButtonText, FeedbackCallback devCallback, String url) {
ModuleRatings.RatingDialogWebView webView = new ModuleRatings.RatingDialogWebView(context);
webView.getSettings().setJavaScriptEnabled(true);
webView.clearCache(true);
webView.clearHistory();
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
ModuleRatings.FeedbackDialogWebViewClient webViewClient = new ModuleRatings.FeedbackDialogWebViewClient();
webView.setWebViewClient(webViewClient);
webView.loadUrl(url);
webView.requestFocus();
AlertDialog.Builder builder = new AlertDialog.Builder(context).setView(webView).setCancelable(false);
String usedCloseButtonText = closeButtonText;
if (closeButtonText == null || closeButtonText.isEmpty()) {
usedCloseButtonText = "Close";
}
builder.setNeutralButton(usedCloseButtonText, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialogInterface, int i) {
L.d("[ModuleFeedback] Cancel button clicked for the feedback widget");
reportFeedbackWidgetCancelButton(widgetInfo);
if (devCallback != null) {
devCallback.onClosed();
}
}
});
builder.show();
}
private void showFeedbackWidget_newActivity(@NonNull Context context, String url, CountlyFeedbackWidget widgetInfo, FeedbackCallback devCallback) {
Activity activity = null;
if (context instanceof Activity && !((Activity) context).isFinishing()) {
activity = (Activity) context;
} else if (currentActivity != null && !currentActivity.isFinishing()) {
activity = currentActivity;
}
if (activity == null) {
L.e("[ModuleFeedback] showFeedbackWidget_newActivity, no valid activity available to show overlay");
if (devCallback != null) {
devCallback.onFinished("No valid activity available to show feedback widget");
}
return;
}
// Do not show feedback widget if content overlay is currently showing
if (_cly.moduleContent != null && _cly.moduleContent.contentOverlay != null) {
L.w("[ModuleFeedback] showFeedbackWidget_newActivity, content overlay is currently showing, skipping feedback widget");
if (devCallback != null) {
devCallback.onFinished("Content overlay is currently showing");
}
return;
}
DisplayMetrics displayMetrics = deviceInfo.mp.getDisplayMetrics(context);
Resources resources = context.getResources();
int currentOrientation = resources.getConfiguration().orientation;
boolean portrait = currentOrientation == Configuration.ORIENTATION_PORTRAIT;
int portraitWidth, portraitHeight, landscapeWidth, landscapeHeight;
int portraitTopOffset = 0;
int landscapeTopOffset = 0;
int portraitLeftOffset = 0;
int landscapeLeftOffset = 0;
int totalWidthPx = displayMetrics.widthPixels;
int totalHeightPx = displayMetrics.heightPixels;
L.d("[ModuleFeedback] showFeedbackWidget_newActivity, total screen dimensions (px): [" + totalWidthPx + "x" + totalHeightPx + "], density: [" + displayMetrics.density + "]");
WebViewDisplayOption displayOption = _cly.config_.webViewDisplayOption;
L.d("[ModuleFeedback] showFeedbackWidget_newActivity, display option: [" + displayOption + "]");
if (displayOption == WebViewDisplayOption.SAFE_AREA) {
L.d("[ModuleFeedback] showFeedbackWidget_newActivity, calculating safe area dimensions...");
SafeAreaDimensions safeArea = SafeAreaCalculator.calculateSafeAreaDimensions(activity, L);
portraitWidth = safeArea.portraitWidth;
portraitHeight = safeArea.portraitHeight;
landscapeWidth = safeArea.landscapeWidth;
landscapeHeight = safeArea.landscapeHeight;
portraitTopOffset = safeArea.portraitTopOffset;
landscapeTopOffset = safeArea.landscapeTopOffset;
portraitLeftOffset = safeArea.portraitLeftOffset;
landscapeLeftOffset = safeArea.landscapeLeftOffset;
L.d("[ModuleFeedback] showFeedbackWidget_newActivity, safe area dimensions (px) - Portrait: [" + portraitWidth + "x" + portraitHeight + "], topOffset: [" + portraitTopOffset + "], leftOffset: [" + portraitLeftOffset + "]");
L.d("[ModuleFeedback] showFeedbackWidget_newActivity, safe area dimensions (px) - Landscape: [" + landscapeWidth + "x" + landscapeHeight + "], topOffset: [" + landscapeTopOffset + "], leftOffset: [" + landscapeLeftOffset + "]");
} else {
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
portraitWidth = portrait ? width : height;
portraitHeight = portrait ? height : width;
landscapeWidth = portrait ? height : width;
landscapeHeight = portrait ? width : height;
L.d("[ModuleFeedback] showFeedbackWidget_newActivity, using immersive mode (full screen) dimensions (px) - Portrait: [" + portraitWidth + "x" + portraitHeight + "], Landscape: [" + landscapeWidth + "x" + landscapeHeight + "]");
}
L.i("[ModuleFeedback] showFeedbackWidget_newActivity, FINAL dimensions for widget (px) - Portrait: [" + portraitWidth + "x" + portraitHeight + "], Landscape: [" + landscapeWidth + "x" + landscapeHeight + "]");
TransparentActivityConfig pConfig = new TransparentActivityConfig(0, 0, portraitWidth, portraitHeight);
TransparentActivityConfig lConfig = new TransparentActivityConfig(0, 0, landscapeWidth, landscapeHeight);
pConfig.url = url;
lConfig.url = url;
pConfig.useSafeArea = (displayOption == WebViewDisplayOption.SAFE_AREA);
lConfig.useSafeArea = (displayOption == WebViewDisplayOption.SAFE_AREA);
pConfig.topOffset = portraitTopOffset;
lConfig.topOffset = landscapeTopOffset;
pConfig.leftOffset = portraitLeftOffset;
lConfig.leftOffset = landscapeLeftOffset;
ContentCallback feedbackCallback = null;
if (devCallback != null) {
feedbackCallback = (contentStatus, contentData) -> {
if (contentStatus.equals(ContentStatus.CLOSED)) {
devCallback.onClosed();
} else {
devCallback.onFinished(null);
}
};
}
// Clean up any existing feedback overlay
if (feedbackOverlay != null) {
feedbackOverlay.destroy();
feedbackOverlay = null;
}
final Activity hostActivity = activity;
feedbackOverlay = new ContentOverlayView(
hostActivity,
pConfig,
lConfig,
currentOrientation,
feedbackCallback,
() -> {
feedbackOverlay = null;
}
);
feedbackOverlay.setOnWidgetCancelRunnable(() -> reportFeedbackWidgetCancelButton(widgetInfo));
feedbackOverlay.attachToActivity(hostActivity);
}
void reportFeedbackWidgetCancelButton(@NonNull CountlyFeedbackWidget widgetInfo) {
L.d("[reportFeedbackWidgetCancelButton] Cancel button event");
if (consentProvider.getConsent(Countly.CountlyFeatureNames.feedback)) {
final Map<String, Object> segm = new HashMap<>();
segm.put("platform", "android");
segm.put("app_version", cachedAppVersion);
segm.put("widget_id", "" + widgetInfo.widgetId);
segm.put("closed", "1");
final String key;
if (widgetInfo.type == FeedbackWidgetType.survey) {
key = SURVEY_EVENT_KEY;
} else if (widgetInfo.type == FeedbackWidgetType.rating) {
key = RATING_EVENT_KEY;
} else {
key = NPS_EVENT_KEY;
}
eventProvider.recordEventInternal(key, segm, 1, 0, 0, null, null);
}
}
/**
* Downloads widget info and returns it to the callback
*
* @param widgetInfo identifies the specific widget for which you want to download widget data
* @param devCallback mandatory callback in which the downloaded data will be returned
*/
void getFeedbackWidgetDataInternal(@Nullable CountlyFeedbackWidget widgetInfo, @Nullable final RetrieveFeedbackWidgetData devCallback) {
L.d("[ModuleFeedback] calling 'getFeedbackWidgetDataInternal', callback set:[" + (devCallback != null) + "]");
if (devCallback == null) {
L.e("[ModuleFeedback] Feedback widget data can't be retrieved without a callback");
return;
}
if (widgetInfo == null) {
L.e("[ModuleFeedback] Feedback widget data if provided widget is 'null'");
return;
}
if (!consentProvider.getConsent(Countly.CountlyFeatureNames.feedback)) {
devCallback.onFinished(null, "Consent is not granted");
return;
}
if (deviceIdProvider.isTemporaryIdEnabled()) {
L.e("[ModuleFeedback] Feedback widget data can't be retrieved when in temporary device ID mode");
devCallback.onFinished(null, "[ModuleFeedback] Feedback widget data can't be retrieved when in temporary device ID mode");
return;
}
StringBuilder requestData = new StringBuilder();
String widgetDataEndpoint = "";
switch (widgetInfo.type) {
case survey:
//https://xxxx.count.ly/o/surveys/survey/widget?widget_id=601345cf5e313f74&shown=1platform=Android&app_version=7
widgetDataEndpoint = "/o/surveys/survey/widget";
break;
case nps:
//https://xxxx.count.ly/o/surveys/nps/widget?widget_id=601345cf5e313f74&shown=1platform=Android&app_version=7
widgetDataEndpoint = "/o/surveys/nps/widget";
break;
case rating:
widgetDataEndpoint = "/o/surveys/rating/widget";
break;
}
requestData.append("widget_id=");
requestData.append(UtilsNetworking.urlEncodeString(widgetInfo.widgetId));
requestData.append("&shown=1");
requestData.append("&sdk_version=");
requestData.append(Countly.sharedInstance().COUNTLY_SDK_VERSION_STRING);
requestData.append("&sdk_name=");
requestData.append(Countly.sharedInstance().COUNTLY_SDK_NAME);
requestData.append("&platform=android");
requestData.append("&app_version=");
requestData.append(cachedAppVersion);
ConnectionProcessor cp = requestQueueProvider.createConnectionProcessor();
final boolean networkingIsEnabled = cp.configProvider_.getNetworkingEnabled();
String requestDataStr = requestData.toString();
L.d("[ModuleFeedback] Using following request params for retrieving widget data:[" + requestDataStr + "]");
(new ImmediateRequestMaker()).doWork(requestDataStr, widgetDataEndpoint, cp, false, networkingIsEnabled, new ImmediateRequestMaker.InternalImmediateRequestCallback() {
@Override public void callback(JSONObject checkResponse) {
if (checkResponse == null) {
L.d("[ModuleFeedback] Not possible to retrieve widget data. Probably due to lack of connection to the server");
devCallback.onFinished(null, "Not possible to retrieve widget data. Probably due to lack of connection to the server");
return;
}
L.d("[ModuleFeedback] Retrieved widget data request: [" + checkResponse.toString() + "]");
devCallback.onFinished(checkResponse, null);
}
}, L);
}
/**
* Report widget info and do data validation
*
* @param widgetInfo identifies the specific widget for which the feedback is filled out
* @param widgetData widget data for this specific widget
* @param widgetResult segmentation of the filled out feedback. If this segmentation is null, it will be assumed that the survey was closed before completion and mark it appropriately
*/
void reportFeedbackWidgetManuallyInternal(@Nullable CountlyFeedbackWidget widgetInfo, @Nullable JSONObject widgetData, @Nullable Map<String, Object> widgetResult) {
if (widgetInfo == null) {
L.e("[ModuleFeedback] Can't report feedback widget data manually with 'null' widget info");
return;
}
L.d("[ModuleFeedback] reportFeedbackWidgetManuallyInternal, widgetData set:[" + (widgetData != null) + ", widget id:[" + widgetInfo.widgetId + "], widget type:[" + widgetInfo.type + "], widget result set:[" + (widgetResult != null) + "]");
if (!consentProvider.getConsent(Countly.CountlyFeatureNames.feedback)) {
L.w("[ModuleFeedback] Can't report feedback widget data, consent is not granted");
return;
}
if (deviceIdProvider.isTemporaryIdEnabled()) {
L.e("[ModuleFeedback] feedback widget result can't be reported when in temporary device ID mode");
return;
}
if (widgetResult != null) {
//removing broken values first
UtilsInternalLimits.removeUnsupportedDataTypes(widgetResult, L);
Iterator<Map.Entry<String, Object>> iter = widgetResult.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Object> entry = iter.next();
if (entry.getKey() == null) {
L.w("[ModuleFeedback] provided feedback widget result contains a 'null' key, it will be removed, value[" + entry.getValue() + "]");
iter.remove();
} else if (entry.getKey().isEmpty()) {
L.w("[ModuleFeedback] provided feedback widget result contains an empty string key, it will be removed, value[" + entry.getValue() + "]");
iter.remove();
} else if (entry.getValue() == null) {
L.w("[ModuleFeedback] provided feedback widget result contains a 'null' value, it will be removed, key[" + entry.getKey() + "]");
iter.remove();
}
if (entry.getValue() instanceof String) {
// TODO, if applicable think about applying key and segmentation count limit for the widget result
String truncatedValue = UtilsInternalLimits.truncateValueSize(entry.getValue().toString(), _cly.config_.sdkInternalLimits.maxValueSize, L, "[ModuleFeedback] reportFeedbackWidgetManuallyInternal");
if (!truncatedValue.equals(entry.getValue())) {
entry.setValue(truncatedValue);
}
}
}
if (widgetInfo.type == FeedbackWidgetType.nps) {
//in case a nps widget was completed
if (!widgetResult.containsKey("rating")) {
L.e("Provided NPS widget result does not have a 'rating' field, result can't be reported");
return;
}
//check rating data type
Object ratingValue = widgetResult.get("rating");
if (!(ratingValue instanceof Integer)) {
L.e("Provided NPS widget 'rating' field is not an integer, result can't be reported");
return;
}
//check rating value range
int ratingValI = (int) ratingValue;
if (ratingValI < 0 || ratingValI > 10) {
L.e("Provided NPS widget 'rating' value is out of bounds of the required value '[0;10]', it is probably an error");
}
if (!widgetResult.containsKey("comment")) {
L.w("Provided NPS widget result does not have a 'comment' field");
}
} else if (widgetInfo.type == FeedbackWidgetType.survey) {
//in case a survey widget was completed
} else if (widgetInfo.type == FeedbackWidgetType.rating) {
//in case a rating widget was completed
if (!widgetResult.containsKey("rating")) {
L.e("Provided Rating widget result does not have a 'rating' field, result can't be reported");
return;
}
//check rating data type
Object ratingValue = widgetResult.get("rating");
if (!(ratingValue instanceof Integer)) {
L.e("Provided Rating widget 'rating' field is not an integer, result can't be reported");
return;
}
//check rating value range
int ratingValI = (int) ratingValue;
if (ratingValI < 1 || ratingValI > 5) {
L.e("Provided Rating widget 'rating' value is out of bounds of the required value '[1;5]', it is probably an error");
}
}
}
if (widgetData == null) {
L.d("[ModuleFeedback] reportFeedbackWidgetManuallyInternal, widgetInfo is 'null', no validation will be done");
} else {
//perform data validation
String idInData = widgetData.optString("_id");
if (!widgetInfo.widgetId.equals(idInData)) {
L.w("[ModuleFeedback] id in widget info does not match the id in widget data");
}
String typeInData = widgetData.optString("type");
if (widgetInfo.type == FeedbackWidgetType.nps) {
if (!"nps".equals(typeInData)) {
L.w("[ModuleFeedback] type in widget info [" + typeInData + "] does not match the type in widget data [nps]");
}
} else if (widgetInfo.type == FeedbackWidgetType.survey) {
if (!"survey".equals(typeInData)) {
L.w("[ModuleFeedback] type in widget info [" + typeInData + "] does not match the type in widget data [survey]");
}
} else if (widgetInfo.type == FeedbackWidgetType.rating) {
if (!"rating".equals(typeInData)) {
L.w("[ModuleFeedback] type in widget info [" + typeInData + "] does not match the type in widget data [rating]");
}
}
}
final String usedEventKey;
if (widgetInfo.type == FeedbackWidgetType.nps) {
usedEventKey = NPS_EVENT_KEY;
//event when closed
//{"key":"[CLY]_nps","segmentation":{"widget_id":"600e9d2e563e892016316339","platform":"android","app_version":"0.0","closed":1},"timestamp":1611570486021,"hour":15,"dow":1}
//event when answered
//{"key":"[CLY]_nps","segmentation":{"widget_id":"600e9b24563e89201631631f","platform":"android","app_version":"0.0","rating":10,"comment":"Thanks"},"timestamp":1611570182023,"hour":15,"dow":1}
} else if (widgetInfo.type == FeedbackWidgetType.survey) {
usedEventKey = SURVEY_EVENT_KEY;
//event when closed
//{"key":"[CLY]_survey","segmentation":{"widget_id":"600e9e0b563e89201631633e","platform":"android","app_version":"0.0","closed":1},"timestamp":1611570709449,"hour":16,"dow":1}
//event when answered
//{"key":"[CLY]_survey","segmentation":{"widget_id":"600e9e0b563e89201631633e","platform":"android","app_version":"0.0","answ-1611570700-0":"ch1611570700-0"},"timestamp":1611570895465,"hour":16,"dow":1}
} else if (widgetInfo.type == FeedbackWidgetType.rating) {
usedEventKey = RATING_EVENT_KEY;
//event when closed
// {"key":"[CLY]_star_rating","count":1,"timestamp":1671783040088,"hour":11,"dow":5,"segmentation":{"app_version":"1.0","widget_id":"614871419f030e44be07d82f","closed":"1","platform":"android"}
//event when answered
//{"key":"[CLY]_star_rating","count":1,"segmentation":{"widget_id":"614871419f030e44be07d82f","contactMe":false,"platform":"android","app_version":"1","platform_version_rate":"","rating":4,"email":"","comment":""}
} else {
usedEventKey = "";
}
Map<String, Object> segm = new HashMap<>();
segm.put("platform", "android");
segm.put("app_version", cachedAppVersion);
segm.put("widget_id", widgetInfo.widgetId);
if (widgetResult == null) {
//mark as closed
segm.put("closed", "1");
} else {
//widget was filled out
//merge given segmentation
segm.putAll(widgetResult);
}
eventProvider.recordEventInternal(usedEventKey, segm, 1, 0, 0, null, null);
}
/**
* Present a feedback widget based on the provided nameIDorTag, internal function to use
*
* @param type the type of the feedback widget to present
* @param nameIDorTag the widget id, widget name or widget tag of the feedback widget to present
*/
private void presentFeedbackWidgetNameIDorTag(@NonNull Context context, @NonNull FeedbackWidgetType type, @NonNull String nameIDorTag, @Nullable FeedbackCallback devCallback) {
getAvailableFeedbackWidgetsInternal(new RetrieveFeedbackWidgets() {
@Override public void onFinished(List<CountlyFeedbackWidget> retrievedWidgets, String error) {
if (error != null) {
L.e("[ModuleFeedback] presentFeedbackWidgetNameIDorTag, Failed to retrieve feedback widget list, [" + error + "]");
return;
}
if (retrievedWidgets.isEmpty()) {
L.e("[ModuleFeedback] presentFeedbackWidgetNameIDorTag, No feedback widgets available");
return;
}
CountlyFeedbackWidget selectedWidget = null;
for (CountlyFeedbackWidget widget : retrievedWidgets) {
if (widget.type == type) {
if (!nameIDorTag.isEmpty()) {
if (widget.widgetId.equals(nameIDorTag) || widget.name.equals(nameIDorTag)) {
selectedWidget = widget;
break;
}
for (String tag : widget.tags) {
if (tag.equals(nameIDorTag)) {
selectedWidget = widget;
break;
}
}
} else {
selectedWidget = widget;
break;
}
}
}
if (selectedWidget == null) {
L.e("[ModuleFeedback] presentFeedbackWidgetNameIDorTag, No feedback widget found with the provided nameIDorTag or type");
return;
}
presentFeedbackWidgetInternal(selectedWidget, context, null, devCallback);
}
});
}
@Override
void initFinished(@NonNull CountlyConfig config) {
}
@Override
void halt() {
feedbackInterface = null;
if (feedbackOverlay != null) {
feedbackOverlay.destroy();
feedbackOverlay = null;
}
currentActivity = null;
}
@Override
void onConsentChanged(@NonNull final List<String> consentChangeDelta, final boolean newConsent, @NonNull final ModuleConsent.ConsentChangeSource changeSource) {
L.d("[ModuleFeedback] onConsentChanged, consentChangeDelta: [" + consentChangeDelta + "], newConsent: [" + newConsent + "], changeSource: [" + changeSource + "]");
if (consentChangeDelta.contains(Countly.CountlyFeatureNames.feedback) && !newConsent) {
if (feedbackOverlay != null) {
feedbackOverlay.destroy();
feedbackOverlay = null;
}
}
}
public class Feedback {
/**
* Get a list of available feedback widgets for this device ID
*
* @param callback
*/
public void getAvailableFeedbackWidgets(@Nullable RetrieveFeedbackWidgets callback) {
synchronized (_cly) {
L.i("[Feedback] Trying to retrieve feedback widget list");
getAvailableFeedbackWidgetsInternal(callback);
}
}
/**
* Present a chosen feedback widget
*
* @param widgetInfo
* @param context
* @param closeButtonText if this is null, no "close" button will be shown
* @param devCallback
* @deprecated use {@link #presentFeedbackWidget(CountlyFeedbackWidget, Context, FeedbackCallback)} instead
*/
public void presentFeedbackWidget(@Nullable CountlyFeedbackWidget widgetInfo, @Nullable Context context, @Nullable String closeButtonText, @Nullable FeedbackCallback devCallback) {
synchronized (_cly) {
L.i("[Feedback] Trying to present feedback widget");
presentFeedbackWidgetInternal(widgetInfo, context, closeButtonText, devCallback);
}
}
/**
* Present a chosen feedback widget
*
* @param widgetInfo the widget to present
* @param context the context to use for displaying the feedback widget
* @param devCallback callback to be called when the feedback widget is closed
*/
public void presentFeedbackWidget(@Nullable CountlyFeedbackWidget widgetInfo, @Nullable Context context, @Nullable FeedbackCallback devCallback) {
synchronized (_cly) {
L.i("[Feedback] Trying to present feedback widget");
presentFeedbackWidgetInternal(widgetInfo, context, null, devCallback);
}
}
/**
* Download data for a specific widget so that it can be displayed with a custom UI
* When requesting this data, it will count as a shown widget (will increment that "shown" count in the dashboard)
*
* @param widgetInfo
* @param callback
*/
public void getFeedbackWidgetData(@Nullable CountlyFeedbackWidget widgetInfo, @Nullable RetrieveFeedbackWidgetData callback) {
synchronized (_cly) {
L.i("[Feedback] Trying to retrieve feedback widget data");
getFeedbackWidgetDataInternal(widgetInfo, callback);
}
}
/**
* Manually report a feedback widget in case a custom interface was used
* In case widgetResult is passed as "null", it would be assumed that the widget was cancelled
*
* @param widgetInfo
* @param widgetData
* @param widgetResult
*/
public void reportFeedbackWidgetManually(@Nullable CountlyFeedbackWidget widgetInfo, @Nullable JSONObject widgetData, @Nullable Map<String, Object> widgetResult) {
synchronized (_cly) {
L.i("[Feedback] Trying to report feedback widget manually");
reportFeedbackWidgetManuallyInternal(widgetInfo, widgetData, widgetResult);
}
}
/**
* Present an NPS feedback widget from the top of the list of available NPS widgets by the nameIDorTag string
*
* @param context the context to use for displaying the feedback widget
* @param nameIDorTag the widget id, widget name or widget tag of the NPS feedback widget to present, if empty, the top widget will be presented
*/
public void presentNPS(@NonNull Context context, @NonNull String nameIDorTag) {
presentNPS(context, nameIDorTag, null);
}
/**
* Present an NPS feedback widget from the top of the list of available NPS widgets
*
* @param context the context to use for displaying the feedback widget
*/
public void presentNPS(@NonNull Context context) {
presentNPS(context, "");
}
/**
* Present a Survey feedback widget from the top of the list of available Survey widgets by the nameIDorTag string
*
* @param context the context to use for displaying the feedback widget
* @param nameIDorTag the widget id, widget name or widget tag of the Survey feedback widget to present, if empty, the top widget will be presented
*/
public void presentSurvey(@NonNull Context context, @NonNull String nameIDorTag) {
presentSurvey(context, nameIDorTag, null);
}
/**
* Present a Survey feedback widget from the top of the list of available Survey widgets
*
* @param context the context to use for displaying the feedback widget
*/
public void presentSurvey(@NonNull Context context) {
presentSurvey(context, "");
}
/**
* Present a Rating feedback widget from the top of the list of available Rating widgets by the nameIDorTag string
*
* @param context the context to use for displaying the feedback widget
* @param nameIDorTag the widget id, widget name or widget tag of the Rating feedback widget to present, if empty, the top widget will be presented
*/
public void presentRating(@NonNull Context context, @NonNull String nameIDorTag) {
presentRating(context, nameIDorTag, null);
}
/**
* Present a Rating feedback widget from the top of the list of available Rating widgets
*
* @param context the context to use for displaying the feedback widget
*/
public void presentRating(@NonNull Context context) {
presentRating(context, "");
}
/**
* Present an NPS feedback widget from the top of the list of available NPS widgets by the nameIDorTag string
*
* @param context the context to use for displaying the feedback widget
* @param nameIDorTag the widget id, widget name or widget tag of the NPS feedback widget to present, if empty, the top widget will be presented
* @param devCallback callback to be called when the feedback widget is closed
*/
public void presentNPS(@NonNull Context context, @NonNull String nameIDorTag, @Nullable FeedbackCallback devCallback) {
synchronized (_cly) {
L.i("[Feedback] presentNPS, got nameIDorTag:[" + nameIDorTag + "], got callback:[" + (devCallback != null) + "]");
presentFeedbackWidgetNameIDorTag(context, FeedbackWidgetType.nps, nameIDorTag, devCallback);
}
}
/**
* Present a Survey feedback widget from the top of the list of available Survey widgets by the nameIDorTag string
*
* @param context the context to use for displaying the feedback widget
* @param nameIDorTag the widget id, widget name or widget tag of the Survey feedback widget to present, if empty, the top widget will be presented
* @param devCallback callback to be called when the feedback widget is closed
*/
public void presentSurvey(@NonNull Context context, @NonNull String nameIDorTag, @Nullable FeedbackCallback devCallback) {
synchronized (_cly) {
L.i("[Feedback] presentSurvey, got nameIDorTag:[" + nameIDorTag + "], got callback:[" + (devCallback != null) + "]");
presentFeedbackWidgetNameIDorTag(context, FeedbackWidgetType.survey, nameIDorTag, devCallback);
}
}