跳到正文

剪贴板

剪贴板 76qlzybj

原文
剪贴板信息

剪贴板信息

收录
更新
JavaScript
// ==UserScript==
// @name         luogu自动跳转助手
// @namespace    http://tampermonkey.net/
// @version      2024.06.05
// @description  自动处理luogu文章/剪切板的跳转与按钮点击
// @author       zhao_daodao
// @match        https://www.luogu.com.cn/paste/*
// @match        https://www.luogu.me/paste/*
// @match        https://www.luogu.com.cn/article/*
// @match        https://www.luogu.me/article/*
// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // ================== 配置中心 ==================
    const CONFIG = {
        pathTypes: ['paste', 'article'],      // 支持的路径类型
        domainMap: {                           // 域名映射关系
            'www.luogu.com.cn': 'www.luogu.me',
            'www.luogu.me': 'www.luogu.me'
        },
        minInterval: 5000,                    // 最小操作间隔
        timeoutDuration: 5000,                 // 操作超时时间
        buttonSelectors: {                     // 按钮选择器配置
            a: "a[href='#'][onclick='saveArticle()'].ui.animated.button.small",
            div: "div[onclick='saveArticle()'].ui.vertical.button.animated"
        },
        specificLinkSelector: "body > div:nth-child(1) > div > p:nth-child(5) > a"
    };

    // ================== 核心逻辑 ==================
    class LuoguAutoRedirect {
        constructor() {
            this.pathType = this.detectPathType();
            this.pathSuffix = this.extractPathSuffix();
            this.buttonClicked = false;
            this.observer = null;
        }

        // 主入口
        init() {
            if (!this.validateEnvironment()) return;
            this.handleRedirection();
            this.setupMutationObserver();
            this.attemptClick();
        }

        // 路径类型检测
        detectPathType() {
            return CONFIG.pathTypes.find(type =>
                location.pathname.includes(`/${type}/`)
            ) || 'unknown';
        }

        // 提取路径后缀
        extractPathSuffix() {
            const match = location.pathname.match(new RegExp(`\\/${this.pathType}\\/(.+)`));
            return match ? match[1] : '';
        }

        // 环境验证
        validateEnvironment() {
            const isMeDomain = location.hostname === 'www.luogu.me';
            const hasSpecificLink = !!document.querySelector(CONFIG.specificLinkSelector);

            if (!isMeDomain && !hasSpecificLink) {
                console.log('未满足执行条件,退出脚本');
                return false;
            }
            return true;
        }

        // 处理重定向
        handleRedirection() {
            const sourceDomain = Object.keys(CONFIG.domainMap)
                .find(domain => location.hostname === domain);

            if (sourceDomain && location.hostname !== CONFIG.domainMap[sourceDomain]) {
                window.location.href = `https://${CONFIG.domainMap[sourceDomain]}/${this.pathType}/${this.pathSuffix}`;
                return true;
            }
            return false;
        }

        // 按钮操作逻辑
        attemptClick() {
            if (this.checkTimeConstraint() && this.findAndClickButton()) {
                this.updateTimestamp();
                this.scheduleRefresh();
                return true;
            }
            return false;
        }

        // 时间间隔检查
        checkTimeConstraint() {
            const storageKey = `lastClick_${this.pathType}_${this.pathSuffix}`;
            const lastClick = localStorage.getItem(storageKey);
            const currentTime = Date.now();

            if (lastClick && (currentTime - lastClick < CONFIG.minInterval)) {
                console.log(`操作间隔过短,请等待 ${CONFIG.minInterval/1000} 秒`);
                return false;
            }
            return true;
        }

        // 查找并点击按钮
        findAndClickButton() {
            let button = document.querySelector(CONFIG.buttonSelectors.a) ||
                        document.querySelector(CONFIG.buttonSelectors.div);

            if (!button) {
                console.log('未找到目标按钮');
                return false;
            }

            button.dispatchEvent(new MouseEvent('click', {
                bubbles: true,
                cancelable: true
            }));
            console.log('成功触发按钮点击');
            return true;
        }

        // 更新操作时间戳
        updateTimestamp() {
            localStorage.setItem(
                `lastClick_${this.pathType}_${this.pathSuffix}`,
                Date.now()
            );
        }

        // 定时刷新
        scheduleRefresh() {
            setTimeout(() => {
                window.location.href = `https://www.luogu.me/${this.pathType}/${this.pathSuffix}`;
            }, CONFIG.timeoutDuration);
        }

        // DOM变化监听
        setupMutationObserver() {
            this.observer = new MutationObserver(mutations => {
                for (const mutation of mutations) {
                    if (mutation.type === 'childList') {
                        this.attemptClick();
                        this.observer.disconnect();
                        break;
                    }
                }
            });

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

    // ================== 执行入口 ==================
    if (document.readyState === 'complete') {
        new LuoguAutoRedirect().init();
    } else {
        window.addEventListener('load', () => new LuoguAutoRedirect().init());
    }
})();