跳转到内容

User:Wcam/Filetestpixel.js

维基百科,自由的百科全书
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google ChromeFirefoxMicrosoft EdgeSafari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
// Derived from User:小躍/Filetestpixel.js
// <nowiki>
// Wikipedia File Pixel Maintenance Tool - Streamlined Version
(function() {
    'use strict';
    
    // Configuration
    const CONFIG = {
        pixelLimit: 100000,
        largeImageThreshold: 500000
    };
    
    // Initialization
    mw.loader.using(['jquery.ui', 'mediawiki.api', 'mediawiki.util'], function() {
        addPortletLink();
    });
    
    // Add link to page actions menu
    function addPortletLink() {
        const link = mw.util.addPortletLink(
            'p-cactions', 
            '#摘要', 
            wgULS('档案像素维护', '檔案像素維護'), 
            't-fileshow', 
            '檢查檔案是否符合非合理使用大小像素的模板', 
            '', 
            '#ca-move'
        );
        
        $(link).click(function(event) {
            event.preventDefault();
            
            // If we're on a file page, process it directly
            const currentPage = mw.config.get('wgPageName');
            if (/^(File:|Image:)/i.test(currentPage)) {
                getFileInfo(event, currentPage);
            } else {
                // If not on a file page, show a simple error
                createDialog({
                    id: 'filenotfound',
                    title: '檔案像素檢測器',
                    content: '請先進入檔案頁面才能使用此功能。',
                    width: 400
                });
            }
        });
    }
    
    // Get file information from the API
    function getFileInfo(event, fileName) {
        if (event) event.preventDefault();
        
        const api = new mw.Api();
        api.get({
            'action': 'query',
            'titles': fileName,
            'prop': 'revisions|info|imageinfo',
            'iiprop': 'size',
            'intoken': 'edit',
            'rvprop': 'content',
            'indexpageids': 1
        }).done(function(response) {
            processFileInfo(response, fileName);
        }).fail(function() {
            showError('檔案資訊獲取失敗,請重試。');
        });
    }
    
    // Process the file information from the API response
    function processFileInfo(response, fileName) {
        const result = response.query;
        const pageId = result.pageids[0];
        
        // Handle non-existent pages
        if (pageId === '-1') {
            showError('檔案不存在,請檢查檔案名稱。');
            return;
        }
        
        const page = result.pages[pageId];
        const fileContent = page.revisions[0]['*'].toString();
        const height = page.imageinfo[0].height;
        const width = page.imageinfo[0].width;
        const totalPixels = height * width;
        
        // Calculate recommended width
        const recommendedWidth = calculateRecommendedWidth(width, height);
        
        // Check existing templates
        const hasNonFreeReduce = /\{\{[Nn]on-free reduce\}\}/.test(fileContent);
        const hasIfd = /\{\{[Ii]fd/.test(fileContent);
        const hasDelete = /\{\{[Dd]elete/.test(fileContent);
        const hasMoveToCommons = /\{\{[Mm]ove to commons\}\}/.test(fileContent);
        
        // Clean content (for template removal)
        const cleanContent = fileContent.replace(/\{\{[Nn]on-free reduce\}\}/g, '');
        
        // Handle actions automatically based on conditions
        if (totalPixels <= CONFIG.pixelLimit && hasNonFreeReduce) {
            // Auto-remove template if image is within limits
            removeNonFreeReduceTemplate(fileName, cleanContent);
            showActionMessage('移除模板', fileName);
        } else if (totalPixels > CONFIG.pixelLimit && !hasNonFreeReduce && !hasIfd && !hasDelete && !hasMoveToCommons) {
            // Auto-add template for oversized images
            addNonFreeReduceTemplate(fileName, recommendedWidth);
            showActionMessage('添加模板', fileName);
        } else {
            // Show info dialog without actions
            showFileInfoDialog(fileName, height, width, totalPixels, recommendedWidth, hasNonFreeReduce, hasIfd, hasDelete, hasMoveToCommons);
        }
    }
    
    // Calculate the recommended width for reducing image size
    function calculateRecommendedWidth(width, height) {
        let recommendedWidth = width;
        const aspectRatio = height / width;
        
        // Iteratively reduce width until total pixels are below the limit
        while ((recommendedWidth * (recommendedWidth * aspectRatio)) > CONFIG.pixelLimit) {
            recommendedWidth--;
            if (recommendedWidth <= 0) break; // Safety check
        }
        
        return recommendedWidth;
    }
    
    // Show dialog with file information
    function showFileInfoDialog(fileName, height, width, totalPixels, recommendedWidth, hasNonFreeReduce, hasIfd, hasDelete, hasMoveToCommons) {
        let statusInfo = '';
        
        // Size status
        if (totalPixels > CONFIG.pixelLimit) {
            statusInfo += `<br><font color="blue"><b>建議寬度縮小至${recommendedWidth}像素</b></font>`;
            statusInfo += '<br><font color="red"><b>已超過容許像素,請務必縮小</b></font>';
        } else {
            statusInfo += '<br><font color="green"><b>容許像素的範圍內</b></font>';
        }
        
        // Template status
        if (hasIfd) {
            statusInfo += '<br><font color="green"><b>已掛上檔案存廢討論的模板</b></font>';
        } else if (hasDelete) {
            statusInfo += '<br><font color="green"><b>已掛上快速刪除的模板</b></font>';
        } else if (hasMoveToCommons) {
            statusInfo += '<br><font color="green"><b>已掛上請求移動至維基共享資源的維護模板</b></font>';
        } else if (hasNonFreeReduce) {
            statusInfo += '<br><font color="green"><b>已掛上{{Non-free reduce}}模板</b></font>';
        }
        
        // Add action button if needed
        const actionButton = (!hasNonFreeReduce && totalPixels > CONFIG.pixelLimit) ? 
            '<br><input id="wpfilesave" value="添加維護模板" title="添加模板" type="button"/>' : '';
        
        createDialog({
            id: 'filenfrshowing',
            title: '檔案像素檢測器',
            content: `
                <label>顯示檔案名稱:${fileName}</label>
                <br/><img src="https://upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />
                <label>高度:${height}像素;寬度:${width}像素;總共:${totalPixels}像素${statusInfo}</label>
                ${actionButton}
            `,
            width: 500
        });
        
        // Add handler for template addition button if present
        $('#wpfilesave').click(function(event) {
            event.preventDefault();
            addNonFreeReduceTemplate(fileName, recommendedWidth);
            showActionMessage('添加模板', fileName);
        });
    }
    
    // Show message after action
    function showActionMessage(action, fileName) {
        createDialog({
            id: 'fileactiondone',
            title: '檔案像素檢測器編輯訊息',
            content: `<label>已成功${action},正在重新載入頁面...</label>`,
            width: 400
        });
        
        // Reload page after a short delay
        setTimeout(function() {
            window.location.href = mw.util.getUrl(fileName);
        }, 1500);
    }
    
    // Add Non-free reduce template to file
    function addNonFreeReduceTemplate(fileName, recommendedWidth) {
        const template = '{{Non-free reduce}}';
        const summary = `建議縮小寬度至${recommendedWidth}像素,依照[[Wikipedia:非自由版权图片大小|非自由版權圖片大小]]快速添加{{Non-free reduce}}維護模板`;
        
        editPage({
            title: fileName,
            prependtext: template + "\n",
            summary: summary,
            minor: true
        });
    }
    
    // Remove Non-free reduce template from file
    function removeNonFreeReduceTemplate(fileName, cleanContent) {
        const summary = '經偵測為容許像素,依照[[Wikipedia:非自由版权图片大小|非自由版權圖片大小]]快速移除{{Non-free reduce}}維護模板';
        
        editPage({
            title: fileName,
            text: cleanContent,
            summary: summary,
            minor: true
        });
    }
    
    // Helper function to create dialogs
    function createDialog(options) {
        $(`<div id="${options.id}" title="${options.title}">${options.content}</div>`).dialog({
            modal: false,
            autoOpen: true,
            width: options.width || 400
        });
    }
    
    // Helper function to show error messages
    function showError(message) {
        createDialog({
            id: 'fileerror',
            title: '檔案像素檢測器錯誤',
            content: `<label>${message}</label>`,
            width: 400
        });
    }
    
    // Helper function to edit pages
    function editPage(options) {
        const api = new mw.Api();
        const params = {
            action: 'edit',
            title: options.title,
            summary: options.summary,
            token: mw.user.tokens.get('csrfToken'),
            minor: options.minor ? 1 : 0
        };
        
        // Add text content based on edit type
        if (options.text) params.text = options.text;
        if (options.prependtext) params.prependtext = options.prependtext;
        if (options.appendtext) params.appendtext = options.appendtext;
        
        api.post(params).done(function() {
            if (options.callback) options.callback();
        }).fail(function() {
            showError('編輯操作失敗,請重試。');
        });
    }
})();
// </nowiki>