Bikarhêner:Balyozxane/skrîpt/js/kopi-enwiki.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>
$(document).ready(function() {
//CSS loader
mw.loader.addStyleTag('.help { font-size: 12px }');
mw.loader.addStyleTag('.button { display: inline-block; text-align: center; margin-top: 10px; margin-bottom: 10px }');
mw.loader.addStyleTag('.etiket-box { font: 12px sans-serif; margin-left: 1rem; margin: 1px; width: 100%; padding:0px; }');
// It is important to make sure that OOUI is loaded before we can make use of it.
mw.loader.using("oojs-ui", "mediawiki.api").done(function() {
let rupelaEnInput, rupelaKuInput;
// Initialize form input variables
rupelaEnInput = new OO.ui.TextInputWidget({
id: 'rupelaEn',
placeholder: 'Rûpela en.wiki',
classes: ['etiket-box']
});
rupelaKuInput = new OO.ui.TextInputWidget({
id: 'rupelaKu',
placeholder: 'Rûpela nû ya ku.wiki',
classes: ['etiket-box']
});
fieldset = new OO.ui.FieldsetLayout({
label: 'Rûpelê Kopî Bike',
id: 'new-kopi-fieldset',
classes: ["help"],
items: [
new OO.ui.FieldLayout(rupelaEnInput, {
label: 'Rûpela en.wikt',
align: 'left',
}),
new OO.ui.FieldLayout(rupelaKuInput, {
label: 'Rûpela nû ya ku.wikt',
align: 'left',
})
]
});
// Create the submit button
const submitButton = new OO.ui.ButtonInputWidget({
label: 'Bişîne',
classes: ["button"],
flags: ['primary', 'progressive'],
});
// Create the "Bigre" button
const cancelButton = new OO.ui.ButtonInputWidget({
label: 'Bigre',
classes: ["button"],
flags: ['destructive']
});
// Add click event to the "Bigre" button
cancelButton.on('click', function() {
popUp.toggle();
rupelaEnInput.getValue() === "";
rupelaKuInput.getValue() === "";
});
// Add form fields and submit button to the form
fieldset.addItems([submitButton, cancelButton]);
// Add click event to the submit button
submitButton.on('click', function() {
console.log("Submit button clicked.");
submitForm();
popUp.toggle();
});
// Function to handle form submission
function submitForm() {
console.log("Submitting form.");
var rupelaEnVal = rupelaEnInput.getValue();
const rupelaKuVal = rupelaKuInput.getValue();
var rupelaEn = rupelaEnVal
.replace(/Şablon:/g, 'Template:')
.replace(/Modul:/g, 'Module:');
var rupelaKu = rupelaKuVal
.replace(/Template:/g, 'Şablon:')
.replace(/Module:/g, 'Modul:');
fetchContent(rupelaEn, function(content) {
if (!rupelaEn.includes("/doc") && !rupelaEn.includes(".js") && !rupelaEn.includes(".css")) {
//check if rupelaEn is a redirect
var redirectMatch = content.match(/#\s*[Rr][Ee][Dd][iI][rR][eE][cC][tT]\s*\[\[([^\]]+)\]\]/i);
if (redirectMatch) {
var redirectTarget = redirectMatch[1];
if (redirectTarget.trim() !== "") {
var redirectTitle = redirectTarget;
mw.notify(`Rûpela enwîkiyê beralî dike: ${redirectTitle}`, {
type: 'warn'
});
//rupelaEn is a redirect create with
fetchContent(redirectTitle, function(redirectContent) {
rupelaKuNu = redirectTitle
.replace(/Template:/g, 'Şablon:')
.replace(/Module:/g, 'Modul:');
destpebike(redirectTitle, rupelaKuNu, redirectContent, rupelaEn);
});
}
} else {
destpebike(rupelaEn, rupelaKu, content);
}
} else {
createPage(rupelaEn, rupelaKu, content, false);
}
});
}
function destpebike(rupelaEn, rupelaKu, content, redirect) {
checkSitelinkToKuwikiExists(rupelaEn)
.then(function(result) {
if (result !== false) {
var kuExistingTitle = result.kuExistingTitle;
var qid = result.qid;
if (kuExistingTitle !== undefined && kuExistingTitle !== null && kuExistingTitle !== false) {
if (kuExistingTitle !== rupelaKu) {
redirectPage(rupelaKu, kuExistingTitle);
}
// If redirect is true, also redirect the redirect to kuExistingTitle
if (redirect && kuExistingTitle !== redirect) {
redirectPage(redirect, kuExistingTitle);
}
} else {
// Check if qid is defined before calling createPage
if (qid !== undefined && qid !== null) {
createPage(rupelaEn, rupelaKu, content, qid);
if (redirect) {
redirectPage(redirect, rupelaKu);
}
// Check if rupelaEn starts with "Template" or "Module"
if (rupelaEn.startsWith("Template") || rupelaEn.startsWith("Module")) {
// belgekirinê çêke
const docRupelaEn = rupelaEn + "/doc";
const belgeRupelaKu = rupelaKu + "/belge";
fetchContent(docRupelaEn, function(content) {
createPage(docRupelaEn, belgeRupelaKu, content, false);
});
}
}
}
} else {
createPage(rupelaEn, rupelaKu, content, false);
}
})
.catch(function(error) {
createPage(rupelaEn, rupelaKu, content, false);
// Handle the error or propagate it further if needed
});
}
function redirectPage(rupelaEn, rupelaKu) {
// Construct the content string
var content = "#BERALÎKIRIN [[" + rupelaKu + "]]";
var summary = "Ji bo [[" + rupelaKu + "]] hat beralîkirin ([[Bikarhêner:Balyozxane/skrîpt/js/kopi-enwiki.js|kopî-enwiki.js]])";
// API request to create or edit the page
const api = new mw.Api();
api.postWithToken('csrf', {
action: 'edit',
title: rupelaEn,
text: content,
summary: summary,
createonly: true
}).then(function(response) {
// Handle the API response
console.log("API Response: ", response);
// Display a notification based on the API response
if (response.edit && response.edit.result === 'Success') {
mw.notify(`${rupelaEn} hat beralîkirin: ${rupelaKu}`, {
type: 'success'
});
// If you want to redirect to the Kurdish Wikipedia page, you can still do that
var kuwikiURL = 'https://ku.wikipedia.org/wiki/' + encodeURIComponent(rupelaKu);
window.open(kuwikiURL, '_blank');
} else {
mw.notify(`Xeletî di beralîkirinê de çêbû: ${response}`, {
type: 'error'
});
console.error("API Error: ", response);
}
}).catch(function(error) {
// Handle API errors
mw.notify(`Xeletî di beralîkirinê de çêbû: ${error}`, {
type: 'error'
});
console.error("API Error: ", error);
});
}
function createPage(rupelaEn, rupelaKu, content, qid) {
const api = new mw.Api();
const summary = `[[:en:${rupelaEn}]] hat kopîkirin ([[Bikarhêner:Balyozxane/skrîpt/js/kopi-enwiki.js|kopî-enwiki.js]])`;
api.postWithToken('csrf', {
action: 'edit',
title: rupelaKu,
text: content,
summary: summary,
createonly: true
}).then(data => {
mw.notify(`${rupelaKu} hat çêkirin.`, {
type: 'success'
});
if (
rupelaEn !== null &&
typeof rupelaEn !== "undefined" &&
!rupelaKu.includes("/belge") &&
!rupelaKu.includes("/.css") &&
!rupelaKu.includes("/.js")
) {
// Call the function to get the QID for the specified category
if (qid) {
// Call the function to set the sitelink and return its promise
return setWikidataSitelink(rupelaKu, 'ku', qid, '[[:ku:' + rupelaKu + ']]').then(function(response) {
mw.notify(`${rupelaKu} sitelink set successfully.`, {
type: 'success'
});
// Open the created page in a new tab
const kuWiktionaryUrl = `https://ku.wikipedia.org/wiki/${encodeURIComponent(rupelaKu)}`;
window.open(kuWiktionaryUrl, '_blank');
}).catch(function(error) {
mw.notify(`Xeletî di girêdana Wîkîdaneyê de çêbû: ${error}`, {
type: 'error'
});
});
} else {
mw.notify(`QID not found for: ${rupelaEn}`, {
type: 'warn'
});
return Promise.resolve();
}
} else {
return Promise.resolve();
}
}).catch(err => {
mw.notify(`Xeletî di çêkirina rûpelê de çêbû: ${err}`, {
type: 'error'
});
});
}
function fetchContent(pageTitle, callback) {
var apiUrl = `https://en.wikipedia.org/w/api.php?action=query&titles=${encodeURIComponent(pageTitle)}&prop=revisions&rvprop=content&rvlimit=1&format=json&callback=?`;
$.getJSON(apiUrl, function(data) {
var pages = data.query.pages;
var pageId = Object.keys(pages)[0];
var content = pages[pageId].revisions[0]['*'];
callback(content); // Call the callback function with the content value
}).fail(function(error) {
mw.notify(`Error fetching content: ${error}`, {
type: 'error'
});
callback(null); // Call the callback function with null in case of an error
});
}
var APIoptions = {
ajax: {
headers: {
'Api-User-Agent': 'kopi-enwiki (w:ku:Bikarhêner:Balyozxane/skrîpt/js/kopi-enwiki.js)'
}
}
};
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;
});
});
};
// Function to check if a sitelink to kuwiki exists for rupelaEn
function checkSitelinkToKuwikiExists(rupelaEn) {
return getWikidataQID(rupelaEn, 'en').then(function(qid) {
if (qid !== null && typeof qid !== "undefined") {
return getWikidataSitelinks(qid).then(function(sitelinks) {
// Check if 'kuwiki' sitelink exists and return the full title
if (sitelinks.hasOwnProperty('kuwiki')) {
return {
kuExistingTitle: sitelinks['kuwiki'].title,
qid: qid
};
} else {
return {
kuExistingTitle: false,
qid: qid
};
}
});
} else {
throw new Error("QID not found for rupelaEn");
}
}).catch(function(error) {
mw.notify("QID not found for rupelaEn" + error.message, {
type: 'error'
});
throw error; // Propagate the error to the caller
});
}
// Function to get all sitelinks for a given QID
function getWikidataSitelinks(qid) {
return mw.loader.using('mediawiki.ForeignApi').then(function() {
return wikidataAPI.get({
action: 'wbgetentities',
ids: qid,
props: 'sitelinks',
format: 'json'
}).then(function(data) {
return data.entities[qid].sitelinks;
});
});
}
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/skrîpt/js/kopi-enwiki.js|kopi-enwiki.js]]"
});
});
};
var targetContainer = mw.config.get('skin') === 'vector-2022' ? 'p-cactions' : 'p-tb';
var node = mw.util.addPortletLink(targetContainer, '#', 'Kopî enWîkiyê', 't-kopi', 'Rûpela îngilîzî kopî bike');
// A popup widget is instantiated
var popUp = new OO.ui.PopupWidget({
align: "forwards",
$floatableContainer: $(node),
$content: fieldset.$element,
padded: true,
popup: false,
width: 400,
height: 250,
head: true,
// hideWhenOutOfView: false,
// autoClose: false,
hideCloseButton: true,
});
$(node).on('click', function(e) {
console.log("Link clicked.");
popUp.toggle();
e.preventDefault();
});
$(document.body).append(popUp.$element);
});
});
// </nowiki>