百度网盘不限速下载-KDown🔥🔥🔥

一款百度云加速程序,加速永无止境,无视黑号

// ==UserScript==
// @name         百度网盘不限速下载-KDown🔥🔥🔥
// @namespace    https://kdown.moiu.net
// @description  一款百度云加速程序,加速永无止境,无视黑号
// @version 1.3.5
// @license      MIT
// @icon https://upload.moiu.net/MoTeam-CDN-img/logo.png
// @resource https://cdn.staticfile.org/limonte-sweetalert2/11.7.1/sweetalert2.min.css
// @require https://cdn.jsdelivr.net/npm/sweetalert2@11.12.2/dist/sweetalert2.all.min.js
// @require https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @grant        GM_setClipboard
// @match        *://pan.baidu.com/*
// @match        *://yun.baidu.com/*
// @match        *://pan.baidu.com/disk/home*
// @match        *://yun.baidu.com/disk/home*
// @match        *://pan.baidu.com/disk/main*
// @match        *://yun.baidu.com/disk/main*
// @match        *://pan.baidu.com/s/*
// @match        *://yun.baidu.com/s/*
// @match        *://pan.baidu.com/share/*
// @match        *://yun.baidu.com/share/*
// @connect      moiu.cn
// @connect      jsdelivr.net
// @connect      baidu.com
// ==/UserScript==

(() => {
    // 在页面加载时立即调用GetNotify函数
    GetNotify();

    if (window.location.pathname === "/disk/home") {
        window.location.replace("/disk/main");
    }

    AddElement();

    function GetNotify() {
        GM_xmlhttpRequest({
            method: "GET",
            url: "https://api.moiu.cn/JavaScript/user/info",
            onload: function(response) {
                try {
                    const jsondata = JSON.parse(response.responseText);
                    // 假设返回的jsondata格式和您示例中的相同
                    const { code, message, ua, gg, open } = jsondata;

                    // 确保公告是打开状态
                    if (open === 1 && code === 200) {
                        Swal.fire({
                            icon: "info",
                            title: gg, // 使用公告标题
                            text: message, // 使用公告信息
                            confirmButtonText: "关闭",
                        });
                    }
                } catch (e) {
                    console.error("Error fetching announcement:", e);
                }
            },
        });
    }

    // 存储用户信息
    let userInfo = {};

    // 获取用户信息
    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);
                }
            });
        });
    }

    // 在页面加载完成后请求用户信息
    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("KDown") === null) {
            const toolbar = document.querySelector("div.wp-s-agile-tool-bar__header");
            if (toolbar) {
                const newButton = document.createElement("button");
                newButton.id = "KDown";
                newButton.className = "u-button nd-file-list-toolbar-action-item u-button--primary";
                newButton.style.marginRight = "8px";
                newButton.innerText = "KDown";
                toolbar.prepend(newButton);

                const statusButton = document.createElement("button");
                statusButton.id = "KDownStatus";
                statusButton.className = "u-button nd-file-list-toolbar-action-item u-button--primary";
                statusButton.style.marginRight = "8px";
                statusButton.innerText = "KDown Status";
                toolbar.prepend(statusButton);

                newButton.addEventListener("click", handleKDownClick);
                statusButton.addEventListener("click", handleKDownStatusClick);
            } else {
                setTimeout(AddElement, 100);
            }
        } else {
            console.log("KDown button already added.");
        }
    }

    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";
            const formParams = {
                "surl": shorturl,
                "dir": "/",
                "password": password,
                "pwd": bdpassword
            };

            $.ajax({
                type: "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, // 提取第一个列表项的 size 属性
        };
    }

    function postToSaveApi(data, password, userid) {
        const requestData = {
            fsidlist: JSON.stringify(data.list.map(item => item.fs_id)), // 将 fsidlist 转换为 JSON 字符串
            sekey: data.randsk,
            uk: data.uk,
            shareid: data.shareid,
            password,
            userid,
            size: data.size // 将提取到的 size 作为参数提交
        };

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

        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: "POST",
                url: "https://api.moiu.cn/JavaScript/users/save",
                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);
                    }
                },
                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
                    });
                }
            });
        });
    }

    function postToDlinkApi(to_fs_id, shareid, surl, password, userid, size) {
        const requestData = {
            fsidlist: JSON.stringify([to_fs_id]), // 将 to_fs_id 转换为 JSON 字符串数组
            shareid,
            surl,
            password,
            userid, // 添加 userid 参数
            size // 添加 size 参数
        };
        console.log("Posting to Dlink API with data:", requestData);

        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: "POST",
                url: "https://api.moiu.cn/JavaScript/users/dlink",
                headers: {
                    "Content-Type": "application/json"
                },
                data: JSON.stringify(requestData),
                onload: function(response) {
                    const responseData = JSON.parse(response.responseText);
                    console.log("Dlink API response:", responseData);
                    if (responseData.code !== 200) {
                        Swal.fire("错误", responseData.message, "error");
                        reject({
                            status: response.status,
                            statusText: responseData.message
                        });
                    } else {
                        resolve(responseData.data.dlink);
                    }
                },
                onerror: function(response) {
                    const errorMessage = JSON.parse(response.responseText).message || '网络错误';
                    Swal.fire("错误", errorMessage, "error");
                    console.error("Error posting to Dlink API:", response);
                    reject({
                        status: response.status,
                        statusText: errorMessage
                    });
                }
            });
        });
    }

    async function handleKDownClick() {
        console.log("KDown 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: '输入在QQ群中公告密码,群在脚本简介可以看到',
            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, userInfo.uk);

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

            const toFsIdList = saveResponseData.map(item => item.to_fs_id);
            const dlinkPromises = toFsIdList.map(to_fs_id => postToDlinkApi(to_fs_id, extractedData.shareid, shorturl, password, userInfo.uk, extractedData.size));

            const downloadLinks = await Promise.all(dlinkPromises);

            const ua = window.userAgent;

            Swal.fire({
                icon: 'success',
                title: '下载链接获取成功',
                html: downloadLinks.map(link => `
                    <div style="border: 1px solid #ddd; padding: 10px; margin-bottom: 10px;">
                        <a href="${link}" target="_blank">下载链接:${link.substring(0, 50)}...</a>
                    </div>
                `).join('') +
                `<div style="border: 1px solid #ddd; padding: 10px; margin-top: 10px;">UA: Mozilla/5.0 (KDown;mf;javascript)</div>`,
                showCancelButton: true,
                cancelButtonText: '取消',
                confirmButtonText: '复制链接',
                showDenyButton: true,
                denyButtonText: '发送到 Aria2',
                preConfirm: async () => {
                    try {
                        await navigator.clipboard.writeText(downloadLinks.join('\n'));
                        Swal.fire("已复制", "下载链接已复制到剪贴板", "success");
                    } catch (err) {
                        console.error("Failed to copy: ", err);
                        Swal.fire("复制失败", "无法将链接复制到剪贴板", "error");
                    }
                }
            }).then((result) => {
                if (result.isDenied) {
                    sendToAria2(downloadLinks);
                }
            });

        } 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: Mozilla/5.0 (KDown;mf;javascript)']
                }
            ]
        };

        fetch("http://127.0.0.1:16800/jsonrpc", {
            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);
            });
    }

    async function handleKDownStatusClick() {
        Swal.fire("检查中...", "正在检查服务器状态,请稍候...", "info");
        GM_xmlhttpRequest({
            method: "GET",
            url: "https://api.moiu.cn/JavaScript/users/status",
            onload: function(response) {
                try {
                    const data = JSON.parse(response.responseText);
                    const { code, message } = data;
                    console.log("Server status response:", data);
                    if (code === 200) {
                        Swal.fire({
                            icon: "success",
                            title: "服务器状态",
                            text: message,
                        });
                    } else if (code === 201) {
                        Swal.fire({
                            icon: "error",
                            title: "服务器状态",
                            text: message,
                        });
                    } else {
                        Swal.fire({
                            icon: "warning",
                            title: "服务器状态",
                            text: "未知状态",
                        });
                    }
                } catch (error) {
                    Swal.fire("错误", "处理服务器响应时发生错误", "error");
                    console.error("Error handling server response:", error);
                }
            },
            onerror: function(error) {
                Swal.fire("错误", "无法连接到服务器", "error");
                console.error("Error connecting to server:", error);
            },
        });
    }

    // 在页面加载完成后请求用户信息
    getUserInfoOnPageLoad();
})();