mioku-plugin-music 3.0.3 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,67 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import * as fs from "node:fs/promises";
3
+ import * as path from "node:path";
4
+
5
+ const SEND_DIR = path.join(process.cwd(), "temp", "music", "send");
6
+ const MAX_BASE_LENGTH = 80;
7
+ const FALLBACK_BASE = "song";
8
+
9
+ function sanitizeBaseName(value: string): string {
10
+ return value
11
+ .replace(/[\\/:*?"<>|\u0000-\u001f]/g, "_")
12
+ .replace(/\s+/g, " ")
13
+ .slice(0, MAX_BASE_LENGTH)
14
+ .replace(/^[.\s]+|[.\s]+$/g, "")
15
+ .trim();
16
+ }
17
+
18
+ /** 由歌名与歌手生成发送用文件名(不含扩展名) */
19
+ export function buildTrackBaseName(
20
+ track: { title?: string; artist?: string },
21
+ fallback: string = FALLBACK_BASE,
22
+ ): string {
23
+ const label = [track.title, track.artist]
24
+ .map((part) => String(part ?? "").trim())
25
+ .filter((part) => part.length > 0)
26
+ .join(" - ");
27
+ return sanitizeBaseName(label) || sanitizeBaseName(fallback) || FALLBACK_BASE;
28
+ }
29
+
30
+ export interface PreparedAudioFile {
31
+ readonly filePath: string;
32
+ readonly fileName: string;
33
+ cleanup(): Promise<void>;
34
+ }
35
+
36
+ /** 按歌名生成发送副本,避免把缓存文件名(如 netease-<id>.mp3)直接发出去 */
37
+ export async function prepareTrackFile(options: {
38
+ sourcePath: string;
39
+ title?: string;
40
+ artist?: string;
41
+ fallbackName?: string;
42
+ }): Promise<PreparedAudioFile> {
43
+ const ext = path.extname(options.sourcePath);
44
+ const fileName = `${buildTrackBaseName(options, options.fallbackName)}${ext}`;
45
+ const dir = path.join(SEND_DIR, randomUUID());
46
+ const filePath = path.join(dir, fileName);
47
+
48
+ await fs.mkdir(dir, { recursive: true });
49
+ try {
50
+ await fs.link(options.sourcePath, filePath);
51
+ } catch {
52
+ try {
53
+ await fs.copyFile(options.sourcePath, filePath);
54
+ } catch (error) {
55
+ await fs.rm(dir, { recursive: true, force: true }).catch(() => {});
56
+ throw error;
57
+ }
58
+ }
59
+
60
+ return {
61
+ filePath,
62
+ fileName,
63
+ async cleanup(): Promise<void> {
64
+ await fs.rm(dir, { recursive: true, force: true }).catch(() => {});
65
+ },
66
+ };
67
+ }
@@ -0,0 +1,54 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import * as path from "node:path";
4
+ import type { Logger } from "mioku";
5
+ import type { MusicBaseConfig } from "../types";
6
+
7
+ const SERVICE_PACKAGE_PREFIX = "mioku-service-";
8
+ const attempted = new Set<string>();
9
+
10
+ function desiredServiceShortNames(config: MusicBaseConfig): string[] {
11
+ const names: string[] = [];
12
+ for (const value of [config.defaultProvider, config.dumpProvider]) {
13
+ const short = String(value ?? "").trim().toLowerCase();
14
+ if (short) names.push(short);
15
+ }
16
+ return [...new Set(names)];
17
+ }
18
+
19
+ function isPackageInstalled(pkgName: string): boolean {
20
+ return existsSync(path.join(process.cwd(), "node_modules", pkgName, "package.json"));
21
+ }
22
+
23
+ export function installMissingOptionalServices(
24
+ logger: Logger,
25
+ config: MusicBaseConfig,
26
+ ): void {
27
+ for (const short of desiredServiceShortNames(config)) {
28
+ const pkgName = `${SERVICE_PACKAGE_PREFIX}${short}`;
29
+ if (attempted.has(pkgName) || isPackageInstalled(pkgName)) continue;
30
+ attempted.add(pkgName);
31
+
32
+ logger.info(
33
+ `[music] ${short} 已在配置中启用但服务包未安装,正在后台执行 bun add ${pkgName},完成后重启生效`,
34
+ );
35
+ const child = spawn("bun", ["add", pkgName], {
36
+ cwd: process.cwd(),
37
+ detached: true,
38
+ shell: process.platform === "win32",
39
+ stdio: "ignore",
40
+ windowsHide: true,
41
+ });
42
+ child.on("error", (err: unknown) => {
43
+ logger.warn(`[music] 自动安装 ${pkgName} 失败: ${String(err)}`);
44
+ });
45
+ child.on("close", (code: number | null) => {
46
+ if (code === 0) {
47
+ logger.info(`[music] ${pkgName} 安装完成,重启后生效`);
48
+ } else {
49
+ logger.warn(`[music] 自动安装 ${pkgName} 失败(退出码 ${code ?? "unknown"})`);
50
+ }
51
+ });
52
+ child.unref();
53
+ }
54
+ }
@@ -0,0 +1,72 @@
1
+ import * as fs from "node:fs/promises";
2
+ import * as path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import type { Logger, MessageEvent, MiokuContext } from "mioku";
5
+ import type { DumpProvider } from "../dumps/types";
6
+ import type { IncomingFile } from "../dumps/file-source";
7
+ import { sendFileMessage } from "./message";
8
+
9
+ const DUMP_TEMP_ROOT = path.join(process.cwd(), "temp", "ncmdump");
10
+ const JOBS_DIR = path.join(DUMP_TEMP_ROOT, "jobs");
11
+
12
+ function sanitizeFileName(name: string): string {
13
+ const base = path.basename(name).replace(/[\u0000-\u001f]/g, "");
14
+ return base.length > 0 ? base : `file-${Date.now()}`;
15
+ }
16
+
17
+ function stripExtension(fileName: string): string {
18
+ const index = fileName.lastIndexOf(".");
19
+ return index > 0 ? fileName.slice(0, index) : fileName;
20
+ }
21
+
22
+ function shortError(error: unknown): string {
23
+ return String(error)
24
+ .replace(/^Error:\s*/, "")
25
+ .trim()
26
+ .slice(0, 160);
27
+ }
28
+
29
+ async function createJobDir(): Promise<string> {
30
+ const jobDir = path.join(JOBS_DIR, `${Date.now()}-${randomUUID().slice(0, 8)}`);
31
+ await fs.mkdir(jobDir, { recursive: true });
32
+ return jobDir;
33
+ }
34
+
35
+ export class DumpFlow {
36
+ private tail: Promise<void> = Promise.resolve();
37
+
38
+ constructor(private readonly deps: { logger: Logger }) {}
39
+
40
+ enqueue(ctx: MiokuContext, event: MessageEvent, provider: DumpProvider, file: IncomingFile): void {
41
+ this.tail = this.tail
42
+ .then(() => this.process(ctx, event, provider, file))
43
+ .catch((error: unknown) => {
44
+ this.deps.logger.warn(`[music] dump 任务异常: ${shortError(error)}`);
45
+ });
46
+ }
47
+
48
+ private async process(
49
+ ctx: MiokuContext,
50
+ event: MessageEvent,
51
+ provider: DumpProvider,
52
+ file: IncomingFile,
53
+ ): Promise<void> {
54
+ const { logger } = this.deps;
55
+ const jobDir = await createJobDir();
56
+ try {
57
+ const sourcePath = path.join(jobDir, sanitizeFileName(file.name));
58
+ await file.saveTo(sourcePath);
59
+ const result = await provider.dump({
60
+ sourcePath,
61
+ fileName: file.name,
62
+ outputDir: jobDir,
63
+ });
64
+ await sendFileMessage(ctx, event, result.filePath, stripExtension(result.fileName));
65
+ logger.info(`[music] dump 完成: ${file.name} -> ${result.fileName} (${provider.name})`);
66
+ } catch (error) {
67
+ logger.error(`[music] dump 失败 (${file.name}): ${shortError(error)}`);
68
+ } finally {
69
+ await fs.rm(jobDir, { recursive: true, force: true });
70
+ }
71
+ }
72
+ }
@@ -1,5 +1,6 @@
1
1
  import * as fs from "fs/promises";
2
2
  import * as path from "path";
3
+ import type { MessageEvent, MessageSegment, MiokuContext } from "mioku";
3
4
 
4
5
  function normalizeFileSource(file: string): string {
5
6
  const value = String(file || "").trim();
@@ -15,221 +16,183 @@ function normalizeFileSource(file: string): string {
15
16
  return value;
16
17
  }
17
18
  if (value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value)) {
18
- return `file://${value}`;
19
+ const normalized = value.replace(/\\/g, "/");
20
+ return `file:///${normalized.replace(/^\//, "")}`;
19
21
  }
20
22
  return value;
21
23
  }
22
24
 
23
- function getBotAndTarget(ctx: any, event: any): {
24
- bot: any;
25
+ function getBotAndTarget(event: MessageEvent): {
26
+ bot: MessageEvent["bot"];
25
27
  groupId?: string;
26
28
  userId?: string;
27
29
  } {
28
- const bot = event?.bot;
29
30
  const groupId = String(event?.group_id ?? "").trim();
30
31
  const userId = String(event?.user_id ?? "").trim();
31
32
 
32
33
  return {
33
- bot,
34
+ bot: event?.bot,
34
35
  groupId: event?.message_type === "group" ? groupId : undefined,
35
36
  userId: event?.message_type !== "group" ? userId : undefined,
36
37
  };
37
38
  }
38
39
 
39
- export async function sendTextMessage(
40
- ctx: any,
41
- event: any,
42
- text: string,
40
+ async function sendSegments(
41
+ ctx: MiokuContext,
42
+ event: MessageEvent,
43
+ segments: readonly MessageSegment[],
43
44
  ): Promise<void> {
44
- const { bot, groupId, userId } = getBotAndTarget(ctx, event);
45
- const payload: any[] = [];
46
-
47
- payload.push(ctx.segment.text(text));
48
-
45
+ const { bot, groupId, userId } = getBotAndTarget(event);
49
46
  if (bot && groupId != null && groupId !== "") {
50
- await bot.sendGroupMsg(groupId, payload);
47
+ await bot.sendGroupMsg(groupId, [...segments]);
51
48
  return;
52
49
  }
53
50
  if (bot && userId != null && userId !== "") {
54
- await bot.sendPrivateMsg(userId, payload);
51
+ await bot.sendPrivateMsg(userId, [...segments]);
55
52
  return;
56
53
  }
57
54
  if (typeof event?.reply === "function") {
58
- await event.reply(text);
55
+ await event.reply([...segments]);
59
56
  return;
60
57
  }
61
- throw new Error("当前上下文不支持文本发送");
58
+ throw new Error("当前上下文不支持消息发送");
59
+ }
60
+
61
+ export async function sendTextMessage(
62
+ ctx: MiokuContext,
63
+ event: MessageEvent,
64
+ text: string,
65
+ ): Promise<void> {
66
+ await sendSegments(ctx, event, [ctx.segment.text(text)]);
62
67
  }
63
68
 
64
69
  export async function sendImageMessage(
65
- ctx: any,
66
- event: any,
70
+ ctx: MiokuContext,
71
+ event: MessageEvent,
67
72
  imagePath: string,
68
73
  ): Promise<void> {
69
- const { bot, groupId, userId } = getBotAndTarget(ctx, event);
70
- const sendPayload = async (source: string) => {
71
- const payload: any[] = [];
72
- payload.push(ctx.segment.image(normalizeFileSource(source)));
73
-
74
- if (bot && groupId != null && groupId !== "") {
75
- await bot.sendGroupMsg(groupId, payload);
76
- return;
77
- }
78
- if (bot && userId != null && userId !== "") {
79
- await bot.sendPrivateMsg(userId, payload);
80
- return;
81
- }
82
- if (typeof event?.reply === "function") {
83
- await event.reply(payload);
84
- return;
85
- }
86
- throw new Error("当前上下文不支持图片发送");
74
+ const send = async (source: string): Promise<void> => {
75
+ await sendSegments(ctx, event, [
76
+ ctx.segment.image(normalizeFileSource(source)),
77
+ ]);
87
78
  };
88
79
 
89
80
  try {
90
- await sendPayload(imagePath);
81
+ await send(imagePath);
91
82
  } catch {
92
83
  const buffer = await fs.readFile(imagePath);
93
- const base64 = `base64://${buffer.toString("base64")}`;
94
- await sendPayload(base64);
84
+ await send(`base64://${buffer.toString("base64")}`);
95
85
  }
96
86
  }
97
87
 
88
+ function errorText(error: unknown): string {
89
+ const text = error instanceof Error ? error.message : String(error ?? "");
90
+ return text.trim().slice(0, 300) || "未知错误";
91
+ }
92
+
93
+ function isTimeoutError(error: unknown): boolean {
94
+ const text = errorText(error);
95
+ return (
96
+ text.includes("timeout") ||
97
+ text.includes("超时") ||
98
+ text.includes("timed out") ||
99
+ text.includes("ETIMEDOUT")
100
+ );
101
+ }
102
+
98
103
  export async function sendFileMessage(
99
- ctx: any,
100
- event: any,
104
+ ctx: MiokuContext,
105
+ event: MessageEvent,
101
106
  filePath: string,
102
107
  name: string,
103
108
  ): Promise<void> {
104
109
  const ext = path.extname(filePath);
105
- const fileName = ext ? `${name}${ext}` : name;
106
- const { bot, groupId, userId } = getBotAndTarget(ctx, event);
107
- const sendPayload = async (source: string) => {
108
- const payload: any[] = [];
109
- payload.push(ctx.segment.file(normalizeFileSource(source), { name: fileName }));
110
-
111
- if (bot && groupId != null && groupId !== "") {
112
- await bot.sendGroupMsg(groupId, payload);
113
- return;
114
- }
115
- if (bot && userId != null && userId !== "") {
116
- await bot.sendPrivateMsg(userId, payload);
117
- return;
118
- }
119
- if (typeof event?.reply === "function") {
120
- await event.reply(payload);
121
- return;
122
- }
123
- throw new Error("当前上下文不支持文件发送");
110
+ const fileName =
111
+ !ext || name.toLowerCase().endsWith(ext.toLowerCase())
112
+ ? name
113
+ : `${name}${ext}`;
114
+
115
+ const send = async (source: string): Promise<void> => {
116
+ await sendSegments(ctx, event, [
117
+ ctx.segment.file(normalizeFileSource(source), { name: fileName }),
118
+ ]);
124
119
  };
125
120
 
126
121
  const canReadLocalFile =
127
122
  filePath.startsWith("/") || /^[A-Za-z]:[\\/]/.test(filePath);
128
123
 
129
- let fileSendError: unknown;
124
+ let pathError: unknown;
130
125
  try {
131
- await sendPayload(filePath);
126
+ await send(filePath);
132
127
  return;
133
128
  } catch (error) {
134
- fileSendError = error;
129
+ pathError = error;
135
130
  }
136
131
 
137
132
  if (!canReadLocalFile) {
138
- throw fileSendError instanceof Error
139
- ? fileSendError
140
- : new Error(String(fileSendError || "文件发送失败"));
133
+ throw new Error(`文件发送失败:${errorText(pathError)}`);
141
134
  }
142
135
 
143
136
  let buffer: Buffer;
144
137
  try {
145
138
  buffer = await fs.readFile(filePath);
146
139
  } catch {
147
- throw fileSendError instanceof Error
148
- ? fileSendError
149
- : new Error(String(fileSendError || "文件发送失败"));
140
+ throw new Error(`文件发送失败:${errorText(pathError)}`);
150
141
  }
151
142
 
152
- const base64 = `base64://${buffer.toString("base64")}`;
153
143
  try {
154
- await sendPayload(base64);
144
+ await send(`base64://${buffer.toString("base64")}`);
155
145
  } catch (base64Error) {
156
- const message = String(base64Error || "");
157
- const timeoutLike =
158
- message.includes("timeout") ||
159
- message.includes("超时") ||
160
- message.includes("timed out") ||
161
- message.includes("ETIMEDOUT");
162
- if (timeoutLike) {
146
+ if (isTimeoutError(base64Error)) {
163
147
  return;
164
148
  }
165
- throw new Error("文件发送失败:路径发送失败,base64 发送也失败");
149
+ throw new Error(
150
+ `文件发送失败:路径发送失败(${errorText(pathError)});base64 发送失败(${errorText(base64Error)})`,
151
+ );
166
152
  }
167
153
  }
168
154
 
169
155
  export async function sendRecordMessage(
170
- ctx: any,
171
- event: any,
156
+ ctx: MiokuContext,
157
+ event: MessageEvent,
172
158
  audioPath: string,
173
159
  ): Promise<void> {
174
- const { bot, groupId, userId } = getBotAndTarget(ctx, event);
175
- const sendPayload = async (source: string) => {
176
- const payload: any[] = [];
177
- payload.push(ctx.segment.record(normalizeFileSource(source)));
178
-
179
- if (bot && groupId != null && groupId !== "") {
180
- await bot.sendGroupMsg(groupId, payload);
181
- return;
182
- }
183
- if (bot && userId != null && userId !== "") {
184
- await bot.sendPrivateMsg(userId, payload);
185
- return;
186
- }
187
- if (typeof event?.reply === "function") {
188
- await event.reply(payload);
189
- return;
190
- }
191
- throw new Error("当前上下文不支持语音发送");
160
+ const send = async (source: string): Promise<void> => {
161
+ await sendSegments(ctx, event, [
162
+ ctx.segment.record(normalizeFileSource(source)),
163
+ ]);
192
164
  };
193
165
 
194
166
  const canReadLocalFile =
195
167
  audioPath.startsWith("/") || /^[A-Za-z]:[\\/]/.test(audioPath);
196
168
 
197
- let fileSendError: unknown;
169
+ let pathError: unknown;
198
170
  try {
199
- await sendPayload(audioPath);
171
+ await send(audioPath);
200
172
  return;
201
173
  } catch (error) {
202
- fileSendError = error;
174
+ pathError = error;
203
175
  }
204
176
 
205
177
  if (!canReadLocalFile) {
206
- throw fileSendError instanceof Error
207
- ? fileSendError
208
- : new Error(String(fileSendError || "语音发送失败"));
178
+ throw new Error(`语音发送失败:${errorText(pathError)}`);
209
179
  }
210
180
 
211
181
  let buffer: Buffer;
212
182
  try {
213
183
  buffer = await fs.readFile(audioPath);
214
184
  } catch {
215
- throw fileSendError instanceof Error
216
- ? fileSendError
217
- : new Error(String(fileSendError || "语音发送失败"));
185
+ throw new Error(`语音发送失败:${errorText(pathError)}`);
218
186
  }
219
187
 
220
- const base64 = `base64://${buffer.toString("base64")}`;
221
188
  try {
222
- await sendPayload(base64);
189
+ await send(`base64://${buffer.toString("base64")}`);
223
190
  } catch (base64Error) {
224
- const message = String(base64Error || "");
225
- const timeoutLike =
226
- message.includes("timeout") ||
227
- message.includes("超时") ||
228
- message.includes("timed out") ||
229
- message.includes("ETIMEDOUT");
230
- if (timeoutLike) {
191
+ if (isTimeoutError(base64Error)) {
231
192
  return;
232
193
  }
233
- throw new Error("语音发送失败:路径发送失败,base64 发送也失败");
194
+ throw new Error(
195
+ `语音发送失败:路径发送失败(${errorText(pathError)});base64 发送失败(${errorText(base64Error)})`,
196
+ );
234
197
  }
235
198
  }
@@ -0,0 +1,14 @@
1
+ import type { ServiceRef } from "mioku";
2
+
3
+ export async function importOptionalService<T>(
4
+ moduleName: string,
5
+ exportName: string,
6
+ ): Promise<ServiceRef<T> | undefined> {
7
+ try {
8
+ const mod = (await import(moduleName)) as Record<string, unknown>;
9
+ const ref = mod[exportName];
10
+ return ref ? (ref as ServiceRef<T>) : undefined;
11
+ } catch {
12
+ return undefined;
13
+ }
14
+ }
@@ -2,7 +2,14 @@ import type { AIService } from "mioku";
2
2
  import type { ScreenshotService } from "mioku";
3
3
  import type { AppleMusicServiceApi } from "mioku-service-applemusic";
4
4
  import type { NeteaseServiceApi } from "mioku-service-netease";
5
+ import type { NcmdumpServiceApi } from "mioku-service-ncmdump";
5
6
  import { MUSIC_DEFAULTS } from "../config";
7
+ import {
8
+ createDumpProvider,
9
+ getDumpProviderCandidates,
10
+ resolveDumpProviderName,
11
+ } from "../dumps/factory";
12
+ import type { DumpProvider } from "../dumps/types";
6
13
  import {
7
14
  createMusicProvider,
8
15
  getMusicProviderCandidates,
@@ -11,6 +18,7 @@ import {
11
18
  import { renderMusicSearchListHtml } from "../render/search-list";
12
19
  import { MusicSessionStore } from "./session-store";
13
20
  import { notifyFallback } from "./fallback";
21
+ import { prepareTrackFile } from "./audio-file";
14
22
  import {
15
23
  sendImageMessage,
16
24
  sendRecordMessage,
@@ -19,6 +27,7 @@ import {
19
27
  } from "./message";
20
28
  import type {
21
29
  MusicBaseConfig,
30
+ MusicProvider,
22
31
  MusicProviderName,
23
32
  MusicSearchResult,
24
33
  MusicSessionState,
@@ -30,6 +39,13 @@ interface MusicPluginRuntimeDeps {
30
39
  screenshotService?: ScreenshotService;
31
40
  applemusicService?: AppleMusicServiceApi;
32
41
  neteaseService?: NeteaseServiceApi;
42
+ ncmdumpService?: NcmdumpServiceApi;
43
+ }
44
+
45
+ interface SendSongOptions {
46
+ title?: string;
47
+ artist?: string;
48
+ forceFile?: boolean;
33
49
  }
34
50
 
35
51
  export class MusicPluginRuntime {
@@ -59,6 +75,31 @@ export class MusicPluginRuntime {
59
75
  `music defaultProvider=${configured} 不可用,已回退到 ${resolved}`,
60
76
  );
61
77
  }
78
+ this.warnDumpProvider(nextConfig);
79
+ }
80
+
81
+ private warnDumpProvider(config: MusicBaseConfig): void {
82
+ const configured = String(config.dumpProvider || "").trim();
83
+ if (!configured) return;
84
+ if (resolveDumpProviderName(configured, this.getDumpServices())) return;
85
+ const candidates = getDumpProviderCandidates();
86
+ this.deps.logger.warn(
87
+ `music dumpProvider=${configured} 不可用,私聊文件解密未启用。候选列表=${candidates.join(", ")}`,
88
+ );
89
+ }
90
+
91
+ resolveDumpProvider(): DumpProvider | null {
92
+ const services = this.getDumpServices();
93
+ const configured = String(this.config.dumpProvider || "").trim();
94
+ const resolved = resolveDumpProviderName(configured, services);
95
+ if (!resolved) return null;
96
+ return createDumpProvider(resolved, services);
97
+ }
98
+
99
+ private getDumpServices() {
100
+ return {
101
+ ncmdump: this.deps.ncmdumpService,
102
+ };
62
103
  }
63
104
 
64
105
  setSessionMediaUserToken(event: any, token: string): void {
@@ -114,8 +155,7 @@ export class MusicPluginRuntime {
114
155
  ctx: any,
115
156
  event: any,
116
157
  songId: string,
117
- fileName?: string,
118
- options?: { forceFile?: boolean },
158
+ options?: SendSongOptions,
119
159
  ): Promise<void> {
120
160
  const session = this.getOrCreateSession(event);
121
161
  const provider = await this.createProvider(
@@ -137,11 +177,59 @@ export class MusicPluginRuntime {
137
177
  }
138
178
  const isPrivate = event?.message_type !== "group";
139
179
  const sendAsFile = isPrivate || options?.forceFile === true;
140
- if (sendAsFile) {
141
- const finalName = fileName || "song";
142
- await sendFileMessage(ctx, event, result.filePath, finalName);
143
- } else {
180
+ if (!sendAsFile) {
144
181
  await sendRecordMessage(ctx, event, result.filePath);
182
+ return;
183
+ }
184
+
185
+ const track = await this.resolveTrackMeta(
186
+ provider,
187
+ songId,
188
+ options,
189
+ session.lastSearch,
190
+ );
191
+ const prepared = await prepareTrackFile({
192
+ sourcePath: result.filePath,
193
+ title: track.title,
194
+ artist: track.artist,
195
+ fallbackName: `song-${songId}`,
196
+ });
197
+ try {
198
+ await sendFileMessage(ctx, event, prepared.filePath, prepared.fileName);
199
+ } finally {
200
+ await prepared.cleanup();
201
+ }
202
+ }
203
+
204
+ private async resolveTrackMeta(
205
+ provider: MusicProvider,
206
+ songId: string,
207
+ options?: SendSongOptions,
208
+ lastSearch?: MusicSearchResult,
209
+ ): Promise<{ title: string; artist: string }> {
210
+ const title = String(options?.title ?? "").trim();
211
+ const artist = String(options?.artist ?? "").trim();
212
+ if (title) {
213
+ return { title, artist };
214
+ }
215
+ const known = lastSearch?.tracks.find((item) => item.id === songId);
216
+ if (known) {
217
+ return {
218
+ title: String(known.title ?? "").trim(),
219
+ artist: String(known.artist ?? "").trim(),
220
+ };
221
+ }
222
+ try {
223
+ const detail = await provider.getSongDetail(songId);
224
+ return {
225
+ title: String(detail.title ?? "").trim(),
226
+ artist: String(detail.artist ?? "").trim(),
227
+ };
228
+ } catch (error) {
229
+ this.deps.logger.warn(
230
+ `[music] 获取歌曲信息失败 songId=${songId}: ${String(error)}`,
231
+ );
232
+ return { title: "", artist: "" };
145
233
  }
146
234
  }
147
235
 
@@ -179,7 +267,11 @@ export class MusicPluginRuntime {
179
267
  return;
180
268
  }
181
269
 
182
- await this.sendSongById(ctx, event, first.id, first.title, options);
270
+ await this.sendSongById(ctx, event, first.id, {
271
+ title: first.title,
272
+ artist: first.artist,
273
+ forceFile: options?.forceFile,
274
+ });
183
275
  }
184
276
 
185
277
  async searchAndSendList(
@@ -254,7 +346,9 @@ export class MusicPluginRuntime {
254
346
  }
255
347
 
256
348
  try {
257
- await this.sendSongById(ctx, event, target.id, target.title, {
349
+ await this.sendSongById(ctx, event, target.id, {
350
+ title: target.title,
351
+ artist: target.artist,
258
352
  forceFile,
259
353
  });
260
354
  } catch (error) {