13LSR commited on
Commit
0a0eb07
·
1 Parent(s): a45143e
Files changed (17) hide show
  1. .dockerignore +3 -0
  2. .env +8 -0
  3. .gitignore +10 -0
  4. Dockerfile +27 -0
  5. LICENSE +21 -0
  6. cookie.txt +1 -0
  7. cookie_manager.py +469 -0
  8. docker-compose.yml +10 -0
  9. entrypoint.sh +4 -0
  10. main.py +717 -0
  11. music_api.log +21 -0
  12. music_api.py +673 -0
  13. music_downloader.py +587 -0
  14. qr_login.py +364 -0
  15. requirements.txt +0 -0
  16. templates/index.html +684 -0
  17. 使用文档.md +462 -0
.dockerignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ LICENSE
2
+ README.md
3
+ .gitignore
.env ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # 对应命令行参数的 level
2
+ LEVEL=lossless
3
+
4
+ # 对应命令行参数的 level
5
+ MODE=api
6
+
7
+ # 对应命令行参数的 url
8
+ URL=http://127.0.0.1:5000
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ .idea
2
+ .vscode
3
+
4
+ venv
5
+ .venv
6
+
7
+ __pycache__
8
+ *.pyc
9
+ *.pyo
10
+ *.pyd
Dockerfile ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ # 设置工作目录
4
+ WORKDIR /app
5
+
6
+ # 安装系统依赖(如需编译部分库)并清理缓存
7
+ RUN apt-get update && apt-get install -y --no-install-recommends \
8
+ build-essential \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ # 复制并安装 Python 依赖
12
+ COPY requirements.txt requirements.txt
13
+ RUN pip install --no-cache-dir -r requirements.txt
14
+
15
+ # 复制项目文件
16
+ COPY . .
17
+
18
+ # 时区与环境变量
19
+ ENV TZ=Asia/Shanghai \
20
+ PORT=7860 \
21
+ PYTHONUNBUFFERED=1
22
+
23
+ # 暴露端口(Hugging Face Spaces 默认使用 $PORT)
24
+ EXPOSE 7860
25
+
26
+ # 启动服务(HOST 从 main.py 读取默认 0.0.0.0,PORT 从环境变量读取)
27
+ CMD ["python", "-u", "main.py"]
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Suxiaoqinx
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
cookie.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ MUSIC_U=006B4BDE415F719815A323DA837A07E7E78AE075589A3C676EC223ABE97770ED302F86E8BDEA4B8A4E81622578B6265B89E50878216B4BFBCC11856E9B426D0580061926E62BC2BA120CF8606C1B2323254846C5C367D21627D4DA480ABD8068F708D87395FBE122E2D0BE6720B70CFF56F0719A8FB491090BADEFC800E98256EB3F3C8D1F50EF7F8D91616C5D49E957E7869F8FCA364BCBD2022C73D9262B1BD9A33E27A3419CF37975216B22463B2D08842A1ECD17548E9A2B53FAB74B8C0C86B223F2A7E78543499F41077949CEEADBA44A015AD4D6E8A32EA737D68B0A3C6D8CDECDF1C5E6A896A0A4473AB1AF4C140B78EA8F655CF9C71F9718EFD010B7E2DFAF821B8A8BD0FFC776B0547FA98A766F710A2D4B0026FE33BE3A5C70735BDCC2EF76157ED5FCC19DF507CCA47FBE364154EBCC6FC36DCEDA21B31FB52371FBC4C01E5FA8614BB0EABA8F331A58C76B0F6C4D87AA62ED40DDC34796CA0D46D635E37B456401F533ECBC7CC0637064BB089623643DB688794510E66CE74576B41DE5BAED4DF8353213263E9336E1EB3D;os=pc;appver=8.9.70;
cookie_manager.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cookie管理器模块
2
+
3
+ 提供网易云音乐Cookie管理功能,包括:
4
+ - Cookie文件读取和写入
5
+ - Cookie格式验证和解析
6
+ - Cookie有效性检查
7
+ - 自动过期处理
8
+ """
9
+
10
+ import os
11
+ import json
12
+ import time
13
+ from typing import Dict, Optional, List, Tuple, Any
14
+ from pathlib import Path
15
+ from dataclasses import dataclass
16
+ from datetime import datetime, timedelta
17
+ import logging
18
+
19
+
20
+ @dataclass
21
+ class CookieInfo:
22
+ """Cookie信息数据类"""
23
+ name: str
24
+ value: str
25
+ domain: str = ""
26
+ path: str = "/"
27
+ expires: Optional[int] = None
28
+ secure: bool = False
29
+ http_only: bool = False
30
+
31
+
32
+ class CookieException(Exception):
33
+ """Cookie相关异常类"""
34
+ pass
35
+
36
+
37
+ class CookieManager:
38
+ """Cookie管理器主类"""
39
+
40
+ def __init__(self, cookie_file: str = "cookie.txt"):
41
+ """
42
+ 初始化Cookie管理器
43
+
44
+ Args:
45
+ cookie_file: Cookie文件路径
46
+ """
47
+ self.cookie_file = Path(cookie_file)
48
+ self.logger = logging.getLogger(__name__)
49
+
50
+ # 网易云音乐相关的重要Cookie字段
51
+ self.important_cookies = {
52
+ 'MUSIC_U', # 用户标识
53
+ 'MUSIC_A', # 用户认证
54
+ '__csrf', # CSRF令牌
55
+ 'NMTID', # 设备标识
56
+ 'WEVNSM', # 会话管理
57
+ 'WNMCID', # 客户端标识
58
+ }
59
+
60
+ # 确保cookie文件存在
61
+ self._ensure_cookie_file_exists()
62
+
63
+ def _ensure_cookie_file_exists(self) -> None:
64
+ """确保Cookie文件存在"""
65
+ if not self.cookie_file.exists():
66
+ self.cookie_file.touch()
67
+ self.logger.info(f"创建Cookie文件: {self.cookie_file}")
68
+
69
+ def read_cookie(self) -> str:
70
+ """读取Cookie文件内容
71
+
72
+ Returns:
73
+ Cookie字符串内容
74
+
75
+ Raises:
76
+ CookieException: 读取失败时抛出
77
+ """
78
+ try:
79
+ if not self.cookie_file.exists():
80
+ self.logger.warning(f"Cookie文件不存在: {self.cookie_file}")
81
+ return ""
82
+
83
+ content = self.cookie_file.read_text(encoding='utf-8').strip()
84
+
85
+ if not content:
86
+ self.logger.warning("Cookie文件为空")
87
+ return ""
88
+
89
+ self.logger.debug(f"成功读取Cookie文件,长度: {len(content)}")
90
+ return content
91
+
92
+ except UnicodeDecodeError as e:
93
+ raise CookieException(f"Cookie文件编码错误: {e}")
94
+ except PermissionError as e:
95
+ raise CookieException(f"没有权限读取Cookie文件: {e}")
96
+ except Exception as e:
97
+ raise CookieException(f"读取Cookie文件失败: {e}")
98
+
99
+ def write_cookie(self, cookie_content: str) -> bool:
100
+ """写入Cookie到文件
101
+
102
+ Args:
103
+ cookie_content: Cookie内容字符串
104
+
105
+ Returns:
106
+ 是否写入成功
107
+
108
+ Raises:
109
+ CookieException: 写入失败时抛出
110
+ """
111
+ try:
112
+ if not cookie_content or not cookie_content.strip():
113
+ raise CookieException("Cookie内容不能为空")
114
+
115
+ # 验证Cookie格式
116
+ if not self.validate_cookie_format(cookie_content):
117
+ raise CookieException("Cookie格式无效")
118
+
119
+ # 写入文件
120
+ self.cookie_file.write_text(cookie_content.strip(), encoding='utf-8')
121
+
122
+ self.logger.info(f"成功写入Cookie到文件: {self.cookie_file}")
123
+ return True
124
+
125
+ except PermissionError as e:
126
+ raise CookieException(f"没有权限写入Cookie文件: {e}")
127
+ except Exception as e:
128
+ raise CookieException(f"写入Cookie文件失败: {e}")
129
+
130
+ def parse_cookies(self) -> Dict[str, str]:
131
+ """解析Cookie字符串为字典
132
+
133
+ Returns:
134
+ Cookie字典
135
+
136
+ Raises:
137
+ CookieException: 解析失败时抛出
138
+ """
139
+ try:
140
+ cookie_content = self.read_cookie()
141
+ if not cookie_content:
142
+ return {}
143
+
144
+ return self.parse_cookie_string(cookie_content)
145
+
146
+ except Exception as e:
147
+ raise CookieException(f"解析Cookie失败: {e}")
148
+
149
+ def parse_cookie_string(self, cookie_string: str) -> Dict[str, str]:
150
+ """解析Cookie字符串
151
+
152
+ Args:
153
+ cookie_string: Cookie字符串
154
+
155
+ Returns:
156
+ Cookie字典
157
+ """
158
+ if not cookie_string or not cookie_string.strip():
159
+ return {}
160
+
161
+ cookies = {}
162
+
163
+ try:
164
+ # 处理多种Cookie格式
165
+ cookie_string = cookie_string.strip()
166
+
167
+ # 分割Cookie项
168
+ cookie_pairs = []
169
+ if ';' in cookie_string:
170
+ cookie_pairs = cookie_string.split(';')
171
+ elif '\n' in cookie_string:
172
+ cookie_pairs = cookie_string.split('\n')
173
+ else:
174
+ cookie_pairs = [cookie_string]
175
+
176
+ for pair in cookie_pairs:
177
+ pair = pair.strip()
178
+ if not pair or '=' not in pair:
179
+ continue
180
+
181
+ # 分割键值对
182
+ key, value = pair.split('=', 1)
183
+ key = key.strip()
184
+ value = value.strip()
185
+
186
+ if key and value:
187
+ cookies[key] = value
188
+
189
+ self.logger.debug(f"解析得到 {len(cookies)} 个Cookie项")
190
+ return cookies
191
+
192
+ except Exception as e:
193
+ self.logger.error(f"解析Cookie字符串失败: {e}")
194
+ return {}
195
+
196
+ def validate_cookie_format(self, cookie_string: str) -> bool:
197
+ """验证Cookie格式是否有效
198
+
199
+ Args:
200
+ cookie_string: Cookie字符串
201
+
202
+ Returns:
203
+ 是否格式有效
204
+ """
205
+ if not cookie_string or not cookie_string.strip():
206
+ return False
207
+
208
+ try:
209
+ # 尝试解析Cookie
210
+ cookies = self.parse_cookie_string(cookie_string)
211
+
212
+ # 检查是否至少包含一个有效的Cookie
213
+ if not cookies:
214
+ return False
215
+
216
+ # 检查Cookie名称是否合法
217
+ for name, value in cookies.items():
218
+ if not name or not isinstance(name, str):
219
+ return False
220
+ if not isinstance(value, str):
221
+ return False
222
+ # 检查是否包含非法字符
223
+ if any(char in name for char in [' ', '\t', '\n', '\r', ';', ',']):
224
+ return False
225
+
226
+ return True
227
+
228
+ except Exception:
229
+ return False
230
+
231
+ def is_cookie_valid(self) -> bool:
232
+ """检查Cookie是否有效
233
+
234
+ Returns:
235
+ Cookie是否有效
236
+ """
237
+ try:
238
+ cookies = self.parse_cookies()
239
+
240
+ if not cookies:
241
+ self.logger.warning("Cookie为空")
242
+ return False
243
+
244
+ # 检查重要Cookie是否存在
245
+ missing_cookies = self.important_cookies - set(cookies.keys())
246
+ if missing_cookies:
247
+ self.logger.warning(f"缺少重要Cookie: {missing_cookies}")
248
+ return False
249
+
250
+ # 检查MUSIC_U是否有效(基本验证)
251
+ music_u = cookies.get('MUSIC_U', '')
252
+ if not music_u or len(music_u) < 10:
253
+ self.logger.warning("MUSIC_U Cookie无效")
254
+ return False
255
+
256
+ self.logger.debug("Cookie验证通过")
257
+ return True
258
+
259
+ except Exception as e:
260
+ self.logger.error(f"Cookie验证失败: {e}")
261
+ return False
262
+
263
+ def get_cookie_info(self) -> Dict[str, Any]:
264
+ """获取Cookie详细信息
265
+
266
+ Returns:
267
+ 包含Cookie信息的字典
268
+ """
269
+ try:
270
+ cookies = self.parse_cookies()
271
+
272
+ info = {
273
+ 'file_path': str(self.cookie_file),
274
+ 'file_exists': self.cookie_file.exists(),
275
+ 'file_size': self.cookie_file.stat().st_size if self.cookie_file.exists() else 0,
276
+ 'cookie_count': len(cookies),
277
+ 'is_valid': self.is_cookie_valid(),
278
+ 'important_cookies_present': list(self.important_cookies & set(cookies.keys())),
279
+ 'missing_important_cookies': list(self.important_cookies - set(cookies.keys())),
280
+ 'all_cookie_names': list(cookies.keys())
281
+ }
282
+
283
+ # 添加文件修改时间
284
+ if self.cookie_file.exists():
285
+ mtime = self.cookie_file.stat().st_mtime
286
+ info['last_modified'] = datetime.fromtimestamp(mtime).isoformat()
287
+
288
+ return info
289
+
290
+ except Exception as e:
291
+ return {
292
+ 'error': str(e),
293
+ 'file_path': str(self.cookie_file),
294
+ 'file_exists': False,
295
+ 'is_valid': False
296
+ }
297
+
298
+ def backup_cookie(self, backup_suffix: str = None) -> str:
299
+ """备份Cookie文件
300
+
301
+ Args:
302
+ backup_suffix: 备份文件后缀,默认使用时间戳
303
+
304
+ Returns:
305
+ 备份文件路径
306
+
307
+ Raises:
308
+ CookieException: 备份失败时抛出
309
+ """
310
+ try:
311
+ if not self.cookie_file.exists():
312
+ raise CookieException("Cookie文件不存在,无法备份")
313
+
314
+ if backup_suffix is None:
315
+ backup_suffix = datetime.now().strftime("%Y%m%d_%H%M%S")
316
+
317
+ backup_path = self.cookie_file.with_suffix(f".{backup_suffix}.bak")
318
+
319
+ # 复制文件内容
320
+ content = self.cookie_file.read_text(encoding='utf-8')
321
+ backup_path.write_text(content, encoding='utf-8')
322
+
323
+ self.logger.info(f"Cookie备份成功: {backup_path}")
324
+ return str(backup_path)
325
+
326
+ except Exception as e:
327
+ raise CookieException(f"备份Cookie文件失败: {e}")
328
+
329
+ def restore_cookie(self, backup_path: str) -> bool:
330
+ """从备份恢复Cookie
331
+
332
+ Args:
333
+ backup_path: 备份文件路径
334
+
335
+ Returns:
336
+ 是否恢复成功
337
+
338
+ Raises:
339
+ CookieException: 恢复失败时抛出
340
+ """
341
+ try:
342
+ backup_file = Path(backup_path)
343
+ if not backup_file.exists():
344
+ raise CookieException(f"备份文件不存在: {backup_path}")
345
+
346
+ # 读取备份内容
347
+ backup_content = backup_file.read_text(encoding='utf-8')
348
+
349
+ # 验证备份内容
350
+ if not self.validate_cookie_format(backup_content):
351
+ raise CookieException("备份文件中的Cookie格式无效")
352
+
353
+ # 写入当前Cookie文件
354
+ self.write_cookie(backup_content)
355
+
356
+ self.logger.info(f"从备份恢复Cookie成功: {backup_path}")
357
+ return True
358
+
359
+ except Exception as e:
360
+ raise CookieException(f"恢复Cookie失败: {e}")
361
+
362
+ def clear_cookie(self) -> bool:
363
+ """清空Cookie文件
364
+
365
+ Returns:
366
+ 是否清空成功
367
+ """
368
+ try:
369
+ if self.cookie_file.exists():
370
+ self.cookie_file.write_text("", encoding='utf-8')
371
+ self.logger.info("Cookie文件已清空")
372
+ return True
373
+
374
+ except Exception as e:
375
+ self.logger.error(f"清空Cookie文件失败: {e}")
376
+ return False
377
+
378
+ def update_cookie(self, new_cookies: Dict[str, str]) -> bool:
379
+ """更新Cookie
380
+
381
+ Args:
382
+ new_cookies: 新的Cookie字典
383
+
384
+ Returns:
385
+ 是否更新成功
386
+ """
387
+ try:
388
+ if not new_cookies:
389
+ raise CookieException("新Cookie不能为空")
390
+
391
+ # 读取现有Cookie
392
+ existing_cookies = self.parse_cookies()
393
+
394
+ # 合并Cookie
395
+ existing_cookies.update(new_cookies)
396
+
397
+ # 转换为Cookie字符串
398
+ cookie_string = '; '.join(f"{k}={v}" for k, v in existing_cookies.items())
399
+
400
+ # 写入文件
401
+ return self.write_cookie(cookie_string)
402
+
403
+ except Exception as e:
404
+ self.logger.error(f"更新Cookie失败: {e}")
405
+ return False
406
+
407
+ def get_cookie_for_request(self) -> Dict[str, str]:
408
+ """获取用于HTTP请求的Cookie字典
409
+
410
+ Returns:
411
+ 适用于requests库的Cookie字典
412
+ """
413
+ try:
414
+ cookies = self.parse_cookies()
415
+
416
+ # 过滤掉空值
417
+ filtered_cookies = {k: v for k, v in cookies.items() if k and v}
418
+
419
+ return filtered_cookies
420
+
421
+ except Exception as e:
422
+ self.logger.error(f"获取请求Cookie失败: {e}")
423
+ return {}
424
+
425
+ def format_cookie_string(self, cookies: Dict[str, str]) -> str:
426
+ """将Cookie字典格式化为字符串
427
+
428
+ Args:
429
+ cookies: Cookie字典
430
+
431
+ Returns:
432
+ Cookie字符串
433
+ """
434
+ if not cookies:
435
+ return ""
436
+
437
+ return '; '.join(f"{k}={v}" for k, v in cookies.items() if k and v)
438
+
439
+ def __str__(self) -> str:
440
+ """字符串表示"""
441
+ info = self.get_cookie_info()
442
+ return f"CookieManager(file={info['file_path']}, valid={info['is_valid']}, count={info['cookie_count']})"
443
+
444
+ def __repr__(self) -> str:
445
+ """详细字符串表示"""
446
+ return self.__str__()
447
+
448
+
449
+ if __name__ == "__main__":
450
+ # 测试代码
451
+ import sys
452
+
453
+ # 配置日志
454
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
455
+
456
+ manager = CookieManager()
457
+
458
+ print("Cookie管理器模块")
459
+ print("支持的功能:")
460
+ print("- Cookie文件读写")
461
+ print("- Cookie格式验证")
462
+ print("- Cookie有效性检查")
463
+ print("- Cookie备份和恢复")
464
+ print("- Cookie信息查看")
465
+
466
+ # 显示当前Cookie信息
467
+ info = manager.get_cookie_info()
468
+ print(f"\n当前Cookie状态: {manager}")
469
+ print(f"详细信息: {info}")
docker-compose.yml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ netease-url:
3
+ build:
4
+ context: .
5
+ dockerfile: Dockerfile
6
+ env_file:
7
+ - .env
8
+ ports:
9
+ - "5000:5000"
10
+ restart: unless-stopped
entrypoint.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/sh
2
+ # 兼容保留:原先使用 LEVEL/MODE/URL 参数的启动方式已不再需要。
3
+ # 现在直接启动 Python 应用,由 main.py 自行读取环境变量(HOST / PORT 等)。
4
+ exec python3 -u main.py
main.py ADDED
@@ -0,0 +1,717 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ 网易云音乐 API 服务主程序
2
+ 提供网易云音乐相关 API 服务,包括:
3
+ - 歌曲信息获取
4
+ - 音乐搜索
5
+ - 歌单和专辑详情
6
+ - 音乐下载
7
+ - 健康检查
8
+ """
9
+
10
+ import logging
11
+ import sys
12
+ import time
13
+ import traceback
14
+ import os
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Dict, Any, Optional, Tuple
18
+ from urllib.parse import quote
19
+ from flask import Flask, request, send_file, render_template, Response
20
+
21
+ try:
22
+ from music_api import (
23
+ NeteaseAPI, APIException, QualityLevel,
24
+ url_v1, name_v1, lyric_v1, search_music,
25
+ playlist_detail, album_detail
26
+ )
27
+ from cookie_manager import CookieManager, CookieException
28
+ from music_downloader import MusicDownloader, DownloadException, AudioFormat
29
+ except ImportError as e:
30
+ print(f" 导入模块失败: {e}")
31
+ print("请确保所有依赖模块存在且可用")
32
+ sys.exit(1)
33
+
34
+
35
+ @dataclass
36
+ class APIConfig:
37
+ """API 配置类"""
38
+ host: str = '0.0.0.0'
39
+ port: int = 5000
40
+ debug: bool = False
41
+ downloads_dir: str = 'downloads'
42
+ max_file_size: int = 500 * 1024 * 1024 # 500MB
43
+ request_timeout: int = 30
44
+ log_level: str = 'INFO'
45
+ cors_origins: str = '*'
46
+
47
+
48
+ class APIResponse:
49
+ """API 响应工具类"""
50
+
51
+ @staticmethod
52
+ def success(data: Any = None, message: str = 'success', status_code: int = 200) -> Tuple[Dict[str, Any], int]:
53
+ """成功响应"""
54
+ response = {
55
+ 'status': status_code,
56
+ 'success': True,
57
+ 'message': message
58
+ }
59
+ if data is not None:
60
+ response['data'] = data
61
+ return response, status_code
62
+
63
+ @staticmethod
64
+ def error(message: str, status_code: int = 400, error_code: str = None) -> Tuple[Dict[str, Any], int]:
65
+ """错误响应"""
66
+ response = {
67
+ 'status': status_code,
68
+ 'success': False,
69
+ 'message': message
70
+ }
71
+ if error_code:
72
+ response['error_code'] = error_code
73
+ return response, status_code
74
+
75
+
76
+ class MusicAPIService:
77
+ """音乐 API 服务类"""
78
+
79
+ def __init__(self, config: APIConfig):
80
+ self.config = config
81
+ self.logger = self._setup_logger()
82
+ self.cookie_manager = CookieManager()
83
+ self.netease_api = NeteaseAPI()
84
+ self.downloader = MusicDownloader()
85
+
86
+ # 创建下载目录
87
+ self.downloads_path = Path(config.downloads_dir)
88
+ self.downloads_path.mkdir(exist_ok=True)
89
+
90
+ self.logger.info(f" 音乐 API 服务初始化完成,下载目录: {self.downloads_path.absolute()}")
91
+
92
+ def _setup_logger(self) -> logging.Logger:
93
+ """设置日志记录器"""
94
+ logger = logging.getLogger('music_api')
95
+ logger.setLevel(getattr(logging, self.config.log_level.upper()))
96
+
97
+ if not logger.handlers:
98
+ # 控制台处理器
99
+ console_handler = logging.StreamHandler()
100
+ console_formatter = logging.Formatter(
101
+ '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
102
+ )
103
+ console_handler.setFormatter(console_formatter)
104
+ logger.addHandler(console_handler)
105
+
106
+ # 文件处理器
107
+ try:
108
+ file_handler = logging.FileHandler('music_api.log', encoding='utf-8')
109
+ file_formatter = logging.Formatter(
110
+ '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
111
+ )
112
+ file_handler.setFormatter(file_formatter)
113
+ logger.addHandler(file_handler)
114
+ except Exception as e:
115
+ logger.warning(f" 无法创建日志文件: {e}")
116
+
117
+ return logger
118
+
119
+ def _get_cookies(self) -> Dict[str, str]:
120
+ """获取 Cookie"""
121
+ try:
122
+ cookie_str = self.cookie_manager.read_cookie()
123
+ return self.cookie_manager.parse_cookie_string(cookie_str)
124
+ except CookieException as e:
125
+ self.logger.warning(f" 获取 Cookie 失败: {e}")
126
+ return {}
127
+ except Exception as e:
128
+ self.logger.error(f"Cookie 处理异常: {e}")
129
+ return {}
130
+
131
+ def _extract_music_id(self, id_or_url: str) -> str:
132
+ """提取音乐 ID"""
133
+ try:
134
+ # 处理短链接
135
+ if '163cn.tv' in id_or_url:
136
+ import requests
137
+ response = requests.get(id_or_url, allow_redirects=False, timeout=10)
138
+ id_or_url = response.headers.get('Location', id_or_url)
139
+
140
+ # 处理网易云链接
141
+ if 'music.163.com' in id_or_url:
142
+ index = id_or_url.find('id=') + 3
143
+ if index > 2:
144
+ return id_or_url[index:].split('&')[0]
145
+
146
+ # 直接返回 ID
147
+ return str(id_or_url).strip()
148
+
149
+ except Exception as e:
150
+ self.logger.error(f" 提取音乐 ID 失败: {e}")
151
+ return str(id_or_url).strip()
152
+
153
+ def _format_file_size(self, size_bytes: int) -> str:
154
+ """格式化文件大小"""
155
+ if size_bytes == 0:
156
+ return "0B"
157
+
158
+ units = ["B", "KB", "MB", "GB", "TB"]
159
+ size = float(size_bytes)
160
+ unit_index = 0
161
+
162
+ while size >= 1024.0 and unit_index < len(units) - 1:
163
+ size /= 1024.0
164
+ unit_index += 1
165
+
166
+ return f"{size:.2f}{units[unit_index]}"
167
+
168
+ def _get_quality_display_name(self, quality: str) -> str:
169
+ """获取音质显示名称"""
170
+ quality_names = {
171
+ 'standard': "标准音质",
172
+ 'exhigh': "极高音质",
173
+ 'lossless': "无损音质",
174
+ 'hires': "Hi-Res 音质",
175
+ 'sky': "沉浸环绕声",
176
+ 'jyeffect': "高清环绕声",
177
+ 'jymaster': "超清母带"
178
+ }
179
+ return quality_names.get(quality, f" 未知音质 ({quality})")
180
+
181
+ def _validate_request_params(self, required_params: Dict[str, Any]) -> Optional[Tuple[Dict[str, Any], int]]:
182
+ """验证请求参数"""
183
+ for param_name, param_value in required_params.items():
184
+ if not param_value:
185
+ return APIResponse.error(f" 参数 '{param_name}' 不能为空 ", 400)
186
+ return None
187
+
188
+ def _safe_get_request_data(self) -> Dict[str, Any]:
189
+ """安全获取请求数据"""
190
+ try:
191
+ if request.method == 'GET':
192
+ return dict(request.args)
193
+ else:
194
+ # 优先使用 JSON 数据,然后是表单数据
195
+ json_data = request.get_json(silent=True) or {}
196
+ form_data = dict(request.form)
197
+ # 合并数据,JSON 优先
198
+ return {**form_data, **json_data}
199
+ except Exception as e:
200
+ self.logger.error(f" 获取请求数据失败: {e}")
201
+ return {}
202
+
203
+
204
+ # 创建 Flask 应用和服务实例
205
+ config = APIConfig()
206
+ # 从环境变量加载配置(适配 Hugging Face Spaces)
207
+ # HOST:默认 0.0.0.0;PORT:优先读取 PORT,未设置则默认 7860(HF Spaces 会注入 PORT)
208
+ host = os.getenv('HOST', (config.host or '0.0.0.0'))
209
+ port_env = os.getenv('PORT')
210
+ try:
211
+ port = int(port_env) if port_env else 7860
212
+ except ValueError:
213
+ port = 7860
214
+ config.host = host
215
+ config.port = port
216
+
217
+ # 其他可选配置:DEBUG、DOWNLOADS_DIR、REQUEST_TIMEOUT、LOG_LEVEL、CORS_ORIGINS
218
+ debug_env = os.getenv('DEBUG')
219
+ if debug_env is not None:
220
+ config.debug = debug_env.lower() in ('1', 'true', 'yes', 'on')
221
+
222
+ downloads_dir = os.getenv('DOWNLOADS_DIR')
223
+ if downloads_dir:
224
+ config.downloads_dir = downloads_dir
225
+
226
+ req_timeout = os.getenv('REQUEST_TIMEOUT')
227
+ if req_timeout:
228
+ try:
229
+ config.request_timeout = int(req_timeout)
230
+ except ValueError:
231
+ pass
232
+
233
+ log_level = os.getenv('LOG_LEVEL')
234
+ if log_level:
235
+ config.log_level = log_level
236
+
237
+ cors_origins = os.getenv('CORS_ORIGINS')
238
+ if cors_origins:
239
+ config.cors_origins = cors_origins
240
+
241
+ app = Flask(__name__)
242
+ api_service = MusicAPIService(config)
243
+
244
+
245
+ @app.before_request
246
+ def before_request():
247
+ """请求前处理"""
248
+ # 记录请求信息
249
+ api_service.logger.info(
250
+ f"{request.method} {request.path} - IP: {request.remote_addr} - "
251
+ f"User-Agent: {request.headers.get('User-Agent', 'Unknown')}"
252
+ )
253
+
254
+
255
+ @app.after_request
256
+ def after_request(response: Response) -> Response:
257
+ """请求后处理 - 设置 CORS 头"""
258
+ response.headers.add('Access-Control-Allow-Origin', config.cors_origins)
259
+ response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
260
+ response.headers.add('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
261
+ response.headers.add('Access-Control-Max-Age', '3600')
262
+
263
+ # 记录响应信息
264
+ api_service.logger.info(f" 响应状态: {response.status_code}")
265
+ return response
266
+
267
+
268
+ @app.errorhandler(400)
269
+ def handle_bad_request(e):
270
+ """处理 400 错误"""
271
+ return APIResponse.error("请求参数错误", 400)
272
+
273
+
274
+ @app.errorhandler(404)
275
+ def handle_not_found(e):
276
+ """处理 404 错误"""
277
+ return APIResponse.error("请求的资源不存在", 404)
278
+
279
+
280
+ @app.errorhandler(500)
281
+ def handle_internal_error(e):
282
+ """处理 500 错误"""
283
+ api_service.logger.error(f" 服务器内部错误: {e}")
284
+ return APIResponse.error("服务器内部错误", 500)
285
+
286
+
287
+ @app.route('/')
288
+ def index() -> str:
289
+ """首页路由"""
290
+ return render_template('index.html')
291
+
292
+
293
+ @app.route('/health', methods=['GET'])
294
+ def health_check():
295
+ """健康检查 API"""
296
+ try:
297
+ # 检查 Cookie 状态
298
+ cookie_status = api_service.cookie_manager.is_cookie_valid()
299
+
300
+ health_info = {
301
+ 'service': 'running',
302
+ 'timestamp': int(time.time()) if 'time' in sys.modules else None,
303
+ 'cookie_status': 'valid' if cookie_status else 'invalid',
304
+ 'downloads_dir': str(api_service.downloads_path.absolute()),
305
+ 'version': '2.0.0'
306
+ }
307
+
308
+ return APIResponse.success(health_info, "API 服务运行正常")
309
+
310
+ except Exception as e:
311
+ api_service.logger.error(f" 健康检查失败: {e}")
312
+ return APIResponse.error(f" 健康检查失败: {str(e)}", 500)
313
+
314
+
315
+ @app.route('/song', methods=['GET', 'POST'])
316
+ @app.route('/Song_V1', methods=['GET', 'POST']) # 向后兼容
317
+ def get_song_info():
318
+ """获取歌曲信息 API"""
319
+ try:
320
+ # 获取请求参数
321
+ data = api_service._safe_get_request_data()
322
+ song_ids = data.get('ids') or data.get('id')
323
+ url = data.get('url')
324
+ level = data.get('level', 'lossless')
325
+ info_type = data.get('type', 'url')
326
+
327
+ # 参数验证
328
+ if not song_ids and not url:
329
+ return APIResponse.error("必须提供 'ids'、'id' 或 'url' 参数")
330
+
331
+ # 提取音乐 ID
332
+ music_id = api_service._extract_music_id(song_ids or url)
333
+
334
+ # 验证音质参数
335
+ valid_levels = ['standard', 'exhigh', 'lossless', 'hires', 'sky', 'jyeffect', 'jymaster']
336
+ if level not in valid_levels:
337
+ return APIResponse.error(f" 无效的音质参数,支持: {', '.join(valid_levels)}")
338
+
339
+ # 验证类型参数
340
+ valid_types = ['url', 'name', 'lyric', 'json']
341
+ if info_type not in valid_types:
342
+ return APIResponse.error(f" 无效的类型参数,支持: {', '.join(valid_types)}")
343
+
344
+ cookies = api_service._get_cookies()
345
+
346
+ # 根据类型获取不同信息
347
+ if info_type == 'url':
348
+ result = url_v1(music_id, level, cookies)
349
+ if result and result.get('data') and len(result['data']) > 0:
350
+ song_data = result['data'][0]
351
+ response_data = {
352
+ 'id': song_data.get('id'),
353
+ 'url': song_data.get('url'),
354
+ 'level': song_data.get('level'),
355
+ 'quality_name': api_service._get_quality_display_name(song_data.get('level', level)),
356
+ 'size': song_data.get('size'),
357
+ 'size_formatted': api_service._format_file_size(song_data.get('size', 0)),
358
+ 'type': song_data.get('type'),
359
+ 'bitrate': song_data.get('br')
360
+ }
361
+ return APIResponse.success(response_data, "获取歌曲 URL 成功")
362
+ else:
363
+ return APIResponse.error("获取音乐 URL 失败,可能是版权限制或音质不支持", 404)
364
+
365
+ elif info_type == 'name':
366
+ result = name_v1(music_id)
367
+ return APIResponse.success(result, "获取歌曲信息成功")
368
+
369
+ elif info_type == 'lyric':
370
+ result = lyric_v1(music_id, cookies)
371
+ return APIResponse.success(result, "获取歌词成功")
372
+
373
+ elif info_type == 'json':
374
+ # 获取完整的歌曲信息(用于前端解析)
375
+ song_info = name_v1(music_id)
376
+ url_info = url_v1(music_id, level, cookies)
377
+ lyric_info = lyric_v1(music_id, cookies)
378
+
379
+ if not song_info or 'songs' not in song_info or not song_info['songs']:
380
+ return APIResponse.error("未找到歌曲信息", 404)
381
+
382
+ song_data = song_info['songs'][0]
383
+
384
+ # 构建前端期望的响应格式
385
+ response_data = {
386
+ 'id': music_id,
387
+ 'name': song_data.get('name', ''),
388
+ 'ar_name': ', '.join(artist['name'] for artist in song_data.get('ar', [])),
389
+ 'al_name': song_data.get('al', {}).get('name', ''),
390
+ 'pic': song_data.get('al', {}).get('picUrl', ''),
391
+ 'level': level,
392
+ 'lyric': lyric_info.get('lrc', {}).get('lyric', '') if lyric_info else '',
393
+ 'tlyric': lyric_info.get('tlyric', {}).get('lyric', '') if lyric_info else ''
394
+ }
395
+
396
+ # 添加 URL 和大小信息
397
+ if url_info and url_info.get('data') and len(url_info['data']) > 0:
398
+ url_data = url_info['data'][0]
399
+ response_data.update({
400
+ 'url': url_data.get('url', ''),
401
+ 'size': api_service._format_file_size(url_data.get('size', 0)),
402
+ 'level': url_data.get('level', level)
403
+ })
404
+ else:
405
+ response_data.update({
406
+ 'url': '',
407
+ 'size': '获取失败'
408
+ })
409
+
410
+ return APIResponse.success(response_data, "获取歌曲信息成功")
411
+
412
+ except APIException as e:
413
+ api_service.logger.error(f"API 调用失败: {e}")
414
+ return APIResponse.error(f"API 调用失败: {str(e)}", 500)
415
+ except Exception as e:
416
+ api_service.logger.error(f" 获取歌曲信息异常: {e}\n{traceback.format_exc()}")
417
+ return APIResponse.error(f" 服务器错误: {str(e)}", 500)
418
+
419
+
420
+ @app.route('/search', methods=['GET', 'POST'])
421
+ @app.route('/Search', methods=['GET', 'POST']) # 向后兼容
422
+ def search_music_api():
423
+ """搜索音乐 API"""
424
+ try:
425
+ # 获取请求参数
426
+ data = api_service._safe_get_request_data()
427
+ keyword = data.get('keyword') or data.get('keywords') or data.get('q')
428
+ limit = int(data.get('limit', 30))
429
+ offset = int(data.get('offset', 0))
430
+ search_type = data.get('type', '1') # 1 - 歌曲, 10 - 专辑, 100 - 歌手, 1000 - 歌单
431
+
432
+ # 参数验证
433
+ validation_error = api_service._validate_request_params({'keyword': keyword})
434
+ if validation_error:
435
+ return validation_error
436
+
437
+ # 限制搜索数量
438
+ if limit > 100:
439
+ limit = 100
440
+
441
+ cookies = api_service._get_cookies()
442
+ result = search_music(keyword, cookies, limit)
443
+
444
+ # search_music 返回的是歌曲列表,需要包装成前端期望的格式
445
+ if result:
446
+ for song in result:
447
+ # 添加艺术家字符串(如果需要)
448
+ if 'artists' in song:
449
+ song['artist_string'] = song['artists']
450
+
451
+ return APIResponse.success(result, "搜索完成")
452
+
453
+ except ValueError as e:
454
+ return APIResponse.error(f" 参数格式错误: {str(e)}")
455
+ except Exception as e:
456
+ api_service.logger.error(f" 搜索音乐异常: {e}\n{traceback.format_exc()}")
457
+ return APIResponse.error(f" 搜索失败: {str(e)}", 500)
458
+
459
+
460
+ @app.route('/playlist', methods=['GET', 'POST'])
461
+ @app.route('/Playlist', methods=['GET', 'POST']) # 向后兼容
462
+ def get_playlist():
463
+ """获取歌单详情 API"""
464
+ try:
465
+ # 获取请求参数
466
+ data = api_service._safe_get_request_data()
467
+ playlist_id = data.get('id')
468
+
469
+ # 参数验证
470
+ validation_error = api_service._validate_request_params({'playlist_id': playlist_id})
471
+ if validation_error:
472
+ return validation_error
473
+
474
+ cookies = api_service._get_cookies()
475
+ result = playlist_detail(playlist_id, cookies)
476
+
477
+ # 适配前端期望的响应格式
478
+ response_data = {
479
+ 'status': 'success',
480
+ 'playlist': result
481
+ }
482
+
483
+ return APIResponse.success(response_data, "获取歌单详情成功")
484
+
485
+ except Exception as e:
486
+ api_service.logger.error(f" 获取歌单异常: {e}\n{traceback.format_exc()}")
487
+ return APIResponse.error(f" 获取歌单失败: {str(e)}", 500)
488
+
489
+
490
+ @app.route('/album', methods=['GET', 'POST'])
491
+ @app.route('/Album', methods=['GET', 'POST']) # 向后兼容
492
+ def get_album():
493
+ """获取专辑详情 API"""
494
+ try:
495
+ # 获取请求参数
496
+ data = api_service._safe_get_request_data()
497
+ album_id = data.get('id')
498
+
499
+ # 参数验证
500
+ validation_error = api_service._validate_request_params({'album_id': album_id})
501
+ if validation_error:
502
+ return validation_error
503
+
504
+ cookies = api_service._get_cookies()
505
+ result = album_detail(album_id, cookies)
506
+
507
+ # 适配前端期望的响应格式
508
+ response_data = {
509
+ 'status': 200,
510
+ 'album': result
511
+ }
512
+
513
+ return APIResponse.success(response_data, "获取专辑详情成功")
514
+
515
+ except Exception as e:
516
+ api_service.logger.error(f" 获取专辑异常: {e}\n{traceback.format_exc()}")
517
+ return APIResponse.error(f" 获取专辑失败: {str(e)}", 500)
518
+
519
+
520
+ @app.route('/download', methods=['GET', 'POST'])
521
+ @app.route('/Download', methods=['GET', 'POST']) # 向后兼容
522
+ def download_music_api():
523
+ """下载音乐 API"""
524
+ try:
525
+ # 获取请求参数
526
+ data = api_service._safe_get_request_data()
527
+ music_id = data.get('id')
528
+ quality = data.get('quality', 'lossless')
529
+ return_format = data.get('format', 'file') # file 或 json
530
+
531
+ # 参数验证
532
+ validation_error = api_service._validate_request_params({'music_id': music_id})
533
+ if validation_error:
534
+ return validation_error
535
+
536
+ # 验证音质参数
537
+ valid_qualities = ['standard', 'exhigh', 'lossless', 'hires', 'sky', 'jyeffect', 'jymaster']
538
+ if quality not in valid_qualities:
539
+ return APIResponse.error(f" 无效的音质参数,支持: {', '.join(valid_qualities)}")
540
+
541
+ # 验证返回格式
542
+ if return_format not in ['file', 'json']:
543
+ return APIResponse.error("返回格式只支持 'file' 或 'json'")
544
+
545
+ music_id = api_service._extract_music_id(music_id)
546
+ cookies = api_service._get_cookies()
547
+
548
+ # 获取音乐基本信息
549
+ song_info = name_v1(music_id)
550
+ if not song_info or 'songs' not in song_info or not song_info['songs']:
551
+ return APIResponse.error("未找到音乐信息", 404)
552
+
553
+ # 获取音乐下载链接
554
+ url_info = url_v1(music_id, quality, cookies)
555
+ if not url_info or 'data' not in url_info or not url_info['data'] or not url_info['data'][0].get('url'):
556
+ return APIResponse.error("无法获取音乐下载链接,可能是版权限制或音质不支持", 404)
557
+
558
+ # 构建音乐信息
559
+ song_data = song_info['songs'][0]
560
+ url_data = url_info['data'][0]
561
+
562
+ music_info = {
563
+ 'id': music_id,
564
+ 'name': song_data['name'],
565
+ 'artist_string': ', '.join(artist['name'] for artist in song_data['ar']),
566
+ 'album': song_data['al']['name'],
567
+ 'pic_url': song_data['al']['picUrl'],
568
+ 'file_type': url_data['type'],
569
+ 'file_size': url_data['size'],
570
+ 'duration': song_data.get('dt', 0),
571
+ 'download_url': url_data['url']
572
+ }
573
+
574
+ # 生成安全文件名
575
+ safe_name = f"{music_info['name']} [{quality}]"
576
+ safe_name = ''.join(c for c in safe_name if c not in r'<>:"/\|?*')
577
+ filename = f"{safe_name}.{music_info['file_type']}"
578
+
579
+ file_path = api_service.downloads_path / filename
580
+
581
+ # 检查文件是否已存在
582
+ if file_path.exists():
583
+ api_service.logger.info(f" 文件已存在: {filename}")
584
+ else:
585
+ # 使用优化后的下载器下载
586
+ try:
587
+ download_result = api_service.downloader.download_music_file(
588
+ music_id, quality
589
+ )
590
+
591
+ if not download_result.success:
592
+ return APIResponse.error(f" 下载失败: {download_result.error_message}", 500)
593
+
594
+ file_path = Path(download_result.file_path)
595
+ api_service.logger.info(f" 下载完成: {filename}")
596
+
597
+ except DownloadException as e:
598
+ api_service.logger.error(f" 下载异常: {e}")
599
+ return APIResponse.error(f" 下载失败: {str(e)}", 500)
600
+
601
+ # 根据返回格式返回结果
602
+ if return_format == 'json':
603
+ response_data = {
604
+ 'music_id': music_id,
605
+ 'name': music_info['name'],
606
+ 'artist': music_info['artist_string'],
607
+ 'album': music_info['album'],
608
+ 'quality': quality,
609
+ 'quality_name': api_service._get_quality_display_name(quality),
610
+ 'file_type': music_info['file_type'],
611
+ 'file_size': music_info['file_size'],
612
+ 'file_size_formatted': api_service._format_file_size(music_info['file_size']),
613
+ 'file_path': str(file_path.absolute()),
614
+ 'filename': filename,
615
+ 'duration': music_info['duration']
616
+ }
617
+ return APIResponse.success(response_data, "下载完成")
618
+ else:
619
+ # 返回文件下载
620
+ if not file_path.exists():
621
+ return APIResponse.error("文件不存在", 404)
622
+
623
+ try:
624
+ response = send_file(
625
+ str(file_path),
626
+ as_attachment=True,
627
+ download_name=filename,
628
+ mimetype=f"audio/{music_info['file_type']}"
629
+ )
630
+ response.headers['X-Download-Message'] = 'Download completed successfully'
631
+ response.headers['X-Download-Filename'] = quote(filename, safe='')
632
+ return response
633
+ except Exception as e:
634
+ api_service.logger.error(f" 发送文件失败: {e}")
635
+ return APIResponse.error(f" 文件发送失败: {str(e)}", 500)
636
+
637
+ except Exception as e:
638
+ api_service.logger.error(f" 下载音乐异常: {e}\n{traceback.format_exc()}")
639
+ return APIResponse.error(f" 下载异常: {str(e)}", 500)
640
+
641
+
642
+ @app.route('/api/info', methods=['GET'])
643
+ def api_info():
644
+ """API 信息接口"""
645
+ try:
646
+ info = {
647
+ 'name': ' 网易云音乐 API 服务',
648
+ 'version': '2.0.0',
649
+ 'description': ' 提供网易云音乐相关 API 服务',
650
+ 'endpoints': {
651
+ '/health': 'GET - 健康检查',
652
+ '/song': 'GET / POST - 获取歌曲信息',
653
+ '/search': 'GET / POST - 搜索音乐',
654
+ '/playlist': 'GET / POST - 获取歌单详情',
655
+ '/album': 'GET / POST - 获取专辑详情',
656
+ '/download': 'GET / POST - 下载音乐',
657
+ '/api/info': 'GET - API 信息'
658
+ },
659
+ 'supported_qualities': [
660
+ 'standard', 'exhigh', 'lossless',
661
+ 'hires', 'sky', 'jyeffect', 'jymaster'
662
+ ],
663
+ 'config': {
664
+ 'downloads_dir': str(api_service.downloads_path.absolute()),
665
+ 'max_file_size': f"{config.max_file_size // (1024*1024)}MB",
666
+ 'request_timeout': f"{config.request_timeout}s"
667
+ }
668
+ }
669
+
670
+ return APIResponse.success(info, "API 信息获取成功")
671
+
672
+ except Exception as e:
673
+ api_service.logger.error(f" 获取 API 信息异常: {e}")
674
+ return APIResponse.error(f" 获取 API 信息失败: {str(e)}", 500)
675
+
676
+
677
+ def start_api_server():
678
+ """启动 API 服务器"""
679
+ try:
680
+ print("\n" + "="*60)
681
+ print("🚀 网易云音乐 API 服务启动中...")
682
+ print("="*60)
683
+ print(f"📡 服务地址: http://{config.host}:{config.port}")
684
+ print(f"📁 下载目录: {api_service.downloads_path.absolute()}")
685
+ print(f"📋 日志级别: {config.log_level}")
686
+ print("\n📚 API 端点:")
687
+ print(f"├─ GET /health - 健康检查")
688
+ print(f"├─ POST /song - 获取歌曲信息")
689
+ print(f"├─ POST /search - 搜索音乐")
690
+ print(f"├─ POST /playlist - 获取歌单详情")
691
+ print(f"├─ POST /album - 获取专辑详情")
692
+ print(f"├─ POST /download - 下载音乐")
693
+ print(f"└─ GET /api/info - API 信息")
694
+ print("\n🎵 支持的音质:")
695
+ print(f" standard, exhigh, lossless, hires, sky, jyeffect, jymaster")
696
+ print("="*60)
697
+ print(f"⏰ 启动时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
698
+ print("🌟 服务已就绪,等待请求...\n")
699
+
700
+ # 启动 Flask 应用
701
+ app.run(
702
+ host=config.host,
703
+ port=config.port,
704
+ debug=config.debug,
705
+ threaded=True
706
+ )
707
+
708
+ except KeyboardInterrupt:
709
+ print("\n\n👋 服务已停止")
710
+ except Exception as e:
711
+ api_service.logger.error(f" 启动服务失败: {e}")
712
+ print(f"❌ 启动失败: {e}")
713
+ sys.exit(1)
714
+
715
+
716
+ if __name__ == '__main__':
717
+ start_api_server()
music_api.log ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2025-09-23 23:10:14,710 - music_api - INFO - __init__:90 - 音乐API服务初始化完成,下载目录: D:\byzxj\R\program\git\1\netease2\Netease_url\downloads
2
+ 2025-09-23 23:10:28,340 - music_api - INFO - before_request:214 - GET / - IP: 127.0.0.1 - User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36
3
+ 2025-09-23 23:10:28,346 - music_api - INFO - after_request:229 - 响应状态: 200
4
+ 2025-09-23 23:10:59,810 - music_api - INFO - before_request:214 - GET /.well-known/appspecific/com.chrome.devtools.json - IP: 127.0.0.1 - User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36
5
+ 2025-09-23 23:10:59,811 - music_api - INFO - after_request:229 - 响应状态: 404
6
+ 2025-09-23 23:11:52,684 - music_api - INFO - before_request:214 - GET / - IP: 127.0.0.1 - User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36
7
+ 2025-09-23 23:11:52,684 - music_api - INFO - after_request:229 - 响应状态: 200
8
+ 2025-09-23 23:11:53,911 - music_api - INFO - before_request:214 - GET / - IP: 127.0.0.1 - User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36
9
+ 2025-09-23 23:11:53,911 - music_api - INFO - after_request:229 - 响应状态: 200
10
+ 2025-09-23 23:31:05,552 - music_api - INFO - __init__:90 - 音乐API服务初始化完成,下载目录: D:\byzxj\R\program\git\1\netease\Netease_url\downloads
11
+ 2025-09-23 23:31:11,957 - music_api - INFO - before_request:214 - GET / - IP: 127.0.0.1 - User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36
12
+ 2025-09-23 23:31:11,963 - music_api - INFO - after_request:229 - 响应状态: 200
13
+ 2025-09-23 23:36:35,222 - music_api - INFO - before_request:214 - GET / - IP: 127.0.0.1 - User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36
14
+ 2025-09-23 23:36:35,223 - music_api - INFO - after_request:229 - 响应状态: 200
15
+ 2025-09-23 23:37:01,427 - music_api - INFO - before_request:214 - GET / - IP: 127.0.0.1 - User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36
16
+ 2025-09-23 23:37:01,428 - music_api - INFO - after_request:229 - 响应状态: 200
17
+ 2025-09-23 23:37:03,940 - music_api - INFO - before_request:214 - GET / - IP: 127.0.0.1 - User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36
18
+ 2025-09-23 23:37:03,941 - music_api - INFO - after_request:229 - 响应状态: 200
19
+ 2025-09-23 23:37:15,344 - music_api - INFO - __init__:90 - 音乐API服务初始化完成,下载目录: D:\byzxj\R\program\git\1\netease\Netease_url\downloads
20
+ 2025-09-23 23:37:19,950 - music_api - INFO - before_request:214 - GET / - IP: 127.0.0.1 - User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36
21
+ 2025-09-23 23:37:19,956 - music_api - INFO - after_request:229 - 响应状态: 200
music_api.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """网易云音乐API模块
2
+
3
+ 提供网易云音乐相关API接口的封装,包括:
4
+ - 音乐URL获取
5
+ - 歌曲详情获取
6
+ - 歌词获取
7
+ - 搜索功能
8
+ - 歌单和专辑详情
9
+ - 二维码登录
10
+ """
11
+
12
+ import json
13
+ import urllib.parse
14
+ import time
15
+ from random import randrange
16
+ from typing import Dict, List, Optional, Tuple, Any
17
+ from hashlib import md5
18
+ from enum import Enum
19
+
20
+ import requests
21
+ from cryptography.hazmat.primitives import padding
22
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
23
+
24
+
25
+ class QualityLevel(Enum):
26
+ """音质等级枚举"""
27
+ STANDARD = "standard" # 标准音质
28
+ EXHIGH = "exhigh" # 极高音质
29
+ LOSSLESS = "lossless" # 无损音质
30
+ HIRES = "hires" # Hi-Res音质
31
+ SKY = "sky" # 沉浸环绕声
32
+ JYEFFECT = "jyeffect" # 高清环绕声
33
+ JYMASTER = "jymaster" # 超清母带
34
+
35
+
36
+ # 常量定义
37
+ class APIConstants:
38
+ """API相关常量"""
39
+ AES_KEY = b"e82ckenh8dichen8"
40
+ USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 Chrome/91.0.4472.164 NeteaseMusicDesktop/2.10.2.200154'
41
+ REFERER = 'https://music.163.com/'
42
+
43
+ # API URLs
44
+ SONG_URL_V1 = "https://interface3.music.163.com/eapi/song/enhance/player/url/v1"
45
+ SONG_DETAIL_V3 = "https://interface3.music.163.com/api/v3/song/detail"
46
+ LYRIC_API = "https://interface3.music.163.com/api/song/lyric"
47
+ SEARCH_API = 'https://music.163.com/api/cloudsearch/pc'
48
+ PLAYLIST_DETAIL_API = 'https://music.163.com/api/v6/playlist/detail'
49
+ ALBUM_DETAIL_API = 'https://music.163.com/api/v1/album/'
50
+ QR_UNIKEY_API = 'https://interface3.music.163.com/eapi/login/qrcode/unikey'
51
+ QR_LOGIN_API = 'https://interface3.music.163.com/eapi/login/qrcode/client/login'
52
+
53
+ # 默认配置
54
+ DEFAULT_CONFIG = {
55
+ "os": "pc",
56
+ "appver": "",
57
+ "osver": "",
58
+ "deviceId": "pyncm!"
59
+ }
60
+
61
+ DEFAULT_COOKIES = {
62
+ "os": "pc",
63
+ "appver": "",
64
+ "osver": "",
65
+ "deviceId": "pyncm!"
66
+ }
67
+
68
+
69
+ class CryptoUtils:
70
+ """加密工具类"""
71
+
72
+ @staticmethod
73
+ def hex_digest(data: bytes) -> str:
74
+ """将字节数据转换为十六进制字符串"""
75
+ return "".join([hex(d)[2:].zfill(2) for d in data])
76
+
77
+ @staticmethod
78
+ def hash_digest(text: str) -> bytes:
79
+ """计算MD5哈希值"""
80
+ return md5(text.encode("utf-8")).digest()
81
+
82
+ @staticmethod
83
+ def hash_hex_digest(text: str) -> str:
84
+ """计算MD5哈希值并转换为十六进制字符串"""
85
+ return CryptoUtils.hex_digest(CryptoUtils.hash_digest(text))
86
+
87
+ @staticmethod
88
+ def encrypt_params(url: str, payload: Dict[str, Any]) -> str:
89
+ """加密请求参数"""
90
+ url_path = urllib.parse.urlparse(url).path.replace("/eapi/", "/api/")
91
+ digest = CryptoUtils.hash_hex_digest(f"nobody{url_path}use{json.dumps(payload)}md5forencrypt")
92
+ params = f"{url_path}-36cd479b6b5-{json.dumps(payload)}-36cd479b6b5-{digest}"
93
+
94
+ # AES加密
95
+ padder = padding.PKCS7(algorithms.AES(APIConstants.AES_KEY).block_size).padder()
96
+ padded_data = padder.update(params.encode()) + padder.finalize()
97
+ cipher = Cipher(algorithms.AES(APIConstants.AES_KEY), modes.ECB())
98
+ encryptor = cipher.encryptor()
99
+ enc = encryptor.update(padded_data) + encryptor.finalize()
100
+
101
+ return CryptoUtils.hex_digest(enc)
102
+
103
+
104
+ class HTTPClient:
105
+ """HTTP客户端类"""
106
+
107
+ @staticmethod
108
+ def post_request(url: str, params: str, cookies: Dict[str, str]) -> str:
109
+ """发送POST请求并返回文本响应"""
110
+ headers = {
111
+ 'User-Agent': APIConstants.USER_AGENT,
112
+ 'Referer': APIConstants.REFERER,
113
+ }
114
+
115
+ request_cookies = APIConstants.DEFAULT_COOKIES.copy()
116
+ request_cookies.update(cookies)
117
+
118
+ try:
119
+ response = requests.post(url, headers=headers, cookies=request_cookies,
120
+ data={"params": params}, timeout=30)
121
+ response.raise_for_status()
122
+ return response.text
123
+ except requests.RequestException as e:
124
+ raise APIException(f"HTTP请求失败: {e}")
125
+
126
+ @staticmethod
127
+ def post_request_full(url: str, params: str, cookies: Dict[str, str]) -> requests.Response:
128
+ """发送POST请求并返回完整响应对象"""
129
+ headers = {
130
+ 'User-Agent': APIConstants.USER_AGENT,
131
+ 'Referer': APIConstants.REFERER,
132
+ }
133
+
134
+ request_cookies = APIConstants.DEFAULT_COOKIES.copy()
135
+ request_cookies.update(cookies)
136
+
137
+ try:
138
+ response = requests.post(url, headers=headers, cookies=request_cookies,
139
+ data={"params": params}, timeout=30)
140
+ response.raise_for_status()
141
+ return response
142
+ except requests.RequestException as e:
143
+ raise APIException(f"HTTP请求失败: {e}")
144
+
145
+
146
+ class APIException(Exception):
147
+ """API异常类"""
148
+ pass
149
+
150
+
151
+ class NeteaseAPI:
152
+ """网易云音乐API主类"""
153
+
154
+ def __init__(self):
155
+ self.http_client = HTTPClient()
156
+ self.crypto_utils = CryptoUtils()
157
+
158
+ def get_song_url(self, song_id: int, quality: str, cookies: Dict[str, str]) -> Dict[str, Any]:
159
+ """获取歌曲播放URL
160
+
161
+ Args:
162
+ song_id: 歌曲ID
163
+ quality: 音质等级 (standard, exhigh, lossless, hires, sky, jyeffect, jymaster)
164
+ cookies: 用户cookies
165
+
166
+ Returns:
167
+ 包含歌曲URL信息的字典
168
+
169
+ Raises:
170
+ APIException: API调用失败时抛出
171
+ """
172
+ try:
173
+ config = APIConstants.DEFAULT_CONFIG.copy()
174
+ config["requestId"] = str(randrange(20000000, 30000000))
175
+
176
+ payload = {
177
+ 'ids': [song_id],
178
+ 'level': quality,
179
+ 'encodeType': 'flac',
180
+ 'header': json.dumps(config),
181
+ }
182
+
183
+ if quality == 'sky':
184
+ payload['immerseType'] = 'c51'
185
+
186
+ params = self.crypto_utils.encrypt_params(APIConstants.SONG_URL_V1, payload)
187
+ response_text = self.http_client.post_request(APIConstants.SONG_URL_V1, params, cookies)
188
+
189
+ result = json.loads(response_text)
190
+ if result.get('code') != 200:
191
+ raise APIException(f"获取歌曲URL失败: {result.get('message', '未知错误')}")
192
+
193
+ return result
194
+ except (json.JSONDecodeError, KeyError) as e:
195
+ raise APIException(f"解析响应数据失败: {e}")
196
+
197
+ def get_song_detail(self, song_id: int) -> Dict[str, Any]:
198
+ """获取歌曲详细信息
199
+
200
+ Args:
201
+ song_id: 歌曲ID
202
+
203
+ Returns:
204
+ 包含歌曲详细信息的字典
205
+
206
+ Raises:
207
+ APIException: API调用失败时抛出
208
+ """
209
+ try:
210
+ data = {'c': json.dumps([{"id": song_id, "v": 0}])}
211
+ response = requests.post(APIConstants.SONG_DETAIL_V3, data=data, timeout=30)
212
+ response.raise_for_status()
213
+
214
+ result = response.json()
215
+ if result.get('code') != 200:
216
+ raise APIException(f"获取歌曲详情失败: {result.get('message', '未知错误')}")
217
+
218
+ return result
219
+ except requests.RequestException as e:
220
+ raise APIException(f"获取歌曲详情请求失败: {e}")
221
+ except json.JSONDecodeError as e:
222
+ raise APIException(f"解析歌曲详情响应失败: {e}")
223
+
224
+ def get_lyric(self, song_id: int, cookies: Dict[str, str]) -> Dict[str, Any]:
225
+ """获取歌词信息
226
+
227
+ Args:
228
+ song_id: 歌曲ID
229
+ cookies: 用户cookies
230
+
231
+ Returns:
232
+ 包含歌词信息的字典
233
+
234
+ Raises:
235
+ APIException: API调用失败时抛出
236
+ """
237
+ try:
238
+ data = {
239
+ 'id': song_id,
240
+ 'cp': 'false',
241
+ 'tv': '0',
242
+ 'lv': '0',
243
+ 'rv': '0',
244
+ 'kv': '0',
245
+ 'yv': '0',
246
+ 'ytv': '0',
247
+ 'yrv': '0'
248
+ }
249
+
250
+ headers = {
251
+ 'User-Agent': APIConstants.USER_AGENT,
252
+ 'Referer': APIConstants.REFERER
253
+ }
254
+
255
+ response = requests.post(APIConstants.LYRIC_API, data=data,
256
+ headers=headers, cookies=cookies, timeout=30)
257
+ response.raise_for_status()
258
+
259
+ result = response.json()
260
+ if result.get('code') != 200:
261
+ raise APIException(f"获取歌词失败: {result.get('message', '未知错误')}")
262
+
263
+ return result
264
+ except requests.RequestException as e:
265
+ raise APIException(f"获取歌词请求失败: {e}")
266
+ except json.JSONDecodeError as e:
267
+ raise APIException(f"解析歌词响应失败: {e}")
268
+
269
+ def search_music(self, keywords: str, cookies: Dict[str, str], limit: int = 10) -> List[Dict[str, Any]]:
270
+ """搜索音乐
271
+
272
+ Args:
273
+ keywords: 搜索关键词
274
+ cookies: 用户cookies
275
+ limit: 返回数量限制
276
+
277
+ Returns:
278
+ 歌曲信息列表
279
+
280
+ Raises:
281
+ APIException: API调用失败时抛出
282
+ """
283
+ try:
284
+ data = {'s': keywords, 'type': 1, 'limit': limit}
285
+ headers = {
286
+ 'User-Agent': APIConstants.USER_AGENT,
287
+ 'Referer': APIConstants.REFERER
288
+ }
289
+
290
+ response = requests.post(APIConstants.SEARCH_API, data=data,
291
+ headers=headers, cookies=cookies, timeout=30)
292
+ response.raise_for_status()
293
+
294
+ result = response.json()
295
+ if result.get('code') != 200:
296
+ raise APIException(f"搜索失败: {result.get('message', '未知错误')}")
297
+
298
+ songs = []
299
+ for item in result.get('result', {}).get('songs', []):
300
+ song_info = {
301
+ 'id': item['id'],
302
+ 'name': item['name'],
303
+ 'artists': '/'.join(artist['name'] for artist in item['ar']),
304
+ 'album': item['al']['name'],
305
+ 'picUrl': item['al']['picUrl']
306
+ }
307
+ songs.append(song_info)
308
+
309
+ return songs
310
+ except requests.RequestException as e:
311
+ raise APIException(f"搜索请求失败: {e}")
312
+ except (json.JSONDecodeError, KeyError) as e:
313
+ raise APIException(f"解析搜索响应失败: {e}")
314
+
315
+ def get_playlist_detail(self, playlist_id: int, cookies: Dict[str, str]) -> Dict[str, Any]:
316
+ """获取歌单详情
317
+
318
+ Args:
319
+ playlist_id: 歌单ID
320
+ cookies: 用户cookies
321
+
322
+ Returns:
323
+ 歌单详情信息
324
+
325
+ Raises:
326
+ APIException: API调用失败时抛出
327
+ """
328
+ try:
329
+ data = {'id': playlist_id}
330
+ headers = {
331
+ 'User-Agent': APIConstants.USER_AGENT,
332
+ 'Referer': APIConstants.REFERER
333
+ }
334
+
335
+ response = requests.post(APIConstants.PLAYLIST_DETAIL_API, data=data,
336
+ headers=headers, cookies=cookies, timeout=30)
337
+ response.raise_for_status()
338
+
339
+ result = response.json()
340
+ if result.get('code') != 200:
341
+ raise APIException(f"获取歌单详情失败: {result.get('message', '未知错误')}")
342
+
343
+ playlist = result.get('playlist', {})
344
+ info = {
345
+ 'id': playlist.get('id'),
346
+ 'name': playlist.get('name'),
347
+ 'coverImgUrl': playlist.get('coverImgUrl'),
348
+ 'creator': playlist.get('creator', {}).get('nickname', ''),
349
+ 'trackCount': playlist.get('trackCount'),
350
+ 'description': playlist.get('description', ''),
351
+ 'tracks': []
352
+ }
353
+
354
+ # 获取所有trackIds并分批获取详细信息
355
+ track_ids = [str(t['id']) for t in playlist.get('trackIds', [])]
356
+ for i in range(0, len(track_ids), 100):
357
+ batch_ids = track_ids[i:i+100]
358
+ song_data = {'c': json.dumps([{'id': int(sid), 'v': 0} for sid in batch_ids])}
359
+
360
+ song_resp = requests.post(APIConstants.SONG_DETAIL_V3, data=song_data,
361
+ headers=headers, cookies=cookies, timeout=30)
362
+ song_resp.raise_for_status()
363
+
364
+ song_result = song_resp.json()
365
+ for song in song_result.get('songs', []):
366
+ info['tracks'].append({
367
+ 'id': song['id'],
368
+ 'name': song['name'],
369
+ 'artists': '/'.join(artist['name'] for artist in song['ar']),
370
+ 'album': song['al']['name'],
371
+ 'picUrl': song['al']['picUrl']
372
+ })
373
+
374
+ return info
375
+ except requests.RequestException as e:
376
+ raise APIException(f"获取歌单详情请求失败: {e}")
377
+ except (json.JSONDecodeError, KeyError) as e:
378
+ raise APIException(f"解析歌单详情响应失败: {e}")
379
+
380
+ def get_album_detail(self, album_id: int, cookies: Dict[str, str]) -> Dict[str, Any]:
381
+ """获取专辑详情
382
+
383
+ Args:
384
+ album_id: 专辑ID
385
+ cookies: 用户cookies
386
+
387
+ Returns:
388
+ 专辑详情信息
389
+
390
+ Raises:
391
+ APIException: API调用失败时抛出
392
+ """
393
+ try:
394
+ url = f'{APIConstants.ALBUM_DETAIL_API}{album_id}'
395
+ headers = {
396
+ 'User-Agent': APIConstants.USER_AGENT,
397
+ 'Referer': APIConstants.REFERER
398
+ }
399
+
400
+ response = requests.get(url, headers=headers, cookies=cookies, timeout=30)
401
+ response.raise_for_status()
402
+
403
+ result = response.json()
404
+ if result.get('code') != 200:
405
+ raise APIException(f"获取专辑详情失败: {result.get('message', '未知错误')}")
406
+
407
+ album = result.get('album', {})
408
+ info = {
409
+ 'id': album.get('id'),
410
+ 'name': album.get('name'),
411
+ 'coverImgUrl': self.get_pic_url(album.get('pic')),
412
+ 'artist': album.get('artist', {}).get('name', ''),
413
+ 'publishTime': album.get('publishTime'),
414
+ 'description': album.get('description', ''),
415
+ 'songs': []
416
+ }
417
+
418
+ for song in result.get('songs', []):
419
+ info['songs'].append({
420
+ 'id': song['id'],
421
+ 'name': song['name'],
422
+ 'artists': '/'.join(artist['name'] for artist in song['ar']),
423
+ 'album': song['al']['name'],
424
+ 'picUrl': self.get_pic_url(song['al'].get('pic'))
425
+ })
426
+
427
+ return info
428
+ except requests.RequestException as e:
429
+ raise APIException(f"获取专辑详情请求失败: {e}")
430
+ except (json.JSONDecodeError, KeyError) as e:
431
+ raise APIException(f"解析专辑详情响应失败: {e}")
432
+
433
+ def netease_encrypt_id(self, id_str: str) -> str:
434
+ """网易云加密图片ID算法
435
+
436
+ Args:
437
+ id_str: 图片ID字符串
438
+
439
+ Returns:
440
+ 加密后的字符串
441
+ """
442
+ import base64
443
+ import hashlib
444
+
445
+ magic = list('3go8&$8*3*3h0k(2)2')
446
+ song_id = list(id_str)
447
+
448
+ for i in range(len(song_id)):
449
+ song_id[i] = chr(ord(song_id[i]) ^ ord(magic[i % len(magic)]))
450
+
451
+ m = ''.join(song_id)
452
+ md5_bytes = hashlib.md5(m.encode('utf-8')).digest()
453
+ result = base64.b64encode(md5_bytes).decode('utf-8')
454
+ result = result.replace('/', '_').replace('+', '-')
455
+
456
+ return result
457
+
458
+ def get_pic_url(self, pic_id: Optional[int], size: int = 300) -> str:
459
+ """获取网易云加密歌曲/专辑封面直链
460
+
461
+ Args:
462
+ pic_id: 封面ID
463
+ size: 图片尺寸
464
+
465
+ Returns:
466
+ 图片URL
467
+ """
468
+ if pic_id is None:
469
+ return ''
470
+
471
+ enc_id = self.netease_encrypt_id(str(pic_id))
472
+ return f'https://p3.music.126.net/{enc_id}/{pic_id}.jpg?param={size}y{size}'
473
+
474
+
475
+ class QRLoginManager:
476
+ """二维码登录管理器"""
477
+
478
+ def __init__(self):
479
+ self.http_client = HTTPClient()
480
+ self.crypto_utils = CryptoUtils()
481
+
482
+ def generate_qr_key(self) -> Optional[str]:
483
+ """生成二维码的key
484
+
485
+ Returns:
486
+ 成功返回unikey,失败返回None
487
+
488
+ Raises:
489
+ APIException: API调用失败时抛出
490
+ """
491
+ try:
492
+ config = APIConstants.DEFAULT_CONFIG.copy()
493
+ config["requestId"] = str(randrange(20000000, 30000000))
494
+
495
+ payload = {
496
+ 'type': 1,
497
+ 'header': json.dumps(config)
498
+ }
499
+
500
+ params = self.crypto_utils.encrypt_params(APIConstants.QR_UNIKEY_API, payload)
501
+ response = self.http_client.post_request_full(APIConstants.QR_UNIKEY_API, params, {})
502
+
503
+ result = json.loads(response.text)
504
+ if result.get('code') == 200:
505
+ return result.get('unikey')
506
+ else:
507
+ raise APIException(f"生成二维码key失败: {result.get('message', '未知错误')}")
508
+ except (json.JSONDecodeError, KeyError) as e:
509
+ raise APIException(f"解析二维码key响应失败: {e}")
510
+
511
+ def create_qr_login(self) -> Optional[str]:
512
+ """创建登录二维码并在控制台显示
513
+
514
+ Returns:
515
+ 成功返回unikey,失败返回None
516
+ """
517
+ try:
518
+ import qrcode
519
+
520
+ unikey = self.generate_qr_key()
521
+ if not unikey:
522
+ print("生成二维码key失败")
523
+ return None
524
+
525
+ # 创建二维码
526
+ qr = qrcode.QRCode()
527
+ qr.add_data(f'https://music.163.com/login?codekey={unikey}')
528
+ qr.make(fit=True)
529
+
530
+ # 在控制台显示二维码
531
+ qr.print_ascii(tty=True)
532
+ print("\n请使用网易云音乐APP扫描上方二维码登录")
533
+ return unikey
534
+ except ImportError:
535
+ print("请安装qrcode库: pip install qrcode")
536
+ return None
537
+ except Exception as e:
538
+ print(f"创建二维码失败: {e}")
539
+ return None
540
+
541
+ def check_qr_login(self, unikey: str) -> Tuple[int, Dict[str, str]]:
542
+ """检查二维码登录状态
543
+
544
+ Args:
545
+ unikey: 二维码key
546
+
547
+ Returns:
548
+ (登录状态码, cookie字典)
549
+
550
+ Raises:
551
+ APIException: API调用失败时抛出
552
+ """
553
+ try:
554
+ config = APIConstants.DEFAULT_CONFIG.copy()
555
+ config["requestId"] = str(randrange(20000000, 30000000))
556
+
557
+ payload = {
558
+ 'key': unikey,
559
+ 'type': 1,
560
+ 'header': json.dumps(config)
561
+ }
562
+
563
+ params = self.crypto_utils.encrypt_params(APIConstants.QR_LOGIN_API, payload)
564
+ response = self.http_client.post_request_full(APIConstants.QR_LOGIN_API, params, {})
565
+
566
+ result = json.loads(response.text)
567
+ cookie_dict = {}
568
+
569
+ if result.get('code') == 803:
570
+ # 登录成功,提取cookie
571
+ all_cookies = response.headers.get('Set-Cookie', '').split(', ')
572
+ for cookie_str in all_cookies:
573
+ if 'MUSIC_U=' in cookie_str:
574
+ cookie_dict['MUSIC_U'] = cookie_str.split('MUSIC_U=')[1].split(';')[0]
575
+
576
+ return result.get('code', -1), cookie_dict
577
+ except (json.JSONDecodeError, KeyError) as e:
578
+ raise APIException(f"解析登录状态响应失败: {e}")
579
+
580
+ def qr_login(self) -> Optional[str]:
581
+ """完整的二维码登录流程
582
+
583
+ Returns:
584
+ 成功返回cookie字符串,失败返回None
585
+ """
586
+ try:
587
+ unikey = self.create_qr_login()
588
+ if not unikey:
589
+ return None
590
+
591
+ while True:
592
+ code, cookies = self.check_qr_login(unikey)
593
+
594
+ if code == 803:
595
+ print("\n登录成功!")
596
+ return f"MUSIC_U={cookies['MUSIC_U']};os=pc;appver=8.9.70;"
597
+ elif code == 801:
598
+ print("\r等待扫码...", end='')
599
+ elif code == 802:
600
+ print("\r扫码成功,请在手机上确认登录...", end='')
601
+ else:
602
+ print(f"\n登录失败,错误码:{code}")
603
+ return None
604
+
605
+ time.sleep(2)
606
+ except KeyboardInterrupt:
607
+ print("\n用户取消登录")
608
+ return None
609
+ except Exception as e:
610
+ print(f"\n登录过程中发生错误: {e}")
611
+ return None
612
+
613
+
614
+ # 向后兼容的函数接口
615
+ def url_v1(song_id: int, level: str, cookies: Dict[str, str]) -> Dict[str, Any]:
616
+ """获取歌曲URL(向后兼容)"""
617
+ api = NeteaseAPI()
618
+ return api.get_song_url(song_id, level, cookies)
619
+
620
+
621
+ def name_v1(song_id: int) -> Dict[str, Any]:
622
+ """获取歌曲详情(向后兼容)"""
623
+ api = NeteaseAPI()
624
+ return api.get_song_detail(song_id)
625
+
626
+
627
+ def lyric_v1(song_id: int, cookies: Dict[str, str]) -> Dict[str, Any]:
628
+ """获取歌词(向后兼容)"""
629
+ api = NeteaseAPI()
630
+ return api.get_lyric(song_id, cookies)
631
+
632
+
633
+ def search_music(keywords: str, cookies: Dict[str, str], limit: int = 10) -> List[Dict[str, Any]]:
634
+ """搜索音乐(向后兼容)"""
635
+ api = NeteaseAPI()
636
+ return api.search_music(keywords, cookies, limit)
637
+
638
+
639
+ def playlist_detail(playlist_id: int, cookies: Dict[str, str]) -> Dict[str, Any]:
640
+ """获取歌单详情(向后兼容)"""
641
+ api = NeteaseAPI()
642
+ return api.get_playlist_detail(playlist_id, cookies)
643
+
644
+
645
+ def album_detail(album_id: int, cookies: Dict[str, str]) -> Dict[str, Any]:
646
+ """获取专辑详情(向后兼容)"""
647
+ api = NeteaseAPI()
648
+ return api.get_album_detail(album_id, cookies)
649
+
650
+
651
+ def get_pic_url(pic_id: Optional[int], size: int = 300) -> str:
652
+ """获取图片URL(向后兼容)"""
653
+ api = NeteaseAPI()
654
+ return api.get_pic_url(pic_id, size)
655
+
656
+
657
+ def qr_login() -> Optional[str]:
658
+ """二维码登录(向后兼容)"""
659
+ manager = QRLoginManager()
660
+ return manager.qr_login()
661
+
662
+
663
+ if __name__ == "__main__":
664
+ # 测试代码
665
+ print("网易云音乐API模块")
666
+ print("支持的功能:")
667
+ print("- 歌曲URL获取")
668
+ print("- 歌曲详情获取")
669
+ print("- 歌词获取")
670
+ print("- 音乐搜索")
671
+ print("- 歌单详情")
672
+ print("- 专辑详情")
673
+ print("- 二维码登录")
music_downloader.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """音乐下载器模块
2
+
3
+ 提供网易云音乐下载功能,包括:
4
+ - 音乐信息获取
5
+ - 文件下载到本地
6
+ - 内存下载
7
+ - 音乐标签写入
8
+ - 异步下载支持
9
+ """
10
+
11
+ import os
12
+ import re
13
+ import asyncio
14
+ import aiohttp
15
+ import aiofiles
16
+ from io import BytesIO
17
+ from typing import Dict, List, Optional, Tuple, Any, Union
18
+ from pathlib import Path
19
+ from dataclasses import dataclass
20
+ from enum import Enum
21
+
22
+ import requests
23
+ from mutagen.flac import FLAC
24
+ from mutagen.mp3 import MP3
25
+ from mutagen.id3 import ID3, TIT2, TPE1, TALB, TDRC, TRCK, APIC
26
+ from mutagen.mp4 import MP4
27
+
28
+ from music_api import NeteaseAPI, APIException
29
+ from cookie_manager import CookieManager
30
+
31
+
32
+ class AudioFormat(Enum):
33
+ """音频格式枚举"""
34
+ MP3 = "mp3"
35
+ FLAC = "flac"
36
+ M4A = "m4a"
37
+ UNKNOWN = "unknown"
38
+
39
+
40
+ class QualityLevel(Enum):
41
+ """音质等级枚举"""
42
+ STANDARD = "standard" # 标准
43
+ EXHIGH = "exhigh" # 极高
44
+ LOSSLESS = "lossless" # 无损
45
+ HIRES = "hires" # Hi-Res
46
+ SKY = "sky" # 沉浸环绕声
47
+ JYEFFECT = "jyeffect" # 高清环绕声
48
+ JYMASTER = "jymaster" # 超清母带
49
+
50
+
51
+ @dataclass
52
+ class MusicInfo:
53
+ """音乐信息数据类"""
54
+ id: int
55
+ name: str
56
+ artists: str
57
+ album: str
58
+ pic_url: str
59
+ duration: int
60
+ track_number: int
61
+ download_url: str
62
+ file_type: str
63
+ file_size: int
64
+ quality: str
65
+ lyric: str = ""
66
+ tlyric: str = ""
67
+
68
+
69
+ @dataclass
70
+ class DownloadResult:
71
+ """下载结果数据类"""
72
+ success: bool
73
+ file_path: Optional[str] = None
74
+ file_size: int = 0
75
+ error_message: str = ""
76
+ music_info: Optional[MusicInfo] = None
77
+
78
+
79
+ class DownloadException(Exception):
80
+ """下载异常类"""
81
+ pass
82
+
83
+
84
+ class MusicDownloader:
85
+ """音乐下载器主类"""
86
+
87
+ def __init__(self, download_dir: str = "downloads", max_concurrent: int = 3):
88
+ """
89
+ 初始化音乐下载器
90
+
91
+ Args:
92
+ download_dir: 下载目录
93
+ max_concurrent: 最大并发下载数
94
+ """
95
+ self.download_dir = Path(download_dir)
96
+ self.download_dir.mkdir(exist_ok=True)
97
+ self.max_concurrent = max_concurrent
98
+
99
+ # 初始化依赖
100
+ self.cookie_manager = CookieManager()
101
+ self.api = NeteaseAPI()
102
+
103
+ # 支持的文件格式
104
+ self.supported_formats = {
105
+ 'mp3': AudioFormat.MP3,
106
+ 'flac': AudioFormat.FLAC,
107
+ 'm4a': AudioFormat.M4A
108
+ }
109
+
110
+ def _sanitize_filename(self, filename: str) -> str:
111
+ """清理文件名,移除非法字符
112
+
113
+ Args:
114
+ filename: 原始文件名
115
+
116
+ Returns:
117
+ 清理后的安全文件名
118
+ """
119
+ # 移除或替换非法字符
120
+ illegal_chars = r'[<>:"/\\|?*]'
121
+ filename = re.sub(illegal_chars, '_', filename)
122
+
123
+ # 移除前后空格和点
124
+ filename = filename.strip(' .')
125
+
126
+ # 限制长度
127
+ if len(filename) > 200:
128
+ filename = filename[:200]
129
+
130
+ return filename or "unknown"
131
+
132
+ def _determine_file_extension(self, url: str, content_type: str = "") -> str:
133
+ """根据URL和Content-Type确定文件扩展名
134
+
135
+ Args:
136
+ url: 下载URL
137
+ content_type: HTTP Content-Type头
138
+
139
+ Returns:
140
+ 文件扩展名
141
+ """
142
+ # 首先尝试从URL获取
143
+ if '.flac' in url.lower():
144
+ return '.flac'
145
+ elif '.mp3' in url.lower():
146
+ return '.mp3'
147
+ elif '.m4a' in url.lower():
148
+ return '.m4a'
149
+
150
+ # 从Content-Type获取
151
+ content_type = content_type.lower()
152
+ if 'flac' in content_type:
153
+ return '.flac'
154
+ elif 'mpeg' in content_type or 'mp3' in content_type:
155
+ return '.mp3'
156
+ elif 'mp4' in content_type or 'm4a' in content_type:
157
+ return '.m4a'
158
+
159
+ return '.mp3' # 默认
160
+
161
+ def get_music_info(self, music_id: int, quality: str = "standard") -> MusicInfo:
162
+ """获取音乐详细信息
163
+
164
+ Args:
165
+ music_id: 音乐ID
166
+ quality: 音质等级
167
+
168
+ Returns:
169
+ 音乐信息对象
170
+
171
+ Raises:
172
+ DownloadException: 获取信息失败时抛出
173
+ """
174
+ try:
175
+ # 获取cookies
176
+ cookies = self.cookie_manager.parse_cookies()
177
+
178
+ # 获取音乐URL信息
179
+ url_result = self.api.get_song_url(music_id, quality, cookies)
180
+ if not url_result.get('data') or not url_result['data']:
181
+ raise DownloadException(f"无法获取音乐ID {music_id} 的播放链接")
182
+
183
+ song_data = url_result['data'][0]
184
+ download_url = song_data.get('url', '')
185
+ if not download_url:
186
+ raise DownloadException(f"音乐ID {music_id} 无可用的下载链接")
187
+
188
+ # 获取音乐详情
189
+ detail_result = self.api.get_song_detail(music_id)
190
+ if not detail_result.get('songs') or not detail_result['songs']:
191
+ raise DownloadException(f"无法获取音乐ID {music_id} 的详细信息")
192
+
193
+ song_detail = detail_result['songs'][0]
194
+
195
+ # 获取歌词
196
+ lyric_result = self.api.get_lyric(music_id, cookies)
197
+ lyric = lyric_result.get('lrc', {}).get('lyric', '') if lyric_result else ''
198
+ tlyric = lyric_result.get('tlyric', {}).get('lyric', '') if lyric_result else ''
199
+
200
+ # 构建艺术家字符串
201
+ artists = '/'.join(artist['name'] for artist in song_detail.get('ar', []))
202
+
203
+ # 创建MusicInfo对象
204
+ music_info = MusicInfo(
205
+ id=music_id,
206
+ name=song_detail.get('name', '未知歌曲'),
207
+ artists=artists or '未知艺术家',
208
+ album=song_detail.get('al', {}).get('name', '未知专辑'),
209
+ pic_url=song_detail.get('al', {}).get('picUrl', ''),
210
+ duration=song_detail.get('dt', 0) // 1000, # 转换为秒
211
+ track_number=song_detail.get('no', 0),
212
+ download_url=download_url,
213
+ file_type=song_data.get('type', 'mp3').lower(),
214
+ file_size=song_data.get('size', 0),
215
+ quality=quality,
216
+ lyric=lyric,
217
+ tlyric=tlyric
218
+ )
219
+
220
+ return music_info
221
+
222
+ except APIException as e:
223
+ raise DownloadException(f"API调用失败: {e}")
224
+ except Exception as e:
225
+ raise DownloadException(f"获取音乐信息时发生错误: {e}")
226
+
227
+ def download_music_file(self, music_id: int, quality: str = "standard") -> DownloadResult:
228
+ """下载音乐文件到本地
229
+
230
+ Args:
231
+ music_id: 音乐ID
232
+ quality: 音质等级
233
+
234
+ Returns:
235
+ 下载结果对象
236
+ """
237
+ try:
238
+ # 获取音乐信息
239
+ music_info = self.get_music_info(music_id, quality)
240
+
241
+ # 生成文件名
242
+ filename = f"{music_info.artists} - {music_info.name}"
243
+ safe_filename = self._sanitize_filename(filename)
244
+
245
+ # 确定文件扩展名
246
+ file_ext = self._determine_file_extension(music_info.download_url)
247
+ file_path = self.download_dir / f"{safe_filename}{file_ext}"
248
+
249
+ # 检查文件是否已存在
250
+ if file_path.exists():
251
+ return DownloadResult(
252
+ success=True,
253
+ file_path=str(file_path),
254
+ file_size=file_path.stat().st_size,
255
+ music_info=music_info
256
+ )
257
+
258
+ # 下载文件
259
+ response = requests.get(music_info.download_url, stream=True, timeout=30)
260
+ response.raise_for_status()
261
+
262
+ # 写入文件
263
+ with open(file_path, 'wb') as f:
264
+ for chunk in response.iter_content(chunk_size=8192):
265
+ if chunk:
266
+ f.write(chunk)
267
+
268
+ # 写入音乐标签
269
+ self._write_music_tags(file_path, music_info)
270
+
271
+ return DownloadResult(
272
+ success=True,
273
+ file_path=str(file_path),
274
+ file_size=file_path.stat().st_size,
275
+ music_info=music_info
276
+ )
277
+
278
+ except DownloadException:
279
+ raise
280
+ except requests.RequestException as e:
281
+ return DownloadResult(
282
+ success=False,
283
+ error_message=f"下载请求失败: {e}"
284
+ )
285
+ except Exception as e:
286
+ return DownloadResult(
287
+ success=False,
288
+ error_message=f"下载过程中发生错误: {e}"
289
+ )
290
+
291
+ async def download_music_file_async(self, music_id: int, quality: str = "standard") -> DownloadResult:
292
+ """异步下载音乐文件到本地
293
+
294
+ Args:
295
+ music_id: 音乐ID
296
+ quality: 音质等级
297
+
298
+ Returns:
299
+ 下载结果对象
300
+ """
301
+ try:
302
+ # 获取音乐信息(同步操作)
303
+ music_info = self.get_music_info(music_id, quality)
304
+
305
+ # 生成文件名
306
+ filename = f"{music_info.artists} - {music_info.name}"
307
+ safe_filename = self._sanitize_filename(filename)
308
+
309
+ # 确定文件扩展名
310
+ file_ext = self._determine_file_extension(music_info.download_url)
311
+ file_path = self.download_dir / f"{safe_filename}{file_ext}"
312
+
313
+ # 检查文件是否已存在
314
+ if file_path.exists():
315
+ return DownloadResult(
316
+ success=True,
317
+ file_path=str(file_path),
318
+ file_size=file_path.stat().st_size,
319
+ music_info=music_info
320
+ )
321
+
322
+ # 异步下载文件
323
+ async with aiohttp.ClientSession() as session:
324
+ async with session.get(music_info.download_url) as response:
325
+ response.raise_for_status()
326
+
327
+ async with aiofiles.open(file_path, 'wb') as f:
328
+ async for chunk in response.content.iter_chunked(8192):
329
+ await f.write(chunk)
330
+
331
+ # 写入音乐标签
332
+ self._write_music_tags(file_path, music_info)
333
+
334
+ return DownloadResult(
335
+ success=True,
336
+ file_path=str(file_path),
337
+ file_size=file_path.stat().st_size,
338
+ music_info=music_info
339
+ )
340
+
341
+ except DownloadException:
342
+ raise
343
+ except aiohttp.ClientError as e:
344
+ return DownloadResult(
345
+ success=False,
346
+ error_message=f"异步下载请求失败: {e}"
347
+ )
348
+ except Exception as e:
349
+ return DownloadResult(
350
+ success=False,
351
+ error_message=f"异步下载过程中发生错误: {e}"
352
+ )
353
+
354
+ def download_music_to_memory(self, music_id: int, quality: str = "standard") -> Tuple[bool, BytesIO, MusicInfo]:
355
+ """下载音乐到内存
356
+
357
+ Args:
358
+ music_id: 音乐ID
359
+ quality: 音质等级
360
+
361
+ Returns:
362
+ (是否成功, 音乐数据流, 音乐信息)
363
+
364
+ Raises:
365
+ DownloadException: 下载失败时抛出
366
+ """
367
+ try:
368
+ # 获取音乐信息
369
+ music_info = self.get_music_info(music_id, quality)
370
+
371
+ # 下载到内存
372
+ response = requests.get(music_info.download_url, timeout=30)
373
+ response.raise_for_status()
374
+
375
+ # 创建BytesIO对象
376
+ audio_data = BytesIO(response.content)
377
+
378
+ return True, audio_data, music_info
379
+
380
+ except DownloadException:
381
+ raise
382
+ except requests.RequestException as e:
383
+ raise DownloadException(f"下载到内存失败: {e}")
384
+ except Exception as e:
385
+ raise DownloadException(f"内存下载过程中发生错误: {e}")
386
+
387
+ async def download_batch_async(self, music_ids: List[int], quality: str = "standard") -> List[DownloadResult]:
388
+ """批量异步下载音乐
389
+
390
+ Args:
391
+ music_ids: 音乐ID列表
392
+ quality: 音质等级
393
+
394
+ Returns:
395
+ 下载结果列表
396
+ """
397
+ semaphore = asyncio.Semaphore(self.max_concurrent)
398
+
399
+ async def download_with_semaphore(music_id: int) -> DownloadResult:
400
+ async with semaphore:
401
+ return await self.download_music_file_async(music_id, quality)
402
+
403
+ tasks = [download_with_semaphore(music_id) for music_id in music_ids]
404
+ results = await asyncio.gather(*tasks, return_exceptions=True)
405
+
406
+ # 处理异常结果
407
+ processed_results = []
408
+ for i, result in enumerate(results):
409
+ if isinstance(result, Exception):
410
+ processed_results.append(DownloadResult(
411
+ success=False,
412
+ error_message=f"下载音乐ID {music_ids[i]} 时发生异常: {result}"
413
+ ))
414
+ else:
415
+ processed_results.append(result)
416
+
417
+ return processed_results
418
+
419
+ def _write_music_tags(self, file_path: Path, music_info: MusicInfo) -> None:
420
+ """写入音乐标签信息
421
+
422
+ Args:
423
+ file_path: 音乐文件路径
424
+ music_info: 音乐信息
425
+ """
426
+ try:
427
+ file_ext = file_path.suffix.lower()
428
+
429
+ if file_ext == '.mp3':
430
+ self._write_mp3_tags(file_path, music_info)
431
+ elif file_ext == '.flac':
432
+ self._write_flac_tags(file_path, music_info)
433
+ elif file_ext == '.m4a':
434
+ self._write_m4a_tags(file_path, music_info)
435
+
436
+ except Exception as e:
437
+ print(f"写入音乐标签失败: {e}")
438
+
439
+ def _write_mp3_tags(self, file_path: Path, music_info: MusicInfo) -> None:
440
+ """写入MP3标签"""
441
+ try:
442
+ audio = MP3(str(file_path), ID3=ID3)
443
+
444
+ # 添加ID3标签
445
+ audio.tags.add(TIT2(encoding=3, text=music_info.name))
446
+ audio.tags.add(TPE1(encoding=3, text=music_info.artists))
447
+ audio.tags.add(TALB(encoding=3, text=music_info.album))
448
+
449
+ if music_info.track_number > 0:
450
+ audio.tags.add(TRCK(encoding=3, text=str(music_info.track_number)))
451
+
452
+ # 下载并添加封面
453
+ if music_info.pic_url:
454
+ try:
455
+ pic_response = requests.get(music_info.pic_url, timeout=10)
456
+ pic_response.raise_for_status()
457
+ audio.tags.add(APIC(
458
+ encoding=3,
459
+ mime='image/jpeg',
460
+ type=3,
461
+ desc='Cover',
462
+ data=pic_response.content
463
+ ))
464
+ except:
465
+ pass # 封面下载失败不影响主流程
466
+
467
+ audio.save()
468
+ except Exception as e:
469
+ print(f"写入MP3标签失败: {e}")
470
+
471
+ def _write_flac_tags(self, file_path: Path, music_info: MusicInfo) -> None:
472
+ """写入FLAC标签"""
473
+ try:
474
+ audio = FLAC(str(file_path))
475
+
476
+ audio['TITLE'] = music_info.name
477
+ audio['ARTIST'] = music_info.artists
478
+ audio['ALBUM'] = music_info.album
479
+
480
+ if music_info.track_number > 0:
481
+ audio['TRACKNUMBER'] = str(music_info.track_number)
482
+
483
+ # 下载并添加封面
484
+ if music_info.pic_url:
485
+ try:
486
+ pic_response = requests.get(music_info.pic_url, timeout=10)
487
+ pic_response.raise_for_status()
488
+
489
+ from mutagen.flac import Picture
490
+ picture = Picture()
491
+ picture.type = 3 # Cover (front)
492
+ picture.mime = 'image/jpeg'
493
+ picture.desc = 'Cover'
494
+ picture.data = pic_response.content
495
+ audio.add_picture(picture)
496
+ except:
497
+ pass # 封面下载失败不影响主流程
498
+
499
+ audio.save()
500
+ except Exception as e:
501
+ print(f"写入FLAC标签失败: {e}")
502
+
503
+ def _write_m4a_tags(self, file_path: Path, music_info: MusicInfo) -> None:
504
+ """写入M4A标签"""
505
+ try:
506
+ audio = MP4(str(file_path))
507
+
508
+ audio['\xa9nam'] = music_info.name
509
+ audio['\xa9ART'] = music_info.artists
510
+ audio['\xa9alb'] = music_info.album
511
+
512
+ if music_info.track_number > 0:
513
+ audio['trkn'] = [(music_info.track_number, 0)]
514
+
515
+ # 下载并添加封面
516
+ if music_info.pic_url:
517
+ try:
518
+ pic_response = requests.get(music_info.pic_url, timeout=10)
519
+ pic_response.raise_for_status()
520
+ audio['covr'] = [pic_response.content]
521
+ except:
522
+ pass # 封面下载失败不影响主流程
523
+
524
+ audio.save()
525
+ except Exception as e:
526
+ print(f"写入M4A标签失败: {e}")
527
+
528
+ def get_download_progress(self, music_id: int, quality: str = "standard") -> Dict[str, Any]:
529
+ """获取下载进度信息
530
+
531
+ Args:
532
+ music_id: 音乐ID
533
+ quality: 音质等级
534
+
535
+ Returns:
536
+ 包含进度信息的字典
537
+ """
538
+ try:
539
+ music_info = self.get_music_info(music_id, quality)
540
+
541
+ filename = f"{music_info.artists} - {music_info.name}"
542
+ safe_filename = self._sanitize_filename(filename)
543
+ file_ext = self._determine_file_extension(music_info.download_url)
544
+ file_path = self.download_dir / f"{safe_filename}{file_ext}"
545
+
546
+ if file_path.exists():
547
+ current_size = file_path.stat().st_size
548
+ progress = (current_size / music_info.file_size * 100) if music_info.file_size > 0 else 0
549
+
550
+ return {
551
+ 'music_id': music_id,
552
+ 'filename': safe_filename + file_ext,
553
+ 'total_size': music_info.file_size,
554
+ 'current_size': current_size,
555
+ 'progress': min(progress, 100),
556
+ 'completed': current_size >= music_info.file_size
557
+ }
558
+ else:
559
+ return {
560
+ 'music_id': music_id,
561
+ 'filename': safe_filename + file_ext,
562
+ 'total_size': music_info.file_size,
563
+ 'current_size': 0,
564
+ 'progress': 0,
565
+ 'completed': False
566
+ }
567
+
568
+ except Exception as e:
569
+ return {
570
+ 'music_id': music_id,
571
+ 'error': str(e),
572
+ 'progress': 0,
573
+ 'completed': False
574
+ }
575
+
576
+
577
+ if __name__ == "__main__":
578
+ # 测试代码
579
+ downloader = MusicDownloader()
580
+ print("音乐下载器模块")
581
+ print("支持的功能:")
582
+ print("- 同步下载")
583
+ print("- 异步下载")
584
+ print("- 批量下载")
585
+ print("- 内存下载")
586
+ print("- 音乐标签写入")
587
+ print("- 下载进度跟踪")
qr_login.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """网易云音乐二维码登录模块
2
+
3
+ 提供网易云音乐二维码登录功能,包括:
4
+ - 二维码生成和显示
5
+ - 登录状态检查
6
+ - Cookie获取和保存
7
+ - 用户友好的交互界面
8
+ """
9
+
10
+ import sys
11
+ import time
12
+ import logging
13
+ from typing import Optional, Dict, Any, Tuple
14
+ from pathlib import Path
15
+
16
+ try:
17
+ from music_api import QRLoginManager, APIException
18
+ from cookie_manager import CookieManager, CookieException
19
+ except ImportError as e:
20
+ print(f"导入模块失败: {e}")
21
+ print("请确保 music_api.py 和 cookie_manager.py 文件存在且可用")
22
+ sys.exit(1)
23
+
24
+
25
+ class QRLoginClient:
26
+ """二维码登录客户端"""
27
+
28
+ def __init__(self, cookie_file: str = "cookie.txt"):
29
+ """
30
+ 初始化二维码登录客户端
31
+
32
+ Args:
33
+ cookie_file: Cookie保存文件路径
34
+ """
35
+ self.cookie_manager = CookieManager(cookie_file)
36
+ self.qr_manager = QRLoginManager()
37
+ self.logger = logging.getLogger(__name__)
38
+
39
+ # 配置日志
40
+ if not self.logger.handlers:
41
+ handler = logging.StreamHandler()
42
+ formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
43
+ handler.setFormatter(formatter)
44
+ self.logger.addHandler(handler)
45
+ self.logger.setLevel(logging.INFO)
46
+
47
+ def check_existing_login(self) -> bool:
48
+ """检查是否已有有效登录
49
+
50
+ Returns:
51
+ 是否已登录
52
+ """
53
+ try:
54
+ if self.cookie_manager.is_cookie_valid():
55
+ self.logger.info("检测到有效的登录Cookie")
56
+ return True
57
+ else:
58
+ self.logger.info("未检测到有效的登录Cookie")
59
+ return False
60
+ except Exception as e:
61
+ self.logger.error(f"检查登录状态失败: {e}")
62
+ return False
63
+
64
+ def interactive_login(self) -> Tuple[bool, Optional[str]]:
65
+ """交互式二维码登录
66
+
67
+ Returns:
68
+ (登录是否成功, 错误信息)
69
+ """
70
+ try:
71
+ print("\n=== 网易云音乐二维码登录 ===")
72
+
73
+ # 检查现有登录状态
74
+ if self.check_existing_login():
75
+ choice = input("检测到已有有效登录,是否重新登录?(y/N): ").strip().lower()
76
+ if choice not in ['y', 'yes', '是']:
77
+ print("使用现有登录状态")
78
+ return True, None
79
+
80
+ print("\n开始二维码登录流程...")
81
+
82
+ # 生成二维码
83
+ print("正在生成二维码...")
84
+ qr_result = self.qr_manager.create_qr_login()
85
+
86
+ if not qr_result['success']:
87
+ error_msg = f"生成二维码失败: {qr_result.get('message', '未知错误')}"
88
+ self.logger.error(error_msg)
89
+ return False, error_msg
90
+
91
+ qr_key = qr_result['qr_key']
92
+ print(f"\n二维码已生成!")
93
+ print(f"请使用网易云音乐手机APP扫描二维码进行登录")
94
+ print(f"二维码有效期: 3分钟")
95
+ print("\n等待扫码中...")
96
+
97
+ # 轮询检查登录状态
98
+ max_attempts = 60 # 最多等待5分钟
99
+ attempt = 0
100
+
101
+ while attempt < max_attempts:
102
+ try:
103
+ # 检查登录状态
104
+ status_result = self.qr_manager.check_qr_login(qr_key)
105
+
106
+ if status_result['success']:
107
+ if status_result['status'] == 'success':
108
+ # 登录成功
109
+ cookie = status_result.get('cookie', '')
110
+ if cookie:
111
+ # 保存Cookie
112
+ success = self.save_cookie(cookie)
113
+ if success:
114
+ print("\n✅ 登录成功!Cookie已保存")
115
+ return True, None
116
+ else:
117
+ error_msg = "登录成功但Cookie保存失败"
118
+ self.logger.error(error_msg)
119
+ return False, error_msg
120
+ else:
121
+ error_msg = "登录成功但未获取到Cookie"
122
+ self.logger.error(error_msg)
123
+ return False, error_msg
124
+
125
+ elif status_result['status'] == 'waiting':
126
+ # 等待扫码
127
+ if attempt % 10 == 0: # 每10次显示一次提示
128
+ print(f"等待扫码中... ({attempt + 1}/{max_attempts})")
129
+
130
+ elif status_result['status'] == 'scanned':
131
+ # 已扫码,等待确认
132
+ print("二维码已扫描,请在手机上确认登录")
133
+
134
+ elif status_result['status'] == 'expired':
135
+ # 二维码过期
136
+ error_msg = "二维码已过期,请重新尝试"
137
+ print(f"\n❌ {error_msg}")
138
+ return False, error_msg
139
+
140
+ elif status_result['status'] == 'error':
141
+ # 登录错误
142
+ error_msg = f"登录失败: {status_result.get('message', '未知错误')}"
143
+ print(f"\n❌ {error_msg}")
144
+ return False, error_msg
145
+
146
+ else:
147
+ self.logger.warning(f"检查登录状态失败: {status_result.get('message', '未知错误')}")
148
+
149
+ # 等待5秒后重试
150
+ time.sleep(5)
151
+ attempt += 1
152
+
153
+ except KeyboardInterrupt:
154
+ print("\n用户取消登录")
155
+ return False, "用户取消登录"
156
+ except Exception as e:
157
+ self.logger.error(f"检查登录状态时发生错误: {e}")
158
+ time.sleep(5)
159
+ attempt += 1
160
+
161
+ # 超时
162
+ error_msg = "登录超时,请重新尝试"
163
+ print(f"\n❌ {error_msg}")
164
+ return False, error_msg
165
+
166
+ except APIException as e:
167
+ error_msg = f"API调用失败: {e}"
168
+ self.logger.error(error_msg)
169
+ return False, error_msg
170
+ except Exception as e:
171
+ error_msg = f"登录过程中发生未知错误: {e}"
172
+ self.logger.error(error_msg)
173
+ return False, error_msg
174
+
175
+ def save_cookie(self, cookie: str) -> bool:
176
+ """保存Cookie到文件
177
+
178
+ Args:
179
+ cookie: Cookie字符串
180
+
181
+ Returns:
182
+ 是否保存成功
183
+ """
184
+ try:
185
+ # 备份现有Cookie(如果存在)
186
+ if self.cookie_manager.cookie_file.exists():
187
+ try:
188
+ backup_path = self.cookie_manager.backup_cookie()
189
+ self.logger.info(f"已备份现有Cookie到: {backup_path}")
190
+ except Exception as e:
191
+ self.logger.warning(f"备份Cookie失败: {e}")
192
+
193
+ # 保存新Cookie
194
+ success = self.cookie_manager.write_cookie(cookie)
195
+
196
+ if success:
197
+ # 验证保存的Cookie
198
+ if self.cookie_manager.is_cookie_valid():
199
+ self.logger.info("Cookie保存并验证成功")
200
+ return True
201
+ else:
202
+ self.logger.warning("Cookie保存成功但验证失败")
203
+ return False
204
+ else:
205
+ self.logger.error("Cookie保存失败")
206
+ return False
207
+
208
+ except CookieException as e:
209
+ self.logger.error(f"Cookie操作失败: {e}")
210
+ return False
211
+ except Exception as e:
212
+ self.logger.error(f"保存Cookie时发生错误: {e}")
213
+ return False
214
+
215
+ def show_login_info(self) -> None:
216
+ """显示登录信息"""
217
+ try:
218
+ info = self.cookie_manager.get_cookie_info()
219
+
220
+ print("\n=== 登录状态信息 ===")
221
+ print(f"Cookie文件: {info['file_path']}")
222
+ print(f"文件存在: {'是' if info['file_exists'] else '否'}")
223
+ print(f"Cookie数量: {info['cookie_count']}")
224
+ print(f"登录状态: {'有效' if info['is_valid'] else '无效'}")
225
+
226
+ if info.get('last_modified'):
227
+ print(f"最后更新: {info['last_modified']}")
228
+
229
+ if info['is_valid']:
230
+ present_cookies = info.get('important_cookies_present', [])
231
+ print(f"重要Cookie: {', '.join(present_cookies)}")
232
+ else:
233
+ missing_cookies = info.get('missing_important_cookies', [])
234
+ if missing_cookies:
235
+ print(f"缺少Cookie: {', '.join(missing_cookies)}")
236
+
237
+ except Exception as e:
238
+ print(f"获取登录信息失败: {e}")
239
+
240
+ def logout(self) -> bool:
241
+ """登出(清除Cookie)
242
+
243
+ Returns:
244
+ 是否登出成功
245
+ """
246
+ try:
247
+ # 备份Cookie
248
+ if self.cookie_manager.cookie_file.exists():
249
+ try:
250
+ backup_path = self.cookie_manager.backup_cookie("logout")
251
+ print(f"Cookie已备份到: {backup_path}")
252
+ except Exception as e:
253
+ self.logger.warning(f"备份Cookie失败: {e}")
254
+
255
+ # 清除Cookie
256
+ success = self.cookie_manager.clear_cookie()
257
+
258
+ if success:
259
+ print("已成功登出")
260
+ return True
261
+ else:
262
+ print("登出失败")
263
+ return False
264
+
265
+ except Exception as e:
266
+ print(f"登出时发生错误: {e}")
267
+ return False
268
+
269
+
270
+ def main():
271
+ """主函数"""
272
+ # 配置日志
273
+ logging.basicConfig(
274
+ level=logging.INFO,
275
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
276
+ )
277
+
278
+ client = QRLoginClient()
279
+
280
+ # 解析命令行参数
281
+ if len(sys.argv) > 1:
282
+ command = sys.argv[1].lower()
283
+
284
+ if command == 'login':
285
+ # 执行登录
286
+ success, error = client.interactive_login()
287
+ if success:
288
+ print("\n登录完成!")
289
+ client.show_login_info()
290
+ sys.exit(0)
291
+ else:
292
+ print(f"\n登录失败: {error}")
293
+ sys.exit(1)
294
+
295
+ elif command == 'status' or command == 'info':
296
+ # 显示登录状态
297
+ client.show_login_info()
298
+ sys.exit(0)
299
+
300
+ elif command == 'logout':
301
+ # 登出
302
+ success = client.logout()
303
+ sys.exit(0 if success else 1)
304
+
305
+ elif command == 'help' or command == '-h' or command == '--help':
306
+ # 显示帮助
307
+ print("网易云音乐二维码登录工具")
308
+ print("\n用法:")
309
+ print(" python qr_login.py [命令]")
310
+ print("\n命令:")
311
+ print(" login - 执行二维码登录")
312
+ print(" status - 显示登录状态")
313
+ print(" logout - 登出(清除Cookie)")
314
+ print(" help - 显示此帮助信息")
315
+ print("\n如果不提供命令,将进入交互模式")
316
+ sys.exit(0)
317
+
318
+ else:
319
+ print(f"未知命令: {command}")
320
+ print("使用 'python qr_login.py help' 查看帮助")
321
+ sys.exit(1)
322
+
323
+ # 交互模式
324
+ try:
325
+ while True:
326
+ print("\n=== 网易云音乐登录工具 ===")
327
+ print("1. 二维码登录")
328
+ print("2. 查看登录状态")
329
+ print("3. 登出")
330
+ print("4. 退出")
331
+
332
+ choice = input("\n请选择操作 (1-4): ").strip()
333
+
334
+ if choice == '1':
335
+ success, error = client.interactive_login()
336
+ if success:
337
+ print("\n登录成功!")
338
+ client.show_login_info()
339
+ else:
340
+ print(f"\n登录失败: {error}")
341
+
342
+ elif choice == '2':
343
+ client.show_login_info()
344
+
345
+ elif choice == '3':
346
+ client.logout()
347
+
348
+ elif choice == '4':
349
+ print("再见!")
350
+ break
351
+
352
+ else:
353
+ print("无效选择,请重试")
354
+
355
+ except KeyboardInterrupt:
356
+ print("\n\n程序已退出")
357
+ sys.exit(0)
358
+ except Exception as e:
359
+ print(f"\n程序运行出错: {e}")
360
+ sys.exit(1)
361
+
362
+
363
+ if __name__ == "__main__":
364
+ main()
requirements.txt ADDED
Binary file (948 Bytes). View file
 
templates/index.html ADDED
@@ -0,0 +1,684 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>网易云音乐工具箱</title>
7
+ <link href="https://mirrors.sustech.edu.cn/cdnjs/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
8
+ <link rel="stylesheet" href="https://mirrors.sustech.edu.cn/cdnjs/ajax/libs/aplayer/1.10.1/APlayer.min.css">
9
+ <style>
10
+ body {
11
+ background-color: #f8f9fa;
12
+ color: #333;
13
+ }
14
+ .container {
15
+ max-width: 800px;
16
+ }
17
+ .form-group {
18
+ margin-bottom: 15px;
19
+ }
20
+ .btn-primary {
21
+ margin-top: 20px;
22
+ background-color: #007bff;
23
+ border-color: #007bff;
24
+ }
25
+ .btn-primary:hover {
26
+ background-color: #0056b3;
27
+ border-color: #004085;
28
+ }
29
+ .btn-success {
30
+ margin-top: 20px;
31
+ background-color: #28a745;
32
+ border-color: #28a745;
33
+ }
34
+ .btn-success:hover {
35
+ background-color: #218838;
36
+ border-color: #1e7e34;
37
+ }
38
+ .btn-warning {
39
+ margin-top: 20px;
40
+ background-color: #ffc107;
41
+ border-color: #ffc107;
42
+ }
43
+ .btn-warning:hover {
44
+ background-color: #e0a800;
45
+ border-color: #d39e00;
46
+ }
47
+ #song-info {
48
+ margin-top: 20px;
49
+ }
50
+ #song-info img {
51
+ max-width: 100%;
52
+ border-radius: 8px;
53
+ }
54
+ .alert-info {
55
+ background-color: #d1ecf1;
56
+ color: #0c5460;
57
+ border-color: #bee5eb;
58
+ }
59
+ /* 歌曲/歌单标题过长自动省略号 */
60
+ .song-title, .playlist-title {
61
+ display: inline-block;
62
+ max-width: 180px;
63
+ vertical-align: middle;
64
+ white-space: nowrap;
65
+ overflow: hidden;
66
+ text-overflow: ellipsis;
67
+ }
68
+ /* 歌单列表按钮不换行 */
69
+ .list-group-item .select-song {
70
+ flex-shrink: 0;
71
+ margin-left: 10px;
72
+ }
73
+ /* 歌词区域美化 */
74
+ .lyric-box {
75
+ max-height: 180px;
76
+ overflow-y: auto;
77
+ background: linear-gradient(90deg,#f7f7fa 60%,#f0f4fa 100%);
78
+ border-radius: 8px;
79
+ padding: 12px 16px;
80
+ font-size: 15px;
81
+ color: #222;
82
+ box-shadow: 0 1px 4px rgba(0,0,0,0.04);
83
+ line-height: 1.7;
84
+ margin-bottom: 0;
85
+ }
86
+ </style>
87
+ </head>
88
+ <body>
89
+ <div class="container mt-5">
90
+ <h1 class="text-center mb-4">网易云音乐工具箱</h1>
91
+ <div class="card shadow-sm">
92
+ <div class="card-body">
93
+ <form id="main-form">
94
+ <div class="mb-3">
95
+ <label class="form-label">功能选择</label>
96
+ <select id="mode-select" class="form-select">
97
+ <option value="search">歌曲搜索</option>
98
+ <option value="parse">单曲解析</option>
99
+ <option value="playlist">歌单解析</option>
100
+ <option value="album">专辑解析</option>
101
+ <option value="download">音乐下载</option>
102
+ </select>
103
+ </div>
104
+ <div id="search-area">
105
+ <div class="mb-3">
106
+ <label for="search_keywords" class="form-label">搜索关键词</label>
107
+ <input type="text" id="search_keywords" class="form-control" placeholder="输入关键词进行搜索">
108
+ </div>
109
+ <div class="mb-3">
110
+ <label for="search_limit" class="form-label">返回数量</label>
111
+ <input type="number" id="search_limit" class="form-control" value="10" min="1" max="50">
112
+ </div>
113
+ <div class="text-center">
114
+ <button type="button" id="search-btn" class="btn btn-success w-50">搜索</button>
115
+ </div>
116
+ </div>
117
+ <div id="parse-area" style="display:none;">
118
+ <div class="mb-3">
119
+ <label for="song_ids" class="form-label">歌曲ID或URL</label>
120
+ <input type="text" id="song_ids" class="form-control" placeholder="输入歌曲ID或URL">
121
+ </div>
122
+ <div class="mb-3">
123
+ <label for="level" class="form-label">音质选择</label>
124
+ <select id="level" class="form-select">
125
+ <option value="standard">标准音质</option>
126
+ <option value="exhigh">极高音质</option>
127
+ <option value="lossless">无损音质</option>
128
+ <option value="hires">Hires音质</option>
129
+ <option value="sky">沉浸环绕声</option>
130
+ <option value="jyeffect">高清环绕声</option>
131
+ <option value="jymaster">超清母带</option>
132
+ </select>
133
+ </div>
134
+ <div class="text-center">
135
+ <button type="button" id="parse-btn" class="btn btn-primary w-50">解析</button>
136
+ </div>
137
+ </div>
138
+ <div id="playlist-area" style="display:none;">
139
+ <div class="mb-3">
140
+ <label for="playlist_id" class="form-label">歌单ID或链接</label>
141
+ <input type="text" id="playlist_id" class="form-control" placeholder="输入歌单ID或网易云歌单链接">
142
+ </div>
143
+ <div class="text-center">
144
+ <button type="button" id="playlist-btn" class="btn btn-warning w-50">解析歌单</button>
145
+ </div>
146
+ </div>
147
+ <div id="album-area" style="display:none;">
148
+ <div class="mb-3">
149
+ <label for="album_id" class="form-label">专辑ID或链接</label>
150
+ <input type="text" id="album_id" class="form-control" placeholder="输入专辑ID或网易云专辑链接">
151
+ </div>
152
+ <div class="text-center">
153
+ <button type="button" id="album-btn" class="btn btn-info w-50">解析专辑</button>
154
+ </div>
155
+ </div>
156
+ <div id="download-area" style="display:none;">
157
+ <div class="mb-3">
158
+ <label for="download_id" class="form-label">音乐ID或URL</label>
159
+ <input type="text" id="download_id" class="form-control" placeholder="输入音乐ID或网易云音乐链接">
160
+ </div>
161
+ <div class="mb-3">
162
+ <label for="download_quality" class="form-label">下载音质</label>
163
+ <select id="download_quality" class="form-select">
164
+ <option value="standard">标准音质</option>
165
+ <option value="exhigh">极高音质</option>
166
+ <option value="lossless" selected>无损音质</option>
167
+ <option value="hires">Hires音质</option>
168
+ <option value="sky">沉浸环绕声</option>
169
+ <option value="jyeffect">高清环绕声</option>
170
+ <option value="jymaster">超清母带</option>
171
+ </select>
172
+ </div>
173
+ <div class="text-center">
174
+ <button type="button" id="download-btn" class="btn btn-success w-50">下载音乐</button>
175
+ </div>
176
+ <div id="download-progress" class="mt-3 d-none">
177
+ <div class="progress">
178
+ <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 100%"></div>
179
+ </div>
180
+ <div class="text-center mt-2">
181
+ <small class="text-muted">正在下载并写入元信息...</small>
182
+ </div>
183
+ </div>
184
+ </div>
185
+ </form>
186
+ </div>
187
+ </div>
188
+ <!-- 搜索结果列表 -->
189
+ <div id="search-result" class="mt-4 d-none">
190
+ <h5>搜索结果:</h5>
191
+ <ul class="list-group" id="search-list"></ul>
192
+ </div>
193
+ <!-- 结果展示区域 -->
194
+ <div id="song-info" class="alert alert-info d-none mt-4 p-0 border-0" style="box-shadow:0 2px 8px rgba(0,0,0,0.07);">
195
+ <div class="row g-0 align-items-stretch">
196
+ <div class="col-md-8 p-3 d-flex flex-column justify-content-between">
197
+ <h4 class="mb-2" id="song_name" style="font-weight:700;"></h4>
198
+ <div class="mb-2"><span class="badge bg-primary me-2">歌手</span><span id="artist_names"></span></div>
199
+ <div class="mb-2"><span class="badge bg-secondary me-2">专辑</span><span id="song_alname"></span></div>
200
+ <div class="mb-2"><span class="badge bg-success me-2">音质</span><span id="song_level"></span></div>
201
+ <div class="mb-2"><span class="badge bg-warning text-dark me-2">大小</span><span id="song_size"></span></div>
202
+ <div class="mb-2">
203
+ <button id="show-big-pic" type="button" class="btn btn-outline-info btn-sm me-2" style="vertical-align:middle;">显示大图</button>
204
+ </div>
205
+ <div class="mb-2"><span class="badge bg-info text-dark me-2">链接</span><a id="song_url" href="" target="_blank">点击下载</a></div>
206
+ <div class="mb-2"><span class="badge bg-dark me-2">歌词</span></div>
207
+ <div class="lyric-box" id="lyric"></div>
208
+ </div>
209
+ </div>
210
+ <div class="row g-0">
211
+ <div class="col-12 p-3 pt-0">
212
+ <div id="aplayer"></div>
213
+ </div>
214
+ </div>
215
+ </div>
216
+ <!-- 歌单解析结果 -->
217
+ <div id="playlist-result" class="mt-4 d-none">
218
+ <div class="card">
219
+ <div class="card-body">
220
+ <div class="d-flex align-items-center mb-3">
221
+ <img id="playlist-cover" src="" alt="cover" style="width:60px;height:60px;object-fit:cover;border-radius:8px;margin-right:15px;">
222
+ <div>
223
+ <h5 id="playlist-name" class="mb-1"></h5>
224
+ <div class="text-muted" id="playlist-creator"></div>
225
+ </div>
226
+ </div>
227
+ <div id="playlist-desc" class="mb-2 text-secondary small"></div>
228
+ <div>共 <span id="playlist-count"></span> 首歌</div>
229
+ </div>
230
+ </div>
231
+ <ul class="list-group mt-3" id="playlist-tracks"></ul>
232
+ </div>
233
+ <!-- 专辑解析结果 -->
234
+ <div id="album-result" class="mt-4 d-none">
235
+ <div class="card">
236
+ <div class="card-body">
237
+ <div class="d-flex align-items-center mb-3">
238
+ <img id="album-cover" src="" alt="cover" style="width:60px;height:60px;object-fit:cover;border-radius:8px;margin-right:15px;">
239
+ <div>
240
+ <h5 id="album-name" class="mb-1"></h5>
241
+ <div class="text-muted" id="album-artist"></div>
242
+ </div>
243
+ </div>
244
+ <div id="album-desc" class="mb-2 text-secondary small"></div>
245
+ <div>共 <span id="album-count"></span> 首歌</div>
246
+ </div>
247
+ </div>
248
+ <ul class="list-group mt-3" id="album-tracks"></ul>
249
+ </div>
250
+ </div>
251
+ <!-- Modal for big picture -->
252
+ <div class="modal fade" id="bigPicModal" tabindex="-1" aria-labelledby="bigPicModalLabel" aria-hidden="true">
253
+ <div class="modal-dialog modal-dialog-centered">
254
+ <div class="modal-content">
255
+ <div class="modal-header">
256
+ <h5 class="modal-title" id="bigPicModalLabel">大图预览</h5>
257
+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
258
+ </div>
259
+ <div class="modal-body text-center">
260
+ <img id="big-pic-img" src="" alt="大图" style="max-width:100%;max-height:60vh;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.12);">
261
+ </div>
262
+ </div>
263
+ </div>
264
+ </div>
265
+ <footer class="footer mt-5 py-3 bg-light border-top">
266
+ <div class="container text-center text-muted small">
267
+ <span>网易云音乐工具箱 &copy; 2025 | Protect What You Love</span>
268
+ </div>
269
+ </footer>
270
+ <script src="https://mirrors.sustech.edu.cn/cdnjs/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
271
+ <script src="https://mirrors.sustech.edu.cn/cdnjs/ajax/libs/aplayer/1.10.1/APlayer.min.js"></script>
272
+ <script src="https://mirrors.sustech.edu.cn/cdnjs/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
273
+ <script>
274
+ $(document).ready(function() {
275
+ function lrctrim(lyrics) {
276
+ const lines = lyrics.split('\n');
277
+ const data = [];
278
+
279
+ lines.forEach((line, index) => {
280
+ const matches = line.match(/\[(\d{2}):(\d{2}[\.:]?\d*)]/);
281
+ if (matches) {
282
+ const minutes = parseInt(matches[1], 10);
283
+ const seconds = parseFloat(matches[2].replace('.', ':')) || 0;
284
+ const timestamp = minutes * 60000 + seconds * 1000;
285
+
286
+ let text = line.replace(/\[\d{2}:\d{2}[\.:]?\d*\]/g, '').trim();
287
+ text = text.replace(/\s\s+/g, ' '); // Replace multiple spaces with a single space
288
+
289
+ data.push([timestamp, index, text]);
290
+ }
291
+ });
292
+
293
+ data.sort((a, b) => a[0] - b[0]);
294
+
295
+ return data;
296
+ }
297
+
298
+ function lrctran(lyric, tlyric) {
299
+ lyric = lrctrim(lyric);
300
+ tlyric = lrctrim(tlyric);
301
+
302
+ let len1 = lyric.length;
303
+ let len2 = tlyric.length;
304
+ let result = "";
305
+
306
+ for (let i = 0, j = 0; i < len1 && j < len2; i++) {
307
+ while (lyric[i][0] > tlyric[j][0] && j + 1 < len2) {
308
+ j++;
309
+ }
310
+
311
+ if (lyric[i][0] === tlyric[j][0]) {
312
+ tlyric[j][2] = tlyric[j][2].replace('/', '');
313
+ if (tlyric[j][2]) {
314
+ lyric[i][2] += ` (翻译:${tlyric[j][2]})`;
315
+ }
316
+ j++;
317
+ }
318
+ }
319
+
320
+ for (let i = 0; i < len1; i++) {
321
+ let t = lyric[i][0];
322
+ result += `[${String(Math.floor(t / 60000)).padStart(2, '0')}:${String(Math.floor((t % 60000) / 1000)).padStart(2, '0')}.${String(t % 1000).padStart(3, '0')}]${lyric[i][2]}\n`;
323
+ }
324
+
325
+ return result;
326
+ }
327
+
328
+ function extractLinks(text) {
329
+ var regex = /https?:\/\/\S+/g;
330
+ var matches = text.match(regex);
331
+ if (matches) {
332
+ return matches[0];
333
+ } else {
334
+ return '';
335
+ }
336
+ }
337
+
338
+ function checkValidLink(link) {
339
+ if (link.indexOf("http") === -1 ||
340
+ (link.indexOf("music.163.com") === -1 && link.indexOf("163cn.tv") === -1)) {
341
+ return false;
342
+ }
343
+ return true;
344
+ }
345
+
346
+ function extractAndCheckId(text) {
347
+ var link = extractLinks(text);
348
+ if (checkValidLink(link)) {
349
+ return link;
350
+ } else {
351
+ var idRegex = /\b\d+\b/g;
352
+ var ids = text.match(idRegex);
353
+ if (ids && ids.length > 0) {
354
+ return ids[0];
355
+ }
356
+ return '';
357
+ }
358
+ }
359
+
360
+ // 切换功能区
361
+ $('#mode-select').on('change', function() {
362
+ if ($(this).val() === 'search') {
363
+ $('#search-area').show();
364
+ $('#parse-area').hide();
365
+ $('#playlist-area').hide();
366
+ $('#album-area').hide();
367
+ $('#download-area').hide();
368
+ $('#song-info').addClass('d-none');
369
+ $('#playlist-result').addClass('d-none');
370
+ $('#album-result').addClass('d-none');
371
+ } else if ($(this).val() === 'parse') {
372
+ $('#search-area').hide();
373
+ $('#parse-area').show();
374
+ $('#playlist-area').hide();
375
+ $('#album-area').hide();
376
+ $('#download-area').hide();
377
+ $('#search-result').addClass('d-none');
378
+ $('#playlist-result').addClass('d-none');
379
+ $('#album-result').addClass('d-none');
380
+ } else if ($(this).val() === 'playlist') {
381
+ $('#search-area').hide();
382
+ $('#parse-area').hide();
383
+ $('#playlist-area').show();
384
+ $('#album-area').hide();
385
+ $('#download-area').hide();
386
+ $('#search-result').addClass('d-none');
387
+ $('#song-info').addClass('d-none');
388
+ $('#album-result').addClass('d-none');
389
+ } else if ($(this).val() === 'album') {
390
+ $('#search-area').hide();
391
+ $('#parse-area').hide();
392
+ $('#playlist-area').hide();
393
+ $('#album-area').show();
394
+ $('#download-area').hide();
395
+ $('#search-result').addClass('d-none');
396
+ $('#song-info').addClass('d-none');
397
+ $('#playlist-result').addClass('d-none');
398
+ $('#album-result').addClass('d-none');
399
+ } else if ($(this).val() === 'download') {
400
+ $('#search-area').hide();
401
+ $('#parse-area').hide();
402
+ $('#playlist-area').hide();
403
+ $('#album-area').hide();
404
+ $('#download-area').show();
405
+ $('#search-result').addClass('d-none');
406
+ $('#song-info').addClass('d-none');
407
+ $('#playlist-result').addClass('d-none');
408
+ $('#album-result').addClass('d-none');
409
+ } else {
410
+ $('#album-area').hide();
411
+ $('#download-area').hide();
412
+ $('#album-result').addClass('d-none');
413
+ }
414
+ });
415
+
416
+ // 搜索功能
417
+ $('#search-btn').on('click', function() {
418
+ const keywords = $('#search_keywords').val();
419
+ const limit = $('#search_limit').val();
420
+ if (!keywords) {
421
+ alert('请输入搜索关键词');
422
+ return;
423
+ }
424
+ $.ajax({
425
+ url: '/Search',
426
+ method: 'POST',
427
+ data: { keyword: keywords, limit: limit },
428
+ dataType: 'json',
429
+ success: function(data) {
430
+ if (data.status === 200) {
431
+ $('#search-list').empty();
432
+ data.data.forEach(function(song) {
433
+ const item = `<li class="list-group-item d-flex justify-content-between align-items-center">
434
+ <div>
435
+ <img src="${song.picUrl}" alt="cover" style="width:40px;height:40px;object-fit:cover;border-radius:4px;margin-right:10px;">
436
+ <strong class='song-title'>${song.name}</strong> - <span>${song.artists}</span> <span class="text-muted">[${song.album}]</span>
437
+ </div>
438
+ <div>
439
+ <button class="btn btn-sm btn-outline-primary select-song me-2" data-id="${song.id}" data-name="${song.name}">解析</button>
440
+ <button class="btn btn-sm btn-success download-song" data-id="${song.id}" data-name="${song.name}">下载</button>
441
+ </div>
442
+ </li>`;
443
+ $('#search-list').append(item);
444
+ });
445
+ $('#search-result').removeClass('d-none');
446
+ } else {
447
+ $('#search-list').html('<li class="list-group-item">未找到相关歌曲</li>');
448
+ $('#search-result').removeClass('d-none');
449
+ }
450
+ },
451
+ error: function() {
452
+ $('#search-list').html('<li class="list-group-item">搜索失败,请重试</li>');
453
+ $('#search-result').removeClass('d-none');
454
+ }
455
+ });
456
+ });
457
+
458
+ // 搜索结果点击解析
459
+ $(document).on('click', '.select-song', function() {
460
+ const songId = $(this).data('id');
461
+ $('#song_ids').val(songId);
462
+ $('#mode-select').val('parse').trigger('change');
463
+ $('html,body').animate({scrollTop: $('#main-form').offset().top}, 300);
464
+ });
465
+
466
+ // 单曲解析
467
+ $('#parse-btn').on('click', function() {
468
+ const songIds = $('#song_ids').val();
469
+ const level = $('#level').val();
470
+ if (!songIds) {
471
+ alert('请输入歌曲ID或URL');
472
+ return;
473
+ }
474
+ $.post('/Song_V1', { url: songIds, level: level, type:'json' }, function(data) {
475
+ if (data.status === 200) {
476
+ $('#song_name').text(data.data.name);
477
+ $('#artist_names').text(data.data.ar_name);
478
+ $('#song_alname').text(data.data.al_name);
479
+ $('#song_level').text(data.data.level);
480
+ $('#song_size').text(data.data.size);
481
+ let processedLyrics = data.data.lyric;
482
+ if (data.data.tlyric) {
483
+ processedLyrics = lrctran(data.data.lyric, data.data.tlyric);
484
+ }
485
+ $('#lyric').html(processedLyrics.replace(/\n/g, '<br>'));
486
+ $('#song_url').attr('href', data.data.url).text('点击下载');
487
+ $('#song-info').removeClass('d-none');
488
+ $('#show-big-pic').data('pic', data.data.pic);
489
+ new APlayer({
490
+ container: document.getElementById('aplayer'),
491
+ lrcType: 1,
492
+ audio: [{
493
+ name: data.data.name,
494
+ artist: data.data.ar_name,
495
+ url: data.data.url,
496
+ cover: data.data.pic,
497
+ lrc: processedLyrics
498
+ }]
499
+ });
500
+ } else {
501
+ alert(data.data.msg);
502
+ }
503
+ }, 'json');
504
+ });
505
+
506
+ // 显示大图按钮事件
507
+ $(document).on('click', '#show-big-pic', function() {
508
+ var picUrl = $(this).data('pic');
509
+ $('#big-pic-img').attr('src', picUrl);
510
+ var modal = new bootstrap.Modal(document.getElementById('bigPicModal'));
511
+ modal.show();
512
+ });
513
+
514
+ // 歌单解析
515
+ $('#playlist-btn').on('click', function() {
516
+ let pid = $('#playlist_id').val().trim();
517
+ if (!pid) {
518
+ alert('请输入歌单ID或链接');
519
+ return;
520
+ }
521
+ // 支持直接粘贴歌单链接
522
+ const idMatch = pid.match(/playlist\?id=(\d+)/);
523
+ if (idMatch) pid = idMatch[1];
524
+ $.get('/Playlist', { id: pid }, function(data) {
525
+ if (data.status === 200) {
526
+ const pl = data.data.playlist;
527
+ $('#playlist-cover').attr('src', pl.coverImgUrl);
528
+ $('#playlist-name').text(pl.name);
529
+ $('#playlist-creator').text('by ' + pl.creator);
530
+ $('#playlist-desc').text(pl.description || '');
531
+ $('#playlist-count').text(pl.trackCount);
532
+ $('#playlist-tracks').empty();
533
+ pl.tracks.forEach(function(song, idx) {
534
+ const item = `<li class="list-group-item d-flex justify-content-between align-items-center">
535
+ <div>
536
+ <img src="${song.picUrl}" alt="cover" style="width:32px;height:32px;object-fit:cover;border-radius:4px;margin-right:8px;">
537
+ <strong class="playlist-title">${idx+1}. ${song.name}</strong> - <span>${song.artists}</span> <span class="text-muted">[${song.album}]</span>
538
+ </div>
539
+ <div>
540
+ <button class="btn btn-sm btn-outline-primary select-song me-2" data-id="${song.id}" data-name="${song.name}">解析</button>
541
+ <button class="btn btn-sm btn-success download-song" data-id="${song.id}" data-name="${song.name}">下载</button>
542
+ </div>
543
+ </li>`;
544
+ $('#playlist-tracks').append(item);
545
+ });
546
+ $('#playlist-result').removeClass('d-none');
547
+ } else {
548
+ $('#playlist-result').removeClass('d-none');
549
+ $('#playlist-tracks').html('<li class="list-group-item">歌单解析失败:'+data.data.msg+'</li>');
550
+ }
551
+ }, 'json');
552
+ });
553
+
554
+ // 专辑解析
555
+ $(document).on('click', '#album-btn', function() {
556
+ let aid = $('#album_id').val().trim();
557
+ if (!aid) {
558
+ alert('请输入专辑ID或链接');
559
+ return;
560
+ }
561
+ // 支持直接粘贴专辑链接
562
+ const idMatch = aid.match(/album\?id=(\d+)/);
563
+ if (idMatch) aid = idMatch[1];
564
+ $.get('/Album', { id: aid }, function(data) {
565
+ if (data.status === 200) {
566
+ const al = data.data.album;
567
+ $('#album-cover').attr('src', al.coverImgUrl);
568
+ $('#album-name').text(al.name);
569
+ $('#album-artist').text(al.artist);
570
+ $('#album-desc').text(al.description || '');
571
+ $('#album-count').text(al.songs.length);
572
+ $('#album-tracks').empty();
573
+ al.songs.forEach(function(song, idx) {
574
+ const item = `<li class="list-group-item d-flex justify-content-between align-items-center">
575
+ <div>
576
+ <img src="${song.picUrl}" alt="cover" style="width:32px;height:32px;object-fit:cover;border-radius:4px;margin-right:8px;">
577
+ <strong class="playlist-title">${idx+1}. ${song.name}</strong> - <span>${song.artists}</span> <span class="text-muted">[${song.album}]</span>
578
+ </div>
579
+ <div>
580
+ <button class="btn btn-sm btn-outline-primary select-song me-2" data-id="${song.id}" data-name="${song.name}">解析</button>
581
+ <button class="btn btn-sm btn-success download-song" data-id="${song.id}" data-name="${song.name}">下载</button>
582
+ </div>
583
+ </li>`;
584
+ $('#album-tracks').append(item);
585
+ });
586
+ $('#album-result').removeClass('d-none');
587
+ } else {
588
+ $('#album-result').removeClass('d-none');
589
+ $('#album-tracks').html('<li class="list-group-item">专辑解析失败:'+data.data.msg+'</li>');
590
+ }
591
+ }, 'json');
592
+ });
593
+
594
+ // 音乐下载功能
595
+ $('#download-btn').on('click', function() {
596
+ const musicId = $('#download_id').val().trim();
597
+ const quality = $('#download_quality').val();
598
+
599
+ if (!musicId) {
600
+ alert('请输入音乐ID或URL');
601
+ return;
602
+ }
603
+
604
+ // 提取ID(支持URL格式)
605
+ let processedId = musicId;
606
+ const idMatch = musicId.match(/song\?id=(\d+)/);
607
+ if (idMatch) {
608
+ processedId = idMatch[1];
609
+ }
610
+
611
+ // 显示进度条
612
+ $('#download-progress').removeClass('d-none');
613
+ $('#download-btn').prop('disabled', true).text('下载中...');
614
+
615
+ // 使用XMLHttpRequest来处理下载并获取响应头
616
+ const xhr = new XMLHttpRequest();
617
+ xhr.open('POST', '/Download', true);
618
+ xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
619
+ xhr.responseType = 'blob';
620
+
621
+ xhr.onload = function() {
622
+ if (xhr.status === 200) {
623
+ // 获取自定义响应头
624
+ const downloadMessage = xhr.getResponseHeader('X-Download-Message');
625
+ const encodedFilename = xhr.getResponseHeader('X-Download-Filename');
626
+ const filename = encodedFilename ? decodeURIComponent(encodedFilename) : 'music.flac';
627
+
628
+ // 创建下载链接
629
+ const blob = xhr.response;
630
+ const url = window.URL.createObjectURL(blob);
631
+ const a = document.createElement('a');
632
+ a.href = url;
633
+ a.download = filename || 'music.flac';
634
+ document.body.appendChild(a);
635
+ a.click();
636
+ document.body.removeChild(a);
637
+ window.URL.revokeObjectURL(url);
638
+
639
+ // 显示完成提示
640
+ alert('✅ 音乐文件下载完成!');
641
+ console.log(`下载完成: ${filename}`);
642
+ if (downloadMessage) {
643
+ console.log(`服务器消息: ${downloadMessage}`);
644
+ }
645
+ } else {
646
+ alert('下载失败,请重试');
647
+ }
648
+
649
+ // 重置按钮状态
650
+ $('#download-progress').addClass('d-none');
651
+ $('#download-btn').prop('disabled', false).text('下载音乐');
652
+ };
653
+
654
+ xhr.onerror = function() {
655
+ alert('下载出错,请重试');
656
+ $('#download-progress').addClass('d-none');
657
+ $('#download-btn').prop('disabled', false).text('下载音乐');
658
+ };
659
+
660
+ // 发送请求
661
+ const formData = `id=${encodeURIComponent(processedId)}&quality=${encodeURIComponent(quality)}`;
662
+ xhr.send(formData);
663
+ });
664
+
665
+ // 列表中的下载按钮点击事件
666
+ // 下载按钮点击跳转到下载功能
667
+ $(document).on('click', '.download-song', function() {
668
+ const musicId = $(this).data('id');
669
+ const songName = $(this).data('name');
670
+
671
+ if (!musicId) {
672
+ alert('无法获取音乐ID');
673
+ return;
674
+ }
675
+
676
+ // 填充下载ID并跳转到下载功能区域
677
+ $('#download_id').val(musicId);
678
+ $('#mode-select').val('download').trigger('change');
679
+ $('html,body').animate({scrollTop: $('#main-form').offset().top}, 300);
680
+ });
681
+ });
682
+ </script>
683
+ </body>
684
+ </html>
使用文档.md ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 网易云音乐工具箱 - 使用文档
2
+
3
+ ## 📖 项目简介
4
+
5
+ 网易云音乐工具箱是一个功能强大的网易云音乐解析工具,支持歌曲搜索、单曲解析、歌单解析、专辑解析和音乐下载等功能。项目提供了友好的Web界面和完整的API接口,支持多种音质选择,包括无损、Hi-Res等高品质音频格式。
6
+
7
+ ## ✨ 功能特性
8
+
9
+ ### 🎵 核心功能
10
+ - **歌曲搜索**:支持关键词搜索网易云音乐库中的歌曲
11
+ - **单曲解析**:解析单首歌曲的详细信息和下载链接
12
+ - **歌单解析**:批量解析歌单中的所有歌曲
13
+ - **专辑解析**:批量解析专辑中的所有歌曲
14
+ - **音乐下载**:支持多种音质的音乐文件下载
15
+
16
+ ### 🎧 音质支持
17
+ - `standard`:标准音质 (128kbps)
18
+ - `exhigh`:极高音质 (320kbps)
19
+ - `lossless`:无损音质 (FLAC)
20
+ - `hires`:Hi-Res音质 (24bit/96kHz)
21
+ - `jyeffect`:高清环绕声
22
+ - `sky`:沉浸环绕声
23
+ - `jymaster`:超清母带
24
+
25
+ ### 🌐 使用方式
26
+ - **Web界面**:直观的网页操作界面
27
+ - **API接口**:完整的RESTful API
28
+ - **批量处理**:支持歌单和专辑的批量解析
29
+
30
+ ## 🚀 快速开始
31
+
32
+ ### 环境要求
33
+ - Python 3.7+
34
+ - 网易云音乐黑胶会员账号(用于获取高音质资源)
35
+
36
+ ### 安装步骤
37
+
38
+ 1. **克隆项目**
39
+ ```bash
40
+ git clone https://github.com/Suxiaoqinx/Netease_url.git
41
+ cd Netease_url
42
+ ```
43
+
44
+ 2. **安装依赖**
45
+ ```bash
46
+ pip install -r requirements.txt
47
+ ```
48
+
49
+ 3. **配置Cookie**
50
+
51
+ 在 `cookie.txt` 文件中填入黑胶会员账号的Cookie:
52
+
53
+ > 💡 **获取Cookie方法**:
54
+ > 1. 登录网易云音乐网页版
55
+ > 2. 按F12打开开发者工具
56
+ > 3. 在Network标签页找到任意请求
57
+ > 4. 复制请求头中的Cookie值
58
+
59
+ 4. **启动服务**
60
+ ```bash
61
+ python main.py
62
+ ```
63
+
64
+ 5. **访问界面**
65
+
66
+ 打开浏览器访问:`http://localhost:5000`
67
+
68
+ ## 🎯 使用指南
69
+
70
+ ### Web界面使用
71
+
72
+ #### 1. 歌曲搜索
73
+ 1. 选择「歌曲搜索」功能
74
+ 2. 输入搜索关键词
75
+ 3. 点击「搜索」按钮
76
+ 4. 在搜索结果中点击「解析」或「下载」按钮
77
+
78
+ #### 2. 单曲解析
79
+ 1. 选择「单曲解析」功能
80
+ 2. 输入歌曲ID或网易云音乐链接
81
+ 3. 选择音质等级
82
+ 4. 点击「解析」按钮查看歌曲信息
83
+ 5. 点击「下载」按钮下载音乐文件
84
+
85
+ #### 3. 歌单解析
86
+ 1. 选择「歌单解析」功能
87
+ 2. 输入歌单ID或歌单链接
88
+ 3. 点击「解析歌单」按钮
89
+ 4. 查看歌单信息和歌曲列表
90
+ 5. 点击单首歌曲的「解析」或「下载」按钮
91
+
92
+ #### 4. 专辑解析
93
+ 1. 选择「专辑解析」功能
94
+ 2. 输入专辑ID或专辑链接
95
+ 3. 点击「解析专辑」按钮
96
+ 4. 查看专辑信息和歌曲列表
97
+ 5. 点击单首歌曲的「解析」或「下载」按钮
98
+
99
+ #### 5. 音乐下载
100
+ 1. 选择「音乐下载」功能
101
+ 2. 输入音乐ID或链接
102
+ 3. 选择下载音质
103
+ 4. 点击「下载」按钮
104
+ 5. 等待下载完成
105
+
106
+ ### 链接格式支持
107
+
108
+ 项目支持多种网易云音乐链接格式:
109
+
110
+ - **歌曲链接**:`https://music.163.com/song?id=123456`
111
+ - **歌单链接**:`https://music.163.com/playlist?id=123456`
112
+ - **专辑链接**:`https://music.163.com/album?id=123456`
113
+ - **直接ID**:`123456`
114
+
115
+ ## 🔌 API接口文档
116
+
117
+ ### 基础信息
118
+ - **服务地址**:`http://localhost:5000`
119
+ - **请求方式**:POST(部分接口支持GET)
120
+ - **响应格式**:JSON
121
+
122
+ ### 接口列表
123
+
124
+ #### 1. 健康检查
125
+ ```http
126
+ GET /health
127
+ ```
128
+
129
+ **响应示例**:
130
+ ```json
131
+ {
132
+ "status": 200,
133
+ "success": true,
134
+ "message": "服务运行正常",
135
+ "data": {
136
+ "service": "网易云音乐API",
137
+ "version": "1.0.0",
138
+ "uptime": "2小时3分钟"
139
+ }
140
+ }
141
+ ```
142
+
143
+ #### 2. 歌曲搜索
144
+ ```http
145
+ POST /search
146
+ ```
147
+
148
+ **请求参数**:
149
+ ```json
150
+ {
151
+ "keyword": "搜索关键词",
152
+ "limit": 30
153
+ }
154
+ ```
155
+
156
+ **响应示例**:
157
+ ```json
158
+ {
159
+ "status": 200,
160
+ "success": true,
161
+ "message": "搜索完成",
162
+ "data": [
163
+ {
164
+ "id": "123456",
165
+ "name": "歌曲名称",
166
+ "artists": "艺术家",
167
+ "album": "专辑名称",
168
+ "picUrl": "封面图片URL"
169
+ }
170
+ ]
171
+ }
172
+ ```
173
+
174
+ #### 3. 单曲解析
175
+ ```http
176
+ POST /song
177
+ ```
178
+
179
+ **请求参数**:
180
+ ```json
181
+ {
182
+ "url": "歌曲ID或链接",
183
+ "level": "lossless",
184
+ "type": "json"
185
+ }
186
+ ```
187
+
188
+ **响应示例**:
189
+ ```json
190
+ {
191
+ "status": 200,
192
+ "success": true,
193
+ "message": "解析成功",
194
+ "data": {
195
+ "name": "歌曲名称",
196
+ "ar_name": "艺术家",
197
+ "al_name": "专辑名称",
198
+ "level": "lossless",
199
+ "size": "45.2MB",
200
+ "url": "下载链接",
201
+ "pic": "封面图片",
202
+ "lyric": "歌词内容"
203
+ }
204
+ }
205
+ ```
206
+
207
+ #### 4. 歌单解析
208
+ ```http
209
+ POST /playlist
210
+ ```
211
+
212
+ **请求参数**:
213
+ ```json
214
+ {
215
+ "id": "歌单ID"
216
+ }
217
+ ```
218
+
219
+ **响应示例**:
220
+ ```json
221
+ {
222
+ "status": 200,
223
+ "success": true,
224
+ "message": "歌单解析成功",
225
+ "data": {
226
+ "playlist": {
227
+ "name": "歌单名称",
228
+ "creator": "创建者",
229
+ "description": "歌��描述",
230
+ "coverImgUrl": "封面图片",
231
+ "trackCount": 50,
232
+ "tracks": [
233
+ {
234
+ "id": "123456",
235
+ "name": "歌曲名称",
236
+ "artists": "艺术家",
237
+ "album": "专辑名称",
238
+ "picUrl": "封面图片"
239
+ }
240
+ ]
241
+ }
242
+ }
243
+ }
244
+ ```
245
+
246
+ #### 5. 专辑解析
247
+ ```http
248
+ POST /album
249
+ ```
250
+
251
+ **请求参数**:
252
+ ```json
253
+ {
254
+ "id": "专辑ID"
255
+ }
256
+ ```
257
+
258
+ **响应示例**:
259
+ ```json
260
+ {
261
+ "status": 200,
262
+ "success": true,
263
+ "message": "专辑解析成功",
264
+ "data": {
265
+ "album": {
266
+ "name": "专辑名称",
267
+ "artist": "艺术家",
268
+ "description": "专辑描述",
269
+ "coverImgUrl": "封面图片",
270
+ "songs": [
271
+ {
272
+ "id": "123456",
273
+ "name": "歌曲名称",
274
+ "artists": "艺术家",
275
+ "album": "专辑名称",
276
+ "picUrl": "封面图片"
277
+ }
278
+ ]
279
+ }
280
+ }
281
+ }
282
+ ```
283
+
284
+ #### 6. 音乐下载
285
+ ```http
286
+ POST /download
287
+ ```
288
+
289
+ **请求参数**:
290
+ ```json
291
+ {
292
+ "id": "音乐ID",
293
+ "quality": "lossless"
294
+ }
295
+ ```
296
+
297
+ **响应**:返回音频文件流,支持直接下载
298
+
299
+ ## 🐳 Docker部署
300
+
301
+ ### 使用Docker Compose
302
+
303
+ 1. **修改配置**(可选)
304
+
305
+ 编辑 `docker-compose.yml` 文件修改端口:
306
+ ```yaml
307
+ ports:
308
+ - "8080:5000" # 将服务映射到8080端口
309
+ ```
310
+
311
+ 2. **启动服务**
312
+ ```bash
313
+ docker-compose up -d
314
+ ```
315
+
316
+ 3. **查看日志**
317
+ ```bash
318
+ docker-compose logs -f
319
+ ```
320
+
321
+ 4. **停止服务**
322
+ ```bash
323
+ docker-compose down
324
+ ```
325
+
326
+ ### 使用Dockerfile
327
+
328
+ ```bash
329
+ # 构建镜像
330
+ docker build -t netease-music-api .
331
+
332
+ # 运行容器
333
+ docker run -d -p 5000:5000 -v $(pwd)/downloads:/app/downloads netease-music-api
334
+ ```
335
+
336
+ ## ⚙️ 配置说明
337
+
338
+ ### 环境变量
339
+
340
+ 可以通过 `.env` 文件或环境变量配置服务:
341
+
342
+ ```bash
343
+ # 服务配置
344
+ HOST=0.0.0.0
345
+ PORT=5000
346
+ DEBUG=false
347
+
348
+ # 下载配置
349
+ DOWNLOADS_DIR=downloads
350
+ MAX_FILE_SIZE=524288000 # 500MB
351
+
352
+ # 日志配置
353
+ LOG_LEVEL=INFO
354
+ ```
355
+
356
+ ### Cookie配置
357
+
358
+ 在 `cookie.txt` 文件中配置网易云音乐Cookie:
359
+
360
+ ```
361
+ MUSIC_U=你的MUSIC_U值;os=pc;appver=8.9.70;
362
+ ```
363
+
364
+ > ⚠️ **重要提示**:
365
+ > - 必须使用黑胶会员账号的Cookie
366
+ > - Cookie格式必须严格按照示例填写
367
+ > - 定期更新Cookie以保持有效性
368
+
369
+ ## 🔧 故障排除
370
+
371
+ ### 常见问题
372
+
373
+ #### 1. Cookie无效
374
+ **问题**:提示Cookie无效或过期
375
+
376
+ **解决方案**:
377
+ - 确认使用的是黑胶会员账号
378
+ - 重新获取Cookie并更新 `cookie.txt`
379
+ - 检查Cookie格式是否正确
380
+
381
+ #### 2. 无法下载高音质
382
+ **问题**:只能下载标准音质
383
+
384
+ **解决方案**:
385
+ - 确认账号是黑胶会员
386
+ - 检查Cookie是否有效
387
+ - 确认歌曲本身支持高音质
388
+
389
+ #### 3. 服务启动失败
390
+ **问题**:运行 `python main.py` 报错
391
+
392
+ **解决方案**:
393
+ - 检查Python版本(需要3.7+)
394
+ - 安装所有依赖:`pip install -r requirements.txt`
395
+ - 检查端口5000是否被占用
396
+
397
+ #### 4. 下载文件损坏
398
+ **问题**:下载的音频文件无法播放
399
+
400
+ **解决方案**:
401
+ - 检查网络连接是否稳定
402
+ - 重新下载文件
403
+ - 尝试其他音质选项
404
+
405
+ ### 日志查看
406
+
407
+ 服务运行时会生成日志文件 `music_api.log`,可以查看详细的错误信息:
408
+
409
+ ```bash
410
+ tail -f music_api.log
411
+ ```
412
+
413
+ ## 📝 开发说明
414
+
415
+ ### 项目结构
416
+
417
+ ```
418
+ Netease_url/
419
+ ├── main.py # 主程序入口
420
+ ├── music_api.py # 音乐API核心模块
421
+ ├── music_downloader.py # 音乐下载模块
422
+ ├── cookie_manager.py # Cookie管理模块
423
+ ├── qr_login.py # 二维码登录模块
424
+ ├── templates/
425
+ │ └── index.html # Web界面模板
426
+ ├── downloads/ # 下载文件目录
427
+ ├── requirements.txt # Python依赖
428
+ ├── Dockerfile # Docker构建文件
429
+ ├── docker-compose.yml # Docker Compose配置
430
+ └── README.md # 项目说明
431
+ ```
432
+
433
+ ### 技术栈
434
+
435
+ - **后端**:Flask + Python
436
+ - **前端**:Bootstrap + jQuery
437
+ - **音频处理**:mutagen
438
+ - **HTTP客户端**:aiohttp + requests
439
+ - **容器化**:Docker
440
+
441
+ ## 📄 许可证
442
+
443
+ 本项目采用 MIT 许可证开源,但**禁止用于任何商业或付费项目**。
444
+
445
+ ## 🤝 贡献指南
446
+
447
+ 欢迎提交Issue和Pull Request!
448
+
449
+ 1. Fork本项目
450
+ 2. 创建特性分支:`git checkout -b feature/new-feature`
451
+ 3. 提交更改:`git commit -am 'Add new feature'`
452
+ 4. 推送分支:`git push origin feature/new-feature`
453
+ 5. 提交Pull Request
454
+
455
+ ## 📞 联系方式
456
+
457
+ - **GitHub Issues**:[提交问题](https://github.com/Suxiaoqinx/Netease_url/issues)
458
+ - **作者博客**:[https://www.toubiec.cn](https://www.toubiec.cn)
459
+
460
+ ---
461
+
462
+ **⭐ 如果这个项目对你有帮助,请给个Star支持一下!**