import requests
from time import sleep


def download(name):
    url = f"https://api.xingzhige.com/API/Kugou_GN_new/?name={name}&n=1"
    resp = requests.get(url)
    resp.close()
    music_name = resp.json()["data"]["songname"]
    singer = resp.json()["data"]["name"]
    music_url = resp.json()["data"]["src"]
    response = requests.get(music_url, stream=True)
    formated = music_url.split("?")[0].rsplit(".", 1)[1]
    filename_without_endswith = f"{singer} - {music_name}"
    filename = f"{filename_without_endswith}.{formated}"
    filename = filename.replace("\\", "#").replace("/", "#")
    filename = filename.replace(":", "#").replace("*", "#")
    filename = filename.replace("?", "#").replace("\"", "#")
    filename = filename.replace("<", "#").replace(">", "#").replace("|", "#")
    with open(filename, "wb") as f:
        for data in response.iter_content(chunk_size=1024):
            f.write(data)
    response.close()


while True:
    music = input("请输入要下载的音乐(歌名-歌手):")
    print("正在下载，请稍后...")
    try:
        download(music)
        print("下载完成!")
    except Exception as e:
        print(e)
    sleep(2)