User:Terasail/TargetWikidata.js

/* 	TargetWikidata.js	Created by: Terasail // jshint esnext: false, esversion: 8 var api = new mw.Api; var runTW = false; var categoriesTW = ["Netflix title", "IMDb title", "Rotten Tomatoes"];

//Check for matching category for (let i = 0; i < categoriesTW.length; i++) { if (mw.config.get("wgCategories").includes(categoriesTW[i] + " ID not in Wikidata")) { runTW = true; } }

//Add link to Tools-Actions if (runTW && mw.config.get("wgCanonicalNamespace") != "Special") { $.when(mw.loader.using('mediawiki.util'), $.ready).then(function {		let potletIDMatches = mw.util.addPortletLink( 'p-cactions','', 'Check Item Matches', 'ca-QIDMatches', 'Replace ID values with Wikidata item targets.', 'd','' );		$(potletIDMatches).on('click', function (e) { e.preventDefault; targetWikidata; });	}); }

async function targetWikidata { let machFailed = false; var properties = { P1874: ["Netflix title", "Netflix[ _]title", "", ""], P345: ["IMDb title", "IMDb[_ -]?(title|film|movie)", "(tt)", "tt"], P1258: ["Rotten Tomatoes", "Rotten[ _-]?Tomatoes", "((m|tv|franchise|celebrity|critics)\\/)", "m/"] };	let pageData = await new Promise(function(resolve) {		api.get({ action: "parse", page: mw.config.get("wgPageName"), prop: "wikitext" }).done(function(data) { resolve(data.parse.wikitext["*"]); });	});	//FIND MATCHES IN WIKIDATA let propertyValues = Object.entries(properties); let matches = []; for (let i = 0; i < propertyValues.length; i++) { let regex = new RegExp("(?<={{" + propertyValues[i][1][1] + " *\\| *(id *= *)?)" + propertyValues[i][1][2] + "?[^=|}]*(?![^|}]*=)", "gi"); let regexMatch = pageData.match(regex); if (regexMatch != null) { for (let j = 0; j < regexMatch.length; j++) { matches.push([propertyValues[i][0], regexMatch[j]]); }		}	}	//Check through each match for (let i = 0; i < matches.length; i++) { let match = matches[i]; let prop = properties[match[0]]; let wdVal = match[1].trim; //Add a prefix if there is none provided in id		if (wdVal.search(new RegExp("^" + prop[2], "i")) == -1) { if (match[0] == "P345") {//If IMDb wdVal = prop[3] + String(match[1]).padStart(7, "0").trim;//Pad 7 0's for id			} else { wdVal = prop[3] + match[1]; }		}		wdVal = wdVal.trim; let apiQuery = encodeURIComponent('SELECT ?item WHERE { ?item wdt:' + match[0] + ' "' + wdVal + '". }'); let apiTarget = 'https://query.wikidata.org/bigdata/namespace/wdq/sparql?format=json&query=' + apiQuery; let items = await new Promise(function(resolve) {			fetch(apiTarget).then(function(response) {return response.json;}).then(function(response) { resolve(response.results.bindings); });		});		if (items.length > 0) { let qid = items[0].item.value.replace("http://www.wikidata.org/entity/", ""); if (qid != mw.config.get("wgWikibaseItemId")) { // Replace template with title parameter not matching page title let templateRegex = new RegExp("{{ *" + prop[1] + " *\\| *(id *= *)?" + prop[2] + "?" + match[1] + "\\| *(title *= *)?(?=[^=|}]*[|}])", "gi"); pageData = pageData.replaceAll(templateRegex, "{{" + prop[0] + "|qid=" + qid + "|title="); // Replace template without title parameter templateRegex = new RegExp("{{ *" + prop[1] + " *\\| *(id *= *)?" + prop[2] + "?" + match[1] + " *(?=[|}])", "gi"); pageData = pageData.replaceAll(templateRegex, "{{" + prop[0] + "|qid=" + qid); // Deal with any 3rd unnamed parameter - Join it to title templateRegex = new RegExp("(?<={{" + prop[1] + "\\|qid=" + qid + "\\| *title *=[^|}]+)\\|(?=[^=}]*}})", "gi"); pageData = pageData.replaceAll(templateRegex, "|description="); }		} else { console.warn('NO MATCH IN WIKIDATA: "' + wdVal + '"'); let link = ' ' + wdVal + ' '); machFailed = true; }	}	//POST EDIT let editSummary = "Replaced id values with Wikidata items from external link templates | Userscript"; if (!machFailed) { api.postWithEditToken({			action: 'edit',			title: mw.config.get("wgRelevantPageName"),			text: pageData,			summary: editSummary,			minor: true		}).done(function(result) {			console.log(result);			if (result.edit.result == "Success") {				window.open(mw.util.getUrl(null, {type: 'revision', diff: 'cur', oldid: 'prev'}), "_self");				//location.reload;			}		}); } else { $('#ca-QIDMatches a')[0].style = "color:red;"; } } //