User:Polygnotus/Scripts/Surveys.js: Difference between revisions

Content deleted Content added
No edit summary
No edit summary
 
(7 intermediate revisions by the same user not shown)
Line 1:
// Wikipedia QuickSurveys Tracker for common.js
// Fetches active surveys and postsdisplays them toon your userpage
 
(function() {
Line 8:
const QUICKSURVEYS_URL = 'https://en.wikipedia.org/w/load.php?modules=ext.quicksurveys.lib&debug=true';
const MEDIAWICK_BASE_URL = 'https://en.wikipedia.org/wiki/MediaWiki:';
// Track processed pages to prevent duplicates
let processedPages = new Set();
// Function to extract survey data from the loaded module
Line 13 ⟶ 16:
try {
// Look for the surveyData.json content in the module
const jsonMatchjsonStart = moduleText.matchindexOf(/'"resources\/ext\.quicksurveys\.lib\/surveyData\.json":\s*(\[[\s\S]*?\])/');
if (!jsonMatchjsonStart === -1) {
console.log('No survey data found in module');
return [];
}
const// surveyDataFind =the JSON.parse(jsonMatch[1]);start of the array
const arrayStart = moduleText.indexOf('[', jsonStart);
if (arrayStart === -1) {
console.log('No array found in survey data');
return [];
}
// Find the matching closing bracket
let bracketCount = 0;
let arrayEnd = arrayStart;
for (let i = arrayStart; i < moduleText.length; i++) {
if (moduleText[i] === '[') bracketCount++;
if (moduleText[i] === ']') bracketCount--;
if (bracketCount === 0) {
arrayEnd = i + 1;
break;
}
}
let jsonString = moduleText.substring(arrayStart, arrayEnd);
console.log('Extracted JSON length:', jsonString.length);
console.log('JSON preview:', jsonString.substring(0, 300) + '...');
const surveyData = JSON.parse(jsonString);
console.log('Found survey data:', surveyData);
Line 66 ⟶ 92:
}
// Format link key for MediaWiki URL (capitalize only the first letter of each word)
function formatLinkKey(key) {
return key.splitcharAt('-'0).maptoUpperCase(word) =>+ key.slice(1);
word.charAt(0).toUpperCase() + word.slice(1)
).join('-');
}
// Display survey information in console/notification instead of updating userpage
// Generate wiki markup for the surveys
function generateSurveyMarkupdisplaySurveyInfo(surveys) {
if (surveys.length === 0) {
return console.log('== Wikipedia QuickSurveys ==\n\nNoNo surveys found in the QuickSurveys module at this time.\n\n');
mw.notify('No surveys found in QuickSurveys module', { type: 'info' });
return;
}
let markup = console.log('=== Wikipedia QuickSurveys ==\n\n=');
markup += console.log(`Last updated:Found ${newsurveys.length} Datesurvey(s).toUTCString(:`)}\n\n`;
let notificationText = `Found ${surveys.length} survey(s): `;
surveys.forEach(survey => {
markup += `=== ${survey.name} ===\n`;
surveys.forEach((survey, index) => {
markup += `* '''Type:''' ${survey.type}\n`;
markupconsole.log(`\n${index += `* '''Coverage:'''1}. ${(survey.coverage * 100).toFixed(1)name}%\n`);
console.log(` Type: ${survey.type}`);
console.log(` Coverage: ${(survey.coverage * 100).toFixed(1)}%`);
if (survey.links.length > 0) {
markupconsole.log(' += `* '''MediaWiki Links:'''\n`);
survey.links.forEach(link => {
markupconsole.log(` += `** [${link.url} - ${link.key}]: (${link.typeurl})\n`);
});
}
markup += '\n';
notificationText += survey.name;
if (index < surveys.length - 1) notificationText += ', ';
});
mw.notify(notificationText, { type: 'success', autoHide: false });
return markup;
console.log('\n=== End of QuickSurveys ===');
}
// Main function to fetch and process surveys (for manual checking)
// Update userpage with survey information
function updateUserpage(content) {
const username = mw.config.get('wgUserName');
if (!username) {
console.error('Not logged in - cannot update userpage');
return;
}
const pageTitle = `User:${username}`;
// Get current page content
new mw.Api().get({
action: 'query',
prop: 'revisions',
titles: pageTitle,
rvprop: 'content',
rvlimit: 1,
formatversion: 2
}).then(data => {
const pages = data.query.pages;
if (pages.length === 0) {
console.error('Could not find userpage');
return;
}
let currentContent = '';
if (pages[0].revisions && pages[0].revisions[0]) {
currentContent = pages[0].revisions[0].content;
}
// Remove existing survey section if it exists
const sectionRegex = /== Wikipedia QuickSurveys ==[\s\S]*?(?=\n== |\n----|\n\[\[Category:|\n\{\{|\n<|\n#|$)/;
let newContent = currentContent.replace(sectionRegex, '').trim();
// Add new survey section
if (newContent) {
newContent += '\n\n' + content;
} else {
newContent = content;
}
// Save the page
return new mw.Api().postWithToken('csrf', {
action: 'edit',
title: pageTitle,
text: newContent,
summary: 'Updated active QuickSurveys information via common.js script',
minor: true
});
}).then(() => {
console.log('Successfully updated userpage with survey information');
mw.notify('QuickSurveys information updated on your userpage!', { type: 'success' });
}).catch(error => {
console.error('Error updating userpage:', error);
mw.notify('Error updating userpage: ' + error.message, { type: 'error' });
});
}
// Main function to fetch and process surveys
function fetchAndProcessSurveys() {
console.log('Fetching QuickSurveys data...');
Line 168 ⟶ 141:
console.log('Extracted surveys:', surveys);
const markup = generateSurveyMarkupdisplaySurveyInfo(surveys);
console.log('Generated markup:', markup);
updateUserpage(markup);
})
.catch(error => {
console.error('Error fetching survey data:', error);
mw.notify('Error fetching QuickSurveys data: ' + error.message, { type: 'error' });
});
}
// Generate survey display when viewing userpage
function generateSurveyDisplay() {
const currentPage = mw.config.get('wgPageName');
const username = mw.config.get('wgUserName');
const pageKey = `${currentPage}-${Date.now()}`;
// Check if we've already processed this page recently (within 1 second)
const now = Date.now();
const recentProcessing = Array.from(processedPages).find(entry => {
const [page, timestamp] = entry.split('-');
return page === currentPage && (now - parseInt(timestamp)) < 1000;
});
if (recentProcessing) {
console.log('Survey display recently processed, skipping...');
return;
}
// Prevent duplicate execution by checking for existing elements
if ($('#quicksurveys-display-box').length > 0) {
console.log('Survey display already exists, skipping...');
return;
}
// Add to processed pages
processedPages.add(`${currentPage}-${now}`);
// Clean up old entries (keep only last 10)
if (processedPages.size > 10) {
const sortedEntries = Array.from(processedPages).sort();
processedPages = new Set(sortedEntries.slice(-10));
}
console.log('Generating survey display for userpage...');
fetch(QUICKSURVEYS_URL)
.then(response => response.text())
.then(moduleText => {
const surveys = extractSurveyData(moduleText);
if (surveys.length === 0) {
return;
}
// Double-check that the element doesn't exist (race condition protection)
if ($('#quicksurveys-display-box').length > 0) {
console.log('Survey display was created while fetching, skipping...');
return;
}
// Create a display box on the userpage
const $surveyBox = $('<div>')
.attr('id', 'quicksurveys-display-box')
.css({
'border': '1px solid #a2a9b1',
'background-color': '#f8f9fa',
'padding': '10px',
'margin': '10px 0',
'border-radius': '3px'
})
.html('<strong>Wikipedia QuickSurveys</strong><br>');
surveys.forEach(survey => {
$surveyBox.append(`<div style="margin: 5px 0;">
<strong>${survey.name}</strong> (${survey.type}, ${(survey.coverage * 100).toFixed(1)}% coverage)
</div>`);
if (survey.links.length > 0) {
survey.links.forEach(link => {
$surveyBox.append(`<div style="margin-left: 15px; font-size: 0.9em;">
→ <a href="${link.url}" target="_blank">${link.key}</a>
</div>`);
});
}
});
// Insert at the top of mw-content-text
const $content = $('#mw-content-text');
$content.prepend($surveyBox);
})
.catch(error => {
console.error('Error fetching survey data for display:', error);
});
}
Line 188 ⟶ 242:
if (username && currentPage === `User:${username}`) {
// OnlyUse addsetTimeout linkto ifensure itDOM doesn'tis alreadyready existand avoid race conditions
if setTimeout($('#update-quicksurveys').length === 0)> {
// AddAuto-generate asurvey smalldisplay linkon to manually updateuserpage
generateSurveyDisplay();
const $link = $('<span style="font-size: 0.8em; margin-left: 1em;">').html(
}, 100); // Small delay to ensure DOM is ready
'[<a href="#" id="update-quicksurveys">Update QuickSurveys</a>]'
);
$('#firstHeading').append($link);
$('#update-quicksurveys').on('click', function(e) {
e.preventDefault();
fetchAndProcessSurveys();
});
}
}
});
console.log('QuickSurveys tracker loaded. Use window.updateQuickSurveys() to manually updatecheck, or visit your userpage andto clicksee thesurveys updatedisplayed linkautomatically.');
})();