-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWapiClient.js
More file actions
699 lines (594 loc) · 19.8 KB
/
WapiClient.js
File metadata and controls
699 lines (594 loc) · 19.8 KB
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
class WapiClient {
static API_PATH = '/w/api.php';
wapiPort = null;
/**
* @param {string} baseURL Wiki istance domain (es: 'https://www.wikidata.org' o 'https://my.wikibase.site').
* @param {string} lang Default language (es: 'en', 'it').
*/
constructor(baseURL = 'https://www.wikidata.org', lang = 'en', port = null) {
this.baseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
this.lang = lang;
this.apiURL = this.baseURL + WapiClient.API_PATH;
if (this.baseURL.includes("wikidata.org") || this.baseURL.includes("query.wikidata.org")) {
this.sparqlEndpoint = 'https://query.wikidata.org/sparql';
} else {
this.sparqlEndpoint = `${this.baseURL}/query/sparql`;
}
this.token = null;
this.wapiPort = port;
this.isPopup = this.isPopup = this.#detectChromeExtensionContext();;
}
#detectChromeExtensionContext() {
try {
if (typeof chrome === 'undefined') return false;
if (!chrome.runtime) return false;
if (!chrome.runtime.id) return false;
if (window.location.protocol !== 'chrome-extension:') return false;
return true;
} catch (error) {
console.warn("Errore nel rilevamento contesto:", error);
return false;
}
}
/**
* @private
* Send request to WAPI browser-extension
* @returns {Promise<{json: () => Promise<Object>}>}
*/
async #wapiFetch(url, method = 'GET', headers = {}, body = null) {
if (this.isPopup) {
return this.#popupFetch(url, method, headers, body); // Browser Extension
} else {
return this.#windowFetch(url, method, headers, body); // Web page
}
};
/**
* @private
* Communication via native API (Popup, SidePanel, ecc.)
*/
async #popupFetch(url, method, headers, body) {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({
action: "proxy-api",
url: url,
method: method,
headers: headers,
body: body
}, (response) => {
if (chrome.runtime.lastError) {
return reject(new Error("Runtime error: " + chrome.runtime.lastError.message));
}
if (response && response.success) {
resolve({
ok: true,
json: () => Promise.resolve(response.data)
});
} else {
const errorMsg = response?.error || 'Unknown error from WAPI.';
reject(new Error(errorMsg));
}
});
});
}
/**
* @private
* Communication via window.postMessage (Content Script).
*/
async #windowFetch(url, method, headers, body) {
return new Promise((resolve, reject) => {
const requestId = new Date().getTime();
const responseHandler = (event) => {
if (event.origin !== window.origin || !event.data || event.data.requestId !== requestId) return;
if (event.data.action !== 'api-response') return;
window.removeEventListener('message', responseHandler);
if (event.data.success) {
resolve({ ok: true, json: () => Promise.resolve(event.data.data) });
} else {
reject(new Error(event.data.error || 'Unknown error from WAPI.'));
}
};
window.addEventListener('message', responseHandler);
window.postMessage({
action: 'request-api',
url: url,
requestId: requestId,
method: method,
headers: headers,
body: body
}, window.origin);
});
}
/**
* @private
* Generic query to API.
* @param {Object} params API URL params
* @returns {Promise<Object>} JSON Object.
*/
async #query(params) {
const defaultParams = {
format: 'json',
formatversion: 2,
...params
};
const url = new URL(this.apiURL);
Object.entries(defaultParams).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
url.searchParams.append(key, value);
}
});
try {
const response = await this.#wapiFetch(
url.toString(),
'GET',
{'Accept': 'application/json'}
)
const data = await response.json();
return data;
} catch (error) {
console.error(`Errore durante l'interazione con l'API di ${this.baseURL}:`, error);
throw error;
}
}
/**
* SPARQL Query request
* @param {string} query - Query SPARQL
* @returns {Array<Object>|[]}
*/
async #sparql(sparql_query) {
try {
const params = new URLSearchParams({ query: sparql_query });
const url = `${this.sparqlEndpoint}?${params.toString()}`;
const response = await this.#wapiFetch(
url,
'GET',
{ 'Accept': 'application/sparql-results+json' },
null
);
const data = await response.json();
return data;
} catch (error) {
console.error(`Errore SPARQL:`, error);
throw error;
}
}
/**
* POST request for edit
* @param {Object} params - API URL params
* @returns {bool}
*/
async #edit(params) {
const defaultParams = {
token: this.token,
...params
}
const url = new URL(this.apiURL);
const response = await this.#wapiFetch(
url,
'POST',
{'Content-Type': 'application/x-www-form-urlencoded'},
new URLSearchParams(defaultParams).toString()
)
return await response.json();
}
// USER INFO
/**
* Get CSRF token from browser for editing.
* @returns {Promise<string>} Token CSRF
*/
async getCsrfToken() {
const params = {
action: "query",
meta: "tokens"
};
const data = await this.#query(params);
const raw_token = data.query.tokens.csrftoken
const token = raw_token == "+\\" ? null : raw_token
if (!token) {
throw new Error("CSRF not found. Session not authenticated");
}
this.token = token;
return token
}
/**
* Get user information
* @returns {Object|null}
*/
async getUserInfo() {
const params = {
action: "query",
meta: "userinfo"
};
const data = await this.#query(params);
if (data.query?.userinfo) {
return data.query.userinfo
} else {
return null
}
}
// QUERY
/**
* Send request to WAPI browser-extension
* @returns {Promise<{json: () => Promise<Object>}>}
*/
async wapiFetch(url, method = 'GET', headers = {}, body = null) {
const data = await this.#wapiFetch(url, method, headers, body);
return data;
}
/**
* public SPARQL request method.
* @param {string} itemId - QID
* @returns {Promise<Array>} Objects array
*/
async querySparql(query) {
const json = await this.#sparql(query);
const data = json.results?.bindings || [];
return data
}
/**
* Get Item details
* @param {string} itemId - QID
* @returns {Object|null}
*/
async getItem(itemId, props = 'labels|descriptions|claims') {
const params = {
action: 'wbgetentities',
ids: itemId,
props: props,
languages: this.lang
};
const data = await this.#query(params);
return data.entities[itemId] || null;
}
/**
* Get item with formatted "property label: value label" pairs
* @param {string} itemId - QID (es: "Q42")
* @returns {Promise<Array<{property: string, propertyLabel: string, value: string, valueLabel: string}>>}
*/
async getItemDetails(itemId) {
const query = `
SELECT DISTINCT ?property ?propertyLabel ?value ?valueLabel WHERE {
wd:${itemId} ?propertyUri ?value .
BIND(IRI(REPLACE(STR(?propertyUri), "prop/direct/", "entity/")) AS ?property)
?property rdfs:label ?propertyLabel .
FILTER(LANG(?propertyLabel) = "it" || LANG(?propertyLabel) = "en")
OPTIONAL {
?value rdfs:label ?valueLabel .
FILTER(LANG(?valueLabel) = "it" || LANG(?valueLabel) = "en")
}
}
ORDER BY ?propertyLabel
LIMIT 100
`;
try {
const results = await this.querySparql(query);
results.reverse();
return results.map(row => ({
property: row.property, // P31
propertyLabel: row.propertyLabel?.value || row.property.value.split('/').pop(),
value: row.value.value,
valueLabel: row.valueLabel?.value || this.#formatValue(row.value.value),
raw: row
}));
} catch (error) {
console.error("Errore query key-value labels:", error);
return [];
}
}
/**
* @private
* Formatta valori non-labelati
*/
#formatValue(value) {
if (value.includes('http://www.wikidata.org/entity/Q')) {
return value.split('/').pop(); // Qxxx
} else if (value.includes('http://www.wikidata.org/entity/P')) {
return value.split('/').pop(); // Pxxx
} else {
// Rimuovi datatype per valori letterali
return value.replace(/^"|"(@.+)?$/g, '').replace(/\\"/g, '"');
}
}
/**
* Get specific claim value
* * @param {string} itemId - QID
* @param {string} propertyId - Property ID (es: "P27").
* @returns {Promise<Array<Object>|[]>}
*/
async getClaimValue(itemId, propertyId) {
const params = {
action: 'wbgetentities',
ids: itemId,
props: 'claims',
languages: this.lang
};
const data = await this.#query(params);
const entity = data.entities[itemId];
if (!entity || entity.missing) {
console.warn(`Claim not found: ${itemId}`);
return [];
}
const claims = entity.claims[propertyId];
if (!claims) {
return [];
}
const values = claims
.filter(claim => claim.mainsnak && claim.mainsnak.snaktype === 'value')
.map(claim => claim.mainsnak.datavalue);
return values;
}
/**
* Get sitelink (link to Wikipedia, ecc.)
* @param {string} entityId - QID
* @returns {Promise<Object|null>} Mapped obj (es: { itwiki: {...} }).
*/
async getSitelinks(entityId) {
const params = {
action: 'wbgetentities',
ids: entityId,
props: 'sitelinks'
};
const data = await this.#query(params);
const entity = data.entities[entityId];
if (!entity || entity.missing) {
return null;
}
return entity.sitelinks || null;
}
/**
* Get matches with items using label
* @param {string} label - label to search
* @param {number} limit - Results limit
* @returns {Array<{id: string, label: string, description: string, uri: string>}|[]} - Ritorna un array di oggetti
*/
async searchEntitiesByLabel(label, limit) {
const params = {
action: "wbsearchentities",
search: label,
language: this.lang,
uselang: this.lang,
type: "item",
limit: limit
};
const json = await this.#query(params);
if (json && json?.search) {
const filterList = json.search.map((ent) => ({
id: ent.id,
label: ent.label,
description: ent.description,
uri: ent.concepturi
}));
return filterList
}
return [];
}
/**
* Get matches with properties using label
* @param {string} label - Label to search
* @param {number} limit - Results limit
* @returns {Array<{id: string, label: string, description: string, uri: string>}|[]}
*/
async searchPropertiesByLabel(label, limit) {
const params = {
action: "wbsearchentities",
search: label,
language: this.lang,
uselang: this.lang,
type: "property",
limit: limit
};
const json = await this.#query(params);
if (json && json?.search) {
const filterList = json.search.map((prop) => ({
id: prop.id,
label: prop.label,
description: prop.description,
uri: prop.concepturi
}));
return filterList
} else {
return []
}
}
/**
* Get properties related to give property
* @param {string} label - Label to search
* @returns {Array<{id: string, label: string, description: string, uri: string}|[]}
*/
async getRelatedProperties(property, limit) {
const query = `
SELECT ?relatedProp ?relatedPropLabel ?relatedPropDescription
WHERE {
{
wd:${property.toUpperCase()} wdt:P1659 ?relatedProp .
} UNION {
?relatedProp wdt:P1659 wd:${property.toUpperCase()} .
}
SERVICE wikibase:label {
bd:serviceParam wikibase:language "[AUTO_LANGUAGE],it,en".
?relatedProp rdfs:label ?relatedPropLabel ;
schema:description ?relatedPropDescription .
}
}
LIMIT ${limit}
`;
const json = await this.#sparql(query);
if (json && json.results?.bindings) {
const filterList = json.results?.bindings.map((prop) => ({
id: prop.relatedProp.value.split("/").pop(),
label: prop.relatedPropLabel?.value || "",
description: prop.relatedPropDescription?.value || "",
uri: prop.relatedProp.value
}));
return filterList
} else {
return []
}
}
// EDIT
/**
* Set title, alias o description for an existing item
* @param {string} itemId - QID
* @param {string} type - 'label', 'description' or 'alias'.
* @param {string} value - New value
* @param {string} summary - Edit summary
* @returns {Promise<Object>}
*/
async setTitle(itemId, type, value, lang = this.lang, summary = "") {
if (!this.token) {
this.token = await this.getAuthToken()
}
if (!this.token) {
throw new Error("Not logged");
}
const params = {
action: 'wbsetlabel',
id: itemId,
[type]: value,
language: lang,
summary: summary
};
const response = await this.#edit(params);
return response
}
/**
* Set a claim for a specific item
* @param {string} itemId - QID
* @param {object} body - Request body (es. { claims: [] })
* @param {string} summary - Edit summary
* @returns {bool}
*/
async setClaim(itemId, propertyId, value, dataType, summary) {
if (!this.token) {
this.token = await this.getAuthToken()
}
if (!this.token) {
throw new Error("Not logged");
}
let datavalue;
switch (dataType) {
case 'wikibase-item':
case 'wikibase-property':
datavalue = {
"value": {
"entity-type": dataType.split('-')[1], // 'item' o 'property'
"id": value // Es: "Q145"
},
"type": "wikibase-entityid"
};
break;
case 'string':
case 'url':
case 'external-id':
datavalue = {
"value": value, // Es: "Douglas Adams"
"type": "string"
};
break;
case 'time':
datavalue = {
"value": {
"time": value,
"timezone": 0,
"before": 0,
"after": 0,
"precision": 11, // Day
"calendarmodel": "http://www.wikidata.org/entity/Q1985727"
},
"type": "time"
};
break;
// 'globe-coordinate', 'quantity', ...
default:
throw new Error(`Data type not supported: ${dataType}`);
}
const claimPayload = {
"property": propertyId,
"mainsnak": {
"snaktype": "value",
"property": propertyId,
"datavalue": datavalue
},
"type": "statement"
};
const params = {
action: 'wbsetclaim',
claim: JSON.stringify(claimPayload),
id: itemId,
summary: summary,
token: this.token
};
const data = await this.#edit(params)
if (data.error) {
throw new Error(`API Error (${data.error.code}): ${data.error.info}`);
}
return data;
}
/**
* Remove a claim given claim-id (es: 'Q42$20F4C8C2-4C79-450F-87D9-4E65A548F065').
* @param {string|Array<string>} claimIds - Claim IDs
* @param {string} summary - Edit summary
* @returns {Promise<Object>}
*/
async removeClaim(claimIds, summary) {
if (!this.token) {
this.token = await this.getAuthToken()
}
if (!this.token) {
throw new Error("Not logged");
}
const claims = Array.isArray(claimIds) ? claimIds.join('|') : claimIds;
const params = {
action: 'wbremoveclaims',
claim: claims,
summary: summary,
token: this.token
};
const response = await this.#edit(params);
return response;
}
/**
* Edit Item using custom body
* @param {string} itemId - QID
* @param {object} body - Request body (es. { claims: [] })
* @param {string} summary - Edit summary
* @returns {bool}
*/
async editEntity(itemId, claims, summary = null) {
if (!this.token) {
this.token = await this.getCsrfToken()
}
if (!this.token) {
throw new Error("Not logged");
}
const params = {
action: "wbeditentity",
id: itemId,
format: "json",
token: this.token,
data: JSON.stringify( {claims : claims}),
summary: summary
};
const formData = new URLSearchParams(params);
const response = await this.#wapiFetch(
this.apiURL,
'POST',
{},
formData.toString()
);
const jsonResponse = await response.json();
if (jsonResponse.success === 1) {
return true
} else {
console.log(jsonResponse)
return false
}
}
}
export { WapiClient };
if (typeof window !== 'undefined') {
window.WapiClient = WapiClient;
}
// CommonJS (Node.js)
if (typeof module !== 'undefined' && module.exports) {
module.exports = { WapiClient };
}