-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocusky.ui.getDbCorpusDocumentsSimpleUI.js
1928 lines (1770 loc) · 93 KB
/
docusky.ui.getDbCorpusDocumentsSimpleUI.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.getDbCorpusDocumentsSimpleUI.js
* (URL)
*
* (Description)
* 這是利用 docusky web api 所包裝起來的一份 JavaScript
* Note: - this component is developed and tested under Firefox
* - requires jquery
*
* @version
* 0.01 (April 30 2016)
* 0.02 (August 30 2016)
* 0.03 (December 20 2016) adds PostClassification and TagAnalysis functions
* 0.04 (January 18 2017) adds channelBuffer support
* 0.05 (January 24 2017) fix css class name (adds prefix 'dsw-' to better avoid naming conflicts)
* also fix channelBuffer problems in async mode
* 0.06 (June 19 2017) modify the position of dynamic icons (change "none" to "fix")
* 0.07 (July 17 2017) add hideLoadingIcon(), hideWidget()
* 0.08 (July 29 2017) set "private" methods, add myVer to widget title
* 0.09 (Sept 15 2018) add "fieldsOnly" to urlGetQueryResultDocumentsJson parameter
* 0.10 (Oct 06 2018) add a showPublicDbLink to login container for accessing open databases
* 0.11 (Oct 15 2018) add some functions to support future providers API
* 0.12 (Dec 02 2018) add replaceDocument(), corpus list resizable()
* 0.13 (Mar 23 2019) add url parameter 'includeFriendDb' and setDbListOption()
* 0.14 (April 11 2019) add error handling and me.Error for the most functions and
* remove callerCallbackParameters, loginInvokeFunParameters as well as successFuncParameters in each param
* 0.15 (April 16 2019) add with mechanism on maxResponseTimeout and maxRetryCount
* 0.16 (April 23 2019) add ownerUsername for supporting friend-accessible db
* 0.17 (April 24 2019) add utility.setStyle, setLoadingIcon and modify UI display position
* 0.18 (May 4 2019) fix retry problem when server improperly return a non-JSON
* 0.19 (May 18 2019) add extra DocuSky links to widget display
* 0.20 (June 06 2019) remove the dependency of jQuery UI
* 0.21 (July 12 2019) modify setLoadingIcon() to support more options
* 0.22 (Sept 21 2020) fix provider change bug (add urlWebApiPath)
* 0.23 (Jan 26 2021) add SessionKey to pass session key via url parameter
* 0.24 (June 14 2021) expose login() as public function, add public logout(), and fix bugs
* 0.25 (July 02 2021) add request param to DocuSky API, add setRequester(), and fix bugs (encodeURIComponent(query))
* 0.26 (Dec 30 2021) minor fix (add const parameter forceHttps), reset SessionKey after logout
* 0.27 (Feb 11 2022) add var ForceHttps, WithCredentials (since may include multiple widgets, cannot use 'const' here), fix hideWidget()
*
* @copyright
* Copyright (C) 2016-2019 Hsieh-Chang Tu
*
* @license
*
*/
var ForceHttps = false; // 2021-12-20: 若放到 server 上,可能需設為 true(避免 BigIP 將 http 轉為 https 時沒有帶上 CORS 所需的 headers)
var WithCredentials = true; // 2022-02-10: 若放到 server 上,可能需設為 false(避免瀏覽器不接受 Access-Control-Allow-Origin:* -- 但瀏覽器在登入時會顯示「不安全」訊息)
var SessionKey; // 2021-02-06: 必須是全域變數,才能在 widgets 之間共用(且僅宣告而不指定值)
if (window.navigator.userAgent.indexOf("MSIE ") > 0) {
alert("抱歉,DocuSky 工具目前只支援 Firefox 與 Chrome");
}
var ClsDocuskyGetDbCorpusDocumentsSimpleUI = function(param) { // class (constructor)
var me = this;
this.package = 'docusky.ui.getDbCorpusDocumentsSimpleUI.js'; // 主要目的:取得給定 db, corpus 的文件
this.version = 0.25; // 2021-07-02
this.idPrefix = 'CorpusDoc_'; // 2016-08-13
this.showPublicDbLink = true; // 2018-09-30, 2018-10-15
this.enableGetProviderList = true; // 設定是否嘗試從 api 取得 providers(需 DocuSky 支援 provider api)
this.utility = null;
this.protocol = null; // 'http',
this.urlHostPath = null;
this.urlWebApiPath = null;
this.urlLogin = null;
this.urlGetDbCorpusListJson = null;
this.urlGetQueryResultDocumentsJson = null;
this.urlGetQueryPostClassificationJson = null; // 2016-12-18
this.urlGetQueryTagAnalysisJson = null; // 2016-12-19
this.urlUpdateCorpusDocumentJson = null;
this.urlReplaceSingleCorpusDocJson = null; // 2018-10-15
this.urlGetProviderListJson = null; // 2018-10-12
this.callerEvent = null;
this.callerCallback = null; // 儲存成功執行後所需呼叫的函式
//this.callerCallbackParameters = null; // 儲存回呼函式的傳入參數
this.initialized = false;
this.target = 'USER'; // 'target', 'db', 'corpus' are input parameters of urlGetQueryResultDocumentsJson
this.includeFriendDb = false; // 2019-03-23: default false for backward-compatibility
this.ownerUsername = null; // 2019-04-21: 目前似乎只需 ownerUsername 而不需要 username...
this.db = '';
this.corpus = '';
this.query = ''; // 儲存最後一個 query
this.fieldsOnly = undefined; // 2018-09-14
this.requester = 'Widget:getDbCorpusDocuments'; // 2021-06-24: 預設值,呼叫者可覆蓋(修改起來頗繁瑣,目前只是先加進此變數)
this.loadingIconWidth = 140; // 2017-06-19: size of the loading image
this.displayLoadingIcon = true; // 2017-07-13
this.displayWidget = true; // 2017-07-24
// login action
this.loginInvokeFun = null;
//this.loginInvokeFunParameters = null;
// returns
this.totalFound = 0;
this.page = 1;
this.pageSize = 200; // default page size
this.docList = []; // 儲存 DocuSky 的文件列表 (if fieldsOnly ==> the content will be doc metadata only)
this.spotlights = '';
this.featureAnalysisSettings = ''; // 2019-04-23: expose to caller
this.postClassification = {};
this.features = '';
this.tagAnalysis = {};
this.channelBuffer = {}; // store query results in "channels" (access by channelKey)
// extra data
this.providerList = []; // 2018-10-12
this.uiState = {}; // 2018-12-02: uiState[dbCorpusListContainerId] = {size: { width:w, height: h}}
this.Error = null; //all scope error handle
this.maxResponseTimeout = 300000;
this.maxRetryCount = 10;
this.presentRetryCount = 0;
if (typeof(param)=='object' && 'target' in param) {
me.target = (param.target.toUpperCase() == 'OPEN') ? 'OPEN' : 'USER';
}
// a small set of default loading icons
this.loadingIconSet = [ 'loading-circle.gif', 'loading-circle-gray.gif',
'loading-gears-blue.gif', 'loading-blueball.gif'];
this.loadingIconIdx = 0;
this.loadingIconMessageType = 0; // 2019-07-12: 0: default (page n), 1: fetched/total
// =================================
// main functions
// =================================
var init = function() {
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';
let pathParts = me.urlHostPath.match(/(http[s]?):\/\/([^\/]+)\/(.*)/);
let pos = me.urlWebApiPath.split('/', 3).join('/').length;
let [urlHost, urlPort] = pathParts[2].split(':');
let urlPath = me.urlWebApiPath.substr(pos);
if (urlPort === undefined) urlPort = (scheme == 'http') ? '80' : '443';
let curProvider = { title: 'Current',
type: 'api',
urlScheme: scheme,
urlHost: urlHost,
urlPort: urlPort,
urlPath: urlPath,
description: 'Current'};
me.providerList.push(curProvider);
//alert(JSON.stringify(curProvider));
setUrlApiPath(me, curProvider);
me.uniqueId = me.utility.uniqueId();
//alert(me.uniqueId);
// 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 showProviderListId = me.idPrefix + "showProviderList" + me.uniqueId;
var myVer = me.package + " - Ver " + me.version;
var myProvider = (me.enableGetProviderList) ? " P " : ""; // note: will show this option when there are more than 1 providers
var s = "<div id='" + loginContainerId + "' class='dsw-container'>"
+ "<div id='" + loginContainerOverlayId + "' class='dsw-overlay'></div>"
+ "<div id='" + loginContainerId + "_TitleBar' class='dsw-titleBar'>"
+ "<table><tr>"
+ "<td class='dsw-titleContainer' title='Select DocuSky Provider'><nobr><span id='" + showProviderListId + "' class='dsw-span-listOption'>" + myProvider + "</span><span class='dsw-span-provider'></span><span class='dsw-titlename'>Login</span></nobr></td>"
+ "<td class='dsw-closeContainer' id='" + closeLoginContainerId + "'><span class='dsw-btn-close' id='" + closeLoginButtonId + "'>✖</span></td>" // 2018-10-06: adds id for draggable with TitleBar
+ "</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>"
+ ((me.showPublicDbLink) ? ("<tr><td colspan='2'><span class='dsw-listOpenCorpuses'>Public Databases</span></td></tr>") : "")
+ "</table>"
+ "</div>"
+ "</div>";
$("html").append(s);
$("#" + loginContainerId).hide();
$("#" + loginSubmitId).click(function(e) {
me.login($("#" + dsUsernameId).val(), $("#" + dsPasswordId).val());
});
$("#" + closeLoginButtonId).click(function(e) {
$("#" + closeProviderListButtonId).click(); // close provider window
$("#" + loginContainerId).fadeOut();
});
$("#" + showProviderListId).click(function(e) {
displayProviderList(curProvider, e);
$("#" + providerListContainerId).fadeIn();
});
$("span.dsw-listOpenCorpuses").click(function(e) { // 2018-09-30
//alert($(this).attr('id'));
$("#" + loginContainerId).hide();
var param = { target: 'OPEN',
invokeFunName: 'getDbCorpusDocumentsGivenPageAndSize'};
displayDbCorpusList(param, me.callerEvent);
});
// 2018-10-13: providerList container
var providerListContainerId = me.idPrefix + "providerListContainer" + me.uniqueId;
var providerListContainerOverlayId = me.idPrefix + "providerListContainerOverlay" + me.uniqueId;
var providerListContentId = me.idPrefix + "providerListContent" + me.uniqueId;
var closeProviderListContainerId = me.idPrefix + "closeProviderListContainer" + me.uniqueId;
var closeProviderListButtonId = me.idPrefix + "closeProviderListButton" + me.uniqueId;
var s = "<div id='" + providerListContainerId + "' class='dsw-container' style='border-color:#3F3F3F; z-index:1002'>"
+ "<div id='" + providerListContainerOverlayId + "' class='dsw-overlay'></div>"
+ "<div id='" + providerListContainerId + "_TitleBar' class='dsw-titleBar'>"
+ "<table><tr>"
+ "<td class='dsw-titleContainer' title='ProviderList'><nobr><span class='dsw-span-provider'></span><span class='dsw-titlename'>Providers</span></nobr></td>"
+ "<td class='dsw-closeContainer' id='" + closeProviderListContainerId + "'><span class='dsw-btn-close' id='" + closeProviderListButtonId + "'>✖</span></td>"
+ "</tr></table>"
+ "</div>"
+ "<div class='dsw-containerContent'>"
+ "<table>"
+ "</table>"
+ "<div id='" + providerListContentId + "' class='dsw-containerContent'>"
+ "</div>";
$("html").append(s);
$("#" + providerListContainerId).hide();
$("#" + closeProviderListButtonId).click(function(e) {
$("#" + providerListContainerId).fadeOut();
});
me.utility.dragElement($("#" + providerListContainerId)[0],$('#' + providerListContainerId + '_TitleBar')[0]);
// dbCorpusListContainer container
var dbCorpusListContainerId = me.idPrefix + "dbCorpusListContainer" + me.uniqueId;
var dbCorpusListContainerOverlayId = me.idPrefix + "dbCorpusListContainerOverlay" + me.uniqueId;
var closeDbCorpusListButtonId = me.idPrefix + "closeDbCorpusListButton" + me.uniqueId;
var closeDbCorpusListContainerId = me.idPrefix + "closeDbCorpusListContainer" + me.uniqueId;
var dbCorpusListContentId = me.idPrefix + "dbCorpusListContent" + me.uniqueId;
var logoutDBId = me.idPrefix + "logoutDB" + me.uniqueId;
var s = "<div id='" + dbCorpusListContainerId + "' class='dsw-container'>"
+ "<div id='" + dbCorpusListContainerOverlayId + "' class='overlay'></div>"
+ "<div id='" + dbCorpusListContainerId + "_TitleBar' class='dsw-titleBar'>"
+ "<table>"
+ "<tr><td class='dsw-titleContainer'>" // 2018-10-06: adds id to title bar for draggable event
+ "<nobr><span class='dsw-span-provider'></span><span id='" + dbCorpusListContainerId + "_Title' class='dsw-titlename' title='DbCorpusList'>DbCorpus List</span></nobr></td>"
+ "<td class='dsw-closeContainer' id='" + closeDbCorpusListContainerId + "'>"
+ "<span class='dsw-btn-close' id='" + closeDbCorpusListButtonId + "'>✖</span>"
+ "<span class='dsw-btn-logout' id='" + logoutDBId + "' title='登出'>Logout</span></td></tr>"
+ "</table></div>"
+ "<div id='" + dbCorpusListContentId + "' class='dsw-containerContent'>"
+ "</div>"
+ "</div>";
$("html").append(s);
$("#" + dbCorpusListContainerId).hide();
$("#" + logoutDBId).click(function(e) {
e.preventDefault();
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
let url = me.urlLogout + "?requester=" + me.requester // 2021-06-24
+ ((SessionKey) ? ("&" + SessionKey) : ""); // 2021-02-06
$.get(url, function(jsonObj) {
//me.utility.displayJson(jsonObj);
if (jsonObj.code == 0) { // successfully logged out
alert("Successfully logged out");
SessionKey = 'NONE'; // 2021-12-30
}
else {
alert(jsonObj.code + ': ' + jsonObj.message);
}
$("#" + dbCorpusListContainerOverlayId).show();
$("#" + dbCorpusListContainerId).fadeOut();
}, '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.");
}
}
}
});
// Clear out obtained document list
me.docList = [];
});
$("#" + closeDbCorpusListButtonId).click(function(e) {
$("#" + dbCorpusListContainerOverlayId).show();
$("#" + dbCorpusListContainerId).fadeOut();
});
// loadingContainer
var loadingContainerId = me.idPrefix + "loadingContainer" + me.uniqueId;
var workingProgressId = me.idPrefix + "workingProgressId" + me.uniqueId;
var loadingIcon = me.loadingIconSet[me.loadingIconIdx];
var s = "<div id='" + loadingContainerId + "' class='dsw-loadingIcon'>" +
"<img id='dsLoadingIcon' src='" + me.urlWebApiPath + "/images/loading/" + loadingIcon + "' width='" + me.loadingIconWidth + "' border='0'/>" +
"<div id='" + workingProgressId + "' class='dsw-progressMessage' style='position:absolute; top:60px; left:20%; width:60%; text-align:center;'></div>" +
"</div>";
$("html").append(s);
$("#" + loadingContainerId).hide();
// 2018-10-12: set provider list
if (me.enableGetProviderList) {
// location.procotol contains ':'
let url = me.urlGetProviderListJson + "?scheme=http,https&requester=" + me.requester; // 2021-06-24
url += (SessionKey) ? ("&" + SessionKey) : ""; // 2021-02-06
$.ajax({ url: url, method: "GET"})
.done(function(retObj) {
if (retObj.code == 0) {
var curProvider = me.providerList[0];
retObj.message.forEach(function(item, idx) {
if (item.urlScheme.toLowerCase() != curProvider.urlScheme.toLowerCase()
|| item.urlHost.toLowerCase() != curProvider.urlHost.toLowerCase()
|| item.urlPort.toLowerCase() != curProvider.urlPort.toLowerCase()
|| item.urlPath.toLowerCase() != curProvider.urlPath.toLowerCase()) {
me.providerList.push(item);
}
});
}
else{
console.error("Server Error");
if(typeof me.Error === "function"){
me.Error("Server Error");
}
else {
alert("Error: " + retObj.message);
}
}
//setUrlApiPath(me, me.providerList[1]); // test
})
.fail(function(jqXHR, textStatus) {
console.error("Connection Error: " + url); // 2020-10-08: local test 會跑出 connection error?
if(typeof me.Error === "function"){
me.Error("Connection Error: " + url);
}
else{
alert("Connection Error");
}
})
.always(function() {
// 2018-10-14
var showProviderListId = me.idPrefix + "showProviderList" + me.uniqueId;
if (me.providerList.length <= 1) $("#" + showProviderListId).hide("");
});
};
// 2017-01-17: clear variables
me.channelBuffer = {};
me.initialized = true;
};
var setUrlApiPath = function(obj, provider) { // 2018-10-12
if (provider.urlScheme == 'https') {
var port = (provider.urlPort != "443") ? (":" + provider.urlPort) : ":443";
}
else if (provider.urlScheme == 'file') {
provider.urlScheme = 'https';
provider.urlHost = 'docusky.org.tw';
port = ':443';
}
else {
port = (provider.urlPort != "80") ? (":" + provider.urlPort) : "";
}
var urlApiPath = provider.urlScheme + "://" + provider.urlHost + port + provider.urlPath;
//alert("SET API PATH: " + urlApiPath);
obj.urlWebApiPath = urlApiPath; // 2020-09-21: bug fix (e.g., to allow invokers to connect to retrieval page directly)
obj.urlLogin = urlApiPath + '/userLoginJson.php';
obj.urlLogout = urlApiPath + '/userLogoutJson.php';
obj.urlGetDbCorpusListJson = urlApiPath + '/getDbCorpusListJson.php';
obj.urlGetQueryResultDocumentsJson = urlApiPath + '/getQueryResultDocumentsJson.php';
obj.urlGetQueryPostClassificationJson = urlApiPath + '/getQueryPostClassificationJson.php';
obj.urlGetQueryTagAnalysisJson = urlApiPath + '/getQueryTagAnalysisJson.php';
obj.urlUpdateCorpusDocumentJson = urlApiPath + '/updateCorpusDocumentJson.php';
obj.urlReplaceSingleCorpusDocJson = urlApiPath + '/replaceSingleCorpusDocJson.php';
obj.urlGetProviderListJson = urlApiPath + '/getProviderListJson.php';
obj.curProvider = JSON.parse(JSON.stringify(provider)); // copy content
$(".dsw-span-provider").html(provider.title);
};
var displayDbCorpusList = function(param, evt) { // list all db/corpus pairs (not the corpuses under a given db)
// add the mechanism of inadvertent error prevention on UI display
if(!evt && me.displayWidget){
var evt = {clientX:40, clientY:40};
}
var loginContainerId = me.idPrefix + "loginContainer" + me.uniqueId;
$("#" + loginContainerId).hide();
// show loading icon
var loadingContainerId = me.idPrefix + "loadingContainer" + me.uniqueId;
var workingProgressId = me.idPrefix + "workingProgressId" + me.uniqueId;
$("#" + loadingContainerId).css({top: evt.clientY, left: evt.clientX});
$("#" + loadingContainerId).show();
$("#" + workingProgressId).html("connecting");
var dbCorpusListContentId = me.idPrefix + "dbCorpusListContent" + me.uniqueId;
var dbCorpusListContainerOverlayId = me.idPrefix + "dbCorpusListContainerOverlay" + me.uniqueId;
var dbCorpusListContainerId = me.idPrefix + "dbCorpusListContainer" + me.uniqueId;
var displayTarget = param.target;
var titleId = dbCorpusListContainerId + "_Title";
$("#" + titleId).html(displayTarget + " corpus list"); // 2018-10-02, 2018-10-13
var invokeFunName = param.invokeFunName;
//$.ajaxSetup({async:false});
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
let friendDb = (me.includeFriendDb || param.includeFriendDb) ? '&includeFriendDb=1' : ''; // 2021-06-13: 加上 param.includeFriendDb
let url = me.urlGetDbCorpusListJson + '?' + 'target=' + displayTarget + friendDb + '&requester=' + me.requester;
url += (SessionKey) ? ("&" + SessionKey) : ""; // 2021-02-06
//alert(url);
$.get(url, function(data) {
$("#" + loadingContainerId).hide();
if (data.code == 0) { // success
//me.utility.displayJson(data);
var dbCorpusList = data.message;
//me.utility.displayJson(dbCorpusList);
var contentTableId = me.idPrefix + "dbCorpusContentTable" + me.uniqueId;
var s = "<table id='" + contentTableId + "' class='dsw-tableContentList'>";
for (var i=0; i<dbCorpusList.length; i++) {
let target = dbCorpusList[i]['target'];
let ownerUsername = dbCorpusList[i]['ownerUsername']; // 2019-03-23
var username = dbCorpusList[i]['username']; // 2019-03-23
var db = dbCorpusList[i]['db'];
var corpus = dbCorpusList[i]['corpus'];
var page = me.page; // 2018-07-03 wayne
var pageSize = me.pageSize;
var channelKey = me.channelKey; // 2018-09-14
var fieldsOnly = me.fieldsOnly; // 2018-09-14
var num = i + 1;
var urlParam = "target=" + target
+ "&ownerUsername=" + ownerUsername
+ "&db=" + db + "&corpus=" + corpus + "&query=.all&page=" + page + "&pageSize=" + pageSize
+ (fieldsOnly ? "&fieldsOnly=" + fieldsOnly : '');
s += "<tr class='dsw-tr-contentlist'>"
+ "<td class='dsw-td-contentlist dsw-td-contentlist-num' width='25'>" + num + ".</td>"
+ "<td class='dsw-td-contentlist dsw-td-contentlist-dbname' align='left' width='32%'>" + (username == ownerUsername ? "" : "<span class='dsw-ownerUsername'>" + ownerUsername + "</span> ") + db + "</td>"
+ "<td class='dsw-td-contentlist dsw-td-contentlist-corpusname' width='50%'>" + corpus + "</td>"
+ "<td class='dsw-td-contentlist dsw-td-contentlist-load'><nobr><a class='loadDbCorpusDocument' href='dummy?" + urlParam + "'>載入</a></nobr></td>" // 2018-09-04: add <nobr>
+ "</tr>";
}
if (me.showPublicDbLink) { // 2018-09-30
var t = "<td class='dsw-inExtraRow' colspan='2' align='right'>開啟:<span id='openDocuSkyHome' class='dsw-linkOpenWin'>DocuSky 首頁</span> | <span id='openMyDatabases' class='dsw-linkOpenWin'>我的資料庫</span>  </td>"; // 2019-05-18
s += (displayTarget == 'OPEN')
? "<tr><td class='dsw-inExtraRow' colspan='2' align='left'><span class='dsw-listPersonalCorpuses'>Show Personal Databases</span></td>" + t + "</tr>"
: "<tr><td class='dsw-inExtraRow' colspan='2' align='left'><span class='dsw-listOpenCorpuses'>Show Public Databases</span></td>" + t + "</tr>";
}
s += "</table>";
me.target = displayTarget; // set target to object scope
//var w = Math.min($("#" + contentTableId).width(), 600);
let w = me.uiState[dbCorpusListContainerId] && me.uiState[dbCorpusListContainerId].size
&& me.uiState[dbCorpusListContainerId].size.width; // 2018-12-02
w = (w === undefined) ? 600: w - 12; // assumes border 12 in total
$("#" + dbCorpusListContentId).width(w); // 設定寬度
$("#" + dbCorpusListContentId).html(s);
// 2018-09-30: needs to place event hander for switching open/personal corpuses
$("span.dsw-listOpenCorpuses").unbind("click").click(function(e) {
var param = { target: 'OPEN',
invokeFunName: 'getDbCorpusDocumentsGivenPageAndSize'};
displayDbCorpusList(param, evt);
});
$("span.dsw-listPersonalCorpuses").unbind("click").click(function(e) {
var param = { target: 'USER',
invokeFunName: 'getDbCorpusDocumentsGivenPageAndSize'};
displayDbCorpusList(param, evt);
});
$("#openDocuSkyHome").unbind("click").click(function(e) { // 2019-05-18
var url = (e.altKey)
? me.urlHostPath + "/ds-v1-01.home.html"
: "https://docusky.org.tw";
window.open(url, "_blank");
});
$("#openMyDatabases").unbind("click").click(function(e) { // 2019-05-18
var url = (e.altKey)
? me.urlHostPath + "/userMainPage.php"
: "https://docusky.org.tw/docusky/docuTools/UserMain/index.html";
window.open(url, "_blank");
});
$(".loadDbCorpusDocument").click(function(e) {
e.preventDefault();
var url = this.href;
var target = me.utility.getUrlParameterVarValue(url, 'target');
var ownerUsername = me.utility.getUrlParameterVarValue(url, 'ownerUsername'); // 2019-04-21
var db = me.utility.getUrlParameterVarValue(url, 'db');
var corpus = me.utility.getUrlParameterVarValue(url, 'corpus');
var page = me.utility.getUrlParameterVarValue(url, 'page');
var pageSize = me.utility.getUrlParameterVarValue(url, 'pageSize');
var fieldsOnly = me.utility.getUrlParameterVarValue(url, 'fieldsOnly'); // 2018-09-15
// 2016-08-30(pykenny) remove argument "message"
//me.getDbCorpusDocumentsGivenPageAndSize(target, db, corpus, page, pageSize, me.callerEvent, me.callerCallback); // me.callerCallback 負責將載入的內容顯示出來
// 2017-01-17: 先前沒規劃好,讓函式具有相同的參數結構,現在只好用 switch 個別檢查...
// 否則,若能用 callback.apply(),程式就會漂亮許多..
// 例如:callback.apply(me, [target, db, corpus, page, pageSize, me.callerEvent, me.callerCallback]); // me.callerCallback 負責將載入的內容顯示出來
var param = { target: target,
ownerUsername: ownerUsername, // 2019-04-21
db: db,
corpus: corpus,
page: page,
pageSize: pageSize, // 2018-09-18: fix bug (misspelled "pageSizde")
fieldsOnly: fieldsOnly, // 2018-09-15
};
switch (invokeFunName) {
case 'getDbCorpusDocumentsGivenPageAndSize':
// me.callerCallback 負責將載入的內容顯示出來
// 2017-07-22: 注意,傳入當前的 event e,而非 me.callerEvent
//me.getDbCorpusDocumentsGivenPageAndSize(target, db, corpus, page, pageSize, e, me.callerCallback, null);
me.getQueryResultDocuments(param, evt, me.callerCallback); // 2018-09-15
break;
case 'getQueryPostClassification':
me.getQueryPostClassification(param, me.callerEvent, me.callerCallback);
break;
case 'getQueryTagAnalysis':
me.getQueryTagAnalysis(param, me.callerEvent, me.callerCallback);
break;
default:
// unsupported function
console.log("Unsupported function: " + invokeFunName);
}
});
$("#" + dbCorpusListContainerOverlayId).show();
// 2016-05-24: 必須在顯示之後,才能取得 render 之後的 height...
// To get an accurate value, ensure the element is visible before using .height()
let jelement = $("#" + dbCorpusListContainerId);
let duration = 40;
let opacity = 1;
//jelement.position({my: "left top", at: "center bottom", of: evt, collision: "fit"}); // 20170619: change "none" to "fit"
jelement.fadeTo(duration, opacity, function() {
// 2018-10-02
//let h = $(this).height();
let h = $("#" + dbCorpusListContentId).height(); // 2018-10-08
h = Math.min(360, Math.max(h,50));
$("#" + dbCorpusListContentId).height(h);
$(this).css({top: evt.clientY, left: evt.clientX});
});
$("#" + dbCorpusListContainerOverlayId).hide();
//jelement.position({my: "left top", at: "center bottom", of: evt, collision: "fit"}); // 20170619: change "none" to "fit"
//alert(h);
//$("#" + dbCorpusListContentId).height(h);
}
else {
if (data.code == '101') { // 2018-09-30: requires login
$("#" + dbCorpusListContainerId).hide();
let loginContainerId = me.idPrefix + "loginContainer" + me.uniqueId;
$("#" + loginContainerId).show();
}
else {
console.error("Server Error");
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 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(){
displayDbCorpusList(param, evt);
}
setTimeout(retry,3000);
}else{
alert("Please check your Internet connection and refresh this page.");
}
}
}
});
//$.ajaxSetup({async:true});
};
var displayProviderList = function(curProvider, evt) {
var providerListContainerId = me.idPrefix + "providerListContainer" + me.uniqueId;
var providerListContainerOverlayId = me.idPrefix + "providerListContainerOverlay" + me.uniqueId;
var providerListContentId = me.idPrefix + "providerListContent" + me.uniqueId;
var providers = me.providerList;
// TODO: show content...
var contentTableId = me.idPrefix + "providerContentTable" + me.uniqueId;
var s = "<table id='" + contentTableId + "' class='dsw-tableContentList'>";
for (var i=0; i<providers.length; i++) {
let title = providers[i].title;
let host = providers[i].urlScheme + "://" + providers[i].urlHost;
let description = providers[i].description;
s += "<tr class='dsw-tr-contentlist'>"
+ "<td class='dsw-td-contentlist dsw-td-contentlist-num'>" + (i+1) + ".</td>"
+ "<td class='dsw-td-contentlist'>" + title + "</td>"
+ "<td class='dsw-td-contentlist'>" + host + "</td>"
+ "<td class='dsw-td-contentlist'>" + description + "</td>"
+ "<td class='dsw-td-contentlist'><nobr><a class='dsw-a-switchProvider' x-title='" + title + "'>選擇</a></nobr></td>"
+ "</tr>";
}
s += "</table>";
$("#" + providerListContentId).html(s);
$(".dsw-a-switchProvider").click(function() {
var title = $(this).attr("x-title");
me.providerList.forEach(function(provider, idx) {
if (provider.title == title) {
setUrlApiPath(me, provider);
return;
}
});
$("#" + providerListContainerId).hide();
});
$("#" + providerListContainerId).css({top:0, left:0, position:'absolute'}); // needs to reset position first? (or, the position will move if clicking several times?)
$("#" + providerListContainerOverlayId).show();
let jelement = $("#" + providerListContainerId);
let duration = 200;
let opacity = 1;
let h = $("#" + providerListContentId).height
h = Math.min(300, Math.max(h,50));
$("#" + providerListContentId).height(h);
//alert(evt.pageX + ':' + evt.pageY);
//jelement.position({my:"left+20 top", at:"center bottom", of:evt, collision:"none"});
jelement.css({top: evt.pageX, left: evt.pageY, position:'absolute'});
$("#" + providerListContainerOverlayId).hide();
};
// -------------- object "public" functions ---------
me.login = function(username, password, succFunc, failFunc) { // 2021-06-13: 改 public, 加上 succFunc
//$.ajaxSetup({async:false});
//var postdata = { dsgUname: username, dsgPword: password }; // camel style: to get dbCorpusDocuments
//$.post("../DocuGate/webApi/userDispatcherLoginJson.php", postdata, function(jsonObj) {
var postdata = { dsUname: username, // camel style: to get dbCorpusDocuments
dsPword: password,
requester: me.requester };
$.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 loginContainerOverlayId = me.idPrefix + "loginContainerOverlay" + 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 訊息 -- getQueryResultDocuments() 會用到(放入 url parameter)
$("#" + loginMessageId).empty(); // 成功登入,清除(先前可能有的)訊息
$("#" + loginContainerOverlayId).show();
$("#" + loginContainerId).fadeOut();
if (typeof succFunc === "function") succFunc(jsonObj.message);
//else if (typeof me.loginInvokeFun === "function") me.loginInvokeFun(jsonObj); // 登入後,就自動載入第一頁的內容... 日後該改為可由工具自行設定
else {
me.target = 'USER'; // 2018-10-02
//me.getDbCorpusDocuments(me.target, me.db, me.corpus, me.callerEvent, me.callerCallback, me.callerCallbackParameters);
// 2018-09-15
var param = { target: me.target,
ownerUsername: me.ownerUsername, // 2019-04-21
db: me.db,
corpus: me.corpus,
page: me.page,
pageSize: me.pageSize, // 2018-09-18: fix bug (misspelled "pageSizde")
fieldsOnly: me.fieldsOnly,
requester: me.requester, // 2021-06-24
};
//alert(JSON.stringify(param));
me.getQueryResultDocuments(param, me.callerEvent, me.callerCallback);
}
}
else if (jsonObj.code == 101) ; // alert("Login fails: requires login"); // Requires login
else {
console.error("Login Error");
if(typeof me.Error === "function"){
me.Error("Login Error");
}
else {
$("#" + 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 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 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);
}
setTimeout(retry,3000);
}
else{
$("#" + loginMessageId).html("Please check your Internet connection and refresh this page.");
}
}
}
});
//$.ajaxSetup({async:true});
};
me.logout = function(succFunc) { // 2021-06-14
$.ajaxSetup({xhrFields: {withCredentials: WithCredentials}});
let url = me.urlLogout + ((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.addExtraApiFunctions = function(func) { // e.g., add extra/docusky.dbRefdataAPI.js
if (typeof func === 'function') func(me);
else alert("Argument of addExtraFunctions() must be a function");
};
me.setRequester = function(requester) { // 2021-06-24: 由呼叫者設定 requester 名稱
if (requester) me.requester = requester;
};
/*me.setLoginAction = function(loginInvokeFun, loginInvokeFunParameters) {
me.loginInvokeFun = loginInvokeFun;
me.loginInvokeFunParameters = loginInvokeFunParameters;
}*/
// --------------------------------------------------------------------------------------
// 2021-06-13
me.getAccessibleDbCorpusList = function(param, succFunc, failFunc) {
let friendDb = (param.includeFriendDb) ? '&includeFriendDb=1' : '';
let url = me.urlGetDbCorpusListJson + '?' + 'target=USER' + friendDb + '&requester=' + me.requester;
url += (SessionKey) ? ("&" + SessionKey) : ""; // 2021-02-06
//let data = "friendAccessibleDb=" + JSON.stringify(friendAccessibleDb);
let data = "";
$.ajax({
method: 'POST',
url: url,
data: data
}).done(function(data) {
if (data.code == 0) {
if (typeof succFunc === "function") succFunc(data.message);
else alert("getMyAccessibleDbCorpusList:\n" + JSON.stringify(data.message));
}
else {
console.error("Server Error");
if (typeof failFunc === "function"){
failFunc(data);
}
else if(typeof me.Error === "function"){
me.Error("Server Error");
}
else {
alert("deleteUserFriendAccessibleDb: " + data.message);
}
}
}).fail(function(jqXHR, textStatus, errorThrown) {
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.deleteUserFriendAccessibleDb(param, succFunc, failFunc);
}
setTimeout(retry,3000);
}
else{
alert("Please check your Internet connection and refresh this page.");
}
}
}
});
}
// --------------------------------------------------------------------------------------
me.getDbCorpusDocuments = function(target, db, corpus, evt, succFunc, failFunc) {
var param = { 'target': target,
'ownerUsername': me.ownerUsername, // 2019-04-21: this can get trouble...
'db': db,
'corpus': corpus,
'query': '.all',
'page': 1,
'pageSize': me.pageSize,
'requester': me.requester,
};
me.getQueryResultDocuments(param, evt, succFunc, failFunc);
};
// 2016-08-19: pykenny adds "message" to the parameter list
// 2016-08-30(pykenny): fix problem when argument 'message' is not given
// note: me function does not support "callback parameters" (for backward compatibility)
me.getDbCorpusDocumentsGivenPageAndSize = function(target, db, corpus, page, pageSize, evt, succFunc, message, failFunc) {
me.pageSize = pageSize;
var msg = "";
// reset links got by init(): urlGetDbCorpusListJson.php
$(".loadDbCorpusDocument").each(function(idx){
var href = $(this).attr('href');
href = href.replace(/page=\d+/,'page='+pageSize);
$(this).attr('href', href);
});
if (typeof message === "undefined" || !message || typeof message === "function"){
msg = "page: " + page;
} else {
msg = message.toString();
}
var param = { 'target': target,
'ownerUsername': me.ownerUsername, // 2019-04-21: this can get trouble...
'db': db,
'corpus': corpus,
'query': '.all',
'page': page,
'pageSize': pageSize,
'message': msg};
if(failFunc && typeof failFunc === "function"){
me.getQueryResultDocuments(param, evt, succFunc, failFunc);
}
else{
me.getQueryResultDocuments(param, evt, succFunc);
}
};
me.hideLoadingIcon = function(bool) {
me.displayLoadingIcon = (bool === false);
};
me.hideWidget = function(setVar = false, bool = true) { // 2021-12-30: 加入 setVar,登出時雖然需隱藏 widget,但不應設定 displayWidget 為 false
// 2022-02-10: 將 setVar 改放在第一個參數(預設是 false -- 僅關閉視窗,不設定 displayWidget)