User:Polygnotus/Scripts/Surveys.js

This is an old revision of this page, as edited by Polygnotus (talk | contribs) at 00:15, 5 June 2025 (Created page with '// Wikipedia QuickSurveys Tracker for common.js // Fetches active surveys and posts them to your userpage (function() { 'use strict'; // Configuration 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:'; // Function to extract survey data from the loaded module function extractSurveyData(moduleText) {...'). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Wikipedia QuickSurveys Tracker for common.js
// Fetches active surveys and posts them to your userpage

(function() {
    'use strict';
    
    // Configuration
    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:';
    
    // Function to extract survey data from the loaded module
    function extractSurveyData(moduleText) {
        try {
            // Look for the surveyData.json content in the module
            const jsonMatch = moduleText.match(/"resources\/ext\.quicksurveys\.lib\/surveyData\.json":\s*(\[[\s\S]*?\])/);
            if (!jsonMatch) {
                console.log('No survey data found in module');
                return [];
            }
            
            const surveyData = JSON.parse(jsonMatch[1]);
            console.log('Found survey data:', surveyData);
            
            const activeSurveys = [];
            
            surveyData.forEach(survey => {
                if (survey.name && survey.coverage > 0) { // Only active surveys with coverage > 0
                    const surveyInfo = {
                        name: survey.name,
                        coverage: survey.coverage,
                        type: survey.type || 'unknown',
                        links: []
                    };
                    
                    // Check for direct link property
                    if (survey.link) {
                        surveyInfo.links.push({
                            type: 'main',
                            key: survey.link,
                            url: MEDIAWICK_BASE_URL + formatLinkKey(survey.link)
                        });
                    }
                    
                    // Check questions for links
                    if (survey.questions && Array.isArray(survey.questions)) {
                        survey.questions.forEach(question => {
                            if (question.link) {
                                surveyInfo.links.push({
                                    type: 'question',
                                    key: question.link,
                                    url: MEDIAWICK_BASE_URL + formatLinkKey(question.link)
                                });
                            }
                        });
                    }
                    
                    activeSurveys.push(surveyInfo);
                }
            });
            
            return activeSurveys;
        } catch (error) {
            console.error('Error parsing survey data:', error);
            return [];
        }
    }
    
    // Format link key for MediaWiki URL (capitalize first letter of each word)
    function formatLinkKey(key) {
        return key.split('-').map(word => 
            word.charAt(0).toUpperCase() + word.slice(1)
        ).join('-');
    }
    
    // Generate wiki markup for the surveys
    function generateSurveyMarkup(surveys) {
        if (surveys.length === 0) {
            return '== Active Wikipedia QuickSurveys ==\n\nNo active surveys found at this time.\n\n';
        }
        
        let markup = '== Active Wikipedia QuickSurveys ==\n\n';
        markup += `Last updated: ${new Date().toUTCString()}\n\n`;
        
        surveys.forEach(survey => {
            markup += `=== ${survey.name} ===\n`;
            markup += `* '''Type:''' ${survey.type}\n`;
            markup += `* '''Coverage:''' ${(survey.coverage * 100).toFixed(1)}%\n`;
            
            if (survey.links.length > 0) {
                markup += `* '''MediaWiki Links:'''\n`;
                survey.links.forEach(link => {
                    markup += `** [${link.url} ${link.key}] (${link.type})\n`;
                });
            }
            markup += '\n';
        });
        
        return markup;
    }
    
    // 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 = /== Active 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...');
        
        fetch(QUICKSURVEYS_URL)
            .then(response => response.text())
            .then(moduleText => {
                console.log('Successfully fetched module data');
                const surveys = extractSurveyData(moduleText);
                console.log('Extracted surveys:', surveys);
                
                const markup = generateSurveyMarkup(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' });
            });
    }
    
    // Add to window for manual execution
    window.updateQuickSurveys = fetchAndProcessSurveys;
    
    // Auto-run when on your userpage
    mw.hook('wikipage.content').add(function() {
        const currentPage = mw.config.get('wgPageName');
        const username = mw.config.get('wgUserName');
        
        if (username && currentPage === `User:${username}`) {
            // Add a small link to manually update
            const $link = $('<span style="font-size: 0.8em; margin-left: 1em;">').html(
                '[<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 update, or visit your userpage and click the update link.');
})();