dsh-podwave 0.0.0-stage → 0.10.19
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.
- package/LICENSE +21 -0
- package/README.md +183 -2
- package/cordis.patch.yml +4 -0
- package/dist/client.js +1328 -0
- package/package.json +58 -4
- package/scripts/__pycache__/asr_sherpa.cpython-312.pyc +0 -0
- package/scripts/asr_sherpa.py +69 -0
- package/scripts/asr_sherpa_batch.py +40 -0
- package/scripts/diarize.py +79 -0
- package/scripts/release.mjs +79 -0
- package/scripts/translate_local.py +59 -0
- package/src/catalog.js +238 -0
- package/src/config.js +103 -0
- package/src/diarize.js +87 -0
- package/src/downloader.js +364 -0
- package/src/host.js +903 -0
- package/src/jobs.js +86 -0
- package/src/library.js +248 -0
- package/src/llama.js +166 -0
- package/src/models.js +42 -0
- package/src/platform.js +163 -0
- package/src/setup.js +539 -0
- package/src/state.js +111 -0
- package/src/transcribe.js +1123 -0
- package/src/translate.js +256 -0
package/src/host.js
ADDED
|
@@ -0,0 +1,903 @@
|
|
|
1
|
+
// dsh-podwave host 半片:在 DSH 的 webServer 上挂 /podwave/api/*。
|
|
2
|
+
// 数据仍然放在 ~/.podwave,和独立版 Podwave 共用媒体库与进度。
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import http from 'node:http'
|
|
5
|
+
import crypto from 'node:crypto'
|
|
6
|
+
import { copyFile, mkdir, realpath, rm, stat } from 'node:fs/promises'
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
import { createReadStream, createWriteStream } from 'node:fs'
|
|
9
|
+
import { execFile } from 'node:child_process'
|
|
10
|
+
import { pipeline } from 'node:stream/promises'
|
|
11
|
+
import { DATA_DIR } from './state.js'
|
|
12
|
+
import {
|
|
13
|
+
addFolderState,
|
|
14
|
+
getState,
|
|
15
|
+
updateState,
|
|
16
|
+
initState,
|
|
17
|
+
removeFolderState,
|
|
18
|
+
removeProgressFor,
|
|
19
|
+
setProgress,
|
|
20
|
+
setSettings,
|
|
21
|
+
} from './state.js'
|
|
22
|
+
import {
|
|
23
|
+
addFolder,
|
|
24
|
+
expandHome,
|
|
25
|
+
forgetEpisodesUnder,
|
|
26
|
+
getCoverPath,
|
|
27
|
+
getEpisode,
|
|
28
|
+
getEpisodePaths,
|
|
29
|
+
getEpisodes,
|
|
30
|
+
getScanState,
|
|
31
|
+
scanLibrary,
|
|
32
|
+
} from './library.js'
|
|
33
|
+
import {
|
|
34
|
+
deleteTranscript,
|
|
35
|
+
getTranscriptionState,
|
|
36
|
+
migrateAllTranscripts,
|
|
37
|
+
readTranscript,
|
|
38
|
+
runtimeInfo,
|
|
39
|
+
startTranscription,
|
|
40
|
+
TRANSCRIPTS_DIR,
|
|
41
|
+
stopAll,
|
|
42
|
+
toMarkdown,
|
|
43
|
+
toSRT,
|
|
44
|
+
cancelTranscription,
|
|
45
|
+
diarizeTranscript,
|
|
46
|
+
editTranscriptLine,
|
|
47
|
+
enqueueBatch,
|
|
48
|
+
mergeTranscriptLine,
|
|
49
|
+
saveTranscript,
|
|
50
|
+
splitTranscriptLine,
|
|
51
|
+
validateTranscript,
|
|
52
|
+
} from './transcribe.js'
|
|
53
|
+
import { isLinux, isMac, isWindows } from './platform.js'
|
|
54
|
+
import { listJobs, removeJob } from './jobs.js'
|
|
55
|
+
import { scan as scanSetup, plan as planSetup, install as installSetup, cancelSetup, setupJob, llamaBinary, verify as verifySetup } from './setup.js'
|
|
56
|
+
import { getSection, updateSection } from './config.js'
|
|
57
|
+
import { diarizeInfo } from './diarize.js'
|
|
58
|
+
import { getTranslationState, publicConfig, saveConfig, startTranslation } from './translate.js'
|
|
59
|
+
import { listModels, loadModelConfig, saveModelConfig } from './models.js'
|
|
60
|
+
|
|
61
|
+
export const name = 'dsh-podwave'
|
|
62
|
+
|
|
63
|
+
const IMPORTS_DIR = path.join(DATA_DIR, 'imports')
|
|
64
|
+
|
|
65
|
+
function importOrphans() {
|
|
66
|
+
let entries = []
|
|
67
|
+
try {
|
|
68
|
+
entries = fs.readdirSync(IMPORTS_DIR, { withFileTypes: true }).filter((entry) => entry.isDirectory())
|
|
69
|
+
} catch {
|
|
70
|
+
return { batches: [], bytes: 0 }
|
|
71
|
+
}
|
|
72
|
+
const referenced = new Set(getState().folders || [])
|
|
73
|
+
const batches = []
|
|
74
|
+
let bytes = 0
|
|
75
|
+
for (const entry of entries) {
|
|
76
|
+
const dir = path.join(IMPORTS_DIR, entry.name)
|
|
77
|
+
if (referenced.has(dir)) continue
|
|
78
|
+
let size = 0
|
|
79
|
+
const walk = (target) => {
|
|
80
|
+
let info
|
|
81
|
+
try {
|
|
82
|
+
info = fs.statSync(target)
|
|
83
|
+
} catch {
|
|
84
|
+
return
|
|
85
|
+
}
|
|
86
|
+
if (info.isDirectory()) {
|
|
87
|
+
for (const name of fs.readdirSync(target)) walk(path.join(target, name))
|
|
88
|
+
} else {
|
|
89
|
+
size += info.size
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
walk(dir)
|
|
93
|
+
bytes += size
|
|
94
|
+
batches.push({ name: entry.name, path: dir, bytes: size })
|
|
95
|
+
}
|
|
96
|
+
return { batches, bytes }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// P2:撤销栈(每集最多 20 步,进程内保存)。
|
|
100
|
+
const undoStacks = new Map()
|
|
101
|
+
|
|
102
|
+
function pushUndo(id, transcript) {
|
|
103
|
+
const stack = undoStacks.get(id) || []
|
|
104
|
+
stack.push(JSON.parse(JSON.stringify(transcript.lines || [])))
|
|
105
|
+
if (stack.length > 20) stack.shift()
|
|
106
|
+
undoStacks.set(id, stack)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
function loadUiSettings() {
|
|
111
|
+
return getSection('ui')
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function saveUiSettings(patch) {
|
|
115
|
+
return updateSection('ui', patch)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const MIME = {
|
|
119
|
+
'.mp3': 'audio/mpeg',
|
|
120
|
+
'.m4a': 'audio/mp4',
|
|
121
|
+
'.m4b': 'audio/mp4',
|
|
122
|
+
'.aac': 'audio/aac',
|
|
123
|
+
'.wav': 'audio/wav',
|
|
124
|
+
'.flac': 'audio/flac',
|
|
125
|
+
'.ogg': 'audio/ogg',
|
|
126
|
+
'.oga': 'audio/ogg',
|
|
127
|
+
'.opus': 'audio/ogg',
|
|
128
|
+
'.weba': 'audio/webm',
|
|
129
|
+
'.webm': 'audio/webm',
|
|
130
|
+
'.wma': 'audio/x-ms-wma',
|
|
131
|
+
'.jpg': 'image/jpeg',
|
|
132
|
+
'.jpeg': 'image/jpeg',
|
|
133
|
+
'.png': 'image/png',
|
|
134
|
+
'.webp': 'image/webp',
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
let booted = null
|
|
138
|
+
|
|
139
|
+
function boot() {
|
|
140
|
+
if (!booted) {
|
|
141
|
+
booted = (async () => {
|
|
142
|
+
await initState()
|
|
143
|
+
await migrateAllTranscripts().catch((error) => console.error('[dsh-podwave] transcript migration failed:', error.message))
|
|
144
|
+
if (getState().folders.length) {
|
|
145
|
+
scanLibrary().catch((error) => console.error('[dsh-podwave] initial scan failed:', error.message))
|
|
146
|
+
}
|
|
147
|
+
})().catch((error) => {
|
|
148
|
+
booted = null
|
|
149
|
+
throw error
|
|
150
|
+
})
|
|
151
|
+
}
|
|
152
|
+
return booted
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function json(res, status, body) {
|
|
156
|
+
res.statusCode = status
|
|
157
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
158
|
+
res.setHeader('cache-control', 'no-store')
|
|
159
|
+
res.end(JSON.stringify(body))
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async function readJson(req) {
|
|
163
|
+
const chunks = []
|
|
164
|
+
let size = 0
|
|
165
|
+
for await (const chunk of req) {
|
|
166
|
+
size += chunk.length
|
|
167
|
+
if (size > 1024 * 1024) throw Object.assign(new Error('内容太大'), { status: 413 })
|
|
168
|
+
chunks.push(chunk)
|
|
169
|
+
}
|
|
170
|
+
const raw = Buffer.concat(chunks)
|
|
171
|
+
if (!raw.length) return {}
|
|
172
|
+
try {
|
|
173
|
+
return JSON.parse(raw.toString('utf8'))
|
|
174
|
+
} catch {
|
|
175
|
+
throw Object.assign(new Error('请求不是有效的 JSON'), { status: 400 })
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function requestRejection(ctx, req) {
|
|
180
|
+
const connection = ctx.get('connection')
|
|
181
|
+
if (typeof connection?.requestRejection !== 'function') return 403
|
|
182
|
+
return connection.requestRejection({ headers: req.headers })
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function sendFile(req, res, file, cacheControl = 'private, max-age=3600') {
|
|
186
|
+
let info
|
|
187
|
+
try {
|
|
188
|
+
info = await stat(file)
|
|
189
|
+
} catch {
|
|
190
|
+
return json(res, 404, { error: '文件不存在' })
|
|
191
|
+
}
|
|
192
|
+
const type = MIME[path.extname(file).toLowerCase()] || 'application/octet-stream'
|
|
193
|
+
res.setHeader('content-type', type)
|
|
194
|
+
res.setHeader('accept-ranges', 'bytes')
|
|
195
|
+
res.setHeader('cache-control', cacheControl)
|
|
196
|
+
res.setHeader('x-content-type-options', 'nosniff')
|
|
197
|
+
|
|
198
|
+
const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range || '')
|
|
199
|
+
if (range && (range[1] || range[2])) {
|
|
200
|
+
const start = range[1] ? Number(range[1]) : Math.max(0, info.size - Number(range[2]))
|
|
201
|
+
const end = range[1] && range[2] ? Math.min(Number(range[2]), info.size - 1) : info.size - 1
|
|
202
|
+
if (start >= info.size || start > end) {
|
|
203
|
+
res.statusCode = 416
|
|
204
|
+
res.setHeader('content-range', `bytes */${info.size}`)
|
|
205
|
+
return res.end()
|
|
206
|
+
}
|
|
207
|
+
res.statusCode = 206
|
|
208
|
+
res.setHeader('content-range', `bytes ${start}-${end}/${info.size}`)
|
|
209
|
+
res.setHeader('content-length', end - start + 1)
|
|
210
|
+
return createReadStream(file, { start, end }).pipe(res)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
res.statusCode = 200
|
|
214
|
+
res.setHeader('content-length', info.size)
|
|
215
|
+
if (req.method === 'HEAD') return res.end()
|
|
216
|
+
return createReadStream(file).pipe(res)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// 桌面端页面是 dsh-app:// 自定义 scheme,媒体经它代理时可能拿不到 Range,
|
|
220
|
+
// 导致 audio.currentTime 赋值被忽略(拖了回起点)。这里另起一个只监听回环的
|
|
221
|
+
// 小 HTTP 服务专门提供音频/封面,路径带随机密钥,浏览器可用 Range 正常拖动。
|
|
222
|
+
let mediaBase = ''
|
|
223
|
+
let mediaServer = null
|
|
224
|
+
let mediaReadyResolve = null
|
|
225
|
+
const mediaReady = new Promise((resolve) => {
|
|
226
|
+
mediaReadyResolve = resolve
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
function startMediaServer() {
|
|
230
|
+
const secret = crypto.randomBytes(16).toString('hex')
|
|
231
|
+
mediaServer = http.createServer(async (req, res) => {
|
|
232
|
+
try {
|
|
233
|
+
const prefix = `/m/${secret}/`
|
|
234
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1')
|
|
235
|
+
if (!url.pathname.startsWith(prefix)) {
|
|
236
|
+
res.statusCode = 404
|
|
237
|
+
return res.end()
|
|
238
|
+
}
|
|
239
|
+
res.setHeader('access-control-allow-origin', '*')
|
|
240
|
+
const rest = url.pathname.slice(prefix.length)
|
|
241
|
+
const match = /^episodes\/([^/]+)\/(audio|cover)$/.exec(rest)
|
|
242
|
+
if (!match) {
|
|
243
|
+
res.statusCode = 404
|
|
244
|
+
return res.end()
|
|
245
|
+
}
|
|
246
|
+
const episode = getEpisode(decodeURIComponent(match[1]))
|
|
247
|
+
if (!episode) {
|
|
248
|
+
res.statusCode = 404
|
|
249
|
+
return res.end()
|
|
250
|
+
}
|
|
251
|
+
if (match[2] === 'cover') {
|
|
252
|
+
const cover = getCoverPath(episode.id)
|
|
253
|
+
if (!cover) {
|
|
254
|
+
res.statusCode = 404
|
|
255
|
+
return res.end()
|
|
256
|
+
}
|
|
257
|
+
return sendFile(req, res, cover, 'public, max-age=86400')
|
|
258
|
+
}
|
|
259
|
+
if (!episode.file) {
|
|
260
|
+
res.statusCode = 404
|
|
261
|
+
return res.end()
|
|
262
|
+
}
|
|
263
|
+
return sendFile(req, res, episode.file, 'no-store')
|
|
264
|
+
} catch (error) {
|
|
265
|
+
res.statusCode = 500
|
|
266
|
+
res.end()
|
|
267
|
+
}
|
|
268
|
+
})
|
|
269
|
+
mediaServer.on('error', (error) => console.error('[podwave-media]', error.message))
|
|
270
|
+
mediaServer.listen(0, '127.0.0.1', () => {
|
|
271
|
+
const { port } = mediaServer.address()
|
|
272
|
+
mediaBase = `http://127.0.0.1:${port}/m/${secret}`
|
|
273
|
+
mediaReadyResolve()
|
|
274
|
+
})
|
|
275
|
+
mediaServer.unref()
|
|
276
|
+
return mediaServer
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function safeName(name) {
|
|
280
|
+
return String(name || 'audio')
|
|
281
|
+
.replace(/[\\/\u0000-\u001f]/g, '_')
|
|
282
|
+
.replace(/^\.+/, '_')
|
|
283
|
+
.slice(0, 180) || 'audio'
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function pickFolderDialog() {
|
|
287
|
+
const preset = process.env.PODWAVE_PICK_FOLDER
|
|
288
|
+
if (preset) return Promise.resolve({ path: preset })
|
|
289
|
+
let command
|
|
290
|
+
let args
|
|
291
|
+
if (isMac) {
|
|
292
|
+
command = 'osascript'
|
|
293
|
+
args = ['-e', 'POSIX path of (choose folder with prompt "选择存放播客的文件夹")']
|
|
294
|
+
} else if (isWindows) {
|
|
295
|
+
command = 'powershell.exe'
|
|
296
|
+
args = [
|
|
297
|
+
'-NoProfile',
|
|
298
|
+
'-STA',
|
|
299
|
+
'-Command',
|
|
300
|
+
[
|
|
301
|
+
'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
|
|
302
|
+
'Add-Type -AssemblyName System.Windows.Forms',
|
|
303
|
+
'$dialog = New-Object System.Windows.Forms.FolderBrowserDialog',
|
|
304
|
+
"$dialog.Description = '选择存放播客的文件夹'",
|
|
305
|
+
"if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { Write-Output $dialog.SelectedPath }",
|
|
306
|
+
].join('; '),
|
|
307
|
+
]
|
|
308
|
+
} else if (isLinux) {
|
|
309
|
+
command = 'zenity'
|
|
310
|
+
args = ['--file-selection', '--directory', '--title=选择存放播客的文件夹']
|
|
311
|
+
} else {
|
|
312
|
+
return Promise.resolve({ error: '当前系统没有可用的文件夹选择器,请手动输入路径' })
|
|
313
|
+
}
|
|
314
|
+
return new Promise((resolve) => {
|
|
315
|
+
execFile(command, args, { timeout: 180000 }, (error, stdout) => {
|
|
316
|
+
if (error) {
|
|
317
|
+
const message = String(error.stderr || error.message || '')
|
|
318
|
+
if (/canceled|cancelled|-128|exit code 1/i.test(message)) return resolve({ canceled: true })
|
|
319
|
+
if (error.code === 'ENOENT') return resolve({ error: '找不到系统选择器,请手动输入路径' })
|
|
320
|
+
return resolve({ error: `打开系统选择器失败:${message.trim().slice(0, 240)}` })
|
|
321
|
+
}
|
|
322
|
+
const picked = String(stdout || '').trim()
|
|
323
|
+
resolve(picked ? { path: picked } : { canceled: true })
|
|
324
|
+
})
|
|
325
|
+
})
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
async function addFolderByPath(rawPath) {
|
|
329
|
+
const folder = await addFolder(rawPath)
|
|
330
|
+
addFolderState(folder)
|
|
331
|
+
scanLibrary().catch((error) => console.error('[dsh-podwave] scan failed:', error.message))
|
|
332
|
+
return folder
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async function route(ctx, req, res) {
|
|
336
|
+
const url = new URL(req.url || '/', 'http://local')
|
|
337
|
+
const routePath = url.pathname.replace(/^\/podwave\/?/, '')
|
|
338
|
+
const method = req.method || 'GET'
|
|
339
|
+
|
|
340
|
+
if (routePath === 'api/setup') {
|
|
341
|
+
return json(res, 200, { ...scanSetup(), job: setupJob() })
|
|
342
|
+
}
|
|
343
|
+
if (routePath === 'api/setup/plan' && method === 'GET') {
|
|
344
|
+
const source = url.searchParams.get('source') || 'auto'
|
|
345
|
+
return json(res, 200, planSetup({ source }))
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
if (routePath === 'api/setup/verify' && method === 'GET') {
|
|
349
|
+
return json(res, 200, await verifySetup())
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
if (routePath === 'api/setup/diagnose' && method === 'GET') {
|
|
353
|
+
const { detectPlatform, recommendEngine, ffmpegPath, venvPython } = await import('./platform.js')
|
|
354
|
+
const platform = detectPlatform()
|
|
355
|
+
let components = null
|
|
356
|
+
try {
|
|
357
|
+
components = (await scanSetup()).components
|
|
358
|
+
} catch (error) {
|
|
359
|
+
components = [{ id: 'scan', label: 'scan', ready: false, detail: String(error.message || error) }]
|
|
360
|
+
}
|
|
361
|
+
return json(res, 200, {
|
|
362
|
+
ok: true,
|
|
363
|
+
generatedAt: new Date().toISOString(),
|
|
364
|
+
version: '0.10.13',
|
|
365
|
+
platform,
|
|
366
|
+
engine: recommendEngine(platform),
|
|
367
|
+
paths: {
|
|
368
|
+
data: DATA_DIR,
|
|
369
|
+
ffmpeg: ffmpegPath(),
|
|
370
|
+
python: venvPython(),
|
|
371
|
+
llama: llamaBinary(platform),
|
|
372
|
+
},
|
|
373
|
+
components,
|
|
374
|
+
setup: setupJob(),
|
|
375
|
+
})
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
if (routePath === 'api/setup/install' && method === 'POST') {
|
|
379
|
+
const body = await readJson(req)
|
|
380
|
+
if (setupJob()?.running) return json(res, 409, { error: '安装已在进行中' })
|
|
381
|
+
installSetup({ source: body?.source || 'auto' }).catch(() => {})
|
|
382
|
+
return json(res, 200, { started: true })
|
|
383
|
+
}
|
|
384
|
+
if (routePath === 'api/setup/cancel' && method === 'POST') {
|
|
385
|
+
return json(res, 200, { cancelled: cancelSetup() })
|
|
386
|
+
}
|
|
387
|
+
if ((method === 'GET' || method === 'HEAD') && routePath === 'api/health') {
|
|
388
|
+
await mediaReady
|
|
389
|
+
return json(res, 200, { ok: true, app: 'podwave', version: '0.10.19', mediaBase, transcribe: runtimeInfo(), diarize: diarizeInfo(), translate: publicConfig() })
|
|
390
|
+
}
|
|
391
|
+
if (method === 'GET' && routePath === 'api/state') {
|
|
392
|
+
const state = getState()
|
|
393
|
+
return json(res, 200, { folders: state.folders, settings: state.settings })
|
|
394
|
+
}
|
|
395
|
+
if (method === 'GET' && routePath === 'api/episodes') {
|
|
396
|
+
const state = getState()
|
|
397
|
+
let transcriptIds = []
|
|
398
|
+
try {
|
|
399
|
+
transcriptIds = fs.readdirSync(TRANSCRIPTS_DIR).filter((file) => file.endsWith('.json')).map((file) => file.replace(/\.json$/, ''))
|
|
400
|
+
} catch {
|
|
401
|
+
transcriptIds = []
|
|
402
|
+
}
|
|
403
|
+
const withTranscript = new Set(transcriptIds)
|
|
404
|
+
const favorites = new Set(state.favorites || [])
|
|
405
|
+
const hidden = new Set(state.hidden || [])
|
|
406
|
+
return json(res, 200, {
|
|
407
|
+
items: getEpisodes()
|
|
408
|
+
.filter((episode) => !hidden.has(episode.id))
|
|
409
|
+
.map((episode) => ({ ...episode, hasTranscript: withTranscript.has(episode.id), favorite: favorites.has(episode.id) })),
|
|
410
|
+
folders: state.folders,
|
|
411
|
+
progress: state.progress,
|
|
412
|
+
scan: getScanState(),
|
|
413
|
+
})
|
|
414
|
+
}
|
|
415
|
+
if (method === 'POST' && routePath === 'api/scan') {
|
|
416
|
+
scanLibrary().catch((error) => console.error('[dsh-podwave] scan failed:', error.message))
|
|
417
|
+
return json(res, 200, { scan: getScanState() })
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
if (routePath === 'api/pick-folder') {
|
|
421
|
+
if (method !== 'POST') return json(res, 405, { error: 'Method not allowed' })
|
|
422
|
+
const result = await pickFolderDialog()
|
|
423
|
+
if (result.error) return json(res, 500, { error: result.error })
|
|
424
|
+
return json(res, 200, result)
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
if (routePath === 'api/import/upload') {
|
|
428
|
+
if (method !== 'POST') return json(res, 405, { error: 'Method not allowed' })
|
|
429
|
+
const name = safeName(url.searchParams.get('name'))
|
|
430
|
+
const batch = safeName(url.searchParams.get('batch')) || `drop-${Date.now()}`
|
|
431
|
+
const dir = path.join(IMPORTS_DIR, batch)
|
|
432
|
+
await mkdir(dir, { recursive: true })
|
|
433
|
+
let file = path.join(dir, name)
|
|
434
|
+
let counter = 1
|
|
435
|
+
while (fs.existsSync(file)) file = path.join(dir, `${counter++}-${name}`)
|
|
436
|
+
await pipeline(req, createWriteStream(file))
|
|
437
|
+
const size = (await stat(file)).size
|
|
438
|
+
return json(res, 200, { folder: dir, file, size })
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
if (routePath === 'api/import/paths') {
|
|
442
|
+
if (method !== 'POST') return json(res, 405, { error: 'Method not allowed' })
|
|
443
|
+
const body = await readJson(req)
|
|
444
|
+
const inputs = Array.isArray(body?.paths) ? body.paths : []
|
|
445
|
+
const mode = (getSection('import') || {}).mode === 'reference' ? 'reference' : 'copy'
|
|
446
|
+
const library = getEpisodePaths()
|
|
447
|
+
const existing = new Map(library.map((episode) => [episode.file, episode.id]))
|
|
448
|
+
const signatures = new Set(library.map((episode) => `${path.basename(episode.file)}:${episode.size || 0}`))
|
|
449
|
+
const skipped = []
|
|
450
|
+
let added = 0
|
|
451
|
+
let copied = 0
|
|
452
|
+
for (const input of inputs) {
|
|
453
|
+
const target = expandHome(String(input || ''))
|
|
454
|
+
if (!target) continue
|
|
455
|
+
let info
|
|
456
|
+
try {
|
|
457
|
+
info = await stat(target)
|
|
458
|
+
} catch {
|
|
459
|
+
skipped.push({ path: target, reason: 'not-found' })
|
|
460
|
+
continue
|
|
461
|
+
}
|
|
462
|
+
try {
|
|
463
|
+
if (info.isDirectory()) {
|
|
464
|
+
await addFolderByPath(target)
|
|
465
|
+
added++
|
|
466
|
+
continue
|
|
467
|
+
}
|
|
468
|
+
const resolved = await realpath(target).catch(() => target)
|
|
469
|
+
if (existing.has(resolved) || signatures.has(`${path.basename(target)}:${info.size || 0}`)) {
|
|
470
|
+
skipped.push({ path: target, reason: 'duplicate' })
|
|
471
|
+
continue
|
|
472
|
+
}
|
|
473
|
+
signatures.add(`${path.basename(target)}:${info.size || 0}`)
|
|
474
|
+
if (mode === 'reference') {
|
|
475
|
+
await addFolderByPath(path.dirname(target))
|
|
476
|
+
added++
|
|
477
|
+
} else {
|
|
478
|
+
const batch = `drop-${Date.now()}-${copied}`
|
|
479
|
+
const dir = path.join(IMPORTS_DIR, batch)
|
|
480
|
+
await mkdir(dir, { recursive: true })
|
|
481
|
+
await copyFile(target, path.join(dir, path.basename(target)))
|
|
482
|
+
await addFolderByPath(dir)
|
|
483
|
+
copied++
|
|
484
|
+
}
|
|
485
|
+
} catch (error) {
|
|
486
|
+
if (error.status !== 409) skipped.push({ path: target, reason: error.message })
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
return json(res, 200, { added: added + copied, copied, skipped, mode, folders: getState().folders })
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
const favoriteMatch = /^api\/episodes\/([^/]+)\/favorite$/.exec(routePath)
|
|
493
|
+
if (favoriteMatch) {
|
|
494
|
+
if (method !== 'PUT') return json(res, 405, { error: 'Method not allowed' })
|
|
495
|
+
const id = decodeURIComponent(favoriteMatch[1])
|
|
496
|
+
const body = await readJson(req)
|
|
497
|
+
const favorite = Boolean(body?.favorite)
|
|
498
|
+
const favorites = new Set(getState().favorites || [])
|
|
499
|
+
if (favorite) favorites.add(id)
|
|
500
|
+
else favorites.delete(id)
|
|
501
|
+
updateState({ favorites: [...favorites] })
|
|
502
|
+
return json(res, 200, { id, favorite })
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
const hideMatch = /^api\/episodes\/([^/]+)$/.exec(routePath)
|
|
506
|
+
if (hideMatch) {
|
|
507
|
+
if (method !== 'DELETE') return json(res, 405, { error: 'Method not allowed' })
|
|
508
|
+
const id = decodeURIComponent(hideMatch[1])
|
|
509
|
+
const hidden = new Set(getState().hidden || [])
|
|
510
|
+
hidden.add(id)
|
|
511
|
+
updateState({ hidden: [...hidden] })
|
|
512
|
+
return json(res, 200, { id, hidden: true })
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
if (routePath === 'api/import/settings') {
|
|
516
|
+
if (method === 'GET') {
|
|
517
|
+
const config = getSection('import') || {}
|
|
518
|
+
const { batches, bytes } = importOrphans()
|
|
519
|
+
return json(res, 200, { mode: config.mode === 'reference' ? 'reference' : 'copy', orphans: batches.length, orphanBytes: bytes })
|
|
520
|
+
}
|
|
521
|
+
if (method === 'PUT') {
|
|
522
|
+
const body = await readJson(req)
|
|
523
|
+
const mode = body?.mode === 'reference' ? 'reference' : 'copy'
|
|
524
|
+
const next = updateSection('import', { mode })
|
|
525
|
+
return json(res, 200, { mode: next.mode })
|
|
526
|
+
}
|
|
527
|
+
return json(res, 405, { error: 'Method not allowed' })
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
if (routePath === 'api/imports/orphans') {
|
|
531
|
+
if (method === 'GET') return json(res, 200, importOrphans())
|
|
532
|
+
if (method === 'DELETE') {
|
|
533
|
+
const { batches } = importOrphans()
|
|
534
|
+
for (const batch of batches) await rm(batch.path, { recursive: true, force: true }).catch(() => {})
|
|
535
|
+
return json(res, 200, { removed: batches.length })
|
|
536
|
+
}
|
|
537
|
+
return json(res, 405, { error: 'Method not allowed' })
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
if (routePath === 'api/folders') {
|
|
541
|
+
if (method === 'POST') {
|
|
542
|
+
const body = await readJson(req)
|
|
543
|
+
const folder = await addFolder(body?.path)
|
|
544
|
+
addFolderState(folder)
|
|
545
|
+
scanLibrary().catch((error) => console.error('[dsh-podwave] scan failed:', error.message))
|
|
546
|
+
return json(res, 200, { folder, folders: getState().folders })
|
|
547
|
+
}
|
|
548
|
+
if (method === 'DELETE') {
|
|
549
|
+
const body = await readJson(req)
|
|
550
|
+
const input = body?.path || url.searchParams.get('path')
|
|
551
|
+
const target = expandHome(input)
|
|
552
|
+
if (!target) return json(res, 400, { error: '缺少文件夹路径' })
|
|
553
|
+
const folders = getState().folders
|
|
554
|
+
const next = folders.filter((folder) => folder !== target)
|
|
555
|
+
if (next.length === folders.length) return json(res, 404, { error: '文件夹不在列表中' })
|
|
556
|
+
const removed = forgetEpisodesUnder(target)
|
|
557
|
+
removeProgressFor((id) => removed.has(id))
|
|
558
|
+
removeFolderState(target)
|
|
559
|
+
scanLibrary().catch((error) => console.error('[dsh-podwave] scan failed:', error.message))
|
|
560
|
+
return json(res, 200, { folders: next })
|
|
561
|
+
}
|
|
562
|
+
return json(res, 405, { error: '不支持的方法' })
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
const coverMatch = /^api\/episodes\/([^/]+)\/cover$/.exec(routePath)
|
|
566
|
+
if (coverMatch && (method === 'GET' || method === 'HEAD')) {
|
|
567
|
+
const episode = getEpisode(decodeURIComponent(coverMatch[1]))
|
|
568
|
+
const cover = episode ? getCoverPath(episode.id) : null
|
|
569
|
+
if (!cover) return json(res, 404, { error: '没有封面' })
|
|
570
|
+
res.setHeader('cache-control', 'public, max-age=86400')
|
|
571
|
+
return sendFile(req, res, cover, 'public, max-age=86400')
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
const audioMatch = /^api\/episodes\/([^/]+)\/audio$/.exec(routePath)
|
|
575
|
+
if (audioMatch && (method === 'GET' || method === 'HEAD')) {
|
|
576
|
+
const episode = getEpisode(decodeURIComponent(audioMatch[1]))
|
|
577
|
+
if (!episode) return json(res, 404, { error: '单集不存在' })
|
|
578
|
+
try {
|
|
579
|
+
await stat(episode.file)
|
|
580
|
+
} catch {
|
|
581
|
+
return json(res, 410, { error: '文件已不存在' })
|
|
582
|
+
}
|
|
583
|
+
return sendFile(req, res, episode.file, 'no-store')
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
const transcriptMatch = /^api\/episodes\/([^/]+)\/transcript$/.exec(routePath)
|
|
587
|
+
if (transcriptMatch) {
|
|
588
|
+
const id = decodeURIComponent(transcriptMatch[1])
|
|
589
|
+
if (!getEpisode(id)) return json(res, 404, { error: '单集不存在' })
|
|
590
|
+
if (method === 'GET') return json(res, 200, await getTranscriptionState(id))
|
|
591
|
+
if (method === 'DELETE') {
|
|
592
|
+
const ok = await deleteTranscript(id)
|
|
593
|
+
return ok ? json(res, 200, { ok: true }) : json(res, 409, { error: '正在转写,完成后再试' })
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
const transcribeMatch = /^api\/episodes\/([^/]+)\/transcribe$/.exec(routePath)
|
|
598
|
+
if (transcribeMatch && method === 'POST') {
|
|
599
|
+
const episode = getEpisode(decodeURIComponent(transcribeMatch[1]))
|
|
600
|
+
if (!episode) return json(res, 404, { error: '单集不存在' })
|
|
601
|
+
const body = await readJson(req)
|
|
602
|
+
const result = await startTranscription(episode, { force: Boolean(body?.force), resume: Boolean(body?.resume) })
|
|
603
|
+
return json(res, 200, result)
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
const diarizeMatch = /^api\/episodes\/([^/]+)\/diarize$/.exec(routePath)
|
|
607
|
+
if (diarizeMatch && method === 'POST') {
|
|
608
|
+
const episode = getEpisode(decodeURIComponent(diarizeMatch[1]))
|
|
609
|
+
if (!episode) return json(res, 404, { error: '单集不存在' })
|
|
610
|
+
try {
|
|
611
|
+
const transcript = await diarizeTranscript(episode)
|
|
612
|
+
return json(res, 200, { transcript })
|
|
613
|
+
} catch (error) {
|
|
614
|
+
return json(res, 400, { error: error.message })
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
const transcribeCancelMatch = /^api\/episodes\/([^/]+)\/transcribe\/cancel$/.exec(routePath)
|
|
619
|
+
if (transcribeCancelMatch && method === 'POST') {
|
|
620
|
+
const id = decodeURIComponent(transcribeCancelMatch[1])
|
|
621
|
+
if (!getEpisode(id)) return json(res, 404, { error: '单集不存在' })
|
|
622
|
+
return json(res, 200, cancelTranscription(id))
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
if (routePath === 'api/transcribe/batch' && method === 'POST') {
|
|
626
|
+
const body = await readJson(req)
|
|
627
|
+
const ids = Array.isArray(body?.ids) ? body.ids.map((id) => String(id)) : []
|
|
628
|
+
const episodes = ids.map((id) => getEpisode(id)).filter(Boolean)
|
|
629
|
+
if (!episodes.length) return json(res, 400, { error: '没有可转写的单集' })
|
|
630
|
+
const result = await enqueueBatch(episodes)
|
|
631
|
+
return json(res, 200, result)
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
if (routePath === 'api/transcribe/settings') {
|
|
635
|
+
if (method === 'GET') return json(res, 200, { ...getSection('transcribe'), runtime: runtimeInfo() })
|
|
636
|
+
if (method === 'PUT') {
|
|
637
|
+
const body = await readJson(req)
|
|
638
|
+
const patch = {}
|
|
639
|
+
if (Array.isArray(body?.hotwords)) patch.hotwords = body.hotwords.map((word) => String(word || '').trim()).filter(Boolean).slice(0, 500)
|
|
640
|
+
if (Number.isFinite(Number(body?.chunkMinutes))) patch.chunkMinutes = Math.max(1, Math.min(60, Number(body.chunkMinutes)))
|
|
641
|
+
if (typeof body?.diarize === 'boolean') patch.diarize = body.diarize
|
|
642
|
+
if (!Object.keys(patch).length) return json(res, 400, { error: '没有可保存的设置' })
|
|
643
|
+
return json(res, 200, { ...updateSection('transcribe', patch), runtime: runtimeInfo() })
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
const lineMatch = /^api\/episodes\/([^/]+)\/transcript\/lines\/([^/]+)$/.exec(routePath)
|
|
648
|
+
if (lineMatch && method === 'PUT') {
|
|
649
|
+
const id = decodeURIComponent(lineMatch[1])
|
|
650
|
+
if (!getEpisode(id)) return json(res, 404, { error: '单集不存在' })
|
|
651
|
+
const before = await readTranscript(id)
|
|
652
|
+
if (!before) return json(res, 404, { error: '还没有转写' })
|
|
653
|
+
const body = await readJson(req)
|
|
654
|
+
try {
|
|
655
|
+
pushUndo(id, before)
|
|
656
|
+
const transcript = await editTranscriptLine(id, decodeURIComponent(lineMatch[2]), body || {})
|
|
657
|
+
return json(res, 200, { transcript })
|
|
658
|
+
} catch (error) {
|
|
659
|
+
return json(res, 400, { error: error.message })
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
const splitMatch = /^api\/episodes\/([^/]+)\/transcript\/lines\/([^/]+)\/split$/.exec(routePath)
|
|
664
|
+
if (splitMatch && method === 'POST') {
|
|
665
|
+
const id = decodeURIComponent(splitMatch[1])
|
|
666
|
+
if (!getEpisode(id)) return json(res, 404, { error: '单集不存在' })
|
|
667
|
+
const before = await readTranscript(id)
|
|
668
|
+
if (!before) return json(res, 404, { error: '还没有转写' })
|
|
669
|
+
const body = await readJson(req)
|
|
670
|
+
try {
|
|
671
|
+
pushUndo(id, before)
|
|
672
|
+
const transcript = await splitTranscriptLine(id, decodeURIComponent(splitMatch[2]), Number(body?.offset))
|
|
673
|
+
return json(res, 200, { transcript })
|
|
674
|
+
} catch (error) {
|
|
675
|
+
return json(res, 400, { error: error.message })
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
const mergeMatch = /^api\/episodes\/([^/]+)\/transcript\/lines\/([^/]+)\/merge$/.exec(routePath)
|
|
680
|
+
if (mergeMatch && method === 'POST') {
|
|
681
|
+
const id = decodeURIComponent(mergeMatch[1])
|
|
682
|
+
if (!getEpisode(id)) return json(res, 404, { error: '单集不存在' })
|
|
683
|
+
const before = await readTranscript(id)
|
|
684
|
+
if (!before) return json(res, 404, { error: '还没有转写' })
|
|
685
|
+
try {
|
|
686
|
+
pushUndo(id, before)
|
|
687
|
+
const transcript = await mergeTranscriptLine(id, decodeURIComponent(mergeMatch[2]))
|
|
688
|
+
return json(res, 200, { transcript })
|
|
689
|
+
} catch (error) {
|
|
690
|
+
return json(res, 400, { error: error.message })
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
const undoMatch = /^api\/episodes\/([^/]+)\/transcript\/undo$/.exec(routePath)
|
|
695
|
+
if (undoMatch && method === 'POST') {
|
|
696
|
+
const id = decodeURIComponent(undoMatch[1])
|
|
697
|
+
if (!getEpisode(id)) return json(res, 404, { error: '单集不存在' })
|
|
698
|
+
const transcript = await readTranscript(id)
|
|
699
|
+
if (!transcript) return json(res, 404, { error: '还没有转写' })
|
|
700
|
+
const stack = undoStacks.get(id) || []
|
|
701
|
+
if (!stack.length) return json(res, 409, { error: '没有可以撤销的修改' })
|
|
702
|
+
transcript.lines = stack.pop()
|
|
703
|
+
transcript.text = transcript.lines.map((line) => line.text).join(' ')
|
|
704
|
+
await saveTranscript(transcript)
|
|
705
|
+
return json(res, 200, { transcript })
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
const validateMatch = /^api\/episodes\/([^/]+)\/transcript\/validate$/.exec(routePath)
|
|
709
|
+
if (validateMatch && method === 'GET') {
|
|
710
|
+
return json(res, 200, await validateTranscript(decodeURIComponent(validateMatch[1])))
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
const transcriptExportMatch = /^api\/episodes\/([^/]+)\/transcript\/export$/.exec(routePath)
|
|
714
|
+
if (transcriptExportMatch && method === 'GET') {
|
|
715
|
+
const id = decodeURIComponent(transcriptExportMatch[1])
|
|
716
|
+
const transcript = await readTranscript(id)
|
|
717
|
+
if (!transcript) return json(res, 404, { error: '还没有转写' })
|
|
718
|
+
const format = (url.searchParams.get('format') || 'srt').toLowerCase()
|
|
719
|
+
const markdown = format === 'md' || format === 'markdown'
|
|
720
|
+
res.statusCode = 200
|
|
721
|
+
res.setHeader('content-type', 'text/plain; charset=utf-8')
|
|
722
|
+
res.setHeader('content-disposition', `attachment; filename="podwave-${id}.${markdown ? 'md' : 'srt'}"`)
|
|
723
|
+
res.setHeader('cache-control', 'no-store')
|
|
724
|
+
return res.end(markdown ? toMarkdown(transcript) : toSRT(transcript))
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
if (routePath === 'api/models') {
|
|
728
|
+
if (method === 'GET') return json(res, 200, { config: loadModelConfig(), models: listModels(), transcribe: runtimeInfo(), translate: publicConfig() })
|
|
729
|
+
if (method === 'PUT') {
|
|
730
|
+
const body = await readJson(req)
|
|
731
|
+
const available = new Set(listModels().filter((model) => model.ready).map((model) => model.name))
|
|
732
|
+
const patch = {}
|
|
733
|
+
if (typeof body?.asrModel === 'string' && available.has(body.asrModel)) patch.asrModel = body.asrModel
|
|
734
|
+
if (typeof body?.translateModel === 'string' && available.has(body.translateModel)) patch.translateModel = body.translateModel
|
|
735
|
+
if (!Object.keys(patch).length) return json(res, 400, { error: '没有可用的模型' })
|
|
736
|
+
const config = saveModelConfig(patch)
|
|
737
|
+
return json(res, 200, { config, models: listModels(), transcribe: runtimeInfo(), translate: publicConfig() })
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
if (routePath === 'api/jobs') {
|
|
742
|
+
if (method === 'GET') return json(res, 200, { items: listJobs() })
|
|
743
|
+
if (method === 'DELETE') {
|
|
744
|
+
const body = await readJson(req)
|
|
745
|
+
if (body?.key) removeJob(String(body.key))
|
|
746
|
+
return json(res, 200, { items: listJobs() })
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
if (method === 'GET' && routePath === 'api/history') {
|
|
751
|
+
const items = []
|
|
752
|
+
let files = []
|
|
753
|
+
try {
|
|
754
|
+
files = fs.readdirSync(TRANSCRIPTS_DIR).filter((file) => file.endsWith('.json'))
|
|
755
|
+
} catch {
|
|
756
|
+
files = []
|
|
757
|
+
}
|
|
758
|
+
for (const file of files) {
|
|
759
|
+
const id = file.replace(/\.json$/, '')
|
|
760
|
+
const transcript = await readTranscript(id)
|
|
761
|
+
if (!transcript) continue
|
|
762
|
+
const episode = getEpisode(id)
|
|
763
|
+
let completedAt = null
|
|
764
|
+
try {
|
|
765
|
+
completedAt = (await stat(path.join(TRANSCRIPTS_DIR, file))).mtimeMs
|
|
766
|
+
} catch {
|
|
767
|
+
completedAt = null
|
|
768
|
+
}
|
|
769
|
+
items.push({
|
|
770
|
+
id,
|
|
771
|
+
title: episode?.title || transcript.title || id,
|
|
772
|
+
artist: episode?.artist || '',
|
|
773
|
+
duration: episode?.duration || null,
|
|
774
|
+
language: transcript.language || null,
|
|
775
|
+
lines: Array.isArray(transcript.lines) ? transcript.lines.length : 0,
|
|
776
|
+
translations: Object.keys(transcript.providers || {}),
|
|
777
|
+
translated: Array.isArray(transcript.lines)
|
|
778
|
+
? transcript.lines.filter((line) => Object.keys(line.translations || {}).length).length
|
|
779
|
+
: 0,
|
|
780
|
+
provider: Object.values(transcript.providers || {})[0] || null,
|
|
781
|
+
completedAt,
|
|
782
|
+
})
|
|
783
|
+
}
|
|
784
|
+
items.sort((a, b) => (b.completedAt || 0) - (a.completedAt || 0))
|
|
785
|
+
return json(res, 200, { items })
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
if (routePath === 'api/ui-settings') {
|
|
789
|
+
if (method === 'GET') return json(res, 200, loadUiSettings())
|
|
790
|
+
if (method === 'PUT') {
|
|
791
|
+
const body = await readJson(req)
|
|
792
|
+
const patch = {}
|
|
793
|
+
if (typeof body?.showSidebarPanel === 'boolean') patch.showSidebarPanel = body.showSidebarPanel
|
|
794
|
+
if (typeof body?.sidebarCollapsed === 'boolean') patch.sidebarCollapsed = body.sidebarCollapsed
|
|
795
|
+
if (!Object.keys(patch).length) return json(res, 400, { error: '没有可保存的设置' })
|
|
796
|
+
return json(res, 200, saveUiSettings(patch))
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
if (routePath === 'api/translate/settings') {
|
|
801
|
+
if (method === 'GET') return json(res, 200, publicConfig())
|
|
802
|
+
if (method === 'PUT') {
|
|
803
|
+
const body = await readJson(req)
|
|
804
|
+
const patch = {}
|
|
805
|
+
if (body?.provider === 'api' || body?.provider === 'local') patch.provider = body.provider
|
|
806
|
+
if (body?.target === 'zh' || body?.target === 'en') patch.target = body.target
|
|
807
|
+
if (typeof body?.apiKey === 'string') patch.apiKey = body.apiKey.trim()
|
|
808
|
+
if (typeof body?.apiBase === 'string' && body.apiBase.trim()) patch.apiBase = body.apiBase.trim()
|
|
809
|
+
if (typeof body?.apiModel === 'string' && body.apiModel.trim()) patch.apiModel = body.apiModel.trim()
|
|
810
|
+
saveConfig(patch)
|
|
811
|
+
return json(res, 200, publicConfig())
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
const translateMatch = /^api\/episodes\/([^/]+)\/translate$/.exec(routePath)
|
|
816
|
+
if (translateMatch) {
|
|
817
|
+
const id = decodeURIComponent(translateMatch[1])
|
|
818
|
+
if (!getEpisode(id)) return json(res, 404, { error: '单集不存在' })
|
|
819
|
+
if (method === 'GET') {
|
|
820
|
+
const target = url.searchParams.get('target') === 'en' ? 'en' : 'zh'
|
|
821
|
+
return json(res, 200, await getTranslationState(id, target))
|
|
822
|
+
}
|
|
823
|
+
if (method === 'POST') {
|
|
824
|
+
const body = await readJson(req)
|
|
825
|
+
const target = body?.target === 'en' ? 'en' : 'zh'
|
|
826
|
+
const provider = body?.provider === 'local' ? 'local' : body?.provider === 'api' ? 'api' : undefined
|
|
827
|
+
return json(res, 200, await startTranslation(id, { target, provider }))
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
const progressMatch = /^api\/progress\/([^/]+)$/.exec(routePath)
|
|
832
|
+
if (progressMatch && method === 'PUT') {
|
|
833
|
+
const episode = getEpisode(decodeURIComponent(progressMatch[1]))
|
|
834
|
+
if (!episode) return json(res, 404, { error: '单集不存在' })
|
|
835
|
+
const body = await readJson(req)
|
|
836
|
+
const position = Number(body?.position)
|
|
837
|
+
const duration = Number(body?.duration) || episode.duration || 0
|
|
838
|
+
if (!Number.isFinite(position) || position < 0) return json(res, 400, { error: '位置无效' })
|
|
839
|
+
setProgress(episode.id, Math.round(position * 10) / 10, duration)
|
|
840
|
+
return json(res, 200, { ok: true })
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
if (routePath === 'api/settings' && method === 'PATCH') {
|
|
844
|
+
const body = await readJson(req)
|
|
845
|
+
const patch = {}
|
|
846
|
+
if (Number.isFinite(Number(body?.rate))) patch.rate = Math.min(3, Math.max(0.5, Number(body.rate)))
|
|
847
|
+
if (Number.isFinite(Number(body?.volume))) patch.volume = Math.min(1, Math.max(0, Number(body.volume)))
|
|
848
|
+
if (typeof body?.lastEpisodeId === 'string' || body?.lastEpisodeId === null) patch.lastEpisodeId = body.lastEpisodeId
|
|
849
|
+
setSettings(patch)
|
|
850
|
+
return json(res, 200, { settings: getState().settings })
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
return json(res, 404, { error: '接口不存在' })
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
export default {
|
|
857
|
+
inject: ['webServer', 'connection'],
|
|
858
|
+
apply(ctx) {
|
|
859
|
+
const ready = boot()
|
|
860
|
+
startMediaServer()
|
|
861
|
+
ctx.effect(() => () => {
|
|
862
|
+
try {
|
|
863
|
+
mediaServer?.close()
|
|
864
|
+
} catch {
|
|
865
|
+
/* ignore */
|
|
866
|
+
}
|
|
867
|
+
}, 'dsh-podwave: media server')
|
|
868
|
+
ctx.effect(
|
|
869
|
+
() =>
|
|
870
|
+
ctx.webServer.register({
|
|
871
|
+
kind: 'prefix',
|
|
872
|
+
path: '/podwave',
|
|
873
|
+
handler: async (req, res) => {
|
|
874
|
+
try {
|
|
875
|
+
const rejection = requestRejection(ctx, req)
|
|
876
|
+
if (rejection) {
|
|
877
|
+
json(res, rejection, { error: '未授权' })
|
|
878
|
+
return
|
|
879
|
+
}
|
|
880
|
+
await ready
|
|
881
|
+
if (req.method && req.method !== 'GET' && req.method !== 'HEAD') {
|
|
882
|
+
const site = req.headers['sec-fetch-site']
|
|
883
|
+
if (site && site !== 'same-origin' && site !== 'none') {
|
|
884
|
+
json(res, 403, { error: '拒绝跨站请求' })
|
|
885
|
+
return
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
await route(ctx, req, res)
|
|
889
|
+
} catch (error) {
|
|
890
|
+
if (res.headersSent) {
|
|
891
|
+
res.end()
|
|
892
|
+
return
|
|
893
|
+
}
|
|
894
|
+
console.error('[podwave-error]', error && error.stack ? error.stack : error)
|
|
895
|
+
json(res, error.status || 500, { error: error.message || '服务器错误' })
|
|
896
|
+
}
|
|
897
|
+
},
|
|
898
|
+
}),
|
|
899
|
+
'dsh-podwave: /podwave routes',
|
|
900
|
+
)
|
|
901
|
+
ctx.effect(() => () => stopAll(), 'dsh-podwave: stop transcription workers')
|
|
902
|
+
},
|
|
903
|
+
}
|