-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocusky.ui.manageDataFileListSimpleUI.js
1375 lines (1257 loc) · 62.7 KB
/
docusky.ui.manageDataFileListSimpleUI.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.manageDataFileListSimpleUI.js
* (URL)
*
* (Description)
* 這是利用 docusky web api 所包裝起來的一份 JavaScript
* Note: - this component is only tested in 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 (July 07 2017) bugs fix: apply encodeURIComponent() to category/pathfile
* 0.06 (July 28 2017) set "private" methods
* 0.07 (July 31 2017) modify the arguments of jsonTransporter.storeJson(), add hideWidget()
* 0.08 (Nov 27 2017) add renameDataFile()
* 0.09 (January 30 2018) expose login(), add withCredentials
* 0.10 (May 07 2019) add error handling, me.Error, me.maxResponseTimeout, me.maxRetryCount, me.uploadProgressFunc and utility.setStyle
* fix server improperly return a non-JSON (should not retry in this case)
* modify UI display and position
* 0.11 (June 06 2019) remove the dependency of jQuery UI
* 0.12 (July 19 2020) adds login interface to uploadBlob()
* 0.13 (Jan 26 2021) add SessionKey to pass session key via url parameter
* 0.14 (June 13 2021) add public logout() and fix bugs
* 0.15 (June 25 2021) add class variable requester and setRequester()
* 0.16 (Dec 30 2021) add me.urlWebApiPath, add me.urlWebApiPath, fix me.mangeDbList() to me.manageDataFileList(), reset SessionKey after logout
* 0.17 (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 ClsDocuskyManageDataFileListSimpleUI = function(param) { // constructor
var me = this; // store object reference
me.package = 'docusky.ui.manageDataFileListSimpleUI.js'; // 主要目的:取得 data file list,並讓使用者可上載或刪除 data files
me.version = 0.15; // 2021-06-25
me.idPrefix = 'DataFile_';
me.utility = null;
me.protocol = null; // 'http',
me.urlHostPath = null;
me.urlWebApiPath = null;
me.urlGetAllCategoryDataFilenamesJson = null;
me.urlGetCategoryDataFilenamesJson = null; // v0.02
me.urlSaveDataFileJson = null;
me.urlDeleteDataFileJson = null;
me.urlLoadDataFileBinary = null;
me.urlRenameDataFileJson = null;
me.urlLogin = null;
me.urlLogout = null;
me.username = '';
me.requester = 'Widget:manageDataFileList'; // initial value
me.callerEvent = null;
me.callerCallback = null; // 儲存成功執行後所需呼叫的函式
me.initialized = false;
me.categoryFilenameList = []; // 儲存 category => filenames 的物件
me.fileName = ''; // 欲上傳檔案(在本地)的名稱
me.fileData = ''; // 欲上傳檔案的內容
me.displayWidget = true; // 2017-07-31
me.uiState = {}; // 2019-04-29: uiState[dbCorpusListContainerId] = {size: { width:w, height: h}}
me.Error = null; //all scope error handle
me.maxResponseTimeout = 300000;
me.maxRetryCount = 10;
me.presentRetryCount = 0;
me.uploadProgressFunc = null; //callback function for the percentage of upload progress
me.jsonTransporter = { // 利用此物件的 jsonObj 在 client-server 之間傳遞 json 物件
category: 'unknown',
datapath: 'unknown',
filename: 'unknown',
jsonObj: null,
serverCode: 0,
serverMessage: '',
// 利用此函式存取 Json -- 注意 storeJson 和 retrieveJson 字面的 "Json" 指的是以 JSON 儲存到 DocuSky,
// 函式的 json 參數都是物件型態(而非字串)
storeJson: function(category, datapath, filename, jsonObj, succFunc, failFunc) {
// 2017-07-30: 舊的方式傳入 (json, callback) 兩參數,但與 retrieveJson(category, datapath, filename, callback)不對稱
// 為了保持相容,且讓參數對稱,在此對 arguments 進行檢查:若參數數量小於等於 2,使用舊方式維持相容性;否則採用新參數
if (arguments.length <= 2) { // (jsonObj, callback)
var transporter = this;
transporter.jsonObj = arguments[0];
var jsonStr = JSON.stringify(transporter.jsonObj);
var succFunc = (arguments.length == 2) ? arguments[1] : null;
var category = transporter.category; // 舊的方式,利用物件屬性傳遞儲存位置
var datapath = transporter.datapath;
var filename = transporter.filename;
}
else { // (category, datapath, filename, jsonObj, callback)
var category = arguments[0];
var datapath = arguments[1];
var filename = arguments[2];
var jsonStr = JSON.stringify(arguments[3]);
var succFunc = (arguments.length >= 5) ? arguments[4] : null;
var failFunc = (arguments.length >= 6) ? arguments[5] : null;
}
// get parameters from parent
if (me.urlSaveDataFileJson === null) init();
var url = me.urlSaveDataFileJson;
url += "?requester=" + me.requester; // 2021-06-25
url += (SessionKey) ? ("&" + SessionKey) : ""; // 2021-02-06
//alert(SessionKey + "\n" + url);
var fd = new FormData();
fd.append('uploadDataCategory', category);
fd.append('uploadDataPath', datapath);
fd.append('uploadDataFilename', filename);
// 2021-02-06
//if (SessionKey) {
// let [name, val] = SessionKey.split("=");
// fd.append(name, val);
//}
//var bytes = new Uint8Array(me.fileData.length);
//for (var i=0; i<me.fileData.length; i++) bytes[i] = me.fileData.charCodeAt(i);
//var blob = new Blob([bytes]);
var blob = new Blob([jsonStr]);
//alert(me.fileData.length + ':' + blob.size);
fd.append('importedFiles[]', blob);
uploadBlob(url, fd, false, succFunc, failFunc); // false: disable dialog
},
retrieveJson: function(category, datapath, filename, succFunc, failFunc) {
var transporter = this;
transporter.category = category;
transporter.datapath = datapath;
transporter.filename = filename;
var url = me.urlLoadDataFileBinary;
var parameters = "catpathfile=" + encodeURIComponent(transporter.category) + "/" + encodeURIComponent(transporter.datapath) + "/" + encodeURIComponent(transporter.filename);
url += "?" + parameters;
url += "&requester=" + me.requester; // 2021-06-25
url += (SessionKey) ? ("&" + SessionKey) : ""; // 2021-02-06
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
$.getJSON(url, function(data) {
if(data){
transporter.jsonObj = data;
if (typeof succFunc === 'function') succFunc();
}
else{
console.error("Server Error");
if (typeof failFunc === "function"){
failFunc();
}
else if(typeof me.Error === "function"){
me.Error("Server Error");
}
else {
alert("retrieveJson Error");
}
}
});
},
// 2017-07-31
deleteDataFile: function(category, datapath, filename, succFunc, failFunc) {
var transporter = this;
var url = me.urlDeleteDataFileJson;
var parameters = "category=" + encodeURIComponent(category)
+ "&pathfile=" + encodeURIComponent(datapath + "/" + filename);
url += "?" + parameters;
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){
transporter.jsonObj = data;
if (typeof succFunc === 'function') succFunc();
}
else{
console.error("Server Error");
if (typeof failFunc === "function"){
failFunc();
}
else if(typeof me.Error === "function"){
me.Error("Server Error");
}
else {
alert("deleteDataFile Error");
}
}
})
.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");
let retry = function(){
me.jsonTransporter.deleteDataFile(category, datapath, filename, succFunc, failFunc);
}
setTimeout(retry,3000);
}
else{
alert("Please check your Internet connection and refresh this page.");
}
}
}
});
},
// 2016-08-12: v0.02
listCategoryDataFiles: function(category, datapath, succFunc, failFunc) {
var transporter = this;
if (datapath == "*") datapath = "";
var catpath = category + '/' + datapath;
var url = me.urlGetCategoryDataFilenamesJson;
var parameters = "catpath=" + catpath;
url += "?" + parameters;
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){
transporter.jsonObj = data;
if (typeof succFunc === 'function') succFunc();
}
else{
console.error("Server Error");
if (typeof failFunc === "function"){
failFunc();
}
else if(typeof me.Error === "function"){
me.Error("Server Error");
}
else {
alert("listCategoryDataFiles Error");
}
}
})
.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");
let retry = function(){
me.jsonTransporter.listCategoryDataFiles(category, datapath, succFunc, failFunc);
}
setTimeout(retry,3000);
}
else{
alert("Please check your Internet connection and refresh this page.");
}
}
}
});
},
// 2017-11-27: v0.08 (currently not support renaming category and datapath ==> assuming tools need these names to find their data files)
renameDataFile: function(category, datapath, fromFilename, toFilename, succFunc, failFunc) {
var transporter = this;
var url = me.urlRenameDataFileJson;
var parameters = "category=" + encodeURIComponent(category)
+ "&filepath=" + encodeURIComponent(datapath)
+ "&fromFilename=" + encodeURIComponent(fromFilename)
+ "&toFilename=" + encodeURIComponent(toFilename);
url += "?" + parameters;
url += "&requester=" + me.requester; // 2021-06-25
url += (SessionKey) ? ("&" + SessionKey) : ""; // 2021-02-06
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
$.get(url, function(data) {
if(data.code == 0){
transporter.jsonObj = data;
if (typeof succFunc === 'function') succFunc();
}
else{
console.error("Server Error");
if (typeof failFunc === "function"){
failFunc();
}
else if(typeof me.Error === "function"){
me.Error("Server Error");
}
else {
alert("deleteDataFile Error");
}
}
})
.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");
let retry = function(){
me.jsonTransporter.renameDataFile(category, datapath, fromFilename, toFilename, succFunc, failFunc);
}
setTimeout(retry,3000);
}
else{
alert("Please check your Internet connection and refresh this page.");
}
}
}
});
},
};
// =================================
// main functions
// =================================
var init = function() {
//var scriptPath = me.utility.getScriptPath();
//me.urlWebApiPath = 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.urlLogin = me.urlWebApiPath + '/userLoginJson.php';
me.urlLogout = me.urlWebApiPath + '/userLogoutJson.php';
me.urlGetAllCategoryDataFilenamesJson = me.urlWebApiPath + '/getAllCategoryDataFilenamesJson.php';
me.urlGetCategoryDataFilenamesJson = me.urlWebApiPath + '/getDataFilenamesUnderCatpathJson.php';
me.urlSaveDataFileJson = me.urlWebApiPath + '/saveDataFileByHttpPostJson.php';
me.urlDeleteDataFileJson = me.urlWebApiPath + '/deleteDataFileJson.php';
me.urlLoadDataFileBinary = me.urlWebApiPath + '/getDataFileBinary.php';
me.urlRenameDataFileJson = me.urlWebApiPath + '/renameDataFileJson.php';
me.username = '';
me.uniqueId = me.utility.uniqueId();
// login container
var loginContainerId = me.idPrefix + "loginContainer" + 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 loginMessageId = me.idPrefix + "loginMessage" + me.uniqueId;
var s = "<div id='" + loginContainerId + "' class='dsw-container'>"
+ "<div class='dsw-titleBar'><table><tr><td class='dsw-titleContainer'><div class='dsw-titlename'>DocuSky Login</div></td><td class='dsw-closeContainer' id='" + closeLoginContainerId + "'><div class='dsw-btn-close'>✖</div></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 colspan='2' class='dsw-td-dslogin dsw-loginsubmit'><button id='" + loginSubmitId + "'>登入</button></td></tr>"
+ "<tr><td colspan='2' class='dsw-loginmsg' id='" + loginMessageId + "'></td></tr>"
+ "</table>"
+ "</div>"
+ "</div>";
$("html").append(s);
$("#" + loginContainerId).hide(); // zzz
$("#" + loginSubmitId).click(function(e) {
me.username = $("#" + dsUsernameId).val();
$("#" + spanUsernameId).html(me.username);
me.login(me.username, $("#" + dsPasswordId).val());
});
$("#" + closeLoginContainerId).click(function(e) {
$("#" + loginContainerId).hide();
});
var filenameListContainerId = me.idPrefix + "filenameListContainer" + me.uniqueId;
var spanUsernameId = me.idPrefix + "spanUsername" + me.uniqueId;
var filenameListContentId = me.idPrefix + "filenameListContent" + me.uniqueId;
var dataFilenameToUploadId = me.idPrefix + "dataFilenameToUpload" + me.uniqueId;
var uploadFormId = me.idPrefix + "uploadForm" + me.uniqueId;
var uploadDataFilenameSelectedId = me.idPrefix + "uploadDataFilenameSelected" + me.uniqueId;
var uploadDataCategoryId = me.idPrefix + "uploadDataCategory" + me.uniqueId;
var uploadDataPathId = me.idPrefix + "uploadDataPath" + me.uniqueId;
var uploadFormSubmitId = me.idPrefix + "uploadFormSubmit" + me.uniqueId;
var logoutAnchorId = me.idPrefix + "logoutAnchor" + me.uniqueId;
var closefilenameListId = me.idPrefix + "closefilenameList" + me.uniqueId;
var uploadProgressId = me.idPrefix + "uploadProgress" + me.uniqueId; // 20170302
// filenameListContainer container
var myVer = me.package + " - Ver " + me.version;
var t = "登出";
var s = "<div id='" + filenameListContainerId + "' class='dsw-container'>"
+ "<div class='dsw-titleBar'>"
+ "<table><tr><td class='dsw-titleContainer'><div class='dsw-titlename' title='" + myVer + "'>DataFile List</div></td>"
+ "<td class='dsw-closeContainer'>" + "<div class='dsw-btn-close' id='" + closefilenameListId + "'>✖</div>" + "<span class='dsw-btn-logout' id='" + logoutAnchorId + "'>Logout</span>" + "<span class='dsw-useridContainer'><span class='dsw-userid' id='" + spanUsernameId + "'>" + me.username + "</span></span>" + "</td>" + "</tr></table>"
+ "</div>"
+ "<div id='" + filenameListContentId + "' class='dsw-containerContent'>"
+ "</div>"
+ "<hr width='96%'/>"
+ "<div id='" + dataFilenameToUploadId + "' class='dsw-containerContent'>"
+ "<form id='" + uploadFormId + "' name='uploadForm'>"
+ "<div>上載單份資料檔:<input type='file' id='" + uploadDataFilenameSelectedId + "' name='importedFiles[]'></input></div>"
+ "<table class='dsw-uploadfile'>"
+ "<tr><td>指定欲儲存的位置:</td>"
+ "<td>類別:<input type='text' class='dsw-userinput' id='" + uploadDataCategoryId + "' name='uploadDataCategory' value='Default'></input></td>"
+ "<td>路徑:<input type='text' class='dsw-userinput' id='" + uploadDataPathId + "' name='uploadDataPath' size='20' value='Default'></input></td>"
+ "</tr><tr>"
+ "<td colspan='2'><div class='dsw-uploadprogressbar' id='" + uploadProgressId + "'><div class='dsw-uploadprogressbar-progress'></div></div></td>"
+ "<td align='right'><button id='" + uploadFormSubmitId + "' disabled='disabled'>開始上傳</button></td></tr>"
+ "</table>"
+ "</div>"
+ "</form></div>";
+ "</div>";
$("html").append(s);
$("#" + filenameListContainerId).hide();
$("#" + logoutAnchorId).click(function(e) {
e.preventDefault();
me.logout();
});
$("#" + closefilenameListId).click(function(e) {
$("#" + filenameListContainerId).hide();
});
$("#" + uploadFormSubmitId).click(function(e) {
e.preventDefault(); // 2016-05-05: 非常重要,否則會出現 out of memory 的 uncaught exception
//alert(SessionKey);
var url = me.urlSaveDataFileJson;
url += "?requester=" + me.requester; // 2021-06-25
url += (SessionKey) ? ("&" + SessionKey) : ""; // 2021-02-06
var uploadDataCategoryId = me.idPrefix + "uploadDataCategory" + me.uniqueId;
var uploadDataPath = me.idPrefix + "uploadDataPath" + me.uniqueId;
var fd = new FormData();
fd.append('uploadDataCategory', $("#" + uploadDataCategoryId).val());
fd.append('uploadDataPath', $("#" + uploadDataPathId).val());
fd.append('uploadDataFilename', me.fileName);
// 2021-02-06
//if (SessionKey) {
// let [name, val] = SessionKey.split("=");
// fd.append(name, val);
//}
var bytes = new Uint8Array(me.fileData.length);
for (var i=0; i<me.fileData.length; i++) bytes[i] = me.fileData.charCodeAt(i);
var blob = new Blob([bytes]);
//alert(me.fileData.length + ':' + blob.size);
fd.append('importedFiles[]', blob);
uploadBlob(url, fd, true, null); // true: enable dialog display
//// HTTP POST with multipart -- but, XmlHttp has some restrictions on sending binary data!
//var formData = $("#uploadForm").serializeArray();
//var nameVal = $("#uploadDataFilenameSelected").attr("name"); // <input type="file" name="...">
//formData.file = {value: me.fileData, filename: me.fileName, name:nameVal};
});
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.manageDataFileList(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(succFuc) {
$.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: reset SessionKey (否則因已登出,將會取得空的資料)
}
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;
};
// 繪製 DataFileList 的表格
var displayFilenameList = function() { // category => filelist
var editableContentBackup = null;
var categoryFilenameList = me.categoryFilenameList;
//alert(JSON.stringify(categoryFilenameList, null, '\t'));
var contentTableId = me.idPrefix + "contentTable" + me.uniqueId;
var filenameListContentId = me.idPrefix + "filenameListContent" + me.uniqueId;
var uploadDataFilenameSelectedId = me.idPrefix + "uploadDataFilenameSelected" + me.uniqueId;
var s = "<table class='dsw-filenameList' id='" + contentTableId + "'>";
var itemNumber = 0;
for (var category in categoryFilenameList) {
var pathfiles = categoryFilenameList[category];
for (var i=0; i<pathfiles.length; i++) {
itemNumber++;
var pathfile = pathfiles[i];
var p = pathfile.lastIndexOf('/');
if (p === false) conntinue; // invalid pathfile
var path = pathfile.substring(0, p);
var filename = pathfile.substring(p+1);
var categoryEncoded = encodeURIComponent(category); // 20170707
var pathfileEncoded = encodeURIComponent(pathfile); // 20170707
var catpathfileEncoded = encodeURIComponent(category + "/" + pathfile); // 20170730
let hrefViewDataFile = me.urlLoadDataFileBinary + "?catpathfile=" + catpathfileEncoded
+ "&requester=" + me.requester // 2021-06-25
+ (SessionKey ? ("&" + SessionKey) : "");
let hrefDeleteDataFile = me.urlDeleteDataFileJson + "?category=" + categoryEncoded + "&pathfile=" + pathfileEncoded
+ "&requester=" + me.requester // 2021-06-25
+ (SessionKey ? ("&" + SessionKey) : "");
s += "<tr class='dsw-tr-datafilelist'><td class='dsw-filenameList-id'>" + itemNumber + ".</td>"
+ "<td class='dsw-filenameList-category' title='" + category + "'>" + category + "</td>"
+ "<td class='dsw-filenameList-path' title='" + path + "'>" + path + "</td>"
+ "<td class='dsw-filenameList-filename' x-category='" + category + "' x-path='" + path + "' title='" + filename + "'>" + filename + "</td>"
+ "<td class='dsw-filenameList-download'><a class='downloadFile' target='DataFileDownload' href='" + hrefViewDataFile + "'>檢視</a></td>"
+ "<td class='dsw-filenameList-delete'><a class='deleteFile' href='" + hrefDeleteDataFile + "'>刪除</a></td>";
+ "</tr>";
}
}
s += "</table>";
$("#" + filenameListContentId).html(s);
$(".dsw-filenameList-filename").on("dblclick", function() {
$(this).attr("contentEditable", "true");
editableContentBackup = $(this).text();
$(this).addClass("dsw-filenameList-editing");
$(this).focus(); // to prepare for "blur" event
});
$(".dsw-filenameList-filename").on("blur", function() {
var editing = this;
$(editing).removeClass("dsw-filenameList-editing");
$(editing).attr("contentEditable", "false");
var curCategory = $(editing).attr("x-category");
var curPath = $(editing).attr("x-path");
var newVal = $(editing).text();
if (newVal !== editableContentBackup) {
var transporter = me.jsonTransporter;
transporter.renameDataFile(curCategory, curPath, editableContentBackup, newVal, function() {
var response = transporter.jsonObj;
if (response.code === 0) alert("Successfully rename '" + editableContentBackup + "' to '" + newVal);
else {
alert("Error: " + response.message);
$(editing).text(editableContentBackup);
}
editableContentBackup = null;
});
}
else ; // same content ==> does nothing
});
var h = $("#" + contentTableId).height();
$("#" + filenameListContentId).height(Math.min(280,Math.max(h,50)));
$("#" + uploadDataFilenameSelectedId).change(function(e) {
// Currently only support one file upload
var files = this.files;
me.fileName = files[0].name;
readFile(files[0]).done(function(fileData){
me.fileData = fileData;
//alert(me.fileData.length);
let uploadFormSubmitId = me.idPrefix + "uploadFormSubmit" + me.uniqueId;
$("#" + uploadFormSubmitId).prop('disabled', false);
});
//me.urlSaveDataFileJson
});
$(".deleteFile").click(function(e) {
e.preventDefault();
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
$.get(this.href, function(jsonObj) {
var filenameListContainerId = me.idPrefix + "filenameListContainer" + me.uniqueId;
$("#" + filenameListContainerId).fadeOut();
//me.utility.displayJson(jsonObj);
if (jsonObj.code == 0) { // successfully deleted
alert("Successfully deleted");
}
else{
console.error("Server Error");
if (typeof failFunc === "function"){
failFunc();
}
else if(typeof me.Error === "function"){
me.Error("Server Error");
}
else {
alert("deleteDataFile Error");
}
}
}, '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.");
}
}
}
});
});
//2019-04-29
var filenameListContainerId = me.idPrefix + "filenameListContainer" + me.uniqueId;
me.uiState[filenameListContainerId] = {};
me.uiState[filenameListContainerId].size = {};
me.uiState[filenameListContainerId].size.height = $("#"+filenameListContainerId).height();
me.uiState[filenameListContainerId].size.width = $("#"+filenameListContainerId).width();
me.utility.dragElement($("#"+filenameListContainerId)[0],$("#"+filenameListContainerId + " .dsw-titleBar")[0]);
};
// 顯示 DataFileList 的 container
me.manageDataFileList = function(evt, succFunc, failFunc) {
if (!me.initialized) init();
me.callerEvent = evt;
me.callerCallback = succFunc;
if(evt){
// 決定顯示的位置
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);
}
//$.ajaxSetup({async:false});
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
let url = me.urlGetAllCategoryDataFilenamesJson
+ "?requester=" + me.requester // 2021-06-25
+ (SessionKey ? ("&" + SessionKey) : ""); // 2021-02-06
$.get(url, function(data) {
var filenameListContainerId = me.idPrefix + "filenameListContainer" + me.uniqueId;
var loginContainerId = me.idPrefix + "loginContainer" + me.uniqueId;
if (data.code == 0) { // successfully get db list
me.categoryFilenameList = data.message;
if (me.displayWidget) {
var jelement = $("#" + filenameListContainerId);
var w = jelement.width(800); // 2018-03-21
var h = jelement.height();
if (evt) {
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);
}
else {
posTop = 200;
posLeft = 300;
$(window).scrollTop(posTop - 20);
}
jelement.css({ top: posTop + 'px', left: posLeft + 'px' });
jelement.show();
displayFilenameList();
}
if (typeof me.callerCallback === "function") me.callerCallback();
}
else if (data.code == 101) { // requires login
if(me.displayWidget){
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);
jelement.css({ top: posTop + 'px', left: posLeft + 'px' });
jelement.show();
}else{
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
var posTop = Math.min(winHeight - overY - 15, 15);
jelement.css({ top: posTop + 'px', left: posLeft + 'px' });
jelement.show();
}
}
else {
console.error("Server Error");
if (typeof failFunc === "function") {
me.hideWidget(false, me.displayWidget);
failFunc();
}
else if(typeof me.Error === "function"){
me.hideWidget(false, me.displayWidget);
me.Error("Server Error");
}
else{
alert("Error: " + data.code + "\n" + data.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") {
me.hideWidget(false, me.displayWidget);
failFunc();
}
else if(typeof me.Error === "function"){
me.hideWidget(false, me.displayWidget);
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(){
//$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
//$.ajax(this); //occur CORS
me.manageDataFileList(evt, succFunc, failFunc);
}
setTimeout(retry,3000);
}
else{
alert("Please check your Internet connection and refresh this page.");
}
}
}
});
//$.ajaxSetup({async:true});
};
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);
if (bool || !me.displayWidget) {
var filenameListContainerId = me.idPrefix + "filenameListContainer" + me.uniqueId;