|
1 | 1 | import { existsSync, createWriteStream } from "fs"; |
2 | | -import { unlink } from "fs/promises"; |
| 2 | +import { unlink, rename } from "fs/promises"; |
3 | 3 | import { pipeline } from "stream/promises"; |
4 | 4 | import { CacheService } from "./CacheService"; |
5 | 5 | import { useStore } from "../store"; |
@@ -52,9 +52,11 @@ export class MusicCacheService { |
52 | 52 | // 模糊查找 (API请求失败时,只要有缓存就用) |
53 | 53 | try { |
54 | 54 | const items = await this.cacheService.list("music"); |
55 | | - // 查找以 id_ 开头的文件 |
| 55 | + // 查找以 id_ 开头且以 .sc 结尾的文件(排除 .tmp 文件) |
56 | 56 | 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 | + ); |
58 | 60 | if (match) { |
59 | 61 | return this.cacheService.getFilePath("music", match.key); |
60 | 62 | } |
@@ -91,25 +93,29 @@ export class MusicCacheService { |
91 | 93 |
|
92 | 94 | const key = this.getCacheKey(id, quality); |
93 | 95 | const filePath = this.cacheService.getFilePath("music", key); |
| 96 | + const tempPath = `${filePath}.tmp`; |
94 | 97 |
|
95 | 98 | // 确保目录存在 |
96 | 99 | await this.cacheService.init(); |
97 | 100 |
|
98 | 101 | // 下载并写入 |
99 | 102 | try { |
100 | 103 | const downloadStream = got.stream(url); |
101 | | - const fileStream = createWriteStream(filePath); |
| 104 | + const fileStream = createWriteStream(tempPath); |
102 | 105 |
|
103 | 106 | await pipeline(downloadStream, fileStream); |
104 | 107 |
|
| 108 | + // 下载成功后,将临时文件重命名为正式缓存文件 |
| 109 | + await rename(tempPath, filePath); |
| 110 | + |
105 | 111 | // 更新 CacheService 的大小记录 |
106 | 112 | await this.cacheService.notifyFileChange("music", key); |
107 | 113 |
|
108 | 114 | return filePath; |
109 | 115 | } catch (error) { |
110 | | - // 下载失败,清理残余 |
111 | | - if (existsSync(filePath)) { |
112 | | - await unlink(filePath); |
| 116 | + // 下载失败,清理残余的临时文件 |
| 117 | + if (existsSync(tempPath)) { |
| 118 | + await unlink(tempPath).catch(() => {}); |
113 | 119 | } |
114 | 120 | cacheLog.error("Music download failed:", error); |
115 | 121 | throw error; |
|
0 commit comments