-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
172 lines (146 loc) · 5.64 KB
/
index.js
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
const ffmpeg = require('fluent-ffmpeg');
const fs = require('fs-extra');
const path = require('path');
const moment = require('moment-timezone');
const configPath = 'config.json';
if (!fs.existsSync(configPath)) {
console.error("No config file ", configPath, " found");
process.exit(1);
}
let config = {};
try {
const configContent = fs.readFileSync(configPath, 'utf8');
config = JSON.parse(configContent);
} catch (error) {
console.error('Error while reading config:', error);
}
const rtspUrl = config.rtspUrl;
const baseRecordingsDirectory = config.recordingsDirectory;
const segmentTime = config.segmentTimeSeconds || 120;
// start recording
console.log('Starting recording.');
startRecording();
monitorDiskSpace();
function startRecording() {
const localTimeZone = config.timeZone || 'Europe/Warsaw';
const startTimestamp = moment().tz(localTimeZone);
const dateFolder = startTimestamp.format('YYYY.MM.DD');
const timeFilename = startTimestamp.format('HH-mm-ss');
const recordingsDirectory = path.join(baseRecordingsDirectory, dateFolder);
// create recordings directory if not exists
fs.ensureDirSync(recordingsDirectory);
const outputPath = path.join(recordingsDirectory, `${timeFilename}.mkv`);
currentRecording = ffmpeg(rtspUrl)
.inputFormat('rtsp')
.videoCodec('libx264')
.audioCodec('aac')
.outputOptions([
'-reset_timestamps', '1',
'-rtsp_transport', 'tcp',
])
.output(outputPath)
.on('end', () => {
console.log('Recording ended, starting a new one.');
setTimeout(() => {
startRecording();
}, 50);
})
.on('error', (err) => {
var errorMessage = err.message.replace(rtspUrl, '***URL REMOVED***');
console.error('Error during recording:', errorMessage);
setTimeout(() => {
startRecording();
}, 50);
});
// stop recording after x seconds
setTimeout(() => {
console.log('Stopping segment..');
stopRecording();
}, segmentTime * 1000);
currentRecording.run();
}
function stopRecording() {
if (currentRecording) {
currentRecording.ffmpegProc.stdin.write('q');
currentRecording.ffmpegProc.stdin.end();
console.log('Recording stopped.');
}
}
function monitorDiskSpace() {
const interval = 5 * 1000;
setInterval(async () => {
const spaceThresholdMB = config.diskSpaceThresholdMb; // max size of folder in MB
try {
const files = await fs.promises.readdir(config.recordingsDirectory);
const folderSizeMB = await calculateFolderSize(files, config.recordingsDirectory) / (1024 * 1024); // to MB
console.log(`Folder size: ${folderSizeMB}MB`);
if (folderSizeMB > spaceThresholdMB) {
console.log(`Folder size exceeds ${spaceThresholdMB}MB. Deleting oldest files.`);
await removeOldestFile(config.recordingsDirectory);
}
} catch (error) {
console.error('Error while reading folder size ', error);
}
}, interval);
}
async function calculateFolderSize(files, folderPath) {
let size = 0;
for (const file of files) {
const filePath = path.join(folderPath, file);
const stats = await fs.promises.stat(filePath);
if (stats.isDirectory()) {
const subFiles = await fs.promises.readdir(filePath);
size += await calculateFolderSize(subFiles, filePath);
} else {
size += stats.size;
}
}
return size;
}
async function removeOldestFile(baseDirectory) {
try {
const folders = await fs.readdir(baseDirectory);
if (folders.length > 0) {
const oldestFolder = folders.reduce((oldest, folder) => {
const folderPath = path.join(baseDirectory, folder);
const stats = fs.statSync(folderPath);
if (stats.isDirectory()) {
return stats.birthtimeMs < oldest.stats.birthtimeMs ? { folder, stats } : oldest;
} else {
return oldest;
}
}, { folder: null, stats: { birthtimeMs: Infinity } });
if (oldestFolder.folder) {
const folderPath = path.join(baseDirectory, oldestFolder.folder);
const filesInFolder = await fs.readdir(folderPath);
if (filesInFolder.length > 0) {
const oldestFile = filesInFolder.reduce((oldest, file) => {
const filePath = path.join(folderPath, file);
const stats = fs.statSync(filePath);
return stats.birthtimeMs < oldest.stats.birthtimeMs ? { file, stats } : oldest;
}, { file: null, stats: { birthtimeMs: Infinity } });
if (oldestFile.file) {
await fs.unlink(path.join(folderPath, oldestFile.file));
console.log('Oldest file in oldest folder was deleted: ', oldestFile.file);
// check if folder is empty
const isFolderEmpty = (await fs.readdir(folderPath)).length === 0;
if (isFolderEmpty) {
await fs.rmdir(folderPath);
console.log('Oldest folder was empty so it was deleted', oldestFolder.folder);
}
} else {
console.log('No files to delete in oldest folder');
}
} else {
console.log('Oldest folder is empty, no files to delete');
}
} else {
console.log('No folders to delete');
}
} else {
console.log('No folders to delete');
}
} catch (err) {
console.error('Error reading dictionary ', err);
}
}