11import { existsSync , createWriteStream } from "fs" ;
2- import { unlink } from "fs/promises" ;
2+ import { unlink , rename } from "fs/promises" ;
33import { pipeline } from "stream/promises" ;
44import { CacheService } from "./CacheService" ;
55import { useStore } from "../store" ;
@@ -52,9 +52,11 @@ export class MusicCacheService {
5252 // 模糊查找 (API请求失败时,只要有缓存就用)
5353 try {
5454 const items = await this . cacheService . list ( "music" ) ;
55- // 查找以 id_ 开头的文件
55+ // 查找以 id_ 开头且以 .sc 结尾的文件(排除 .tmp 文件)
5656 const prefix = `${ id } _` ;
57- const match = items . find ( ( item ) => item . key . startsWith ( prefix ) ) ;
57+ const match = items . find (
58+ ( item ) => item . key . startsWith ( prefix ) && item . key . endsWith ( ".sc" ) ,
59+ ) ;
5860 if ( match ) {
5961 return this . cacheService . getFilePath ( "music" , match . key ) ;
6062 }
@@ -73,7 +75,7 @@ export class MusicCacheService {
7375 */
7476 public async cacheMusic ( id : number | string , url : string , quality : string ) : Promise < string > {
7577 const store = useStore ( ) ;
76- const limitSizeGB = store . get ( "cacheLimit" ) || 10 ;
78+ const limitSizeGB = store . get ( "cacheLimit" ) ?? 10 ;
7779 const limitSizeBytes = limitSizeGB * 1024 * 1024 * 1024 ;
7880
7981 // 如果设置为 0,则不限制
@@ -91,25 +93,29 @@ export class MusicCacheService {
9193
9294 const key = this . getCacheKey ( id , quality ) ;
9395 const filePath = this . cacheService . getFilePath ( "music" , key ) ;
96+ const tempPath = `${ filePath } .tmp` ;
9497
9598 // 确保目录存在
9699 await this . cacheService . init ( ) ;
97100
98101 // 下载并写入
99102 try {
100103 const downloadStream = got . stream ( url ) ;
101- const fileStream = createWriteStream ( filePath ) ;
104+ const fileStream = createWriteStream ( tempPath ) ;
102105
103106 await pipeline ( downloadStream , fileStream ) ;
104107
108+ // 下载成功后,将临时文件重命名为正式缓存文件
109+ await rename ( tempPath , filePath ) ;
110+
105111 // 更新 CacheService 的大小记录
106112 await this . cacheService . notifyFileChange ( "music" , key ) ;
107113
108114 return filePath ;
109115 } catch ( error ) {
110- // 下载失败,清理残余
111- if ( existsSync ( filePath ) ) {
112- await unlink ( filePath ) ;
116+ // 下载失败,清理残余的临时文件
117+ if ( existsSync ( tempPath ) ) {
118+ await unlink ( tempPath ) . catch ( ( ) => { } ) ;
113119 }
114120 cacheLog . error ( "Music download failed:" , error ) ;
115121 throw error ;
0 commit comments