-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1948 lines (1597 loc) · 70.8 KB
/
Copy pathmain.py
File metadata and controls
1948 lines (1597 loc) · 70.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""网易云音乐API服务主程序
提供网易云音乐相关API服务,包括:
- 歌曲信息获取
- 音乐搜索
- 歌单和专辑详情
- 音乐下载
- 健康检查
- API可用性监控
"""
import logging
import sys
import time
import traceback
import threading
import smtplib
import requests
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import date, datetime
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Any, Optional, Tuple, List
from urllib.parse import quote
from flask import Flask, request, send_file, render_template, Response, session, redirect, url_for, jsonify
import functools
import db_helper
import requests as sync_requests
from config import config as app_config
# ===== 代理池配置 =====
PROXY_API_URL = 'https://proxy.scdn.io/api/get_proxy.php'
PROXY_CACHE_FILE = 'proxy_cache.json'
class ProxyPool:
"""代理池管理类"""
def __init__(self):
self._lock = threading.Lock()
self._cache = []
self._last_fetch = 0
self._fetch_interval = 300 # 5分钟刷新一次
def _fetch_from_api(self, protocol: str = 'all', count: int = 10) -> List[str]:
"""从API获取代理"""
try:
params = {'protocol': protocol, 'count': count}
response = sync_requests.get(PROXY_API_URL, params=params, timeout=15)
data = response.json()
if data.get('code') == 200 and data.get('data', {}).get('proxies'):
return data['data']['proxies']
except Exception as e:
print(f"获取代理失败: {e}")
return []
def get_proxies(self, protocol: str = 'all', count: int = 5, force_refresh: bool = False) -> List[Dict[str, Any]]:
"""获取代理列表"""
with self._lock:
now = time.time()
if force_refresh or now - self._last_fetch > self._fetch_interval or not self._cache:
self._cache = self._fetch_from_api(protocol, 20)
self._last_fetch = now
result = []
for proxy in self._cache[:count]:
if ':' in proxy:
ip, port = proxy.rsplit(':', 1)
result.append({
'proxy': proxy,
'ip': ip,
'port': int(port),
'protocol': protocol if protocol != 'all' else 'http'
})
return result
def refresh(self, protocol: str = 'all') -> int:
"""手动刷新代理池"""
with self._lock:
self._cache = self._fetch_from_api(protocol, 20)
self._last_fetch = time.time()
return len(self._cache)
# 全局代理池实例
proxy_pool = ProxyPool()
try:
from music_api import (
NeteaseAPI, APIException, QualityLevel,
url_v1, name_v1, lyric_v1, search_music,
playlist_detail, album_detail
)
from cookie_manager import CookieManager, CookieException
from music_downloader import MusicDownloader, DownloadException, AudioFormat
except ImportError as e:
print(f"导入模块失败: {e}")
print("请确保所有依赖模块存在且可用")
sys.exit(1)
@dataclass
class APIConfig:
"""API配置类"""
host: str = '0.0.0.0'
port: int = 5000
debug: bool = False
downloads_dir: str = 'downloads'
max_file_size: int = 500 * 1024 * 1024 # 500MB
request_timeout: int = 30
log_level: str = 'INFO'
cors_origins: str = '*'
system_public_key: str = ''
class APIResponse:
"""API响应工具类"""
@staticmethod
def success(data: Any = None, message: str = 'success', status_code: int = 200) -> Tuple[Dict[str, Any], int]:
"""成功响应"""
response = {
'status': status_code,
'success': True,
'message': message
}
if data is not None:
response['data'] = data
return response, status_code
@staticmethod
def error(message: str, status_code: int = 400, error_code: str = None) -> Tuple[Dict[str, Any], int]:
"""错误响应"""
response = {
'status': status_code,
'success': False,
'message': message
}
if error_code:
response['error_code'] = error_code
return response, status_code
class MusicAPIService:
"""音乐API服务类"""
def __init__(self, config: APIConfig):
self.config = config
self.logger = self._setup_logger()
self.cookie_manager = CookieManager()
self.netease_api = NeteaseAPI()
self.downloader = MusicDownloader()
# 创建下载目录
self.downloads_path = Path(config.downloads_dir)
self.downloads_path.mkdir(exist_ok=True)
self.logger.info(f"音乐API服务初始化完成,下载目录: {self.downloads_path.absolute()}")
def _setup_logger(self) -> logging.Logger:
"""设置日志记录器"""
logger = logging.getLogger('music_api')
logger.setLevel(getattr(logging, self.config.log_level.upper()))
if not logger.handlers:
# 控制台处理器
console_handler = logging.StreamHandler()
console_formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
console_handler.setFormatter(console_formatter)
logger.addHandler(console_handler)
# 文件处理器
try:
file_handler = logging.FileHandler('music_api.log', encoding='utf-8')
file_formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
)
file_handler.setFormatter(file_formatter)
logger.addHandler(file_handler)
except Exception as e:
logger.warning(f"无法创建日志文件: {e}")
return logger
def _get_cookies(self) -> Dict[str, str]:
"""获取Cookie"""
try:
cookie_str = self.cookie_manager.read_cookie()
return self.cookie_manager.parse_cookie_string(cookie_str)
except CookieException as e:
self.logger.warning(f"获取Cookie失败: {e}")
return {}
except Exception as e:
self.logger.error(f"Cookie处理异常: {e}")
return {}
def _extract_music_id(self, id_or_url: str) -> str:
"""提取音乐ID"""
try:
# 处理短链接
if '163cn.tv' in id_or_url:
import requests
response = requests.get(id_or_url, allow_redirects=False, timeout=10)
id_or_url = response.headers.get('Location', id_or_url)
# 处理网易云链接
if 'music.163.com' in id_or_url:
index = id_or_url.find('id=') + 3
if index > 2:
return id_or_url[index:].split('&')[0]
# 直接返回ID
return str(id_or_url).strip()
except Exception as e:
self.logger.error(f"提取音乐ID失败: {e}")
return str(id_or_url).strip()
def _format_file_size(self, size_bytes: int) -> str:
"""格式化文件大小"""
if size_bytes == 0:
return "0B"
units = ["B", "KB", "MB", "GB", "TB"]
size = float(size_bytes)
unit_index = 0
while size >= 1024.0 and unit_index < len(units) - 1:
size /= 1024.0
unit_index += 1
return f"{size:.2f}{units[unit_index]}"
def _get_quality_display_name(self, quality: str) -> str:
"""获取音质显示名称"""
quality_names = {
'standard': "标准音质",
'exhigh': "极高音质",
'lossless': "无损音质",
'hires': "Hi-Res音质",
'sky': "沉浸环绕声",
'jyeffect': "高清环绕声",
'jymaster': "超清母带",
'dolby': "杜比全景声"
}
return quality_names.get(quality, f"未知音质({quality})")
def _validate_request_params(self, required_params: Dict[str, Any]) -> Optional[Tuple[Dict[str, Any], int]]:
"""验证请求参数"""
for param_name, param_value in required_params.items():
if not param_value:
return APIResponse.error(f"参数 '{param_name}' 不能为空", 400)
return None
def _safe_get_request_data(self) -> Dict[str, Any]:
"""安全获取请求数据"""
try:
if request.method == 'GET':
return dict(request.args)
else:
# 优先使用JSON数据,然后是表单数据
json_data = request.get_json(silent=True) or {}
form_data = dict(request.form)
# 合并数据,JSON优先
return {**form_data, **json_data}
except Exception as e:
self.logger.error(f"获取请求数据失败: {e}")
return {}
# 创建Flask应用和服务实例
config = APIConfig()
config.host = app_config.HOST
config.port = app_config.PORT
config.debug = app_config.DEBUG
config.downloads_dir = app_config.DOWNLOADS_DIR
config.cors_origins = app_config.CORS_ORIGINS
# 加载系统公用密钥
try:
conn = db_helper.get_conn()
with conn.cursor() as cur:
cur.execute("SELECT api_key FROM api_keys WHERE key_name = '系统公用密钥' AND status = 1 LIMIT 1")
row = cur.fetchone()
if row:
config.system_public_key = row['api_key']
print(f"✅ 系统公用密钥已加载")
else:
print("️ 未找到系统公用密钥,主页API调用可能失败")
conn.close()
except Exception as e:
print(f"⚠️ 加载系统公用密钥失败: {e}")
app = Flask(__name__)
app.secret_key = app_config.SECRET_KEY
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
# Session配置
from flask import session
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['SESSION_COOKIE_SECURE'] = False
api_service = MusicAPIService(config)
def send_health_email(to_emails: list, subject: str, body: str):
"""发送健康通知邮件"""
smtp = {
"host": app_config.SMTP_HOST,
"port": app_config.SMTP_PORT,
"user": app_config.SMTP_USER,
"password": app_config.SMTP_PASSWORD,
"from_name": app_config.SMTP_FROM_NAME,
}
if not smtp.get("user") or not smtp.get("password"):
return
try:
msg = MIMEMultipart()
msg["From"] = f"{smtp['from_name']} <{smtp['user']}>"
msg["Subject"] = subject
msg.attach(MIMEText(body, "html", "utf-8"))
server = smtplib.SMTP(smtp["host"], smtp["port"], timeout=15)
server.starttls()
server.login(smtp["user"], smtp["password"])
for email in to_emails:
msg["To"] = email
server.sendmail(smtp["user"], email, msg.as_string())
server.quit()
except Exception as e:
pass
def check_api_health():
"""检测API健康状态并存入数据库,状态变化时发送邮件通知"""
try:
start = time.time()
response = sync_requests.get('http://localhost:5000/health', timeout=30)
latency = int((time.time() - start) * 1000)
if response.status_code == 200:
status = 'up'
elif latency > 5000:
status = 'warning'
else:
status = 'down'
prev = db_helper.get_health_previous_status()
db_helper.save_health_check(status, latency)
if prev != 'unknown' and prev != status:
subscribers = db_helper.get_active_subscribers()
if subscribers:
now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if status == 'up' and prev in ('down', 'warning'):
send_health_email(subscribers,
'✅ MusicAPI 服务已恢复',
f'<h3>服务已恢复正常</h3>'
f'<p>恢复时间:{now_str}</p><p>响应延迟:{latency}ms</p>'
f'<p><a href="https://music.rrvenn.cn/health/monitor">查看监控面板</a></p>')
elif status == 'down' and prev in ('up', 'warning'):
send_health_email(subscribers,
'🔴 MusicAPI 服务异常',
f'<h3>服务检测失败</h3>'
f'<p>异常时间:{now_str}</p><p>请及时排查。</p>'
f'<p><a href="https://music.rrvenn.cn/health/monitor">查看监控面板</a></p>')
except Exception as e:
prev = db_helper.get_health_previous_status()
db_helper.save_health_check('down', -1)
if prev != 'unknown' and prev != 'down':
subscribers = db_helper.get_active_subscribers()
if subscribers:
now_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
send_health_email(subscribers,
'🔴 MusicAPI 服务异常',
f'<h3>服务检测失败(连接超时)</h3>'
f'<p>异常时间:{now_str}</p><p>请及时排查。</p>'
f'<p><a href="https://music.rrvenn.cn/health/monitor">查看监控面板</a></p>')
def health_monitor_loop():
"""健康监控定时任务循环"""
while True:
check_api_health()
time.sleep(900)
# 启动健康监控线程(延迟5秒启动,等待Flask服务就绪)
def start_monitor_with_delay():
time.sleep(5)
check_api_health()
monitor_thread = threading.Thread(target=health_monitor_loop, daemon=True)
monitor_thread.start()
monitor_init_thread = threading.Thread(target=start_monitor_with_delay, daemon=True)
monitor_init_thread.start()
# 存储当前请求的 API Key 信息
g_api_key_info = None
def get_api_key_from_request():
"""从请求中获取 API Key"""
# 从 Header 获取
auth_header = request.headers.get('Authorization', '')
if auth_header.startswith('Bearer '):
return auth_header[7:]
# 从 Query 参数获取
return request.args.get('api_key', '')
@app.before_request
def before_request():
"""请求前处理 - 强制API Key认证"""
global g_api_key_info
g_api_key_info = None
# 记录请求信息
api_service.logger.info(
f"{request.method} {request.path} - IP: {request.remote_addr} - "
f"User-Agent: {request.headers.get('User-Agent', 'Unknown')}"
)
# 公开路径(不需要API Key)
public_paths = ['/user', '/admin', '/docs', '/health', '/static', '/favicon.ico', '/api/stats']
# 检查是否是公开路径(管理后台和用户平台有自己的session认证)
is_public = False
# 精确匹配根路径
if request.path == '/':
is_public = True
else:
for p in public_paths:
if request.path == p or request.path.startswith(p + '/'):
is_public = True
break
if is_public:
return
# 获取API Key
api_key = get_api_key_from_request()
# 如果没有提供API Key,使用系统公用密钥
if not api_key:
api_key = config.system_public_key
# 验证 API Key
if not db_helper.validate_api_key(api_key):
api_service.logger.warning(f"API Key验证失败: {api_key[:10]}...")
resp = jsonify({"status": 401, "success": False, "message": "无效的API Key"})
resp.status_code = 401
return resp
g_api_key_info = db_helper.get_api_key_info(api_key)
api_service.logger.info(f"API Key认证成功: key_id={g_api_key_info['id']}, name={g_api_key_info['key_name']}")
@app.after_request
def after_request(response: Response) -> Response:
"""请求后处理 - 设置CORS头、禁用缓存并记录统计"""
# 获取请求的Origin头
origin = request.headers.get('Origin', '')
# 如果有Origin头,设置CORS(支持credentials)
if origin:
if config.cors_origins == '*' or origin in config.cors_origins.split(','):
response.headers.add('Access-Control-Allow-Origin', origin)
response.headers.add('Access-Control-Allow-Credentials', 'true')
else:
response.headers.add('Access-Control-Allow-Origin', config.cors_origins)
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,X-API-Key')
response.headers.add('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
response.headers.add('Access-Control-Max-Age', '3600')
# 完全禁用缓存 - 通用 + CDN 专用头
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0, s-maxage=0, proxy-revalidate, private'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT'
response.headers['CDN-Cache-Control'] = 'no-store, max-age=0'
response.headers['Surrogate-Control'] = 'no-store, max-age=0'
response.headers['Edge-Control'] = 'no-store, max-age=0'
response.headers['x-cache-ttl'] = '0'
api_service.logger.info(f"响应状态: {response.status_code}")
skip_paths = ('/admin', '/static', '/favicon.ico', '/@', '/__')
if not request.path.startswith(skip_paths):
try:
user_id = None
api_key_id = None
if g_api_key_info:
api_key_id = g_api_key_info['id']
# 获取 Key 所属用户
keys = db_helper.list_api_keys()
for key in keys:
if key['id'] == api_key_id:
user_id = key['user_id']
break
db_helper.log_api_call(
endpoint=request.path,
method=request.method,
ip_address=request.headers.get('X-Forwarded-For', '').split(',')[0].strip() or request.headers.get('X-Real-IP', '') or request.remote_addr or '127.0.0.1',
user_agent=request.headers.get('User-Agent', '')[:500],
status_code=response.status_code,
user_id=user_id,
api_key_id=api_key_id
)
except Exception:
pass
return response
@app.errorhandler(400)
def handle_bad_request(e):
"""处理400错误"""
return APIResponse.error("请求参数错误", 400)
@app.errorhandler(404)
def handle_not_found(e):
"""处理404错误"""
return APIResponse.error("请求的资源不存在", 404)
@app.errorhandler(500)
def handle_internal_error(e):
"""处理500错误"""
api_service.logger.error(f"服务器内部错误: {e}")
return APIResponse.error("服务器内部错误", 500)
def login_required(f):
"""登录检查装饰器 - 支持管理员session或API Key认证"""
@functools.wraps(f)
def decorated_function(*args, **kwargs):
if not session.get('user_id') and not g_api_key_info:
return APIResponse.error("请先登录或提供有效的API Key", 401)
return f(*args, **kwargs)
return decorated_function
@app.route('/')
def index() -> str:
"""首页路由"""
return render_template('index.html')
@app.route('/docs')
def api_docs():
"""API文档页面"""
return render_template('docs.html')
@app.route('/user')
def user_home():
"""用户平台首页"""
return render_template('user_home.html')
@app.route('/user/dashboard')
def user_dashboard():
"""用户控制面板"""
return render_template('user_dashboard.html')
@app.route('/api/api.php', methods=['GET', 'POST'])
@login_required
def api_php_compat():
"""兼容旧版API格式(Scratch扩展使用)"""
try:
data = api_service._safe_get_request_data()
action = data.get('action', '').lower()
if action == 'search':
keyword = data.get('name', '')
limit = int(data.get('limit', 10))
search_type = int(data.get('type', 1))
import flask
original_args = flask.request.args.to_dict()
original_form = flask.request.form.to_dict()
flask.request.args = flask.MultiDict({'keyword': keyword, 'limit': limit})
flask.request.form = flask.MultiDict({'keyword': keyword, 'limit': limit})
try:
resp = search_music_api()
result = []
for item in resp[0].get('data', []):
result.append({
'id': item.get('id'),
'name': item.get('name'),
'artist': item.get('artists', item.get('artist_string', '')),
'album': item.get('album', ''),
'picUrl': item.get('picUrl', '')
})
return jsonify({'code': 200, 'data': result[:limit], 'msg': 'success'})
finally:
flask.request.args = flask.MultiDict(original_args)
flask.request.form = flask.MultiDict(original_form)
elif action == 'music':
url = data.get('url', '')
level = data.get('level', 'standard')
yrc = data.get('yrc', 0)
if not url:
return jsonify({'code': 400, 'error': '缺少url参数'})
song_id = api_service._extract_music_id(url)
cookies = api_service._get_cookies()
valid_levels = ['standard', 'exhigh', 'lossless', 'hires', 'sky', 'jyeffect', 'jymaster']
if level not in valid_levels:
level = 'standard'
result = url_v1(song_id, level, cookies)
if result and result.get('data') and len(result['data']) > 0:
song_data = result['data'][0]
response = {
'code': 200,
'data': {
'id': song_data.get('id'),
'name': song_data.get('name', ''),
'artist': song_data.get('ar', song_data.get('ar_name', '')),
'album': song_data.get('al', song_data.get('al_name', '')),
'url': song_data.get('url', ''),
'size': song_data.get('size', 0),
'level': song_data.get('level', level),
'pic': song_data.get('pic', ''),
'lyric': song_data.get('lyric', ''),
'tlyric': song_data.get('tlyric', '')
},
'msg': 'success'
}
if isinstance(response['data']['artist'], dict):
response['data']['artist'] = response['data']['artist'].get('name', '')
if isinstance(response['data']['album'], dict):
response['data']['album'] = response['data']['album'].get('name', '')
return jsonify(response)
else:
return jsonify({'code': 500, 'error': '获取歌曲信息失败'})
elif action == 'artist':
artist_id = data.get('id', '')
limit = int(data.get('limit', 10))
if not artist_id:
return jsonify({'code': 400, 'error': '缺少id参数'})
return jsonify({'code': 200, 'data': [], 'msg': 'success'})
else:
return jsonify({'code': 400, 'error': f'未知action: {action}'})
except Exception as e:
api_service.logger.error(f"兼容API错误: {e}")
return jsonify({'code': 500, 'error': str(e)})
@app.route('/health', methods=['GET'])
def health_check():
"""健康检查API"""
try:
# 检查Cookie状态
cookie_status = api_service.cookie_manager.is_cookie_valid()
health_info = {
'service': 'running',
'timestamp': int(time.time()) if 'time' in sys.modules else None,
'cookie_status': 'valid' if cookie_status else 'invalid',
'downloads_dir': str(api_service.downloads_path.absolute()),
'version': '2.0.0'
}
return APIResponse.success(health_info, "API服务运行正常")
except Exception as e:
api_service.logger.error(f"健康检查失败: {e}")
return APIResponse.error(f"健康检查失败: {str(e)}", 500)
@app.route('/song', methods=['GET', 'POST'])
@app.route('/Song_V1', methods=['GET', 'POST']) # 向后兼容
@login_required
def get_song_info():
"""获取歌曲信息API"""
try:
# 获取请求参数
data = api_service._safe_get_request_data()
song_ids = data.get('ids') or data.get('id')
url = data.get('url')
level = data.get('level', 'lossless')
info_type = data.get('type', 'url')
# 参数验证
if not song_ids and not url:
return APIResponse.error("必须提供 'ids'、'id' 或 'url' 参数")
# 提取音乐ID
music_id = api_service._extract_music_id(song_ids or url)
# 验证音质参数
valid_levels = ['standard', 'exhigh', 'lossless', 'hires', 'sky', 'jyeffect', 'jymaster']
if level not in valid_levels:
return APIResponse.error(f"无效的音质参数,支持: {', '.join(valid_levels)}")
# 验证类型参数
valid_types = ['url', 'name', 'lyric', 'json']
if info_type not in valid_types:
return APIResponse.error(f"无效的类型参数,支持: {', '.join(valid_types)}")
cookies = api_service._get_cookies()
# 根据类型获取不同信息
if info_type == 'url':
result = url_v1(music_id, level, cookies)
if result and result.get('data') and len(result['data']) > 0:
song_data = result['data'][0]
response_data = {
'id': song_data.get('id'),
'url': song_data.get('url'),
'level': song_data.get('level'),
'quality_name': api_service._get_quality_display_name(song_data.get('level', level)),
'size': song_data.get('size'),
'size_formatted': api_service._format_file_size(song_data.get('size', 0)),
'type': song_data.get('type'),
'bitrate': song_data.get('br')
}
return APIResponse.success(response_data, "获取歌曲URL成功")
else:
return APIResponse.error("获取音乐URL失败,可能是版权限制或音质不支持", 404)
elif info_type == 'name':
result = name_v1(music_id)
return APIResponse.success(result, "获取歌曲信息成功")
elif info_type == 'lyric':
result = lyric_v1(music_id, cookies)
return APIResponse.success(result, "获取歌词成功")
elif info_type == 'json':
# 获取完整的歌曲信息(用于前端解析)
song_info = name_v1(music_id)
url_info = url_v1(music_id, level, cookies)
lyric_info = lyric_v1(music_id, cookies)
if not song_info or 'songs' not in song_info or not song_info['songs']:
return APIResponse.error("未找到歌曲信息", 404)
song_data = song_info['songs'][0]
# 构建前端期望的响应格式
response_data = {
'id': music_id,
'name': song_data.get('name', ''),
'ar_name': ', '.join(artist['name'] for artist in song_data.get('ar', [])),
'al_name': song_data.get('al', {}).get('name', ''),
'pic': song_data.get('al', {}).get('picUrl', ''),
'level': level,
'lyric': lyric_info.get('lrc', {}).get('lyric', '') if lyric_info else '',
'tlyric': lyric_info.get('tlyric', {}).get('lyric', '') if lyric_info else ''
}
# 添加URL和大小信息
if url_info and url_info.get('data') and len(url_info['data']) > 0:
url_data = url_info['data'][0]
response_data.update({
'url': url_data.get('url', ''),
'size': api_service._format_file_size(url_data.get('size', 0)),
'level': url_data.get('level', level)
})
else:
response_data.update({
'url': '',
'size': '获取失败'
})
return APIResponse.success(response_data, "获取歌曲信息成功")
except APIException as e:
api_service.logger.error(f"API调用失败: {e}")
return APIResponse.error(f"API调用失败: {str(e)}", 500)
except Exception as e:
api_service.logger.error(f"获取歌曲信息异常: {e}\n{traceback.format_exc()}")
return APIResponse.error(f"服务器错误: {str(e)}", 500)
@app.route('/search', methods=['GET', 'POST'])
@app.route('/Search', methods=['GET', 'POST']) # 向后兼容
@login_required
def search_music_api():
"""搜索音乐API"""
try:
# 获取请求参数
data = api_service._safe_get_request_data()
keyword = data.get('keyword') or data.get('keywords') or data.get('q')
limit = int(data.get('limit', 30))
offset = int(data.get('offset', 0))
search_type = data.get('type', '1') # 1-歌曲, 10-专辑, 100-歌手, 1000-歌单
# 参数验证
validation_error = api_service._validate_request_params({'keyword': keyword})
if validation_error:
return validation_error
# 限制搜索数量
if limit > 100:
limit = 100
cookies = api_service._get_cookies()
result = search_music(keyword, cookies, limit)
# search_music返回的是歌曲列表,需要包装成前端期望的格式
if result:
for song in result:
# 添加艺术家字符串(如果需要)
if 'artists' in song:
song['artist_string'] = song['artists']
return APIResponse.success(result, "搜索完成")
except ValueError as e:
return APIResponse.error(f"参数格式错误: {str(e)}")
except Exception as e:
api_service.logger.error(f"搜索音乐异常: {e}\n{traceback.format_exc()}")
return APIResponse.error(f"搜索失败: {str(e)}", 500)
@app.route('/playlist', methods=['GET', 'POST'])
@app.route('/Playlist', methods=['GET', 'POST']) # 向后兼容
@login_required
def get_playlist():
"""获取歌单详情API"""
try:
# 获取请求参数
data = api_service._safe_get_request_data()
playlist_id = data.get('id')
# 参数验证
validation_error = api_service._validate_request_params({'playlist_id': playlist_id})
if validation_error:
return validation_error
cookies = api_service._get_cookies()
result = playlist_detail(playlist_id, cookies)
# 适配前端期望的响应格式
response_data = {
'status': 'success',
'playlist': result
}
return APIResponse.success(response_data, "获取歌单详情成功")
except Exception as e:
api_service.logger.error(f"获取歌单异常: {e}\n{traceback.format_exc()}")
return APIResponse.error(f"获取歌单失败: {str(e)}", 500)
@app.route('/album', methods=['GET', 'POST'])
@app.route('/Album', methods=['GET', 'POST']) # 向后兼容
@login_required
def get_album():
"""获取专辑详情API"""
try:
# 获取请求参数
data = api_service._safe_get_request_data()
album_id = data.get('id')
# 参数验证
validation_error = api_service._validate_request_params({'album_id': album_id})
if validation_error:
return validation_error
cookies = api_service._get_cookies()
result = album_detail(album_id, cookies)
# 适配前端期望的响应格式
response_data = {
'status': 200,
'album': result
}
return APIResponse.success(response_data, "获取专辑详情成功")
except Exception as e:
api_service.logger.error(f"获取专辑异常: {e}\n{traceback.format_exc()}")
return APIResponse.error(f"获取专辑失败: {str(e)}", 500)
@app.route('/download', methods=['GET', 'POST'])
@app.route('/Download', methods=['GET', 'POST']) # 向后兼容
@login_required
def download_music_api():
"""下载音乐API"""
try:
# 获取请求参数
data = api_service._safe_get_request_data()
music_id = data.get('id')
quality = data.get('quality', 'lossless')
return_format = data.get('format', 'file') # file 或 json
# 参数验证
validation_error = api_service._validate_request_params({'music_id': music_id})
if validation_error:
return validation_error
# 验证音质参数
valid_qualities = ['standard', 'exhigh', 'lossless', 'hires', 'sky', 'jyeffect', 'jymaster']
if quality not in valid_qualities:
return APIResponse.error(f"无效的音质参数,支持: {', '.join(valid_qualities)}")
# 验证返回格式
if return_format not in ['file', 'json']:
return APIResponse.error("返回格式只支持 'file' 或 'json'")
music_id = api_service._extract_music_id(music_id)
cookies = api_service._get_cookies()
# 获取音乐基本信息
song_info = name_v1(music_id)
if not song_info or 'songs' not in song_info or not song_info['songs']:
return APIResponse.error("未找到音乐信息", 404)
# 获取音乐下载链接
url_info = url_v1(music_id, quality, cookies)
if not url_info or 'data' not in url_info or not url_info['data'] or not url_info['data'][0].get('url'):
return APIResponse.error("无法获取音乐下载链接,可能是版权限制或音质不支持", 404)
# 构建音乐信息
song_data = song_info['songs'][0]
url_data = url_info['data'][0]
music_info = {
'id': music_id,
'name': song_data['name'],
'artist_string': ', '.join(artist['name'] for artist in song_data['ar']),
'album': song_data['al']['name'],
'pic_url': song_data['al']['picUrl'],
'file_type': url_data['type'],
'file_size': url_data['size'],
'duration': song_data.get('dt', 0),
'download_url': url_data['url']
}
# 生成安全文件名
safe_name = f"{music_info['name']} [{quality}]"
safe_name = ''.join(c for c in safe_name if c not in r'<>:"/\|?*')
filename = f"{safe_name}.{music_info['file_type']}"
file_path = api_service.downloads_path / filename
# 检查文件是否已存在
if file_path.exists():
api_service.logger.info(f"文件已存在: {filename}")
else:
# 使用优化后的下载器下载
try:
download_result = api_service.downloader.download_music_file(
music_id, quality
)
if not download_result.success:
return APIResponse.error(f"下载失败: {download_result.error_message}", 500)
file_path = Path(download_result.file_path)
api_service.logger.info(f"下载完成: {filename}")
except DownloadException as e:
api_service.logger.error(f"下载异常: {e}")
return APIResponse.error(f"下载失败: {str(e)}", 500)
# 根据返回格式返回结果
if return_format == 'json':
response_data = {
'music_id': music_id,
'name': music_info['name'],
'artist': music_info['artist_string'],
'album': music_info['album'],
'quality': quality,
'quality_name': api_service._get_quality_display_name(quality),