-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
236 lines (216 loc) · 9.36 KB
/
Copy pathbackground.js
File metadata and controls
236 lines (216 loc) · 9.36 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
// Define the API base URL
const API_BASE_URL = 'https://ff61-2601-645-8700-5460-38ac-1b89-3e3a-f547.ngrok-free.app'; // Replace with your actual API base URL
// Initialize the recordedActions array and recordingId
let recordedActions = [];
let recordingId = null;
let isRecording = false;
// Initialize state from storage when background script loads
chrome.storage.local.get(['recordingId', 'isRecording'], (result) => {
recordingId = result.recordingId || null;
isRecording = result.isRecording || false;
});
// Function to get IP address
async function getIPAddress() {
try {
const response = await fetch('https://api.ipify.org?format=json');
const data = await response.json();
return data.ip;
} catch (error) {
console.error('Error fetching IP:', error);
return null;
}
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === 'getRecordingState') {
sendResponse({ isRecording: isRecording });
return true;
}
if (request.message === 'startRecording') {
recordedActions = [];
getIPAddress().then(ipAddress => {
fetch(`${API_BASE_URL}/studio/start_recording`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
studio_id: 1,
ip_address: ipAddress || 'unknown'
})
})
.then(response => response.json())
.then(data => {
if (data.recording_id) {
recordingId = data.recording_id;
isRecording = true;
// Store the state
chrome.storage.local.set({
recordingId: recordingId,
isRecording: isRecording
});
console.log('Recording started with ID:', recordingId);
// Inject the content script into the active tab
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs.length > 0) {
const activeTab = tabs[0];
const url = activeTab.url;
// Check if the URL is allowed for script injection
if (!url.startsWith('chrome://') && !url.startsWith('chrome-extension://')) {
chrome.scripting.executeScript({
target: { tabId: activeTab.id },
files: ['content.js']
}, () => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
sendResponse({ success: false });
} else {
sendResponse({ success: true });
}
});
} else {
console.error('Cannot inject scripts into chrome:// URLs');
sendResponse({ success: false, error: 'Cannot inject scripts into chrome:// URLs' });
}
} else {
sendResponse({ success: false, error: 'No active tab found.' });
}
});
} else {
console.error('Failed to start recording:', data.error);
sendResponse({ success: false, error: data.error || 'Failed to start recording.' });
}
})
.catch(error => {
console.error('Error starting recording:', error);
sendResponse({ success: false, error: 'Error starting recording.' });
});
});
return true; // Keeps the message channel open for sendResponse
} else if (request.message === 'getRecordedActions') {
// Send the recordedActions array to the popup
sendResponse({ actions: recordedActions });
return true; // Keeps the message channel open for sendResponse
} else if (request.actionType === 'type' || request.actionType === 'click' ||
request.actionType === 'keydown' || request.actionType === 'input' ||
request.actionType === 'specialKey') { // Add specialKey to the list
if (!recordingId) {
console.error('No active recording session.');
return false;
}
let action;
if (request.actionType === 'specialKey') { // Handle specialKey type
action = {
type: 'specialKey',
details: request.details,
timestamp: new Date().toISOString()
};
} else if (request.actionType === 'click') {
action = {
type: 'click',
details: request.details,
timestamp: new Date().toISOString()
};
} else if (request.actionType === 'input') {
action = {
type: 'input',
details: request.details,
timestamp: new Date().toISOString()
};
}
if (action) {
recordedActions.push(action);
console.log(`${action.type} action recorded:`, action.details);
// Capture screenshot and send action
chrome.tabs.captureVisibleTab(sender.tab.windowId, { format: 'png' }, (dataUrl) => {
if (chrome.runtime.lastError) {
console.error('Error capturing screenshot:', chrome.runtime.lastError.message);
} else {
action.screenshot = dataUrl;
fetch(`${API_BASE_URL}/studio/save_ui_action`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
recording_id: recordingId,
action: action
})
})
.then(response => response.json())
.then(data => {
if (data.message !== 'Action saved successfully') {
console.error('Failed to save action with screenshot:', data.message);
}
})
.catch(error => {
console.error('Error saving action with screenshot:', error);
});
}
});
}
return true;
} else if (request.message === 'stopRecording') {
if (!recordingId) {
console.error('No active recording session to stop.');
sendResponse({ success: false, error: 'No active recording session.' });
return true;
}
fetch(`${API_BASE_URL}/studio/stop_recording`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
recording_id: recordingId,
name: request.recordingName
})
})
.then(response => response.json())
.then(data => {
recordingId = null;
isRecording = false;
// Clear the stored state
chrome.storage.local.remove(['recordingId', 'isRecording']);
if (data.message === 'Recording stopped and marked as COMPLETED') {
console.log('Recording stopped successfully.');
sendResponse({
success: true,
message: data.message,
recordingName: request.recordingName
});
} else {
console.error('Failed to stop recording:', data.message);
sendResponse({ success: false, error: data.message || 'Failed to stop recording.' });
}
})
.catch(error => {
recordingId = null;
isRecording = false;
// Clear the stored state even on error
chrome.storage.local.remove(['recordingId', 'isRecording']);
console.error('Error stopping recording:', error);
sendResponse({ success: false, error: 'Error stopping recording.' });
});
return true; // Keeps the message channel open for sendResponse
} else {
// Handle other actionTypes if necessary
recordedActions.push({
type: request.actionType,
details: request.details,
timestamp: new Date().toISOString()
});
console.log('Action recorded:', request.actionType, request.details);
}
});
// Function to record keydown actions
function recordKeydownAction(details) {
// Implement the logic to record keydown actions
console.log('Keydown Action Recorded:', details);
// You can store these details as needed
}
// Function to record click actions
function recordClickAction(details) {
// Implement the logic to record click actions
console.log('Click Action Recorded:', details);
// You can store these details as needed
}