enwiki Episode Generator

Creates QuickStatements for Wikidata items from Wikipedia episode lists

Ekde 2021/10/13. Vidu La ĝisdata versio.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         enwiki Episode Generator
// @namespace    https://greasyfork.org/users/21515
// @version      0.1.1
// @description  Creates QuickStatements for Wikidata items from Wikipedia episode lists
// @author       CennoxX
// @contact      [email protected]
// @homepage     https://twitter.com/CennoxX
// @match        https://en.wikipedia.org/wiki/List_of_*
// @match        https://en.wikipedia.org/wiki/*(season*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=wikipedia.org
// @grant        GM.xmlHttpRequest
// @grant        GM.setClipboard
// @grant        GM.registerMenuCommand
// @license      MIT
// ==/UserScript==
/* jshint esversion: 8 */
/* eslint quotes: ["warn", "double", "avoid-escape"]*/

(function() {
    "use strict";
    function getDate(episodeDate){
        return episodeDate.replace(/{{Start date\|(\d+)\|(\d+)\|(\d+)}}.*/,"$1-$2-$3").replace(/-(\d)\b/g,"-0$1");
    }
    GM.registerMenuCommand("convert episode lists for Wikidata",
                           (async()=>{
        var article = document.title.split(" – Wikipedia")[0];
        var response = await fetch(`/w/api.php?action=query&prop=revisions&titles=${encodeURIComponent(article)}&rvslots=*&rvprop=content&formatversion=2&format=json`);
        var data = await response.json();
        var articletext = Object.values(data.query.pages)[0].revisions[0].slots.main.content;
        articletext = articletext.split(/== *Special/)[0].split("identity as grandparents but eventually ")[0];
        var seriesTitle = "";
        if (article.split("List of ").length==2){
            seriesTitle = article.split("List of ")[1].split(" episodes")[0];
        }else{
            seriesTitle = article.split(" (season")[0];
        }
        response = await fetch(`/w/api.php?action=query&prop=pageprops&ppprop=wikibase_item&redirects=1&titles=${encodeURIComponent(seriesTitle)}&format=json`);
        data = await response.json();
        var seriesId = Object.values(data.query.pages)[0].pageprops.wikibase_item;
        response = await GM.xmlHttpRequest({
            method: "GET",
            url: `https://www.wikidata.org/w/api.php?action=wbgetentities&props=sitelinks|claims|labels&sitefilter=dewiki&ids=${seriesId}&format=json`,
            onload: function(response) {
                return response;
            }
        });
        var jsonObj = JSON.parse(response.responseText);
        var series = Object.values(jsonObj.entities)[0].labels.de.value;
        var seriesEn = Object.values(jsonObj.entities)[0].labels.en.value;
        var networkId = Object.values(jsonObj.entities)[0].claims.P449[0].mainsnak.datavalue.value.id;
        var originalLanguageId = Object.values(jsonObj.entities)[0].claims.P364[0].mainsnak.datavalue.value.id;
        var seasons = Object.values(jsonObj.entities)[0].claims.P527.map(i => i.mainsnak.datavalue.value.id);//.sort(i => i.qualifiers.P1545[0].datavalue.value)
        var wikilinks = [];
        var episodes = articletext.split(/== *Specials *==/)[0].split(/{{Episode list.*\n/).map(i => i.split(/\n}}\n/)[0]).slice(1).map(i => {
            wikilinks=wikilinks.concat([...i.matchAll(/\[\[(.*?)\]\]/g)].map(i => i[1].split("|")[0]));
            var skip = false;
            if (i.match("EpisodeNumber *= *(\\d+) *\n")==null){skip = true;console.log("ERROR: EpisodeNumber\n",i);}
            if (i.match("EpisodeNumber2 *= *(\\d+) *\n")==null){skip = true;console.log("ERROR: EpisodeNumber2\n",i);}
            if (i.match("Title *= *(\.+) *\n")==null){skip = true;console.log("ERROR: Title\n",i);}
            if (i.match("OriginalAirDate *= *(\.+) *\n")==null){skip = true;console.log("ERROR: OriginalAirDate\n",i);}
            if (i.match("DirectedBy *= *(\.+) *\n")==null){skip = true;console.log("ERROR: DirectedBy\n",i);}
            if (i.match("WrittenBy *= *(\.+) *\n")==null){skip = true;console.log("ERROR: WrittenBy\n",i);}
            if (skip) return;
            return {
                "NR_GES": i.match("EpisodeNumber *= *(\\d+) *\n")[1],
                "NR_ST": i.match("EpisodeNumber2 *= *(\\d+) *\n")[1],
                "OT": i.match("Title *= *(\.+) *\n")[1],
                "EA": getDate(i.match("OriginalAirDate *= *(\.+) *\n")[1]),
                "REG": [...i.match("DirectedBy *= *(\.+) *\n")[1].matchAll(new RegExp(wikilinks.join("|"),"g"))].map(i => i[0]).filter(i => i != ""),
                "DRB": [...i.match("WrittenBy *= *(\.+) *\n")[1].matchAll(new RegExp(wikilinks.join("|"),"g"))].map(i => i[0]).filter(i => i != "")
            };
        }).filter(i => i);
        var seasonId = 0;
        var episodeId = 0;
        var wikipediaLink = location.href.split("#")[0];
        var output = "";

        episodes.forEach(i => {
            if (Number(i.NR_ST)<episodeId){
                seasonId++;
            }
            i.season=seasonId;
            episodeId=i.NR_ST;
        });
        episodes.forEach(ep=>{
            ep.DRBid = [];
            ep.REGid = [];
            ep.DRB.forEach(async(drb)=>{
                response = await fetch(`/w/api.php?action=query&prop=pageprops&ppprop=wikibase_item&redirects=1&titles=${encodeURIComponent(drb)}&format=json`);
                data = await response.json();
                if (Object.values(data.query.pages)[0].pageprops != null){
                    ep.DRBid.push(Object.values(data.query.pages)[0].pageprops.wikibase_item);
                }
            });
            ep.REG.forEach(async(reg)=>{
                response = await fetch(`/w/api.php?action=query&prop=pageprops&ppprop=wikibase_item&redirects=1&titles=${encodeURIComponent(reg)}&format=json`);
                data = await response.json();
                if (Object.values(data.query.pages)[0].pageprops != null){
                    ep.REGid.push(Object.values(data.query.pages)[0].pageprops.wikibase_item);
                }
            });
        });
        var stopInterval = setInterval(()=>{
            var idNumber = 0;
            episodes.forEach(i=> {
                idNumber+=i.DRBid.length+i.REGid.length;
            });
            var number = 0;
            episodes.forEach(i=>{
                number+=i.DRB.length+i.REG.length;
            });
            if (number == 0 || idNumber==number){
                clearInterval(stopInterval);
                //write CREATE-Statements, get DRB and REG
                episodes.forEach(ep => {
                    ep.OT=ep.OT.replace(/\[\[/,"").replace(/\]\]/,"").trim();
                    if (ep.OT.includes("|")){
                        ep.OT = ep.OT.split(/\|.*/)[0];
                    }
                    output +=
                        `CREATE
LAST	Len	"${ep.OT}"
LAST	P1476	en:"${ep.OT}"
LAST	Den	"episode of ${seriesEn}"
LAST	Dde	"Folge von ${series}"
LAST	P31	Q21191270	S143	Q328	S4656	"${wikipediaLink}"
LAST	P179	${seriesId}	P1545	"${ep.NR_GES}"	S143	Q328	S4656	"${wikipediaLink}"
LAST	P4908	${seasons[ep.season]}	P1545	"${ep.NR_ST}"	S143	Q328	S4656	"${wikipediaLink}"
LAST	P449	${networkId}	S143	Q328	S4656	"${wikipediaLink}"
LAST	P364	${originalLanguageId}	S143	Q328	S4656	"${wikipediaLink}"
LAST	P577	+${ep.EA}T00:00:00Z/11	P291	Q30	S143	Q328	S4656	"${wikipediaLink}"
`;
                    ep.REGid.forEach(reg=> {
                        output += `LAST	P57	${reg}	S143	Q328	S4656	"${wikipediaLink}"
`;});
                    ep.DRBid.forEach(drb=> {
                        output += `LAST	P58	${drb}	S143	Q328	S4656	"${wikipediaLink}"
`;});
                });
                console.log(output);
                GM.setClipboard(output);
            }
        },100);
    }),"w");
})();