Skip to content

Commit 439fa0f

Browse files
committed
🐞 fix: 修复一些小问题 & 模式切换提示
1 parent 5417f1a commit 439fa0f

8 files changed

Lines changed: 170 additions & 44 deletions

File tree

electron/main/ipc/ipc-file.ts

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,19 @@ const initFileIpc = (): void => {
222222
// 修改音乐元信息
223223
ipcMain.handle("set-music-metadata", async (_, path: string, metadata: any) => {
224224
try {
225-
const { name, artist, album, alia, lyric, cover } = metadata;
225+
const {
226+
name,
227+
artist,
228+
album,
229+
alia,
230+
lyric,
231+
cover,
232+
albumArtist,
233+
genre,
234+
year,
235+
trackNumber,
236+
discNumber,
237+
} = metadata;
226238
// 规范化路径
227239
const songPath = resolve(path);
228240
const coverPath = cover ? resolve(cover) : undefined;
@@ -233,6 +245,11 @@ const initFileIpc = (): void => {
233245
album: album || "未知专辑",
234246
lyric: lyric || "",
235247
description: alia || "",
248+
albumArtist: albumArtist,
249+
genre: genre,
250+
year: year,
251+
trackNumber: trackNumber,
252+
discNumber: discNumber,
236253
};
237254

238255
if (!tools) {
@@ -542,7 +559,7 @@ const initFileIpc = (): void => {
542559
await mkdir(downloadPath, { recursive: true });
543560
}
544561

545-
const finalFilePath = fileType
562+
const finalFilePath = fileType
546563
? join(downloadPath, `${fileName}.${fileType}`)
547564
: join(downloadPath, fileName);
548565

@@ -606,20 +623,21 @@ const initFileIpc = (): void => {
606623

607624
// Handle both object (new) and JSON string (legacy/fallback)
608625
if (typeof progressData === "string") {
609-
try {
610-
progressData = JSON.parse(progressData);
611-
} catch (e) {
612-
console.error("Failed to parse progress json", e);
613-
return;
614-
}
626+
try {
627+
progressData = JSON.parse(progressData);
628+
} catch (e) {
629+
console.error("Failed to parse progress json", e);
630+
return;
631+
}
615632
}
616633

617-
if (!progressData || typeof progressData !== 'object') return;
634+
if (!progressData || typeof progressData !== "object") return;
618635

619636
// Map snake_case (Rust) to camelCase (JS)
620637
// Rust struct: { percent, transferred_bytes, total_bytes }
621638
const percent = progressData.percent;
622-
const transferredBytes = progressData.transferredBytes ?? progressData.transferred_bytes ?? 0;
639+
const transferredBytes =
640+
progressData.transferredBytes ?? progressData.transferred_bytes ?? 0;
623641
const totalBytes = progressData.totalBytes ?? progressData.total_bytes ?? 0;
624642

625643
win.webContents.send("download-progress", {
@@ -629,12 +647,7 @@ const initFileIpc = (): void => {
629647
totalBytes: totalBytes,
630648
});
631649
} catch (e) {
632-
console.error(
633-
"Error processing progress callback",
634-
e,
635-
"Args:",
636-
args,
637-
);
650+
console.error("Error processing progress callback", e, "Args:", args);
638651
}
639652
};
640653

electron/main/ipc/ipc-window.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,14 @@ const initWindowsIpc = (): void => {
121121
win.focus();
122122
});
123123

124+
// 显示主窗口
125+
ipcMain.on("win-show-main", () => {
126+
const mainWin = mainWindow.getWin();
127+
if (!mainWin) return;
128+
mainWin.show();
129+
mainWin.focus();
130+
});
131+
124132
// 重载
125133
ipcMain.on("win-reload", (event) => {
126134
const win = BrowserWindow.fromWebContents(event.sender);
@@ -137,7 +145,7 @@ const initWindowsIpc = (): void => {
137145
// 向主窗口发送事件
138146
ipcMain.on("send-to-main-win", (_, eventName, ...args) => {
139147
const mainWin = mainWindow.getWin();
140-
if (!mainWin || mainWin.isDestroyed() || mainWin.webContents.isDestroyed()) return;
148+
if (!mainWin) return;
141149
mainWin.webContents.send(eventName, ...args);
142150
});
143151

@@ -149,7 +157,6 @@ const initWindowsIpc = (): void => {
149157
const updateProgressBar = () => {
150158
const mainWin = mainWindow.getWin();
151159
if (!mainWin) return;
152-
153160
if (currentProgress < 0) {
154161
mainWin.setProgressBar(-1);
155162
} else {

electron/main/windows/taskbar-lyric-window.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,10 @@ class TaskbarLyricWindow {
103103
maximizable: false,
104104
fullscreenable: false,
105105
resizable: false,
106+
webPreferences: {
107+
zoomFactor: 1.0,
108+
partition: "persist:taskbar-lyric",
109+
},
106110
});
107111

108112
if (!this.win) return null;

native/tools/index.d.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/* auto-generated by NAPI-RS */
2-
2+
/* eslint-disable */
33
export declare class DownloadTask {
44
constructor()
55
cancel(): void
@@ -48,6 +48,11 @@ export interface SongMetadata {
4848
coverUrl?: string
4949
lyric?: string
5050
description?: string
51+
albumArtist?: string
52+
genre?: string
53+
year?: number
54+
trackNumber?: number
55+
discNumber?: number
5156
}
5257

5358
export declare function writeMusicMetadata(filePath: string, metadata: SongMetadata, coverPath?: string | undefined | null): Promise<void>

native/tools/src/download.rs

Lines changed: 62 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ where
3838
where
3939
C: std::fmt::Display,
4040
{
41-
self.map_err(|e| Error::from_reason(format!("{}: {}", context, e)))
41+
self.map_err(|e| Error::from_reason(format!("{context}: {e}")))
4242
}
4343
}
4444

@@ -127,9 +127,19 @@ pub struct SongMetadata {
127127
pub cover_url: Option<String>,
128128
pub lyric: Option<String>,
129129
pub description: Option<String>,
130+
pub album_artist: Option<String>,
131+
pub genre: Option<String>,
132+
pub year: Option<u32>,
133+
pub track_number: Option<u32>,
134+
pub disc_number: Option<u32>,
130135
}
131136

132137
#[napi]
138+
#[allow(
139+
clippy::trailing_empty_array,
140+
clippy::missing_errors_doc,
141+
clippy::option_if_let_else
142+
)]
133143
pub async fn write_music_metadata(
134144
file_path: String,
135145
metadata: SongMetadata,
@@ -164,13 +174,23 @@ impl DownloadTask {
164174
token: CancellationToken::new(),
165175
}
166176
}
177+
}
167178

179+
impl Default for DownloadTask {
180+
fn default() -> Self {
181+
Self::new()
182+
}
183+
}
184+
185+
#[napi]
186+
impl DownloadTask {
168187
#[napi]
169188
pub fn cancel(&self) {
170189
self.token.cancel();
171190
}
172191

173192
#[napi]
193+
#[allow(clippy::too_many_arguments, clippy::missing_errors_doc)]
174194
pub async fn download(
175195
&self,
176196
url: String,
@@ -191,13 +211,10 @@ impl DownloadTask {
191211
let (total_size, http_version) =
192212
detect_content_length(&client, &url, referer.as_deref()).await;
193213

194-
println!(
195-
"[Download] URL: {}, Version: {:?}, Size: {}",
196-
url, http_version, total_size
197-
);
214+
println!("[Download] URL: {url}, Version: {http_version:?}, Size: {total_size}");
198215

199216
if total_size > 0 {
200-
println!("[Download] Threads: {}", thread_count);
217+
println!("[Download] Threads: {thread_count}");
201218
download_range_stream(
202219
self.token.clone(),
203220
client.clone(),
@@ -241,9 +258,7 @@ fn build_client(enable_http2: bool) -> Result<reqwest::Client> {
241258
builder = builder.http1_only();
242259
}
243260

244-
builder
245-
.build()
246-
.context("Failed to build HTTP client")
261+
builder.build().context("Failed to build HTTP client")
247262
}
248263

249264
async fn detect_content_length(
@@ -321,7 +336,7 @@ async fn download_simple_stream(
321336

322337
let process_result = async {
323338
while let Some(item) = tokio::select! {
324-
_ = token.cancelled() => None,
339+
() = token.cancelled() => None,
325340
item = stream.next() => item,
326341
} {
327342
let chunk = item.context("Read error")?;
@@ -330,7 +345,10 @@ async fn download_simple_stream(
330345
}
331346

332347
if token.is_cancelled() {
333-
return Err(Error::new(Status::Cancelled, "Download cancelled".to_string()));
348+
return Err(Error::new(
349+
Status::Cancelled,
350+
"Download cancelled".to_string(),
351+
));
334352
}
335353

336354
file.flush().await.context("Flush failed")?;
@@ -348,6 +366,7 @@ async fn download_simple_stream(
348366
Ok(())
349367
}
350368

369+
#[allow(clippy::too_many_arguments)]
351370
async fn download_range_stream(
352371
token: CancellationToken,
353372
client: reqwest::Client,
@@ -390,7 +409,10 @@ async fn download_range_stream(
390409
while let Some(result) = stream.next().await {
391410
let (offset, data) = result?;
392411
if token.is_cancelled() {
393-
return Err(Error::new(Status::Cancelled, "Download cancelled".to_string()));
412+
return Err(Error::new(
413+
Status::Cancelled,
414+
"Download cancelled".to_string(),
415+
));
394416
}
395417

396418
file.seek(SeekFrom::Start(offset))
@@ -407,7 +429,7 @@ async fn download_range_stream(
407429
if let Err(e) = process_result {
408430
drop(file);
409431
let _ = tokio::fs::remove_file(&file_path).await;
410-
return Err(Error::from_reason(format!("Range download failed: {}", e)));
432+
return Err(Error::from_reason(format!("Range download failed: {e}")));
411433
}
412434

413435
tracker.finish();
@@ -427,10 +449,13 @@ async fn download_chunk_with_retry(
427449

428450
while attempts < MAX_RETRIES {
429451
if token.is_cancelled() {
430-
return Err(Error::new(Status::Cancelled, "Download cancelled".to_string()));
452+
return Err(Error::new(
453+
Status::Cancelled,
454+
"Download cancelled".to_string(),
455+
));
431456
}
432457

433-
let range_header = format!("bytes={}-{}", start, end);
458+
let range_header = format!("bytes={start}-{end}");
434459
let mut req = client.get(&url).header("Range", &range_header);
435460
if let Some(ref r) = referer {
436461
req = req.header("Referer", r);
@@ -448,7 +473,7 @@ async fn download_chunk_with_retry(
448473
match resp.bytes().await {
449474
Ok(bytes) => return Ok((start, bytes)),
450475
Err(e) => {
451-
last_error = format!("Read bytes failed: {}", e);
476+
last_error = format!("Read bytes failed: {e}");
452477
}
453478
}
454479
}
@@ -461,8 +486,7 @@ async fn download_chunk_with_retry(
461486
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
462487
}
463488
Err(Error::from_reason(format!(
464-
"Chunk {}-{} failed after {} retries. Last error: {}",
465-
start, end, MAX_RETRIES, last_error
489+
"Chunk {start}-{end} failed after {MAX_RETRIES} retries. Last error: {last_error}"
466490
)))
467491
}
468492

@@ -532,6 +556,26 @@ fn write_metadata(path: &str, meta: SongMetadata, cover_data: Option<bytes::Byte
532556
tag.set_artist(meta.artist);
533557
tag.set_album(meta.album);
534558

559+
if let Some(album_artist) = meta.album_artist {
560+
tag.insert_text(ItemKey::AlbumArtist, album_artist);
561+
}
562+
563+
if let Some(genre) = meta.genre {
564+
tag.set_genre(genre);
565+
}
566+
567+
if let Some(year) = meta.year {
568+
tag.set_year(year);
569+
}
570+
571+
if let Some(track) = meta.track_number {
572+
tag.set_track(track);
573+
}
574+
575+
if let Some(disc) = meta.disc_number {
576+
tag.set_disk(disc);
577+
}
578+
535579
if let Some(desc) = meta.description {
536580
tag.set_comment(desc);
537581
}

0 commit comments

Comments
 (0)