-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
357 lines (329 loc) · 14.6 KB
/
background.js
File metadata and controls
357 lines (329 loc) · 14.6 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
355
356
357
// Create context menu when extension is installed
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.removeAll(() => {
chrome.contextMenus.create({
id: "scrapeAssignment",
title: "📝 Export to Markdown",
contexts: ["all"],
documentUrlPatterns: ["https://seek.onlinedegree.iitm.ac.in/*", "https://score-checker-379619009600.asia-south1.run.app/*"]
});
chrome.contextMenus.create({
id: "unlockPage",
title: "🔓 Unlock Editor/Copy-Paste",
contexts: ["all"],
documentUrlPatterns: ["https://seek.onlinedegree.iitm.ac.in/*", "https://score-checker-379619009600.asia-south1.run.app/*"]
});
// Top-level UI Management (No nesting as requested)
chrome.contextMenus.create({
id: "toggleCleanMode",
title: "🪄 Toggle Clean UI (All)",
contexts: ["all"],
documentUrlPatterns: ["https://seek.onlinedegree.iitm.ac.in/*"]
});
chrome.contextMenus.create({
id: "toggleFocusBar",
title: "⏱️ Toggle Focus Bar",
contexts: ["all"],
documentUrlPatterns: ["https://seek.onlinedegree.iitm.ac.in/*"]
});
chrome.contextMenus.create({
id: "toggleProgress",
title: "📊 Toggle Progress Tracker",
contexts: ["all"],
documentUrlPatterns: ["https://seek.onlinedegree.iitm.ac.in/*"]
});
// Curriculum Archiver — only shows on the public academics page
chrome.contextMenus.create({
id: "archiveCurriculum",
title: "📚 Archive Full Curriculum (IITM)",
contexts: ["all"],
documentUrlPatterns: ["https://study.iitm.ac.in/ds/academics.html*"]
});
// Capture selection (Only shows when something is highlighted)
chrome.contextMenus.create({
id: "sendToNotes",
title: "📝 Send Selected to Notes",
contexts: ["selection"],
documentUrlPatterns: ["https://seek.onlinedegree.iitm.ac.in/*"]
});
});
});
// Helper to unlock editors and events
function unlockPage(tabId) {
chrome.scripting.executeScript({
target: { tabId: tabId },
world: 'MAIN',
func: () => {
const doUnlock = () => {
document.querySelectorAll('.ace_editor').forEach(el => {
try {
const editor = el.env?.editor || (typeof ace !== 'undefined' ? ace.edit(el) : null);
if (editor) {
// Persistence: Force readonly to false even if the site tries to re-lock it
editor.setReadOnly(false);
editor.setOptions({
readOnly: false,
enableBasicAutocompletion: true,
enableLiveAutocompletion: true
});
if (!editor.__unlocked) {
editor.__unlocked = true;
const originalSetReadOnly = editor.setReadOnly;
editor.setReadOnly = function(ro) {
return originalSetReadOnly.call(this, false);
};
// Reset shortcuts if they were blocked
editor.commands.addCommand({
name: 'undo',
bindKey: {win: 'Ctrl-Z', mac: 'Command-Z'},
exec: (editor) => { if(editor.undoManager) editor.undoManager.undo(); else editor.undo(); }
});
editor.commands.addCommand({
name: 'redo',
bindKey: {win: 'Ctrl-Y|Ctrl-Shift-Z', mac: 'Command-Shift-Z'},
exec: (editor) => { if(editor.undoManager) editor.undoManager.redo(); else editor.redo(); }
});
editor.textInput.getElement().removeAttribute('readonly');
editor.textInput.getElement().disabled = false;
}
}
} catch(e) {}
// Force the underlying textarea properties
el.querySelectorAll('textarea').forEach(ta => {
ta.removeAttribute('readonly');
ta.readOnly = false;
ta.disabled = false;
ta.style.pointerEvents = 'auto';
ta.style.opacity = '1';
});
el.classList.remove('ace_readonly');
el.classList.remove('readonly');
});
// True Native Cut/Copy/Paste mapped directly via AceEditor memory APIs
window.addEventListener('keydown', (e) => {
const isMeta = e.ctrlKey || e.metaKey;
if (!isMeta) return;
const key = e.key.toLowerCase();
if (key === 'c' || key === 'x') {
document.querySelectorAll('.ace_editor').forEach(el => {
try {
const editor = el.env?.editor || (typeof ace !== 'undefined' ? ace.edit(el) : null);
if (editor && editor.isFocused()) {
let text = '';
try { text = editor.getCopyText(); } catch(e) {}
if (!text || text.length === 0) {
const fallbackTA = el.querySelector('textarea.ace_text-input');
if (fallbackTA) text = fallbackTA.value;
}
if (text) navigator.clipboard.writeText(text).catch(()=>{});
if (key === 'x') editor.execCommand('backspace'); // Native cut removal
e.preventDefault(); e.stopPropagation();
}
} catch(err) {}
});
} else if (key === 'v') {
// Suppress the V keystroke from Angular anti-cheat monitors
// Chrome will then inherently follow up with a native 'paste' event cascading down
// directly into the AceEditor where it is natively absorbed!
e.stopPropagation();
}
}, true);
// Obliterate Site-Wide Right-Click Blockers
document.oncontextmenu = null;
if (document.body) document.body.oncontextmenu = null;
window.addEventListener('contextmenu', (e) => e.stopPropagation(), true);
};
doUnlock();
let count = 0;
const interval = setInterval(() => {
doUnlock();
if (++count > 20) clearInterval(interval);
}, 2000);
console.log('🔓 Ultimate Unlocker Active!');
}
});
}
// Listen for keyboard shortcuts
chrome.commands.onCommand.addListener((command) => {
if (command === "unlock_page") {
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
if (tabs[0]?.id) unlockPage(tabs[0].id);
});
}
});
// Function to execute the scraper
function executeScaper(tabId, mode = 'single', title = null, token = null) {
if (tabId) {
chrome.scripting.executeScript({
target: { tabId: tabId },
func: (m, t, tk) => {
window.__scraperMode = m;
window.__bulkScrapeTitle = t; // New: Pass real sidebar title
window.__bulkScrapeToken = tk;
console.log('IITM Background: Mode set to', m);
},
args: [mode, title, token]
}).then(() => {
chrome.scripting.executeScript({
target: { tabId: tabId },
files: ['scripts/scraper.js']
});
});
}
}
// Helper to create Offscreen document for ZIP generation
async function setupOffscreen() {
const existing = await chrome.offscreen.hasDocument();
if (existing) return;
await chrome.offscreen.createDocument({
url: 'docs/offscreen.html',
reasons: ['DOM_SCRAPING'],
justification: 'Generate ZIP file for course export'
});
}
// RELAY MESSAGE TO OFFSCREEN
async function relayToOffscreen(msg) {
await setupOffscreen();
chrome.runtime.sendMessage(msg);
}
// Listen for messages from content scripts
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'triggerScraper' && sender.tab) {
executeScaper(sender.tab.id, request.mode || 'single', request.title, request.token || null);
sendResponse({ success: true });
return true;
} else if (request.action === 'fetchScores') {
const scoreCheckerUrl = request.url || 'https://score-checker-379619009600.asia-south1.run.app/course_wise';
fetch(scoreCheckerUrl, {
method: 'GET',
credentials: 'include',
redirect: 'follow'
})
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.text();
})
.then(html => {
if (html.includes('accounts.google.com')) {
throw new Error('Authentication Required. Please log in to the Score Checker first.');
}
sendResponse({ success: true, data: html });
})
.catch(err => sendResponse({ success: false, error: err.message }));
return true;
} else if (request.action === 'syncAce' && sender.tab) {
chrome.scripting.executeScript({
target: { tabId: sender.tab.id },
world: 'MAIN',
func: () => {
document.querySelectorAll('.ace_editor').forEach(el => {
try {
const editor = el.env?.editor || (typeof ace !== 'undefined' ? ace.edit(el) : null);
if (editor) {
const val = editor.getValue();
el.setAttribute('data-full-code', val);
const mode = editor.getSession().getMode().$id;
if (mode) el.setAttribute('data-ace-mode', mode.split('/').pop());
const ta = el.querySelector('textarea.ace_text-input');
if (ta) ta.value = val;
editor.setReadOnly(false);
}
} catch(e) {}
});
}
}).then(() => {
sendResponse({ success: true });
}).catch((err) => {
sendResponse({ success: false, error: err.message });
});
return true;
} else if (request.action === 'unlockPage' && sender.tab) {
unlockPage(sender.tab.id);
sendResponse({ success: true });
return true;
} else if (request.action === 'generateZip') {
relayToOffscreen(request)
.then(() => sendResponse({ success: true }))
.catch(err => sendResponse({ success: false, error: err.message }));
return true;
} else if (request.action === 'indexTranscript') {
chrome.storage.local.get(['iitm_transcripts'], (result) => {
const transcripts = result.iitm_transcripts || [];
// Check if already indexed
const exists = transcripts.some(t => t.url === request.data.url);
if (!exists) {
transcripts.push({
title: request.data.title,
course: request.data.course,
url: request.data.url,
text: request.data.text.substring(0, 5000), // Cap size
timestamp: Date.now()
});
chrome.storage.local.set({ iitm_transcripts: transcripts });
}
});
sendResponse({ success: true });
} else if (request.action === 'fetchBlob' && request.url) {
fetch(request.url)
.then(res => res.blob())
.then(blob => {
const reader = new FileReader();
reader.onloadend = () => sendResponse({ success: true, data: reader.result });
reader.readAsDataURL(blob);
})
.catch(err => sendResponse({ success: false, error: err.message }));
return true;
} else if (request.action === 'fetchRelay' && request.url) {
const options = {
method: request.method || 'GET',
headers: request.headers || {}
};
if (request.body) options.body = request.body;
fetch(request.url, options)
.then(res => {
if (res.url.includes('accounts.google.com')) {
throw new Error('Authentication Required. Please log in to the Score Checker first.');
}
return res.text();
})
.then(html => sendResponse({ success: true, data: html }))
.catch(err => sendResponse({ success: false, error: err.message }));
return true;
} else if (request.action === 'reloadExtension') {
chrome.runtime.reload();
sendResponse({ success: true });
return true;
}
});
// Inject the curriculum archiver on-demand (JSZip first, then the scraper)
function launchCurriculumArchiver(tabId) {
// Step 1: inject the already-bundled jszip.min.js (same one used by the portal)
chrome.scripting.executeScript({
target: { tabId },
files: ['jszip.min.js']
}).then(() => {
// Step 2: inject the curriculum scraper script
chrome.scripting.executeScript({
target: { tabId },
files: ['scripts/curriculum_scraper.js']
});
}).catch(err => {
console.error('[Archiver] Injection failed:', err);
});
}
chrome.action.onClicked.addListener((tab) => {
executeScaper(tab.id);
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "scrapeAssignment") {
executeScaper(tab.id);
} else if (info.menuItemId === "unlockPage") {
unlockPage(tab.id);
} else if (["toggleCleanMode", "toggleFocusBar", "toggleNotesBtn", "toggleProgress"].includes(info.menuItemId)) {
chrome.tabs.sendMessage(tab.id, { action: info.menuItemId });
} else if (info.menuItemId === "sendToNotes") {
chrome.tabs.sendMessage(tab.id, { action: "sendToNotes", selectionText: info.selectionText });
} else if (info.menuItemId === "archiveCurriculum") {
launchCurriculumArchiver(tab.id);
}
});