-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
197 lines (173 loc) · 4.76 KB
/
background.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
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
// Constants for recording settings
const DEFAULT_SETTINGS = {
quality: '1080p',
audioEnabled: true,
fileFormat: 'webm',
};
const QUALITY_PRESETS = {
'720p': { width: 1280, height: 720, bitrate: 2500000 },
'1080p': { width: 1920, height: 1080, bitrate: 5000000 },
'4k': { width: 3840, height: 2160, bitrate: 15000000 },
};
// State management
let activeRecording = null;
let recordingStream = null;
let mediaRecorder = null;
let recordedChunks = [];
let startTime = 0;
let pauseTime = 0;
let isPaused = false;
// Initialize extension
chrome.runtime.onInstalled.addListener(async () => {
await chrome.storage.local.set({ settings: DEFAULT_SETTINGS });
});
// Handle commands (keyboard shortcuts)
chrome.commands.onCommand.addListener((command) => {
switch (command) {
case 'start-stop-recording':
if (activeRecording) {
stopRecording();
} else {
startRecording();
}
break;
case 'pause-resume-recording':
if (activeRecording) {
togglePause();
}
break;
}
});
// Message handling from popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
switch (message.action) {
case 'START_RECORDING':
startRecording(message.options);
sendResponse({ success: true });
break;
case 'STOP_RECORDING':
stopRecording();
sendResponse({ success: true });
break;
case 'TOGGLE_PAUSE':
togglePause();
sendResponse({ success: true });
break;
case 'GET_STATUS':
sendResponse({
isRecording: !!activeRecording,
isPaused,
duration: getRecordingDuration(),
});
break;
}
return true;
});
// Recording functions
async function startRecording(options = {}) {
try {
const settings = await chrome.storage.local.get('settings');
const quality = QUALITY_PRESETS[settings.settings.quality || '1080p'];
const streamConstraints = {
audio: settings.settings.audioEnabled,
video: {
...quality,
displaySurface: 'monitor',
}
};
const stream = await navigator.mediaDevices.getDisplayMedia(streamConstraints);
recordingStream = stream;
const mimeType = 'video/webm;codecs=vp9';
mediaRecorder = new MediaRecorder(stream, {
mimeType,
videoBitsPerSecond: quality.bitrate
});
mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.onstop = handleRecordingStop;
recordedChunks = [];
startTime = Date.now();
pauseTime = 0;
isPaused = false;
activeRecording = true;
mediaRecorder.start(1000); // Capture chunks every second
broadcastStatus();
} catch (error) {
console.error('Error starting recording:', error);
cleanup();
}
}
function stopRecording() {
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
recordingStream.getTracks().forEach(track => track.stop());
}
}
function togglePause() {
if (!mediaRecorder) return;
if (mediaRecorder.state === 'recording') {
mediaRecorder.pause();
pauseTime = Date.now();
isPaused = true;
} else if (mediaRecorder.state === 'paused') {
mediaRecorder.resume();
startTime += (Date.now() - pauseTime);
isPaused = false;
}
broadcastStatus();
}
function handleDataAvailable(event) {
if (event.data.size > 0) {
recordedChunks.push(event.data);
}
}
async function handleRecordingStop() {
const blob = new Blob(recordedChunks, { type: 'video/webm' });
const url = URL.createObjectURL(blob);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = `screen-recording-${timestamp}.webm`;
try {
const downloadId = await chrome.downloads.download({
url: url,
filename: filename,
saveAs: true
});
console.log('Download started:', downloadId);
} catch (error) {
console.error('Download failed:', error);
}
cleanup();
}
function cleanup() {
activeRecording = null;
recordingStream = null;
mediaRecorder = null;
recordedChunks = [];
startTime = 0;
pauseTime = 0;
isPaused = false;
broadcastStatus();
}
function getRecordingDuration() {
if (!startTime) return 0;
const pauseDuration = pauseTime ? (Date.now() - pauseTime) : 0;
return isPaused ? (pauseTime - startTime) : (Date.now() - startTime - pauseDuration);
}
function broadcastStatus() {
const status = {
action: 'STATUS_UPDATE',
status: {
isRecording: !!activeRecording,
isPaused,
duration: getRecordingDuration()
}
};
try {
chrome.runtime.sendMessage(status).catch(() => {
// Ignore errors when popup is closed
console.debug('Failed to broadcast status - popup might be closed');
});
} catch (error) {
// Handle any synchronous errors
console.debug('Failed to broadcast status:', error);
}
}