Bikarhêner:Balyozxane/skrîpt/js/CatMaker.js

Ji Wîkîpediya, ensîklopediya azad.

Zanibe: Piştî weşandinê, ji bo dîtina guhartinan dibe ku hewce be "cache"ya geroka xwe paqij bikî.

  • Firefox / Safari: Pê li Shift û Reload bike an jî Ctrl-F5 an Ctrl-R bike (ji bo Mac: ⌘-R)
  • Google Chrome: Pê li Ctrl-Shift-R (ji bo Mac: ⌘-Shift-R) bike
  • Internet Explorer / Edge: Pê li Ctrl û Refresh bike, an jî Ctrl-F5 bike
  • Opera: Pê li Ctrl-F5 bike.
/*jslint browser: true, indent: 2*/
/*global mediaWiki, jQuery*/
/*!
 * @author User:Ebraminio, User:Yamaha5
 * originally imported from ckb.wiki, forked by Balyozxane to connect pages to wikidata instead of adding sitelinks.
 */
(function($, mw) {
    'use strict';
    //mw.notify('version '+'3');
    var APIoptions = {
        ajax: {
            headers: {
                'Api-User-Agent': 'Short description editer/viewer gadget (w:en:Wikipedia:Shortdesc helper)'
            }
        }
    };
    var API = new mw.Api(APIoptions);
    var wikidataAPI = new mw.ForeignApi('https://www.wikidata.org/w/api.php', APIoptions);
    var getWikidataQID = function(pageTitle, sourceLanguage) {
        return mw.loader.using('mediawiki.ForeignApi').then(function() {
            return wikidataAPI.get({
                action: 'wbgetentities',
                titles: pageTitle,
                sites: sourceLanguage + 'wiki',
                props: 'info',
                format: 'json'
            }).then(function(data) {
                // Extract the QID from the response
                var entities = data.entities;
                var qid = null;
                for (var entityId in entities) {
                    if (entities.hasOwnProperty(entityId)) {
                        qid = entityId;
                        break;
                    }
                }
                return qid;
            });
        });
    };

    var setWikidataSitelink = function(pageTitle, siteLanguage, wikidataID, summary) {
        return mw.loader.using('mediawiki.ForeignApi').then(function() {
            return wikidataAPI.postWithToken('csrf', {
                action: 'wbsetsitelink',
                id: wikidataID, // The Wikidata ID of the entity
                linksite: siteLanguage + 'wiki', // The target site (Wikipedia in this case)
                linktitle: pageTitle, // The title of the page on the target site
                summary: (summary || '') + " ([[:w:ku:Bikarhêner:Balyozxane/Gadget-CatMaker.js|Gadget-CatMaker]]"
            });
        });
    };

    function createPage(falink, text, summary) {
        return new mw.Api().post({
            action: 'edit',
            title: falink,
            text: text,
            summary: summary,
            createonly: '',
            minor: '',
            token: mw.user.tokens.get('csrfToken')
        }).then(
            function(data) {
                if (data.error && data.error.info) {
                    mw.notify(falink + ' çênebû: ' + data.error.info);
                } else {
                    mw.notify('Page edited successfully: ' + falink);
                }
                return data;
            },
            function(data) {
                mw.notify(falink + ' çênebû: ' + data);
                return data;
            }
        );
    }



    function faWikiName(title) {
        return $.ajax({
            url: '//en.wikipedia.org/w/api.php',
            data: {
                action: 'query',
                prop: 'langlinks',
                titles: title,
                redirects: 1,
                format: 'json',
                lllimit: 500
            },
            dataType: 'jsonp'
        }).then(function(data) {
            try {
                return $.grep($.map(data.query.pages, function(x) {
                    return x;
                })[0].langlinks, function(x) {
                    return x.lang === 'ku';
                })[0]['*'];
            } catch (ignore) {}
        });
    }

    function catParents(title) {
        return $.ajax({
            url: '//en.wikipedia.org/w/api.php',
            data: {
                action: 'query',
                prop: 'categories',
                titles: title,
                clshow: '!hidden',
                cllimit: 500,
                format: 'json'
            },
            dataType: 'jsonp'
        }).then(function(data) {
            try {
                return $.map($.map(data.query.pages, function(x) {
                    return x;
                })[0].categories, function(x) {
                    return x.title;
                });
            } catch (ignore) {}
        });
    }

    function getWikidataEntity(entitle) {
        return new mw.Api({
            ajax: {
                url: '//www.wikidata.org/w/api.php'
            }
        }).get({
            action: 'wbgetentities',
            format: 'json',
            sites: 'enwiki',
            titles: entitle,
            normalize: 'true',
            origin: window.location.protocol + '//' + window.location.hostname
        }).then(function(x) {
            return $.map(x.entities, function(x) {
                return x;
            })[0];
        });
    }

    function commonsCatFromEntity(entity) {
        try {
            return entity.claims.P373[0].mainsnak.datavalue.value;
        } catch (ignore) {}
    }
    
	function startCat(falink, enlink) {
	    enlink = enlink.replace(/\_/g, ' ');
	
	    return faWikiName(enlink).then(function(x) {
	        if (x) {
	            mw.notify('Çênebû: rûpel berê jixwe hebû');
	            return Promise.resolve(); // Resolve immediately if the page already exists
	        }
	
	        return catParents(enlink).then(function(x) {
	            if (!x) {
	                mw.notify('rûpela "' + enlink + '"di en.wîkiyê de tine');
	                return Promise.resolve(); // Resolve immediately if there are no parent categories
	            }
	
	            return $.when.apply(null, $.map(x, function(y) {
	                return faWikiName(y);
	            })).then(function() {
	                var catText = $.map(arguments, function(x) {
	                    return '[[' + x + ']]';
	                }).join('\n');
	                catText = catText.replace(/\[\[undefined\]\]/g, '');
	                catText = catText.replace(/\n\n/g, '\n');
	                catText = catText.trim();
	                catText = '\{\{standard-kat}}\n' + catText;
	
	                // Return a promise that resolves after a 2-second delay
	                var delayPromise = new Promise(function(resolve) {
	                    setTimeout(resolve, 2000);
	                });
	
	                // Chain the delay promise with the createPage promise
	                return delayPromise.then(function() {
	                    // Use createPage and return its promise
	                    return createPage(
	                        falink,
	                        catText,
	                        'bi [[Bikarhêner:Balyozxane/Gadget-CatMaker.js|CatMaker]]ê wekheva [[:en:' + enlink + ']] hat çêkirin'
	                    ).then(function() {
	                        // Check if enlink is provided and not null or undefined
	                        if (enlink !== null && typeof enlink !== "undefined") {
	                            // Call the function to get the QID for the specified category
	                            return getWikidataQID(enlink, 'en').then(function(qid) {
	                                if (qid) {
	                                    console.log('QID for ' + enlink + ': ' + qid);
	                                    // Call the function to set the sitelink and return its promise
	                                    return setWikidataSitelink(falink, 'ku', qid, 'Adding sitelink [[:ku:' + falink + ']]').then(function(response) {
	                                        mw.notify('Sitelink set successfully: ' + falink, response);

	                                    }).catch(function(error) {
	                                        mw.notify('Error setting sitelink:', error);
	                                    });
	                                } else {
	                                    mw.notify('QID not found for ' + enlink);
	                                    return Promise.resolve();
	                                }
	                            });
	                        } else {
	                            return Promise.resolve();
	                        }
	                    }).catch(function(error) {
	                        mw.notify('Error creating category:', error);
	                    });
	                });
	            });
	        });
	    });
	}

    // Update the button click event to handle the array of promises
    $(mw.util.addPortletLink('p-tb', '#', 'Cat-creator', 't-catmaker', 'automatically create cats')).click(init);

	function init(e) {
	    // Create a modal dialog
	    var modal = $('<div>', {
	        title: 'Cat Maker',
	        id: 'category-modal'
	    });
	
	    // Add a message to the modal
	    var message = $('<div>', {
	        style: 'width: 40em',
	        html: 'Ne hewce ye di destpêkê de Kategorî: û Category: binivîsin.<br>Tenê navê kategoriyê bes e. Divê di navbera kategoriyên cuda de rêzek hebe.<br> Nimûne:<br>Kategorî1@Category1<br>Kategorî2@Category2<br>Kategorî3@Category3'
	    });
	
	    // Create a textarea for category input
	    var categoryInput = $('<textarea>', {
	        style: 'width: 100%; box-sizing: border-box;',
	        placeholder: 'Navê kategoriya kurdî@Navê kategoriya îngilîzî',
	        id: 'catmakerinput',
	        rows: '7'
	    });
	
	    // Create a submit button
	    var submitButton = $('<button>', {
	        text: 'Proceed',
	        click: function () {
	            var formInput = $('#catmakerinput').val();
	            if (formInput === '') {
	                mw.notify('Error: Please enter category information.');
	                return;
	            }
	
	            var categoriesToCreate = formInput.split('\n');
	            createCategoriesWithDelay(categoriesToCreate, 0)
	                .then(function () {
	                    mw.notify('Category creation finished, you can discuss it now.');
	                    window.location = '/wiki/Special:Contributions/' + mw.config.get('wgUserName');
	                    modal.dialog('close'); // Close the modal when done
	                });
	        },
	        css: {
                    width: '100px', // Set the width
                    height: '40px', // Set the height
                    border: '1px solid #ccc', // Add a border for visibility
                    borderRadius: '5px', 
                    marginRight: '10px' 
	        }
	    });
	
	    // Append the message, textarea, and button to the modal
	    modal.append(message, categoryInput, submitButton);
	
	    // Append the modal to the container (e.g., the body)
	    $(document.body).append(modal);
	
		// Initialize the modal as a jQuery UI dialog
		modal.dialog({
		    modal: true,
		    width: 'auto', // Adjusted for responsiveness
		    close: function () {
		        // Remove the modal from the DOM when closed
		        $(this).dialog('destroy').remove();
		    }
		});
	
	    function createCategoriesWithDelay(categories, index) {
	        if (index < categories.length) {
	            var req = categories[index].split('@');
	            if (req.length === 2) {
	                req[0] = req[0].replace(/[Kk]ategorî:/g, '');
	                req[1] = req[1].replace(/[Cc]ategory:/g, '');
	                return startCat('Kategorî:' + req[0], 'Category:' + req[1])
	                    .then(function () {
	                        return new Promise(function (resolve) {
	                            setTimeout(function () {
	                                resolve(createCategoriesWithDelay(categories, index + 1));
	                            }, 2000);
	                        });
	                    });
	            } else {
	                return createCategoriesWithDelay(categories, index + 1);
	            }
	        } else {
	            return Promise.resolve();
	        }
	    }
	}

    mw.loader.using(['jquery.ui'], function() {
        $(function() {
            mw.util.addCSS('#t-catmaker { font-weight: normal; }');
        });
    });
}(jQuery, mediaWiki));