jjm2473 / 果汁畅饮

// ==UserScript==
// @name         果汁畅饮
// @version      0.1
// @icon         http://guozhivip.com/yinyue/favicon.ico
// @description  果汁音乐直接下载,并重命名为歌曲名
// @author       jjm2473
// @copyright    2020, jjm2473@qq.com
// @license      MIT
// @supportURL   mailto:jjm2473@qq.com
// @namespace    https://openuserjs.org/users/jjm2473/

// @match        http://guozhivip.com/yinyue/
// @run-at       document-end

// @grant        GM_xmlhttpRequest

// @connect		 music.126.net
// @connect		 ws.stream.qqmusic.qq.com
// @connect		 xiami.net
// @connect		 kugou.com
// @connect		 qianqian.com
// @connect		 dmhmusic.com
// ==/UserScript==

(function() {
    'use strict';

    var GM_xmlhttpRequest = window.GM_xmlhttpRequest;
    window = window.unsafeWindow;
    var layer = window.layer;
    window.mkPlayer.debug = true;
    var musicValid = function(music) {
        return !(music.url == 'err' || music.url == "" || music.url == null || (music.source == 'netease' && music.url.startsWith('https://music.163.com/')));
    };
    window.ajaxShare = function(music){
        if (!musicValid(music)) {
            layer.msg('这首歌不支持外链获取');
            return;
        }

        downloadWithIframe(music.url, music.artist + ' - ' + music.name);
    };
    var downloadWithIframe = window.downloadWithIframe = function(url, name) {
        //var tmpHtml = '<p>' + name + ' 的外链地址为:</p>' +
        //    '<a href="' + url + '" download="'+ name +'">'+music.url+'</a>' +
        //   '<p class="share-tips">* 获取到的音乐外链有效期较短,请按需使用。</p>';

        var content = '<a href="' + url + '" download="'+ name +'">' + url + '</a>';

        content = '<html><head><meta charset="utf-8"></head><body style="width: 270px;overflow-wrap: break-word;user-select: all;">' + content + '</body></html>';
        var tmpHtml = '<p>' + name + ' 的外链地址为:</p>'+
            '<iframe src="data: text/html, ' + content.replace(/"/g, "&quot;") + '" ></iframe>';

        layer.open({
            title: '歌曲外链分享'
            ,content: tmpHtml
        });
    };
    var isSuccess = function(resp) {
        if (resp.status === 200) {
            return true;
        }else if(resp.status === 504){
            layer.msg('下载失败,请求超时');
        }else{
            layer.msg('下载失败');
        }
        return false;
    };
    var saveData = function(data, type, name, url) {
        if (type == 'application/octet-stream' && url !== undefined) {
            var pathname = new URL(url).pathname;
            var ext = pathname.substring(pathname.lastIndexOf('.'));
            if (ext && ext.indexOf('/') == -1) {
                name = name + ext;
            }
        }
        var blob = new Blob([data], {type:type});
        var downloadHelper = document.createElement('a');
        downloadHelper.href = URL.createObjectURL(blob);
        downloadHelper.download = name;
        downloadHelper.click();
    };
    var downloadWithXHR = window.downloadWithXHR = function(url, name){
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = "blob";
        xhr.onload = function () {
            if (isSuccess(this)) {
                saveData(this.response, this.getResponseHeader('content-type')||'application/stream', name, url);
            }
        };
        xhr.send();
    };
    var downloadWithGMXHR = window.downloadWithGMXHR = function(url, name){
        GM_xmlhttpRequest({
            method: 'GET',
            url: url,
            responseType: 'blob',
            onload: function (response) {
                if (isSuccess(response)) {
                    var type = (response.responseHeaders.split('\r\n').filter(s=>s.startsWith('content-type: '))[0] || 'content-type: application/octet-stream').substring(14);
                    saveData(response.response, type, name, url);
                }
            },
            onerror:  function (response) {
                layer.msg('脚本发生未知错误');
            }
        });
    };
    window.download = function(music) {
        if (!musicValid(music)) {
            layer.msg('这首歌不支持下载');
            return;
        }
        var df = downloadWithGMXHR;
        if (''.indexOf(music.source) >= 0) {
            // 如果有哪个网站不支持XHR下载,则只展示下载链接
            df = downloadWithIframe;
        }
        df(music.url, music.artist + ' - ' + music.name);
    }
})();