میدیاویکی:Gadget-CatMaker.js

لە ئینسایکڵۆپیدیای ئازادی ویکیپیدیاوە
تێبینی: دوای پاشەکەوتکردن، پێویستە کاشی وێبگەڕەکەت پاک بکەیتەوە تا گۆڕانکارییەکان ببینیت. بۆ گووگڵ کڕۆم، فایەرفۆکس، مایکرۆسۆفت ئێج و سافاری: پەنجە لەسەر دوگمەی ⇧ Shift ڕاگرە و کرتە لەسەر Reload بکە. بۆ وردەکاری و ڕێنمایییەکان لەسەر وێبگەڕەکانی تر، بڕوانە ئێرە.
/*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.
 * Maintainers: User:Balyozxane@kuwiki
 */
(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 || '') + " (using [[:w:ckb:Mediawiki:Gadget-CatMaker.js|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 + '» دروست نەکرا؛ ' + data.error.info);
                } else {
                    mw.notify('«' + falink + '» بەسەرکەوتوویی دروست کرا!');
                }
                return data;
            },
            function(data) {
                mw.notify('«' + falink + '» دروست نەکرا؛ ' + 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 === 'ckb';
                })[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('«' + falink + '» دروست نەکرا؛ پەڕەکە ھەر ئێستا ھەیە');
	            return Promise.resolve(); // Resolve immediately if the page already exists
	        }
	
	        return catParents(enlink).then(function(x) {
	            if (!x) {
	                mw.notify('پەڕەی «' + enlink + '» لە ویکیپیدیای ئینگلیزی نییە');
	                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;	// Local consensus required
	
	                // 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,
	                        'دروستکردنی پۆلی ھاوپلەی [[:en:' + enlink + ']] بە بەکارھێنانی [[Mediawiki:Gadget-CatMaker.js|پۆلساز]]'
	                    ).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, 'ckb', qid, 'Adding sitelink [[:ckb:' + falink + ']]').then(function(response) {
	                                        mw.notify('بەستەری «' + falink + '» بەسەرکەوتوویی لەگەڵ ویکیدراوە گرێ درا!', response);

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

    // Update the button click event to handle the array of promises
    $(mw.util.addPortletLink('p-tb', '#', 'پۆلساز', 't-catmaker', 'بە خۆگەڕانە پۆلەکان بەپێی ویکیپیدیای ئینگلیزی دروست بکە و گرێیان بدە')).click(init);

    function init(e) {
        e.preventDefault();
        $('<div>' +
            '<div style="width: 40em">پێویست ناکات لە سەرەتادا پۆل: یان Category: بنووسرێت. تەنیا ناوی پۆلەکە بەسە.<br>پێویستە ھەر پۆلێک لەسەر ھێڵێکی نوێ بێت. نموونە:<br>پۆل١@Category1<br>پۆل٢@Category2<br>پۆل٣@Category3</div>' +
            '<textarea style="width: 100%; background-color: white;" placeholder="پۆل:١@Cateogry:1" id="catmakerinput" rows="7"></textarea>' +
            '</div>'
        ).dialog({
            modal: true,
            width: 700,
            buttons: [{
                id: 'catmaker-button-import',
                text: 'پۆلەکان دروست بکە',
                click: function() {
                    var formInput = $('#catmakerinput').val();
                    if (formInput === '') {
                        mw.notify('ھەڵەیەک لە فۆڕمەکەدا ھەیە');
                        return;
                    }
					function createCategoriesWithDelay(categories, index) {
					    if (index < categories.length) {
					        var req = categories[index].split('@');
					        if (req.length === 2) {
							    // Check if "پۆل:" exists in req[1], and remove it if present
							    req[0] = req[0].replace('پۆل:', '');
							    // Check if "Category:" exists in req[1], and remove it if present
							    req[1] = req[1].replace(/[Cc]ategory:/g, '');
							    // Add "پۆل", and "Category" agaîn so we don't get people confused.
					            return startCat('پۆل:' + req[0], 'Category:' + req[1])
					                .then(function() {
					                    // Create a promise for the next category with a 2-second delay
					                    return new Promise(function(resolve) {
					                        setTimeout(function() {
					                            resolve(createCategoriesWithDelay(categories, index + 1));
					                        }, 2000);
					                    });
					                });
					        } else {
					            // Skip invalid input and proceed to the next one
					            return createCategoriesWithDelay(categories, index + 1);
					        }
					    } else {
					        // All categories are processed, return a resolved promise
					        return Promise.resolve();
					    }
					}
					
					var categoriesToCreate = formInput.split('\n');
					createCategoriesWithDelay(categoriesToCreate, 0)
					    .then(function() {
					        // After setWikidataSitelink is done for all categories, notify
					        mw.notify('تەواو! دەتوانن ئێستا پەڕەی وتووێژەکانیان بەکاربێنن.');
					        window.location = '/wiki/Special:Contributions/' + mw.config.get('wgUserName');
					    });
                }
            }]
        });
    }


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