-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptions.js
More file actions
354 lines (298 loc) · 11.8 KB
/
Copy pathoptions.js
File metadata and controls
354 lines (298 loc) · 11.8 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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
document.addEventListener('DOMContentLoaded', () => {
const exportDataButton = document.getElementById('export-data');
const importDataButton = document.getElementById('import-data');
const importFileInput = document.getElementById('import-file');
const clearDataButton = document.getElementById('clear-data');
const themeToggleSwitch = document.getElementById('theme-toggle');
const themeStatus = document.getElementById('theme-status');
const syncToggleSwitch = document.getElementById('sync-toggle');
const syncStatus = document.getElementById('sync-status');
const syncNowButton = document.getElementById('sync-now');
const syncStatusButton = document.getElementById('sync-status-btn');
const syncInfo = document.getElementById('sync-info');
const syncInfoContent = document.getElementById('sync-info-content');
initTheme();
initSync();
exportDataButton.addEventListener('click', async () => {
try {
const data = await chrome.storage.local.get(['scripts', 'darkMode']);
const scripts = data.scripts || {};
const darkMode = data.darkMode;
const exportData = {
version: 1,
scripts,
theme: darkMode,
exportDate: Date.now()
};
const jsonString = JSON.stringify(exportData, null, 2);
const blob = new Blob([jsonString], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `code-injection-backup-${new Date().toISOString().slice(0, 10)}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => {
URL.revokeObjectURL(url);
}, 100);
showMessage('Dados exportados com sucesso!', 'success');
} catch (error) {
console.error('Erro ao exportar dados:', error);
showMessage('Falha ao exportar dados, tente novamente.', 'error');
}
});
importDataButton.addEventListener('click', () => {
importFileInput.click();
});
importFileInput.addEventListener('change', async (event) => {
const file = event.target.files[0];
if (!file) {
return;
}
try {
const fileContent = await readFileAsText(file);
const importData = JSON.parse(fileContent);
if (!importData.scripts || typeof importData.scripts !== 'object') {
throw new Error('Formato de dados inválido');
}
if (confirm('A importação irá sobrescrever os dados de scripts existentes. Tem certeza de que deseja continuar?')) {
const dataToSave = { scripts: importData.scripts };
const themeValue = importData.theme !== undefined ? importData.theme : importData.darkMode;
if (themeValue !== undefined) {
dataToSave.darkMode = themeValue;
}
await chrome.storage.local.set(dataToSave);
if (themeValue !== undefined) {
applyTheme(themeValue);
themeToggleSwitch.checked = themeValue;
updateThemeStatusText(themeValue);
updateThemeHeaderButton(themeValue);
}
showMessage('Dados importados com sucesso!', 'success');
}
} catch (error) {
console.error('Erro na importação:', error);
showMessage(`Falha na importação: ${error.message}`, 'error');
}
importFileInput.value = '';
});
clearDataButton.addEventListener('click', async () => {
if (confirm('Tem certeza de que deseja excluir todos os scripts? Esta ação não pode ser desfeita.')) {
try {
await chrome.storage.local.set({ scripts: {} });
showMessage('Todos os scripts foram limpos!', 'success');
} catch (error) {
console.error('Erro ao limpar dados:', error);
showMessage('Falha ao limpar dados, tente novamente.', 'error');
}
}
});
function showMessage(message, type) {
const existingMessages = document.querySelectorAll('.message');
existingMessages.forEach(msg => msg.remove());
const messageElement = document.createElement('div');
messageElement.className = `message ${type}`;
messageElement.textContent = message;
document.body.appendChild(messageElement);
setTimeout(() => {
messageElement.style.opacity = '0';
setTimeout(() => messageElement.remove(), 500);
}, 3000);
}
function readFileAsText(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => resolve(event.target.result);
reader.onerror = (error) => reject(error);
reader.readAsText(file);
});
}
function initTheme() {
chrome.storage.local.get('darkMode', (data) => {
let isDarkMode;
if (data.darkMode === undefined) {
isDarkMode = true;
chrome.storage.local.set({ darkMode: true });
} else {
isDarkMode = data.darkMode === true;
}
applyTheme(isDarkMode);
themeToggleSwitch.checked = isDarkMode;
updateThemeStatusText(isDarkMode);
});
themeToggleSwitch.addEventListener('change', toggleTheme);
}
function updateThemeHeaderButton(isDarkMode) {
const themeToggleBtn = document.getElementById('toggle-theme-header');
if (themeToggleBtn) {
themeToggleBtn.innerHTML = isDarkMode ? '<span>☀️</span>' : '<span>🌙</span>';
themeToggleBtn.title = isDarkMode ? 'Alternar para modo claro' : 'Alternar para modo escuro';
}
}
function applyTheme(isDark) {
const headerIcon = document.getElementById('header-icon');
if (isDark) {
document.documentElement.setAttribute('data-theme', 'dark');
if (headerIcon) {
headerIcon.src = 'images/code-injection[dark].png';
}
} else {
document.documentElement.removeAttribute('data-theme');
if (headerIcon) {
headerIcon.src = 'images/code-injection[light].png';
}
}
updateThemeHeaderButton(isDark);
}
function updateThemeStatusText(isDarkMode) {
themeStatus.textContent = isDarkMode ? 'Ligado' : 'Desligado';
}
function toggleTheme() {
const isDarkMode = themeToggleSwitch.checked;
applyTheme(isDarkMode);
updateThemeStatusText(isDarkMode);
chrome.storage.local.set({ darkMode: isDarkMode });
updateThemeHeaderButton(isDarkMode);
}
const headerIcon = document.getElementById('header-icon');
if (headerIcon) {
headerIcon.addEventListener('click', function () {
chrome.tabs.create({ url: chrome.runtime.getURL('manager.html') });
});
}
const backBtn = document.getElementById('back-header');
if (backBtn) {
backBtn.addEventListener('click', function () {
chrome.tabs.create({ url: chrome.runtime.getURL('manager.html') });
});
}
const themeToggleBtn = document.getElementById('toggle-theme-header');
if (themeToggleBtn) {
themeToggleBtn.addEventListener('click', function () {
themeToggleSwitch.checked = !themeToggleSwitch.checked;
toggleTheme();
});
}
chrome.storage.local.get('darkMode', (data) => {
const isDarkMode = data.darkMode !== false;
updateThemeHeaderButton(isDarkMode);
});
async function initSync() {
try {
const response = await chrome.runtime.sendMessage({ action: 'getSyncStatus' });
if (response && response.success) {
const status = response.status;
syncToggleSwitch.checked = status.autoSyncEnabled;
updateSyncStatusText(status.autoSyncEnabled);
} else {
const data = await chrome.storage.local.get(['syncSettings']);
const settings = data.syncSettings || { autoSync: true };
syncToggleSwitch.checked = settings.autoSync !== false;
updateSyncStatusText(settings.autoSync !== false);
}
} catch (error) {
console.error('Erro ao inicializar sincronização:', error);
syncToggleSwitch.checked = true;
updateSyncStatusText(true);
}
syncToggleSwitch.addEventListener('change', toggleSync);
syncNowButton.addEventListener('click', syncNow);
syncStatusButton.addEventListener('click', showSyncStatus);
}
function updateSyncStatusText(isEnabled) {
syncStatus.textContent = isEnabled ? 'Ligado' : 'Desligado';
}
async function toggleSync() {
const isEnabled = syncToggleSwitch.checked;
updateSyncStatusText(isEnabled);
try {
const data = await chrome.storage.local.get(['syncSettings']);
const currentSettings = data.syncSettings || {
autoSync: true,
syncInterval: 10 * 60 * 1000,
syncProvider: 'chrome'
};
const newSettings = {
...currentSettings,
autoSync: isEnabled
};
await chrome.storage.local.set({ syncSettings: newSettings });
chrome.runtime.sendMessage({
action: 'updateSyncSettings',
settings: newSettings
});
showMessage(
isEnabled
? 'Sincronização automática habilitada!'
: 'Sincronização automática desabilitada!',
'success'
);
} catch (error) {
console.error('Erro ao alterar configuração de sincronização:', error);
showMessage('Falha ao alterar configuração de sincronização.', 'error');
syncToggleSwitch.checked = !isEnabled;
updateSyncStatusText(!isEnabled);
}
}
async function syncNow() {
syncNowButton.disabled = true;
syncNowButton.textContent = 'Sincronizando...';
try {
const response = await chrome.runtime.sendMessage({ action: 'syncNow' });
if (response && response.success) {
const result = response.result;
let message = 'Sincronização concluída!';
if (result.direction === 'cloud_to_local') {
message += ` ${result.changes.scripts} script(s) baixado(s) da nuvem.`;
} else if (result.direction === 'local_to_cloud') {
message += ` ${result.changes.scripts} script(s) enviado(s) para a nuvem.`;
}
if (result.dataTooLarge) {
message += ' (Nota: Alguns dados não foram sincronizados devido ao limite de tamanho)';
}
showMessage(message, 'success');
} else {
throw new Error(response?.error || 'Falha na sincronização');
}
} catch (error) {
console.error('Erro ao sincronizar:', error);
showMessage(`Falha na sincronização: ${error.message}`, 'error');
} finally {
syncNowButton.disabled = false;
syncNowButton.textContent = 'Sincronizar Agora';
}
}
async function showSyncStatus() {
try {
const response = await chrome.runtime.sendMessage({ action: 'getSyncStatus' });
if (response && response.success) {
const status = response.status;
let infoHtml = '<strong>Status da Sincronização</strong><br><br>';
infoHtml += `Sincronização Automática: <strong>${status.autoSyncEnabled ? 'Habilitada' : 'Desabilitada'}</strong><br>`;
infoHtml += `Provedor: <strong>${status.syncProvider || 'Chrome Sync'}</strong><br>`;
if (status.lastSyncTime) {
const lastSync = new Date(status.lastSyncTime);
infoHtml += `Última Sincronização: <strong>${lastSync.toLocaleString('pt-BR')}</strong><br>`;
} else {
infoHtml += `Última Sincronização: <strong>Nunca</strong><br>`;
}
if (status.timeUntilNextSync !== null && status.autoSyncEnabled) {
const minutes = Math.floor(status.timeUntilNextSync / 60000);
const seconds = Math.floor((status.timeUntilNextSync % 60000) / 1000);
infoHtml += `Próxima Sincronização: <strong>${minutes}min ${seconds}s</strong><br>`;
}
syncInfoContent.innerHTML = infoHtml;
syncInfo.style.display = 'block';
setTimeout(() => {
syncInfo.style.display = 'none';
}, 5000);
} else {
throw new Error(response?.error || 'Falha ao obter status');
}
} catch (error) {
console.error('Erro ao obter status de sincronização:', error);
showMessage(`Falha ao obter status: ${error.message}`, 'error');
}
}
});