Greasy Fork

百度网盘不限速下载-QHY-Down

一款百度网盘不限速解析脚本,搭配下载器不限速下载,好用就完事了!

目前为 2024-08-08 提交的版本。查看 最新版本

// ==UserScript==
// @name         百度网盘不限速下载-QHY-Down
// @namespace    https://qhy6.cn/help.php
// @description  一款百度网盘不限速解析脚本,搭配下载器不限速下载,好用就完事了!
// @version 0.3
// @license      MIT
// @author       MoTeam-Top、QHY-Down
// @icon https://pic.imge.cc/2024/08/03/66adb23a8e763.jpg
// @resource https://cdn.staticfile.org/limonte-sweetalert2/11.7.1/sweetalert2.min.css
// @require https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.all.min.js
// @require https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @grant        GM_setClipboard
// @match        *://pan.baidu.com/disk/home*
// @match        *://yun.baidu.com/disk/home*
// @match        *://pan.baidu.com/disk/main*
// @match        *://yun.baidu.com/disk/main*
// @connect      moiu.cn
// @connect      jsdelivr.net
// @connect      baidu.com
// 本代码由KDown原作者XiaoMo授权给QHY-Down,请管理大大手下留情
// ==/UserScript==

(() => {
//获取按钮状态
    if (window.location.pathname === "/disk/home") {
        window.location.replace("/disk/main");
    }

    AddElement();

    let userInfo = {};
//执行get请求
    function fetchUserInfo() {
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: "GET",
                url: "https://pan.baidu.com/rest/2.0/membership/user/info?method=query&clienttype=0&app_id=250528",
                onload: function(response) {
                    try {
                        const data = JSON.parse(response.responseText);
                        resolve(data.user_info);
                    } catch (error) {
                        reject(error);
                    }
                },
                onerror: function(error) {
                    reject(error);
                }
            });
        });
    }
//请求成功显示QHY-Down
    async function getUserInfoOnPageLoad() {
        try {
            const data = await fetchUserInfo();
            userInfo = data;
            console.log("User info fetched on page load:", userInfo);
        } catch (error) {
            console.error("Error fetching user info on page load:", error);
        }
    }
//获取请求成功显示按钮
    function AddElement() {
        if (document.getElementById("QHY-Down") === null) {
            const toolbar = document.querySelector("div.wp-s-agile-tool-bar__header");
            if (toolbar) {
                const newButton = document.createElement("button");
                newButton.id = "QHY-Down";
                newButton.className = "u-button nd-file-list-toolbar-action-item u-button--primary";
                newButton.style.marginRight = "8px";
                newButton.style.backgroundColor = "red"; //红
                newButton.style.color = "white"; //白
                newButton.innerText = "QHY-Down";
                toolbar.prepend(newButton);

                newButton.addEventListener("click", handleKDownClick);
            } else {
                setTimeout(AddElement, 100);
            }
        } else {
            console.log("QHY-Down button already added.");
        }
    }
//点击QHY-Down执行解析操作
    async function getBdsToken() {
        var htmlString = $("html").html();
        var regex = /"bdstoken":"(\w+)"/;
        var match = regex.exec(htmlString);
        console.log("bdstoken:", match ? match[1] : null);
        return match ? match[1] : null;
    }
//判定解析密码是否正确
    async function shareFiles(bdstoken, selectedIds) {
        const bdpassword = "7777";
        console.log("Sharing files with bdstoken:", bdstoken, "selectedIds:", selectedIds, "bdpassword:", bdpassword);
        return $.post("https://pan.baidu.com/share/set?channel=chunlei&bdstoken=" + bdstoken, {
            period: 1,
            pwd: bdpassword,
            eflag_disable: true,
            channel_list: "[]",
            schannel: 4,
            fid_list: JSON.stringify(selectedIds)
        }).then(response => response);
    }
//检测是否为度盘链接
    function extractShortUrl(link) {
        const regex = /https:\/\/pan\.baidu\.com\/s\/([a-zA-Z0-9-_]+)/;
        const match = regex.exec(link);
        console.log("Extracted short URL:", match ? match[1] : null);
        return match ? match[1] : null;
    }

    function callWxlistApi(shorturl, password) {
        console.log("Calling Wxlist API with shorturl:", shorturl, "password:", password);
        const bdpassword = "7777";
        return new Promise((resolve, reject) => {
            const url = "https://api.moiu.cn/api/List";
            //调用xiaomo接口
            const formParams = {
                "surl": shorturl,
                "dir": "/",
                "password": password,
                "pwd": bdpassword
            };

            $.ajax({
                type: "POST",
//post请求检测属性
                url: url,
                data: formParams,
                success: function(response) {
                    console.log("Wxlist API response:", response);
                    resolve(response);
                },
                error: function(xhr, status, error) {
                    console.error("Error calling Wxlist API:", xhr, status, error);
                    reject({
                        status: xhr.status,
                        statusText: xhr.statusText
                    });
                }
            });
        });
    }

    function extractWxlistData(responseBody) {
        const data = responseBody.data;
        console.log("Extracted data from Wxlist response:", data);
        return {
            uk: data.uk,
            shareid: data.shareid,
            randsk: data.randsk,
            list: data.list,
            fsidlist: data.list.map(item => item.fs_id.toString()),
            size: data.list[0]?.size || 0,
        };
    }

    function postToSaveApi(data, password) {
        const requestData = {
            fsidlist: JSON.stringify(data.list.map(item => item.fs_id)),
            sekey: data.randsk,
            uk: data.uk,
            shareid: data.shareid,
            password,
            size: data.size
        };

        console.log("Prepared request data for Save API:", requestData);

        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: "POST",
                url: "https://api.moiu.cn/qhy/api/parse",
                //调用所授权的QHY-Down接口
                headers: {
                    "Content-Type": "application/json"
                },
                data: JSON.stringify(requestData),
                onload: function(response) {
                    const responseData = JSON.parse(response.responseText);
                    console.log("Save API response:", responseData);
                    if (responseData.code !== 200) {
                        Swal.fire("错误", responseData.message, "error");//检测错误值
                        reject({
                            status: response.status,
                            statusText: responseData.message
                        });
                    } else {
                        resolve(responseData.data); // 返回data对象值
                    }
                },
                onerror: function(response) {
                    const errorMessage = JSON.parse(response.responseText).message || '网络错误';
                    Swal.fire("错误", errorMessage, "error");
                    console.error("Error posting to Save API:", response);
                    reject({
                        status: response.status,
                        statusText: errorMessage
                    });
                }
            });
        });
    }

    let currentLinkIndex = 0;
    let downloadLinks = [];

    async function handleKDownClick() {
        console.log("QHY-Down button clicked.");
        let selectedElements = document.querySelectorAll(".wp-s-pan-table__body-row.mouse-choose-item.selected, .wp-s-file-grid-list__item.text-center.cursor-p.mouse-choose-item.is-checked, .wp-s-file-contain-list__item.text-center.cursor-p.mouse-choose-item.is-checked");
        let selectedIds = Array.from(selectedElements).map(item => item.getAttribute("data-id"));

        console.log("Selected elements:", selectedElements);
        console.log("Selected IDs:", selectedIds);

        if (selectedIds.length === 0) {
            Swal.fire({
                showConfirmButton: true,
                title: '系统提示',
                text: '请选择需要解析下载的文件',
                icon: 'error'
            });
            return;
        }

        if (selectedIds.length > 1) {
            Swal.fire({
                showConfirmButton: true,
                title: '系统提示',
                text: '一次暂时只能解析单个文件哦',
                icon: 'error'
            });
            return;
        }

        let selectedItems = Array.from(selectedElements);
        if (selectedItems.some(item => item.dataset.isdir === "true") || $('tr.selected img[src*="ceH8M5EZYnGhnBKRceGqmaZXPPw2xbO+1x"]').length > 0) {
            Swal.fire({
                title: '系统提示',
                text: '暂不支持文件夹解析,请选择文件再解析',
                icon: 'error'
            });
            return;
        }

        const { value: password } = await Swal.fire({
            title: '输入解析密码',
            input: 'password',
            inputLabel: '解析密码在群公告834936379获取',
            inputPlaceholder: '解析密码是为了控制下载流量,希望大家理解',
            inputAttributes: {
                maxlength: 30,
                autocapitalize: 'off',
                autocorrect: 'off'
            }
        });

        if (!password) {
            Swal.fire("提示", "需要输入解析密码解析哦", "info");
            return;
        }

        Swal.fire({
            title: "正在获取下载链接...",
            onBeforeOpen: () => {
                Swal.showLoading();
            }
        });

        const bdstoken = await getBdsToken();
        if (!bdstoken) {
            Swal.fire("错误", "无法获取bdstoken参数", "error");
            return;
        }

        if (!userInfo.uk) {
            try {
                userInfo = await fetchUserInfo();
                console.log("Fetched user info in handleKDownClick:", userInfo);
            } catch (error) {
                Swal.fire("错误", "无法获取用户信息参数", "error");
                return;
            }
        }

        const shareResponse = await shareFiles(bdstoken, selectedIds);
        const shorturl = extractShortUrl(shareResponse.link);

        if (!shorturl) {
            Swal.fire("错误", "无法提取shorturl参数", "error");
            return;
        }

        try {
            const wxlistResponse = await callWxlistApi(shorturl, password);
            const extractedData = extractWxlistData(wxlistResponse);

            console.log("Extracted Wxlist Data:", extractedData);

            if (!extractedData.randsk) {
                console.error("randsk is undefined in extracted data");
                Swal.fire("错误", "无法提取 randsk参数", "error");
                return;
            }

            const saveResponseData = await postToSaveApi(extractedData, password);

            console.log("Save API Response Data:", saveResponseData);

            downloadLinks = [saveResponseData.dlink, ...saveResponseData.urls]; // 获取下载链接
            currentLinkIndex = 0;

            const showDownloadLink = () => {
                Swal.fire({
                    icon: 'success',
                    title: '下载链接获取成功',
                    html: `
                        <div style="border: 1px solid #ddd; padding: 10px; margin-bottom: 10px;">
                            <a href="${downloadLinks[currentLinkIndex]}" target="_blank">下载链接:${downloadLinks[currentLinkIndex].substring(0, 50)}...</a>
                        </div>
                        <div style="border: 1px solid #ddd; padding: 10px; margin-top: 10px;">当前的UA: netdisk;qhynb</div>
                    `,
                    showCancelButton: true,
                    cancelButtonText: '取消',
                    confirmButtonText: '复制当前下载链接',
                    showDenyButton: true,
                    denyButtonText: '发送到 Aria2',
                    footer: '<button id="ChangeLink" class="swal2-deny">更换下载链接</button>',
                    preConfirm: async () => {
                        try {
                            await navigator.clipboard.writeText(downloadLinks[currentLinkIndex]);
                            Swal.fire("已复制", "下载链接已复制", "success");
                        } catch (err) {
                            console.error("Failed to copy: ", err);
                            Swal.fire("复制失败", "复制失败,无法复制", "error");
                        }
                    }
                }).then((result) => {
                    if (result.isDenied) {
                        sendToAria2([downloadLinks[currentLinkIndex]]);
                    }
                });

                document.getElementById("ChangeLink").addEventListener("click", () => {
                    if (currentLinkIndex < downloadLinks.length - 1) {
                        currentLinkIndex++;
                        showDownloadLink();
                    }
                    if (currentLinkIndex === downloadLinks.length - 1) {
                        document.getElementById("ChangeLink").disabled = true;
                        document.getElementById("ChangeLink").innerText = "没有更多下载链接";
                    }
                });
            };

            showDownloadLink();

        } catch (error) {
            Swal.fire("错误", error.statusText || "处理过程中出现系统错误", "error");
            console.error("Error:", error);
        }
    }

    function sendToAria2(downloadLinks) {
        const aria2Config = {
            jsonrpc: "2.0",
            method: "aria2.addUri",
            id: Date.now(),
            params: [
                `token:`,
                downloadLinks,
                {
                    header: ['User-Agent: netdisk;qhynb']
                    //千幻云默认下载User-Agent
                }
            ]
        };

        fetch("http://127.0.0.1:6800/jsonrpc", {
        // 默认监听端口设置为6800
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(aria2Config)
        })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    console.error("Aria2 Error:", data.error.message);
                } else {
                    console.log("Aria2 Download Added:", data.result);
                }
            })
            .catch(fetchError => {
                console.error("Fetch Error:", fetchError);
            });
    }

    // 本代码由KDown原作者XiaoMo授权给QHY-Down,管理大大手下留情
    getUserInfoOnPageLoad();
})();