-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocusky.ui.manageDbListSimpleUI.js
1959 lines (1810 loc) · 84.7 KB
/
docusky.ui.manageDbListSimpleUI.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
/**
* docusky.ui.manageDbListSimpleUI.js
* (URL)
*
* (Description)
* 這是利用 docusky web api 所包裝起來的一份 JavaScript
* Note: - this component is only tested under Firefox and Chrome
* - requires jquery
*
* @version
* 0.01 (May xx 2016)
* 0.02 (August xx 2016)
* 0.03 (January 23 2017) fix css class name (adds prefix 'dsw-' to better avoid naming conflicts)
* 0.04 (March 01 2017) add simple message for upload progress
* 0.05 (April 23 2017) add hideWidget() and modify some codes to let invoker better use widget functions
* 0.06 (July 28 2017) set some functions as "private" methods (and fix some bugs)
* 0.07 (August 09 2017) open uploadMultipart() method
* 0.08 (January 28 2017) add enableWidgetEvent(), disableWidgetEvent() to allow db/corpus callback
* 0.09 (January 30 2018) expose login() and uploadMultipart(), and add with credentials to allow CORS requests
* 0.10 (May 13 2018) add default 'corpusClick' function
* 0.11 (Feb 19 2019) add renameDbTitle, getUserProfile function (modify widgetEvents so that the callback func
* has evt in the first arg and this in the second arg)
* 0.12 (April 01 2019) add error handling and me.Error for the most functions and
* modify the parameter of uploadMultipart()
* 0.13 (April 04 2019) add functions for user friendship and accessible dbs
* 0.14 (April 23 2019) add with mechanism on maxResponseTimeout, maxRetryCount, uploadProgressFunc, utility.setStyle, setLoadingIcon
* fix the display of uploadprogressbar
* 0.15 (May 04 2019) fix hideWidget(), add ownerUsername, and fix server improperly return a non-JSON (should not retry in this case)
* 0.16 (June 06 2019) remove the dependency of jQuery UI
* 0.17 (Jan 26 2021) add SessionKey to pass session key via url parameter
* 0.18 (June 14 2021) add getAccessibleDbCorpusList(), public logout(), and fix bugs
* 0.19 (June 25 2021) add class variable requester and setRequester()
* 0.20 (Dec 30 2021) add me.urlWebApiPath, minor fix (add const parameter forceHttps -- but not finished, ref. getDbCorpusDocumentsSimpleUI.js), reset SessionKey after logout
* 0.21 (Feb 11 2022) add var ForceHttps, WithCredentials (since may include multiple widgets, cannot use 'const' here), fix hideWidget()
*
* @copyright
* Copyright (C) 2016 Hsieh-Chang Tu
*
* @license
*
*/
var ForceHttps = false; // 2021-12-20: 若放到 server 上,可能需設為 true(避免 BigIP 將 http 轉為 https 時沒有帶上 CORS 所需的 headers)
var WithCredentials = true; // 2022-02-11: 若放到 server 上,可能需設為 false(避免瀏覽器不接受 Access-Control-Allow-Origin:* -- 但瀏覽器在登入時會顯示「不安全」訊息)
var SessionKey; // 2021-02-06: 必須是全域變數,才能在 widgets 之間共用(且僅宣告而不指定值)
if (window.navigator.userAgent.indexOf("MSIE ") > 0) {
alert("抱歉,DocuSky 工具目前只支援 Firefox 與 Chrome");
}
var ClsDocuskyManageDbListSimpleUI = function(param) { // constructor
var me = this; // stores object reference
me.package = 'docusky.ui.manageDbListSimpleUI.js'; // 主要目的:取得給定 db, corpus 的文件
me.version = 0.19; // 2021-06-25
me.idPrefix = 'DbList_'; // 2016-08-13
me.utility = null;
me.protocol = null; // 'http', 'https'
me.urlHostPath = null;
me.urlHostPath = null;
me.urlWebApiPath = null;
me.urlGetDbListJson = null;
me.urlUploadXmlFilesToBuildDbJson = null;
me.urlDeleteDbJson = null;
me.urlLogin = null;
me.urlLogout = null;
me.displayname = '';
me.username = '';
me.requester = 'Widget:manageDbList'; // 2021-06-25
me.callerEvent = null;
me.callerCallback = null; // 儲存成功執行後所需呼叫的函式
me.initialized = false;
me.includeFriendDb = false; // 2019-05-04: default false for backward-compatibility
me.ownerUsername = null; // 2019-05-04
me.dbList = []; // 儲存 DocuSky 的 user databasees 列表
me.fileName = ''; // 欲上傳檔案(在本地)的名稱
me.fileData = ''; // 欲上傳檔案的內容
me.fileSizeLimit = 132 * 1024 * 1024; // 132MB limit -- 需配合 urlUploadXmlFilesToBuildDbJson.php 的設定
me.enableRefresh = true; // 2017-04-19
me.timeoutFunId = null;
me.loadingIconWidth = 140; // 2018-01-07: 參考 docusky.ui.getDbCorpusDocumentsSimpleUI
me.displayLoadingIcon = true; // 2018-01-07
me.displayWidget = true; // 2017-07-24
me.widgetEvents = { dbClick: null, // null: disable clicking db -- can be set from invoker as obj.widgetEvents.dbClick=function(s){...}, where s will be the db title
corpusAttCntClick: null, // 2018-01-08: 若 enable 此項,則 corpusClick/attCntClick 將失效
corpusClick: // 2018-05-13: default function ==> open a new window to display db+corpus content
function(evt, ownerUsername, db, corpus) { // 2019-05-04: add ownerUsername
var url = me.urlWebApiPath + "/webpage-search-3in1.php?ownerUsername=" + ownerUsername + "&db=" + db + "&corpus=" + corpus;
window.open(url, "_blank");
},
attCntClick: null
};
me.validEvtKeys = ['dbClick', 'corpusAttCntClick', 'corpusClick', 'attCntClick'];
me.loginSuccFunc = null; // 2019-02-19
me.loginFailFunc = null;
me.Error = null; //all scope error handle
me.uploadProgressFunc = null; //callback function for the percentage of upload progress
me.maxResponseTimeout = 300000;
me.maxRetryCount = 10;
me.presentRetryCount = 0;
// =================================
// main functions
// =================================
var init = function() {
//var scriptPath = me.utility.getScriptPath();
//me.urlHostPath = scriptPath.protocol + '://' + scriptPath.host + '/' + me.utility.dirname(scriptPath.path) + '/webApi';
// 注意: 由於利用 jQuery 動態載入 utility functions,call stack 最後會是在 jQuery 函式,因此不能從 me.utility.getScriptPath() 取得 script URL
let scheme = location.protocol.substr(0, location.protocol.length-1);
if (scheme == 'file') me.urlHostPath = "https://docusky.org.tw/docusky";
else me.urlHostPath = me.utility.dirname(me.utility.dirname(me.scriptPath + 'dummy'));
if (ForceHttps && scheme == 'http') scheme = 'https'; // 2021-12-20: 強迫改用 https
me.urlWebApiPath = me.urlHostPath + '/webApi';
me.urlUserMain = me.urlHostPath + '/docuTools/userMain/';
me.urlLogin = me.urlWebApiPath + '/userLoginJson.php';
me.urlLogout = me.urlWebApiPath + '/userLogoutJson.php';
me.urlGetDbListJson = me.urlWebApiPath + '/getDbListJson.php';
me.urlUploadXmlFilesToBuildDbJson = me.urlWebApiPath + '/uploadXmlFilesToBuildDbJson.php';
me.urlDeleteDbJson = me.urlWebApiPath + '/deleteDbJson.php';
me.urlRenameDbTitleJson = me.urlWebApiPath + '/renameDbTitleJson.php';
me.urlGetUserProfileJson = me.urlWebApiPath + '/getUserProfileJson.php';
//me.urlUpdateUserProfileJson = me.urlWebApiPath + '/updateUserProfileJson.php'; // api not existed yet
me.displayname = '';
me.username = '';
me.uniqueId = me.utility.uniqueId();
// 2019-04-04: for user friendship and accessible dbs
me.urlReplaceUserFriendshipJson = me.urlWebApiPath + '/replaceUserFriendshipJson.php';
me.urlReplaceUserFriendAccessibleDbJson = me.urlWebApiPath + '/replaceUserFriendAccessibleDbJson.php';
me.urlDeleteUserFriendshipJson = me.urlWebApiPath + '/deleteUserFriendshipJson.php';
me.urlDeleteUserFriendAccessibleDbJson = me.urlWebApiPath + '/deleteUserFriendAccessibleDbJson.php';
me.urlGetUserFriendshipJson = me.urlWebApiPath + '/getUserFriendshipJson.php';
me.urlGetUserFriendAccessibleDbJson = me.urlWebApiPath + '/getUserFriendAccessibleDbJson.php';
me.urlGetDbCorpusListJson = me.urlWebApiPath + '/getDbCorpusListJson.php'; // 2021-06-13
// login container
var loginContainerId = me.idPrefix + "loginContainer" + me.uniqueId;
var loginContainerOverlayId = me.idPrefix + "loginContainerOverlay" + me.uniqueId;
var closeLoginContainerId = me.idPrefix + "closeLoginContainer" + me.uniqueId;
var dsUsernameId = me.idPrefix + "dsUsername" + me.uniqueId;
var dsPasswordId = me.idPrefix + "dsPassword" + me.uniqueId;
var loginSubmitId = me.idPrefix + "loginSubmit" + me.uniqueId;
var closeLoginButtonId = me.idPrefix + "closeLoginButton" + me.uniqueId;
var loginMessageId = me.idPrefix + "loginMessage" + me.uniqueId;
var s = "<div id='" + loginContainerId + "' class='dsw-container'>"
+ "<div id='" + loginContainerOverlayId + "' class='dsw-overlay'></div>"
+ "<div class='dsw-titleBar'><table><tr><td class='dsw-titleContainer'><div class='dsw-titlename'>DocuSky Login</div></td><td class='dsw-closeContainer' id='" + closeLoginContainerId + "'><span class='dsw-btn-close' id='" + closeLoginButtonId + "'>✖</span></td></tr></table></div>"
+ "<div class='dsw-containerContent'>"
+ "<table>"
+ "<tr><td class='dsw-td-dslogin dsw-logintitle'>Username:</td><td class='dsw-td-dslogin'><input type='text' class='dsw-userinput' id='" + dsUsernameId + "'/></td></tr>"
+ "<tr><td class='dsw-td-dslogin dsw-logintitle'>Password:</td><td class='dsw-td-dslogin'><input type='password' class='dsw-userinput' id='" + dsPasswordId + "'/></td></tr>"
+ "<tr><td class='dsw-td-dslogin dsw-loginsubmit' colspan='2'><input id='" + loginSubmitId + "' type='submit' value='登入'/></td></tr>"
+ "<tr><td colspan='2' class='dsw-loginmsg' id='" + loginMessageId + "'></td></tr>"
+ "</table>"
+ "</div>"
+ "</div>";
$("html").append(s); // 呃, 用 body 有時會出問題?
$("#" + loginContainerId).hide();
$("#" + loginSubmitId).click(function(e) {
me.login($("#" + dsUsernameId).val(), $("#" + dsPasswordId).val(), me.loginSuccFunc, me.loginFailFunc); // 2018-01-30
});
$("#" + closeLoginButtonId).click(function(e) {
$("#" + loginContainerId).fadeOut();
me.hideWidget();
});
// dbListContainer container
var dbListContainerId = me.idPrefix + "dbListContainer" + me.uniqueId;
var dbListContentId = me.idPrefix + "dbListContent" + me.uniqueId;
var spanDisplaynameId = me.idPrefix + "spanDisplayname" + me.uniqueId;
var dbListImportToBuildDbId = me.idPrefix + "dbListImportToBuildDb" + me.uniqueId;
var logoutAnchorId = me.idPrefix + "logoutAnchor" + me.uniqueId;
var docuskyLinkAnchorId = me.idPrefix + "DocuSkyLinkAnchor" + me.uniqueId;
var closeDbListId = me.idPrefix + "closeDbList" + me.uniqueId; // 20170224
var uploadXmlFileId = me.idPrefix + "uploadXmlFile" + me.uniqueId;
var uploadXmlToBuildDbId = me.idPrefix + "uploadXmlToBuildDb" + me.uniqueId;
var dbTitleForImportId = me.idPrefix + "dbTitleForImport" + me.uniqueId;
var uploadFormId = me.idPrefix + "uploadForm" + me.uniqueId;
var uploadProgressId = me.idPrefix + "uploadProgress" + me.uniqueId;
var myVer = me.package + " - Ver " + me.version;
var t = "登出";
var s = "<div id='" + dbListContainerId + "' class='dsw-container'>"
+ "<div class='dsw-titleBar'>"
+ "<table><tr><td class='dsw-titleContainer'><div class='dsw-titlename' title='" + myVer + "'>資料庫文獻集列表</div> <span class='dsw-btn-docusky' id='" + docuskyLinkAnchorId + "'>DocuSky</span></td>"
+ "<td class='dsw-closeContainer'><div class='dsw-btn-close' id='" + closeDbListId + "'>✖</div><span class='dsw-btn-logout' id='" + logoutAnchorId + "'>Logout</span><span class='dsw-displaynameContainer'><span class='dsw-displayname' id='" + spanDisplaynameId + "'>" + me.displayname + "</span></span></td></tr></table>"
+ "</div>"
+ "<div id='" + dbListContentId + "' class='dsw-containerContent'>"
+ "</div>"
+ "<hr width='96%'/>"
+ "<div id='" + dbListImportToBuildDbId + "' class='dsw-containerContent'>"
+ "<form id='" + uploadFormId + "' name='uploadForm'>"
+ "<div>上載單份 ThdlExportXml 檔以建構文字資料庫:<input type='file' id='" + uploadXmlFileId + "' name='importedFiles[]' accept='.xml'></input></div>"
+ "<table class='dsw-uploadfile'>"
+ "<tr><td>資料庫名稱:</td>"
+ " <td><input type='text' class='dsw-userinput' id='" + dbTitleForImportId + "' name='dbTitleForImport' value='Default'></input></td>"
+ " <td width='40%'><div class='dsw-uploadprogressbar' id='" + uploadProgressId + "'><div class='dsw-uploadprogressbar-progress'></div></div></td>"
+ " <td align='right'><button id='" + uploadXmlToBuildDbId + "' disabled='disabled'>開始上傳</button></td></tr>"
+ "</table>"
+ "</div>"
+ "</form></div>";
+ "</div>";
$("html").append(s);
$("#" + dbListContainerId).hide();
$("#" + logoutAnchorId).click(function(e) {
e.preventDefault();
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
let url = me.urlLogout + ((SessionKey) ? ("?" + SessionKey) : ""); // 2021-02-06
$.get(url, function(jsonObj) {
//me.utility.displayJson(jsonObj);
var dbListContainerId = me.idPrefix + "dbListContainer" + me.uniqueId;
if (jsonObj.code == 0) { // successfully logged out
$("#" + dbListContainerId).fadeOut();
alert("Successfully logged out");
SessionKey = 'NONE'; // 2021-12-30
}
else {
$("#" + dbListContainerId).fadeout();
alert(jsonObj.code + ': ' + jsonObj.message);
}
}, 'json')
.fail(function (jqXHR, textStatus, errorThrown){
if (jqXHR.status=="200") { // 2019-05-07: server return not correct json
alert("Server response seems not a valid JSON");
return;
}
if(jqXHR.status=="404" || jqXHR.status=="403"){
console.error("Server Error");
}
else{
console.error("Connection Error");
}
if (typeof failFunc === "function") {
failFunc();
}
else if(typeof me.Error === "function"){
if(jqXHR.status=="404" || jqXHR.status=="403"){
me.Error("Server Error");
}
else{
me.Error("Connection Error");
}
}
else{
if(jqXHR.status=="404" || jqXHR.status=="403"){
alert("Server Error");
}
else{
if(me.presentRetryCount < me.maxRetryCount){
me.presentRetryCount++;
alert("Connection Error");
}
else{
alert("Please check your Internet connection and refresh this page.");
}
}
}
});
});
$("#" + docuskyLinkAnchorId).click(function(e) {
let url = me.urlUserMain + (SessionKey ? ("?" + SessionKey) : ""); // 2021-02-06
window.open(url);
});
$("#" + closeDbListId).click(function(e) {
me.hideWidget(); // 2017-04-18
});
$("#" + uploadXmlToBuildDbId).click(function(e) {
e.preventDefault(); // 2016-05-05: 非常重要,否則會出現 out of memory 的 uncaught exception
//var loadingContainerId = me.idPrefix + "loadingContainer" + me.uniqueId;
$("#" + loadingContainerId).css({top: e.clientY, left: e.clientX});
$("#" + loadingContainerId).show();
var url = me.urlUploadXmlFilesToBuildDbJson;
url += "?requester=" + me.requester; // 2021-06-25
url += (SessionKey ? ("&" + SessionKey) : ""); // 2021-02-06: 應(也可)放入 form data 中...
var formData = $("#" + uploadFormId).serializeArray();
var nameVal = $("#" + uploadXmlFileId).attr("name"); // <input type="file" name="...">
formData.file = {value: me.fileData, filename: me.fileName, name:nameVal};
//alert(JSON.stringify(formData));
me.uploadMultipart(url, formData);
});
// loadingContainer
var loadingContainerId = me.idPrefix + "loadingContainer" + me.uniqueId;
var loadingSignId = me.idPrefix + "loadingSign" + me.uniqueId;
var workingProgressId = me.idPrefix + "workingProgressId" + me.uniqueId;
var s = "<div id='" + loadingContainerId + "' style='position:absolute; border:3px grey solid; border-radius:6px; background-color:white; z-index: 1003;'>" +
"<div id='" + loadingSignId + "'>" +
"<img src='" + me.urlWebApiPath + "/images/loading-circle.gif' width='140' border='0'/>" +
"</div>" +
"<div id='" + workingProgressId + "' style='position:absolute; top:60px; width:100%; text-align:center;;'></div>" +
"</div>";
$("html").append(s);
$("#" + loadingContainerId).hide();
me.initialized = true;
};
// ----------------------------------------------------------------------------
me.login = function(username, password, succFunc, failFunc) { // 2018-01-30: expose login()
// login and shows DbList
//$.ajaxSetup({async:false});
var postdata = { dsUname: username, // camel style: to get dbCorpusDocuments
dsPword: password,
requester: me.requester // 2021-06-25
};
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}}); // 2018-01-30: must add this for later CORS requests
$.post(me.urlLogin, postdata, function(jsonObj) {
//me.utility.displayJson(jsonObj);
var loginMessageId = me.idPrefix + "loginMessage" + me.uniqueId;
var loginContainerId = me.idPrefix + "loginContainer" + me.uniqueId;
if (jsonObj.code == 0) { // successfully login
// 2022-02-10: 應在 succ callback 前設定 SessionKey!
SessionKey = jsonObj.message; // 2021-02-06: message 將包含 session key 訊息
$("#" + loginMessageId).empty(); // 成功登入,清除(先前可能有的)訊息
$("#" + loginContainerId).fadeOut();
if (typeof succFunc === 'function') succFunc(jsonObj.message); // 2019-02-19 fixed
else me.manageDbList(me.callerEvent, me.callerCallback);
}
else {
console.error("Login Error");
if (typeof failFunc === 'function'){
failFunc(jsonObj);
}
else if(typeof me.Error === "function"){
me.Error("Login Error");
}
else {
$("#" + loginContainerId).show();
$("#" + loginMessageId).html(jsonObj.code + ': ' + jsonObj.message); // jsonObj.code == 101 ==> Requires login
}
}
}, 'json')
.fail(function (jqXHR, textStatus, errorThrown){
if (jqXHR.status=="200") { // 2019-05-04: server return is not correct json
alert("Server response seems not a valid JSON");
return;
}
if(jqXHR.status=="404" || jqXHR.status=="403"){
console.error("Server Error");
}
else{
console.error("Connection Error");
}
if (typeof failFunc === "function") {
failFunc();
}
else if(typeof me.Error === "function"){
if(jqXHR.status=="404" || jqXHR.status=="403"){
me.Error("Server Error");
}
else{
me.Error("Connection Error");
}
}
else{
let loginMessageId = me.idPrefix + "loginMessage" + me.uniqueId;
let loginContainerId = me.idPrefix + "loginContainer" + me.uniqueId;
$("#" + loginContainerId).show();
if(jqXHR.status=="404" || jqXHR.status=="403"){
$("#" + loginMessageId).html("Server Error");
}
else{
if(me.presentRetryCount < me.maxRetryCount){
me.presentRetryCount++;
$("#" + loginMessageId).html("Connection Error");
let retry = function(){
me.login(username, password, succFunc, failFunc);
}
setTimeout(retry,3000);
}
else{
$("#" + loginMessageId).html("Please check your Internet connection and refresh this page.");
}
}
}
});
};
me.logout = function(succFunc, failFunc) { // 2021-06-14
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
let url = me.urlLogout
+ "?requester=" + me.requester // 2021-06-25
+ ((SessionKey) ? ("&" + SessionKey) : ""); // 2021-02-06
$.get(url, function(jsonObj) {
var filenameListContainerId = me.idPrefix + "filenameListContainer" + me.uniqueId;
if (jsonObj.code == 0) { // successfully logged out
$("#" + filenameListContainerId).fadeOut();
if (typeof succFunc === "function") succFunc(jsonObj.message); // 2021-06-14
else alert("Successfully logged out");
SessionKey = 'NONE'; // 2021-12-30
}
else {
$("#" + filenameListContainerId).fadeout();
alert(jsonObj.code + ': ' + jsonObj.message);
}
me.hideWidget(); // 2021-12-30: 隱藏 widget 但不設定 displayWidget 變數
}, 'json')
.fail(function (jqXHR, textStatus, errorThrown){
if (jqXHR.status=="200") { // 2019-05-07: server return not correct json
alert("Server response seems not a valid JSON");
return;
}
if(jqXHR.status=="404" || jqXHR.status=="403"){
console.error("Server Error");
}
else{
console.error("Connection Error");
}
if (typeof failFunc === "function") {
failFunc();
}
else if(typeof me.Error === "function"){
if(jqXHR.status=="404" || jqXHR.status=="403"){
me.Error("Server Error");
}
else{
me.Error("Connection Error");
}
}
else{
if(jqXHR.status=="404" || jqXHR.status=="403"){
alert("Server Error");
}
else{
if(me.presentRetryCount < me.maxRetryCount){
me.presentRetryCount++;
alert("Connection Error");
}
else{
alert("Please check your Internet connection and refresh this page.");
}
}
}
});
};
me.setRequester = function(requester) { // 2021-06-25: 由呼叫者設定 requester 名稱
if (requester) me.requester = requester;
};
me.hideWidget = function(setVar = false, bool = true) { // 2021-12-30: 加入 setVar,登出時雖然需隱藏 widget,但不應設定 displayWidget 為 false
// 2022-02-10: 將 setVar 改放在第一個參數(預設是 false -- 僅關閉視窗,不設定 displayWidget)
if (setVar) me.displayWidget = (bool === false);
//alert(bool + ':' + me.displayWidget);
if (bool || !me.displayWidget) { // 2019-05-03: if bool is true ==> close (i.e., not always hide but just not hide now) the widget
var dbListContainerId = me.idPrefix + "dbListContainer" + me.uniqueId;
$("#" + dbListContainerId).hide();
var loginContainerId = me.idPrefix + "loginContainer" + me.uniqueId;
$("#" + loginContainerId).hide();
clearTimeout(me.timeoutFunId);
me.enableRefresh = false;
}
};
// 2018-01-07
me.hideLoadingIcon = function(bool) {
me.displayLoadingIcon = (bool === false);
};
// 2017-12-28: current events 'dbClick', 'corpusAttCntClick', 'corpusClick', 'attCntClick'
me.enableWidgetEvent = function(evtKey, callback) {
if (me.validEvtKeys.indexOf(evtKey) !== false && typeof(callback)==='function') {
me.widgetEvents[evtKey] = callback;
}
}
me.disableWidgetEvent = function(evtKey) {
if (me.validEvtKeys.indexOf(evtKey) !== false) me.widgetEvents[evtKey] = null;
}
// 2019-04-22
me.setLoadingIcon = function(url){
let loadingSignId = me.idPrefix + "loadingSign" + me.uniqueId;
$("#"+loadingSignId+" img").attr("src", url);
}
var displayDbList = function(evt, succFunc) {
var dbList = me.dbList;
//alert(JSON.stringify(dbList, null, '\t'));
var refreshDbList = false;
var contentTableId = me.idPrefix + "contentTable" + me.uniqueId;
var dbListContentId = me.idPrefix + "dbListContent" + me.uniqueId;
var uploadXmlFileId = me.idPrefix + "uploadXmlFile" + me.uniqueId;
var s = "<table id='" + contentTableId + "' class='dsw-tableDbCorpuslist'>";
for (var i=0; i<dbList.length; i++) {
var username = dbList[i]['username'] || me.username; // 2019-05-04
var ownerUsername = dbList[i]['ownerUsername'] || me.username; // 2019-05-04
var db = dbList[i]['db'];
var dbStatus = dbList[i]['dbStatus'];
if (dbStatus != 0 && dbStatus != 9) refreshDbList = true; // 只要有一份資料庫尚未完成工作,就啟動 refresh
var corpusList = dbList[i]['corpusList'];
var corpusAttCntList = dbList[i]['corpusAttCntList']; // 2017-12-28
var myList = corpusList.split(';');
var attCntList = corpusAttCntList.split(';');
var corpusListStr = "<div>";
for (var j=0; j<myList.length; j++) {
if (j > 0) corpusListStr += ' ‧ ';
var corpus = myList[j];
var attCnt = attCntList[j];
var t2 = "";
let attrStr = `x-db='${db}' x-corpus='${corpus}' x-ownerUsername='${ownerUsername}'`; // 2019-05-04
if (me.widgetEvents.corpusAttCntClick) {
var t1 = "<span class='dsw-corpusAttCntClick' " + attrStr + ">"
+ corpus
+ (attCnt > 0 ? " [" + attCnt + "]" : "")
+ "</span>";
}
else {
var t1 = (me.widgetEvents.corpusClick) ? "<span class='dsw-corpusClick' " + attrStr + ">" + corpus + "</span>" : corpus;
if (attCnt > 0) {
t2 = (me.widgetEvents.attCntClick) ? "<span class='dsw-attCntClick' " + attrStr + ">" + corpus + "'> [" + attCnt + "]</span>" : "[" + attCnt + "]";
}
}
corpusListStr += "<span class='dsw-dbList-corpusnames-corpusname'>"
+ t1 + t2
+ "</span>";
}
corpusListStr += "</div>";
var t = (me.widgetEvents.dbClick) ? "<span class='dsw-dbClick' x-db='" + db + "'>" + db + "</span>" : db;
let hrefDeleteDb = me.urlDeleteDbJson + "?db=" + db
+ (SessionKey ? ("&" + SessionKey) : "")
+ "&requester=" + me.requester; // 2021-06-25
var deleteMsg = (username == ownerUsername)
? "<a class='deleteDb' href='" + hrefDeleteDb + "'>刪除</a>"
: "<span style='background-color:darkred;color:white;'>" + ownerUsername + "</span>";
s += "<tr class='dsw-tr-dbcorpuslist'>"
+ "<td class='dsw-td-dbList dsw-td-dbList-dbname'>" + t + "</td>"
+ "<td class='dsw-td-dbList dsw-td-dbList-corpusnames'>" + corpusListStr + "</td>"
+ "<td class='dsw-td-dbList dsw-td-dbList-delete'>" + deleteMsg + "</td>";
+ "</tr>";
}
s += "</table>";
$("#" + dbListContentId).html(s);
var w = $("#" + contentTableId).width();
// $("#" + dbListContentId).width(800); // 20170224
$("span.dsw-dbClick").on("click", function(evt) {
me.hideWidget();
if (typeof me.widgetEvents.dbClick === 'function') {
me.widgetEvents.dbClick(evt,$(this).attr("x-ownerUsername"),$(this).attr("x-db"));
}
});
$("span.dsw-corpusAttCntClick").on("click", function(evt) {
me.hideWidget();
if (typeof me.widgetEvents.corpusAttCntClick === 'function') {
me.widgetEvents.corpusAttCntClick(evt,$(this).attr("x-ownerUsername"),$(this).attr("x-db"), $(this).attr("x-corpus"));
}
});
$("span.dsw-corpusClick").on("click", function(evt) {
me.hideWidget();
if (typeof me.widgetEvents.corpusClick === 'function') {
me.widgetEvents.corpusClick(evt,$(this).attr("x-ownerUsername"),$(this).attr("x-db"), $(this).attr("x-corpus"));
}
});
$("span.dsw-attCntClick").on("click", function(evt) {
me.hideWidget();
if (typeof me.widgetEvents.attCntClick === 'function') {
me.widgetEvents.attCntClick(evt,$(this).attr("x-ownerUsername"),$(this).attr("x-db"), $(this).attr("x-corpus"));
}
});
// test...
// me.enableWidgetEvent('dbClick', function(db) { alert(db); });
var h = $("#" + contentTableId).height();
$("#" + dbListContentId).height(Math.min(280,h));
$("#" + uploadXmlFileId).change(function(e) {
// Note: currently only support one file upload!
var files = this.files;
me.fileName = files[0].name; // store to object value (only the first file)
var fileSize = files[0].size;
if (fileSize > this.fileSizeLimit) {
alert("Error\n" +
"The size of " + this.fileName + " (" + fileSize + ") exceeds upload limit\n" +
"Upload limit size: " + this.fileSizeLimit);
this.fileData = ''; // if upload empty string, DocuSky will return 'invalid XML' message
return;
}
var loadingContainerId = me.idPrefix + "loadingContainer" + me.uniqueId;
var uploadXmlToBuildDbId = me.idPrefix + "uploadXmlToBuildDb" + me.uniqueId;
$("#" + loadingContainerId).css({top: $("#" + dbListContentId).position().top + $("#" + dbListContentId).height()/2, left: $("#" + dbListContentId).position().left + $("#" + dbListContentId).width()/2});
$("#" + loadingContainerId).show();
readFile(files[0]).done(function(fileData){
me.fileData = fileData;
$("#" + loadingContainerId).hide();
$("#" + uploadXmlToBuildDbId).prop('disabled', false);
});
});
$(".deleteDb").click(function(e) {
e.preventDefault(); // prevent default anchor action
// 2016-08-23: add confirm check
var href = this.href;
var match = this.href.match(/db=([^&]+)/);
var confirmed = confirm("確定要刪除資料庫:「" + decodeURIComponent(match[1] + '」?'));
if (!confirmed) return; // cancel
me.deleteDb(match[1]);
/*$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
$.get(this.href, function(jsonObj) {
var dbListContainerId = me.idPrefix + "dbListContainer" + me.uniqueId;
//me.utility.displayJson(jsonObj);
if (jsonObj.code == 0) { // successfully deleted
//$("#" + dbListContainerId).fadeOut();
alert("Successfully deleted");
me.manageDbList(me.callerEvent, me.callerCallback);
}
else {
$("#" + dbListContainerId).fadeout();
alert(jsonObj.code + ': ' + jsonObj.message);
}
}, 'json');*/
});
var dbListContainerId = me.idPrefix + "dbListContainer" + me.uniqueId;
me.utility.dragElement($("#"+dbListContainerId)[0],$("#"+dbListContainerId+" .dsw-titleBar")[0]);
// 2016-11-19
if (me.enableRefresh && refreshDbList) {
me.timeoutFunId = setTimeout(function() { me.manageDbList(evt, null); }, 15000); // 15 seconds
}
};
//2019-03-06 : public function
me.deleteDb = function(DbTitle,succFunc,failFunc) {
if (!me.initialized) init();
var url = me.urlDeleteDbJson + '?db=' + DbTitle;
url += (SessionKey) ? ("&" + SessionKey) : ""; // 2021-02-06
url += "&requester=" + me.requester; // 2021-06-25
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
$.get(url, function(data) {
if (data.code == 0) { // successfully invoke delete api
if (typeof succFunc === "function") succFunc();
else alert(data.message);
}
else if (data.code == 101) { // requires login
$("#" + loginContainerId).show();
var jelement = $("#" + loginContainerId);
var w = jelement.width();
var h = jelement.height();
jelement.css({ top: '40px', left: '80px' });
jelement.show();
}
else { // fail to invoke delete api
console.error("Server Error");
if (typeof failFunc === "function"){
failFunc();
}
else if(typeof me.Error === "function"){
me.Error("Server Error");
}
else {
alert("Error: " + data.code + "\n" + data.message);
}
}
}, 'json')
.fail(function (jqXHR, textStatus, errorThrown){
if (jqXHR.status=="200") { // 2019-05-04: server return not correct json
alert("Server response seems not a valid JSON");
return;
}
if(jqXHR.status=="404" || jqXHR.status=="403"){
console.error("Server Error");
}
else{
console.error("Connection Error");
}
if (typeof failFunc === "function") {
failFunc();
}
else if(typeof me.Error === "function"){
if(jqXHR.status=="404" || jqXHR.status=="403"){
me.Error("Server Error");
}
else{
me.Error("Connection Error");
}
}
else{
if(jqXHR.status=="404" || jqXHR.status=="403"){
alert("Server Error");
}
else{
if(me.presentRetryCount < me.maxRetryCount){
me.presentRetryCount++;
alert("Connection Error");
let retry = function(){
me.deleteDb(DbTitle,succFunc,failFunc);
}
setTimeout(retry,3000);
}
else{
alert("Please check your Internet connection and refresh this page.");
}
}
}
});
}
// 2019-02-17: public function
me.renameDbTitle = function(oldDbTitle, newDbTitle, succFunc, failFunc) {
if (!me.initialized) init();
var url = me.urlRenameDbTitleJson + '?oldDbTitle=' + oldDbTitle + '&newDbTitle=' + newDbTitle;
url += (SessionKey) ? ("&" + SessionKey) : ""; // 2021-02-06
url += "&requester=" + me.requester; // 2021-06-25
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
$.get(url, function(data) {
if (data.code == 0) { // successfully invoke rename api (but may not update record successfully)
if (typeof succFunc === "function") succFunc();
else alert(data.message);
}
else if (data.code == 101) { // requires login
$("#" + loginContainerId).show();
var jelement = $("#" + loginContainerId);
var w = jelement.width();
var h = jelement.height();
jelement.css({ top: '40px', left: '80px' });
jelement.show();
}
else {
console.error("Server Error");
if (typeof failFunc === "function"){
failFunc();
}
else if(typeof me.Error === "function"){
me.Error("Server Error");
}
else {
alert("Error: " + data.code + "\n" + data.message);
}
}
}, 'json')
.fail(function (jqXHR, textStatus, errorThrown){
if (jqXHR.status=="200") { // 2019-05-04: server return not correct json
alert("Server response seems not a valid JSON");
return;
}
if(jqXHR.status=="404" || jqXHR.status=="403"){
console.error("Server Error");
}
else{
console.error("Connection Error");
}
if (typeof failFunc === "function") {
failFunc();
}
else if(typeof me.Error === "function"){
if(jqXHR.status=="404" || jqXHR.status=="403"){
me.Error("Server Error");
}
else{
me.Error("Connection Error");
}
}
else{
if(jqXHR.status=="404" || jqXHR.status=="403"){
alert("Server Error");
}
else{
if(me.presentRetryCount < me.maxRetryCount){
me.presentRetryCount++;
alert("Connection Error");
let retry = function(){
me.renameDbTitle(oldDbTitle, newDbTitle, succFunc, failFunc);
}
setTimeout(retry,3000);
}
else{
alert("Please check your Internet connection and refresh this page.");
}
}
}
});
}
// 2019-02-19
me.getUserProfile = function(evt, succFunc, failFunc) {
if (!me.initialized) init();
var url = me.urlGetUserProfileJson
+ "?requester=" + me.requester // 2021-06-25
+ (SessionKey ? ("&" + SessionKey) : ""); // 2021-02-06
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
$.get(url, function(data) {
if(evt){
let loadingContainerId = me.idPrefix + "loadingContainer" + me.uniqueId;
$("#"+loadingContainerId).hide();
}
if (data.code == 0) { // successfully invoke rename api (but may not update record successfully)
if (typeof succFunc === "function") succFunc(data.message);
else alert("USER PROFILE:\n" + JSON.stringify(data.message));
}
else if (data.code == 101) { // requires login
var loginContainerId = me.idPrefix + "loginContainer" + me.uniqueId;
$("#" + loginContainerId).show();
var jelement = $("#" + loginContainerId);
var w = jelement.width();
var h = jelement.height();
jelement.css({ top: '40px', left: '80px' });
jelement.show();
}
else {
console.error("Server Error");
if (typeof failFunc === "function"){
failFunc();
}
else if(typeof me.Error === "function"){
me.Error("Server Error");
}
else {
alert("Error: " + data.code + "\n" + data.message);
}
}
}, 'json')
.fail(function (jqXHR, textStatus, errorThrown){
if (jqXHR.status=="200") { // 2019-05-04: server return not correct json
alert("Server response seems not a valid JSON");
return;
}
if(jqXHR.status=="404" || jqXHR.status=="403"){
console.error("Server Error");
}
else{
console.error("Connection Error");
}
if(evt){
let loadingContainerId = me.idPrefix + "loadingContainer" + me.uniqueId;
$("#"+loadingContainerId).show();
let workingProgressId = me.idPrefix + "workingProgressId" + me.uniqueId;
if(jqXHR.status=="404" || jqXHR.status=="403"){
$("#" + workingProgressId).html("<font size='3.5'>Server <br> Error</font>");
}
else{
$("#" + workingProgressId).html("<font size='3.5'>Unstable <br> network</font>");
}
}
if (typeof failFunc === "function") {
failFunc();
}
else if(typeof me.Error === "function"){
if(jqXHR.status=="404" || jqXHR.status=="403"){
me.Error("Server Error");
}
else{
me.Error("Connection Error");
}
}
else{
if(jqXHR.status=="404" || jqXHR.status=="403"){
alert("Server Error");
}
else{
if(me.presentRetryCount < me.maxRetryCount){
me.presentRetryCount++;
alert("Connection Error");
let retry = function(){
me.getUserProfile(evt, succFunc, failFunc);
}
setTimeout(retry,3000);
}
else{
alert("Please check your Internet connection and refresh this page.");
}
}
}
});
}
me.manageDbList = function(evt, succFunc, failFunc) {
//if (!me) { var me = this; }
if (!me.initialized) init();
me.callerEvent = evt;
me.callerCallback = succFunc;
me.enableRefresh = true;
// 決定顯示的位置
var winWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
// winWidth = $('body').innerWidth();
// var scrollbarWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0) - Local.winWidth;
var winHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var loginContainerId = me.idPrefix + "loginContainer" + me.uniqueId;
var loginContainerOverlayId = me.idPrefix + "loginContainerOverlay" + me.uniqueId;
var loadingContainerId = me.idPrefix + "loadingContainer" + me.uniqueId;
let friendDb = (me.includeFriendDb) ? '&includeFriendDb=1' : ''; // 2019-05-04
let displayTarget = 'USER'; // can only "manage" user databases (cannot manage open databases)
let url = me.urlGetDbListJson + '?' + 'target=' + displayTarget + friendDb;
url += (SessionKey) ? ("&" + SessionKey) : ""; // 2021-02-06
url += "&requester=" + me.requester; // 2021-06-25
//$.ajaxSetup({async:false});
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
$.get( url, function(data) {
if(evt){
let loadingContainerId = me.idPrefix + "loadingContainer" + me.uniqueId;
$("#"+loadingContainerId).hide();
}
if (data.code == 0) { // successfully get db list
me.dbList = data.message;
if(evt){
var dbListContainerId = me.idPrefix + "dbListContainer" + me.uniqueId;
var jelement = $("#" + dbListContainerId);
var w = jelement.width();
var h = jelement.height();
var overX = Math.max(0, evt.pageX - 40 + w - winWidth); // 超過右側邊界多少 pixels
var posLeft = Math.max(10, evt.pageX - overX - 40);
var overY = Math.max(0, evt.pageY + h + 15 - winHeight); // 超過下方邊界多少 pixels
//var posTop = Math.min(winHeight - overY - 15, evt.pageY + 15);
var posTop = evt.pageY + 5;
jelement.css({ top: posTop + 'px', left: posLeft + 'px' });
$("#" + dbListContainerId).show();
}
//2019-03-08 inset displayname on dbListContainerId
//Owning to the init() limit, it is needed to insert displayname here.
me.getUserProfile(null,function(data){
me.displayname = data.display_name;
var spanDisplaynameId = me.idPrefix + "spanDisplayname" + me.uniqueId;
$("#"+spanDisplaynameId).html(me.displayname);
});
// 2017-07-22, 2019-05-03
displayDbList(evt);
me.hideWidget(false, !me.displayWidget); // 2019-05-03: only hide widget when setting displayWidget to be false
if (typeof me.callerCallback === "function") me.callerCallback();
}
else if (data.code == 101) { // requires login
if(evt){
$("#" + loginContainerId).show();
var jelement = $("#" + loginContainerId);
var w = jelement.width();
var h = jelement.height();
var overX = Math.max(0, evt.pageX - 40 + w - winWidth); // 超過右側邊界多少 pixels
var posLeft = Math.max(10, evt.pageX - overX - 40);
var overY = Math.max(0, evt.pageY + h + 15 - winHeight); // 超過下方邊界多少 pixels
//var posTop = Math.min(winHeight - overY - 15, evt.pageY + 15);
var posTop = evt.pageY + 5;
jelement.css({ top: posTop + 'px', left: posLeft + 'px' });
jelement.show();
}
else{
$("#" + loginContainerId).show();
var jelement = $("#" + loginContainerId);
var w = jelement.width();
var h = jelement.height();
var overX = Math.max(0, w - 40 - winWidth); // 超過右側邊界多少 pixels
var posLeft = Math.max(10, overX - 40);
var overY = Math.max(0, h + 15 - winHeight); // 超過下方邊界多少 pixels