dashcam 1.3.10-beta → 1.3.13-beta

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,177 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Background recording process for dashcam CLI
4
+ * This script runs detached from the parent process to handle long-running recordings
5
+ */
6
+
7
+ import { startRecording, stopRecording } from '../lib/recorder.js';
8
+ import { upload } from '../lib/uploader.js';
9
+ import { logger, setVerbose } from '../lib/logger.js';
10
+ import fs from 'fs';
11
+ import path from 'path';
12
+ import os from 'os';
13
+
14
+ // Get process directory for status files
15
+ const PROCESS_DIR = path.join(os.homedir(), '.dashcam-cli');
16
+ const STATUS_FILE = path.join(PROCESS_DIR, 'status.json');
17
+ const RESULT_FILE = path.join(PROCESS_DIR, 'upload-result.json');
18
+
19
+ // Parse options from command line argument
20
+ const optionsJson = process.argv[2];
21
+ if (!optionsJson) {
22
+ console.error('No options provided to background process');
23
+ process.exit(1);
24
+ }
25
+
26
+ const options = JSON.parse(optionsJson);
27
+
28
+ // Enable verbose logging in background
29
+ setVerbose(true);
30
+
31
+ logger.info('Background recording process started', {
32
+ pid: process.pid,
33
+ options
34
+ });
35
+
36
+ // Write status file
37
+ function writeStatus(status) {
38
+ try {
39
+ fs.writeFileSync(STATUS_FILE, JSON.stringify({
40
+ ...status,
41
+ timestamp: Date.now(),
42
+ pid: process.pid
43
+ }, null, 2));
44
+ } catch (error) {
45
+ logger.error('Failed to write status file', { error });
46
+ }
47
+ }
48
+
49
+ // Write upload result file
50
+ function writeUploadResult(result) {
51
+ try {
52
+ logger.info('Writing upload result to file', { path: RESULT_FILE, shareLink: result.shareLink });
53
+ fs.writeFileSync(RESULT_FILE, JSON.stringify({
54
+ ...result,
55
+ timestamp: Date.now()
56
+ }, null, 2));
57
+ logger.info('Successfully wrote upload result to file');
58
+ } catch (error) {
59
+ logger.error('Failed to write upload result file', { error });
60
+ }
61
+ }
62
+
63
+ // Main recording function
64
+ async function runBackgroundRecording() {
65
+ let recordingResult = null;
66
+ let isShuttingDown = false;
67
+
68
+ try {
69
+ // Start the recording
70
+ const recordingOptions = {
71
+ fps: parseInt(options.fps) || 10,
72
+ includeAudio: options.audio || false,
73
+ customOutputPath: options.output || null
74
+ };
75
+
76
+ logger.info('Starting recording with options', { recordingOptions });
77
+
78
+ recordingResult = await startRecording(recordingOptions);
79
+
80
+ // Write status to track the recording
81
+ writeStatus({
82
+ isRecording: true,
83
+ startTime: recordingResult.startTime,
84
+ options,
85
+ pid: process.pid,
86
+ outputPath: recordingResult.outputPath
87
+ });
88
+
89
+ logger.info('Recording started successfully', {
90
+ outputPath: recordingResult.outputPath,
91
+ startTime: recordingResult.startTime
92
+ });
93
+
94
+ // Set up signal handlers for graceful shutdown
95
+ const handleShutdown = async (signal) => {
96
+ if (isShuttingDown) {
97
+ logger.info('Shutdown already in progress...');
98
+ return;
99
+ }
100
+ isShuttingDown = true;
101
+
102
+ logger.info(`Received ${signal}, stopping background recording...`);
103
+
104
+ try {
105
+ // Stop the recording
106
+ const stopResult = await stopRecording();
107
+
108
+ if (stopResult) {
109
+ logger.info('Recording stopped successfully', {
110
+ outputPath: stopResult.outputPath,
111
+ duration: stopResult.duration
112
+ });
113
+
114
+ // Upload the recording
115
+ logger.info('Starting upload...');
116
+ const uploadResult = await upload(stopResult.outputPath, {
117
+ title: options.title || 'Dashcam Recording',
118
+ description: options.description || 'Recorded with Dashcam CLI',
119
+ project: options.project || options.k,
120
+ duration: stopResult.duration,
121
+ clientStartDate: stopResult.clientStartDate,
122
+ apps: stopResult.apps,
123
+ logs: stopResult.logs,
124
+ gifPath: stopResult.gifPath,
125
+ snapshotPath: stopResult.snapshotPath
126
+ });
127
+
128
+ logger.info('Upload complete', { shareLink: uploadResult.shareLink });
129
+
130
+ // Write upload result for stop command to read
131
+ writeUploadResult({
132
+ shareLink: uploadResult.shareLink,
133
+ replayId: uploadResult.replay?.id
134
+ });
135
+ }
136
+
137
+ // Update status to indicate recording stopped
138
+ writeStatus({
139
+ isRecording: false,
140
+ completedTime: Date.now(),
141
+ pid: process.pid
142
+ });
143
+
144
+ logger.info('Background process exiting successfully');
145
+ process.exit(0);
146
+ } catch (error) {
147
+ logger.error('Error during shutdown:', error);
148
+ process.exit(1);
149
+ }
150
+ };
151
+
152
+ process.on('SIGINT', () => handleShutdown('SIGINT'));
153
+ process.on('SIGTERM', () => handleShutdown('SIGTERM'));
154
+
155
+ // Keep the process alive
156
+ logger.info('Background recording is now running. Waiting for stop signal...');
157
+ await new Promise(() => {}); // Wait indefinitely for signals
158
+
159
+ } catch (error) {
160
+ logger.error('Background recording failed:', error);
161
+
162
+ // Update status to indicate failure
163
+ writeStatus({
164
+ isRecording: false,
165
+ error: error.message,
166
+ pid: process.pid
167
+ });
168
+
169
+ process.exit(1);
170
+ }
171
+ }
172
+
173
+ // Run the background recording
174
+ runBackgroundRecording().catch(error => {
175
+ logger.error('Fatal error in background process:', error);
176
+ process.exit(1);
177
+ });
@@ -0,0 +1,307 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { fileURLToPath } from 'url';
5
+ import { spawn } from 'child_process';
6
+ import { logger } from './logger.js';
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = path.dirname(__filename);
10
+
11
+ // Use a fixed directory in the user's home directory for cross-process communication
12
+ const PROCESS_DIR = path.join(os.homedir(), '.dashcam-cli');
13
+ const STATUS_FILE = path.join(PROCESS_DIR, 'status.json');
14
+ const RESULT_FILE = path.join(PROCESS_DIR, 'upload-result.json');
15
+
16
+ // Ensure process directory exists
17
+ if (!fs.existsSync(PROCESS_DIR)) {
18
+ fs.mkdirSync(PROCESS_DIR, { recursive: true });
19
+ }
20
+
21
+ class ProcessManager {
22
+ constructor() {
23
+ this.isBackgroundMode = false;
24
+ this.isStopping = false;
25
+ }
26
+
27
+ setBackgroundMode(enabled = true) {
28
+ this.isBackgroundMode = enabled;
29
+ }
30
+
31
+ writeStatus(status) {
32
+ try {
33
+ fs.writeFileSync(STATUS_FILE, JSON.stringify({
34
+ ...status,
35
+ timestamp: Date.now(),
36
+ pid: process.pid
37
+ }, null, 2));
38
+ } catch (error) {
39
+ logger.error('Failed to write status file', { error });
40
+ }
41
+ }
42
+
43
+ readStatus() {
44
+ try {
45
+ if (!fs.existsSync(STATUS_FILE)) return null;
46
+ const data = fs.readFileSync(STATUS_FILE, 'utf8');
47
+ return JSON.parse(data);
48
+ } catch (error) {
49
+ logger.error('Failed to read status file', { error });
50
+ return null;
51
+ }
52
+ }
53
+
54
+ writeUploadResult(result) {
55
+ try {
56
+ logger.info('Writing upload result to file', { path: RESULT_FILE, shareLink: result.shareLink });
57
+ fs.writeFileSync(RESULT_FILE, JSON.stringify({
58
+ ...result,
59
+ timestamp: Date.now()
60
+ }, null, 2));
61
+ logger.info('Successfully wrote upload result to file');
62
+ // Verify it was written
63
+ if (fs.existsSync(RESULT_FILE)) {
64
+ logger.info('Verified upload result file exists');
65
+ } else {
66
+ logger.error('Upload result file does not exist after write!');
67
+ }
68
+ } catch (error) {
69
+ logger.error('Failed to write upload result file', { error });
70
+ }
71
+ }
72
+
73
+ readUploadResult() {
74
+ try {
75
+ if (!fs.existsSync(RESULT_FILE)) return null;
76
+ const data = fs.readFileSync(RESULT_FILE, 'utf8');
77
+ return JSON.parse(data);
78
+ } catch (error) {
79
+ logger.error('Failed to read upload result file', { error });
80
+ return null;
81
+ }
82
+ }
83
+
84
+ isProcessRunning(pid) {
85
+ if (!pid) return false;
86
+ try {
87
+ process.kill(pid, 0); // Signal 0 just checks if process exists
88
+ return true;
89
+ } catch (error) {
90
+ return false;
91
+ }
92
+ }
93
+
94
+ isRecordingActive() {
95
+ const status = this.readStatus();
96
+
97
+ if (!status || !status.pid || !this.isProcessRunning(status.pid)) {
98
+ // Clean up but preserve upload result in case the background process just finished uploading
99
+ this.cleanup({ preserveResult: true });
100
+ return false;
101
+ }
102
+
103
+ return status.isRecording;
104
+ }
105
+
106
+ getActiveStatus() {
107
+ if (!this.isRecordingActive()) return null;
108
+ return this.readStatus();
109
+ }
110
+
111
+ cleanup(options = {}) {
112
+ const { preserveResult = false } = options;
113
+ try {
114
+ if (fs.existsSync(STATUS_FILE)) fs.unlinkSync(STATUS_FILE);
115
+ if (!preserveResult && fs.existsSync(RESULT_FILE)) fs.unlinkSync(RESULT_FILE);
116
+ } catch (error) {
117
+ logger.error('Failed to cleanup process files', { error });
118
+ }
119
+ }
120
+
121
+ async stopActiveRecording() {
122
+ if (this.isStopping) {
123
+ logger.info('Stop already in progress, ignoring additional stop request');
124
+ return false;
125
+ }
126
+
127
+ this.isStopping = true;
128
+
129
+ try {
130
+ const status = this.readStatus();
131
+
132
+ if (!status || !status.isRecording) {
133
+ logger.warn('No active recording found');
134
+ return false;
135
+ }
136
+
137
+ const pid = status.pid;
138
+ if (!pid || !this.isProcessRunning(pid)) {
139
+ logger.warn('Background process not running');
140
+ this.cleanup({ preserveResult: true });
141
+ return false;
142
+ }
143
+
144
+ logger.info('Sending stop signal to background process', { pid });
145
+
146
+ // Send SIGTERM to the background process to trigger graceful shutdown
147
+ try {
148
+ process.kill(pid, 'SIGTERM');
149
+ logger.info('Sent SIGTERM to background process');
150
+ } catch (error) {
151
+ logger.error('Failed to send signal to background process', { error });
152
+ throw new Error('Failed to stop background recording process');
153
+ }
154
+
155
+ // Wait for the background process to finish and write results
156
+ logger.debug('Waiting for background process to complete...');
157
+ const maxWaitTime = 30000; // 30 seconds
158
+ const startWait = Date.now();
159
+
160
+ while (this.isProcessRunning(pid) && (Date.now() - startWait) < maxWaitTime) {
161
+ await new Promise(resolve => setTimeout(resolve, 500));
162
+ }
163
+
164
+ if (this.isProcessRunning(pid)) {
165
+ logger.error('Background process did not exit within timeout, forcing kill');
166
+ try {
167
+ process.kill(pid, 'SIGKILL');
168
+ } catch (error) {
169
+ logger.error('Failed to force kill background process', { error });
170
+ }
171
+ }
172
+
173
+ logger.info('Background process stopped');
174
+
175
+ // Return a minimal result indicating success
176
+ // The upload will be handled by the stop command checking the result file
177
+ return {
178
+ outputPath: status.outputPath,
179
+ duration: Date.now() - status.startTime
180
+ };
181
+
182
+ } catch (error) {
183
+ logger.error('Failed to stop recording', { error });
184
+ throw error;
185
+ } finally {
186
+ this.isStopping = false;
187
+ }
188
+ }
189
+
190
+ async startRecording(options) {
191
+ // Check if recording is already active
192
+ if (this.isRecordingActive()) {
193
+ throw new Error('Recording already in progress');
194
+ }
195
+
196
+ // Spawn background process
197
+ const backgroundScriptPath = path.join(__dirname, '..', 'bin', 'dashcam-background.js');
198
+
199
+ logger.info('Starting background recording process', {
200
+ backgroundScriptPath,
201
+ options
202
+ });
203
+
204
+ // Serialize options to pass to background process
205
+ const optionsJson = JSON.stringify(options);
206
+
207
+ // Determine node executable path
208
+ const nodePath = process.execPath;
209
+
210
+ // Create log file for background process output
211
+ const logDir = path.join(PROCESS_DIR, 'logs');
212
+ if (!fs.existsSync(logDir)) {
213
+ fs.mkdirSync(logDir, { recursive: true });
214
+ }
215
+ const logFile = path.join(logDir, `recording-${Date.now()}.log`);
216
+ const logStream = fs.createWriteStream(logFile, { flags: 'a' });
217
+
218
+ logger.info('Background process log file', { logFile });
219
+
220
+ // Spawn the background process with proper detachment
221
+ const child = spawn(
222
+ nodePath,
223
+ [backgroundScriptPath, optionsJson],
224
+ {
225
+ detached: true, // Detach from parent on Unix-like systems
226
+ stdio: ['ignore', logStream, logStream], // Redirect output to log file
227
+ windowsHide: true, // Hide console window on Windows
228
+ shell: false // Don't use shell to avoid extra process wrapper
229
+ }
230
+ );
231
+
232
+ // Unref to allow parent to exit independently
233
+ child.unref();
234
+
235
+ const pid = child.pid;
236
+
237
+ logger.info('Background process spawned', {
238
+ pid,
239
+ logFile,
240
+ detached: true
241
+ });
242
+
243
+ // Wait for status file to be created by background process
244
+ logger.debug('Waiting for background process to write status file...');
245
+ const maxWaitTime = 10000; // 10 seconds
246
+ const startWait = Date.now();
247
+ let statusCreated = false;
248
+
249
+ while (!statusCreated && (Date.now() - startWait) < maxWaitTime) {
250
+ const status = this.readStatus();
251
+ if (status && status.isRecording && status.pid === pid) {
252
+ statusCreated = true;
253
+ logger.debug('Status file created by background process', { status });
254
+ break;
255
+ }
256
+ // Wait a bit before checking again
257
+ await new Promise(resolve => setTimeout(resolve, 200));
258
+ }
259
+
260
+ if (!statusCreated) {
261
+ logger.error('Background process did not create status file within timeout');
262
+ throw new Error('Failed to start background recording process - status file not created. Check log: ' + logFile);
263
+ }
264
+
265
+ // Read the status to get output path and start time
266
+ const status = this.readStatus();
267
+
268
+ logger.info('Recording started successfully in background', {
269
+ pid,
270
+ outputPath: status.outputPath,
271
+ startTime: status.startTime,
272
+ logFile
273
+ });
274
+
275
+ return {
276
+ pid,
277
+ outputPath: status.outputPath,
278
+ startTime: status.startTime,
279
+ logFile
280
+ };
281
+ }
282
+
283
+ async gracefulExit() {
284
+ logger.info('Graceful exit requested');
285
+
286
+ // If we're currently recording, stop it properly
287
+ if (this.isRecordingActive()) {
288
+ try {
289
+ logger.info('Stopping active recording before exit');
290
+ await this.stopActiveRecording();
291
+ logger.info('Recording stopped successfully during graceful exit');
292
+ } catch (error) {
293
+ logger.error('Failed to stop recording during graceful exit', { error });
294
+ this.cleanup(); // Fallback cleanup
295
+ }
296
+ } else {
297
+ // Just cleanup if no recording is active
298
+ this.cleanup();
299
+ }
300
+
301
+ process.exit(0);
302
+ }
303
+ }
304
+
305
+ const processManager = new ProcessManager();
306
+
307
+ export { processManager };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dashcam",
3
- "version": "1.3.10-beta",
3
+ "version": "1.3.13-beta",
4
4
  "description": "Minimal CLI version of Dashcam desktop app",
5
5
  "main": "bin/dashcam.js",
6
6
  "bin": {