-
Notifications
You must be signed in to change notification settings - Fork 21
/
content.js
4010 lines (3315 loc) · 129 KB
/
content.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
/*
* Simple Gmail Notes
* https://github.com/walty8
* Copyright (C) 2017 Walty Yeung <[email protected]>
* License: GPLv3
*
*/
//use a shorter name as we won't have name conflict here
var SGNC = SimpleGmailNotes;
var settings = {
MAX_RETRY_COUNT : 20
};
var sgnGmailDom = new SGNGmailDOM(jQuery);
var gSummaryPulled = false;
var gCRMLoggedInChecked = false;
var gCRMLoggedIn = false;
var gClassicGmailConversation = false;
var gLastPullTimestamp = null;
var gNextPullTimestamp = null;
var gConsecutiveRequests = 0;
var gConsecutiveStartTime = 0;
var gSyncFutureNotesEnabled = false;
var gGmailWatchEnabled = false;
var gLastCRMShareURL = null;
var g_oec = 0; //open email trigger count
var g_lc = 0; //local trigger count
var g_pnc = 0; //pulled network trigger count
//network locking safe guard -- avoid disaster by over requests
var acquireNetworkLock = function() {
var timestamp = Date.now();
var resetCounter = false;
if(gNextPullTimestamp){//if gNextPullTimestamp is set
if(gNextPullTimestamp > timestamp) //skip the request
return false;
else {
gNextPullTimestamp = null;
return true;
}
}
//avoid crazy pulling in case of multiple network requests
//pull again in 3 seconds, for whatever reasons
if(timestamp - gLastPullTimestamp < 3 * 1000)
gConsecutiveRequests += 1;
else{
resetCounter = true;
}
var disableConsecutiveWarning = isDisableConsecutiveWarning()
if(gConsecutiveRequests >= 40 && !disableConsecutiveWarning){
//penalty timeout for 600 seconds
gNextPullTimestamp = timestamp + 600 * 1000;
var message = "40 consecutive network requests detected from Simple Gmail Notes, " +
"the extension would be self-disabled for 60 seconds.\n\n" +
"Please try to close and reopen the browser to clear the cache of extension. " +
"If the problem persists, please consider to disable/uninstall this extension " +
"to avoid locking of your Gmail account. " +
"This warning message is raised by the extension developer (not Google), " +
"just to ensure your account safety.\n\n" +
"If possible, please kindly send the following information to the extension bug report page, " +
"it would be helpful for the developer to diagnose the problem. Thank you!\n\n";
message += "oec:" + g_oec;
message += "; lc:" + g_lc;
message += "; pnc:" + g_pnc;
message += "; tt:" + Math.round(timestamp - gConsecutiveStartTime);
//very intrusive, but it's still better then
//have the account locked up by Gmail!!!
alert(message);
resetCounter = true;
}
if(resetCounter){
gConsecutiveRequests = 0;
gConsecutiveStartTime = timestamp;
g_oec = 0;
g_lc = 0;
g_pnc = 0;
}
gLastPullTimestamp = timestamp;
return true;
};
var sendBackgroundMessage = function(message){
var networkActions = ["post_note", "initialize", "pull_notes", "delete"];
var action = message.action;
if(networkActions.includes(action) && !acquireNetworkLock()){
var error = "Failed to get network lock: " + action;
SGNC.appendLog(error);
debugLog(error);
if(action == "pull_notes"){
g_pnc += 1;
}
else if(action == "initailize"){
g_lc += 1;
}
else if(action == "post_note"){
g_oec += 1;
}
return;
}
if(isRuntimeAlive()){
SGNC.getBrowser().runtime.sendMessage(message, function(response){
//debugLog("Message response", response);
});
}
else{
showOfflineNotice();
}
};
//https://stackoverflow.com/questions/25840674/chrome-runtime-sendmessage-throws-exception-from-content-script-after-reloading
var isRuntimeAlive = function(){
return SGNC.getBrowser().runtime && !!SGNC.getBrowser().runtime.getManifest();
};
var setupBackgroundEventsListener = function(callback) {
SGNC.getBrowser().runtime.onMessage.addListener(
function(request, sender, sendResponse) {
callback(request);
return true;
}
);
};
var addScript = function(scriptPath){
var j = document.createElement('script');
j.src = SGNC.getBrowser().extension.getURL(scriptPath);
j.async = false;
j.defer = false;
(document.head || document.documentElement).appendChild(j);
};
/* global variables to mark the status of current tab */
var gEmailIdNoteDict = {};
var gCurrentGDriveNoteId = "";
var gCurrentGDriveFolderId = "";
var gPreviousContent = "";
var gCurrentEmailSubject = "";
var gCurrentMessageId = "";
var gCurrentBackgroundColor = "";
var gAbstractBackgroundColor = "";
var gAbstractFontColor = "";
var gAbstractFontSize = "";
var gCurrentPreferences = {};
var gLastHeartBeat = Date.now();
var gSgnUserEmail = "";
var gCrmUserEmail = "";
var gCrmUserToken = "";
var gLastPreferenceString = "";
var gSgnEmtpy = "<SGN_EMPTY>";
var gSgnDeleted = "<SGN_DELETED>";
var gSgnCrmDeleted = 'sgn-crm-has-deleted';
var gSuccessDeleted = false;
var gSearchContent = "";
/* -- end -- */
//http://stackoverflow.com/questions/4434076/best-way-to-alphanumeric-check-in-javascript#25352300
var isAlphaNumeric = function(str) {
var code, i, len;
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
}
return true;
};
//http://stackoverflow.com/questions/46155/validate-email-address-in-javascript#1373724
var gEmailRe = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i;
var isValidEmail = function(email) {
return gEmailRe.test(email);
};
var sendEventMessage = function(eventName, eventDetail){
if(eventDetail === undefined){
eventDetail = {};
}
document.dispatchEvent(new CustomEvent(eventName, {detail: JSON.stringify(eventDetail)}));
};
var debugLog = function(){
if (SGNC.isDebug()) {
console.log.apply(console, arguments);
}
};
var isTinyMCEEditable = function(){
var tinymceContenteditable = $('.sgn_container .mce-tinymce').find("iframe").
contents().find("body").attr("contenteditable");
if(tinymceContenteditable == "true"){
return true;
}
return false;
};
var getCrmThreadId = function() {
var threadId = '';
if(SGNC.isNewGmail()){
threadId = sgnGmailDom.getCurrentThreadId();
}
else if(SGNC.isInbox()){
threadId = sgnGmailDom.getCurrentMessageId();
}
else { //classic gmail
if(gClassicGmailConversation){
threadId = sgnGmailDom.getCurrentMessageId();
}
else{
//for classic gmail UI & non conversation mode,
//it seems impossible to get thread id
}
}
return threadId;
}
var getCrmLastMessageId = function() {
var sgnLastMessageId = '';
if(SGNC.isNewGmail()){
sgnLastMessageId = sgnGmailDom.getLastMessageId();
}
return sgnLastMessageId;
}
var disableEdit = function(retryCount){
if(retryCount === undefined)
retryCount = settings.MAX_RETRY_COUNT;
if(!retryCount)
return;
if(isRichTextEditor()){
if(!isTinyMCEEditable())
return;
sendEventMessage('SGN_tinyMCE_disable');
}else{
$(".sgn_input").prop("disabled", true).css("background-color", "");
$(".sgn_input").val("");
//clear up the cache
gEmailIdNoteDict = {};
//keep trying until it's visible
if($(".sgn_input").is(":disabled") && !$(".sgn_padding").is(":visible"))
return;
}
debugLog("retry disable edit");
retryCount = retryCount - 1;
if(retryCount > 0 )
setTimeout(disableEdit, 100, retryCount);
};
var enableEdit = function(retryCount){
if(retryCount === undefined)
retryCount = settings.MAX_RETRY_COUNT;
if(!retryCount)
return;
if(isRichTextEditor()){
if(!isTinyMCEEditable())
sendEventMessage('SGN_tinyMCE_enable');
return;
}else{
$(".sgn_input").prop("disabled", false);
if(!$(".sgn_input").is(":disabled")) //keep trying until it's visible
return;
}
debugLog("retry enable edit");
retryCount = retryCount - 1;
if(retryCount > 0 )
setTimeout(enableEdit, 100, retryCount);
};
var isSGNEnabled = function() {
return $(".sgn_prompt_logout:visible").length > 0 || gSummaryPulled;
};
var isCRMEnabled = function() {
if(!isSGNEnabled())
return false;
var preferences = SGNC.preferences;
var enabled = (preferences && preferences["showCRMButton"] !== "false");
return enabled;
};
var existsOpportunityListOpener = function() {
var existed = $(".sgn_opportunity_list_opener").length > 0;
return existed;
};
var showLoginPrompt = function(retryCount){
if(retryCount === undefined)
retryCount = settings.MAX_RETRY_COUNT;
$(".sgn_prompt_login").show();
$(".sgn_prompt_logout").hide();
$(".sgn_padding").hide();
debugLog("Login prompt visible", $(".sgn_prompt_login").is(":visible"));
if(!$(".sgn_prompt_login").is(":visible")){ //keep trying until it's visible
debugLog("Retry to show login prompt");
retryCount = retryCount - 1;
if(retryCount > 0 )
setTimeout(showLoginPrompt, 100, retryCount);
}
};
var getNoteProperty = function(properties, propertyName){
if(!properties){
debugLog("Warning, no property found");
return "";
}
for(var i=0; i<properties.length; i++){
if(properties[i]["key"] == propertyName){
return properties[i]["value"];
}
}
return "";
};
var setBackgroundColorWithPicker = function(backgroundColor){
if(!backgroundColor)
return;
var input = SGNC.getCurrentInput();
if(isRichTextEditor()){
sendEventMessage('SGN_tinyMCE_set_backgroundColor', {backgroundColor: backgroundColor});
$(".mce-container").parents(".sgn_container").find(".sgn_color_picker_value").val(backgroundColor);
}else{
input.css('background-color', backgroundColor);
input.parents(".sgn_container").find(".sgn_color_picker_value").val(backgroundColor);
}
gCurrentBackgroundColor = backgroundColor;
};
var showLogoutPrompt = function(email, retryCount){
if(retryCount === undefined)
retryCount = settings.MAX_RETRY_COUNT;
$(".sgn_prompt_logout").show();
$(".sgn_prompt_login").hide();
$(".sgn_padding").hide();
$(".sgn_error").hide();
if(email)
$(".sgn_prompt_logout").find(".sgn_user").text(email);
if(!$(".sgn_prompt_logout").is(":visible")){ //keep trying until it's visible
debugLog("Retry to show prompt");
retryCount = retryCount - 1;
if(retryCount > 0 )
setTimeout(showLogoutPrompt, 100, email, retryCount);
}
};
var getCurrentGoogleAccountId = function(){
var re = /mail\/u\/(\d+)/;
var userId = "0";
var match = window.location.href.match(re);
if(match && match.length > 1)
userId = match[1];
return userId;
};
var getSearchNoteURL = function(){
var searchUrl = "https://drive.google.com/drive/folders/" + gCurrentGDriveFolderId;
return searchUrl;
};
var getDisplayContent = function(content){
var warningMessage = SGNC.offlineMessage;
displayContent = content;
if(displayContent.indexOf(warningMessage) === 0){
displayContent = displayContent.substring(warningMessage.length); //truncate the warning message part
}
if(displayContent == gSgnEmtpy)
displayContent = "";
return displayContent;
};
//I use http instead of https here, because otherwise a new window will not be popped up
//in most cases, google would redirect http to https
var getHistoryNoteURL = function(messageId){
var userId = getCurrentGoogleAccountId();
var url = "http://mail.google.com/mail/u/" + userId + "/#all/" + messageId;
return url;
};
var getAddCalendarURL = function(messageId){
var userId = getCurrentGoogleAccountId();
var emailUrl = getHistoryNoteURL(messageId);
var details = emailUrl + "\n-----\n" + $(".sgn_input").val();
var title = gCurrentEmailSubject;
if(title.indexOf("Re:") < 0)
title = "Re: " + title;
var addCalendarURL = "https://calendar.google.com/calendar/b/" + userId +
"/render?action=TEMPLATE" +
"&text=" + encodeURIComponent(title) +
"&details=" + encodeURIComponent(details);
return addCalendarURL;
};
var setPropertiesPublic = function(properties){
var publicPropertyArray = [];
for(var i=0; i<properties.length; i++){
properties[i]["visibility"] = "PUBLIC";
publicPropertyArray.push(properties[i]);
}
return publicPropertyArray;
};
var batchShareNotes = function(email, noteList){
var commonProperties = [{"key" : "sgn-author", "value" : email}];
var shareNotes = [];
for(var i=0; i<noteList.length; i++){
var properties = [];
var shareNote = {};
shareNote["noteId"] = noteList[i]["sgn-gdrive-note-id"];
properties.push({"key" : "sgn-message-id", "value" : noteList[i]["message_id"]});
properties.push({"key": "sgn-shared", "value": noteList[i]["sgn-shared"]});
properties.push({"key": "sgn-opp-name", "value": noteList[i]["sgn-opp-name"]});
properties.push({"key": "sgn-opp-id", "value": noteList[i]["sgn-opp-id"]});
properties.push({"key": "sgn-opp-url", "value": noteList[i]["sgn-opp-url"]});
properties.push({"key": "sgn-note-timestamp", "value": noteList[i]["sgn-note-timestamp"]});
properties = setPropertiesPublic(properties);
shareNote["metadata"] = {properties: properties};
shareNotes.push(shareNote);
}
sendBackgroundMessage({action:"batch_share_crm", email: email,
shareNotes: shareNotes,
gdriveFolderId: gCurrentGDriveFolderId});
};
var postNote = function(email, messageId, crmProp){
//it's a message mis-match, not a callback from silent push
if(messageId != gCurrentMessageId && !crmProp)
return;
var noteId, folderId, emailSubject, content;
var container = SGNC.getContainer();
var properties = [{"key" : "sgn-author", "value" : email},
{"key" : "sgn-message-id", "value" : messageId}];
content = SGNC.getCurrentContent();
if(crmProp){ //silent push callback
folderId = crmProp["sgn-gdrive-folder-id"];
noteId = crmProp["sgn-gdrive-note-id"];
emailSubject = crmProp["sgn-subject"];
if(crmProp["note_updated"])
content = crmProp["sgn-content"];
properties.push({"key" : "sgn-background-color", "value" : crmProp["sgn-background-color"]});
properties.push({"key": "sgn-shared", "value": crmProp["sgn-shared"]});
properties.push({"key": "sgn-opp-name", "value": crmProp["sgn-opp-name"]});
properties.push({"key": "sgn-opp-id", "value": crmProp["sgn-opp-id"]});
properties.push({"key": "sgn-opp-url", "value": crmProp["sgn-opp-url"]});
properties.push({"key": "sgn-note-timestamp", "value": crmProp["sgn-note-timestamp"]});
}
else { // messageId == gCurrentMessageId
folderId = gCurrentGDriveFolderId;
noteId = gCurrentGDriveNoteId;
emailSubject = gCurrentEmailSubject;
var backgroundColor = SGNC.getCurrentBackgroundColor();
//a new timestamp is not provided
var currentTimeStamp = container.attr("data-note-timestamp");
if(!currentTimeStamp)
currentTimeStamp = "";
var versionNumber = 0;
var timestampBase = currentTimeStamp;
if(currentTimeStamp && currentTimeStamp.includes("-")){
versionNumber = parseInt(currentTimeStamp.split("-")[1]);
timestampBase = currentTimeStamp.split("-")[0];
}
versionNumber += 1;
var newTimestamp = timestampBase + "-" + String(versionNumber);
container.attr("data-note-timestamp", newTimestamp);
//set up the default crm properties using the container node
properties.push({"key": "sgn-note-timestamp",
"value": container.attr("data-note-timestamp")});
properties.push({"key": "sgn-opp-id",
"value": container.attr("data-sgn-opp-id")});
properties.push({"key": "sgn-opp-name",
"value": container.attr("data-sgn-opp-name")});
properties.push({"key": "sgn-opp-url",
"value": container.attr("data-sgn-opp-url")});
properties.push({"key" : "sgn-background-color",
"value" : backgroundColor});
properties.push({"key": gSgnCrmDeleted, "value": false});
var sgnLastMessageId = sgnGmailDom.getLastMessageId();
properties.push({"key" : "sgn-last-message-id", "value" : sgnLastMessageId});
var threadId = sgnGmailDom.getCurrentThreadId();
properties.push({"key": "sgn-thread-id", "value": threadId});
}
if (!folderId)
folderId = gCurrentGDriveFolderId;
properties = setPropertiesPublic(properties);
//update the note
sendBackgroundMessage({action:"post_note",
email:email,
messageId:messageId,
emailTitleSuffix: emailSubject,
gdriveNoteId:noteId,
gdriveFolderId:folderId,
content:content,
properties:properties});
gPreviousContent = content;
//always push the note to CRM (except from CRM succcess)
//debugLog("@373", properties);
//if(container.hasClass('sgn-shared') && !skipCRMShare){
// shareToCRM(email, messageId, true);
//}
};
var deleteMessage = function(messageId){
$(".sgn_input:visible").val('');
if(isRichTextEditor()){
sendEventMessage('SGN_tinyMCE_delete_message');
}
gPreviousContent = '';
if(!gCurrentGDriveNoteId){
return;
}
delete gEmailIdNoteDict[messageId];
gCurrentGDriveNoteId = '';
};
var appendTemplateContent = function(email, messageId) {
var preferences = SGNC.preferences;
var note = SGNC.getCurrentContent() + preferences['templateContent'];
$(".sgn_input:visible").val(note);
if(isRichTextEditor()){
sendEventMessage('SGN_tinyMCE_update_note', {content: note});
SGNC.getCurrentInput().val(note);
}
delete gEmailIdNoteDict[messageId];
postNote(email, messageId);
};
var convertTimestamp = function(timestamp){
var result = "";
if(timestamp){
var receviedDatetime = moment.utc(parseInt(timestamp, 10));
var friendlyDate = moment(receviedDatetime).calendar(null, {
lastWeek: 'Do MMM',
lastDay: '[Yesterday]',
sameDay: '[Today]',
nextDay: '[Tomorrow]',
nextWeek: 'Do MMM',
sameElse: 'Do MMM'
});
var friendlyTime = moment(receviedDatetime).format('hh:mm a');
result = friendlyDate + ' ' + friendlyTime;
}
return result;
};
var cleanupSideBar = function(){
var isDisplayHistoryPosition = $('.Bs.nH .Bu.y3 .y4').is(":visible");
if(isDisplayHistoryPosition){
$('.Bs.nH .Bu.y3 .y4').css('height', '0px'); //change history position in main page
}
};
var addCRMNodeToSideBar = function(crmNode, extraClass, sideBarContainerExtraClass){
var sidebar = SGNC.getSidebarNode();
// create opportunity detail note
var sidebarNode = $("<div class='sgn_sidebar sgn_crm_comments'></div>").addClass(extraClass);
var sidebarContainerNode = $("<div class='sgn_sidebar_container'></div>").addClass(sideBarContainerExtraClass);
sidebarContainerNode.append(crmNode);
sidebarNode.append(sidebarContainerNode);
sidebar.append(sidebarNode);
if(sidebar.find(".sgn_history:visible").length){
sidebar.find(".sgn_history:visible").before(sidebarNode);
}
else{
// debugLog('@601');
sidebar.append(sidebarNode);
}
};
var hideCRMSidebarNode = function(){
$(".sgn_sidebar.sgn_crm_opportunity").remove();
$(".sgn_sidebar.sgn_crm_comments").remove();
};
var hideHistorySidebarNode = function(){
$(".sgn_sidebar.sgn_history").remove();
};
var appendCommentRecordNodes = function(comments) {
$(".sgn_comment_history").empty();
if(!comments){
return;
}
var commentRecordNode;
for (var i = 0; i < comments.length; i++) {
commentRecordNode = generateCommentRecordNode(comments[i]);
$(".sgn_comment_history").prepend(commentRecordNode);
}
updateCommentsTotal();
}
var generateCommentRecordNode = function(commentData) {
if (!commentData){
return;
}
var commentModifiedTime = commentData["modified_datetime"];
var commentFormatDay = new Date(parseInt(commentModifiedTime));
// var commentFormatDay = convertTimestamp(commentModifiedTime);
commentFormatDay = moment(commentFormatDay).fromNow();
var commentContent = commentData["content"];
var authorName = commentData["author"];
var authorImage = commentData["avatar"];
var commentRecordNode = $("<div class='sgn_comment_record'></div>");
var commentAuthorImageContainer = $("<div class='sgn_comment_author_image'></div>");
var commentAuthorImage = $("<img class='sgn_author_image'>").attr("src", authorImage);
commentAuthorImageContainer.append(commentAuthorImage);
commentRecordNode.append(commentAuthorImageContainer);
var commentRecordInfoContainer = $("<div class='sgn_comment_detail_info'></div>");
var commentAuthorNameAndTimeNode = $("<div class='sgn_comment_author_and_time'><span class='sgn_comment_author'>" + authorName + "</span> "+
"<span class='sgn_comment_time'>" + commentFormatDay + "</span></div>");
commentRecordInfoContainer.append(commentAuthorNameAndTimeNode);
var commentContentNode = $("<div class='sgn_comment_content_detail'></div>");
commentContentNode.text(commentContent);
commentRecordInfoContainer.append(commentContentNode);
commentRecordNode.append(commentRecordInfoContainer);
return commentRecordNode;
}
var updateCommentUI = function(isLoading) {
if (isLoading) {
$("button.sgn_comment_send").text('Send...');
} else {
$("button.sgn_comment_send").text('Send');
$("div.sgn_comment_textarea").text('');
}
}
var sendCrmNoteComment = function(email) {
var content = $("div.sgn_comment_textarea").text();
if(!content)
return;
var subContent = content.substring(0, 1000);
var threadId = getCrmThreadId();
var commentData = {"thread_id": threadId, "content": subContent};
var currentMessageId = sgnGmailDom.getCurrentMessageId();
var hideEmailInfo = false;
var emailData = getCRMShareEmailData(email, currentMessageId, hideEmailInfo);
commentData["email_info"] = emailData;
commentData["source"] = "sgn";
commentData["action"] = 'comment-share';
var commentUrl = getCRMCommentUrl(getCrmUser(email), commentData);
updateCommentUI(true);
$.ajax({
url: commentUrl,
dataType: "jsonp",
jsonpCallback: "SimpleGmailNotes.commentNoteCallBack",
success: function(response){
// debugLog("@389", response);
updateCommentUI(false);
},
error: function(response){
// debugLog("@rsponse", response);
updateCommentUI(false);
// even for timeout error, it would not return in this closure
//debugLog("Failed to connect to server");
}
});
}
var buildSgnCommentsNode = function(email, noteComments) {
var crmCommentNode = $("<div class='sgn_comment_container'></div>");
var titleNode = $("<div class='sgn_comment_title'></div>")
var inviteTeamMemberNode = $("<div class='sgn_comment_invite'>" +
"<a class='sgn_inviation_action'>Invite Team Member <i class='sgn_member_right_arrow'></a></div>");
var showCommentNumberNode = $("<div class='sgn_comment_tips'>Comments</div>");
titleNode.append(showCommentNumberNode).append(inviteTeamMemberNode);
crmCommentNode.append(titleNode);
var commentTextAreaContainer = $("<div class='sgn_comment_textarea_container'></div>");
var commentActionButtonNode = $("<div class='sgn_comment_buttons'>" +
"<div class='sgn_comment_action_buttons'><button class='sgn_comment_send'>Send</button><button class='sgn_comment_cancel'>Cancel</button></div>" +
"<div class='sgn_comment_emoji'>" +
"<button class='sgn_comment_emoji_item' data-emoji='👍'>👍</button>" +
"<button class='sgn_comment_emoji_item' data-emoji='🤔️'>🤔️</button>" +
"<button class='sgn_comment_emoji_item' data-emoji='😩'>😩</button>" +
"</div></div>");
var commentTextArea = $("<div class='sgn_comment_textarea' contenteditable='true' data-text='Add comment here'></div>");
var commentErrorNode = $("<div class='sgn_comment_error'></div>");
commentTextAreaContainer.append(commentTextArea);
commentTextAreaContainer.append(commentActionButtonNode);
crmCommentNode.append(commentTextAreaContainer);
crmCommentNode.append(commentErrorNode);
var commentRecordContainer = $("<div class='sgn_comment_history'></div>");
crmCommentNode.append(commentRecordContainer);
addCRMNodeToSideBar(crmCommentNode, undefined, "sgn_extra_comment_container");
appendCommentRecordNodes(noteComments);
$("button.sgn_comment_cancel").click(function() {
$("div.sgn_comment_textarea").text('');
});
$("button.sgn_comment_send").click(function() {
sendCrmNoteComment(email);
});
$("button.sgn_comment_emoji_item").click(function() {
var commentContent = $("div.sgn_comment_textarea").text();
var emoji = $(this).attr("data-emoji");
$("div.sgn_comment_textarea").text(commentContent + emoji);
});
$("a.sgn_inviation_action").click(function() {
var inviationUrl = getCRMInvitationMemberUrl(email);
sendEventMessage(
'SGN_PAGE_open_popup',
{
url: inviationUrl,
windowName: 'sgn-invitation-member',
strWindowFeatures: SGNC.getStrWindowFeatures(1000, 700)
}
);
});
};
var removeLoginSidebarNode = function() {
$("div.sgn_login_container").remove();
};
var setupLoginSidebarNode = function() {
debugLog("@802----- gCRMLogged iN", gCRMLoggedIn);
if ($("div.sgn_login_container").length > 0) {
return;
}
if (gCRMLoggedIn) {
return;
}
var sgnHistoryNode = $("div.sgn_history.sgn_sidebar");
if (sgnHistoryNode.length === 0) {
return
}
var loginLogoUrl = SGNC.getLogoImageSrc("ed");
var loginNodeContainer = $("<div class='sgn_login_container'>" +
"<img class='sgn_comment_login_logo' src=" + loginLogoUrl + "/></div>");
var commentIconNode = $("<div class='sgn_comment_login_icon_node'></div>");
var commentIcon = $("<img >").attr("src", SGNC.getIconBaseUrl() + "/login-comment-icon.3x.png");
commentIconNode.append(commentIcon);
loginNodeContainer.append(commentIconNode);
var commentLoginContainer = $("<div class='sgn_comment_login_container'>" +
"<div class='sgn_comment_login_title'>Add Comment</div>" +
"<div><button class='sgn_comment_login_button'>Login</button></div></div>");
loginNodeContainer.append(commentLoginContainer);
sgnHistoryNode.prepend(loginNodeContainer);
$("button.sgn_comment_login_button").click(function() {
var loginUrl = getCRMLoginUrl();
sendEventMessage(
'SGN_PAGE_open_popup',
{
url: loginUrl,
windowName: 'sgn-login-page',
strWindowFeatures: SGNC.getStrWindowFeatures(1000, 700)
}
);
});
}
var setupCRMSidebarNode = function(email, opportunityInfo, noteComments) {
// debugLog("@779----- note comments", noteComments);
if (!isCRMEnabled() || $(".sgn_crm_opportunity:visible").length) {
return;
}
if($.isEmptyObject(opportunityInfo)){
return;
}
cleanupSideBar();
var opportunityInfoNode = $("<div class='sgn_opportunity_info'></div>");
var opportunityAvatar = $("<img class='sgn_avatar'>").attr(
"src", opportunityInfo["avatar"]);
var opportunityName = $("<div class='sgn_opportunity_name'>").text(
opportunityInfo["name"]);
var opportunityArrow = $("<img class='sgn_arrow'>").attr("src",
SGNC.getIconBaseUrl() + "/arrow-right.png");
opportunityInfoNode.append(opportunityAvatar).append(opportunityName);
opportunityInfoNode.append("<div class='sgn_flex_grow'></div>");
opportunityInfoNode.append(opportunityArrow);
addCRMNodeToSideBar(opportunityInfoNode, "sgn_crm_opportunity");
var _opportunityInfo = opportunityInfo;
var _email = email;
opportunityInfoNode.click(function(){
openCurrentOpportunity(_email, _opportunityInfo.id);
});
buildSgnCommentsNode(email, noteComments);
};
var updateGmailNotePosition = function(injectionNode, notePosition){
var preferences = SGNC.preferences;
//var logo = injectionNode.find(".sgn_bart_logo");
var noticeNode = injectionNode.find(".sgn_notice");
if(injectionNode.attr('data-note-position') === notePosition) {
return;
}
if(notePosition == "side-top" || notePosition == "side-bottom"){
//injectionNode.append(logo);
//all the sidebart display logic are now done in css
//
//$(".sgn_prompt_logout").css("height", "30px");
//var showConnectionPrompt = (preferences["showConnectionPrompt"] !== "false");
//if(showConnectionPrompt){
// $(".mce-tinymce").css("margin-top", "20px");
//}
//logo.after(noticeNode);
//var noteTimeStampDom = SimpleGmailNotes.getNoteTimeStampDom();
//noteTimeStampDom.after(logo);
//if($(".sgn_clear_right").length <= 0){
// $("<div class='sgn_clear_right'></div>").insertAfter(noteTimeStampDom);
//}
//
}
else{
if($(".sgn_clear_right").length > 0){
$(".sgn_clear_right").remove();
}
//injectionNode.children('.sgn_bart_logo').remove();
//injectionNode.children('.sgn_prompt_logout').prepend(logo);
injectionNode.children('.sgn_prompt_logout').append(noticeNode);
}
if(isRichTextEditor() && injectionNode.is(":visible"))
//for richtext editor, cannot prepend the node again, otherwise the iframe
//inside will have problem
return;
if(notePosition == "side-top" || notePosition == "side-bottom"){
if(notePosition == "side-top"){
SGNC.getSidebarNode().prepend(injectionNode);
}else{
SGNC.getSidebarNode().append(injectionNode);
}
injectionNode.addClass("sgn_sidebar");
injectionNode.parent().find(".y4").css("display", "none");
}else{
if(notePosition == "bottom"){
$(".nH.aHU:visible").append(injectionNode);
}else{
$(".nH.if:visible, .nH.aBy:visible").prepend(injectionNode); //hopefully this one is stable
}
injectionNode.css("width", "auto");
//$(".sgn_prompt_logout").css("height", "auto");
}
injectionNode.attr("data-note-position", notePosition);
};
var isEnableFlexibleHeight = function(){
var preferences = SGNC.preferences;
if(!preferences)
return false;
var enableFlexibleHeight = (preferences["enableFlexibleHeight"] !== "false");
return enableFlexibleHeight;
};
var isRichTextEditor = function(){
var preferences = SGNC.preferences;
if(!preferences)
return false;
var enableRichtextEditor = (preferences["enableRichtextEditor"] === "true");
return enableRichtextEditor;
};
var isDisableConsecutiveWarning = function() {
var preferences = SGNC.preferences;
if(!preferences)
return false;
var disableConsecutiveWarning = (preferences["disableConsecutiveWarning"] === "true");
return disableConsecutiveWarning;
};
var isEnableNoteFontBold = function() {
var preferences = SGNC.preferences;
if(!preferences)
return false;
var enableNoteFontBold = (preferences["enableNoteFontBold"] === "true");
return enableNoteFontBold;
};
var isEnableNoDisturbMode = function(){
var preferences = SGNC.preferences;
var enableNoDisturbMode = (preferences["enableNoDisturbMode"] !== "false");
return enableNoDisturbMode;