☰

EH_lanraragi_dl

发送 EH 本子到 LANraragi 或 Cloudflare 网盘后台下载

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(Tôi đã có Trình quản lý tập lệnh người dùng, hãy cài đặt nó!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         EH_lanraragi_dl
// @namespace    魔皇地狱
// @version      0.2
// @description 发送 EH 本子到 LANraragi 或 Cloudflare 网盘后台下载
// @license MIT
// @match        https://e-hentai.org/*
// @match        https://exhentai.org/*
// @grant        GM_notification

// @grant GM_registerMenuCommand
// @grant GM_getValue
// @grant GM_setValue

// @grant GM_xmlhttpRequest
// @connect      *

// @run-at document-idle
// @require https://cdn.jsdelivr.net/npm/sweetalert2@11
// ==/UserScript==

function readObject(key) {
    let value = GM_getValue(key, {});
    if (typeof value === "string") {
        try { value = JSON.parse(value); } catch { return {}; }
    }
    return value && typeof value === "object" && !Array.isArray(value) ? value : {};
}

function readArray(key) {
    let value = GM_getValue(key, []);
    if (typeof value === "string") {
        try { value = JSON.parse(value); } catch { return []; }
    }
    return Array.isArray(value) ? value : [];
}

function selectedBackend(config = readObject("config")) {
    const backend = config.backend || "lanraragi";
    if (backend === "lanraragi") {
        if (typeof config.lanraragi_api !== "string" || !config.lanraragi_api ||
            typeof config.lanraragi_token !== "string" || !config.lanraragi_token) {
            throw new Error("请先设置 LANraragi API 和 Token");
        }
        return {backend, config, scope: `lanraragi:${config.lanraragi_api}`};
    }
    if (backend !== "cloudflare") throw new Error("请选择下载后端");
    const provider = config.cloudflare_provider || "onedrive";
    if (!["onedrive", "googledrive"].includes(provider)) throw new Error("请选择当前网盘");
    let api;
    try { api = new URL(config.cloudflare_api); } catch { throw new Error("请输入 Cloudflare API origin"); }
    const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(api.hostname);
    if ((api.protocol !== "https:" && !(api.protocol === "http:" && loopback)) ||
        api.username || api.password || api.pathname !== "/" || api.search || api.hash) {
        throw new Error("Cloudflare API 须为 HTTPS origin;HTTP 仅允许本机回环地址");
    }
    if (typeof config.cloudflare_token !== "string" || !config.cloudflare_token) throw new Error("请输入 Cloudflare API Token");
    return {backend, config, provider, origin: api.origin, scope: `cloudflare:${api.origin}:${provider}`};
}

GM_registerMenuCommand("⚙️ 设置", async () => {
    const config = readObject("config");
    const result = await Swal.fire({
        title: "设置",
        html: `
            <label for="backend">下载后端</label>
            <select id="backend" class="swal2-select"><option value="lanraragi">LANraragi</option><option value="cloudflare">Cloudflare</option></select>
            <input id="lanraragi_api" class="swal2-input" placeholder="LANraragi API" aria-label="LANraragi API">
            <input id="lanraragi_token" type="password" class="swal2-input" placeholder="LANraragi Token" aria-label="LANraragi Token">
            <input id="cloudflare_api" class="swal2-input" placeholder="Cloudflare API origin" aria-label="Cloudflare API origin">
            <input id="cloudflare_token" type="password" class="swal2-input" placeholder="Cloudflare API Token" aria-label="Cloudflare API Token">
            <label for="cloudflare_provider">当前网盘</label>
            <select id="cloudflare_provider" class="swal2-select"><option value="onedrive">OneDrive</option><option value="googledrive">Google Drive</option></select>
            <br><label><strong>主页查看是否下载<input id="homepage" type="checkbox"></strong></label>
        `,
        showCancelButton: true,
        didOpen: () => {
            for (const key of ["lanraragi_api", "lanraragi_token", "cloudflare_api", "cloudflare_token"]) {
                document.getElementById(key).value = typeof config[key] === "string" ? config[key] : "";
            }
            document.getElementById("backend").value = ["lanraragi", "cloudflare"].includes(config.backend) ? config.backend : "lanraragi";
            document.getElementById("cloudflare_provider").value = ["onedrive", "googledrive"].includes(config.cloudflare_provider) ? config.cloudflare_provider : "onedrive";
            document.getElementById("homepage").checked = config.homepage === true;
        },
        preConfirm: () => {
            const next = {...readObject("config")};
            for (const key of ["backend", "lanraragi_api", "lanraragi_token", "cloudflare_api", "cloudflare_token", "cloudflare_provider"]) {
                next[key] = document.getElementById(key).value;
            }
            next.homepage = document.getElementById("homepage").checked;
            try { selectedBackend(next); } catch (error) {
                Swal.showValidationMessage(error.message);
                return false;
            }
            return next;
        }
    });
    if (result.isConfirmed) {
        await GM_setValue("config", {...readObject("config"), ...result.value});
        activateBackend();
    }
});

GM_registerMenuCommand("手动更新数据库", async () => {
    try {
        const selected = selectedBackend();
        await data_update(selected);
        redraw();
    } catch (error) {
        Swal.fire({icon: "error", title: "更新失败", text: error.message});
    }
});

GM_registerMenuCommand("授权当前网盘", async () => {
    try {
        const selected = selectedBackend();
        if (selected.backend !== "cloudflare") throw new Error("请先选择 Cloudflare 后端及当前网盘");
        const data = await cloudRequest(selected, `/api/oauth/${selected.provider}/start`, "POST", {});
        const consent = new URL(data.url);
        const official = selected.provider === "onedrive"
            ? consent.hostname === "login.microsoftonline.com" && consent.pathname === "/consumers/oauth2/v2.0/authorize"
            : consent.hostname === "accounts.google.com" && consent.pathname === "/o/oauth2/v2/auth";
        if (consent.protocol !== "https:" || consent.username || consent.password || consent.port || !official) {
            throw new Error("后台返回的授权地址不是官方网盘授权页");
        }
        Swal.fire({
            title: "授权当前网盘",
            html: '<p>请在正常浏览器中完成授权,然后手动更新数据库。</p><a id="drive-consent" target="_blank" rel="noopener noreferrer">打开官方网盘授权页</a>',
            didOpen: () => { document.getElementById("drive-consent").href = consent.href; }
        });
    } catch (error) {
        Swal.fire({icon: "error", title: "授权失败", text: error.message});
    }
});

function gallery(value) {
    try {
        const url = new URL(value);
        const match = url.pathname.match(/^\/g\/([1-9]\d*)\/([a-f0-9]{10})\/?$/i);
        if (url.protocol !== "https:" || !["e-hentai.org", "exhentai.org"].includes(url.hostname) ||
            url.username || url.password || url.port || !match) return null;
        const token = match[2].toLowerCase();
        return {gid: match[1], token, key: `${match[1]}-${token}`, url: `${url.origin}/g/${match[1]}/${token}/`};
    } catch { return null; }
}

function cloudState(selected) {
    const saved = readObject(selected.scope);
    const jobs = {};
    if (saved.jobs && typeof saved.jobs === "object" && !Array.isArray(saved.jobs)) {
        for (const [key, job] of Object.entries(saved.jobs)) {
            if (!/^[1-9]\d*-[a-f0-9]{10}$/.test(key) || !job || typeof job !== "object" || Array.isArray(job)) continue;
            const id = typeof job.id === "string" && /^[a-f0-9]{32}$/.test(job.id) ? job.id : null;
            const source = gallery(job.url);
            if (!id && source?.key !== key) continue;
            const state = id && ["queued", "metadata", "acquiring", "downloading", "uploading", "finished", "failed"].includes(job.state)
                ? job.state : "unknown";
            jobs[key] = {id, state, error: typeof job.error === "string" ? job.error : null,
                url: source?.key === key ? source.url : null};
        }
    }
    return {jobs, archives: Array.isArray(saved.archives) ? saved.archives.filter(validArchive) : []};
}

function validArchive(item) {
    return item && typeof item === "object" && /^[1-9]\d*$/.test(String(item.gid)) &&
        typeof item.token === "string" && /^[a-f0-9]{10}$/.test(item.token) &&
        gallery(item.source)?.key === `${item.gid}-${item.token}`;
}

async function saveCloudJob(selected, key, job) {
    const saved = cloudState(selected);
    saved.jobs[key] = job;
    await GM_setValue(selected.scope, saved);
}

let detail = null;
let pollTimer = null;
let pollGeneration = 0;
const cloudBusy = new Set();
const cloudRequests = new Set();
let legacyRequest = null;
const originalTitles = new WeakMap();
const pageGallery = gallery(window.location.href);

function redraw() {
    const config = readObject("config");
    let selected;
    try { selected = selectedBackend(config); } catch { selected = null; }
    const saved = selected?.backend === "cloudflare" ? cloudState(selected) : null;
    const gids = readArray("gid_list");
    const titles = readArray("title_list");
    const keys = new Set((saved?.archives || []).map(x => `${x.gid}-${x.token}`));
    for (const [key, job] of Object.entries(saved?.jobs || {})) {
        if (job?.state === "finished") keys.add(key);
    }
    const exists = (item, title) => selected?.backend === "cloudflare"
        ? keys.has(item.key)
        : selected && (gids.includes(item.gid) || (title && titles.includes(title)));

    if (pageGallery) {
        if (detail && detail.scope !== selected?.scope) {
            detail.p.remove();
            detail = null;
        }
        if (selected && !detail && document.querySelector("#gd5")) {
            const p = document.createElement("p");
            p.className = "g2 gsp";
            const btn = document.createElement("button");
            btn.id = "lanraragi";
            btn.addEventListener("click", () => {
                let current;
                try { current = selectedBackend(); } catch { return; }
                if (current.backend === "cloudflare") cloudDownload(current, pageGallery);
                else lanraragi_download(pageGallery.url, btn, p);
            });
            const status = document.createElement("span");
            p.append(btn, document.createElement("br"), status);
            document.querySelector("#gd5").appendChild(p);
            detail = {p, btn, status, scope: selected.scope};
        }
        if (detail) {
            const title = document.querySelector("#gj")?.textContent?.trim();
            const titleEnglish = document.querySelector("#gn")?.textContent?.trim();
            const status = selected.backend === "cloudflare" ? driveStatus.get(selected.scope) : null;
            detail.status.textContent = selected.backend !== "cloudflare" ? "" :
                `${selected.provider === "onedrive" ? "OneDrive" : "Google Drive"}:${status?.error ? status.error
                    : !status ? "正在检查后台配置及授权"
                    : !status.configured ? "后台尚未配置此网盘,请在服务器设置应用凭据"
                    : status.authorized ? "已授权" : "未授权,请使用“授权当前网盘”菜单"}`;
            if (exists(pageGallery, title) || exists(pageGallery, titleEnglish)) {
                detail.btn.disabled = true;
                detail.btn.textContent = "✅️ 已存在";
            } else if (selected.backend === "cloudflare") {
                const job = saved.jobs[pageGallery.key];
                const labels = {queued: "排队中", metadata: "获取元数据", acquiring: "获取原始归档", downloading: "下载中", uploading: "上传中"};
                const busy = cloudBusy.has(`${selected.scope}:${pageGallery.key}`);
                detail.btn.disabled = busy || Boolean(job && labels[job.state]) ||
                    (!job && status && !status.error && (!status.configured || !status.authorized));
                detail.btn.textContent = busy ? "🔄 正在请求后台"
                    : !job ? "⬇️ 点击发送到 Cloudflare"
                    : job.state === "failed" ? "❌ 下载失败,点击重试"
                    : labels[job.state] ? `🔄 ${labels[job.state]}` : "❓ 状态未知,点击查询";
                detail.btn.title = job?.error || "";
            } else if (!detail.btn.textContent) {
                detail.btn.disabled = false;
                detail.btn.textContent = "⬇️ 点击发送到lanraragi";
            }
        }
    } else {
        const links = document.querySelectorAll(".itg.gld .gl1t a, .itg.gltc td.gl3c.glname a");
        for (const link of links) {
            const item = gallery(link.href);
            const div = link.querySelector(".gl4t.glname.glink, div.glink, span");
            if (!item || !div) continue;
            if (!originalTitles.has(div)) originalTitles.set(div, div.textContent);
            const title = originalTitles.get(div);
            div.textContent = config.homepage === true && selected ? `${exists(item, title) ? "✅" : "❌"} ${title}` : title;
        }
    }
}

function activateBackend() {
    stopPolling();
    let selected;
    try { selected = selectedBackend(); } catch { redraw(); return; }
    if (selected.backend === "cloudflare") {
        driveStatus.delete(selected.scope);
        pollJobs(selected, pollGeneration, true);
    }
    redraw();
    data_update(selected).catch(() => {}).finally(redraw);
}

function stopPolling() {
    clearTimeout(pollTimer);
    pollTimer = null;
    pollGeneration++;
    for (const request of cloudRequests) request?.abort?.();
    cloudRequests.clear();
    legacyRequest?.abort?.();
    legacyRequest = null;
}

async function data_update(selected) {
    if (selected.backend === "lanraragi") return lanraragi_data_update();
    const [, data] = await Promise.all([
        refreshDriveStatus(selected),
        cloudRequest(selected, `/api/library?provider=${selected.provider}`)
    ]);
    if (!Array.isArray(data.archives)) throw new Error("后台数据库响应格式错误");
    const saved = cloudState(selected);
    saved.archives = data.archives.filter(validArchive);
    await GM_setValue(selected.scope, saved);
}

async function lanraragi_data_update() {
    const config = readObject("config");
    return new Promise((resolve, reject) => {
        GM_xmlhttpRequest({
            method: "GET",
            url: `${config.lanraragi_api}/api/archives`,
            timeout: 10000,
            onload(res) {
                try {
                    if (res.status !== 200) throw new Error("LANraragi 数据库请求失败");
                    const data = JSON.parse(res.responseText);
                    if (!Array.isArray(data)) throw new Error("LANraragi 数据库响应格式错误");
                    const gid_list = [];
                    const title_list = [];
                    for (const x of data) {
                        if (typeof x.title === "string") title_list.push(x.title);
                        for (const tag of String(x.tags || "").split(",")) {
                            if (!tag.trim().startsWith("source:")) continue;
                            let source = tag.trim().slice(7).trim();
                            if (!/^https?:\/\//i.test(source)) source = "https://" + source;
                            try {
                                const sourceUrl = new URL(source);
                                if (["e-hentai.org", "exhentai.org"].includes(sourceUrl.hostname)) {
                                    const parts = sourceUrl.pathname.split("/").filter(Boolean);
                                    if (parts[0] === "g" && parts[1]) gid_list.push(parts[1]);
                                }
                            } catch {}
                            break;
                        }
                    }
                    GM_setValue("gid_list", JSON.stringify(gid_list));
                    GM_setValue("title_list", JSON.stringify(title_list));
                    resolve(true);
                } catch { reject(new Error("LANraragi 数据库读取失败")); }
            },
            onerror: () => reject(new Error("LANraragi 网络请求失败")),
            ontimeout: () => reject(new Error("LANraragi 请求超时"))
        });
    });
}

function cloudRequest(selected, path, method = "GET", body) {
    return new Promise((resolve, reject) => {
        let request;
        const finish = (callback, value) => {
            cloudRequests.delete(request);
            callback(value);
        };
        const unknown = () => finish(reject, new Error("网络结果未知,请点击查询以确认任务状态"));
        try {
            request = GM_xmlhttpRequest({
                method,
                url: selected.origin + path,
                headers: {
                    "Authorization": `Bearer ${selected.config.cloudflare_token}`,
                    "Content-Type": "application/json"
                },
                data: body === undefined ? undefined : JSON.stringify(body),
                anonymous: true,
                redirect: "error",
                timeout: 10000,
                onload(res) {
                    let data;
                    try { data = JSON.parse(res.responseText); } catch { unknown(); return; }
                    if (!data || typeof data !== "object" || Array.isArray(data)) { unknown(); return; }
                    if (res.status < 200 || res.status >= 300) {
                        const error = new Error(typeof data.error?.message === "string" ? data.error.message : "Cloudflare 请求失败");
                        error.status = res.status;
                        finish(reject, error);
                        return;
                    }
                    finish(resolve, data);
                },
                onerror: unknown,
                ontimeout: unknown,
                onabort: unknown
            });
            cloudRequests.add(request);
        } catch { unknown(); }
    });
}

function checkedJob(data, selected) {
    if (typeof data.id !== "string" || !/^[a-f0-9]{32}$/.test(data.id) ||
        !["queued", "metadata", "acquiring", "downloading", "uploading", "finished", "failed"].includes(data.state) ||
        (data.provider !== undefined && data.provider !== selected.provider)) {
        throw new Error("后台任务响应格式错误,保留现有任务等待查询");
    }
    return {id: data.id, state: data.state, error: typeof data.error?.message === "string" ? data.error.message : null};
}

const driveStatus = new Map();

async function refreshDriveStatus(selected) {
    try {
        const data = await cloudRequest(selected, "/api/config");
        const status = data.providers?.[selected.provider];
        if (typeof status?.configured !== "boolean" || typeof status.authorized !== "boolean") {
            throw new Error("后台网盘配置响应格式错误");
        }
        driveStatus.set(selected.scope, status);
        return status;
    } catch (error) {
        driveStatus.set(selected.scope, {error: error.message});
        throw error;
    }
}

async function queryCloudJob(selected, key, notify = false) {
    const lock = `${selected.scope}:${key}`;
    const previous = cloudState(selected).jobs[key];
    if (!previous?.id || cloudBusy.has(lock)) return false;
    cloudBusy.add(lock);
    redraw();
    try {
        const data = await cloudRequest(selected, `/api/jobs/${previous.id}`);
        const job = checkedJob(data, selected);
        if (job.id !== previous.id || data.provider !== selected.provider) {
            throw new Error("后台返回的任务不匹配,保留现有任务等待查询");
        }
        await saveCloudJob(selected, key, {...job, url: previous.url});
        return job.state === "finished" && previous.state !== "finished";
    } catch (error) {
        await saveCloudJob(selected, key, {...previous, state: "unknown", error: error.message});
        if (notify) Swal.fire({icon: "error", title: "任务状态未知", text: error.message});
        return false;
    } finally {
        cloudBusy.delete(lock);
        redraw();
    }
}

async function cloudDownload(selected, item) {
    const lock = `${selected.scope}:${item.key}`;
    if (cloudBusy.has(lock)) return;
    const generation = pollGeneration;
    const previous = cloudState(selected).jobs[item.key];
    if (previous?.id && previous.state !== "failed") {
        if (await queryCloudJob(selected, item.key, true) && generation === pollGeneration) {
            await data_update(selected).catch(() => {});
            redraw();
        }
        return;
    }
    cloudBusy.add(lock);
    redraw();
    let pending = null;
    let finished = false;
    try {
        const status = await refreshDriveStatus(selected);
        if (generation !== pollGeneration) return;
        if (!status.configured) throw new Error("后台尚未配置此网盘,请在服务器设置应用凭据");
        if (!status.authorized) throw new Error("当前网盘未授权,请使用“授权当前网盘”菜单");
        const url = previous?.url || item.url;
        const retry = Boolean(previous?.id && previous.state === "failed");
        pending = {id: previous?.id || null, url, state: "unknown", error: null};
        // Persist before sending: a lost response must never turn a reload into a new submission.
        await saveCloudJob(selected, item.key, pending);
        if (generation !== pollGeneration) return;
        const data = await cloudRequest(selected, "/api/jobs", "POST", {url, provider: selected.provider, retry});
        if (typeof data.id === "string" && /^[a-f0-9]{32}$/.test(data.id)) {
            if (pending.id && pending.id !== data.id) throw new Error("后台返回的任务不匹配,保留现有任务等待查询");
            pending.id = data.id;
            await saveCloudJob(selected, item.key, pending);
        }
        const job = checkedJob(data, selected);
        await saveCloudJob(selected, item.key, {...job, url});
        finished = job.state === "finished";
    } catch (error) {
        if (pending) await saveCloudJob(selected, item.key, {...pending, error: error.message});
        if (generation === pollGeneration) {
            Swal.fire({icon: "error", title: pending ? "任务状态未知,请点击查询" : "发送失败", text: error.message});
        }
    } finally {
        cloudBusy.delete(lock);
        redraw();
    }
    if (finished && generation === pollGeneration) {
        await data_update(selected).catch(() => {});
        redraw();
    }
}

async function pollJobs(selected, generation, refresh = false) {
    let finished = false;
    for (const [key, job] of Object.entries(cloudState(selected).jobs)) {
        if (generation !== pollGeneration) return;
        if (!job.id || (!refresh && ["finished", "failed"].includes(job.state))) continue;
        if (await queryCloudJob(selected, key)) finished = true;
    }
    if (generation !== pollGeneration) return;
    if (finished) await data_update(selected).catch(() => {});
    if (generation !== pollGeneration) return;
    redraw();
    pollTimer = setTimeout(() => pollJobs(selected, generation), 3000);
}



async function lanraragi_download(url, btn, p) {
    const config = readObject("config");
    const generation = pollGeneration;
    const formData = new FormData();
    formData.append("url", url);
    btn.disabled = true;
    btn.textContent = "🔄 正在发送到LANraragi";
    const fail = message => {
        if (generation !== pollGeneration) return;
        btn.textContent = message;
        btn.disabled = false;
    };
    legacyRequest = GM_xmlhttpRequest({
        method: "POST",
        url: `${config.lanraragi_api}/api/download_url`,
        data: formData,
        headers: {"Authorization": `Bearer ${btoa(config.lanraragi_token)}`},
        timeout: 10000,
        onload(res) {
            legacyRequest = null;
            if (generation !== pollGeneration) return;
            if (res.status !== 200) {
                fail(res.status === 401 ? "❌ token错误" : "❌ 请求失败,点击重试");
                if (res.status !== 401) {
                    const message = document.createElement("p");
                    message.textContent = res.responseText;
                    message.className = "g2 gsp";
                    p.appendChild(message);
                }
                return;
            }
            let data;
            try { data = JSON.parse(res.responseText); } catch { fail("❌ 后台响应格式错误"); return; }
            if (!data || !["string", "number"].includes(typeof data.job) || !/^[a-zA-Z0-9_-]+$/.test(String(data.job))) {
                fail("❌ 后台未返回任务编号");
                return;
            }
            btn.textContent = "🔄 已发送到LANraragi";
            function checkJob() {
                if (generation !== pollGeneration) return;
                legacyRequest = GM_xmlhttpRequest({
                    method: "GET",
                    url: `${config.lanraragi_api}/api/minion/${data.job}`,
                    timeout: 10000,
                    onload(res) {
                        legacyRequest = null;
                        if (generation !== pollGeneration) return;
                        let job;
                        try { job = JSON.parse(res.responseText); } catch { fail("❓ 任务查询失败"); return; }
                        if (res.status !== 200 || !job || typeof job.state !== "string") { fail("❓ 任务查询失败"); return; }
                        if (job.state === "finished") {
                            btn.textContent = "✅ 下载完成";
                            lanraragi_data_update().then(redraw).catch(() => {});
                        } else if (job.state === "failed") {
                            fail("❌ 下载失败,点击重试");
                        } else {
                            pollTimer = setTimeout(checkJob, 3000);
                        }
                    },
                    onerror: () => fail("❓ 任务查询失败"),
                    ontimeout: () => fail("❓ 任务查询超时")
                });
            }
            checkJob();
        },
        onerror: () => fail("❓ 网络请求失败"),
        ontimeout: () => fail("❓ 请求超时")
    });
}

window.addEventListener("pagehide", stopPolling);
window.addEventListener("pageshow", event => { if (event.persisted) activateBackend(); });
activateBackend();