跳到正文

剪贴板

剪贴板 nz6vxc03

原文
剪贴板信息

剪贴板信息

收录
更新
JavaScript
// ==UserScript==
// @name         洛谷内容净化器(两级防护版·中文优化)
// @namespace    http://tampermonkey.net/
// @version      6.6.3
// @description  洛谷犇犇内容净化:平衡/高两级防护,高级模式下破坏含屏蔽词的链接和图片
// @author       WJRAK&DeepSeek
// @match        *://*/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_registerMenuCommand
// @run-at       document-end
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // ========== 静态词库(开发者手动维护,专注中文变体)==========

    // 平衡级别词库(基础防护)- 只保留常见中文变体
    const BALANCE_WORDS = [
        // 南梁变体
        '南梁',
        // 香香软软变体
        '香香软软',
        // 猫娘变体
        '猫娘',
        // 猫粮变体
        '猫粮','喵','男娘','少女','旮旯','galgame','gay','女装','亲亲'
    ];

    // 高级别词库(更强防护)- 包含更多中文变体和组合
    const HIGH_WORDS = [
        // 南梁变体
        '南梁',
        // 香香软软变体
        '香香软软',
        // 猫娘变体
        '猫娘',
        // 猫粮变体
        '猫粮','小蛋糕','蓝梁','腿照','春','喵','男娘','https://qqemoji.heyc.eu.org/56x56/se.gif','喵!','喵','少女','旮旯','galgame','xnl','gay','女装','xml','嘎啦game','草','操','性','npy','亲亲','呜嘛','放轻松','嘿嘿'
    ];

    // 排序后的词库(用于二分查找)
    let sortedBalanceWords = null;
    let sortedHighWords = null;

    // ========== 存储键名 ==========
    const STORAGE_LEVEL = 'shield_level';  // 'balance' 或 'high'
    const STORAGE_LOG = 'shield_log';

    // ========== 默认设置 ==========
    const DEFAULT_LEVEL = 'balance';
    const DEFAULT_LOG = false;

    // ========== 初始化存储 ==========
    function initStorage() {
        if (GM_getValue(STORAGE_LEVEL, null) === null) {
            GM_setValue(STORAGE_LEVEL, DEFAULT_LEVEL);
        }
        if (GM_getValue(STORAGE_LOG, null) === null) {
            GM_setValue(STORAGE_LOG, DEFAULT_LOG);
        }

        // 初始化排序词库
        if (!sortedBalanceWords) {
            sortedBalanceWords = [...BALANCE_WORDS].sort();
        }
        if (!sortedHighWords) {
            sortedHighWords = [...HIGH_WORDS].sort();
        }
    }
    initStorage();

    // ========== 获取设置 ==========
    function getLevel() {
        return GM_getValue(STORAGE_LEVEL, DEFAULT_LEVEL);
    }
    function getLogEnabled() {
        return GM_getValue(STORAGE_LOG, DEFAULT_LOG);
    }

    // ========== 更新设置 ==========
    function updateSettings(newLevel, newLog) {
        GM_setValue(STORAGE_LEVEL, newLevel);
        GM_setValue(STORAGE_LOG, newLog);
        processDocument();
    }

    // ========== 二分查找 ==========
    function binarySearch(sortedArray, target) {
        let left = 0;
        let right = sortedArray.length - 1;

        while (left <= right) {
            const mid = Math.floor((left + right) / 2);
            const midVal = sortedArray[mid];

            if (midVal === target) {
                return true;
            }

            if (midVal < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return false;
    }

    // ========== 提取关键词(支持中英文和组合)==========
    function extractKeywords(text) {
        if (!text) return [];

        const words = new Set();
        const originalText = text;

        // 1. 原文本
        words.add(originalText);

        // 2. 按标点符号分割
        const parts = originalText.split(/[,,。.!!??;;::"'""()\(\)\[\]【】\s\-_*~·]+/);
        parts.forEach(part => {
            if (part && part.length >= 2) {
                words.add(part);
            }
        });

        // 3. 提取连续中文字符
        const chineseChars = originalText.match(/[\u4e00-\u9fa5]+/g);
        if (chineseChars) {
            chineseChars.forEach(chunk => {
                words.add(chunk);
                // 2-4字词
                for (let i = 0; i < chunk.length; i++) {
                    for (let j = i + 2; j <= i + 4 && j <= chunk.length; j++) {
                        const sub = chunk.substring(i, j);
                        if (sub.length >= 2) {
                            words.add(sub);
                        }
                    }
                }
            });
        }

        // 4. 提取连续英文字母(用于处理拼音/英文词)- 修复xnl问题的关键
        const englishWords = originalText.match(/[a-zA-Z]{2,}/g);
        if (englishWords) {
            englishWords.forEach(word => {
                words.add(word);           // 原样添加
                words.add(word.toLowerCase()); // 转小写添加
                words.add(word.toUpperCase()); // 转大写添加
            });
        }

        // 5. 提取单个字母(用于处理短词)
        const letters = originalText.match(/[a-zA-Z]/g);
        if (letters && letters.length >= 2) {
            // 尝试组合相邻字母
            for (let i = 0; i < letters.length - 1; i++) {
                const twoLetters = letters[i] + letters[i+1];
                words.add(twoLetters);
                words.add(twoLetters.toLowerCase());
            }
            for (let i = 0; i < letters.length - 2; i++) {
                const threeLetters = letters[i] + letters[i+1] + letters[i+2];
                words.add(threeLetters);
                words.add(threeLetters.toLowerCase());
            }
        }

        // 6. 处理中英文混合词
        const mixedPattern = /([\u4e00-\u9fa5]+)([a-zA-Z]+)|([a-zA-Z]+)([\u4e00-\u9fa5]+)/g;
        let match;
        while ((match = mixedPattern.exec(originalText)) !== null) {
            const mixed = (match[1] || '') + (match[2] || '') + (match[3] || '') + (match[4] || '');
            if (mixed.length >= 2) {
                words.add(mixed);
            }
        }

        // 7. 处理带分隔符的中文组合
        const separatorPattern = /([\u4e00-\u9fa5])[,,。.!!??;;::"'""()\(\)\[\]【】\s\-_*~·]+([\u4e00-\u9fa5])/g;
        while ((match = separatorPattern.exec(originalText)) !== null) {
            words.add(match[1] + match[2]);
        }

        // 8. 处理数字和字母组合(如xnl这种)
        const alphanumeric = originalText.match(/[a-zA-Z0-9]{2,}/g);
        if (alphanumeric) {
            alphanumeric.forEach(word => {
                words.add(word);
                words.add(word.toLowerCase());
            });
        }

        return Array.from(words).filter(w => w.length >= 2);
    }

    // ========== 检查文本是否包含屏蔽词 ==========
    function containsBlockedWord(text, level) {
        if (!text) return false;

        const wordList = level === 'high' ? sortedHighWords : sortedBalanceWords;
        if (!wordList) return false;

        const possibleWords = extractKeywords(text);

        // 优先检查完全匹配
        for (const word of possibleWords) {
            if (binarySearch(wordList, word)) {
                return true;
            }
        }

        // 对于英文词,检查忽略大小写
        const lowerText = text.toLowerCase();
        for (const blockedWord of wordList) {
            if (typeof blockedWord === 'string' && /[a-zA-Z]/.test(blockedWord)) {
                if (lowerText.includes(blockedWord.toLowerCase())) {
                    return true;
                }
            }
        }

        return false;
    }

    // ========== 处理图片元素(高级模式专用)==========
    function processImageElement(img) {
        const level = getLevel();

        // 只在高级模式下破坏图片
        if (level !== 'high') return;

        // 检查图片的alt属性和周边文本
        const altText = img.alt || '';
        const titleText = img.title || '';
        const srcText = img.src || '';

        if (!containsBlockedWord(altText, level) &&
            !containsBlockedWord(titleText, level) &&
            !containsBlockedWord(srcText, level)) {
            return;
        }

        const logEnabled = getLogEnabled();

        // 创建新的div元素替换图片,显示【图片已屏蔽】
        const placeholder = document.createElement('div');
        placeholder.textContent = '【图片已屏蔽】';
        placeholder.style.cssText = `
            display: inline-block;
            padding: 8px 12px;
            background: #f0f0f0;
            color: #666;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            min-width: 100px;
            text-align: center;
        `;

        // 如果有被屏蔽的文字,显示提示
        if (altText) {
            placeholder.setAttribute('title', `原图片描述: ${altText}`);
        }

        // 替换图片
        if (img.parentNode) {
            if (logEnabled) {
                console.log(`【破坏图片】alt:"${altText}" 原图:${img.src || '无'}`);
            }
            img.parentNode.replaceChild(placeholder, img);
        }
    }

    // ========== 处理链接元素(高级模式专用)==========
    function processLinkElement(link) {
        const level = getLevel();

        // 只在高级模式下破坏链接
        if (level !== 'high') return;

        // 检查链接文本和URL是否包含屏蔽词
        const linkText = link.textContent || '';
        const linkHref = link.href || '';

        if (!containsBlockedWord(linkText, level) && !containsBlockedWord(linkHref, level)) {
            return;
        }

        const logEnabled = getLogEnabled();

        // 创建新的span元素替换链接,显示【已屏蔽】
        const span = document.createElement('span');
        span.textContent = '(已屏蔽)';
        span.style.cssText = `
            color: #999;
            cursor: default;
            text-decoration: none;
            background: none;
            font-style: italic;
        `;

        // 复制原有样式类(可选)
        if (link.className) {
            span.className = link.className;
        }

        // 替换链接
        if (link.parentNode) {
            if (logEnabled) {
                console.log(`【破坏链接】原文字:"${linkText}" URL:${linkHref} → 已屏蔽`);
            }
            link.parentNode.replaceChild(span, link);
        }
    }

    // ========== 处理文本节点 ==========
    function processTextNode(node) {
        const level = getLevel();
        const logEnabled = getLogEnabled();

        if (!containsBlockedWord(node.nodeValue, level)) {
            return;
        }

        const wordList = level === 'high' ? sortedHighWords : sortedBalanceWords;
        const possibleWords = extractKeywords(node.nodeValue);
        let matchedWord = '';

        for (const word of possibleWords) {
            if (binarySearch(wordList, word)) {
                matchedWord = word;
                break;
            }
        }

        // 如果没找到完全匹配,检查包含关系
        if (!matchedWord) {
            const lowerValue = node.nodeValue.toLowerCase();
            for (const blockedWord of wordList) {
                if (typeof blockedWord === 'string' &&
                    /[a-zA-Z]/.test(blockedWord) &&
                    lowerValue.includes(blockedWord.toLowerCase())) {
                    matchedWord = blockedWord;
                    break;
                }
            }
        }

        if (logEnabled) {
            console.log(`【屏蔽】级别:${level === 'high' ? '高' : '平衡'} 词:${matchedWord} 原文:${node.nodeValue.trim()}`);
        }

        node.nodeValue = '(已屏蔽)';
    }

    // ========== 遍历DOM树(增强版)==========
    function walkDOM(node) {
        // 如果是元素节点
        if (node.nodeType === Node.ELEMENT_NODE) {
            const level = getLevel();

            // 高级模式下先处理链接和图片
            if (level === 'high') {
                // 处理链接(会替换整个元素,所以之后不用遍历子节点)
                if (node.tagName === 'A') {
                    processLinkElement(node);
                    return;
                }

                // 处理图片(会替换整个元素,所以之后不用遍历子节点)
                if (node.tagName === 'IMG') {
                    processImageElement(node);
                    return;
                }
            }

            // 跳过脚本、样式等标签
            if (/^(script|style|textarea|input|code|pre)$/i.test(node.tagName)) {
                return;
            }

            // 继续遍历子节点
            for (let child of node.childNodes) {
                walkDOM(child);
            }
        }
        // 如果是文本节点,处理文本
        else if (node.nodeType === Node.TEXT_NODE) {
            if (node.nodeValue.trim()) {
                processTextNode(node);
            }
        }
    }

    // ========== 核心处理函数 ==========
    function processDocument() {
        if (!document.body) return;

        const level = getLevel();
        const logEnabled = getLogEnabled();

        if (logEnabled) {
            console.log(`【净化器】级别:${level === 'high' ? '高' : '平衡'} 词库大小:${level === 'high' ? sortedHighWords.length : sortedBalanceWords.length}`);
            if (level === 'high') {
                console.log('【净化器】高级模式:将破坏含屏蔽词的链接和图片');
            }
        }

        walkDOM(document.body);
    }

    // ========== 监听动态内容 ==========
    function observeMutations() {
        const observer = new MutationObserver((mutations) => {
            if (observer.timeout) clearTimeout(observer.timeout);
            observer.timeout = setTimeout(processDocument, 300);
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true,
            characterData: true
        });
    }

    // ========== 测试函数(增强版)==========
    function testMatching() {
        const level = getLevel();
        const wordList = level === 'high' ? sortedHighWords : sortedBalanceWords;

        const testCases = [
            '南梁', '南[梁', '南-梁', '南 梁', '男梁', '难梁',
            '蓝梁', '篮梁', '兰梁',
            '香香软软', '香 香 软 软', '湘湘软软',
            '猫娘', '猫 娘', '猫-娘', '毛娘', '猫酿',
            '猫粮', '猫 粮', '毛粮', '猫凉',
            '男娘', '/se', '小蛋糕', '腿照', '春',
            'xnl', 'XNL', 'Xnl', 'xNL', 'xnl123', 'xnl测试'  // 新增xnl测试用例
        ];

        console.log(`【测试】当前级别: ${level === 'high' ? '高' : '平衡'}`);
        console.log('【测试】词库大小:', wordList.length);
        console.log('【测试】匹配结果:');

        testCases.forEach(test => {
            const result = containsBlockedWord(test, level);
            console.log(`  "${test}" → ${result ? '✅ 匹配' : '❌ 不匹配'}`);
        });

        // 测试xnl的各种变体
        console.log('\n【xnl专项测试】:');
        const xnlVariants = ['xnl', 'XNL', 'Xnl', 'xNL', 'xnl123', 'xnl_测试', 'xnl-测试', '测试xnl'];
        xnlVariants.forEach(test => {
            const result = containsBlockedWord(test, level);
            console.log(`  "${test}" → ${result ? '✅ 匹配' : '❌ 不匹配'}`);
        });

        if (level === 'high') {
            console.log('\n【高级模式说明】:');
            console.log('  - 包含上述词的链接 → 替换为"(已屏蔽)"');
            console.log('  - 包含上述词的图片 → 替换为"【图片已屏蔽】"');
            console.log('  - 包含上述词的文本 → 替换为"(已屏蔽)"');
        }
    }

    // ========== 创建设置面板 ==========
    function createSettingsPanel() {
        if (document.getElementById('gm-settings-panel')) return;

        const currentLevel = getLevel();
        const currentLog = getLogEnabled();

        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.id = 'gm-settings-overlay';
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 999998;
            display: none;
            justify-content: center;
            align-items: center;
        `;

        // 创建面板
        const panel = document.createElement('div');
        panel.id = 'gm-settings-panel';
        panel.style.cssText = `
            background: white;
            width: 500px;
            max-width: 90%;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
            padding: 24px;
            font-family: system-ui, -apple-system, sans-serif;
            position: relative;
        `;

        // 标题
        const title = document.createElement('h2');
        title.textContent = '🛡️ 洛谷内容净化器 v6.6';
        title.style.cssText = `
            margin: 0 0 16px 0;
            font-size: 1.5rem;
            border-bottom: 2px solid #eaeef2;
            padding-bottom: 8px;
        `;
        panel.appendChild(title);

        // 说明
        const desc = document.createElement('p');
        desc.innerHTML = '选择防护级别,词库由开发者维护,用户无需手动添加<br><span style="color:#c44536;">✓ 已修复xnl屏蔽问题</span>';
        desc.style.cssText = `
            font-size: 0.9rem;
            color: #666;
            margin-bottom: 20px;
            padding: 10px;
            background: #f0f3f5;
            border-radius: 6px;
        `;
        panel.appendChild(desc);

        // 级别选择
        const levelLabel = document.createElement('div');
        levelLabel.style.marginBottom = '10px';
        levelLabel.style.fontWeight = 'bold';
        levelLabel.textContent = '防护级别:';
        panel.appendChild(levelLabel);

        const balanceDiv = document.createElement('div');
        balanceDiv.style.marginBottom = '8px';

        const balanceRadio = document.createElement('input');
        balanceRadio.type = 'radio';
        balanceRadio.id = 'level-balance';
        balanceRadio.name = 'shield-level';
        balanceRadio.value = 'balance';
        balanceRadio.checked = currentLevel === 'balance';
        balanceRadio.style.marginRight = '8px';

        const balanceLabel = document.createElement('label');
        balanceLabel.htmlFor = 'level-balance';
        balanceLabel.innerHTML = '<strong>平衡模式</strong> <span style="color:#666;font-size:0.85rem">(基础防护,误伤较少)</span>';

        balanceDiv.appendChild(balanceRadio);
        balanceDiv.appendChild(balanceLabel);
        panel.appendChild(balanceDiv);

        const highDiv = document.createElement('div');
        highDiv.style.marginBottom = '20px';

        const highRadio = document.createElement('input');
        highRadio.type = 'radio';
        highRadio.id = 'level-high';
        highRadio.name = 'shield-level';
        highRadio.value = 'high';
        highRadio.checked = currentLevel === 'high';
        highRadio.style.marginRight = '8px';

        const highLabel = document.createElement('label');
        highLabel.htmlFor = 'level-high';
        highLabel.innerHTML = '<strong>高级模式</strong> <span style="color:#666;font-size:0.85rem">(破坏含屏蔽词的链接和图片)</span>';

        highDiv.appendChild(highRadio);
        highDiv.appendChild(highLabel);
        panel.appendChild(highDiv);

        // 统计信息
        const statsDiv = document.createElement('div');
        statsDiv.style.cssText = `
            background: #f8f9fa;
            border-radius: 6px;
            padding: 12px;
            margin-bottom: 20px;
            font-size: 0.9rem;
        `;
        statsDiv.innerHTML = `
            <div>平衡词库: ${BALANCE_WORDS.length} 个变体</div>
            <div>高级词库: ${HIGH_WORDS.length} 个变体 (包含 "xnl")</div>
            <div style="margin-top:8px;color:#c44536;">⚡ 高级模式会:</div>
            <div style="margin-left:12px;color:#c44536;font-size:0.85rem;">• 链接 → 替换为"(已屏蔽)"</div>
            <div style="margin-left:12px;color:#c44536;font-size:0.85rem;">• 图片 → 替换为"【图片已屏蔽】"</div>
            <div style="margin-left:12px;color:#c44536;font-size:0.85rem;">• 文本 → 替换为"(已屏蔽)"</div>
        `;
        panel.appendChild(statsDiv);

        // 日志选项
        const logDiv = document.createElement('div');
        logDiv.style.marginBottom = '20px';

        const logCheckbox = document.createElement('input');
        logCheckbox.type = 'checkbox';
        logCheckbox.id = 'log-console';
        logCheckbox.checked = currentLog;
        logCheckbox.style.marginRight = '8px';

        const logLabel = document.createElement('label');
        logLabel.htmlFor = 'log-console';
        logLabel.innerHTML = '控制台输出屏蔽日志 (F12查看)';

        logDiv.appendChild(logCheckbox);
        logDiv.appendChild(logLabel);
        panel.appendChild(logDiv);

        // 按钮区域
        const btnDiv = document.createElement('div');
        btnDiv.style.cssText = `
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        `;

        const testBtn = document.createElement('button');
        testBtn.textContent = '测试匹配';
        testBtn.style.cssText = `
            padding: 8px 16px;
            border: 1px solid #2c3e50;
            background: white;
            color: #2c3e50;
            border-radius: 6px;
            cursor: pointer;
        `;
        testBtn.onclick = () => {
            testMatching();
            alert('测试结果已输出到控制台 (F12查看)\nxnl 应该被成功屏蔽');
        };

        const cancelBtn = document.createElement('button');
        cancelBtn.textContent = '取消';
        cancelBtn.style.cssText = `
            padding: 8px 16px;
            border: 1px solid #ccc;
            background: white;
            border-radius: 6px;
            cursor: pointer;
        `;
        cancelBtn.onclick = () => {
            overlay.style.display = 'none';
        };

        const saveBtn = document.createElement('button');
        saveBtn.textContent = '保存';
        saveBtn.style.cssText = `
            padding: 8px 16px;
            border: none;
            background: #2c3e50;
            color: white;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
        `;
        saveBtn.onclick = () => {
            const newLevel = document.querySelector('input[name="shield-level"]:checked').value;
            const newLog = document.getElementById('log-console').checked;
            updateSettings(newLevel, newLog);
            overlay.style.display = 'none';
        };

        btnDiv.appendChild(testBtn);
        btnDiv.appendChild(cancelBtn);
        btnDiv.appendChild(saveBtn);
        panel.appendChild(btnDiv);

        // 关闭按钮
        const closeIcon = document.createElement('span');
        closeIcon.innerHTML = '✕';
        closeIcon.style.cssText = `
            position: absolute;
            top: 18px;
            right: 24px;
            font-size: 1.6rem;
            cursor: pointer;
            color: #999;
        `;
        closeIcon.onclick = () => {
            overlay.style.display = 'none';
        };
        panel.appendChild(closeIcon);

        overlay.appendChild(panel);
        document.body.appendChild(overlay);

        // 触发按钮
        let triggerBtn = document.getElementById('gm-settings-trigger');
        if (!triggerBtn) {
            triggerBtn = document.createElement('div');
            triggerBtn.id = 'gm-settings-trigger';
            triggerBtn.innerHTML = '🛡️';
            triggerBtn.style.cssText = `
                position: fixed;
                bottom: 20px;
                right: 20px;
                width: 60px;
                height: 60px;
                background: #c44536;
                color: white;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 32px;
                cursor: pointer;
                box-shadow: 0 4px 15px rgba(0,0,0,0.3);
                z-index: 999999;
                opacity: 0.8;
                border: 2px solid white;
                transition: opacity 0.3s;
            `;
            triggerBtn.onmouseover = () => {
                triggerBtn.style.opacity = '1';
            };
            triggerBtn.onmouseout = () => {
                triggerBtn.style.opacity = '0.8';
            };
            triggerBtn.onclick = () => {
                overlay.style.display = 'flex';
            };
            document.body.appendChild(triggerBtn);
        }
    }

    // ========== 初始化 ==========
    function init() {
        processDocument();
        createSettingsPanel();
        observeMutations();
        console.log('【洛谷内容净化器 v6.6】已启动 - 已修复xnl屏蔽问题');
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

    // ========== 菜单命令 ==========
    GM_registerMenuCommand('🔍 测试匹配 (包含xnl)', testMatching);
    GM_registerMenuCommand('⚙️ 打开设置', () => {
        document.getElementById('gm-settings-overlay').style.display = 'flex';
    });

})();