Widget:FEHUpdateHelper/PagesFromLZList

(function {	"use strict";

const main = function { mw.loader.load(mw.config.get("wgScriptPath")+"/index.php?title=MediaWiki:JavaScript_libraries/apiEditPreview.js&action=raw&ctype=text/javascript","text/javascript"); const api = new mw.Api; const BRANCH = "book5" const GITHUB_AJAX_SETTINGS = {async: true, cache:false, dataType: "json"}; const RAW_PREFIX = "https://raw.githubusercontent.com/HertzDevil/feh-assets-json/" + BRANCH + "/files"; const API_PREFIX = "https://api.github.com/repos/HertzDevil/feh-assets-json/contents/files"; const STRING_DIRECTORIES = ["/Data","/Menu"]; const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); function notifyError(errorMessage) { mw.loader.using("mediawiki.notify", function {				mw.notify(errorMessage, { title: "Error" });				mw.log.error(errorMessage);			}, function(e) {				mw.log.warn(e);				mw.log.error(errorMessage);			}); }

const rootEle = document.getElementById("PageFromLZ");

const pageCreationTypes = JSON.parse(rootEle.dataset.types); /*		pageCreationTypes.push(			{				id: "GC",				module: "OccupationWorldJSONToWikiText",				module_function: "getWikitext",				handler: function(obj) {				}			},		); */

function makeLuaModulePage(lang_json,json_path_from_lang,lang_code) { let lua_source = "--Autogenerated by a script. Read the docs instead of trying to update manually!\nreturn mw.text.jsonDecode([=[";			const key_to_value = {};			for (let i = 0; i < lang_json.length; i++) {				const str_pair = lang_json[i];				key_to_value[str_pair.key] = str_pair.value;			}			lua_source += JSON.stringify(key_to_value);			lua_source += "]=])"; return api.postWithToken( "csrf", {				action: "edit",				title: "Module:FEH lang/"+lang_code+json_path_from_lang,				text: lua_source,				tags: "automated",				bot: true,				format: "json"			} ).fail(notifyError); }

const lang_in = document.createElement("input"); lang_in.type = "text"; lang_in.size = "4"; lang_in.value = "USEN"; const updateLangButton = document.createElement("button"); updateLangButton.innerHTML = "Update selected language for Module:FEH Lang";

const lzList = document.createElement("textarea"); lzList.id = "lzList"; const label_lz = document.createElement("label"); label_lz.innerHTML = "List of new lz files to make pages for"; label_lz.setAttribute("for", lzList.id); const makePagesButton = document.createElement("button"); makePagesButton.innerHTML = "Create pages"; const apiEditPreviewContainer = document.createElement("div");

rootEle.append(lang_in,updateLangButton,document.createElement("br"),label_lz,lzList,makePagesButton,apiEditPreviewContainer);

updateLangButton.addEventListener("click", function {			const selected_lang = lang_in.value;			let timeout = 0;			const deferreds_dir = [];			for (let h = 0; h < STRING_DIRECTORIES.length; h++) {				const mess_dir = STRING_DIRECTORIES[h];				deferreds_dir.push(wait(timeout).then(function {					return $.ajax(API_PREFIX+"/assets/"+selected_lang+"/Message"+mess_dir+"?ref="+BRANCH, GITHUB_AJAX_SETTINGS);				}));				timeout += 1000;			}			Promise.all(deferreds_dir).then(function(lists) { timeout = 0; const deferreds_files = []; const paths = []; const path_from_lang_regex = new RegExp("/"+selected_lang+"(.*)"); for (let h = 0; h < lists.length; h++) { const list = lists[h]; for (let i = 0; i < list.length; i++) { const path_from_lang = path_from_lang_regex.exec(list[i].path)[1]; paths.push(path_from_lang); deferreds_files.push(wait(timeout).then(function { return $.ajax( RAW_PREFIX+"/assets/"+selected_lang+path_from_lang, GITHUB_AJAX_SETTINGS ).then( (lang_json_part) => {								makeLuaModulePage(lang_json_part,path_from_lang,selected_lang).fail(notifyError);							} ).catch(notifyError); }));						timeout += 1000; }				}				Promise.all(deferreds_files).finally(function{					const lua_source = `--Autogenerated by a script. Read the docs instead of trying to update manually! local PATHS = {${paths.map(x => { return '"'+x+'"'; }).join(",")}} local base = "Module:FEH lang/${selected_lang}" local data = {} for i=1,#PATHS do	for k,v in pairs(mw.loadData(base..PATHS[i])) do		data[k] = v	end end return data`;					return api.postWithToken( "csrf", { action: "edit", title: "Module:FEH lang/"+selected_lang+"/data", text: lua_source, tags: "automated", bot: true, format: "json" } );				});			});		});		function pathInfoMatches(pathInfo, str) { const s = str.split("/"); if (s[0] === "") { s.splice(0,1); }			if (s[s.length-1] === "") { s.pop; }			for (let i = 0; i < s.length; i++) { if (s[i] !== pathInfo[i]) { return false }			}			return true; }		function expandModule(moduleName, moduleFunction, moduleArgs) { let wikitext = "{{#invoke:"+moduleName+"|"+moduleFunction; Object.entries(moduleArgs).forEach(function(e) {				const paramName = e[0];				const paramArg = typeof e[1] === "string" ? e[1] : JSON.stringify(e[1]);				const wikitextEscapedParamArg = paramArg.replace(/\|/g, '{{!}}').replace(/}}/g, ' }} ');				wikitext += "|"+paramName+"="+wikitextEscapedParamArg;			}); wikitext += "}}"; return api.post( {				action: "expandtemplates",				text: wikitext,				prop: "wikitext",				format: "json"			} ); }

function filenameToCorrespondingRepoJSONFilename(x) { const p = x.split("/"); if (p[0] === "") { p.splice(0,1); }			for (let i = 0; i < p.length; i++) { if (p[i] === "files") { p.splice(0,i+1); break; }			}			const d = p.join("/").split("."); if (d[d.length-1] === "lz") { d.pop; if (d[d.length-1] === "bin") { d.pop; }				d.push("json"); }			return d.join("."); }		function createPages(pagesToCreate) { for (let i = 0; i < pagesToCreate.length; i++) { const pageTitle = pagesToCreate[i][0]; const pageWikitext = pagesToCreate[i][1]; const apiParams = { action: "edit", title: pageTitle, text: pageWikitext, summary: "Bot: Create page", tags: "automated", bot: true, format: "json" };				apiEditPreview.makeApiEditPreviewElement(apiParams).done(function(ele) {$( rootEle ).append( ele.$element )}); }		}

makePagesButton.addEventListener("click", async function {			const lzFileNamesWithPath = lzList.value.split("\n").map(x => x.startsWith("/") ? x.slice(1) : x);			const ManyToSingleJSONs = new Map;			for (let i = 0; i < lzFileNamesWithPath.length; i++) {				const lzFileNameWithPath = lzFileNamesWithPath[i];				const pathInfo = lzFileNameWithPath.split("/");				const corresspondingJSONFileNameWithPath = filenameToCorrespondingRepoJSONFilename(lzFileNameWithPath);				for (let j = 0; j < pageCreationTypes.length; j++) {					const o = pageCreationTypes[j];					let matchesDir = false;					for (const dir of o.dirs || []) {						if (pathInfoMatches(pathInfo, dir)) {							matchesDir = true;						}					}					if (matchesDir) {						if (o.singleArg && o.singleJSON) {							const moduleArgs = {};							moduleArgs[o.module_arg] = await $.ajax( RAW_PREFIX+"/"+corresspondingJSONFileNameWithPath, GITHUB_AJAX_SETTINGS );							createPages(JSON.parse((await expandModule(o.module, o.module_function, moduleArgs)).expandtemplates.wikitext));						} else if (o.singleArg && !o.singleJSON) { if (!ManyToSingleJSONs.get(j)) { ManyToSingleJSONs.set(j, []); }							const a = ManyToSingleJSONs.get(j); a.push( await $.ajax( RAW_PREFIX+"/"+corresspondingJSONFileNameWithPath, GITHUB_AJAX_SETTINGS ) ); }					} else if ((!o.singleArg) && (!o.singleJSON)) { }				}			}			for (const [key, value] of ManyToSingleJSONs) { const o = pageCreationTypes[key]; const jsons = value; const final_json = jsons.filter(x => {return !!x}).reduce((master_json, x) => master_json.concat(x), []); const moduleArgs = {}; moduleArgs[o.module_arg] = final_json; createPages(JSON.parse((await expandModule(o.module, o.module_function, moduleArgs)).expandtemplates.wikitext)); };		});	};

function defer { var baseDependenciesLoaded = false; try { baseDependenciesLoaded = mw.loader.using && jQuery && document.readyState !== 'loading' ;		} catch (e) {} if (baseDependenciesLoaded) { main; } else { setTimeout(defer, 1000); }	}	defer; });