EH_lanraragi_dl

发送 EH 本子到 LANraragi进行下载

이 스크립트를 설치하려면 Tampermonkey, Greasemonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey와 같은 확장 프로그램을 설치해야 합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Userscripts와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 유저 스크립트 관리자 확장 프로그램이 필요합니다.

(이미 유저 스크립트 관리자가 설치되어 있습니다. 설치를 진행합니다!)

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

(이미 유저 스타일 관리자가 설치되어 있습니다. 설치를 진행합니다!)

// ==UserScript==
// @name         EH_lanraragi_dl
// @namespace    魔皇地狱
// @version      0.1.1
// @description 发送 EH 本子到 LANraragi进行下载
// @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

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

GM_registerMenuCommand("⚙️ 设置", async () => {
    const config = GM_getValue("config");

    Swal.fire({
        title: "设置",
        html: `
            <input id="lanraragi_api" class="swal2-input" value="${config.lanraragi_api ?? ""}" placeholder="lanraragi API">
            <input id="lanraragi_token" class="swal2-input" value="${config.lanraragi_token ?? ""}" placeholder="lanraragi Token">
            <br>
            <label>
                <strong>主页查看是否下载<input id="homepage" type="checkbox"></strong>
            </label>
        `,
        showCancelButton: true,
        preConfirm: () => ({
            lanraragi_api: document.getElementById("lanraragi_api").value,
            lanraragi_token: document.getElementById("lanraragi_token").value,
            homepage: document.getElementById("homepage").checked
        })
    }).then(async (result) => {
        if (result.isConfirmed) {
            await GM_setValue("config", result.value);
        }
    });
});
GM_registerMenuCommand("手动更新数据库", async () => {
    await lanraragi_data_update();
})

let url = window.location.href;
url = new URL(url);
console.log(url);
const parts = url.pathname.split("/").filter(Boolean);
if (url.hostname === "e-hentai.org" || url.hostname === "exhentai.org") {
    const config = GM_getValue("config");
    if (!sessionStorage.getItem("script_loaded") || sessionStorage.getItem("script_loaded") === "0") {
        sessionStorage.setItem("script_loaded", "0");
        // 第一次访问执行
        console.log("第一次打开");
        if (config.lanraragi_api && config.lanraragi_token) {
            (async () => {
                const a = await lanraragi_data_update();
                if (a) {
                    sessionStorage.setItem("script_loaded", "1");
                }
            })();
        }
    }
    if (parts && parts[0] === "g") {
        if (config.lanraragi_api && config.lanraragi_token) {
            const p = document.createElement("p");
            p.className = "g2 gsp";

            const btn = document.createElement("button");
            btn.id = "lanraragi";
            btn.onclick = () => {
                console.log(`将要开始下载${url.href}`);
            };
            btn.addEventListener("click", () => {
                lanraragi_download(url.href, btn, p)
            });
            p.appendChild(btn);

            const gid_list = GM_getValue("gid_list");
            const title_list = GM_getValue("title_list");
            if (gid_list.includes(parts[2]) || title_list.includes(document.querySelector("#gj").textContent) || title_list.includes(document.querySelector("#gn").textContent)) {
                btn.disabled = true;
                btn.textContent = "✅️ 已存在"
            } else {
                btn.textContent = "⬇️ 点击发送到lanraragi"
            }
            document.querySelector("#gd5").appendChild(p);
        }
    } else if (config.homepage) {
        console.log("homepage识别")
        const gid_list = JSON.parse(
            GM_getValue("gid_list") || "[]"
        );
        const title_list = JSON.parse(
            GM_getValue("title_list") || "[]"
        );
        if (document.querySelector(".itg.gld")) {
            console.log("存在homepage")
            const gl1t = document.querySelector(".itg.gld").querySelectorAll(".gl1t");
            for (const x of gl1t) {
                const a = x.querySelector("a");
                if (a) {
                    const url = new URL(a.href);
                    const parts1 = url.pathname.split("/").filter(Boolean);
                    let div = null;
                    if (parts[0] === "favorites.php") {
                        div = a.querySelector("span");
                    } else {
                        div = a.querySelector(".gl4t.glname.glink");
                    }
                    if (gid_list.includes(parts1[1]) || title_list.includes(div.textContent)) {
                        div.textContent = `✅ ${div.textContent}`;
                    } else {
                        div.textContent = `❌ ${div.textContent}`;
                    }
                }
            }
        } else if (document.querySelector(".itg.gltc")) {
            console.log("存在homepage")
            const tr = document.querySelector(".itg.gltc").querySelectorAll("tr");
            for (const x of tr) {
                const a = x.querySelector("td.gl3c.glname a");
                if (a) {
                    const url = new URL(a.href);
                    const div = a.querySelector("div.glink");
                    if (gid_list.includes(parts[1]) || title_list.includes(div.textContent)) {
                        div.textContent = `✅ ${div.textContent}`;
                    } else {
                        div.textContent = `❌ ${div.textContent}`;
                    }
                }
            }
        }
    }
}

async function lanraragi_data_update() {
    const config = GM_getValue("config");
    GM_xmlhttpRequest({
        method: "GET",
        url: `${config.lanraragi_api}/api/archives`,
        timeout: 10000, // 10 秒
        onload(res) {
            console.log(res.status);
            const data = JSON.parse(res.responseText);
            const gid_list = [];
            const title_list = [];
            for (const x of data) {
                title_list.push(x.title)
                for (const y of x.tags.split(",")) {
                    if (y.includes("source")) {
                        let url1 = y.split(":")[1];
                        if (!/^https?:\/\//i.test(url1)) {
                            url1 = "https://" + url1;
                        };
                        url1 = new URL(url1)
                        if (url1.hostname === "exhentai.org" || url.hostname === "e-hentai.org") {
                            gid_list.push(url1.pathname.split("/")[2])
                        }
                        break
                    }
                }
            }
            GM_setValue(
                "gid_list",
                JSON.stringify(gid_list)
            )
            GM_setValue(
                "title_list",
                JSON.stringify(title_list)
            )
            console.log("存储lanraragi")
            console.log(gid_list)
            console.log(title_list)
        }
    })
    return true
}

async function lanraragi_download(url, btn, p) {
    const config = await GM_getValue("config", {});
    const formData = new FormData();
    formData.append("url", url);
    GM_xmlhttpRequest({
        method: "POST",
        url: `${config.lanraragi_api}/api/download_url`,
        data: formData,
        headers: {
            "Authorization": `Bearer ${btoa(config.lanraragi_token)}`
        },
        onload(res) {
            console.log(res.status, res.responseText);
            const data = JSON.parse(res.responseText);
            if (res.status === 200) {
                btn.textContent = "🔄 已发送到LANraragi";
                btn.disabled = true;
                function checkJob() {
                    GM_xmlhttpRequest({
                        method: "GET",
                        url: `${config.lanraragi_api}/api/minion/${data.job}`,
                        onload(res) {
                            if (res.status !== 200) return;

                            const job = JSON.parse(res.responseText);

                            if (job.state === "finished") {
                                btn.textContent = "✅ 下载完成";
                            } else {
                                setTimeout(checkJob, 3000);
                            }
                        }
                    });
                }
                checkJob();
                (async () => {
                    await lanraragi_data_update();
                })();
            } else if (res.status === 400) {
                btn.textContent = "❌ 请求错误";
                const t = document.createElement("p");
                t.textContent = res.responseText;
                t.className = "g2 gsp"
                p.appendChild(t);
            } else if (res.status === 401) {
                btn.textContent = "❌ token错误";
            } else {
                btn.textContent = "❌ 未知错误";
                const t = document.createElement("p");
                t.textContent = res.responseText;
                t.className = "g2 gsp"
                p.appendChild(t);
            }
        }
    });

}