import os
import yt_dlp

def remove_playlist_title_from_filename(d):
    if d['status'] == 'finished':
        filename = d['filename']
        # 获取合集名
        playlist_title = d.get('info_dict', {}).get('playlist_title', '')
        if playlist_title and filename:
            # 如果文件名以“合集名 - ”开头,去掉
            basename = os.path.basename(filename)
            dirname = os.path.dirname(filename)
            if basename.startswith(playlist_title + ' - '):
                new_basename = basename[len(playlist_title) + 3:]  # 3是" - "的长度
                new_filename = os.path.join(dirname, new_basename)
                os.rename(filename, new_filename)
                print(f"已重命名: {filename} -> {new_filename}")

def download_bilibili(url, output_dir="downloads"):
    ydl_opts = {
        'outtmpl': os.path.join(output_dir, '%(playlist_title)s', '%(title)s.%(ext)s'),
        'format': 'bestvideo+bestaudio/best',
        'merge_output_format': 'mp4',
        'noplaylist': False,
        'concurrent_fragment_downloads': 4,
        'continue_dl': True,
        'progress_hooks': [remove_playlist_title_from_filename],  # 添加钩子
    }
    os.makedirs(output_dir, exist_ok=True)
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])

if __name__ == "__main__":
    url = input("请输入哔哩哔哩视频或合集链接:")
    download_bilibili(url)
    print("下载完成!")