-
Notifications
You must be signed in to change notification settings - Fork 6
/
Wikiapi.js
2218 lines (1991 loc) · 70 KB
/
Wikiapi.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
/**
* @name Wikiapi.js
*
* @fileoverview Main codes of module wikiapi (class Wikiapi)
*/
'use strict';
/**
* @description CeJS controller
*
* @type Function
*
* @ignore
* @inner
*
* @see https://github.com/kanasimi/CeJS
*/
let CeL;
try {
// Load CeJS library.
CeL = require('cejs');
if (typeof CeL.then === 'function' && typeof window === "object" && window.CeL) {
// assert: @Snowpack
CeL = window.CeL;
}
} catch (e) /* istanbul ignore next: Only for debugging locally */ {
// https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md
// const Wikiapi = require('./wikiapi.js');
require('./_CeL.loader.nodejs.js');
CeL = globalThis.CeL;
}
// assert: typeof CeL === 'function'
// Load modules.
// @see `wiki loader.js`:
// https://github.com/kanasimi/wikibot/blob/master/wiki%20loader.js
CeL.run(['interact.DOM', 'application.debug',
// 載入不同地區語言的功能 for wiki.work()。
'application.locale',
// 載入操作維基百科的主要功能。
'application.net.wiki',
// Optional 可選功能
'application.net.wiki.data', 'application.net.wiki.admin',
// Add color to console messages. 添加主控端報告的顏色。
'interact.console',
// for 'application.platform.nodejs': CeL.env.arg_hash, wiki_API.cache(),
// CeL.fs_mkdir(), wiki_API.read_dump()
'application.storage']);
// --------------------------------------------------------
/**
* @description syntactic sugar for CeJS MediaWiki module. CeL.net.wiki === CeL.wiki
*
* @ignore
* @inner
*/
const wiki_API = CeL.net.wiki;
/**
* key to get {@link wiki_API} operator when using {@link wiki_API}.
*
* @type Symbol
*
* @ignore
* @inner
*/
const KEY_SESSION = wiki_API.KEY_SESSION;
// Set default language. 改變預設之語言。
wiki_API.set_language('en');
/**
* @description key to get {@link wiki_API} operator inside {@link Wikiapi}.
* <code>this[KEY_wiki_session]</code> inside module code will get {@link wiki_API} operator.
*
* @type Symbol
*
* @ignore
* @inner
*/
const KEY_wiki_session = Symbol('wiki_API session');
// for debug
// Wikiapi.KEY_wiki_session = KEY_wiki_session;
/**
* @description main Wikiapi operator 操作子.
*
* @param {String|Object} [API_URL] - language code or service endpoint of MediaWiki project.<br />
* Input {Object} will be treat as options.
*
* @class
*/
function Wikiapi(API_URL) {
const wiki_session = new wiki_API(null, null, API_URL);
// this[KEY_wiki_session] = new wiki_API(null, null, API_URL);
setup_wiki_session.call(this, wiki_session);
}
// --------------------------------------------------------
/**
* @description Bind {@link wiki_API} instance to {@link Wikiapi} instance
*
* @param {wiki_API} wiki_session - wiki_API session
*
* @ignore
* @inner
*/
function setup_wiki_session(wiki_session) {
Object.defineProperty(this, KEY_wiki_session, {
value: wiki_session,
writable: true,
});
}
/**
* @alias login
* @description login into the target MediaWiki API using the provided username and password.
* For bots, see [[Special:BotPasswords]] on your wiki.
*
* @param {String} user_name - Account username.
* @param {String} password - Account's password.
* @param {String} [API_URL] - API URL of target wiki site.
*
* @returns {Promise} Promise object represents {String} login_name
*
* @example <caption><span id="example__Login to wiki site 1">Login to wiki site method 1 (recommend).</span></caption>
// <code>
const wiki = new Wikiapi;
const login_options = {
user_name: '', password: '', API_URL: 'en',
// e.g., lingualibre. @see https://github.com/kanasimi/wikibot/blob/master/wiki%20configuration.sample.js
//data_API_URL: 'https://lingualibre.org/api.php',
//SPARQL_API_URL: 'https://lingualibre.org/bigdata/namespace/wdq/sparql',
// Calling in another domain
origin: '*'
};
await wiki.login(login_options);
// </code>
*
* @example <caption><span id="example__Login to wiki site 2">Login to wiki site method 2.</span></caption>
// <code>
const wiki = new Wikiapi;
await wiki.login('user_name', 'password', 'en');
// </code>
*
* @memberof Wikiapi.prototype
*/
function Wikiapi_login(user_name, password, API_URL) {
let options;
if (!password && !API_URL && CeL.is_Object(user_name)) {
options = user_name;
} else if (CeL.is_Object(API_URL)) {
options = { ...API_URL, user_name, password };
} else {
options = { user_name, password, API_URL };
}
function Wikiapi_login_executor(resolve, reject) {
const wiki_session = wiki_API.login({
preserve_password: true,
...options,
API_URL: options.API_URL || this[KEY_wiki_session].API_URL,
callback(login_name, error) {
if (error) {
reject(error);
} else {
resolve(login_name);
}
},
// task_configuration_page: 'page title',
});
setup_wiki_session.call(this, wiki_session);
}
return new Promise(Wikiapi_login_executor.bind(this));
}
// --------------------------------------------------------
/**
* @description attributes of {Object} page_data, will setup by {@link set_page_data_attributes}.
*
* @type Object
*
* @ignore
* @inner
*/
const page_data_attributes = {
/**
* @description get {String}page content, maybe undefined.
* 條目/頁面內容 = wiki_API.revision_content(revision)
*
* @type String
*/
wikitext: {
get() {
// console.trace(this);
// console.log(wiki_API.content_of(this, 0));
return wiki_API.content_of(this, 0);
}
},
/**
* @description get {Object}revisions
*
* @type Object
*/
revision: {
value: function revision(revision_NO) {
return wiki_API.content_of(this, revision_NO);
}
},
/**
* @description get {Attay} parsed data of page_data
*
* @type Array
*/
parse: {
value: function parse(options) {
// this === page_data
// options = { ...options, [KEY_SESSION]: this[KEY_wiki_session] };
options = Wikiapi.prototype.append_session_to_options.call(this, options);
// using function parse_page(options) @ wiki_API
return wiki_API.parser(this, options).parse();
// return {Array}parsed
}
},
};
/**
* @description Bind {@link page_data_attributes} to <code>page_data</code>
*
* @param {Object} page_data - page data
* @param {wiki_API} wiki - wiki_API session
*
* @returns {Promise} Promise object represents {Object} page's data
*
* @ignore
* @inner
*/
function set_page_data_attributes(page_data, wiki) {
// `page_data` maybe non-object when error occurres.
if (page_data) {
page_data[KEY_wiki_session] = wiki;
Object.defineProperties(page_data, page_data_attributes);
}
return page_data;
}
/**
* @alias page
* @description Given a title, returns the page's data.
*
* @param {String} title - page title
* @param {Object} [options] - options to run this function
*
* @returns {Promise} Promise object represents {Object} page's data
*
* @example <caption>load page</caption>
// <code>
// on Wikipedia...
const wiki = new Wikiapi('en');
// ...or other MediaWiki websites
//const wiki = new Wikiapi('https://awoiaf.westeros.org/api.php');
let page_data = await wiki.page('Universe', {
// You may also set rvprop.
//rvprop: 'ids|content|timestamp|user',
});
console.log(page_data.wikitext);
// </code>
*
* @example <caption>Get multi revisions</caption>
// <code>
const wiki = new Wikiapi;
let page_data = await wiki.page('Universe', {
// Get multi revisions
revisions: 2
});
console.log(page_data.wikitext);
// </code>
*
* @example <caption>parse wiki page (The parser is more powerful than the example. Please refer to link of wikitext parser examples showing in "Features" section of README.md.)</caption>
// <code>
// Usage with other language
const zhwiki = new Wikiapi('zh');
await zhwiki.login('user', 'password');
let page_data = await zhwiki.page('Universe');
// `page_data.parse(options)` will startup the parser process, create page_data.parsed. After .parse(), we can use parsed.each().
const parsed = page_data.parse();
// See all type in wiki_toString @ https://github.com/kanasimi/CeJS/tree/master/application/net/wiki/parser/wikitext.js
// List all template name.
parsed.each('template', token => console.log(token.name));
// List all [[Template:Tl]] token.
parsed.each('Template:Tl', token => console.log(token));
// </code>
*
* @example <caption>Get information from Infobox template</caption>
// <code>
const wiki = new Wikiapi('en');
const page_data = await wiki.page('JavaScript');
const parsed = page_data.parse();
let infobox;
// Read [[w:en:MOS:INFOBOX|Infobox templates]], convert to JSON.
parsed.each('template', template_token => {
if (template_token.name.startsWith('Infobox')) {
infobox = template_token.parameters;
return parsed.each.exit;
}
});
for (const [key, value] of Object.entries(infobox))
infobox[key] = value.toString();
// print json of the infobox
console.log(infobox);
// </code>
*
* @memberof Wikiapi.prototype
*/
function Wikiapi_page(title, options) {
function Wikiapi_page_executor(resolve, reject) {
const wiki = this[KEY_wiki_session];
wiki.page(title, (page_data, error) => {
if (error) {
reject(error);
} else {
resolve(set_page_data_attributes(page_data, wiki));
}
}, {
// node.js v12.22.7: Cannot use "?."
rvlimit: options && options.revisions,
...options
});
}
return new Promise(Wikiapi_page_executor.bind(this));
}
// --------------------------------------------------------
/**
* @alias tracking_revisions
* @description tracking revisions to lookup what revision had added / removed <code>to_search</code>.
*
* @param {String} title - page title
* @param {String} to_search - filter / text to search. to_search(diff, revision, old_revision): `diff` 為從舊的版本 `old_revision` 改成 `revision` 時的差異。
* @param {Object} [options] - options to run this function
*
* @returns {Promise} Promise object represents {Object} newer_revision,
* newer_revision.page: page_data
*
* @memberof Wikiapi.prototype
*/
function Wikiapi_tracking_revisions(title, to_search, options) {
function Wikiapi_tracking_revisions_executor(resolve, reject) {
const wiki = this[KEY_wiki_session];
wiki.tracking_revisions(title, to_search, (revision, page_data, error) => {
if (error) {
reject(error);
} else {
if (!revision)
revision = Object.create(null);
revision.page = page_data;
resolve(revision);
}
}, options);
}
return new Promise(Wikiapi_tracking_revisions_executor.bind(this));
}
// --------------------------------------------------------
/**
* @description Handle the result of MediaWiki API when executing edit operation.
*
* @param {Function} reject - reject function
* @param {any} error - error object / message
* @param {any} [result] - result of MediaWiki API
*
* @returns {Boolean} Return <code>true</code> if the edit operation failed.
*
* @ignore
* @inner
*/
function reject_edit_error(reject, error, result) {
// skip_edit is not error
if (!error
// e.g., set options.skip_nochange
// @see function do_batch_work_summary @ CeL.application.net.wiki.task
|| error === 'nochange' || error === 'skip'
// @see wiki_API_edit.check_data
|| Array.isArray(error) && error[0] === Wikiapi.skip_edit[0]) {
return;
}
if (Array.isArray(error) && typeof error[1] === 'string') {
// console.log('' + reject);
// console.trace(error);
error = error[1];
const error_object = new Error(error);
error_object.from_string = error;
error = error_object
// console.log(error);
}
if (result && error && typeof error === 'object')
error.result = result;
reject(error);
return true;
}
/**
* @alias edit_page
* @description edits content of target page.<br />
* Note: for multiple pages, you should use {@link Wikiapi#for_each_page}.<br />
* Note: The function will check sections of [[User talk:user name/Stop]] if somebody tells us needed to stop edit. See <a href="https://en.wikipedia.org/wiki/User:Cewbot/Stop">mechanism to stop operations</a>.
*
* @param {String} title - page title
* @param {String|Function} content - 'wikitext page content' || page_data => 'wikitext'
* @param {Object} [options] - options to run this function. e.g., { summary: '', bot: 1, nocreate: 1, minor: 1 }
*
* @returns {Promise} Promise object represents {Object} result of MediaWiki API
*
* @example <caption>edit page: method 1: basic operation</caption>
// <code>
const enwiki = new Wikiapi;
await enwiki.login('bot name', 'password', 'en');
const SB_page_data = await enwiki.page('Wikipedia:Sandbox');
// You may do some operations on SB_page_data
const parsed = SB_page_data.parse();
parsed.each('template', template_token => {
// modify template token
});
// and then edit it. ** You MUST call enwiki.page() before enwiki.edit()! **
await enwiki.edit(parsed.toString(), { bot: 1, minor: 1, nocreate: 1 });
// exmaple 2: append text in the tail of page content
await enwiki.edit(page_data => {
return page_data.wikitext
+ '\nTest edit using {{GitHub|kanasimi/wikiapi}}.';
}, { bot: 1 });
// exmaple 3: replace page content
await enwiki.edit('Just replace by this wikitext', { bot: 1, minor: 1, nocreate: 1, summary: 'test edit' });
// exmaple 4: append a new section
await enwiki.edit('section content', {
section: 'new',
sectiontitle: 'section title',
nocreate : 1,
summary: 'test edit',
});
// </code>
*
* @example <caption>edit page: method 2: modify summary inside function</caption>
// <code>
const enwiki = new Wikiapi;
await enwiki.login('bot name', 'password', 'en');
await enwiki.edit_page('Wikipedia:Sandbox', function (page_data) {
this.summary += ': You may set additional summary inside the function';
delete this.minor;
return page_data.wikitext
+ '\nTest edit using {{GitHub|kanasimi/wikiapi}}.';
}, { bot: 1, nocreate: 1, minor: 1, redirects: 1, summary: 'test edit' });
// </code>
*
* @memberof Wikiapi.prototype
*/
function Wikiapi_edit_page(title, content, options) {
function Wikiapi_edit_page_executor(resolve, reject) {
const wiki = this[KEY_wiki_session];
// console.trace([title, content]);
// console.trace(`Wikiapi_edit_page 1: ${wiki_API.title_link_of(title)}, ${wiki.actions.length} actions, ${wiki.running}/${wiki.thread_count}/${wiki.actions[wiki_API.KEY_waiting_callback_result_relying_on_this]}.`);
// console.trace(title);
// CeL.set_debug(6);
if (title) {
// console.trace(wiki);
options = { ...options, error_with_symbol: true };
if (false && options.page_to_edit && wiki_API.title_of(options.page_to_edit) !== wiki_API.title_of(title)) {
console.trace('delete options.page_to_edit!');
delete options.page_to_edit;
}
// 預防 page 本身是非法的頁面標題。當 session.page() 出錯時,將導致沒有 .last_page。
if (wiki_API.content_of.had_fetch_content(title)) {
options.page_to_edit = title;
} else {
options.page_title_to_edit = title;
options.page_to_edit = wiki_API.VALUE_set_page_to_edit;
// 設定個僅 debug 用、無功能的註記。
//options[Symbol('page title to edit')] = title;
}
// call wiki_API_prototype_method() @ CeL.application.net.wiki.list
wiki.page(title, (page_data, error) => {
// console.trace(`Set .page_to_edit: ${wiki_API.title_link_of(page_data)} (${title}) (${wiki_API.title_link_of(options.page_to_edit)})`);
// console.trace(options);
// console.log([page_data, error]);
// console.log(wiki.actions[0]);
// if (!page_data) console.trace(page_data);
// 手動指定要編輯的頁面。避免多執行續打亂 wiki.last_page。
// Will set at wiki_API.prototype.next
//options.page_to_edit = page_data;
}, options);
}
// console.trace(`Wikiapi_edit_page 2: ${wiki_API.title_link_of(title)}, ${wiki.actions.length} actions, ${wiki.running}/${wiki.thread_count}/${wiki.actions[wiki_API.KEY_waiting_callback_result_relying_on_this]}.`);
// console.trace(wiki);
// console.trace(wiki.last_page);
// wiki.edit(page contents, options, callback)
wiki.edit(typeof content === 'function' ? function (page_data) {
// console.trace(`Get page_data of ${wiki_API.title_link_of(page_data)} (${title})`);
return content.call(this, set_page_data_attributes(page_data, wiki));
} : content, options, (title, error, result) => {
// console.trace(`Wikiapi_edit_page: callbacked: ${wiki_API.title_link_of(title)} (${wiki.running})`);
// CeL.set_debug(6);
if (!reject_edit_error(reject, error, result)) {
// console.log('Wikiapi_edit_page: resolve');
resolve(title);
}
// console.log('Wikiapi_edit_page: callback() return');
});
// console.trace(`Wikiapi_edit_page 3: ${wiki_API.title_link_of(title)}, ${wiki.actions.length} actions, ${wiki.running}/${wiki.thread_count}/${wiki.actions[wiki_API.KEY_waiting_callback_result_relying_on_this]}.`);
}
return new Promise(Wikiapi_edit_page_executor.bind(this));
}
// <code>return Wikiapi.skip_edit;</code> as a symbol to skip this edit, do not generate
// warning message.
// 可以利用 ((return [ wiki_API.edit.cancel, 'reason' ];)) 來回傳 reason。
// ((return [ wiki_API.edit.cancel, 'skip' ];)) 來跳過 (skip) 本次編輯動作,不特別顯示或處理。
// 被 skip/pass 的話,連警告都不顯現,當作正常狀況。
/**
* @description Return <code>Wikiapi.skip_edit</code> when we running edit function, but do not want to edit current page.
*
* @memberof Wikiapi
*/
Wikiapi.skip_edit = [wiki_API.edit.cancel, 'skip'];
// --------------------------------------------------------
/**
* @alias move_page
* @description Move page <code>move_from_title</code> to <code>move_to_title</code>.
*
* @param {Object|String} move_from_title - move from title
* @param {Object|String} move_to_title - move to title
* @param {Object} [options] - options to run this function
*
* @returns {Promise} Promise object represents {String} result of MediaWiki API
*
* @example <caption>Move <code>move_from_title</code> to <code>move_to_title</code>.</caption>
// <code>
await wiki.move_page(move_from_title, move_to_title, { reason, noredirect: true, movetalk: true });
// </code>
*
* @memberof Wikiapi.prototype
*/
function Wikiapi_move_page(move_from_title, move_to_title, options) {
function Wikiapi_move_page_executor(resolve, reject) {
const wiki = this[KEY_wiki_session];
// using wiki_API.prototype.move_page()
wiki.move_page(move_from_title, move_to_title, options, (data, error) => {
if (error) {
/**
* <code>
e.g., { code: 'articleexists', info: 'A page of that name already exists, or the name you have chosen is not valid. Please choose another name.', '*': '...' }
e.g., { code: 'missingtitle', info: "The page you specified doesn't exist.", '*': '...' }
</code>
*/
reject(error);
} else {
/**
* <code>
e.g., { from: 'from', to: 'to', reason: 'move', redirectcreated: '', moveoverredirect: '' }
</code>
*/
resolve(data);
}
}, options);
}
return new Promise(Wikiapi_move_page_executor.bind(this));
}
/**
* @alias move_to
* @description Move to <code>move_to_title</code>. <em>Must call {@link Wikiapi#page} first!</em>
*
* @param {Object|String} move_to_title - move to title
* @param {Object} [options] - options to run this function
*
* @returns {Promise} Promise object represents {String} result of MediaWiki API
*
* @example <caption>Move <code>move_from_title</code> to <code>move_to_title</code>.</caption>
// <code>
page_data = await wiki.page(move_from_title);
await wiki.move_to(move_to_title, { reason: reason, noredirect: true, movetalk: true });
// </code>
*
* @memberof Wikiapi.prototype
*/
function Wikiapi_move_to(move_to_title, options) {
function Wikiapi_move_to_executor(resolve, reject) {
const wiki = this[KEY_wiki_session];
if (!wiki.last_page) {
reject(new Error(Wikiapi_move_to.name + ': Must call .page() first! '
// gettext_config:{"id":"cannot-move-to-$1"}
+ CeL.gettext('Cannot move to %1', wiki_API.title_link_of(move_to_title))));
return;
}
// using wiki_API.prototype.move_to()
wiki.move_to(move_to_title, options, (data, error) => {
if (error) {
/**
* <code>
e.g., { code: 'articleexists', info: 'A page of that name already exists, or the name you have chosen is not valid. Please choose another name.', '*': '...' }
e.g., { code: 'missingtitle', info: "The page you specified doesn't exist.", '*': '...' }
</code>
*/
reject(error);
} else {
/**
* <code>
e.g., { from: 'from', to: 'to', reason: 'move', redirectcreated: '', moveoverredirect: '' }
</code>
*/
resolve(data);
}
}, options);
}
return new Promise(Wikiapi_move_to_executor.bind(this));
}
// --------------------------------------------------------
/**
* @alias query
* @description query MediaWiki API manually
*
* @param {Object} parameters - parameters to call MediaWiki API
* @param {Object} [options] - options to run this function
*
* @returns {Promise} Promise object represents {Object} result of MediaWiki API
*
* @example <caption>query flow-parsoid-utils</caption>
// <code>
const wiki = new Wikiapi('mediawiki');
const results = await wiki.query({
action: "flow-parsoid-utils",
content: "<b>bold</b> & <i>italic</i>",
title: "MediaWiki", from: "html", to: "wikitext"
});
// </code>
*
* @memberof Wikiapi.prototype
*/
function Wikiapi_query(parameters, options) {
function Wikiapi_query_executor(resolve, reject) {
const wiki = this[KEY_wiki_session];
wiki.query_API(parameters, (data, error) => {
if (error) {
reject(error);
} else {
resolve(data);
}
}, {
post_data_only: true,
...options
});
}
return new Promise(Wikiapi_query_executor.bind(this));
}
// --------------------------------------------------------
/**
* @alias purge
* @description Purge the cache for the given title.
*
* @param {Object} title - page title
* @param {Object} [options] - options to run this function
*
* @returns {Promise} Promise object represents {Object} page_data
*
* @example <caption>query flow-parsoid-utils</caption>
// <code>
const metawiki = new Wikiapi('meta');
let page_data = await metawiki.purge('Project:Sandbox');
// </code>
*
* @memberof Wikiapi.prototype
*/
function Wikiapi_purge(title, options) {
if (CeL.is_Object(title) && !options) {
// shift arguments.
[title, options] = [null, title];
}
function Wikiapi_purge_executor(resolve, reject) {
const wiki = this[KEY_wiki_session];
if (title) {
wiki.page(title);
}
// using wiki_API.purge
wiki.purge((data, error) => {
if (error) {
reject(error);
} else {
resolve(data);
}
}, options);
}
return new Promise(Wikiapi_purge_executor.bind(this));
}
// --------------------------------------------------------
/**
* @description Bind properties to {@link wiki_API} data entity.
* 設定 wikidata entity object,讓我們能直接操作 entity.modify(),並且避免洩露 wiki_API session。
*
* @param {Object} data_entity - wiki_API data entity
*
* @ignore
* @inner
*/
function setup_data_entity(data_entity) {
if (!data_entity)
return;
// assert: data_entity[KEY_SESSION].host === this
// console.trace(data_entity[KEY_SESSION].host === this);
delete data_entity[KEY_SESSION];
Object.defineProperties(data_entity, {
[KEY_wiki_session]: { value: this },
modify: { value: modify_data_entity },
});
}
/**
* @description Modify data entity
*
* @param {Object} data_entity - wiki_API data entity
* @param {Object} [options] - options to run this function
*
* @returns {Promise} Promise object represents {Object} result data entity
*
* @ignore
* @inner
*/
function modify_data_entity(data_to_modify, options) {
function modify_data_entity_executor(resolve, reject) {
const wiki = this[KEY_wiki_session];
// console.trace(wiki);
// using function wikidata_edit() @
// https://github.com/kanasimi/CeJS/blob/master/application/net/wiki/data.js
// wiki.edit_data(id, data, options, callback)
wiki.data(this).edit_data(data_to_modify || this, options, (data_entity, error) => {
// console.trace([data_entity, error]);
if (error) {
reject(error);
} else {
setup_data_entity.call(wiki, data_entity);
resolve(data_entity);
}
});
}
return new Promise(modify_data_entity_executor.bind(this));
}
/**
* @alias data
* @description Get wikidata entity / property
*
* @param {Object} data_entity - wiki_API data entity
* @param {Object} [options] - options to run this function
*
* @returns {Promise} Promise object represents {Object} wikidata entity / property
*
* @example <caption>Get wikidata entity method 1</caption>
// <code>
const wiki = new Wikiapi;
const data_entity = await wiki.data('Q1');
// Work with other language
console.assert(CeL.wiki.data.value_of(data_entity.labels.zh) === '宇宙');
// </code>
*
* @example <caption>Get wikidata entity of [[Human]]</caption>
// <code>
const wiki = new Wikiapi;
const page_data = await wiki.page('Human');
const data_entity = await wiki.data(page_data);
console.assert(CeL.wiki.data.value_of(data_entity.labels.zh) === '人類');
// </code>
*
* @example <caption>Get wikidata entity method 2: Get P1419 of wikidata entity: 'Universe'</caption>
// <code>
const wiki = new Wikiapi;
// Read, access by title (English), access property P1419
let data = await wiki.data('Universe', 'P1419');
// assert: {Array}data = [ 'shape of the universe', '', ... ]
console.assert(data.includes('shape of the universe'));
// </code>
*
* @example <caption>update wikidata</caption>
// <code>
// Just for test
delete CeL.wiki.query.default_maxlag;
const wiki = new Wikiapi;
await wiki.login('user', 'password', 'test');
// Get https://test.wikidata.org/wiki/Q7
let entity = await wiki.data('Q7');
// search [ language, label ]
//entity = await wiki.data(['en', 'Earth']);
// Reset claim
entity = await wiki.data('Q1841');
await entity.modify({ claims: [{ P3: "old.wav", remove: true }] }, { bot: 1, summary: 'test edit: Remove specific value' });
// Warning: If you want to perform multiple operations on the same property, you need to get the entity again!
entity = await wiki.data('Q1841');
await entity.modify({ claims: [{ P3: "new.wav" }] }, { bot: 1, summary: 'test edit: Add value' });
// Update claim
await entity.modify({ claims: [{ P17: 'Q213280' }] }, { bot: 1, summary: 'test edit: Update claim' });
// Update claim: set country (P17) to 'Test Country 1' (Q213280) ([language, label] as entity)
await entity.modify({ claims: [{ language: 'en', country: [, 'Test Country 1'] }] }, { summary: '' });
// Remove country (P17) : 'Test Country 1' (Q213280)
await entity.modify({ claims: [{ language: 'en', country: [, 'Test Country 1'], remove: true }] }, { summary: '' });
// Update label
await entity.modify({ labels: [{ language: 'zh-tw', value: '地球' }] }, { summary: '' });
// </code>
*
* @memberof Wikiapi.prototype
*/
function Wikiapi_data(key, property, options) {
if (CeL.is_Object(property) && !options) {
// shift arguments.
[property, options] = [null, property];
}
function Wikiapi_data_executor(resolve, reject) {
const wiki = this[KEY_wiki_session];
if (false && wiki_API.is_page_data(key)) {
// get entity (wikidata item) of page_data: key
// .page(key): 僅僅設定 .last_page,不會真的再獲取一次頁面內容。
wiki.page(key);
}
if (key.title && !key.site) {
// @see function wikidata_entity() @ CeL.application.net.wiki.data
// 確保引用到的是本 wiki session,不會引用到其他 site。
key = { ...key, site: this.site_name() };
}
// using wikidata_entity() → wikidata_datavalue()
wiki.data(key, property, (data_entity, error) => {
if (error) {
reject(error);
} else {
setup_data_entity.call(wiki, data_entity);
resolve(data_entity);
}
}, options);
}
return new Promise(Wikiapi_data_executor.bind(this));
}
/**
* @alias new_data_entity
* @description Create new entity or property
*
* @param {Object} data_to_modify - Initial data.
* @param {Object} [options] - options to run this function
*
* @returns {Promise} Promise object represents {Object} new entity or property.
*
* @example <caption>Create new entity</caption>
// <code>
const new_entity = await wiki.new_data_entity({ labels: { en: "Evolution in Mendelian Populations" }, P698: "17246615", P932: "1201091" }, { new: 'item' });
// </code>
*
* @memberof Wikiapi.prototype
*/
function Wikiapi_new_data_entity(data_to_modify, options) {
function Wikiapi_new_data_entity_executor(resolve, reject) {
options = { new: 'item', ...options };
const wiki = this[KEY_wiki_session];
wiki.edit_data({}, options, (data_entity, error) => {
if (error) {
reject(error);
} else if (data_to_modify) {
delete options.new;
//console.trace([data_entity, options]);
wiki.edit_data(data_entity, data_to_modify, options, (result, error) => {
if (error) {
reject(error);
} else if (false && options.retrieve_entity) {
// reget modified data
this.data(data_entity.id, options).then(resolve, reject);
} else {
//console.trace([data_entity, result]);
//data_entity.latest_result = result;
// data_entity: e.g.,
// {"type":"item","id":"Q123456","labels":{},"descriptions":{},"aliases":{},"claims":{},"sitelinks":{},"lastrevid":123456}
resolve(data_entity);
}
});
} else {
setup_data_entity.call(wiki, data_entity);
resolve(data_entity);
}
});
}
return new Promise(Wikiapi_new_data_entity_executor.bind(this));
}
// --------------------------------------------------------
/**
* @alias SPARQL
* @description Query wikidata via SPARQL
*
* @param {Object} SPARQL - SPARQL to query. Please test it on <a href="https://query.wikidata.org/">Wikidata Query Service</a> first.
* @param {Object} [options] - options to run this function
*
* @returns {Promise} Promise object represents {Array} query result of `SPARQL`.
*
* @example <caption>Get cats</caption>
// <code>
const wikidata_item_list = await wiki.SPARQL(`
SELECT ?item ?itemLabel WHERE {
?item wdt:P31 wd:Q146.
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
`);
// </code>
*
* @example <caption>Get specific DOI</caption>
// <code>
// for case-insensitive DOI
const wikidata_item_list = await wiki.search('haswbstatement:' + JSON.stringify('P356=10.1371/journal.pone.0029797'), { namespace: 0 });
//wikidata_item_list.map(item => item.title)
// for case-sensitive DOI
const wikidata_item_list = await wiki.SPARQL(`
SELECT ?doi ?item ?itemLabel WHERE {
VALUES ?doi { "10.1371/JOURNAL.PONE.0029797" }
?item wdt:P356 ?doi.
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}`, {
// options.API_URL: custom SPARQL endpoint
API_URL: ''
});
//wikidata_item_list.id_list()
// </code>
*
* @memberof Wikiapi.prototype
*/
function Wikiapi_SPARQL(SPARQL, options) {
function Wikiapi_SPARQL_executor(resolve, reject) {
wiki_API.SPARQL(SPARQL, (result, error) => {
if (error) {
reject(error);
} else {
resolve(result);
}
}, this.append_session_to_options(options));