百度云直接下载

直接下载百度云的文件,可以避免下载大文件和exe文件时调用云管家,已支持分享页面下载

As of 2016-10-21 12:05:26 UTC. See the latest version.

// ==UserScript==
// @name         百度云直接下载
// @namespace    undefined
// @version      0.9.4
// @description  直接下载百度云的文件,可以避免下载大文件和exe文件时调用云管家,已支持分享页面下载
// @author       Roger Zhu
// @match        *://pan.baidu.com/disk/home*
// @match        *://yun.baidu.com/disk/home*
// @match        *://pan.baidu.com/s/*
// @match        *://yun.baidu.com/s/*
// @match        *://pan.baidu.com/share/link*
// @match        *://yun.baidu.com/share/link*
// @require      http://code.jquery.com/jquery-latest.js
// @run-at       document-end
// @grant        unsafeWindow
// ==/UserScript==

(function() {
    'use strict';
    
    var $ = $ || window.$;
    
    $(function(){
        if(detectPage() == 'disk'){
            var yunHelper = new YunHelper();
            yunHelper.init();
        }else{
            var shareHelper = new ShareHelper();
            shareHelper.init();
        }
    });

    //网盘页面的下载助手
    function YunHelper(){
        var yunData,sign,timestamp,bdstoken,logid,fid_list;
        var fileList=[],selectFileList=[],
            list_grid_status='list';
        var observer,currentPage,currentPath,currentCategory;
        var panAPIUrl = location.protocol + "//" + location.host + "/api/";
        var restAPIUrl1 = location.protocol + "//pcs.baidu.com/rest/2.0/pcs/";
        
        this.init = function(){
            yunData = unsafeWindow.yunData;
            console.log('yunData:',yunData);
            if(yunData === undefined){
                console.log('页面未正常加载,或者百度已经更新!');
                return;
            }
            initParams();
            registerEventListener();
            createObserver();
            addButton();
            createIframe();
            addDialog();
            addShadow();
            console.log('网盘直接下载助手加载成功!');
        };
        
        function initParams(){
            sign = getSign();
            timestamp = getTimestamp();
            bdstoken = getBDStoken();
            logid = getLogID();
            currentPage = getCurrentPage();

            if(currentPage == 'list')
                currentPath = getPath();

            if(currentPage == 'category')
                currentCategory = getCategory();

            refreshListGridStatus();
            refreshFileList();
            refreshSelectList();
        }

        function refreshFileList(){
            if (currentPage == 'list') {
                fileList = getFileList();
            } else if (currentPage == 'category'){
                fileList = getCategoryFileList();
            }
        }

        function refreshSelectList(){
            selectFileList = [];
        }

        function refreshListGridStatus(){
            list_grid_status = getListGridStatus();
        }

        //获取当前的视图模式
        function getListGridStatus(){
            var status = 'list';
            var $status_div = $('div.list-grid-switch');
            if ($status_div.hasClass('list-switched-on')){
                status = 'list';
            } else if ($status_div.hasClass('grid-switched-on')) {
                status = 'grid';
            }
            return status;
        }

        function registerEventListener(){
            registerHashChange();
            registerListGridStatus();
            registerCheckbox();
            registerAllCheckbox();
            registerFileSelect();
        }

        //监视地址栏#标签的变化
        function registerHashChange(){
            window.addEventListener('hashchange',function(e){
                refreshListGridStatus();
                if(getCurrentPage() == 'list') {
                    if(currentPage == getCurrentPage()){
                        if(currentPath == getPath()){
                            return;
                        } else {
                            currentPath = getPath();
                            refreshFileList();
                            refreshSelectList();
                        }
                    } else {
                        currentPage = getCurrentPage();
                        currentPath = getPath();
                        refreshFileList();
                        refreshSelectList();
                    }
                } else if (getCurrentPage() == 'category') {
                    if(currentPage == getCurrentPage()){
                        if(currentCategory == getCategory()){
                            return;
                        } else {
                            currentPage = getCurrentPage();
                            currentCategory = getCategory();
                            refreshFileList();
                            refreshSelectList();
                        }
                    } else {
                        currentPage = getCurrentPage();
                        currentCategory = getCategory();
                        refreshFileList();
                        refreshSelectList();
                    }
                }
            });
        }

        //监视视图变化
        function registerListGridStatus(){
            var $a_list = $('a[node-type=list-switch]');
            $a_list.click(function(){
                list_grid_status = 'list';
            });

            var $a_grid = $('a[node-type=grid-switch]');
            $a_grid.click(function(){
                list_grid_status = 'grid';
            });
        }

        //文件选择框
        function registerCheckbox(){
            var $checkbox = $('span.checkbox');
            $checkbox.each(function(index,element){
                $(element).bind('click',function(e){
                    var $parent = $(this).parent();
                    var filename;
                    if(list_grid_status == 'list') {
                        filename = $('div.file-name div.text a',$parent).attr('title');
                    }else if(list_grid_status == 'grid'){
                        filename = $('div.file-name a',$parent).attr('title');
                    }
                    if($parent.hasClass('item-active')){
                        console.log('取消选中文件:'+filename);
                        for(var i=0;i<selectFileList.length;i++){
                            if(selectFileList[i].filename == filename){
                                selectFileList.splice(i,1);
                            }
                        }
                    }else{
                        console.log('选中文件:'+filename);
                        $.each(fileList,function(index,element){
                            if(element.server_filename == filename){
                                var obj = {
                                    filename:element.server_filename,
                                    path:element.path,
                                    fs_id:element.fs_id,
                                    isdir:element.isdir
                                };
                                selectFileList.push(obj);
                            }
                        });
                    }
                });
            });
        }

        function unregisterCheckbox(){
            var $checkbox = $('span.checkbox');
            $checkbox.each(function(index,element){
                $(element).unbind('click');
            });
        }

        //全选框
        function registerAllCheckbox(){
            var $checkbox = $('div.col-item.check');
            $checkbox.each(function(index,element){
                $(element).bind('click',function(e){
                    var $parent = $(this).parent();
                    if($parent.hasClass('checked')){
                        console.log('取消全选');
                        selectFileList = [];
                    } else {
                        console.log('全部选中');
                        selectFileList = [];
                        $.each(fileList,function(index,element){
                            var obj = {
                                filename:element.server_filename,
                                path:element.path,
                                fs_id:element.fs_id,
                                isdir:element.isdir
                            };
                            selectFileList.push(obj);
                        });
                    }
                });
            });
        }

        function unregisterAllCheckbox(){
            var $checkbox = $('div.col-item.check');
            $checkbox.each(function(index,element){
                $(element).unbind('click');
            });
        }

        //单个文件选中,点击文件不是点击选中框,会只选中该文件
        function registerFileSelect(){
            var $dd = $('div.list-view dd');
            $dd.each(function(index,element){
                $(element).bind('click',function(e){
                    var nodeName = e.target.nodeName.toLowerCase();
                    if(nodeName != 'span' && nodeName != 'a' && nodeName != 'em') {
                        selectFileList = [];
                        var filename = $('div.file-name div.text a',$(this)).attr('title');
                        console.log('选中文件:' + filename);
                        $.each(fileList,function(index,element){
                            if(element.server_filename == filename){
                                var obj = {
                                    filename:element.server_filename,
                                    path:element.path,
                                    fs_id:element.fs_id,
                                    isdir:element.isdir
                                };
                                selectFileList.push(obj);
                            }
                        });
                    }
                });
            });
        }

        function unregisterFileSelect(){
            var $dd = $('div.list-view dd');
            $dd.each(function(index,element){
                $(element).unbind('click');
            });
        }

        //监视文件列表显示变化
        function createObserver(){
            var MutationObserver = window.MutationObserver;
            var options = {
                'childList': true
            };
            observer = new MutationObserver(function(mutations){
                unregisterCheckbox();
                unregisterAllCheckbox();
                unregisterFileSelect();
                registerCheckbox();
                registerAllCheckbox();
                registerFileSelect();
            });
            var list_view = document.querySelector('.list-view');
            var grid_view = document.querySelector('.grid-view');

            observer.observe(list_view,options);
            observer.observe(grid_view,options);
        }

        //添加助手按钮
        function addButton(){
            var $dropdownbutton = $('<span class="g-dropdown-button"></span>');
            var $dropdownbutton_a = $('<a class="g-button" data-button-id="b200" data-button-index="200" href="javascript:void(0);"></a>');
            var $dropdownbutton_a_span = $('<span class="g-button-right"><em class="icon icon-download" title="百度云下载助手"></em><span class="text" style="width: auto;">下载助手</span></span>');
            var $dropdownbutton_span = $('<span class="menu" style="width:auto"></span>');

            var $panAPIDownloadButton = $('<a data-menu-id="b-menu201" class="g-button-menu" href="javascript:void(0);">直接下载</a>');
            var $restAPIDownloadButton1 = $('<a data-menu-id="b-menu202" class="g-button-menu" href="javascript:void(0);">API下载(百度云ID)</a>');
            var $restAPIDownloadButton2 = $('<a data-menu-id="b-menu203" class="g-button-menu" href="javascript:void(0);">API下载(ES ID)</a>');
            var $linkButton1 = $('<a data-menu-id="b-menu204" class="g-button-menu" href="javascript:void(0);">显示链接(直接下载)</a>');
            var $linkButton2 = $('<a data-menu-id="b-menu205" class="g-button-menu" href="javascript:void(0);">显示链接(百度云ID)</a>');
            var $linkButton3 = $('<a data-menu-id="b-menu206" class="g-button-menu" href="javascript:void(0);">显示链接(ES ID)</a>');

            $dropdownbutton_span.append($panAPIDownloadButton).append($restAPIDownloadButton1).append($restAPIDownloadButton2).append($linkButton1).append($linkButton2).append($linkButton3);
            $dropdownbutton_a.append($dropdownbutton_a_span);
            $dropdownbutton.append($dropdownbutton_a).append($dropdownbutton_span);

            $dropdownbutton.hover(function(){
                $dropdownbutton.toggleClass('button-open');
            });

            $panAPIDownloadButton.click(panAPIDownloadClick);
            $restAPIDownloadButton1.click(restAPIDownloadClick1);
            $restAPIDownloadButton2.click(restAPIDownloadClick2);
            $linkButton1.click(linkButtonClick1);
            $linkButton2.click(linkButtonClick2);
            $linkButton3.click(linkButtonClick3);

            $('div.default-dom div.bar div.list-tools').append($dropdownbutton);
        }

        //添加显示链接的弹出对话框
        function addDialog(){
            var screenWidth = document.body.clientWidth;
            var dialogLeft = screenWidth>568 ? (screenWidth-568)/2 : 0;
            var $dialog_div = $('<div class="dialog" id="dialog-link" style="width: 568px; top: 0px; bottom: auto; left: '+dialogLeft+'px; right: auto; display: hidden; visibility: visible; z-index: 52;"></div>');
            var $dialog_header = $('<div class="dialog-header"><h3><span class="dialog-header-title">下载链接</span></h3></div>');
            var $dialog_control = $('<div class="dialog-control"><span class="dialog-icon dialog-close">×</span></div>');
            var $dialog_body = $('<div class="dialog-body"></div>');
            var $content = $('<div style="padding:0 20px"><a id="dialog-downloadlink" href="javascript:void(0)"></a></div>');
            var $tip = $('<div id="dialog-tip" style="padding-left:20px;background-color:#faf2d3;border-top: 1px solid #c4dbfe;"><p></p></div>');

            //对话框移动
            var mouseInitX,mouseInitY,dialogInitX,dialogInitY;
            $dialog_header.mousedown(function(event){
                mouseInitX = parseInt(event.pageX);
                mouseInitY = parseInt(event.pageY);
                dialogInitX = parseInt($dialog_div.css('left').replace('px',''));
                dialogInitY = parseInt($dialog_div.css('top').replace('px',''));
                $(this).mousemove(function(event){
                    var tempX = dialogInitX + parseInt(event.pageX) - mouseInitX;
                    var tempY = dialogInitY + parseInt(event.pageY) - mouseInitY;
                    tempX = tempX<0 ? 0 : tempX>screenWidth-568 ? screenWidth-568 : tempX;
                    tempY = tempY<0 ? 0 : tempY;
                    $dialog_div.css('left',tempX+'px').css('top',tempY+'px');
                });
            });
            $dialog_header.mouseup(function(event){
                $(this).unbind('mousemove');
            });
            $dialog_control.click(dialogControl);
            $('body').append($dialog_div.append($dialog_header.append($dialog_control)).append($dialog_body.append($content).append($tip)));
        }

        //添加遮罩层
        function addShadow(){
            var $shadow = $('<div id="dialog-shadow" style="position: fixed; left: 0px; top: 0px; z-index: 50; background: rgb(0, 0, 0) none repeat scroll 0% 0%; opacity: 0.5; width: 100%; height: 100%; display: none;"></div>');
            $('body').append($shadow);
        }

        function panAPIDownloadClick(){
            console.log('PAN API下载');

            if(selectFileList.length === 0) {
                alert("获取选中文件失败,请刷新重试!");
                return;
            }

            var downloadType;
            var downloadLink;

            fid_list = getFidList(selectFileList);

            if (selectFileList.length == 1) {
                if (selectFileList[0].isdir === 1)
                    downloadType = 'batch';
                else if (selectFileList[0].isdir === 0)
                    downloadType= 'dlink';
            } else if(selectFileList.length > 1){
                downloadType = 'batch';
            }
            downloadLink = getDownloadLinkWithPanAPI(fid_list,downloadType);
            execDownload(downloadLink);
        }

        function restAPIDownloadClick1(){
            console.log("REST API(百度云ID)下载");

            if(selectFileList.length === 0) {
                alert("获取选中文件失败,请刷新重试!");
                return;
            } else if (selectFileList.length > 1) {
                alert("该方法不支持多文件下载!");
                return;
            } else {
                if(selectFileList[0].isdir == 1){
                    alert("该方法不支持目录下载!");
                    return;
                }
            }

            var downloadLink = getDownloadLinkWithRESTAPI1(selectFileList[0].path);
            execDownload(downloadLink);
        }

        function restAPIDownloadClick2(){
            console.log("REST API(ES ID)下载");

            if(selectFileList.length === 0) {
                alert("获取选中文件失败,请刷新重试!");
                return;
            } else if (selectFileList.length > 1) {
                alert("该方法不支持多文件下载!");
                return;
            } else {
                if(selectFileList[0].isdir == 1){
                    alert("该方法不支持目录下载!");
                    return;
                }
            }

            var downloadLink = getDownloadLinkWithRESTAPI2(selectFileList[0].path);
            execDownload(downloadLink);
        }

        function linkButtonClick1(){
            if(selectFileList.length === 0) {
                alert("获取选中文件失败,请刷新重试!");
                return;
            }

            var downloadType;
            var downloadLink;

            fid_list = getFidList(selectFileList);

            if (selectFileList.length == 1) {
                if (selectFileList[0].isdir === 1)
                    downloadType = 'batch';
                else if (selectFileList[0].isdir === 0)
                    downloadType= 'dlink';
            } else if(selectFileList.length > 1){
                downloadType = 'batch';
            }
            downloadLink = getDownloadLinkWithPanAPI(fid_list,downloadType);

            $('#dialog-downloadlink').attr('href',downloadLink).text(downloadLink);
            var $shadow = $('#dialog-shadow');
            var $dialog = $('#dialog-link');
            var $tip = $('div#dialog-tip p');
            $tip.text('显示模拟百度网盘获取的链接,可以使用右键迅雷下载,复制无用,需要传递cookie');
            $shadow.show();
            $dialog.show();
        }

        function linkButtonClick2(){
            if(selectFileList.length === 0) {
                alert("获取选中文件失败,请刷新重试!");
                return;
            } else if (selectFileList.length > 1) {
                alert("该方法不支持多文件下载!");
                return;
            } else {
                if(selectFileList[0].isdir == 1){
                    alert("该方法不支持目录下载!");
                    return;
                }
            }

            var downloadLink = getDownloadLinkWithRESTAPI1(selectFileList[0].path);
            $('#dialog-downloadlink').attr('href',downloadLink).text(downloadLink);
            var $shadow = $('#dialog-shadow');
            var $dialog = $('#dialog-link');
            var $tip = $('div#dialog-tip p');
            $tip.text('显示模拟APP获取的链接(使用百度云ID),可以使用右键迅雷下载,复制无用,需要传递cookie');
            $shadow.show();
            $dialog.show();
        }

        function linkButtonClick3(){
            if(selectFileList.length === 0) {
                alert("获取选中文件失败,请刷新重试!");
                return;
            } else if (selectFileList.length > 1) {
                alert("该方法不支持多文件下载!");
                return;
            } else {
                if(selectFileList[0].isdir == 1){
                    alert("该方法不支持目录下载!");
                    return;
                }
            }

            var downloadLink = getDownloadLinkWithRESTAPI2(selectFileList[0].path);
            $('#dialog-downloadlink').attr('href',downloadLink).text(downloadLink);
            var $shadow = $('#dialog-shadow');
            var $dialog = $('#dialog-link');
            var $tip = $('div#dialog-tip p');
            $tip.text('显示模拟APP获取的链接(使用ES ID),可以使用右键迅雷下载,复制无用,需要传递cookie');
            $shadow.show();
            $dialog.show();
        }

        //对话框关闭
        function dialogControl(){
            $('#dialog-downloadlink').attr('href','javascript:void(0)').text('');
            $('div#dialog-tip p').text('');
            var $dialog = $('#dialog-link');
            var $shadow = $('#dialog-shadow');
            $dialog.hide();
            $shadow.hide();
        }

        function getSign(){
            var signFnc;
            try{
                signFnc = new Function("return " + yunData.sign2)();
            } catch(e){
                throw new Error(e.message);
            }
            return base64Encode(signFnc(yunData.sign5,yunData.sign1));
        }

        //获取当前目录
        function getPath(){
            var hash = location.hash;
            var regx = /(^|&|\/)path=([^&]*)(&|$)/i;
            var result = hash.match(regx);
            return decodeURIComponent(result[2]);
        }

        //获取分类显示的类别,即地址栏中的type
        function getCategory(){
            var hash = location.hash;
            var regx = /(^|&|\/)type=([^&]*)(&|$)/i;
            var result = hash.match(regx);
            return decodeURIComponent(result[2]);
        }

        //获取当前页面(list或者category)
        function getCurrentPage(){
            var hash = location.hash;
            return decodeURIComponent(hash.substring(hash.indexOf('#')+1,hash.indexOf('/')));
        }

        //获取文件列表
        function getFileList(){
            var filelist = [];
            var listUrl = panAPIUrl + "list";
            var path = getPath();
            var params = {
                dir:path,
                bdstoken:bdstoken,
                logid:logid,
                order:'size',
                desc:0,
                clienttype:0,
                showempty:0,
                web:1,
                channel:'chunlei',
                appid:250528
            };
            $.ajax({
                url:listUrl,
                async:false,
                method:'GET',
                data:params,
                success:function(result){
                    filelist = 0===result.errno ? result.list : [];
                }
            });
            return filelist;
        }

        //获取分类页面下的文件列表
        function getCategoryFileList(){
            var filelist = [];
            var listUrl = panAPIUrl + "categorylist";
            var category = getCategory();
            var params = {
                category:category,
                bdstoken:bdstoken,
                logid:logid,
                order:'size',
                desc:0,
                clienttype:0,
                showempty:0,
                web:1,
                channel:'chunlei',
                appid:250528
            };
            $.ajax({
                url:listUrl,
                async:false,
                method:'GET',
                data:params,
                success:function(result){
                    filelist = 0===result.errno ? result.info : [];
                }
            });
            return filelist;
        }

        //生成下载时的fid_list参数
        function getFidList(list){
            var fidlist = null;
            if (list.length === 0)
                return null;
            var fileidlist = [];
            $.each(list,function(index,element){
                fileidlist.push(element.fs_id);
            });
            fidlist = '[' + fileidlist + ']';
            return fidlist;
        }

        function getTimestamp(){
            return yunData.timestamp;
        }

        function getBDStoken(){
            return yunData.MYBDSTOKEN;
        }

        //获取直接下载地址
        //这个地址不是直接下载地址,访问这个地址会返回302,response header中的location才是真实下载地址
        //暂时没有找到提取方法
        function getDownloadLinkWithPanAPI(fidlist,type){
            var downloadUrl = panAPIUrl + "download";
            var link = null;
            var params= {
                sign:sign,
                timestamp:timestamp,
                fidlist:fidlist,
                type:type,
                channel:'chunlei',
                web:1,
                app_id:250528,
                bdstoken:bdstoken,
                logid:logid,
                clienttype:0
            };
            $.ajax({
                url:downloadUrl,
                async:false,
                method:'GET',
                data:params,
                success:function(result){
                    if (type == 'dlink')
                        link = result.dlink[0].dlink;
                    else if (type == 'batch')
                        link = result.dlink;
                }
            });
            return link;
        }

        function getDownloadLinkWithRESTAPI1(path){
            var link = restAPIUrl1 + 'file?method=download&app_id=250528&path=' + path;
            return link;
        }

        function getDownloadLinkWithRESTAPI2(path){
            var link = restAPIUrl1 + 'file?method=download&app_id=266719&path=' + path;
            return link;
        }

        function execDownload(link){
            console.log('选中文件列表:',selectFileList);
            console.log("下载链接:"+link);
            $('#helperdownloadiframe').attr('src',link);
        }

        function createIframe(){
            var $div = $('<div class="helper-hide" style="padding:0;margin:0;display:block"></div>');
            var $iframe = $('<iframe src="javascript:void(0)" id="helperdownloadiframe" style="display:none"></iframe>');
            $div.append($iframe);
            $('body').append($div);

        }
    }

    //分享页面的下载助手
    function ShareHelper(){
        var yunData,sign,timestamp,bdstoken,channel,clienttype,web,app_id,logid,encrypt,product,uk,primaryid,fid_list,extra,shareid;
        var vcode;
        var shareType,buttonTarget,currentPath,list_grid_status,observer;
        var fileList=[],selectFileList=[];
        var panAPIUrl = location.protocol + "//" + location.host + "/api/";
        var shareListUrl = location.protocol + "//" + location.host + "/share/list";

        this.init = function(){
            yunData = unsafeWindow.yunData;
            console.log('yunData:',yunData);
            if(yunData === undefined || yunData.FILEINFO == null){
                console.log('页面未正常加载,或者百度已经更新!');
                return;
            }
            initParams();
            addButton();
            addLinkDialog();
            addVCodeDialog();
            addShadow();
            createIframe();

            if(!isSingleShare()){
                registerEventListener();
                createObserver();
            }
            
            console.log('分享直接下载加载成功!');
        };

        function initParams(){
            shareType = getShareType();
            sign = yunData.SIGN;
            timestamp = yunData.TIMESTAMP;
            bdstoken = yunData.MYBDSTOKEN;
            channel = 'chunlei';
            clienttype = 0;
            web = 1;
            app_id = 250528;
            logid = getLogID();
            encrypt = 0;
            product = 'share';
            primaryid = yunData.SHARE_ID;
            uk = yunData.SHARE_UK;

            if(shareType == 'secret'){
                extra = getExtra();
            }
            if(isSingleShare()){
                var obj = {
                    filename:yunData.FILEINFO[0].server_filename,
                    path:yunData.FILEINFO[0].path,
                    fs_id:yunData.FILEINFO[0].fs_id,
                    isdir:yunData.FILEINFO[0].isdir
                };
                selectFileList.push(obj);
            } else {
                shareid = yunData.SHARE_ID;
                currentPath = getPath();
                list_grid_status = getListGridStatus();
                fileList = getFileList();
            }
        }

        //判断分享类型(public或者secret)
        function getShareType(){
            return yunData.SHARE_PUBLIC===1 ? 'public' : 'secret';
        }

        //判断是单个文件分享还是文件夹或者多文件分享
        function isSingleShare(){
            return yunData.getContext === undefined ? true : false;
        }

        //判断是否为自己的分享链接
        function isSelfShare(){
            return yunData.MYSELF == 1 ? true : false;
        }

        function getExtra(){
            var seKey = decodeURIComponent(getCookie('BDCLND'));
            return '{' + '"sekey":"' + seKey + '"' + "}";
        }

        //获取当前目录
        function getPath(){
            var hash = location.hash;
            var regx = /(^|&|\/)path=([^&]*)(&|$)/i;
            var result = hash.match(regx);
            return decodeURIComponent(result[2]);
        }

        //获取当前的视图模式
        function getListGridStatus(){
            var status = 'list';
            var $status_div = $('div.list-grid-switch');
            if ($status_div.hasClass('list-switched-on')){
                status = 'list';
            } else if ($status_div.hasClass('grid-switched-on')) {
                status = 'grid';
            }
            return status;
        }

        //添加下载助手按钮
        function addButton(){
            if(isSingleShare())
                $('div.slide-show-right').css('width','500px').css('float','left').css('text-align','left');

            var $dropdownbutton = $('<span class="g-dropdown-button"></span>');
            var $dropdownbutton_a = $('<a class="g-button" data-button-id="b200" data-button-index="200" href="javascript:void(0);"></a>');
            var $dropdownbutton_a_span = $('<span class="g-button-right"><em class="icon icon-download" title="百度云下载助手"></em><span class="text" style="width: auto;">下载助手</span></span>');
            var $dropdownbutton_span = $('<span class="menu" style="width:auto;z-index:31"></span>');

            var $downloadButton = $('<a data-menu-id="b-menu207" class="g-button-menu" href="javascript:void(0);">直接下载</a>');
            var $linkButton = $('<a data-menu-id="b-menu208" class="g-button-menu" href="javascript:void(0);">显示链接</a>');

            $dropdownbutton_span.append($downloadButton).append($linkButton);
            $dropdownbutton_a.append($dropdownbutton_a_span);
            $dropdownbutton.append($dropdownbutton_a).append($dropdownbutton_span);

            $dropdownbutton.hover(function(){
                $dropdownbutton.toggleClass('button-open');
            });

            $downloadButton.click(downloadButtonClick);
            $linkButton.click(linkButtonClick);

            $('div.module-share-top-bar div.bar div.button-box').append($dropdownbutton);
        }

        //添加链接显示对话框
        function addLinkDialog(){
            var screenWidth = document.body.clientWidth;
            var dialogLeft = screenWidth>568 ? (screenWidth-568)/2 : 0;
            var $dialog_div = $('<div class="dialog" id="dialog-link" style="width: 568px; top: 0px; bottom: auto; left: '+dialogLeft+'px; right: auto; display: none; visibility: visible; z-index: 52;"></div>');
            var $dialog_header = $('<div class="dialog-header"><h3><span class="dialog-header-title">下载链接</span></h3></div>');
            var $dialog_control = $('<div class="dialog-control"><span class="dialog-icon dialog-close">×</span></div>');
            var $dialog_body = $('<div class="dialog-body"></div>');
            var $content = $('<div style="padding:0 20px"><a id="dialog-downloadlink" href="javascript:void(0)"></a></div>');
            var $tip = $('<div id="dialog-tip" style="padding-left:20px;background-color:#faf2d3;border-top: 1px solid #c4dbfe;"><p>显示获取的链接,可以使用右键迅雷下载,复制无用,需要传递cookie</p></div>');

            var mouseInitX,mouseInitY,dialogInitX,dialogInitY;
            $dialog_header.mousedown(function(event){
                mouseInitX = parseInt(event.pageX);
                mouseInitY = parseInt(event.pageY);
                dialogInitX = parseInt($dialog_div.css('left').replace('px',''));
                dialogInitY = parseInt($dialog_div.css('top').replace('px',''));
                $(this).mousemove(function(event){
                    var tempX = dialogInitX + parseInt(event.pageX) - mouseInitX;
                    var tempY = dialogInitY + parseInt(event.pageY) - mouseInitY;
                    tempX = tempX<0 ? 0 : tempX>screenWidth-568 ? screenWidth-568 : tempX;
                    tempY = tempY<0 ? 0 : tempY;
                    $dialog_div.css('left',tempX+'px').css('top',tempY+'px');
                });
            });
            $dialog_header.mouseup(function(event){
                $(this).unbind('mousemove');
            });
            $dialog_control.click(linkDialogControl);
            $('body').append($dialog_div.append($dialog_header.append($dialog_control)).append($dialog_body.append($content).append($tip)));
        }

        function linkDialogControl(){
            $('#dialog-downloadlink').attr('href','javascript:void(0)').text('');
            var $dialog = $('#dialog-link');
            var $shadow = $('#dialog-shadow');
            $dialog.hide();
            $shadow.hide();
        }

        //遮罩层
        function addShadow(){
            var $shadow = $('<div id="dialog-shadow" style="position: fixed; left: 0px; top: 0px; z-index: 50; background: rgb(0, 0, 0) none repeat scroll 0% 0%; opacity: 0.5; width: 100%; height: 100%; display: none;"></div>');
            $('body').append($shadow);
        }

        //添加验证码显示对话框
        function addVCodeDialog(){
            var screenWidth = document.body.clientWidth;
            var dialogLeft = screenWidth>520 ? (screenWidth-568)/2 : 0;
            var $dialog_div = $('<div class="dialog" id="dialog-vcode" style="width:520px;top:0px;bottom:auto;left:'+dialogLeft+'px;right:auto;display:none;visibility:visible;z-index:52"></div>');
            var $dialog_header = $('<div class="dialog-header"><h3><span class="dialog-header-title"><em class="select-text">提示</em></span></h3></div>');
            var $dialog_control = $('<div class="dialog-control"><span class="dialog-icon dialog-close icon icon-close"><span class="sicon">x</span></span></div>');
            var $dialog_body = $('<div class="dialog-body"></div>');
            var $dialog_body_div = $('<div style="text-align:center;padding:22px"></div>');
            var $dialog_body_download_verify = $('<div class="download-verify" style="margin-top:10px;padding:0 28px;text-align:left;font-size:12px;"></div>');
            var $dialog_verify_body = $('<div class="verify-body">请输入验证码:</div>');
            var $dialog_input = $('<input id="dialog-input" type="text" style="padding:3px;width:85px;height:23px;border:1px solid #c6c6c6;background-color:white;vertical-align:middle;" class="input-code" maxlength="4">');
            var $dialog_img = $('<img id="dialog-img" class="img-code" style="margin-left:10px;vertical-align:middle;" alt="点击换一张" src="" width="100" height="30">');
            var $dialog_refresh = $('<a href="javascript:void(0)" style="text-decoration:underline;" class="underline">换一张</a>');
            var $dialog_err = $('<div id="dialog-err" style="padding-left:84px;height:18px;color:#d80000" class="verify-error"></div>');
            var $dialog_footer = $('<div class="dialog-footer g-clearfix"></div>');
            var $dialog_confirm_button = $('<a class="g-button g-button-blue" data-button-id="" data-button-index href="javascript:void(0)" style="padding-left:36px"><span class="g-button-right" style="padding-right:36px;"><span class="text" style="width:auto;">确定</span></span></a>');
            var $dialog_cancel_button = $('<a class="g-button" data-button-id="" data-button-index href="javascript:void(0);" style="padding-left: 36px;"><span class="g-button-right" style="padding-right: 36px;"><span class="text" style="width: auto;">取消</span></span></a>');

            $dialog_header.append($dialog_control);
            $dialog_verify_body.append($dialog_input).append($dialog_img).append($dialog_refresh);
            $dialog_body_download_verify.append($dialog_verify_body).append($dialog_err);
            $dialog_body_div.append($dialog_body_download_verify);
            $dialog_body.append($dialog_body_div);
            $dialog_footer.append($dialog_confirm_button).append($dialog_cancel_button);
            $dialog_div.append($dialog_header).append($dialog_body).append($dialog_footer);
            $('body').append($dialog_div);

            var mouseInitX,mouseInitY,dialogInitX,dialogInitY;
            $dialog_header.mousedown(function(event){
                mouseInitX = parseInt(event.pageX);
                mouseInitY = parseInt(event.pageY);
                dialogInitX = parseInt($dialog_div.css('left').replace('px',''));
                dialogInitY = parseInt($dialog_div.css('top').replace('px',''));
                $(this).mousemove(function(event){
                    var tempX = dialogInitX + parseInt(event.pageX) - mouseInitX;
                    var tempY = dialogInitY + parseInt(event.pageY) - mouseInitY;
                    tempX = tempX<0 ? 0 : tempX>screenWidth-568 ? screenWidth-568 : tempX;
                    tempY = tempY<0 ? 0 : tempY;
                    $dialog_div.css('left',tempX+'px').css('top',tempY+'px');
                });
            });
            $dialog_header.mouseup(function(event){
                $(this).unbind('mousemove');
            });
            $dialog_control.click(vcodeDialogControl);
            $dialog_img.click(refreshVCode);
            $dialog_refresh.click(refreshVCode);
            $dialog_input.keypress(function(event){
                if(event.which == 13)
                    confirmClick();
            });
            $dialog_confirm_button.click(confirmClick);
            $dialog_cancel_button.click(cancelClick);
            $dialog_input.click(inputClick);
        }

        function vcodeDialogControl(){
            $('#dialog-img').attr('src','');
            $('#dialog-err').text('');
            var $dialog = $('#dialog-vcode');
            var $shadow = $('#dialog-shadow');
            $dialog.hide();
            $shadow.hide();
        }

        function createIframe(){
            var $div = $('<div class="helper-hide" style="padding:0;margin:0;display:block"></div>');
            var $iframe = $('<iframe src="javascript:void(0)" id="helperdownloadiframe" style="display:none"></iframe>');
            $div.append($iframe);
            $('body').append($div);
        }

        function registerEventListener(){
            registerHashChange();
            registerListGridStatus();
            registerCheckbox();
            registerAllCheckbox();
            registerFileSelect();
        }

        //监视地址栏#标签变化
        function registerHashChange(){
            window.addEventListener('hashchange',function(e){
                list_grid_status = getListGridStatus();
                if(currentPath == getPath()){
                    return;
                } else {
                    currentPath = getPath();
                    refreshFileList();
                    refreshSelectFileList();
                }
            });
        }

        function refreshFileList(){
            fileList = getFileList();
        }

        function refreshSelectFileList(){
            selectFileList = [];
        }

        //监视视图变化
        function registerListGridStatus(){
            var $a_list = $('a[node-type=list-switch]');
            $a_list.click(function(){
                list_grid_status = 'list';
            });

            var $a_grid = $('a[node-type=grid-switch]');
            $a_grid.click(function(){
                list_grid_status = 'grid';
            });
        }

        //监视文件选择框
        function registerCheckbox(){
            var $checkbox = $('span.checkbox');
            $checkbox.each(function(index,element){
                $(element).bind('click',function(e){
                    var $parent = $(this).parent();
                    var filename;
                    if(list_grid_status == 'list') {
                        filename = $('div.file-name div.text a',$parent).attr('title');
                    }else if(list_grid_status == 'grid'){
                        filename = $('div.file-name a',$parent).attr('title');
                    }
                    if($parent.hasClass('item-active')){
                        console.log('取消选中文件:'+filename);
                        for(var i=0;i<selectFileList.length;i++){
                            if(selectFileList[i].filename == filename){
                                selectFileList.splice(i,1);
                            }
                        }
                    }else{
                        console.log('选中文件:'+filename);
                        $.each(fileList,function(index,element){
                            if(element.server_filename == filename){
                                var obj = {
                                    filename:element.server_filename,
                                    path:element.path,
                                    fs_id:element.fs_id,
                                    isdir:element.isdir
                                };
                                selectFileList.push(obj);
                            }
                        });
                    }
                });
            });
        }

        function unregisterCheckbox(){
            var $checkbox = $('span.checkbox');
            $checkbox.each(function(index,element){
                $(element).unbind('click');
            });
        }

        //监视全选框
        function registerAllCheckbox(){
            var $checkbox = $('div.col-item.check');
            $checkbox.each(function(index,element){
                $(element).bind('click',function(e){
                    var $parent = $(this).parent();
                    if($parent.hasClass('checked')){
                        console.log('取消全选');
                        selectFileList = [];
                    } else {
                        console.log('全部选中');
                        selectFileList = [];
                        $.each(fileList,function(index,element){
                            var obj = {
                                filename:element.server_filename,
                                path:element.path,
                                fs_id:element.fs_id,
                                isdir:element.isdir
                            };
                            selectFileList.push(obj);
                        });
                    }
                });
            });
        }

        function unregisterAllCheckbox(){
            var $checkbox = $('div.col-item.check');
            $checkbox.each(function(index,element){
                $(element).unbind('click');
            });
        }

        //监视单个文件选中
        function registerFileSelect(){
            var $dd = $('div.list-view dd');
            $dd.each(function(index,element){
                $(element).bind('click',function(e){
                    var nodeName = e.target.nodeName.toLowerCase();
                    if(nodeName != 'span' && nodeName != 'a' && nodeName != 'em') {
                        selectFileList = [];
                        var filename = $('div.file-name div.text a',$(this)).attr('title');
                        console.log('选中文件:' + filename);
                        $.each(fileList,function(index,element){
                            if(element.server_filename == filename){
                                var obj = {
                                    filename:element.server_filename,
                                    path:element.path,
                                    fs_id:element.fs_id,
                                    isdir:element.isdir
                                };
                                selectFileList.push(obj);
                            }
                        });
                    }
                });
            });
        }

        function unregisterFileSelect(){
            var $dd = $('div.list-view dd');
            $dd.each(function(index,element){
                $(element).unbind('click');
            });
        }

        //监视文件列表显示变化
        function createObserver(){
            var MutationObserver = window.MutationObserver;
            var options = {
                'childList': true
            };
            observer = new MutationObserver(function(mutations){
                unregisterCheckbox();
                unregisterAllCheckbox();
                unregisterFileSelect();
                registerCheckbox();
                registerAllCheckbox();
                registerFileSelect(); 
            });
            var list_view = document.querySelector('.list-view');
            var grid_view = document.querySelector('.grid-view');

            observer.observe(list_view,options);
            observer.observe(grid_view,options);
        }

        //获取文件信息列表
        function getFileList(){
            var result = [];
            if(getPath() == '/'){
                result = yunData.FILEINFO;
            } else {
                var params = {
                    uk:uk,
                    shareid:shareid,
                    order:'other',
                    desc:1,
                    showempty:0,
                    web:web,
                    dir:getPath(),
                    t:Math.random(),
                    bdstoken:bdstoken,
                    channel:channel,
                    clienttype:clienttype,
                    app_id:app_id,
                    logid:logid
                };
                $.ajax({
                    url:shareListUrl,
                    method:'GET',
                    async:false,
                    data:params,
                    success:function(response){
                        if(response.errno === 0){
                            result = response.list;
                        }
                    }
                });
            }
            return result;
        }

        function downloadButtonClick(){
            if(selectFileList.length === 0){
                alert('获取文件ID失败,请重试');
                return;
            }
            buttonTarget = 'download';
            var downloadLink = getDownloadLink();

            if(downloadLink.errno == -20) {
                vcode = getVCode();
                $('#dialog-img').attr('src',vcode.img);
                $('#dialog-shadow').show();
                $('#dialog-vcode').show();
            } else if(downloadLink.errno == 112){
                alert('页面过期,请刷新重试');
            } else if (downloadLink.errno === 0) {
                var link;
                if(selectFileList.length == 1 && selectFileList[0].isdir === 0)
                    link = downloadLink.list[0].dlink;
                else
                    link = downloadLink.dlink;
                execDownload(link);
            } else {
                alert('获取下载链接失败!');
            }
        }

        //获取验证码
        function getVCode(){
            var url = panAPIUrl + 'getvcode';
            var result;
            var params = {
                prod:'pan',
                t:Math.random(),
                bdstoken:bdstoken,
                channel:channel,
                clienttype:clienttype,
                web:web,
                app_id:app_id,
                logid:logid
            };
            $.ajax({
                url:url,
                method:'GET',
                async:false,
                data:params,
                success:function(response){
                    result = response;
                }
            });
            return result;
        }

        //刷新验证码
        function refreshVCode(){
            vcode = getVCode();
            $('#dialog-img').attr('src',vcode.img);
        }

        function inputClick(){
            $('#dialog-err').text('');
        }

        //验证码确认提交
        function confirmClick(){
            var val = $('#dialog-input').val();
            if(val.length === 0) {
                $('#dialog-err').text('请输入验证码');
                return;
            } else if(val.length < 4) {
                $('#dialog-err').text('验证码输入错误,请重新输入');
                return;
            } 
            var result = getDownloadLinkWithVCode(val);
            var $dialog = $('#dialog-vcode');
            var $shadow = $('#dialog-shadow');
            if(result.errno == -20){
                cancelClick();
                $('#dialog-err').text('验证码输入错误,请重新输入');
                refreshVCode();
                if(vcode.errno !== 0){
                    alert('获取验证码失败!');
                    return;
                }
                $('#dialog-vcode').show();
                $('#dialog-shadow').show();
            } else if (result.errno === 0) {
                cancelClick();
                var link;
                if(selectFileList.length ==1 && selectFileList[0].isdir === 0)
                    link = result.list[0].dlink;
                else
                    link = result.dlink;
                if(buttonTarget == 'download'){
                    execDownload(link);
                } else if (buttonTarget == 'link') {
                    $('#dialog-downloadlink').attr('href',link).text(link);
                    $('#dialog-link').show();
                    $('#dialog-shadow').show();
                }
            }
        }

        //验证码取消
        function cancelClick(){
            $('#dialog-img').attr('src','');
            $('#dialog-err').text('');
            var $dialog = $('#dialog-vcode');
            var $shadow = $('#dialog-shadow');
            $dialog.hide();
            $shadow.hide();
        }

        //生成下载用的fid_list参数
        function getFidList(){
            var fidlist = [];
            $.each(selectFileList,function(index,element){
                fidlist.push(element.fs_id);
            });
            return '[' + fidlist + ']';
        }

        function linkButtonClick(){
            if(selectFileList.length === 0){
                alert('没有选中文件,请重试');
                return;
            }
            buttonTarget = 'link';
            var downloadLink = getDownloadLink();

            if(downloadLink.errno == -20) {
                vcode = getVCode();
                if(vcode.errno !== 0){
                    alert('获取验证码失败!');
                    return;
                }
                $('#dialog-img').attr('src',vcode.img);
                $('#dialog-shadow').show();
                $('#dialog-vcode').show();
            } else if (downloadLink.errno == 112) {
                alert('页面过期,请刷新重试');
                return;
            } else if (downloadLink.errno === 0) {
                var link;
                if(selectFileList.length == 1 && selectFileList[0].isdir === 0)
                    link = downloadLink.list[0].dlink;
                else
                    link = downloadLink.dlink;
                if(selectFileList.length == 1)
                    $('#dialog-downloadlink').attr('href',link).text(link);
                else
                    $('#dialog-downloadlink').attr('href',link).text(link);
                var $shadow = $('#dialog-shadow');
                var $dialog = $('#dialog-link');
                $shadow.show();
                $dialog.show();
            } else {
                alert('获取下载链接失败!');
                return;
            }
        }

        //获取下载链接
        function getDownloadLink(){
            var result;
            console.log('选中文件列表:',selectFileList);
            if(isSingleShare){
                fid_list = getFidList();
                var url = panAPIUrl + 'sharedownload?sign=' + sign + '&timestamp=' + timestamp + '&bdstoken=' + bdstoken + '&channel=' + channel + '&clienttype=' + clienttype + '&web='+ web + '&app_id=' + app_id + '&logid=' + logid;
                var params = {
                    encrypt:encrypt,
                    product:product,
                    uk:uk,
                    primaryid:primaryid,
                    fid_list:fid_list
                };
                if(shareType == 'secret'){
                    params.extra = extra;
                }
                if(selectFileList[0].isdir == 1 || selectFileList.length > 1){
                    params.type = 'batch';
                }
                $.ajax({
                    url:url,
                    method:'POST',
                    async:false,
                    data:params,
                    success:function(response){
                        result = response;
                    }
                });
            }
            return result;
        }

        //有验证码输入时获取下载链接
        function getDownloadLinkWithVCode(vcodeInput){
            console.log('选中文件列表:',selectFileList);
            var result;
            if(isSingleShare){
                fid_list = getFidList();
                var url = panAPIUrl + 'sharedownload?sign=' + sign + '&timestamp=' + timestamp + '&bdstoken=' + bdstoken + '&channel=' + channel + '&clienttype=' + clienttype + '&web='+ web + '&app_id=' + app_id + '&logid=' + logid;
                var params = {
                    encrypt:encrypt,
                    product:product,
                    vcode_input:vcodeInput,
                    vcode_str:vcode.vcode,
                    uk:uk,
                    primaryid:primaryid,
                    fid_list:fid_list
                };
                if(shareType == 'secret'){
                    params.extra = extra;
                }
                if(selectFileList[0].isdir == 1 || selectFileList.length > 1 ){
                    params.type = 'batch';
                }
                $.ajax({
                    url:url,
                    method:'POST',
                    async:false,
                    data:params,
                    success:function(response){
                        result = response;
                    }
                });
            }
            return result;
        }

        function execDownload(link){
            console.log('下载链接:'+link);
            $('#helperdownloadiframe').attr('src',link);
        }
    }
    
    function base64Encode(t){
        var a, r, e, n, i, s, o = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        for (e = t.length,r = 0,a = ""; e > r; ) {
            if (n = 255 & t.charCodeAt(r++),r == e) {
                a += o.charAt(n >> 2);
                a += o.charAt((3 & n) << 4);
                a += "==";
                break;
            }
            if (i = t.charCodeAt(r++),r == e) {
                a += o.charAt(n >> 2);
                a += o.charAt((3 & n) << 4 | (240 & i) >> 4);
                a += o.charAt((15 & i) << 2);
                a += "=";
                break;
            }
            s = t.charCodeAt(r++);
            a += o.charAt(n >> 2);
            a += o.charAt((3 & n) << 4 | (240 & i) >> 4);
            a += o.charAt((15 & i) << 2 | (192 & s) >> 6);
            a += o.charAt(63 & s);
        }
        return a;
    }
    
    function detectPage(){
        var regx = /[\/].+[\/]/g;
        var page = location.pathname.match(regx);
        return page[0].replace(/\//g,'');
    }

    function getCookie(e) {
        var o, t;
        var n = document,c=decodeURI;
        return n.cookie.length > 0 && (o = n.cookie.indexOf(e + "="),-1 != o) ? (o = o + e.length + 1,t = n.cookie.indexOf(";", o),-1 == t && (t = n.cookie.length),c(n.cookie.substring(o, t))) : "";
    }

    function getLogID(){
        var name = "BAIDUID";
        var u = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/~!@#¥%……&";
        var d = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
        var f = String.fromCharCode;
        function l(e){
            if (e.length < 2) {
                var n = e.charCodeAt(0);
                return 128 > n ? e : 2048 > n ? f(192 | n >>> 6) + f(128 | 63 & n) : f(224 | n >>> 12 & 15) + f(128 | n >>> 6 & 63) + f(128 | 63 & n);
            }
            var n = 65536 + 1024 * (e.charCodeAt(0) - 55296) + (e.charCodeAt(1) - 56320);
            return f(240 | n >>> 18 & 7) + f(128 | n >>> 12 & 63) + f(128 | n >>> 6 & 63) + f(128 | 63 & n);
        }
        function g(e){
            return (e + "" + Math.random()).replace(d, l);
        }
        function m(e){
            var n = [0, 2, 1][e.length % 3];
            var t = e.charCodeAt(0) << 16 | (e.length > 1 ? e.charCodeAt(1) : 0) << 8 | (e.length > 2 ? e.charCodeAt(2) : 0);
            var o = [u.charAt(t >>> 18), u.charAt(t >>> 12 & 63), n >= 2 ? "=" : u.charAt(t >>> 6 & 63), n >= 1 ? "=" : u.charAt(63 & t)];
            return o.join("");
        }
        function h(e){
            return e.replace(/[\s\S]{1,3}/g, m);
        }
        function p(){
            return h(g((new Date()).getTime()));
        }
        function w(e,n){
            return n ? p(String(e)).replace(/[+\/]/g, function(e) {
                return "+" == e ? "-" : "_";
            }).replace(/=/g, "") : p(String(e));
        }
        return w(getCookie(name));
    }
    
})();