Bikarhêner:Balyozxane/addAutoCat.js
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.
// <nowiki>
function checkPageExistence(page) {
const apiUrl = 'https://ku.wiktionary.org/w/api.php';
const params = new URLSearchParams({
action: 'query',
titles: page,
format: 'json',
origin: '*'
});
return fetch(`${apiUrl}?${params}`)
.then(response => response.json())
.then(data => {
const pages = data.query.pages;
const pageId = Object.keys(pages)[0];
return pageId !== '-1'; // If pageId is not -1, the page exists
})
.catch(error => {
mw.notify('Xeletî çêbû di kontrolkirina hebûna rûpela ' + page + 'de: ' + error, { tag: 'error' });
return false;
});
}
function fetchParentCategories(pageTitle) {
const cleanpageTitle = pageTitle.replace("Kategorî:", "");
const site = new mw.Api();
const params = {
action: 'expandtemplates',
format: 'json',
text: `{{#invoke:getParents|biwesine|${cleanpageTitle}}}`,
prop: 'wikitext'
};
return site.get(params).then(data => {
const parentCategoriesText = data.expandtemplates.wikitext;
const parentCategories = parentCategoriesText.split(',');
console.log(`Serkategoriyên Kategorî:${cleanpageTitle} ew in: ${parentCategories}`);
return parentCategories;
}).catch(error => {
mw.notify(`Xeletî çêbû di wergirtina serkategoriyên Kategorî:${cleanpageTitle} de: ${error}`, { tag: 'error' });
console.log(`Xeletî çêbû di wergirtina serkategoriyên Kategorî:${cleanpageTitle} de: ${error}`);
return [];
});
}
const processedCategories = [];
const createdPages = [];
async function createParentCategoryRecursive(parentName) {
const cleanpageTitle = parentName.replace("Kategorî:", "").trim();
const categoryTitle = `Kategorî:${cleanpageTitle}`;
console.log(`Çêkirina serkategorî '${categoryTitle}' dest pê kir...`);
createdPages.push(categoryTitle);
try {
const exists = await checkPageExistence(categoryTitle);
if (exists) {
mw.notify(`Kategorî:'${categoryTitle}' jixwe heye. Loma çêkirin hat betalkirin`);
return;
}
if (processedCategories.includes(categoryTitle)) {
mw.notify(`Kategorî:'${categoryTitle}' jixwe hatiye çêkirin. Loma çêkirin hat betalkirin.`);
return;
}
processedCategories.push(categoryTitle);
let categoryContent = "{{katbike}}";
let summary = null;
const interwikiContent = await fetchInterwikiLinkContent(cleanpageTitle);
mw.notify(`Rûpela en.wiktê ji bo kategoriya ${cleanpageTitle}: ${interwikiContent.content}`);
if (interwikiContent.pageExists) {
categoryContent += `\n[[en:${interwikiContent.content}]]`;
}
if (interwikiContent.pageExists) {
summary = `Rûpel bi {{[[Şablon:katbike|katbike]]}} hat çêkirin ` +
`û înterwîkî [[en:${interwikiContent.content}]] lê hat zêdekirin`;
} else {
summary = `Rûpel bi {{[[Şablon:katbike|katbike]]}} hat çêkirin ` +
`lê înterwîkî [[en:${interwikiContent.content}]] li en.wiktê tine ye`;
}
// Save the category page
await savePageContentInNewTab(categoryTitle, categoryContent, summary);
// Fetch and create parent categories recursively
const parentCategories = await fetchParentCategories(parentName);
let shouldContinue = true;
for (const parentCategory of parentCategories) {
if (parentCategory.includes("Xeletî çêbû")) {
mw.notify(`Serkategorî nehat dîtin loma çêkirin hat betalkirin.`, { tag: 'error' });
shouldContinue = false;
break;
}
const cleanParentCategory = parentCategory.replace("Kategorî:", "").trim();
if (!processedCategories.includes(`Kategorî:${cleanParentCategory}`)) {
try {
await createParentCategoryRecursive(cleanParentCategory);
} catch (error) {
mw.notify(`Xeletî çêbû di çêkirina kategoriya '${cleanParentCategory}' de: ${error}`, { tag: 'error' });
mw.notify(`Çêkirina kategoriya '${cleanParentCategory}' hat betalkirin.`);
continue;
}
}
}
if (!shouldContinue) {
return;
}
if (processedCategories.length === 0 && createdPages.length === 0) {
// No categories were created or processed
alert("No categories were created or processed. You can reload the page.");
} else {
mw.notify("Hemû kategorî hatin çêkirin.");
console.log("Created pages:", createdPages);
alert("Hemû kategorî hatin çêkirin.\n Ji bo dîtina hemû guhartinan rûpelê ji nû ve bar bike.");
}
} catch (error) {
mw.notify(`Xeletî çêbû di çêkirina kategoriya '${categoryTitle}' de: ${error}`);
mw.notify(`Çêkirina kategoriya '${categoryTitle}' hat betalkirin.`);
}
}
function savePageContentInNewTab(pageTitle, content, editSummary) {
const api = new mw.Api();
return api.postWithToken('csrf', {
action: 'edit',
title: pageTitle,
text: content,
summary: editSummary
}).then(result => {
if (result.edit.result === 'Success') {
mw.notify(`Rûpela '${pageTitle}' hat qeydkirin.`);
} else {
mw.notify(`Xeletî çêbû di qeydkirina rûpela '${pageTitle}' de: ${result.edit.result}`);
}
}).catch(error => {
mw.notify(`Xeletî çêbû di qeydkirina rûpela '${pageTitle}': ${error}`);
});
}
// Function to check if a page exists on the English Wiktionary
function page_exists(page, lang) {
var def = $.Deferred();
$.ajax({
url: '//' + lang +'.wiktionary.org/w/api.php?origin=' + location.protocol + '//' + location.host,
data: {
action: 'query',
titles: page,
format: 'json'
},
dataType: 'json'
}).fail(function () {
mw.notify('An error occurred while checking page existence on English Wiktionary.', { type: 'error' });
def.resolve(false);
}).then(function (data) {
// Check if the page exists on en.wiktionary.org
const pageExists = !data.query.pages.hasOwnProperty('-1');
if (!pageExists) {
mw.notify('Eynî rûpel li ser en.wiktê tine ye..', { type: 'warn' });
}
def.resolve(pageExists);
});
return def.promise();
}
function addInterwikiLinkToPage(content, pageExists) {
// Append the fetched content and the page existence status to the category page
const $textBox = $("#wpTextbox1");
let result = ""; // Initialize the result as an empty string
if (pageExists) {
result = "[[en:" + content + "]]";
}
result += "";
$textBox.val($textBox.val() + result);
}
function handleFetchError(error) {
const errorMessage = "An error occurred while fetching the result.";
mw.notify(errorMessage, { type: 'error' });
addInterwikiLinkToPage(errorMessage, false);
}
function fetchInterwikiLinkContent(pageTitle) {
const api = new mw.Api();
return api.get({
"action": "expandtemplates",
"format": "json",
"text": `{{#invoke:înterwîkî-çêke|biwesine|${pageTitle}}}`,
"prop": "wikitext"
}).then(function (data) {
const interwikiLinkContent = data.expandtemplates.wikitext;
const categoryResult = "Category:" + interwikiLinkContent; // Add "Category:" to the result
// Check if the page exists on en.wiktionary.org
return page_exists(categoryResult, "en").then(function (result) {
return {
content: categoryResult,
pageExists: result
};
}).fail(function (error) {
handleFetchError(error);
return null;
});
}).fail(function (error) {
handleFetchError(error);
return null;
});
}
(function addAutoCatIIFE() {
"use strict";
if (mw.config.get("wgNamespaceNumber") !== 14)
return;
const autoCatEditSummary = typeof window.autoCatEditSummary == "undefined" ? true : window.autoCatEditSummary;
const $textBox = $("#wpTextbox1");
const $editSummaryBox = $("#wpSummary");
function fillAutoCat(autoSave) {
$textBox.val("{{katbike}}"); // Set the text area's value to {{katbike}}
const pageTitle = mw.config.get('wgTitle');
// Fetch interwiki content
fetchInterwikiLinkContent(pageTitle).then(function (result) {
if (result) {
$textBox.val($textBox.val() + "\n\n"); // Add a newline before adding interwiki link
addInterwikiLinkToPage(result.content, result.pageExists); // Append the interwiki link content
}
if (autoCatEditSummary) {
$editSummaryBox.val("Bi riya [[Bikarhêner:Balyozxane/addAutoCat.js|JavaScriptê]] şablona [[şablon:katbike|katbike]] lê zêde kir");
}
if (autoSave) {
// Save the page content in a new tab
var kategori = "Kategorî:" + pageTitle;
savePageContentInNewTab(kategori, $textBox.val(), $editSummaryBox.val());
// Fetch and create parent categories recursively
fetchParentCategories(pageTitle).then(parentCategories => {
for (const parentCategory of parentCategories) {
if (parentCategory.includes("Parents not found for")) {
mw.notify(`Serkategorî nehat dîtin loma çêkirin hat betalkirin.`);
break;
}
const cleanParentCategory = parentCategory.replace("Kategorî:", "");
try {
createParentCategoryRecursive(cleanParentCategory);
} catch (error) {
mw.notify(`Xeletî çêbû di çêkirina kategoriya '${cleanParentCategory}' de: ${error}`);
mw.notify(`Çêkirina kategoriya '${cleanParentCategory}' hat betalkirin.`);
continue;
}
}
});
} else {
// Open the current page in preview mode in a new tab
$("#wpPreview").click();
}
});
}
const action = mw.config.get("wgAction");
mw.loader.using("oojs-ui").done(() => {
if (mw.config.get("wgCurRevisionId") === 0) { // new page
$(() => {
const buttons = [];
if (action === "edit") {
const button1 = new OO.ui.ButtonWidget({
label: "katbike lê zêde bike û tomar bike",
});
const button2 = new OO.ui.ButtonWidget({
label: "yan jî pêşdîtinê bibîne",
});
button1.$element
.click(() => {
fillAutoCat(true);
})
.attr("title", "Vê kategoriyê bi şablona katbike çêke");
button2.$element
.click(() => fillAutoCat(false))
.attr("title", "Bi şablona katbike pêşdîtinê bibîne");
buttons.push(button1.$element);
buttons.push(button2.$element);
// Add the third button conditionally
if (!$textBox.val().includes("katbike")) {
const button3 = new OO.ui.ButtonWidget({
label: "Înterwîkiyê lê zêde bike",
});
button3.$element
.click(() => {
const pageTitle = mw.config.get("wgTitle");
fetchInterwikiLinkContent(pageTitle).then(function (result) {
if (result) {
addInterwikiLinkToPage(result.content, result.pageExists);
}
});
})
.attr("title", "Înterwîkiyê lê zêde bike");
buttons.push(button3.$element);
}
}
if (buttons.length > 0) {
const div = $("<div>").append(buttons);
$("#firstHeading").after(div);
}
});
} else if (action === "edit" && !$textBox.val().includes("katbike")) {
$(() => {
const button = new OO.ui.ButtonWidget({
label: "katbike li şûnê bixe",
id: "add-autocat",
});
button.$element.click(() => {
const pageTitle = mw.config.get("wgTitle");
fetchInterwikiLinkContent(pageTitle).then(function (result) {
if (result) {
$textBox.val($textBox.val() + "\n\n"); // Add a newline before adding interwiki link
mw.notify('Înterwîkî tê çêkirin!');
addInterwikiLinkToPage(result.content, result.pageExists); // Append the interwiki link content
mw.notify('Çêbû!');
} else {
$textBox.val("{{katbike}}");
}
});
});
$("#editform").prepend(button.$element);
});
} else if (action === "edit") {
$(() => {
const button = new OO.ui.ButtonWidget({
label: "Înterwîkiyê lê zêde bike",
id: "add-interwiki",
});
button.$element
.click(() => {
const pageTitle = mw.config.get("wgTitle");
fetchInterwikiLinkContent(pageTitle).then(function (result) {
if (result) {
$textBox.val($textBox.val() + "\n\n"); // Add a newline before adding interwiki link
mw.notify('Înterwîkî tê çêkirin. Li hêviyê bin!');
addInterwikiLinkToPage(result.content, result.pageExists); // Append the interwiki link content
mw.notify('Çêbû!');
}
});
})
.attr("title", "Interwiki Linkê Zêde Bike");
$("#editform").prepend(button.$element);
});
}
});
})();
//</nowiki>