-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiServer.js
More file actions
574 lines (529 loc) · 21 KB
/
apiServer.js
File metadata and controls
574 lines (529 loc) · 21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/**
* Local HTTP API server that replicates the Flask recordings_viewer.pyw endpoints.
* Runs inside Electron's main process on a random port.
*/
const http = require('http')
const fs = require('fs')
const path = require('path')
const { exec, execFile, spawn } = require('child_process')
const { shell } = require('electron')
const url = require('url')
const { MIME_TYPES, formatFileSize, FFMPEG_PATH, FFPROBE_PATH, CODEC_MAP } = require('./constants')
const service = require('./recordingService')
const { loadMarkers, saveMarkers } = require('./markerService')
const { getVideoDuration, getDiskUsage } = require('./videoMetadata')
const { getWaveform, setWaveform } = require('./waveformCache')
const { getNumPeaks, generateWaveform, generateWaveformChunk } = require('./waveformUtils')
let store // set in startApiServer
const MAX_BODY_SIZE = 1024 * 1024 // 1 MB
function isAllowedPath(filePath) {
if (!filePath) return false
const resolved = path.resolve(filePath)
const roots = [store.get('settings.obsRecordingPath'), store.get('settings.destinationPath')]
.filter(Boolean)
.map((p) => path.resolve(p))
return roots.some((base) => resolved === base || resolved.startsWith(base + path.sep))
}
function readBody(req) {
return new Promise((resolve, reject) => {
let body = ''
let size = 0
req.on('data', (chunk) => {
size += chunk.length
if (size > MAX_BODY_SIZE) {
req.destroy()
reject(new Error('Payload too large'))
return
}
body += chunk
})
req.on('end', () => {
try {
resolve(JSON.parse(body))
} catch {
resolve({})
}
})
})
}
function json(res, data, status = 200) {
res.writeHead(status, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' })
res.end(JSON.stringify(data))
}
function startApiServer(appStore) {
store = appStore
service.init(appStore)
const server = http.createServer(async (req, res) => {
// CORS preflight
if (req.method === 'OPTIONS') {
res.writeHead(204, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
})
return res.end()
}
const parsed = url.parse(req.url, true)
const pathname = parsed.pathname
const query = parsed.query
try {
// GET /api/recordings
if (pathname === '/api/recordings' && req.method === 'GET') {
return json(res, service.scanRecordings())
}
// GET /api/clips
if (pathname === '/api/clips' && req.method === 'GET') {
return json(res, service.scanClips())
}
// GET /api/video?path=...
if (pathname === '/api/video' && req.method === 'GET') {
const filePath = query.path
if (!filePath) return json(res, { error: 'File not found' }, 404)
if (!isAllowedPath(filePath)) return json(res, { error: 'Forbidden' }, 403)
let stat
try {
stat = fs.statSync(filePath)
} catch {
return json(res, { error: 'File not found' }, 404)
}
const ext = path.extname(filePath).toLowerCase()
const mimeType = MIME_TYPES[ext] || 'video/mp4'
const fileSize = stat.size
const range = req.headers.range
if (range) {
const match = range.match(/bytes=(\d+)-(\d*)/)
const start = parseInt(match[1])
const end = match[2] ? parseInt(match[2]) : fileSize - 1
const contentLength = end - start + 1
res.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': contentLength,
'Content-Type': mimeType,
'Access-Control-Allow-Origin': '*',
})
const rangeStream = fs.createReadStream(filePath, { start, end })
rangeStream.on('error', () => {})
res.on('close', () => rangeStream.destroy())
rangeStream.pipe(res)
} else {
res.writeHead(200, {
'Accept-Ranges': 'bytes',
'Content-Length': fileSize,
'Content-Type': mimeType,
'Access-Control-Allow-Origin': '*',
})
const fullStream = fs.createReadStream(filePath)
fullStream.on('error', () => {})
res.on('close', () => fullStream.destroy())
fullStream.pipe(res)
}
return
}
// POST /api/clips/create
if (pathname === '/api/clips/create' && req.method === 'POST') {
const data = await readBody(req)
const {
source_path,
start_time,
end_time,
game_name = 'Unknown',
audio_tracks = null,
} = data
try {
const result = await service.createClip(
source_path,
start_time,
end_time,
game_name,
audio_tracks
)
return json(res, result)
} catch (e) {
const status = e.message.includes('not found')
? 404
: e.message.includes('End time')
? 400
: 500
return json(res, { error: e.message }, status)
}
}
// POST /api/clips/trim
if (pathname === '/api/clips/trim' && req.method === 'POST') {
const data = await readBody(req)
const { source_path, start_time, end_time } = data
try {
const result = await service.trimClip(source_path, start_time, end_time)
return json(res, result)
} catch (e) {
const status = e.message.includes('not found')
? 404
: e.message.includes('End time')
? 400
: 500
return json(res, { error: e.message }, status)
}
}
// GET /api/clips/trim-status?path=...
if (pathname === '/api/clips/trim-status' && req.method === 'GET') {
const filePath = query.path
if (!filePath) return json(res, { status: 'idle' })
return json(res, service.getTrimState(filePath))
}
// POST /api/clips/trim-finalize — frontend calls this after clearing video src
if (pathname === '/api/clips/trim-finalize' && req.method === 'POST') {
const data = await readBody(req)
const { source_path } = data
try {
await service.finalizeTrim(source_path)
return json(res, { success: true })
} catch (e) {
return json(res, { error: e.message }, 500)
}
}
// POST /api/clips/delete or /api/delete
if (
(pathname === '/api/clips/delete' || pathname === '/api/delete') &&
req.method === 'POST'
) {
const data = await readBody(req)
if (!data.path) return json(res, { error: 'Not found' }, 404)
if (!isAllowedPath(data.path)) return json(res, { error: 'Forbidden' }, 403)
const result = await service.deleteFile(data.path)
return json(res, result, result.status || 200)
}
// POST /api/recordings/delete
if (pathname === '/api/recordings/delete' && req.method === 'POST') {
const data = await readBody(req)
if (!data.path) return json(res, { error: 'Not found' }, 404)
if (!isAllowedPath(data.path)) return json(res, { error: 'Forbidden' }, 403)
const result = await service.deleteFile(data.path)
return json(res, result, result.status || 200)
}
// POST /api/open-external
if (pathname === '/api/open-external' && req.method === 'POST') {
const data = await readBody(req)
if (data.path) shell.openPath(data.path)
return json(res, { success: true })
}
// POST /api/show-in-explorer
if (pathname === '/api/show-in-explorer' && req.method === 'POST') {
const data = await readBody(req)
if (data.path) shell.showItemInFolder(data.path)
return json(res, { success: true })
}
// GET /api/markers
if (pathname === '/api/markers' && req.method === 'GET') {
const filePath = query.path
const gameName = query.game_name
if (!filePath) return json(res, { error: 'Not found' }, 404)
let stat
try {
stat = fs.statSync(filePath)
} catch {
return json(res, { error: 'Not found' }, 404)
}
const duration = await getVideoDuration(filePath)
if (!duration) return json(res, { markers: [], error: 'Could not get duration' })
const fileMtime = stat.mtimeMs / 1000
const recordingStart = fileMtime - duration
const markersData = loadMarkers()
const matching = []
for (const m of markersData.markers || []) {
if (m.game_name === gameName) {
const mt = m.timestamp || 0
if (mt >= recordingStart && mt <= fileMtime) {
matching.push({
position: mt - recordingStart,
timestamp: mt,
created_at: m.created_at || '',
})
}
}
}
matching.sort((a, b) => a.position - b.position)
return json(res, { markers: matching, duration })
}
// POST /api/markers/delete
if (pathname === '/api/markers/delete' && req.method === 'POST') {
const data = await readBody(req)
const markersData = loadMarkers()
const before = markersData.markers.length
markersData.markers = markersData.markers.filter((m) => m.timestamp !== data.timestamp)
if (markersData.markers.length < before) {
saveMarkers(markersData)
return json(res, { success: true })
}
return json(res, { error: 'Not found' }, 404)
}
// GET /api/storage/stats
if (pathname === '/api/storage/stats' && req.method === 'GET') {
const recordings = service.scanRecordings()
const clips = service.scanClips()
const lockedRecordings = store.get('lockedRecordings') || []
const totalRecSize = recordings.reduce((s, r) => s + r.size_bytes, 0)
const totalClipSize = clips.reduce((s, c) => s + c.size_bytes, 0)
const totalSize = totalRecSize + totalClipSize
const games = {}
for (const r of recordings) {
if (!games[r.game_name]) games[r.game_name] = { recordings: [], clips: [], total_size: 0 }
games[r.game_name].recordings.push(r)
games[r.game_name].total_size += r.size_bytes
}
for (const c of clips) {
if (!games[c.game_name]) games[c.game_name] = { recordings: [], clips: [], total_size: 0 }
games[c.game_name].clips.push(c)
games[c.game_name].total_size += c.size_bytes
}
let diskUsage = null
const orgPath = service.getOrganizedPath()
if (orgPath && fs.existsSync(orgPath)) {
diskUsage = await getDiskUsage(orgPath)
}
return json(res, {
recordings,
clips,
total_size: totalSize,
total_size_formatted: formatFileSize(totalSize),
recording_size: totalRecSize,
recording_size_formatted: formatFileSize(totalRecSize),
clip_size: totalClipSize,
clip_size_formatted: formatFileSize(totalClipSize),
recording_count: recordings.length,
clip_count: clips.length,
games,
disk_usage: diskUsage,
locked_recordings: lockedRecordings,
})
}
// GET/POST /api/storage/settings
if (pathname === '/api/storage/settings') {
if (req.method === 'POST') {
const data = await readBody(req)
if (data.storage_settings) store.set('storageSettings', data.storage_settings)
return json(res, { success: true, settings: store.get('storageSettings') || {} })
}
return json(
res,
store.get('storageSettings') || {
auto_delete_enabled: false,
max_storage_gb: 100,
max_age_days: 30,
exclude_clips: true,
}
)
}
// POST /api/storage/lock
if (pathname === '/api/storage/lock' && req.method === 'POST') {
const data = await readBody(req)
const locked = store.get('lockedRecordings') || []
const normalized = path.normalize(data.path)
if (data.locked) {
if (!locked.includes(normalized)) locked.push(normalized)
} else {
const idx = locked.indexOf(normalized)
if (idx >= 0) locked.splice(idx, 1)
}
store.set('lockedRecordings', locked)
return json(res, { success: true, locked: data.locked })
}
// POST /api/storage/delete-batch
if (pathname === '/api/storage/delete-batch' && req.method === 'POST') {
const data = await readBody(req)
const paths = data.paths || []
const locked = (store.get('lockedRecordings') || []).map((p) => path.normalize(p))
const deleted = [],
failed = [],
skippedLocked = []
for (const p of paths) {
if (locked.includes(path.normalize(p))) {
skippedLocked.push(p)
continue
}
const result = await service.deleteFile(p)
if (result.success) deleted.push(p)
else failed.push({ path: p, error: result.error })
}
return json(res, {
success: true,
deleted,
deleted_count: deleted.length,
failed,
failed_count: failed.length,
skipped_locked: skippedLocked,
skipped_locked_count: skippedLocked.length,
})
}
// POST /api/reencode
if (pathname === '/api/reencode' && req.method === 'POST') {
const data = await readBody(req)
const {
source_path,
codec = 'h265',
crf = 23,
preset = 'medium',
replace_original = false,
original_size = 0,
audio_tracks = null,
} = data
if (!isAllowedPath(source_path)) return json(res, { error: 'Forbidden' }, 403)
if (!CODEC_MAP[codec]) return json(res, { error: `Unsupported codec: ${codec}` }, 400)
const locked = (store.get('lockedRecordings') || []).map((p) => path.normalize(p))
if (locked.includes(path.normalize(source_path)))
return json(res, { error: 'Forbidden' }, 403)
try {
const result = await service.reencodeVideo(source_path, {
codec,
crf,
preset,
replaceOriginal: replace_original,
originalSize: original_size,
audioTracks: audio_tracks,
})
return json(res, result)
} catch (e) {
const status = e.message.includes('Not found') ? 404 : 500
return json(res, { error: e.message }, status)
}
}
// GET /api/video/tracks?path=...
if (pathname === '/api/video/tracks' && req.method === 'GET') {
const filePath = query.path
if (!filePath || !isAllowedPath(filePath)) return json(res, { error: 'Forbidden' }, 403)
if (!fs.existsSync(filePath)) return json(res, { error: 'File not found' }, 404)
// Load sidecar track names if present (written during MKV→MP4 remux)
let sidecarNames = null
try {
sidecarNames = JSON.parse(fs.readFileSync(filePath + '.tracks.json', 'utf-8'))
} catch {}
return new Promise((resolve) => {
execFile(
FFPROBE_PATH,
['-v', 'error', '-show_streams', '-select_streams', 'a', '-of', 'json', filePath],
{ encoding: 'utf-8', timeout: 10000 },
(error, stdout) => {
if (error) {
resolve(json(res, { tracks: [] }))
return
}
try {
const data = JSON.parse(stdout)
const tracks = (data.streams || []).map((s, i) => ({
index: i,
stream_index: s.index ?? i,
codec_name: s.codec_name || 'unknown',
channels: s.channels || 0,
channel_layout: s.channel_layout || '',
sample_rate: s.sample_rate || '',
title: sidecarNames?.[i] || s.tags?.title || s.tags?.TITLE || `Track ${i + 1}`,
}))
resolve(json(res, { tracks }))
} catch {
resolve(json(res, { tracks: [] }))
}
}
)
})
}
// GET /api/video/waveform/chunk?path=...&track=0&start=0&end=30&totalDuration=1800&resolution=default
if (pathname === '/api/video/waveform/chunk' && req.method === 'GET') {
const filePath = query.path
const rawTrack = parseInt(query.track, 10)
const startTime = parseFloat(query.start)
const endTime = parseFloat(query.end)
const totalDuration = parseFloat(query.totalDuration)
const resolution = query.resolution || 'default'
if (isNaN(rawTrack) || rawTrack < 0) return json(res, { error: 'Invalid track index' }, 400)
if (
isNaN(startTime) ||
isNaN(endTime) ||
isNaN(totalDuration) ||
startTime < 0 ||
endTime <= startTime ||
totalDuration <= 0
)
return json(res, { error: 'Invalid time parameters' }, 400)
if (!filePath || !isAllowedPath(filePath)) return json(res, { error: 'Forbidden' }, 403)
if (!fs.existsSync(filePath)) return json(res, { error: 'File not found' }, 404)
const numPeaksTotal = getNumPeaks(resolution)
const peaksForChunk = Math.max(
1,
Math.round(numPeaksTotal * (endTime - startTime) / totalDuration)
)
const rawPeaks = await generateWaveformChunk(filePath, rawTrack, startTime, endTime, peaksForChunk)
if (!rawPeaks || !rawPeaks.length)
return json(res, { peaks: [], startTime, endTime, numPeaksTotal })
return json(res, { peaks: rawPeaks, startTime, endTime, numPeaksTotal })
}
// POST /api/video/waveform/cache
if (pathname === '/api/video/waveform/cache' && req.method === 'POST') {
const data = await readBody(req)
const { path: filePath, track, resolution } = data
const rawTrack = parseInt(track, 10)
if (isNaN(rawTrack) || rawTrack < 0) return json(res, { error: 'Invalid track index' }, 400)
if (!filePath || !isAllowedPath(filePath)) return json(res, { error: 'Forbidden' }, 403)
if (!fs.existsSync(filePath)) return json(res, { error: 'File not found' }, 404)
json(res, { status: 'accepted' }, 202)
setImmediate(async () => {
try {
const NUM_PEAKS = getNumPeaks(resolution || 'default')
const existing = getWaveform(filePath, rawTrack, NUM_PEAKS)
if (existing?.peaks?.length) return
const result = await generateWaveform(filePath, rawTrack, NUM_PEAKS, getVideoDuration)
if (result) setWaveform(filePath, rawTrack, NUM_PEAKS, result.peaks, result.duration)
} catch {}
})
return
}
// GET /api/video/waveform?path=...&track=0&resolution=default
if (pathname === '/api/video/waveform' && req.method === 'GET') {
const filePath = query.path
const rawTrack = parseInt(query.track, 10)
const resolution = query.resolution || 'default'
if (isNaN(rawTrack) || rawTrack < 0) return json(res, { error: 'Invalid track index' }, 400)
const trackIndex = rawTrack
if (!filePath || !isAllowedPath(filePath)) return json(res, { error: 'Forbidden' }, 403)
if (!fs.existsSync(filePath)) return json(res, { error: 'File not found' }, 404)
const NUM_PEAKS = getNumPeaks(resolution)
// Check cache first
const cached = getWaveform(filePath, trackIndex, NUM_PEAKS)
if (cached && cached.peaks?.length) {
return json(res, { peaks: cached.peaks, duration: cached.duration })
}
// Cache miss — signal the client to use the chunked path
const duration = await getVideoDuration(filePath)
if (!duration) return json(res, { peaks: [] })
return json(res, { status: 'miss', duration })
}
// GET /api/ffmpeg-check
if (pathname === '/api/ffmpeg-check' && req.method === 'GET') {
execFile('ffmpeg', ['-version'], { timeout: 5000 }, (err) => {
json(res, { available: !err })
})
return
}
// 404
json(res, { error: 'Not found' }, 404)
} catch (e) {
if (res.headersSent) return
if (e.message === 'Payload too large') {
json(res, { error: 'Payload too large' }, 413)
} else {
json(res, { error: e.message }, 500)
}
}
})
// In dev mode use a fixed port so vite proxy can reach us; otherwise random
// Also check for --integration-mode since those tests also need the fixed port
const isDev =
process.env.NODE_ENV === 'development' ||
process.argv.includes('--dev') ||
process.argv.includes('--integration-mode')
const listenPort = isDev ? 47531 : 0
server.listen(listenPort, '127.0.0.1', () => {
const port = server.address().port
console.log(`API server listening on http://127.0.0.1:${port}`)
})
return server
}
module.exports = { startApiServer }