-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathWIKICOMMONSLINK.gs
48 lines (48 loc) · 1.53 KB
/
WIKICOMMONSLINK.gs
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
// @author Thomas Steiner https://github.com/tomayac/wikipedia-tools-for-google-spreadsheets
/**
* Returns the Wikimedia Commons link for a file.
*
* @param {string} fileName The Wikimedia Commons file name in the format "language:File_Name" ("en:Flag of Berlin.svg") to get the link for.
* @return {string} The link of the Wikimedia Commons file.
* @customfunction
*/
function WIKICOMMONSLINK(fileName) {
'use strict';
if (!fileName) {
return '';
}
var results = [];
try {
var language;
var title;
if (fileName.indexOf(':') !== -1) {
language = fileName.split(/:(.+)?/)[0];
title = fileName.split(/:(.+)?/)[1];
} else {
language = 'en';
title = fileName;
}
if (!title) {
return '';
}
var url = 'https://' + language + '.wikipedia.org/w/api.php' +
'?action=query' +
'&prop=imageinfo' +
'&iiprop=url' +
'&format=xml' +
'&titles=File:' + encodeURIComponent(title.replace(/\s/g, '_'));
var xml = UrlFetchApp.fetch(url, {
headers: {
'X-User-Agent': 'Wikipedia Tools for Google Spreadsheets'
}
}).getContentText();
var document = XmlService.parse(xml);
var entry = document.getRootElement().getChild('query').getChild('pages')
.getChild('page').getChild('imageinfo').getChild('ii');
var fileUrl = entry.getAttribute('url').getValue();
results[0] = fileUrl;
} catch (e) {
console.log(JSON.stringify(e));
}
return results.length > 0 ? results : '';
}