File size: 12,353 Bytes
3b08e6e | 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 | """基于现有架构的网易云MV解析API模块
使用与music_api.py相同的技术架构直接调用官方API
无需依赖外部服务,完全自包含的MV解析实现
"""
import json
import urllib.parse
import time
from random import randrange
from typing import Dict, List, Optional, Any
from dataclasses import dataclass
from enum import Enum
import requests
# 复用现有的加密工具和常量
from music_api import APIConstants, CryptoUtils, HTTPClient, APIException
class MVQuality(Enum):
"""MV画质等级枚举"""
SD_240P = "240" # 标清 240P
SD_480P = "480" # 标清 480P
HD_720P = "720" # 高清 720P
FHD_1080P = "1080" # 全高清 1080P
@dataclass
class MVInfo:
"""MV信息数据类"""
id: int
name: str
artist: str
artist_id: int
duration: int
publish_time: str
play_count: int
like_count: int
share_count: int
comment_count: int
cover_url: str
description: str = ""
tags: List[str] = None
@dataclass
class MVUrlInfo:
"""MV播放链接信息"""
id: int
quality: str
url: str
size: int
bitrate: int
class MVAPIConstants:
"""MV API相关常量 - 基于网易云官方接口"""
# MV相关API端点 - 使用与音乐API相同的domain
MV_DETAIL_API = "https://interface3.music.163.com/eapi/v1/mv/detail"
MV_URL_API = "https://interface3.music.163.com/eapi/song/enhance/play/mv/url"
MV_SEARCH_API = "https://music.163.com/api/cloudsearch/pc" # 与音乐搜索相同的端点
MV_COMMENT_API = "https://music.163.com/api/v1/resource/comments/R_MV_5_{}"
# MV相关常量
SEARCH_TYPE_MV = 1004 # MV搜索类型
# 画质映射
QUALITY_MAP = {
"240": "240P",
"480": "480P",
"720": "720P",
"1080": "1080P"
}
class NeteaseNativeMVAPI:
"""基于原生架构的网易云MV API类"""
def __init__(self):
self.http_client = HTTPClient()
self.crypto_utils = CryptoUtils()
def get_mv_detail(self, mv_id: int, cookies: Dict[str, str] = None) -> MVInfo:
"""
获取MV详细信息
Args:
mv_id: MV ID
cookies: 用户cookies
Returns:
MV详细信息对象
Raises:
APIException: API调用失败时抛出
"""
try:
# 使用eapi加密方式
config = APIConstants.DEFAULT_CONFIG.copy()
config["requestId"] = str(randrange(20000000, 30000000))
payload = {
'id': mv_id,
'header': json.dumps(config)
}
params = self.crypto_utils.encrypt_params(MVAPIConstants.MV_DETAIL_API, payload)
response_text = self.http_client.post_request(
MVAPIConstants.MV_DETAIL_API,
params,
cookies or {}
)
result = json.loads(response_text)
if result.get('code') != 200:
raise APIException(f"获取MV详情失败: {result.get('message', '未知错误')}")
data = result.get('data', {})
return MVInfo(
id=data.get('id', mv_id),
name=data.get('name', ''),
artist=data.get('artistName', ''),
artist_id=data.get('artistId', 0),
duration=data.get('duration', 0),
publish_time=data.get('publishTime', ''),
play_count=data.get('playCount', 0),
like_count=data.get('likeCount', 0),
share_count=data.get('shareCount', 0),
comment_count=data.get('commentCount', 0),
cover_url=data.get('cover', ''),
description=data.get('desc', ''),
tags=data.get('videoGroup', []) if data.get('videoGroup') else []
)
except (json.JSONDecodeError, KeyError) as e:
raise APIException(f"解析MV详情响应失败: {e}")
def get_mv_url(self, mv_id: int, quality: str = "720", cookies: Dict[str, str] = None) -> List[MVUrlInfo]:
"""
获取MV播放链接
Args:
mv_id: MV ID
quality: 画质等级 (240, 480, 720, 1080)
cookies: 用户cookies
Returns:
MV播放链接信息列表
Raises:
APIException: API调用失败时抛出
"""
try:
config = APIConstants.DEFAULT_CONFIG.copy()
config["requestId"] = str(randrange(20000000, 30000000))
payload = {
'id': mv_id,
'r': quality,
'header': json.dumps(config)
}
params = self.crypto_utils.encrypt_params(MVAPIConstants.MV_URL_API, payload)
response_text = self.http_client.post_request(
MVAPIConstants.MV_URL_API,
params,
cookies or {}
)
result = json.loads(response_text)
if result.get('code') != 200:
raise APIException(f"获取MV播放链接失败: {result.get('message', '未知错误')}")
data = result.get('data', {})
if not data or not data.get('url'):
raise APIException("未找到可用的MV播放链接")
# API返回单个视频链接,不是按画质分组
# 实际画质可能与请求的不同
actual_quality = str(data.get('r', quality)) # 实际返回的画质
url_info = MVUrlInfo(
id=mv_id,
quality=actual_quality,
url=data['url'],
size=data.get('size', 0),
bitrate=data.get('r', 0)
)
return [url_info] # 返回列表以保持接口一致性
except (json.JSONDecodeError, KeyError) as e:
raise APIException(f"解析MV播放链接响应失败: {e}")
def search_mv(self, keywords: str, cookies: Dict[str, str] = None, limit: int = 30, offset: int = 0) -> List[Dict[str, Any]]:
"""
搜索MV - 使用与音乐搜索相同的端点
Args:
keywords: 搜索关键词
cookies: 用户cookies
limit: 返回数量限制
offset: 偏移量
Returns:
MV搜索结果列表
Raises:
APIException: API调用失败时抛出
"""
try:
data = {
's': keywords,
'type': MVAPIConstants.SEARCH_TYPE_MV, # 1014 = MV搜索类型
'limit': limit,
'offset': offset
}
headers = {
'User-Agent': APIConstants.USER_AGENT,
'Referer': APIConstants.REFERER
}
response = requests.post(
MVAPIConstants.MV_SEARCH_API,
data=data,
headers=headers,
cookies=cookies or {},
timeout=30
)
response.raise_for_status()
result = response.json()
if result.get('code') != 200:
raise APIException(f"MV搜索失败: {result.get('message', '未知错误')}")
mvs = []
for item in result.get('result', {}).get('mvs', []):
mv_info = {
'id': item['id'],
'name': item['name'],
'artistName': item['artistName'],
'artistId': item.get('artistId', 0),
'duration': item.get('duration', 0),
'playCount': item.get('playCount', 0),
'cover': item.get('cover', ''),
'desc': item.get('briefDesc', '')
}
mvs.append(mv_info)
return mvs
except requests.RequestException as e:
raise APIException(f"MV搜索请求失败: {e}")
except (json.JSONDecodeError, KeyError) as e:
raise APIException(f"解析MV搜索响应失败: {e}")
def get_mv_comments(self, mv_id: int, limit: int = 20, offset: int = 0,
cookies: Dict[str, str] = None) -> Dict[str, Any]:
"""
获取MV评论 - 使用简单的GET请求
Args:
mv_id: MV ID
limit: 返回数量限制
offset: 偏移量
cookies: 用户cookies
Returns:
评论信息字典
"""
try:
comment_api = MVAPIConstants.MV_COMMENT_API.format(mv_id)
params = {
'limit': limit,
'offset': offset
}
headers = {
'User-Agent': APIConstants.USER_AGENT,
'Referer': APIConstants.REFERER
}
response = requests.get(
comment_api,
params=params,
headers=headers,
cookies=cookies or {},
timeout=30
)
response.raise_for_status()
result = response.json()
if result.get('code') != 200:
return {'comments': [], 'total': 0}
return {
'comments': result.get('comments', []),
'hotComments': result.get('hotComments', []),
'total': result.get('total', 0),
'more': result.get('more', False)
}
except Exception as e:
return {'comments': [], 'total': 0, 'error': str(e)}
def get_mv_by_artist(self, artist_id: int, limit: int = 30, offset: int = 0,
cookies: Dict[str, str] = None) -> List[Dict[str, Any]]:
"""
获取艺术家的MV列表
Args:
artist_id: 艺术家ID
limit: 返回数量限制
offset: 偏移量
cookies: 用户cookies
Returns:
MV列表
"""
try:
# 使用搜索API,限定艺术家
data = {
's': '', # 空搜索词
'type': MVAPIConstants.SEARCH_TYPE_MV,
'limit': limit,
'offset': offset
}
headers = {
'User-Agent': APIConstants.USER_AGENT,
'Referer': APIConstants.REFERER
}
# 这里可以根据实际API调整实现
# 作为示例,返回空列表
return []
except Exception as e:
raise APIException(f"获取艺术家MV失败: {e}")
# 向后兼容的函数接口
def get_mv_detail_native(mv_id: int, cookies: Dict[str, str] = None) -> MVInfo:
"""获取MV详情(原生实现)"""
api = NeteaseNativeMVAPI()
return api.get_mv_detail(mv_id, cookies)
def get_mv_url_native(mv_id: int, quality: str = "720", cookies: Dict[str, str] = None) -> List[MVUrlInfo]:
"""获取MV播放链接(原生实现)"""
api = NeteaseNativeMVAPI()
return api.get_mv_url(mv_id, quality, cookies)
def search_mv_native(keywords: str, limit: int = 30, cookies: Dict[str, str] = None) -> List[Dict[str, Any]]:
"""搜索MV(原生实现)"""
api = NeteaseNativeMVAPI()
return api.search_mv(keywords, cookies, limit)
if __name__ == "__main__":
# 测试代码
print("基于原生架构的网易云MV API模块")
print("技术特点:")
print("- 直接调用官方API,无需外部服务依赖")
print("- 使用与音乐API相同的加密机制")
print("- 完全自包含的实现")
print("- 支持MV搜索、详情获取、播放链接解析")
print()
print("支持的功能:")
print("- MV详情获取")
print("- MV播放链接获取")
print("- MV搜索")
print("- MV评论获取")
print("- 多画质支持 (240P/480P/720P/1080P)") |