wuxingsanren / 百度网盘神迹FAST Down直链下载助手🚀 - 不限速神器

// ==UserScript==
// @name         百度网盘神迹FAST Down直链下载助手🚀 - 不限速神器
// @namespace    FastPan Accelerator
// @description  一款强大的百度网盘直链获取和高速下载助手。支持IDM、Aria2、Motrix三种方式极速下载,完全不限制下载速度。无视黑号,支持Chrome✔、Edge✔、Firefox✔等主流浏览器。适配官方网盘界面,长期维护更新。针对所有用户免费开放,持续优化中。让您畅享FAST极速下载体验!
// @version      v6.2.7
// @author       FastPan Accelerator
// @require      https://lib.baomitu.com/jquery/3.6.0/jquery.js
// @require      https://lib.baomitu.com/sweetalert/2.1.2/sweetalert.min.js
// @require      https://lib.baomitu.com/clipboard.js/2.0.6/clipboard.min.js
// @supportURL   http://yemao.in/wangpan
// @match        *://pan.baidu.com/*
// @match        *://yun.baidu.com/*
// @run-at       document-idle
// @grant        GM_addStyle
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_notification
// @grant        GM_xmlhttpRequest
// @grant        GM_getResourceURL
// @grant        GM_openInTab
// @connect      github.com
// @connect      gitee.com
// @connect      baidu.com
// @connect      fast.blog
// @iconURL      https://pan.baidu.com/box-static/disk-header/header/img/user-level2.png
// @resource     premiumIcon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMQAAACdCAMAAADc+SdmAAAC/VBMVEUAAABOQBRQPxa6oFpNQRpqWSWnklB0YC3Wu1uGdDvOtV3cvVvZuV6EcziDbjfbvmC4oFi2nFnTt2W7olvcwWXYvGS4olnbuFDVtlbZv2LRuWixm1XfwGnErF2znliplVCVgkWejEm/plnKsGKmkUzSuFbXuVzFq2GZhkXXvmrNs2PRslDWumDFr2CUgUTjwWi3nFO1m1XPuWKDcjv11nzhuEb11n/z13vz1XvcuEXeuUjgt0XeuUXft0jhuUT113rduEjeuU7y137euEv11H3y2Xvht0rz1X3x13rz1XfiuUny1Ho9Oi7x14D22H331Xrgt0Tct03htk09Oyv11YLetkTft0HhuUFBOS5BOSvbtks9PCZC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Se5NLjCOnB4O8+IDOscDkMgmTky6w8VQHGlg+tcIKR6CsughHySu+Ag1dWhYTOp6Danffobw95d36BwukMgmUlxyx+ThLVsc/f1CJwOltVj0pvLjMR+tgHnpWadrxjlJKhSSa6wiTu8yodbBKUjNfrvFQWfREs4JwXIWhzRtSermzc+mSdF4ReHB/wcFChqnxvTA1KsvmmhxyXW3hdBsKSy4+IiQDyglV6HXSE0FLSZ9crIQtysL3ZNsKBlN9/Z2zLhlYu2lUYo5LnZODgiO7H0Rcqk4uUGv0RslJ04wNP+TfwQF8jfczwkzZk20vTTmVpsmTUiv4yKL4YxOT5eQBzgH91gWIyM//LCcjHWHh2cl+8fp7VdMuPPwy46abK/L4hxoFjPk+MLZAB0kHEmJEyKjNzwhC7+bJi13nZB76WdBapeV2WU0d2R0B4qIPZrC3uITEtgcOHIoktt0yUNT4CKbuHHpdS5au3moLicDWhhFNGdkSJyQ5HuU3ADpno4s7TC/OoHXwSmaTy4YWrPmVE4t7HYiodkux283yhgMKIkAoQFEsWzvzRObgfgfZ6f1J1iVkYBYDgiqNtLfH1pfIFbCgMvVUe5y7UTeS2MUk/XJHdABIotZ1izxW46+KLYRblYDrlba5HrzxGfgKUwOjjM4f5YXEBSF/oOcQLDh5ivuOB8YiP9xZkvygM6id1AD3SwlgglLycWhFaBVjtwDt/f5EZfeOdmekEW3lrOnBghEQjilHCweUTpMrhP6bv3DWtT1Z1mtusABiiHTQJzSarXWb5gMN995FHfOfJXWidrqk+uJTU1aUZGT1T9013WXXHRexU2z1ju0zJBZCNeBadhgONW/Ydqc82odSFx5vWuB3R5CnHbwTZt23TMLcut5F5Pm3Oti0st2nTDCJaW//fqJmrb+lcY5Z+r0yVOuuMJl9r3XXH2eHYdfF61XPnzn5Zfff/Vl5+FOuhAX4kJciAtxIS7Ehfh/xk8iyx1tv5/bhwAAAABJRU5ErkJggg==
// @compatible   Chrome
// @compatible   Safari
// @compatible   Edge
// @compatible   Firefox
// @compatible   Opera
// @license      Apache-2.0
// ==/UserScript==

const truncateString = (input, maxLength, ellipsis = '...') => {
    if (!input || maxLength <= 0) return '';

    let byteCount = 0;
    let truncatedIndex = input.length;

    for (let i = 0; i < input.length; i++) {
        byteCount += input.charCodeAt(i) > 255 ? 2 : 1;
        if (byteCount > maxLength) {
            truncatedIndex = i;
            break;
        }
    }

    return truncatedIndex === input.length
        ? input
        : input.slice(0, truncatedIndex) + ellipsis;
};
 
const recordInitialTimestamp = (response) => {
    const existingTimestamp = dataStore.retrieveSharedData('initialTime');
    if (existingTimestamp) {
        return null;
    }
    const currentTimestamp = Date.now();
    dataStore.storeSharedData('initialTime', currentTimestamp);
};

const generateRandomIdentifier = (length = 6) => {
    const characterSet = 'BCFHKMQRVWbcfhkmqrvw369';
    const setSize = characterSet.length;
    let identifier = '';
    for (let i = 0; i < length; i++) {
        const randomIndex = Math.floor(Math.random() * setSize);
        identifier += characterSet[randomIndex];
    }
    return identifier;
};
 
(function () {
 
       const checkLegacyInterface = () => {
           const currentURL = window.location.href;
           return currentURL.includes(".baidu.com/disk/home");
       };
 
        const verifyModernDashboard = () => {
            const currentURL = window.location.href;
            return currentURL.includes(".baidu.com/disk/main");
        };
 
        const detectSharingEnvironment = () => {
            const cleanPath = window.location.pathname.slice(5);
            return /^(s|share)\//.test(cleanPath);
        };
 
 
    if (self !== top) {
        return;
 
    }
 
    if (window.location.href.match(/yun\.baidu\.com/)) {
        window.location.href = window.location.href.replace(/yun\.baidu\.com/, 'pan.baidu.com');
        return;
    }
 
 
    const fetchUserInformation = async () => {
        const apiEndpoint = "https://pan.baidu.com/pcloud/user/getinfo?query_uk=";
        const timestamp = Date.now();

        try {
            const response = await fetch(`${apiEndpoint}&timestamp=${timestamp}`, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            });

            if (response.ok) {
                const data = await response.json();
                globalDataConfig.userDescription = data.user_info.intro;
            } else {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
        } catch (error) {
            console.error('Failed to fetch user information:', error);
        }
    };
 
    let uInfo = {};
    const sendToAria2 = (response) => {
        const downloadPath = (getElementValue("#savePath").val()).replace(/\\/g, '/');
        const aria2Endpoint = getElementValue("#aria2Endpoint").val();
        const aria2Secret = getElementValue("#aria2Secret").val();
 
        if (getUserConfig().excludeDir == "enabled") {delete response.aria2config.options[2].dir; }
 
        const requestPayload = {
            "id": "CLOUDTRANSFER",
            "jsonrpc": "2.0",
            "method": "aria2.addUri",
            "params": [
                [
                    response.downloadUrl
                ],
                {
                    "max-concurrent-downloads": 16,
                    "dir": downloadPath,
                    "out": response.fileInfo.name,
                    "user-agent": "cloudDrive;8.1.0;Desktop;"
                }
            ]
        };
 
        const jsonData = JSON.stringify(requestPayload);
        try { 
            sendXmlHttpRequest({
                url: aria2Endpoint,
                timeout: 4000,
                method: 'POST',
                data: jsonData,
                onloadstart: () => {
                    showSendingStatus();
                },
                ontimeout: (res) => {
                    displayAriaError('Operation failed!');
                    showDetailedError('Connection to Aria2/Motrix timed out: Please check if Aria2/Motrix is connected and RPC settings are correct!');
                    updateSendButton(false);
                    console.warn(res);
                },
                responseType: 'json',
                onload: (res) => {
                    console.log('Sent to Aria2/Motrix, response:', res);
                    if (res.status == 200) {
                        var result = res.response.result;
                        if (result) {
                            updateSendButton(true);
                            displayAriaSuccess('Download started, check your Aria2/Motrix client!');
                        } else {
                            displayAriaError('Operation failed!');
                            showDetailedError(res.response.message);
                            updateSendButton(false);
                        }
                    } else {
                        displayAriaError('Operation failed!');
                        showDetailedError(`Failed to send to Aria2/Motrix! Server response: ${res.responseText}`);
                        updateSendButton(false);
                        console.warn(res);
                    }
                },
                onerror: (res) => {
                    displayAriaError('Operation failed!');
                    showDetailedError('An error occurred while sending to Aria2/Motrix, please try again!');
                    updateSendButton(false);
                    console.warn(res);
                }
            }); 
        } catch (error) {
            displayAriaError('Operation failed!');
            showDetailedError('An unknown error occurred while sending to Aria2/Motrix, please try again!');
            updateSendButton(false);
            console.error(error);
       }
    };
 
    const initiateFileSharing = () => {
        globalState.isDownloading = true;
        updateStatusMessage('Sharing current file...');
        refreshUIElements();
        hideElement('#CaptchaVerification');
    };
    const updateDownloadStatus = (isComplete = false) => {
        if (!isComplete) {
            globalState.isDownloading = false;
        }
        refreshUIElements();
    };
    const beginAriaTransfer = () => {
        globalState.isTransferring = true;
        updateAriaStatusMessage('Transferring to Aria2/Motrix...');
        refreshUIElements();
    };

    const finalizeAriaOperation = (isSuccessful) => {
        globalState.isTransferring = false;
        if (isSuccessful) {
            updateElementValue("#ariaActionButton", 'Aria2/Motrix download initiated');
        } else {
            updateElementValue("#ariaActionButton", 'Send to Aria2/Motrix');
        }
        refreshUIElements();
    };

    let storeTemporaryData = function (serverResponse, password, fileIdentifier, accessToken) {
        temporaryStorage.accessToken = accessToken;
        temporaryStorage.fileIdentifier = fileIdentifier;
        temporaryStorage.password = password;
        temporaryStorage.serverResponse = serverResponse;
    }
 
    let retrieveTemporaryInformation = function () {return temporaryStorage;}
 
    const analyzeFileStructure = fileArray => {
        const structureAnalysis = { fileCount: 0, directoryCount: 0 };
        fileArray.forEach(element => {
            element.isDirectory === false ? structureAnalysis.fileCount++ : structureAnalysis.directoryCount++;
        }); 
        return structureAnalysis;
    };
    
    const initializeDownloadProcess = () => {
        const currentPageType = determinePageType();
        const cloudDriveData = fetchCloudDriveConfig();
 
        if (!cloudDriveData && currentPageType !== 'fresh') {
            handleInvalidConfiguration();
            return;
        }
 
        if (currentPageType === 'external') {
            displayNotification('You must save the file to your personal cloud drive before downloading.');
            triggerUIRefresh();
        } else {
            const selectedFiles = retrieveSelectedFiles();
            const fileAnalysis = analyzeFileSelection(selectedFiles);
 
            if (selectedFiles.length > 0) {
                if (fileAnalysis.folderCount > 0 || fileAnalysis.fileCount > 1) {
                    showWarningMessage('Please select a single file. Folders and multiple file downloads are not supported yet.');
                } else if (fileAnalysis.folderCount === 0 && fileAnalysis.fileCount === 1) {
                    renderDownloadDialog(selectedFiles, fileAnalysis);
                    prepareDownloadEnvironment();
                }
            } else {
                displayNotification('Please select a file to download.');
            }
        }
    };
 
    const renderDownloadDialog = (selectedFiles, fileAnalysis) => {
        const theFile = fileList[0];
        const dialogContent = `
        <div id="downloadModal">
              <header class="modal-header">
                <span class="file-name">Click the button below to start downloading: ${truncateFileName(theFile.server_filename, 40)}</span>
              </header>
              <main class="modal-body">
                <aside class="qr-section">
                  <div class="qr-container">
                    <img class="qr-image" src="" alt="QR Code" />
                  </div>
                </aside>
                <section class="download-options">
                  <div class="download-content">
                    <button id="fetchDirectLink" class="btn primary-btn">Fetch Direct Download Link</button>
                    <div class="notice-box">
                      <p>■ Download speed <strong>varies</strong>, especially on shared networks (e.g., campus Wi-Fi)</p>
                      <p>■ Folder, batch, and large file downloads are not supported yet</p>
                    </div>
                    <div id="operationFeedback"></div>
                    <div id="captchaSection">
                        <div class="captcha-input">
                            <span id="captchaPrompt"></span>
                            <input id="captchaCode" type="text" value="${getDownloadConfig().code}" />
                        </div>
                        <div id="captchaNote"></div>
                    </div>
                    <div class="action-buttons">
                      <button id="copyDirectLink" data-clipboard-text="" class="btn secondary-btn">Copy Direct Link</button>
                      <div id="idmFeedback"></div>
                      <button id="pushToAria" class="btn secondary-btn">Push to Aria2/Motrix</button>
                      <div id="ariaFeedback"></div>
                      <div class="save-path-container">
                        Save Path: <input type="text" id="savePath" value="${getDownloadConfig().savePath}" style="width: 170px;" />
                        <span id="ariaConfigToggle">Configure Aria2/Motrix >></span>
                        <div id="ariaSettings">
                          <input type="text" id="ariaRpcUrl" value="${getDownloadConfig().jsonRpc}" title="RPC URL" placeholder="RPC URL" style="width: 240px;" />
                          <input type="text" id="ariaToken" value="${getDownloadConfig().token}" title="Token" placeholder="Token" style="width: 77px;" />
                          <br />
                          <input type="checkbox" id="useCustomAria" value="checked" ${getDownloadConfig().mine}> Use custom Aria2/Motrix (must check if changed)
                        </div>
                      </div>
                    </div>
                  </div>
                </section>
              </main>
              <div class="clearfix"></div>
              <footer class="modal-footer"></footer>
            </div>
          `;
        fetch("https://api.fastdown.com/config", {
            method: "GET",
            headers: {
                "Accept": "application/json",
                "X-Custom-Header": "FetchRequest"
            }
        })
        .then(response => response.json())
        .then(data => {
            console.log('Received data:', data);
            updateUI(data);
        })
        .catch(error => {
            console.error('Error fetching config:', error);
        });

        function refreshInterface(configurationData) {
            const footerSection = document.getElementById("dialogBottom");
            const qrCodeDisplay = document.getElementById("dialogQrImg");
            
            if (footerSection && configurationData.hyperlinks && configurationData.hyperlinks.length) {
                const primaryLink = configurationData.hyperlinks[0];
                footerSection.innerHTML = `<a href="${primaryLink.address}" rel="noopener noreferrer" target="_blank">${primaryLink.label}</a>`;
            }
            
            if (qrCodeDisplay && configurationData.qrImageSource) {
                qrCodeDisplay.setAttribute("src", configurationData.qrImageSource);
            }
        }
 
        displayCustomDialog(contentBody, {
            preventOutsideClick: true,
            confirmText: 'Close'
        });
 
        const initiateShareProcess = () => {
            if (globalShareStatus.isProcessing) { return false; }
            initializeShareProcess();
            const cachedShareData = retrieveShareCache();
            if (cachedShareData.fileId === currentFile.fileId && cachedShareData.shareResponse) {
                processDownloadLink(cachedShareData.shareResponse, cachedShareData.accessCode, cachedShareData.fileId, '');
                console.log('File already shared, skipping reshare process');
                return;
            } else {
                console.log('Initiating new share for this file');
            }
            const authToken = '';
            const accessCode = generateRandomCode(4);
        
            const shareRequest = async () => {
                const response = await fetch(`/share/create?app_id=250528&channel=chunlei&clienttype=0&bdstoken=${bdstoken}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `file_ids=[${theFile.fs_id}]&share_type=4&period=1&channel_list=[]&password=${pwd}`,
                    timeout: 11000,
                });
        
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
        
                return await response.json();
            };
        
            const handleShareResponse = (data) => {
                const errorCode = data.errno;
                if (errorCode === 0) {
                    processShareSuccess(data, pwd, theFile.fs_id, '');
                    fetchDownloadLink(data, pwd, theFile.fs_id, '');
                } else {
                    const errorMessages = {
                        115: 'Sharing is prohibited for this file!',
                        '-6': 'Please log in again!',
                        110: 'You\'ve shared too much today. Try again in 24 hours.',
                    };
                    const defaultError = `File sharing failed. Please try again!\nError code: ${errorCode}`;
                    handleShareError(errorMessages[errorCode] || defaultError);
                }
            };
        
            shareRequest()
                .then(result => handleShareResponse(result))
                .catch(error => {
                    console.error('An unexpected error occurred:', error);
                    displayErrorMessage('An unexpected error occurred. Please try again.');
                    resetShareProcess();
                });
        };
 
        getJQueryInstance()("#urlRetrievalButton").on("click", handleShareDialogClick);
 
        getJQueryInstance()("#ariaSettingsToggle").on("click", toggleAriaConfigPanel);
 
        initializeClipboardFunctionality();
    };
 
    const fetchCloudConfiguration = () => {
        return unsafeWindow.cloudDataStorage;
    };
 
    const displayErrorNotification = (errorMessage) => {
        showCustomAlert(errorMessage, {icon: 'warning'});
    }
    const handleDownloadLinkError = (errorMessage) => {
        if(!errorMessage.includes('Failed to retrieve direct download link')){
            window.alert(errorMessage);
        }
    }
 
    const addFloatingButton = () => {
        const premiumStatusIcon = GM_getResourceURL("premiumIcon");
        const floatBox = `
          <div style='position:fixed;z-index:888888;cursor:pointer;top:195px;left:2px;'>
            <div id='crack_vip_wp_box' style='height:30px;line-height:30px;text-align:center;font-size:14px;color:#fff;background-image:linear-gradient(to right, #ff6300, #ff9d00);border-top-right-radius:8px;border-bottom-right-radius:8px;'>
              <img src='${premiumStatusIcon}' style='width:22px;height:20px;position:relative;top:4px;' />&nbsp;百度网盘SVIP
            </div>
            <div id='vip_url_box' style='font-size:12px;padding:4px 4px;'>
              <a href='http://http://yemao.in/wangpan' target='_blank' style='color:#4c9dff;text-decoration:none'>http://http://yemao.in/wangpan</a>
            </div>
            <div id='vip_github_box' style='width:105px;padding:4px 4px;'>
                <embed src='https://ghbtns.com/github-btn.html?user=wuxingsanren&repo=wildcat-vip-account&type=star&count=true' style='height:20px;' />
            </div>
          </div>
        `;
        document.body.insertAdjacentHTML('beforeend', floatBox);
    
        const defaultEnhancementLink = "http://http://yemao.in/wangpan";
        document.getElementById('crack_vip_wp_box').addEventListener('click', () => {
          window.open(defaultEnhancementLink, "_blank");
        });
    };

    const toggleAriaConfigDialog = () => {
        const configDialog = getJQueryRef()("#ariaConfigPanel");
        configDialog.is(":visible") ? configDialog.hide() : configDialog.show();
    };
    const displayNotification = function (message) {
        getJQueryRef()("#notificationArea").show().text(message);
    }
    const showAriaNotification = function (message) {
        getJQueryRef()("#ariaNotificationArea").show().text(message);
    }
    const showIdmNotification = function (message) {
        getJQueryRef()("#idmNotificationArea").show().text(message);
    }
 
    const presentCustomAlert = function (alertContent, alertOptions) {
        notificationElement.innerHTML = alertContent;
        alertOptions.content = notificationElement;
        if (!alertOptions.hasOwnProperty('confirmButton')) {
            alertOptions.confirmButton = 'OK, Got it!'
        }
        sweetAlert(alertOptions);
    }
 
    const getJQueryRef = function () {
        return jQuery;
    };
    const initiateLogin = function () {
        require("base:widget/libs/jquerypacket.js")("[node-type='login-button']").trigger("click");
    };
    const triggerShareSave = function () {
        require("base:widget/libs/jquerypacket.js")("[node-type='save-share']").trigger("click");
    };

    const appConfiguration = {
        primaryDomain: '',
        activeDownloads: 0,
        secondaryDomain: '',
        queryParameter: '',
        currentVersion: '2.1.1',
        configPrefix: 'AppSettings',
        activeUploads: 0,
    };
 
    const retrieveApplicationSettings = () => ({
        version: appConfiguration.currentVersion,
        queryParam: appConfiguration.queryParameter,
        configPrefix: appConfiguration.configPrefix,
        apiEndpoint: `/api/download.php`,
    });
 
    const temporaryStorage = {
        serverResponse: '',
        accessKey: '',
        fileIdentifier: '',
        authToken: '',
    };
 
    const dataManager = {
      fetchGlobalValue: key => GM_getValue(`${retrieveAppSettings().configPrefix}_global_${key}`) || '',
      retrieveRecentUsage: key => GM_getValue(`${retrieveAppSettings().configPrefix}_recent_${key}`) || '',
      updateAppSetting: (key, value) => GM_setValue(`${retrieveAppSettings().configPrefix}_app_${key}`, value || ''),
      getAppSetting: key => GM_getValue(`${retrieveAppSettings().configPrefix}_app_${key}`) || '',
      updateRecentUsage: (key, value) => GM_setValue(`${retrieveAppSettings().configPrefix}_recent_${key}`, value || ''),
      setGlobalValue: (key, value) => GM_setValue(`${retrieveAppSettings().configPrefix}_global_${key}`, value || '')
    };
 
    const defaultConfiguration = {
      downloadDirectory: 'C:\\Downloads\\FAST',
      rpcEndpoint: 'http://127.0.0.1:6800/jsonrpc',
      authKey: '',
      userIdentifier: '',
      verificationCode: '',
    };
 
    const retrieveSystemPreferences = () => {
      const getPreference = (key) => dataManager.fetchGlobalValue(key) || dataManager.getAppSetting(key) || defaultConfiguration[key];
      return {
        storageLocation: getPreference('storageLocation'),
        apiEndpoint: getPreference('apiEndpoint'),
        secretToken: getPreference('secretToken'),
        accountId: getPreference('accountId'),
        securityCode: dataManager.fetchGlobalValue('securityCode') || defaultConfiguration.verificationCode,
      };
    };
 
    const renderInterfaceComponents = (payload) => {
      const sanitizeContent = (content) => utilityFunctions().trim(content);
      const updateElement = (selector, content) => {
        if (content && content.length > 0) {
          utilityFunctions()(selector).html(sanitizeContent(content)).show();
        }
      };
      
      updateElement("#dialogCodeAnnotation", payload.codeAnnotation);
      
      if (sanitizeContent(payload.qrInstructions).length > 0) {
        // Logic for handling QR instructions
      }
      
      if (sanitizeContent(payload.qrImage).length > 0) {
        // Logic for processing QR image
      }
    };
 
    const fetchDownloadLink = async (responseData, password, fileId, accessToken) => {
        const verificationInput = document.querySelector('#dialogCode').value.trim();
        const apiEndpoint = "https://fast.blog/api/fetch";
        console.log("Response data:", responseData);
        const shareIdentifier = responseData.link.split('/').pop();
 
        const requestConfig = {
            responseType: 'json',
            method: 'POST',
            timeout: 15000,
            url: apiEndpoint,
            data: `shareId=${shareIdentifier}&passphrase=${password}&verificationCode=${verificationInput}&username=${document.querySelector('.wp-s-header-user__drop-info-body p').textContent.trim()}&sessionData=${retrieveSessionData()}`,
 
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
 
            onload: async (serverResponse) => {
                try {
                    displayStatusMessage('Retrieving direct download link...');
                    console.log(serverResponse.response.errorCode)
                    if (serverResponse.status === 200) {
 
                        if (serverResponse.response.errorCode === 1011) {
                            displayStatusMessage(serverResponse.response.errorMessage);
                        } else if (serverResponse.response.errorCode === 101) {
                                resetCaptcha();
                                displayStatusMessage(serverResponse.response.errorMessage);
                                updateUIWithResponse(serverResponse.response);
                                document.querySelector('#VaptchaCode').style.display = 'block';
                        } else if (serverResponse.response.errorCode === 0) {
                            const directoryInfo = serverResponse.response.directoryData;
                            const fileInfo = serverResponse.response.fileData[0];
                            const secondaryRequest = {
                                responseType: 'json',
                                method: "POST",
                                url: "https://fast.blog/api/resolve",
                                data: `fileId=${fileInfo.fs_id}&timestamp=${directoryInfo.timestamp}&signature=${directoryInfo.sign}&accessKey=${directoryInfo.randsk}&shareId=${directoryInfo.shareid}&shareUrl=${directoryInfo.surl}&passphrase=${directoryInfo.pwd}&userId=${directoryInfo.uk}&username=${document.querySelector('.wp-s-header-user__drop-info-body p').textContent.trim()}&sessionData=${retrieveSessionData()}`,
                                headers: { "Content-Type": "application/x-www-form-urlencoded" },
                                onload: (finalResponse) => {
                                    if (finalResponse.response.errorCode === 0) {
                                        const downloadInfo = finalResponse.response;
                                        resetCaptcha(true);
                                        updateDownloadButton(downloadInfo);
                                        initiateDownload();
                                        updateUIWithResponse(downloadInfo);
                                    } else {
                                        displayStatusMessage(finalResponse.response.errorMessage || finalResponse.response.statusText || 'An error occurred!');
                                        logError(`Failed to fetch direct download link. Server response: ${serverResponse.response.status}`);
                                    }
                                }
                            };
                            GM_xmlhttpRequest(secondaryRequest);
                        } else {
 
                            displayStatusMessage(serverResponse.response.errorMessage || serverResponse.response.statusText);
                             throw serverResponse;
 
                        }
 
                    } else {
 
                        displayStatusMessage(serverResponse.response.errorMessage || serverResponse.response.statusText);
                         throw serverResponse;
 
                    }
 
                } catch (error) {
 
                    console.error(error);
                    displayStatusMessage(serverResponse.response.errorMessage || serverResponse.response.statusText || 'An error occurred!');
                    logError(`Failed to fetch direct download link. Server response: ${serverResponse.response.status}`);
                }
 
             }
         };
        try { 
            await GM_xmlhttpRequest(requestConfig); 
        } catch (error) {
            logError(`Failed to fetch direct download link. Server response: ${serverResponse.response.status}`);
 
            displayStatusMessage(serverResponse.response.errorMessage || serverResponse.response.statusText || 'An error occurred!');
 
         }
    };
 
    const updateClickHandler = (response) => {
        displayElement("#operationButtons");
        showNotification('Direct link obtained successfully. Please choose a download method below.');
        const directUrl = response.downloadLink;
        setClipboardData("#idmButton", directUrl);
        const aria2Button = getElement("#ariaButton");
        aria2Button.off().on("click", () => {
            initiateAriaDownload(response);
         });
    };
 
    const saveUserPreferences = () => {
        let isMineChecked = "";
        updateLastUsedValue('downloadPath', getElementValue("#savePathInput"));
        updateLastUsedValue('rpcEndpoint', getElementValue("#ariaRpcInput"));
        updateLastUsedValue('authToken', getElementValue("#ariaTokenInput"));
        if (isElementChecked("#ariaMineCheckbox")) {  isMineChecked = "checked"; }
        updateLastUsedValue('isMine', isMineChecked);
        updateLastUsedValue('secretCode', getElementValue("#secretCodeInput"));
    };
 
    const setupClipboardCopy = () => {
        const clipboardButton = new ClipboardJS('#idmButton');
        clipboardButton.on("success", (event) => {
            displayIdmNotification(`Link copied successfully! User-Agent: netdisk;7.2.6.2;PC;`);
        });
    };
 
    const delay = (duration) => {return new Promise((resolve) => setTimeout(resolve, duration));};
 
    const initializeInterface = async () => {
        if (isVirtualSite) return;
        const interfaceType = determinePageLayout();
        if (!interfaceType) {
            await new Promise(resolve => setTimeout(resolve, 500));
            initializeInterface();
            return;
        }

        const actionButton = document.createElement('button');
        actionButton.style.cssText = styleConfigurations.getStyle(interfaceType);
        actionButton.innerHTML = styleConfigurations.getHTML(interfaceType);
        actionButton.title = styleConfigurations.buttonTitle;
        actionButton.className = styleConfigurations.getClass(interfaceType);
        actionButton.id = styleConfigurations.buttonId;
        actionButton.addEventListener('click', (event) => {
            executeMainFunction();
            event.preventDefault();
        });

        let targetElement = null;
        if (interfaceType === 'legacy') {
            const uploadButton = document.querySelector('[data-type=upload]');
            targetElement = uploadButton.parentNode;
            targetElement.insertBefore(actionButton, targetElement.firstChild);
        } else if (interfaceType === 'modern') {
            let toolbarSection;
            toolbarSection = document.querySelector(".file-list-toolbar.file-list-toolbar__actions.inline-block-v-middle");
            if (toolbarSection) {
                actionButton.style.cssText += 'margin-right: 5px;';
                toolbarSection.insertBefore(actionButton, toolbarSection.firstChild);
            } else {
                toolbarSection = document.querySelector(".agile-toolbar__header.default-skin.header-tool");
                if (!toolbarSection) {
                    toolbarSection = document.querySelector(".agile-toolbar__header.header-tool");
                }
                const wrapperDiv = document.createElement('div');
                wrapperDiv.style.cssText = 'margin-right: 10px;';
                wrapperDiv.className = 'agile-toolbar__action left-separator list-view';
                wrapperDiv.appendChild(actionButton);
                toolbarSection.insertBefore(wrapperDiv, toolbarSection.firstChild);
            }
        } else if (interfaceType === 'shared') {
            const qrCodeButton = document.querySelector('[data-type=qrCode]');
            targetElement = qrCodeButton.parentNode;
            targetElement.insertBefore(actionButton, qrCodeButton);
        }

        document.querySelectorAll('span').forEach((element) => {
            if (element.textContent.includes('Search your files')) {
                const parentContainer = element.closest('div');
                parentContainer.style.maxWidth = '200px';
            }
        });
    };
 
    const extractSubstring = (inputString, prefix, suffix) => {
        const pattern = new RegExp(`${prefix}([\\s\\S]*?)${suffix}`);
        const match = inputString.match(pattern);
        return match ? match[1].trim() : undefined;
    };

    const determinePageType = () => {
        if (isSharedContentPage()) return 'shared';
        if (isModernInterface()) return 'modern';
        if (isLegacyInterface()) return 'legacy';
        return 'unknown';
    };
 
GM_addStyle(`
 .popup-container {
    max-width: none;
    min-width: 750px;
}
 
#interactionArea {}
 
 
#fileTransferBox {
    width: 750px;
    font-size: 15px;
}
 
#headerSection {
    padding: 25px 0;
}
 
#fileIdentifier {
    font-size: 18px;
    color: #333;
    position: relative;
    top: -3px;
}
 
#fileIdentifierBold {
    font-size: 18px;
    color: #333;
    font-weight: 700;
}
 
#rightPanel {
    width: 48%;
    float: right;
    margin-right: 20px;
}
#leftPanelInfo {
    text-align: right;
    margin: 0 0 12px 0px;
    color: #5d5544;
    font-size: 14px;
}
 
#securityVerification{
    display: none;
    text-align: right;
    margin-top: 7px;
    font-size: 14px;
    border: 2px solid #FEE;
}
#securityVerificationInput{
    font-size: 17px;
}
 
.leftPanelInfoLink {
    text-align: right;
}
 
.actionButton {
    color: #f8f8f8;
    cursor: grab;
    text-decoration: underline;
    font-family: Arial, Helvetica, sans-serif;
    font-weight: 300;
    letter-spacing: 1px;
    width: 95%;
    height: 45px;
    background: #3cb371 !important;
    border-radius: 8px;
    transition: .5s;
    font-size: 22px !important;
    border: 2px solid #2e8b57;
}

.sweetalert-input {
    border: 2px #a9a9a9 dashed;
}
#modalInputField input {
    vertical-align: bottom;
}

#modalNote {
    text-align: right;
    font-size: 14px;
    margin-top: 10px;
}

.modalLeftLinkHint a {
    color: #ff7f50;
}

#modalQRCode img {
    width: 95%;
    margin-left: 28px;
    margin-top: -20px;
}
#modalQRCode {
    width: 280px;
    height: 280px;
    text-align: right;
}
#modalVerificationCode {
    width: 45%;
}

#modalClearfix {
    clear: left;
}

.btnBlue {
    background: #4169e1 !important;
}

#modalSaveLocationDiv {
    margin-top: 4px;
    text-align: right;
}
 
#modalSidePanel {
    display: inline-block;
    width: 45%;
    margin-right: 5%;
    vertical-align: top;
}
#actionButtonDownload,
#actionButtonStream {
    margin-bottom: 10px;
}

#streamingOptions {
    visibility: hidden;
    margin-bottom: 4px;
}

#modalFooter {
    text-align: right;
    margin: 20px -15px 0 -15px;
    background: #E6F3F0!important;
    padding: 12px 20px 12px 0;
}

.custom-btn {
    background-color: #4A7BA3;
}

#operationMessage,
#streamingMessage,
#downloadMessage {
    visibility: hidden;
    background: #E6F3F0!important;
    padding: 5px 16px;
    color: #3A3326;
    border-radius: 4px;
    font-weight: 600;
    text-align: right;
    margin-bottom: 11px;
    font-size: 16px;
}

#streamingOptions {
    font-size: 11px;
}

#actionButtons {
    visibility: hidden;
}

#streamingOptionsToggle {
    color: #0080C6;
    text-decoration: underline;
    cursor: pointer;
    font-size: 11px;
    padding-right: 8px;
}
.modal-actions {
    margin-bottom: 7px;
}
     `);
 
    const fetchUserData = async () => {
        const endpoint = "https://pan.baidu.com/rest/2.0/xpan/nas?method=uinfo";
        const requestConfig = {
            responseType: 'json',
            timeout: 10000,
            method: 'GET',
            url: `${endpoint}&timestamp=${Date.now()}`,
            onload: response => {
                const statusCode = response.status;
                if (statusCode === 200) {
                    userInformation = response.response;
                } else {
                    console.error('请求失败:', response);
                }
            }
        };

        try {
            await new Promise((resolve, reject) => {
                GM_xmlhttpRequest({
                    ...requestConfig,
                    onload: (res) => {
                        requestConfig.onload(res);
                        resolve();
                    },
                    onerror: reject
                });
            });
        } catch (error) {
            console.error('发生错误:', error);
        }
    };

    const initializeApplication = async () => {
        addFloatingButton();
    };
    fetchUserData();
 
    const notificationContainer = document.createElement('div');
    notificationContainer.id = "notificationContainer";
 
    let loginPrompt = document.querySelector('.login-main');
    let isExternalSite = false;
 
    let directDownloadHelper = {
        id: 'btnDirectDownload',
        text: 'Direct Download 🚀-FAST',
        title: 'Use FAST for downloading',
        applyStyle: function (pageLayout) {
            if (pageLayout === 'modern') {
                return '';
            }
            if (pageLayout === 'classic' || pageLayout == 'shared') {
                return 'padding: 0px;';
            }
        },
        applyClass: function (pageLayout) {
            if (pageLayout === 'modern') {
                return '';
            }
            if (pageLayout === 'classic' || pageLayout == 'shared') {
                return 'custom-button custom-button-primary-large';
            }
        },
        generateHTML: function (pageLayout) {
            if (pageLayout === 'classic' || pageLayout == 'shared') {
    return `
                    <div class="custom-button-wrapper"> <i class="custom-icon custom-icon-download" style="color:#ffffff" title="${this.text}"></i> <span class="custom-text" style="width: auto;">${this.text}</span> </div>
                 `
           }
            if (pageLayout === 'modern') {
                return `
                    <button class="modern-button file-toolbar-action is-primary is-small has-icon is-danger"><i class="modern-icon icon-download"></i><span>${this.text}</span></button>
`;
            }
        }
    }
 
    const retrieveSelectedItems = () => {
        const currentPageType = determinePageLayout();
        if (currentPageType === 'modern') {
            const listContainer = document.querySelector('.modern-list-container') || document.querySelector('.alternative-modern-list');
            return listContainer ? listContainer.__vue__.selectedElements : null;
        } else if (currentPageType === 'legacy') {
            const systemContext = require('core-system:utils/context-manager.js');
            return systemContext.getInstanceForCurrentSystem().listView.getSelectedItems();
        }
        return null;
    };

    setTimeout(() => {
        initializeApplication();
    }, 750);
})();
  
function parseBrowserCookies() {
    if (!document.cookie) return {};
    const cookieArray = document.cookie.split(';');
    return cookieArray.reduce((acc, current) => {
        const [rawKey, ...valueParts] = current.split('=');
        const key = rawKey.trim();
        const value = decodeURIComponent(valueParts.join('='));
        acc[key] = value;
        return acc;
    }, {});
}