Download mv_api_native.py from Zhepher/Netease: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/spaces/Zhepher/Netease/resolve/main/mv_api_native.py
- Command line
-
hf download hf://spaces/Zhepher/Netease/mv_api_native.py
-
curl -L -o mv_api_native.py https://huggingface.co/spaces/Zhepher/Netease/resolve/main/mv_api_native.py
12.4 kB
| """基于现有架构的网易云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 | |
| 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 | |
| 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)") |