-
Notifications
You must be signed in to change notification settings - Fork 118
/
popup.js
1842 lines (1552 loc) · 65.9 KB
/
popup.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var tabid;
var cookieStoreId;
var g_ck;
var url;
var instance;
var urlFull;
var userName;
var roles;
var dtUpdateSets;
var dtUpdates;
var dtNodes;
var dtTables;
var dtDataExplore;
var dtSlashcommands;
var objCustomCommands = {};
var ipArr = [];
var jsnNodes;
var objSettings;
var tablesloaded = false;
var nodesloaded = false;
var dataexploreloaded = false;
var userloaded = false;
var updatesetsloaded = false;
var updatesloaded = false;
var myFrameHref;
var datetimeformat;
var table;
var sys_id;
var isNoRecord = true;
var tabIndex = -1;
$.fn.dataTable.ext.errMode = 'none';
document.addEventListener('DOMContentLoaded', function () {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
tabid = tabs[0].id;
tabIndex = tabs[0].index;
cookieStoreId = tabs[0].cookieStoreId || '';
urlFull = tabs[0].url;
getBrowserVariables(tabid,cookieStoreId);
document.querySelector("#snuVersion").innerText = chrome.runtime.getManifest().version;
//document.querySelector('#leavereview').style.display = 'none';
});
if(navigator.userAgent.match(/firefox/i)) $('input[type="color"]').attr('type','text') //bug in FireFox to use html5 color tag in popup
clearInvalidatedLocalStorageCache();
//document.querySelector('#reqPermission').addEventListener("click", requestPermissionsForCurrentSite);
});
//clear all invalidated cached items like tablenames and nodes
//each items has a accomanied item with a date string value, remove both if not the current day
function clearInvalidatedLocalStorageCache(){
chrome.storage.local.get(null, function(items) {
let allKeys = Object.keys(items);
let dt = new Date().toDateString();
let arr = []
allKeys.forEach(key => {
if (key.endsWith('-date') && dt != items[key]){
arr.push(key.replace('-date',''));
arr.push(key);
}
})
chrome.storage.local.remove(arr, () =>{
let error = chrome.runtime.lastError;
if (error) {
console.error(error);
}
})
});
}
//Retrieve variables from browser tab, passing them back to popup
function getBrowserVariables(tid, cStoreId, callback) {
tabid = tid;
chrome.tabs.sendMessage(tabid, {
method: "getVars",
myVars: "g_ck,g_user_date_time_format,NOW.user.roles,NOW.user.name,NOW.user_name"
}, function (response) {
if (response == null || typeof response !== 'object') return;
g_ck = response.myVars.g_ck || '';
url = response.url;
instance = (new URL(url)).host.replace(".service-now.com", "");
nme = response.myVars.NOWusername || response.myVars.NOWuser_name;
setBrowserVariables(response);
console.log(response);
//callback(response);
});
}
//Try to retrieve current table and syid from browser tab, passing them back to popup
function getRecordVariables() {
chrome.tabs.sendMessage(tabid, {
method: "getVars",
myVars: "NOW.targetTable,NOW.sysId,mySysId,document.cookie"
}, function (response) {
setRecordVariables(response);
});
}
//Set variables, called by BG page after calling getRecordVariables
function setRecordVariables(obj) {
console.log(obj)
isNoRecord = !obj.myVars.hasOwnProperty('NOWsysId');
sys_id = obj.myVars.NOWsysId || obj.myVars.mySysId;
table = obj.myVars.NOWtargetTable;
if (!table)
table = (myFrameHref || urlFull).match(/com\/(.*).do/)[1].replace('_list', '');
if (!sys_id)
sys_id = (getParameterByName('sys_id', myFrameHref || urlFull));
var xmllink = url + '/' + obj.myVars.NOWtargetTable + '.do?sys_id=' + obj.myVars.NOWsysId + '&sys_target=&XML';
$('#btnviewxml').click(function () {
tabCreate({ "url": xmllink, "active": false });
}).prop('disabled', isNoRecord);
$('#btnupdatesets').click(function () {
tabCreate({ "url": url + '/sys_update_set_list.do?sysparm_query=state%3Din%20progress', "active": false });
});
$('#waitinglink, #waitingscript').hide();
}
//Try to get saved form state and set it
function setFormFromSyncStorage(callback) {
var query = instance + "-formvalues";
chrome.storage.sync.get(query, function (result) {
if (query in result) {
$('form').deserialize(result[query]);
}
callback();
});
}
//Try to get json with servicenow tables, first from chrome storage, else via REST api
function prepareJsonTable() {
var dataset = document.querySelector('#slctdataset').value;
var query = [instance + "-tables-" + dataset, instance + "-tables-" + dataset + "-date"];
chrome.storage.local.get(query, function (result) {
try {
var thedate = new Date().toDateString();
if (thedate == result[query[1]].toString()) {
setDataTableTables(result[query[0]]);
}
else{
getTables(dataset);
}
}
catch (err) {
getTables(dataset);
}
});
}
//Query ServiceNow for nodes
function getNodes() {
let isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
if (isSafari) {
document.querySelector('#nodemessage').innerText = "Node switching may not work in Safari";
}
var myurl = url + '/api/now/table/sys_cluster_state?sysparm_query=ORDERBYsystem_id&sysparm_fields=system_id,node_id,status,node_type&sysparm_display_value=true&sysparm_exclude_reference_link=true';
snuFetch(g_ck, myurl, null, function (jsn) {
setNodes(jsn.result);
});
}
async function setActiveNode(node) {
await fetch(url + '/example_add_two_numbers.do'); // call a random leightweight page that returns not found, to make browser aware of new node
let response = await fetch(url + '/stats.do');
let statsDo = await response.text();
if (!statsDo.includes('Servlet statistics')) { //after a node switch, sometimes the first call fails. Try again
response = await fetch(url + '/stats.do');
statsDo = await response.text();
console.log('retrying stats.do');
}
statsDo = statsDo.replaceAll('<br />', '<br/>'); //fix for some instances
ipArr = statsDo
.match(/IP address: ([\s\S]*?)\<br\/>/g)[0]
.replace('IP address: ', '')
.replace('<br/>', '')
.replace('<br />', '')
.split('.');
let nodeId = statsDo
.match(/Node ID: ([\s\S]*?)\<br\/>/g)[0]
.replace('Node ID: ', '')
.replace('<br/>', '');
let nodeName = statsDo
.match(/Connected to cluster node: ([\s\S]*?)\<br\/>/g)[0]
.replace('Connected to cluster node: ', '')
.replace('<br/>', '');
//let realNode = {"nodeId" : nodeId, "nodeName" : nodeName };
setActiveNodeInner(node);
function setActiveNodeInner(node) {
var nodeArr = node.nodeName.split(".");
var ip34 = nodeArr[0].replace("app", ""); //ie: 28125
var ipSegments = [ipArr[0], ipArr[1], Number(ip34.slice(0, -3)), Number(ip34.slice(3))];
var encodedIP = 0;
for (var i = 0; i < ipSegments.length; i++) {
var n = (ipSegments[i] * Math.pow(256, i));
encodedIP += n;
}
var myurl = url + '/api/now/table/sys_cluster_node_stats?sysparm_query=node_id=' + node.nodeId + '&sysparm_fields=stats';
snuFetch(g_ck, myurl, null, function (jsn) {
var port = ($($.parseXML(jsn.result[0].stats)).find('servlet\\.port').text());
var encodedPort = Math.floor(port / 256) + (port % 256) * 256;
var encodeBIGIP = encodedIP + '.' + encodedPort + '.0000';
chrome.cookies.getAll({
url: new URL(url).origin
}, function (instanceCookies) {
var BIGipServerpoolCookie = instanceCookies.find(function (cookie) {
// matches BIGipServerpool_<alphanumeric instance name>
return cookie.name.match(/^(BIGipServer[\w\d]+)$/);
});
if (!BIGipServerpoolCookie) { //onprem or no cookie found
chrome.cookies.set({
"name": "glide_user_route",
"url": new URL(url).origin,
"secure": true,
"httpOnly": true,
"value": 'glide.' + node.nodeId
}, s => {
getActiveNode(jsnNodes);
});
}
else if (!BIGipServerpoolCookie?.value?.endsWith('.0000')){
//this is a test to allow node switching on ADCv2 migrated instances
let ip = ipArr.join('.');
let ipPort = ip + ':' + port;
let md5IpPort = md5(ipPort);
//console.log(md5IpPort, node);
chrome.cookies.set({
"name": BIGipServerpoolCookie.name,
"url": new URL(url).origin,
"secure": true,
"httpOnly": true,
"value": md5IpPort
}, s => {
chrome.cookies.set({
"name": "glide_user_route",
"url": new URL(url).origin,
"secure": true,
"httpOnly": true,
"value": 'glide.' + node.nodeId
}, s => {
getActiveNode(jsnNodes);
});
});
// document.querySelector('#nodemessage').innerText = `This instance uses ADCv2 loadbalancing, node switching may not work or switch to a random node. Try a few times... `;
// document.querySelector('#nodemessage').classList.remove('hidden');
}
else { //classic node switching
chrome.cookies.set({
"name": BIGipServerpoolCookie.name,
"url": new URL(url).origin,
"secure": true,
"httpOnly": true,
"value": encodeBIGIP
}, s => {
chrome.cookies.set({
"name": "glide_user_route",
"url": new URL(url).origin,
"secure": true,
"httpOnly": true,
"value": 'glide.' + node.nodeId
}, s => {
getActiveNode(jsnNodes);
});
});
}
});
});
}
}
function getActiveNode(jsn) {
jsnNodes = jsn;
chrome.cookies.get({
"name": "glide_user_route",
"url": new URL(url).origin
}, cookie => {
setDataTableNodes(jsnNodes, cookie.value.replace('glide.', ''));
});
}
//Try to get json with instance nodes, first from chrome storage, else via REST api
function prepareJsonNodes() {
var query = [instance + "-nodes", instance + "-nodes-date"];
chrome.storage.local.get(query, function (result) {
try {
var thedate = new Date().toDateString();
if (thedate == result[query[1]].toString()) {
getActiveNode(result[query[0]]);
}
else{
getNodes();
}
}
catch (err) {
getNodes();
}
});
}
function getParameterByName(name, url) {
if (!url) url = window.location.href.toLowerCase();
let srch = new URL(url).search;
const params = new Proxy(new URLSearchParams(srch), {
get: (searchParams, prop) => searchParams.get(prop),
});
return params[name];
}
//Set variables, called by BG page after calling getBrowserVariables
//Also attach event handlers.
function setBrowserVariables(obj) {
document.querySelector('#notactive').style.display = 'none';
//document.querySelector('#leavereview').style.display = '';
let elms = document.querySelectorAll('[data-bs-toggle="disabledtab"]');
elms.forEach(function(el) {
el.setAttribute('data-bs-toggle', 'tab');
});
g_ck = obj.myVars.g_ck || '';
url = obj.url;
instance = (new URL(url)).host.replace(".service-now.com", "");
userName = obj.myVars.NOWusername || obj.myVars.NOWuser_name;
//roles = obj.myVars.NOWuserroles ;
datetimeformat = obj.myVars.g_user_date_time_format;
myFrameHref = obj.frameHref;
setFormFromSyncStorage(function () {
$('.nav-tabs a[data-bs-target="' + $('#tbxactivetab').val() + '"]').tab('show');
});
//Attach eventlistners
$('#btnGetUser').click(function () {
getUserDetails(false);
});
//Attach eventlistners
$('#btncreatefiles').click(function () {
sendToSnuFileSync();
});
$('#tbxname').keypress(function (e) {
if (e.which == '13') {
e.preventDefault();
getUserDetails(false);
}
});
$('#btnrefreshtables').click(function () {
$('#waitingtables').show();
var dataset = document.querySelector('#slctdataset').value;
getTables(dataset);
});
$('#slctdataset').on('change', function () {
$('#waitingtables').show();
var dataset = document.querySelector('#slctdataset').value;
getTables(dataset);
});
$('.snu-setting').change(function () {
saveSettings();
});
$('.snu-instance-setting').change(function () {
setInstanceSettings();
});
$('input.snu-instance-setting').on('keyup',function () {
setInstanceSettings();
});
$('#btnrefreshnodes').click(function () {
$('#waitingnodes').show();
getNodes();
});
$('input').on('blur', function () {
setToChromeSyncStorage("formvalues", $('form .sync').serialize());
});
$('select').on('change', function () {
setToChromeSyncStorage("formvalues", $('form .sync').serialize());
});
$('#btnSetGRName').click(function () {
getGRQuery();
});
$('#tbxgrname').keypress(function (e) {
if (e.which == '13') {
e.preventDefault();
getGRQuery();
}
});
$('#tbxgrtemplate, #cbxtemplatelines, #cbxfullvarname').change(function (e) {
getGRQuery();
});
$('a.popuplinks').click(function () {
event.preventDefault();
tabCreate({ "url": $(this).attr('href'), "active": !(event.ctrlKey || event.metaKey) });
});
$('#slashcommands, #slashsswitches').on('dblclick',function(){
var extensionUrl = chrome.runtime.getURL("settingeditor.html");
var createObj = {
'url': extensionUrl + "?setting=" + this.id,
'active': true
}
chrome.tabs.create(createObj);
})
$('#iconallowbadge').on('change',function(){
iconSettingsDiv($(this).prop('checked'));
})
$.fn.dataTable.moment('DD-MM-YYYY HH:mm:ss');
$.fn.dataTable.moment(datetimeformat);
$('a[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
var target = $(e.target).data("bsTarget"); // activated tab
$('#tbxactivetab').val(target);
setToChromeSyncStorage("formvalues", $('form .sync').serialize());
switch (target) {
case "#tabupdatesets":
if (!updatesetsloaded) {
$('#waitingupdatesets').show();
getUpdateSets();
updatesetsloaded = true;
}
$('#tbxupdatesets').focus(function () {
$(this).select();
});
break;
case "#tabupdates":
if (!updatesloaded) {
$('#waitingupdates').show();
getUpdates();
updatesloaded = true;
}
$('#tbxupdates').focus(function () {
$(this).select();
});
break;
case "#tabnodes":
if (!nodesloaded) {
$('#waitingnodes').show();
prepareJsonNodes();
nodesloaded = true;
}
$('#tbxnodes').focus(function () {
$(this).select();
});
break;
case "#tabtables":
$('#tbxtables').focus(function () {
$(this).select();
}).focus();
if (!tablesloaded) {
$('#waitingtables').show();
prepareJsonTable();
tablesloaded = true;
}
break;
case "#tabdataexplore":
if (!dataexploreloaded) {
$('#waitingdataexplore').show();
getExploreData();
dataexploreloaded = true;
}
$('#tbxdataexplore').focus(function () {
$(this).select();
});
break;
case "#tablink":
$('#waitinglink').show();
getRecordVariables();
break;
case "#tabgr":
getGRQuery();
break;
case "#tabuser":
if (!userloaded) {
if ($('#tbxname').val().length > 0)
getUserDetails(false);
userloaded = true;
}
$('#tbxname').focus(function () {
$(this).select();
});
break;
case "#tabsettings":
getSettings(function(){});
getInstanceSettings();
break;
case "#tabslashcommands":
getSlashcommands();
setSampleCommandHref();
break;
case "#tabwhitelist":
getSettings(function(){});
break;
}
});
$('#helperslashcommands').on('click', function () {
$('#navslashcommands').click();
})
chrome.tabs.sendMessage(tabid, { method: "getSelection" }, function (selresponse) {
var selectedText = ('' + selresponse.selectedText).trim();
if (selectedText.length > 0 && selectedText.length <= 30)
getUserDetails(selectedText);
});
document.querySelector('#btnopengrquery').addEventListener('click', evt => openGrInBgScript(!(evt.metaKey || evt.ctrlKey)));
}
//Query ServiceNow for updatsets, pass JSON back to popup
function getUpdateSets() {
var myurl = url + '/api/now/ui/concoursepicker/updateset';
snuFetch(g_ck, myurl, null, function (jsn) {
setDataTableUpdateSets(jsn);
});
}
//Set active updateset and refresh list on popup after it
function setUpdateSet(data) {
var myurl = url + '/api/now/ui/concoursepicker/updateset';
snuFetch(g_ck, myurl, data, function (jsn) {
getUpdateSets();
});
}
//Query ServiceNow for updaes by current user, pass JSON back to popup
function getUpdates() {
var myurl = url + '/api/now/table/sys_update_xml?sysparm_display_value=true&sysparm_fields=sys_id%2Ctype%2Cname%2Ctarget_name%2Cupdate_set.name%2Csys_updated_on%2Csys_updated_by&sysparm_query=sys_updated_byLIKEjavascript:gs.getUserName()%5EORDERBYDESCsys_updated_on&sysparm_limit=20';
snuFetch(g_ck, myurl, null, function (jsn) {
setDataTableUpdates(jsn);
});
}
//Set message, on about tab, callback from getInfoMessage
function setInfoMessage(html) {
$('#livemessage').html(DOMPurify.sanitize(html));
}
function getSettings(callback) {
getFromSyncStorageGlobal("snusettings", function (settings) {
objSettings = settings || {};
for (var setting in settings) {
try {
if (typeof settings[setting] == "boolean")
document.getElementById(setting).checked = settings[setting];
else
document.getElementById(setting).value = settings[setting];
}
catch (ex) { //property removed
}
};
iconSettingsDiv($('#iconallowbadge').prop('checked'));
callback();
})
}
function saveSettings() {
var snusettingsSync = {};
var snusettings = {}
$('.snu-setting').each(function (index, item) {
if (this.type == 'checkbox') {
snusettingsSync[this.id] = this.checked;
}
else {
if (this.value.length < 5000)
snusettingsSync[this.id] = this.value;
else { //overflow to local storage #204
snusettingsSync[this.id] = '';
snusettings[this.id] = this.value;
}
}
});
setToChromeSyncStorageGlobal("snusettings", snusettingsSync);
setToChromeStorageGlobal("snusettings", snusettings);
}
function setInstanceSettings() {
var snuinstancesettings = {};
$('.snu-instance-setting').each(function (index, item) {
snuinstancesettings[this.id] = this.value;
});
setToChromeSyncStorage("snuinstancesettings", snuinstancesettings);
applyFavIconBadge(snuinstancesettings);
}
function getInstanceSettings() {
getFromSyncStorage("snuinstancesettings", function(settings){
objSettings = settings || {};
for (var setting in settings) {
if (typeof settings[setting] == "boolean")
document.getElementById(setting).checked = settings[setting];
else
document.getElementById(setting).value = settings[setting];
};
applyFavIconBadge(settings);
});
$('#instancename').text(instance);
}
function iconSettingsDiv(visible){
if (visible)
$('#iconsettingsdiv').show();
else
$('#iconsettingsdiv').hide();
}
function applyFavIconBadge(settings){
document.getElementById("icontext").style.backgroundColor = settings?.iconcolorbg;
document.getElementById("icontext").style.color = settings?.iconcolortext;
chrome.tabs.sendMessage(tabid, { method: "setFavIconBadge", options: settings }, function () {});
}
function setSampleCommandHref() {
var newHref = myFrameHref || urlFull;
if ((newHref.split('?')[0]).indexOf('_list.do') > 1) {
getListUrl();
}
else {
if (newHref.includes('.do?')) //allow page with .do in url to default to the UI16 iframe
newHref = newHref.replace(url + '/','');
else
newHref = newHref.replace(url,'');
setListUrl(newHref, '');
}
}
function getListUrl() {
chrome.tabs.sendMessage(tabid, {
method: "getVars",
myVars: "g_list.title,g_list.filter,g_list.tableName,g_list.fields,g_list.sortBy,g_list.sortDir"
}, function (response) {
var tableName = response.myVars.g_listtableName;
var tableLabel = response.myVars.g_listtitle;
var encQuery = response.myVars.g_listfilter;
var orderBy = response.myVars.g_listsortBy;
var fields = response.myVars.g_listfields.split(',').slice(0, 2).join(',');
var isDesc = response.myVars.g_listsortDir == "DESC" ? "DESC" : "";
if (orderBy)
encQuery += `^ORDERBY${isDesc}${orderBy}`;
var listUrl = `${tableName}_list.do?sysparm_query=${encQuery}`;
setListUrl(listUrl, tableLabel, fields);
});
}
function setListUrl(listUrl, tableLabel, fields){
var hrf = document.getElementById('cmdforma');
hrf.href = url + '/' + listUrl
hrf.innerText =listUrl;
hrf.setAttribute('data-tablelabel', tableLabel);
hrf.onclick = function(e) {
e.preventDefault();
document.getElementById('tbxslashurl').value = this.innerText;
if (tableLabel)
document.getElementById('tbxslashhint').value = this.getAttribute('data-tablelabel') + ' <search>';
document.getElementById('tbxslashcmd').value = '';
document.getElementById('tbxslashfields').value = fields;
document.getElementById('tbxslashcmd').focus();
slashCommandShowFieldField();
};
}
function getGRQueryList(varName, template, templatelines, fullvarname) {
chrome.tabs.sendMessage(tabid, {
method: "getVars",
myVars: "g_list.filter,g_list.tableName,g_list.sortBy,g_list.sortDir,g_list.rowsPerPage,g_list.fields"
}, function (response) {
var tableName = response.myVars.g_listtableName;
if (!tableName) { //dealing with a table that ends with _list, like sys_ui_list
getGRQueryForm(varName, template, templatelines, fullvarname);
return;
}
varName = varName || grVarName(tableName, fullvarname);
var encQuery = response.myVars.g_listfilter;
var orderBy = response.myVars.g_listsortBy;
var isDesc = (response.myVars.g_listsortDir == "DESC");
var fields = ('' + response.myVars.g_listfields).split(',');
var rowsPerPage = response.myVars.g_listrowsPerPage;
var queryStr = "var " + varName + " = new GlideRecord('" + tableName + "');\n";
queryStr += varName + ".addEncodedQuery(\"" + encQuery.replaceAll('"', '\\"') + "\");\n";
if (isDesc)
queryStr += varName + ".orderByDesc('" + orderBy + "');\n";
else
queryStr += varName + ".orderBy('" + orderBy + "');\n";
queryStr += varName + ".setLimit(" + rowsPerPage + ");\n";
queryStr += varName + ".query();\n";
queryStr += "while (" + varName + ".next()) {\n";
if (templatelines) {
queryStr += " //" + varName + ".initialize();\n";
}
if (template) {
for (var i = 0; i < fields.length; i++) {
queryStr += " " + template.replace(/\{0\}/g, varName).replace(/\{1\}/g, fields[i]) + "\n";
}
} else
queryStr += "\n\n //todo: code ;)\n\n";
if (templatelines) {
queryStr += " //" + varName + ".autoSysFields(false);\n";
queryStr += " //" + varName + ".setWorkflow(false);\n";
queryStr += " //" + varName + ".update();\n";
queryStr += " //" + varName + ".insert();\n";
queryStr += " //" + varName + ".deleteRecord();\n";
}
queryStr += "}";
setGRQuery(queryStr);
});
}
function getGRQueryForm(varName, template, templatelines, fullvarname) {
chrome.tabs.sendMessage(tabid, {
method: "getVars",
myVars: "g_form.tableName,NOW.sysId,mySysId,elNames"
}, function (response) {
var tableName = response.myVars.g_formtableName;
var sysId = response.myVars.NOWsysId || response.myVars.mySysId;
if (!tableName) { //try to find table and sys_id in workspace
var myurl = new URL(response.frameHref)
var parts = myurl.pathname.split("/");
var idx = parts.indexOf("sub") // show subrecord if available
if (idx != -1) parts = parts.slice(idx);
idx = parts.indexOf("record")
if (idx > -1 && parts.length >= idx + 2) {
tableName = parts[idx + 1];
sysId = parts[idx + 2];
}
}
varName = varName || grVarName(tableName, fullvarname);
var fields = ('' + response.myVars.elNames).split(',');
var queryStr = "var " + varName + " = new GlideRecord('" + tableName + "');\n";
queryStr += "if (" + varName + ".get('" + sysId + "')) {\n";
if (templatelines) {
queryStr += " //" + varName + ".initialize();\n";
}
if (template) {
for (var i = 0; i < fields.length; i++) {
queryStr += " " + template.replace(/\{0\}/g, varName).replace(/\{1\}/g, fields[i]) + "\n";
}
} else
queryStr += "\n\n //todo: code ;)\n\n";
if (templatelines) {
queryStr += " //" + varName + ".autoSysFields(false);\n";
queryStr += " //" + varName + ".setWorkflow(false);\n";
queryStr += " //" + varName + ".update();\n";
queryStr += " //" + varName + ".insert();\n";
queryStr += " //" + varName + ".deleteRecord();\n";
}
queryStr += "}";
setGRQuery(queryStr);
});
}
function getGRQuery() {
var newHref = myFrameHref || urlFull;
if ((newHref.split('?')[0]).indexOf('_list.do') > 1) {
getGRQueryList($('#tbxgrname').val(), $('#tbxgrtemplate').val(),
document.getElementById('cbxtemplatelines').checked,
document.getElementById('cbxfullvarname').checked);
}
else {
getGRQueryForm($('#tbxgrname').val(), $('#tbxgrtemplate').val(),
document.getElementById('cbxtemplatelines').checked,
document.getElementById('cbxfullvarname').checked);
}
}
function grVarName(tableName, fullvarname) {
grVar = ('' + tableName).replace(/[-_]([a-z])/g, function (g) {
return g[1].toUpperCase();
});
var varName = grVar.charAt(0).toUpperCase() + grVar.slice(1);
if (varName.length >= 10 && !fullvarname)
varName = varName.replace(/[a-z]/g, '');
return 'gr' + varName;
}
function setGRQuery(gr) {
if (gr.indexOf("GlideRecord('undefined')") > -1) gr = "This only works in forms and lists.";
$('#txtgrquery').val(gr).select();
}
//Initiate Call to servicenow rest api
function getUserDetails(userName) {
if (!userName) userName = $('#tbxname').val();
$('#tbxname').val(userName);
$('#waitinguser').show();
var myurl = url + "/api/now/table/sys_user?sysparm_display_value=all&sysparm_query=user_name%3D" + userName;
snuFetch(g_ck, myurl, null, function (fetchResult) {
var listhyperlink = " <a target='_blank' href='" + url + "/sys_user_list.do?sysparm_query=user_nameLIKE" + userName + "%5EORnameLIKE" + userName + "'> <i class='fa fa-list' aria-hidden='true'></i></a>";
var html;
if (fetchResult.result.length > 0) {
var usr = fetchResult.result[0];
html = "<br /><table class='table table-condensed table-bordered table-striped'>" +
"<tr><th>User details</th><th>" + usr.user_name.display_value + listhyperlink + "</th></tr>" +
"<tr><td>Name:</td><td><a href='" + url + "/nav_to.do?uri=sys_user.do?sys_id=" +
usr.sys_id.display_value + "' target='_user'>" +
usr.name.display_value + "</a></td></tr>" +
"<tr><td>Active:</td><td>" + usr.active.display_value + "</td></tr>" +
"<tr><td>Last login:</td><td>" + usr.last_login_time.display_value + "</td></tr>" +
"<tr><td>Created:</td><td>" + usr.sys_created_on.display_value + "</td></tr>" +
"<tr><td>Created by:</td><td>" + usr.sys_created_by.display_value + " <a id='createdby' data-username='" + usr.sys_created_by.display_value + "' href='#'> <i class='fa fa-sign-out fa-1' aria-hidden='true'></i></a></td></tr>" +
"<tr><td>Phone:</td><td>" + usr.phone.display_value + "</td></tr>" +
"<tr><td>E-mail:</td><td><a href='mailto:" + usr.email.display_value + "'>" + usr.email.display_value + "</a></td></tr></table>";
setUserDetails(html);
} else {
html = "<br /><table class='table table-condensed table-bordered table-striped'><tr><th>User details</th><th>" + userName + listhyperlink + "</th></tr>" +
"<tr><td>Result:</td><td>No exact match, try clicking the list icon.</td></tr></table>";
setUserDetails(html);
}
});
}
//Set the user details table
function setUserDetails(html) {
$('#rspns').html(DOMPurify.sanitize(html));
if ($('#createdby').length > 0) {
$('.nav-tabs a[data-bs-target="#tabuser"]').tab('show');
$('#createdby').click(function () {
var usr = $(this).data('username');
$('#tbxname').val(usr).focus(function () {
$(this).select();
});
getUserDetails(usr);
});
}
else
$('#tbxname').val('');
$('#waitinguser').hide();
}
//set or refresh datatable with ServiceNow updatesets
function setDataTableUpdateSets(nme) {
if (nme == 'error') {
$('#updatesets').hide().after('<br /><div class="alert alert-danger">Data can not be retrieved, are you an Admin?</div>');
$('#waitingupdatesets').hide();
return false;
}
$('#btnnewupdateset').attr('href', url + '/nav_to.do?uri=%2Fsys_update_set.do%3Fsys_id%3D');
$('#btnopenupdatesets').attr('href', url + '/nav_to.do?uri=%2Fsys_update_set_list.do?sysparm_query=state%3Din%20progress');
if (dtUpdateSets) dtUpdateSets.destroy();
dtUpdateSets = $('#updatesets').DataTable({
"aaData": nme.result.updateSet,
"aoColumns": [
{ "mDataProp": "name" },
{
mRender: function (data, type, row) {
var iscurrent = "";
if (row.sysId == nme.result.current.sysId) iscurrent = "iscurrent";
return "<a class='updatesetlist' href='" + url + "/nav_to.do?uri=sys_update_set.do?sys_id=" + row.sysId + "' title='Table definition' ><i class='fas fa-list' aria-hidden='true'></i></a> " +
"<a class='setcurrent " + iscurrent + "' data-post='{name: \"" + row.name + "\", sysId: \"" + row.sysId + "\"}' href='#" + row.sysId + "' title='Set current updateset'><i class='far fa-dot-circle' aria-hidden='true'></i></a> ";
},
"width": "7%",
"searchable": false
}
],
"drawCallback": function () {
var row0 = $("#updatesets tbody tr a.iscurrent").closest('tr');
$('#updatesets tbody tr:first').before(row0.css('background-color', '#86ED78'));
},
"language": {
"info": "Matched: _TOTAL_ of _MAX_ updatesets | Hold down CMD or CTRL to keep window open after clicking a link",
"infoFiltered": "",
"infoEmpty": "No matches found"
},
"bLengthChange": false,
"bSortClasses": false,
"scrollY": "200px",
"scrollCollapse": true,
"paging": false
});
$('#tbxupdatesets').keyup(function () {
dtUpdateSets.search($(this).val(),true).draw();
}).focus().trigger('keyup');
$('a.updatesetlist').click(function () {
event.preventDefault();
tabCreate({ "url": $(this).attr('href'), "active": !(event.ctrlKey || event.metaKey) });
});
$('a.setcurrent').click(function () {
$('#waitingupdatesets').show();
setUpdateSet($(this).data('post'));
});
$('#waitingupdatesets').hide();
}
function setNodes(jsn) {
if (typeof jsn == "undefined" || jsn == "error") {
$('#instancenodes').hide().after('<br /><div class="alert alert-danger">Nodes data can not be retrieved, are you an Admin?</div>');
$('#waitingnodes').hide();
return false;
}
setToChromeStorage("nodes", jsn);
getActiveNode(jsn);
}
//set or refresh datatable with ServiceNow updatesets
function setDataTableNodes(nme, node) {
if (dtNodes) dtNodes.destroy();
dtNodes = $('#instancenodes').DataTable({
"aaData": nme,
"aoColumns": [
{