Jump to content

User:Opencooper/otherImages.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Opencooper (talk | contribs) at 03:52, 9 December 2018 (move id). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/* Checks if the current page has a wikidata image that isn't currently present */
/* Possible other method:
    * Use API to get HTML of interlanguage links
    * Convert to Jquery HTML
    * Use selectors to get all images, excluding .icon .noview, etc
    * Add them all to a set
    * Go through enwiki images, removing the ones inside from the set
    * Find a way to display the resulting images

Alternative method: Use API props such as `images` or `pageimages`
    w/ a `langlinks` generator

Test page: https://en.wikipedia.org/wiki/Ronald_Barnes,_3rd_Baron_Gorell
*/

function setup() {
    // If we're not reading an article, do nothing
    if (!(mw.config.get("wgAction") === "view"
          && mw.config.get("wgIsArticle")
          && mw.config.get("wgRevisionId") === mw.config.get("wgCurRevisionId")
          && mw.config.get("wgPageName") !== "Main_Page")) {
        return;
    }

    var wikidataId = mw.config.get( 'wgWikibaseItemId' );
    if (wikidataId === null) {
        return;
    }

    // API docs: https://www.wikidata.org/w/api.php?action=help&modules=wbgetclaims
    $.ajax({
        url: "https://www.wikidata.org/w/api.php",
        data: {
            action: "wbgetclaims",
            entity: wikidataId,
            property: "P18",
            languages: "en",
            format: "json",
            origin: "*"
        },
        success: parseProperty
    });
}

function parseProperty(response) {
	var filename;
    if (typeof response.claims.P18 != "undefined") {
	    filename = response.claims.P18[0].mainsnak.datavalue.value;
    } else {
    	return;
    }

    filename = filename.replace(/ /g, "_");
	searchForImage(filename);
}

function searchForImage(filename) {
	var foundMatch;
	// Relies on mediawiki.RegExp; See history for an inline implementation
	var filenameEscaped = mw.RegExp.escape(filename);
    var re = new RegExp(filenameEscaped);

    $("#bodyContent img").each(function() {
        var src = $(this).attr("src");
        // MediaWiki seems to encode anything not alphanumeric...
        src = decodeURI(src).replace(/%2C/g, ",").replace(/%26/g, "&");
        /* console.log("otherImages.js: filename: " + filename);
        console.log("otherImages.js: filename escaped: " + filenameEscaped);
        console.log("otherImages.js: src: " + src); */
        
        if (re.test(src)) {
            console.log("otherImages.js: Page already has wikidata image");
            foundMatch = true;
        }
    });

	if (!foundMatch) {
        getThumbUrl(filename);
	}
}

function getThumbUrl(filename) {
	// See: https://www.mediawiki.org/wiki/Help:Magic_words
	var thumbTemplate = "{{filepath:" + filename + "|100}}";

	// API docs: https://www.mediawiki.org/wiki/API:Expandtemplates
    $.ajax({
        url: "https://en.wikipedia.org/w/api.php",
        data: {
            action: "expandtemplates",
            text: thumbTemplate,
            prop: "wikitext",
            format: "json",
        },
        success: function(response) {
        	var thumbUrl = response.expandtemplates.wikitext;
        	displayImage(filename, thumbUrl);
        }
    });
}

function displayImage(filename, thumbUrl) {
    var commonsUrl = "//commons.wikimedia.org/wiki/File:" + filename;
    var wikiDataLogoMarkup = "<img src='/media/wikipedia/commons/thumb/f/ff/Wikidata-logo.svg/30px-Wikidata-logo.svg.png'>";
    var thumbMarkup = "<a href=" + commonsUrl + "><img id='otherImage' src='" + thumbUrl + "'>" + wikiDataLogoMarkup + "</a>";
    $("#contentSub").before(thumbMarkup);
}

$(setup);