-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmusic_downloader.py
More file actions
357 lines (355 loc) · 14.9 KB
/
Copy pathmusic_downloader.py
File metadata and controls
357 lines (355 loc) · 14.9 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
import re
import asyncio
import aiohttp
import aiofiles
import requests
from enum import Enum
from io import BytesIO
from pathlib import Path
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple, Any, Union
from mutagen.flac import FLAC
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, TIT2, TPE1, TALB, TDRC, TRCK, APIC
from mutagen.mp4 import MP4
from music_api import NeteaseAPI, APIException
from cookie_manager import CookieManager
class AudioFormat(Enum):
MP3 = "mp3"
FLAC = "flac"
M4A = "m4a"
UNKNOWN = "unknown"
class QualityLevel(Enum):
STANDARD = "standard"
EXHIGH = "exhigh"
LOSSLESS = "lossless"
HIRES = "hires"
SKY = "sky"
JYEFFECT = "jyeffect"
JYMASTER = "jymaster"
DOLBY = "dolby"
@dataclass
class MusicInfo:
id: int
name: str
artists: str
album: str
pic_url: str
duration: int
track_number: int
download_url: str
file_type: str
file_size: int
quality: str
lyric: str = ""
tlyric: str = ""
@dataclass
class DownloadResult:
success: bool
file_path: Optional[str] = None
file_size: int = 0
error_message: str = ""
music_info: Optional[MusicInfo] = None
class DownloadException(Exception):
pass
class MusicDownloader:
def __init__(self, download_dir: str = "downloads", max_concurrent: int = 3):
self.download_dir = Path(download_dir)
self.download_dir.mkdir(exist_ok=True)
self.max_concurrent = max_concurrent
self.cookie_manager = CookieManager()
self.api = NeteaseAPI()
self.supported_formats = {
'mp3': AudioFormat.MP3,
'flac': AudioFormat.FLAC,
'm4a': AudioFormat.M4A
}
def _sanitize_filename(self, filename: str) -> str:
illegal_chars = r'[<>:"/\\|?*]'
filename = re.sub(illegal_chars, '_', filename)
filename = filename.strip(' .')
if len(filename) > 200:
filename = filename[:200]
return filename or "unknown"
def _determine_file_extension(self, url: str, content_type: str = "") -> str:
if '.flac' in url.lower():
return '.flac'
elif '.mp3' in url.lower():
return '.mp3'
elif '.m4a' in url.lower():
return '.m4a'
content_type = content_type.lower()
if 'flac' in content_type:
return '.flac'
elif 'mpeg' in content_type or 'mp3' in content_type:
return '.mp3'
elif 'mp4' in content_type or 'm4a' in content_type:
return '.m4a'
return '.mp3'
def get_music_info(self, music_id: int, quality: str = "standard") -> MusicInfo:
try:
cookies = self.cookie_manager.parse_cookies()
url_result = self.api.get_song_url(music_id, quality, cookies)
if not url_result.get('data') or not url_result['data']:
raise DownloadException(f"无法获取音乐ID {music_id} 的播放链接")
song_data = url_result['data'][0]
download_url = song_data.get('url', '')
if not download_url:
raise DownloadException(f"音乐ID {music_id} 无可用的下载链接")
detail_result = self.api.get_song_detail(music_id)
if not detail_result.get('songs') or not detail_result['songs']:
raise DownloadException(f"无法获取音乐ID {music_id} 的详细信息")
song_detail = detail_result['songs'][0]
lyric_result = self.api.get_lyric(music_id, cookies)
lyric = lyric_result.get('lrc', {}).get('lyric', '') if lyric_result else ''
tlyric = lyric_result.get('tlyric', {}).get('lyric', '') if lyric_result else ''
artists = '/'.join(artist['name'] for artist in song_detail.get('ar', []))
music_info = MusicInfo(
id=music_id,
name=song_detail.get('name', '未知歌曲'),
artists=artists or '未知艺术家',
album=song_detail.get('al', {}).get('name', '未知专辑'),
pic_url=song_detail.get('al', {}).get('picUrl', ''),
duration=song_detail.get('dt', 0) // 1000,
track_number=song_detail.get('no', 0),
download_url=download_url,
file_type=song_data.get('type', 'mp3').lower(),
file_size=song_data.get('size', 0),
quality=quality,
lyric=lyric,
tlyric=tlyric
)
return music_info
except APIException as e:
raise DownloadException(f"API调用失败: {e}")
except Exception as e:
raise DownloadException(f"获取音乐信息时发生错误: {e}")
def download_music_file(self, music_id: int, quality: str = "standard") -> DownloadResult:
try:
music_info = self.get_music_info(music_id, quality)
filename = f"{music_info.artists} - {music_info.name}"
safe_filename = self._sanitize_filename(filename)
file_ext = self._determine_file_extension(music_info.download_url)
file_path = self.download_dir / f"{safe_filename}{file_ext}"
if file_path.exists():
return DownloadResult(
success=True,
file_path=str(file_path),
file_size=file_path.stat().st_size,
music_info=music_info
)
response = requests.get(music_info.download_url, stream=True, timeout=30)
response.raise_for_status()
with open(file_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
self._write_music_tags(file_path, music_info)
return DownloadResult(
success=True,
file_path=str(file_path),
file_size=file_path.stat().st_size,
music_info=music_info
)
except DownloadException:
raise
except requests.RequestException as e:
return DownloadResult(
success=False,
error_message=f"下载请求失败: {e}"
)
except Exception as e:
return DownloadResult(
success=False,
error_message=f"下载过程中发生错误: {e}"
)
async def download_music_file_async(self, music_id: int, quality: str = "standard") -> DownloadResult:
try:
music_info = self.get_music_info(music_id, quality)
filename = f"{music_info.artists} - {music_info.name}"
safe_filename = self._sanitize_filename(filename)
file_ext = self._determine_file_extension(music_info.download_url)
file_path = self.download_dir / f"{safe_filename}{file_ext}"
if file_path.exists():
return DownloadResult(
success=True,
file_path=str(file_path),
file_size=file_path.stat().st_size,
music_info=music_info
)
async with aiohttp.ClientSession() as session:
async with session.get(music_info.download_url) as response:
response.raise_for_status()
async with aiofiles.open(file_path, 'wb') as f:
async for chunk in response.content.iter_chunked(8192):
await f.write(chunk)
self._write_music_tags(file_path, music_info)
return DownloadResult(
success=True,
file_path=str(file_path),
file_size=file_path.stat().st_size,
music_info=music_info
)
except DownloadException:
raise
except aiohttp.ClientError as e:
return DownloadResult(
success=False,
error_message=f"异步下载请求失败: {e}"
)
except Exception as e:
return DownloadResult(
success=False,
error_message=f"异步下载过程中发生错误: {e}"
)
def download_music_to_memory(self, music_id: int, quality: str = "standard") -> Tuple[bool, BytesIO, MusicInfo]:
try:
music_info = self.get_music_info(music_id, quality)
response = requests.get(music_info.download_url, timeout=30)
response.raise_for_status()
audio_data = BytesIO(response.content)
return True, audio_data, music_info
except DownloadException:
raise
except requests.RequestException as e:
raise DownloadException(f"下载到内存失败: {e}")
except Exception as e:
raise DownloadException(f"内存下载过程中发生错误: {e}")
async def download_batch_async(self, music_ids: List[int], quality: str = "standard") -> List[DownloadResult]:
semaphore = asyncio.Semaphore(self.max_concurrent)
async def download_with_semaphore(music_id: int) -> DownloadResult:
async with semaphore:
return await self.download_music_file_async(music_id, quality)
tasks = [download_with_semaphore(music_id) for music_id in music_ids]
results = await asyncio.gather(*tasks, return_exceptions=True)
processed_results = []
for i, result in enumerate(results):
if isinstance(result, Exception):
processed_results.append(DownloadResult(
success=False,
error_message=f"下载音乐ID {music_ids[i]} 时发生异常: {result}"
))
else:
processed_results.append(result)
return processed_results
def _write_music_tags(self, file_path: Path, music_info: MusicInfo) -> None:
try:
file_ext = file_path.suffix.lower()
if file_ext == '.mp3':
self._write_mp3_tags(file_path, music_info)
elif file_ext == '.flac':
self._write_flac_tags(file_path, music_info)
elif file_ext == '.m4a':
self._write_m4a_tags(file_path, music_info)
except Exception as e:
print(f"写入音乐标签失败: {e}")
def _write_mp3_tags(self, file_path: Path, music_info: MusicInfo) -> None:
try:
audio = MP3(str(file_path), ID3=ID3)
audio.tags.add(TIT2(encoding=3, text=music_info.name))
audio.tags.add(TPE1(encoding=3, text=music_info.artists))
audio.tags.add(TALB(encoding=3, text=music_info.album))
if music_info.track_number > 0:
audio.tags.add(TRCK(encoding=3, text=str(music_info.track_number)))
if music_info.pic_url:
try:
pic_response = requests.get(music_info.pic_url, timeout=10)
pic_response.raise_for_status()
audio.tags.add(APIC(
encoding=3,
mime='image/jpeg',
type=3,
desc='Cover',
data=pic_response.content
))
except:
pass
audio.save()
except Exception as e:
print(f"写入MP3标签失败: {e}")
def _write_flac_tags(self, file_path: Path, music_info: MusicInfo) -> None:
try:
audio = FLAC(str(file_path))
audio['TITLE'] = music_info.name
audio['ARTIST'] = music_info.artists
audio['ALBUM'] = music_info.album
if music_info.track_number > 0:
audio['TRACKNUMBER'] = str(music_info.track_number)
if music_info.pic_url:
try:
pic_response = requests.get(music_info.pic_url, timeout=10)
pic_response.raise_for_status()
from mutagen.flac import Picture
picture = Picture()
picture.type = 3
picture.mime = 'image/jpeg'
picture.desc = 'Cover'
picture.data = pic_response.content
audio.add_picture(picture)
except:
pass
audio.save()
except Exception as e:
print(f"写入FLAC标签失败: {e}")
def _write_m4a_tags(self, file_path: Path, music_info: MusicInfo) -> None:
try:
audio = MP4(str(file_path))
audio['\xa9nam'] = music_info.name
audio['\xa9ART'] = music_info.artists
audio['\xa9alb'] = music_info.album
if music_info.track_number > 0:
audio['trkn'] = [(music_info.track_number, 0)]
if music_info.pic_url:
try:
pic_response = requests.get(music_info.pic_url, timeout=10)
pic_response.raise_for_status()
audio['covr'] = [pic_response.content]
except:
pass
audio.save()
except Exception as e:
print(f"写入M4A标签失败: {e}")
def get_download_progress(self, music_id: int, quality: str = "standard") -> Dict[str, Any]:
try:
music_info = self.get_music_info(music_id, quality)
filename = f"{music_info.artists} - {music_info.name}"
safe_filename = self._sanitize_filename(filename)
file_ext = self._determine_file_extension(music_info.download_url)
file_path = self.download_dir / f"{safe_filename}{file_ext}"
if file_path.exists():
current_size = file_path.stat().st_size
progress = (current_size / music_info.file_size * 100) if music_info.file_size > 0 else 0
return {
'music_id': music_id,
'filename': safe_filename + file_ext,
'total_size': music_info.file_size,
'current_size': current_size,
'progress': min(progress, 100),
'completed': current_size >= music_info.file_size
}
else:
return {
'music_id': music_id,
'filename': safe_filename + file_ext,
'total_size': music_info.file_size,
'current_size': 0,
'progress': 0,
'completed': False
}
except Exception as e:
return {
'music_id': music_id,
'error': str(e),
'progress': 0,
'completed': False
}
if __name__ == "__main__":
downloader = MusicDownloader()
print("音乐下载器模块")
print("支持的功能:")
print("- 同步下载")
print("- 异步下载")
print("- 批量下载")
print("- 内存下载")
print("- 音乐标签写入")
print("- 下载进度跟踪")