// ==UserScript==
// @name         XXQG_mp3_dl
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  try to take over the world!
// @author       You
// @match        https://article.xuexi.cn/articles/audio/share/index.html?*
// @icon         https://article.xuexi.cn/favicon.ico
// @grant        none
// @require      https://lib.baomitu.com/jquery/3.6.0/jquery.min.js
// ==/UserScript==

(function() {
    'use strict';

    // TEST URL
    // https://article.xuexi.cn/articles/audio/share/index.html?art_id=8249913386002990141&part_id=null&type=album&study_style_id=feeds_pure&jump_model=dtxuexi%3A%2F%2Fappclient%2Fpage%2Faudio_album%3FitemId%3D8249913386002990141&share_to=wx_single

    var list_len = 0;

    var str = "";

    function loop_click(index) {
        if (index >= list_len) {
            var filename = $.trim($(".header-title > .title").text());
            saveTxt("bash-" + filename, str);
            console.log("END");
            return;
        }
        var item = $(".playlist > .song:eq(" + index + ")");
        var title_index = $.trim(item.find(".song-index-num").text());
        var title = $.trim(item.find(".song-info-title").text());
        item.find(".song-info").click();
        general_wait(function() {
            return $("audio").length > 0;
        }, function() {
            var src = $("audio source").attr('src');
            str += "wget " + src + " -O '" + title_index + "-" + title + ".mp3'" + "\n";
            console.log(title_index + "-" + title + " " + src);
            $(".close-container .close").click();
            setTimeout(function() {
                loop_click(index + 1);
            }, 200);
        });
    }

    function general_wait(condition, callback) {
        let _tmp_interval = setInterval(function() {
            try {
                let result = condition();
                if (result) {
                    clearInterval(_tmp_interval);
                    callback(result);
                }
            } catch (e) {}
        }, 500);
    }

    function saveTxt(filename, content) {
        var a = document.createElement('a');
        var blob = new Blob([content]);
        a.download = filename + ".txt";
        a.href = URL.createObjectURL(blob);
        a.click();
        URL.revokeObjectURL(blob);
    }

    function initUI() {
        var html = "<div id='mybtn' style='width:50px;height:50px;text-align:center;line-height:50px;position:fixed;top:0;right:0;background:#000;color:#fff;'>开始</div>";
        $("body").append(html);
        $("#mybtn").click(function(){
            list_len = $(".playlist > .song").length;
            loop_click(0);
        });
    }

    initUI();

    /*
    setTimeout(function(){
        loop_click(0);
    }, 1000);
    */

})();