-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
154 lines (132 loc) · 4.86 KB
/
Copy pathserver.js
File metadata and controls
154 lines (132 loc) · 4.86 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
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const VIDEO_DIR = process.env.VIDEO_DIR || '/videos';
const PORT = process.env.PORT || 3000;
const RESOLVED_VIDEO_DIR = path.resolve(VIDEO_DIR);
function safeVideoPath(...parts) {
for (const part of parts) {
if (!part || /[/\\]/.test(part) || part.includes('..')) return null;
}
const resolved = path.resolve(path.join(RESOLVED_VIDEO_DIR, ...parts));
return resolved.startsWith(RESOLVED_VIDEO_DIR + path.sep) ? resolved : null;
}
// Serve index.html
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// List cameras
app.get('/api/cameras', async (req, res) => {
try {
let entries;
try {
entries = await fs.promises.readdir(VIDEO_DIR, { withFileTypes: true });
} catch {
return res.json([]);
}
const cameras = entries
.filter(d => d.isDirectory() && !d.name.startsWith('.'))
.map(d => ({
id: d.name,
name: d.name.replace(/_/g, ' ').split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(' ')
}));
res.json(cameras.length > 0 ? cameras : [{ id: 'default', name: 'Camera' }]);
} catch (error) {
console.error('Error listing cameras:', error);
res.status(500).json({ error: 'Failed to list cameras' });
}
});
// List videos for camera and date
app.get('/api/videos/:camera/:date', async (req, res) => {
try {
const { camera } = req.params;
const dateMatch = req.params.date.match(/^(\d{4})-(\d{2})-(\d{2})$/);
if (!dateMatch) return res.status(400).json({ error: 'Invalid date format' });
const [, year, month, day] = dateMatch;
const dayDir = safeVideoPath(camera, year, month, day);
if (!dayDir) return res.status(400).json({ error: 'Invalid path' });
let fileNames;
try {
fileNames = await fs.promises.readdir(dayDir);
} catch {
return res.json([]);
}
const results = await Promise.all(
fileNames
.filter(f => /\.(mp4|avi|mkv)$/i.test(f))
.map(async f => {
const filePath = path.join(dayDir, f);
const stat = await fs.promises.stat(filePath);
// Parse Reolink filename: ReolinkDuo2PoE_00_YYYYMMDDHHMMSS.mp4
const match = f.match(/_(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\./);
if (!match) return null;
const timestamp = new Date(match[1], match[2] - 1, match[3], match[4], match[5], match[6]).getTime();
// Rough duration estimate assuming ~8 Mbps bitrate (~1 MB/s)
const duration = Math.round(stat.size / (1024 * 1024));
return {
filename: f,
url: `/video/${camera}/${year}/${month}/${day}/${encodeURIComponent(f)}`,
timestamp,
time: `${match[4]}:${match[5]}:${match[6]}`,
size: stat.size,
duration
};
})
);
res.json(results.filter(Boolean).sort((a, b) => a.timestamp - b.timestamp));
} catch (error) {
console.error('Error listing videos:', error);
res.status(500).json({ error: 'Failed to list videos' });
}
});
// Stream or download video
app.get('/video/:camera/:year/:month/:day/:filename', async (req, res) => {
try {
const { camera, year, month, day } = req.params;
const filename = path.basename(req.params.filename);
const filePath = safeVideoPath(camera, year, month, day, filename);
if (!filePath) return res.status(400).send('Invalid path');
let stat;
try {
stat = await fs.promises.stat(filePath);
} catch {
return res.status(404).send('Video not found');
}
const fileSize = stat.size;
const range = req.headers.range;
if (req.query.download === 'true') {
res.writeHead(200, {
'Content-Length': fileSize,
'Content-Type': 'video/mp4',
'Content-Disposition': `attachment; filename="${filename}"`
});
fs.createReadStream(filePath).pipe(res);
} else if (range) {
const parts = range.replace(/bytes=/, '').split('-');
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunksize = end - start + 1;
res.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4'
});
fs.createReadStream(filePath, { start, end }).pipe(res);
} else {
res.writeHead(200, {
'Content-Length': fileSize,
'Content-Type': 'video/mp4'
});
fs.createReadStream(filePath).pipe(res);
}
} catch (error) {
console.error('Error handling video:', error);
res.status(500).send('Error handling video');
}
});
app.listen(PORT, () => {
console.log(`LocalNVR running on http://localhost:${PORT}`);
console.log(`Video directory: ${VIDEO_DIR}`);
});