Bikarhêner:Balyozxane/skrîpt/js/findKuTitle.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.
// Function to extract linked items from text
function extractLinkedItems(text) {
const regex = /\[\[([^\]]+)\]\]/g;
const matches = [];
let match;
while ((match = regex.exec(text)) !== null) {
matches.push(match[1]);
}
return matches;
}
// Function to get the title from a link
function getTitleFromLink(link) {
if (link.includes('|')) {
return link.split('|')[0];
} else {
return link;
}
}
async function getKuWikipediaTitlesInBatches(enTitles) {
const maxTitlesPerBatch =50; // Adjust this value based on the maximum allowed limit
const batches = [];
// Split the titles into batches
for (let i = 0; i < enTitles.length; i += maxTitlesPerBatch) {
const batch = enTitles.slice(i, i + maxTitlesPerBatch);
batches.push(batch);
}
const kuTitlesMap = {};
// Fetch titles for each batch of English titles
for (const batch of batches) {
mw.notify("Lînk tên, bisekine...")
const kuTitlesBatch = await getKuWikipediaTitles(batch);
console.log("kuTitlesBatch", kuTitlesBatch)
Object.assign(kuTitlesMap, kuTitlesBatch);
}
return kuTitlesMap;
}
async function processText(text) {
console.log('Processing text:', text);
const linkedItems = extractLinkedItems(text);
console.log('Linked items:', linkedItems);
const enTitles = linkedItems.map(getTitleFromLink); // Extract English titles from linked items
console.log("enTitles", enTitles)
// Get Kurdish Wikipedia titles for all English titles in batches
const kuTitlesMap = await getKuWikipediaTitlesInBatches(enTitles);
console.log('Kurdish Wikipedia titles:', kuTitlesMap);
var userInput = prompt("Şablon girêdan lê zêde bike? e bo erê n bo na binivîse");
// Replace the links in the text
for (const item of linkedItems) {
const enTitle = getTitleFromLink(item);
const kuTitle = kuTitlesMap[enTitle];
console.log('Processing link:', enTitle, 'Kurdish title:', kuTitle);
// Check if Kurdish title exists and replace the link accordingly
if (kuTitle !== undefined && kuTitle !== null) {
const kuLink = `[[${kuTitle}]]`;
text = text.replace(`[[${item}]]`, kuLink); // Replace original link with Kurdish link
} else {
// If no Kurdish title found, replace the link with a template or handle it accordingly
if (userInput.toLowerCase() === 'e') {
const template = `{{girêdan|${enTitle}|en|${enTitle}}}`;
text = text.replace(`[[${item}]]`, template);
}
}
}
console.log('Text processed:', text);
mw.notify("Hemû xilas bû!");
$("#wpTextbox1").val(text); // Replace the content of the textarea with the processed text
}
async function getKuWikipediaTitles(enTitles) {
console.log('Fetching Kurdish Wikipedia titles for:', enTitles);
// Load the necessary modules
return new Promise((resolve, reject) => {
mw.loader.using(['mediawiki.ForeignApi', 'mediawiki.util']).then(() => {
console.log('ForeignApi module loaded successfully');
// Construct the URL for the Wikidata API query
const apiUrl = 'https://www.wikidata.org/w/api.php';
const params = {
action: 'wbgetentities',
titles: enTitles.join('|'),
sites: 'enwiki',
props: 'sitelinks',
sitefilter: 'enwiki|kuwiki',
format: 'json'
};
// Fetch data from Wikidata API
const foreignApi = new mw.ForeignApi(apiUrl);
foreignApi.get(params).done(data => {
console.log('API request successful:', data);
// Parse the response and store English and Kurdish titles in a map
const entities = data.entities;
const kuTitlesMap = {};
for (const entityId in entities) {
const entity = entities[entityId];
const sitelinks = entity.sitelinks;
// Get titles from both English and Kurdish sitelinks
const enTitle = sitelinks && sitelinks.enwiki ? sitelinks.enwiki.title : null;
const kuTitle = sitelinks && sitelinks.kuwiki ? sitelinks.kuwiki.title : null;
// Update kuTitlesMap with titles from both sitelinks
kuTitlesMap[enTitle] = kuTitle; // Store the Kurdish title or null if not found
}
resolve(kuTitlesMap); // Resolve with map of English titles to Kurdish titles
}).fail(error => {
console.error('Error fetching data:', error);
reject(error); // Reject with error if request fails
});
}).fail(error => {
console.error('Error loading modules:', error);
reject(error); // Reject with error if module loading fails
});
});
}
// Function to handle button click
async function handleButtonClick() {
console.log('Button clicked');
const text = $("#wpTextbox1").val(); // Get the content of the current page
console.log('Retrieved text:', text);
try {
await processText(text);
console.log('Text processed successfully');
mw.notify('Text processed successfully');
} catch (error) {
console.error('Error processing text:', error);
mw.notify('Error processing text: ' + error);
}
console.log('Button click handled');
}
// Add button to the page
var node = mw.util.addPortletLink('p-tb', '#', 'Get Ku Title', 't-gettitle', 'Get Ku Title');
$(node).on('click', handleButtonClick);