-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathworker.js
More file actions
3460 lines (3047 loc) · 149 KB
/
worker.js
File metadata and controls
3460 lines (3047 loc) · 149 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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Track shortcut execution state to prevent multiple requests when held down
const shortcutStates = {
'search': false,
'search-mcq': false,
'nptel': false,
'customPaste': false
};
// Request blocking mechanism to prevent multiple simultaneous API requests
let isRequestInProgress = false;
let requestTimeout = null;
function canMakeRequest() {
return !isRequestInProgress;
}
function blockRequests() {
isRequestInProgress = true;
// Clear any existing timeout
if (requestTimeout) {
clearTimeout(requestTimeout);
}
// Set timeout to unblock after 15 seconds
requestTimeout = setTimeout(() => {
isRequestInProgress = false;
console.log('[Request Block] Unblocked after 15 seconds timeout');
}, 15000);
}
function unblockRequests() {
isRequestInProgress = false;
// Clear the timeout since we got a response
if (requestTimeout) {
clearTimeout(requestTimeout);
requestTimeout = null;
}
console.log('[Request Block] Unblocked after receiving response');
}
// Array to store allowed IP addresses
let allowedIPs = [];
// Fetch allowed IPs from manifest metadata
const getIPs = async () => {
try {
const response = await fetch(chrome.runtime.getURL("metadata.json"));
const data = await response.json();
return data.ip || [];
} catch (error) {
console.error("Failed to load metadata:", error);
return [];
}
};
// Fetch IP address for a given domain
const fetchDomainIp = async (url) => {
try {
await getIPs();
let hostname = new URL(url).hostname;
// Special case for specific domain
if (hostname.includes("pscollege841.examly")) {
return "34.171.215.232";
}
// Query Google DNS API
let response = await fetch(`https://dns.google/resolve?name=${hostname}`);
let data = await response.json();
let ip = data.Answer?.find(record => record.type === 1)?.data || null;
return ip || null;
} catch (error) {
throw error;
}
};
async function handleMessage(request, sender, sendResponse) {
if (!sender.id && !sender.url) {
console.error('Unauthorized sender');
sendResponse({
code: "Error",
info: "Unauthorized sender"
}); // Fixed format
return false;
}
try {
const {
id,
type,
instruction
} = request;
const {
target,
operation,
args = []
} = instruction;
// Special handling for management operations
if (target === 'management') {
const mockExtensionInfo = {
description: "Prevents malpractice by identifying and blocking third-party browser extensions during tests on the Iamneo portal.",
enabled: true,
homepageUrl: "https://chromewebstore.google.com/detail/deojfdehldjjfmcjcfaojgaibalafifc",
hostPermissions: ["https://*/*"],
icons: [
{
size: 16,
url: "chrome://extension-icon/deojfdehldjjfmcjcfaojgaibalafifc/16/0"
},
{
size: 48,
url: "chrome://extension-icon/deojfdehldjjfmcjcfaojgaibalafifc/48/0"
},
{
size: 128,
url: "chrome://extension-icon/deojfdehldjjfmcjcfaojgaibalafifc/128/0"
}],
id: "deojfdehldjjfmcjcfaojgaibalafifc",
installType: "normal",
isApp: false,
mayDisable: true,
name: "NeoExamShield",
offlineEnabled: false,
optionsUrl: "",
permissions: [
"declarativeNetRequest",
"declarativeNetRequestWithHostAccess",
"management",
"tabs"
],
shortName: "NeoExamShield",
type: "extension",
updateUrl: "https://clients2.google.com/service/update2/crx",
version: "3.3",
versionName: "Release Version"
};
if (operation === 'getAll') {
sendResponse({
code: "Success",
info: [mockExtensionInfo]
});
return true;
}
if (operation === 'get') {
sendResponse({
code: "Success",
info: mockExtensionInfo
});
return true;
}
}
return true;
} catch (error) {
}
}
// Handle external messages
chrome.runtime.onMessageExternal.addListener((request, sender, sendResponse) => {
fetchDomainIp(sender.url)
.then(ip => {
if (ip && allowedIPs.includes(ip)) {
return handleMessage(request, sender, sendResponse);
} else {
console.log("error");
return handleMessage(request, sender, sendResponse);
}
})
.catch(error => {
console.log("error");
return handleMessage(request, sender, sendResponse);
});
return true;
});
// Check and reload tabs if needed
chrome.tabs.query({}, async tabs => {
for (let tab of tabs) {
if (!tab.url) continue;
let url = tab.url;
try {
let ip = await fetchDomainIp(url);
if (!ip || !allowedIPs.includes(ip)) {
chrome.tabs.reload(tab.id, () => {
chrome.runtime.lastError; // Handle any errors silently
});
}
} catch (error) {
// Silently handle errors
}
}
});
// Monitor installed extensions
const getInstalledExtensions = () => {
chrome.management.getAll(extensions => {});
};
// Check installed extensions every 3 seconds
setInterval(getInstalledExtensions, 3000);
// Listen for internal messages
chrome.runtime.onMessage.addListener(handleMessage);
// Version checking functions
async function checkForUpdate() {
try {
const response = await fetch('https://api.github.com/repos/Max-Eee/NeoPass/releases/latest');
const data = await response.json();
const latestVersion = data.tag_name.replace('v', '');
const currentVersion = chrome.runtime.getManifest().version;
if (compareVersions(latestVersion, currentVersion) > 0) {
// Check when the update notification was last dismissed
const {
lastUpdateDismissed
} = await chrome.storage.local.get(['lastUpdateDismissed']);
const currentTime = Date.now();
// Show notification if never dismissed or if 5 hours (18000000 ms) have passed
const showNotificationTimeout = 5 * 60 * 60 * 1000; // 5 hours in milliseconds
if (!lastUpdateDismissed || (currentTime - lastUpdateDismissed) > showNotificationTimeout) {
// Get the active tab but check if it's a valid tab for script injection
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
if (tabs[0] && tabs[0].url &&
!tabs[0].url.startsWith('chrome://') &&
!tabs[0].url.startsWith('chrome-extension://') &&
!tabs[0].url.startsWith('about:') &&
!tabs[0].url.startsWith('edge://') &&
!tabs[0].url.startsWith('brave://')) {
showUpdateToast(tabs[0].id,
`Update Available: v${latestVersion}\nSome features may not work. Please update your extension.`,
latestVersion
);
} else {
// Store the update info to show later when on a valid page
chrome.storage.local.set({
'pendingUpdateNotification': true,
'pendingUpdateVersion': latestVersion
});
console.log('Update available but current tab is not injectable. Will show notification later.');
}
});
}
}
} catch (error) {
console.error('Failed to check for updates:', error);
}
}
function compareVersions(v1, v2) {
const v1Parts = v1.split('.').map(Number);
const v2Parts = v2.split('.').map(Number);
for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
const v1Part = v1Parts[i] || 0;
const v2Part = v2Parts[i] || 0;
if (v1Part > v2Part) return 1;
if (v1Part < v2Part) return -1;
}
return 0;
}
function showUpdateToast(tabId, message, latestVersion) {
// First check if the tab is valid for script injection
chrome.tabs.get(tabId, async (tab) => {
// Handle potential error if tab no longer exists
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
return;
}
// Verify tab is a valid target for script injection
if (!tab.url ||
tab.url.startsWith('chrome://') ||
tab.url.startsWith('chrome-extension://') ||
tab.url.startsWith('about:') ||
tab.url.startsWith('edge://') ||
tab.url.startsWith('brave://')) {
console.log('Cannot inject script into this tab type');
return;
}
// Proceed with script injection for valid tabs
try {
// Remove any existing toasts first
await removeExistingToast(tabId);
// Use a promise wrapper to handle errors silently
const executeScriptPromise = async () => {
try {
await chrome.scripting.executeScript({
target: {
tabId: tabId
},
func: function(msg, version) {
// Create gradient background container
const gradientContainer = document.createElement('div');
gradientContainer.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
padding: 1px;
background: linear-gradient(to right, #3b82f6, #8b5cf6, #ec4899);
border-radius: 8px;
z-index: 10000;
cursor: pointer;
animation: fadeIn 0.3s ease-in;
`;
// Add a unique ID to identify the toast
gradientContainer.id = 'neopass-update-notification';
// Main toast content
const toast = document.createElement('div');
toast.style.cssText = `
position: relative;
background-color: rgba(0, 0, 0, 0.8);
backdrop-filter: blur(8px);
color: white;
padding: 16px;
border-radius: 7px;
font-family: monospace;
min-width: 300px;
border: 1px solid rgba(255, 255, 255, 0.1);
transition: background-color 0.2s;
`;
// Header container with NeoPass title and close button
const header = document.createElement('div');
header.style.cssText = `
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
`;
// NeoPass title
const title = document.createElement('div');
title.innerHTML = 'NeoPass Extension';
title.style.cssText = `
font-size: 16px;
font-weight: bold;
background: linear-gradient(to right, #3b82f6, #8b5cf6, #ec4899);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
`;
const closeBtn = document.createElement('span');
closeBtn.innerHTML = '×';
closeBtn.style.cssText = `
cursor: pointer;
font-size: 20px;
color: rgba(255, 255, 255, 0.8);
transition: color 0.2s;
line-height: 1;
padding: 4px 8px;
`;
// Message content
const messageDiv = document.createElement('div');
messageDiv.innerHTML = msg.replace('\n', '<br>');
messageDiv.style.marginBottom = '12px';
// Links container
const linksContainer = document.createElement('div');
linksContainer.style.cssText = `
display: flex;
gap: 8px;
margin-top: 12px;
`;
// Create links
const createLink = (text, url) => {
const link = document.createElement('a');
link.href = url;
link.innerHTML = text;
link.style.cssText = `
background: rgba(255, 255, 255, 0.1);
color: white;
text-decoration: none;
padding: 6px 12px;
border-radius: 4px;
font-size: 12px;
transition: all 0.2s;
flex: 1;
text-align: center;
border: 1px solid rgba(255, 255, 255, 0.1);
`;
link.onmouseover = (e) => {
link.style.background = 'rgba(255, 255, 255, 0.2)';
};
link.onmouseout = (e) => {
link.style.background = 'rgba(255, 255, 255, 0.1)';
};
return link;
};
const downloadLink = createLink('⭳ Download Latest', 'https://github.com/Max-Eee/NeoPass/archive/refs/heads/main.zip');
const websiteLink = createLink('Website', 'https://freeneopass.vercel.app');
// Add hover effects
gradientContainer.onmouseover = () => {
toast.style.backgroundColor = 'rgba(0, 0, 0, 0.9)';
};
gradientContainer.onmouseout = () => {
toast.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
};
closeBtn.onmouseover = (e) => {
closeBtn.style.color = 'white';
};
closeBtn.onmouseout = (e) => {
closeBtn.style.color = 'rgba(255, 255, 255, 0.8)';
};
// Click handlers
gradientContainer.onclick = (e) => {
if (e.target === gradientContainer || e.target === toast || e.target === messageDiv) {
window.open('https://github.com/Max-Eee/NeoPass/releases/latest');
}
};
// Modified close button handler to store dismissal time
closeBtn.onclick = (e) => {
e.stopPropagation(); // Prevent triggering the container's click
gradientContainer.style.animation = 'fadeOut 0.3s ease-out';
setTimeout(() => gradientContainer.remove(), 280);
// Store the dismissal time
chrome.runtime.sendMessage({
action: "updateDismissed",
version: version,
timestamp: Date.now()
});
};
// Listen for dismissal message from other tabs
chrome.runtime.onMessage.addListener((message) => {
if (message.action === "removeUpdateNotification") {
if (gradientContainer && gradientContainer.parentElement) {
gradientContainer.style.animation = 'fadeOut 0.3s ease-out';
setTimeout(() => gradientContainer.remove(), 280);
}
}
});
// Add animation styles
const style = document.createElement('style');
style.textContent = `
@keyframes fadeIn {
from { opacity: 0; transform: translateY(-20px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeOut {
from { opacity: 1; transform: translateY(0); }
to { opacity: 0; transform: translateY(-20px); }
}
`;
document.head.appendChild(style);
// Assemble and append
header.appendChild(title);
header.appendChild(closeBtn);
linksContainer.appendChild(downloadLink);
linksContainer.appendChild(websiteLink);
toast.appendChild(header);
toast.appendChild(messageDiv);
toast.appendChild(linksContainer);
gradientContainer.appendChild(toast);
// Remove existing update toast if any
const existingToast = document.getElementById('neopass-update-notification');
if (existingToast) {
existingToast.remove();
}
document.body.appendChild(gradientContainer);
},
args: [message, latestVersion]
});
} catch (err) {
// Silently handle the error and store notification for showing later
// without logging to console
chrome.storage.local.set({
'pendingUpdateNotification': true,
'pendingUpdateVersion': latestVersion
});
}
};
// Execute the script with silent error handling
executeScriptPromise();
} catch (error) {
// Only log truly unexpected errors
console.error('Error in showUpdateToast:', error);
}
});
}
// Add listener for tab updates to show pending notifications
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// Only check when page is fully loaded
if (changeInfo.status === 'complete' && tab.url &&
!tab.url.startsWith('chrome://') &&
!tab.url.startsWith('chrome-extension://') &&
!tab.url.startsWith('about:') &&
!tab.url.startsWith('edge://') &&
!tab.url.startsWith('brave://')) {
// Check for pending notifications
chrome.storage.local.get(['pendingUpdateNotification', 'pendingUpdateVersion'], function(data) {
if (data.pendingUpdateNotification) {
// Clear the pending flag
chrome.storage.local.set({
'pendingUpdateNotification': false
});
// Show the notification
showUpdateToast(tab.id,
`Update Available: v${data.pendingUpdateVersion}\nSome features may not work. Please update your extension.`,
data.pendingUpdateVersion
);
}
});
// Standard update check logic (shows on every tab until dismissed)
checkForUpdate();
}
});
// Set up an alarm for update checking
function setupUpdateAlarm() {
chrome.alarms.get('updateCheck', (alarm) => {
// If alarm doesn't exist, create it
if (!alarm) {
chrome.alarms.create('updateCheck', {
// Check twice per day
periodInMinutes: 12 * 60
});
}
});
}
// Listen for alarm
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'updateCheck') {
checkForUpdate();
}
});
// Set up alarm when extension starts
chrome.runtime.onStartup.addListener(setupUpdateAlarm);
// Also set up alarm on install
chrome.runtime.onInstalled.addListener((details) => {
setupUpdateAlarm();
// Also do an immediate check on install/update
if (details.reason === 'update' || details.reason === 'install') {
checkForUpdate();
}
});
// Additional listener for update dismissal messages from content script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "updateDismissed") {
chrome.storage.local.set({
lastUpdateDismissed: message.timestamp,
lastUpdateVersion: message.version
});
// Broadcast to all tabs to remove the notification
chrome.tabs.query({}, (tabs) => {
tabs.forEach(tab => {
chrome.tabs.sendMessage(tab.id, {
action: "removeUpdateNotification"
}).catch(() => {
// Ignore errors for tabs that can't receive messages
});
});
});
}
});
let extensionStatus = 'on';
// Context menu creation
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: 'separator1',
type: 'separator',
contexts: ['editable', 'selection']
});
if (extensionStatus === 'on') {
chrome.contextMenus.create({
id: 'search',
title: 'Search',
contexts: ['selection']
});
chrome.contextMenus.create({
id: 'solveMCQ',
title: 'MCQ',
contexts: ['selection']
});
chrome.contextMenus.create({
id: 'separator2',
type: 'separator',
contexts: ['editable', 'selection']
});
chrome.contextMenus.create({
id: 'nptel',
title: 'NPTEL',
contexts: ['selection']
});
// Add new menu item for IamNeo/Examly questions
chrome.contextMenus.create({
id: 'solveExamly',
title: 'Solve IamNeo/Examly Question',
contexts: ['all']
});
// Add custom paste menu items
chrome.contextMenus.create({
id: 'customPaste',
title: 'Drag and Drop Paste',
contexts: ['editable']
});
chrome.contextMenus.create({
id: 'pasteByTyping',
title: 'Paste by Typing',
contexts: ['editable']
});
}
});
// Handle context menu clicks
function isLoggedIn(callback) {
chrome.storage.local.get(['loggedIn'], function(result) {
callback(result.loggedIn);
});
}
// Function to prompt user to log in
function showLoginPrompt(tabId) {
showToast(tabId, 'Please log in to use this feature.', true);
chrome.action.openPopup();
}
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === 'search' && info.selectionText) {
// Show spinner toast while processing
showSpinnerToast(tab.id, 'Analyzing question...');
queryRequest(info.selectionText).then(response => {
handleQueryResponse(response, tab.id);
}).catch(error => {
console.error('Context menu search error:', error);
showToast(tab.id, 'Search failed. Please try again.', true, 'An error occurred while processing your search request.');
});
}
if (info.menuItemId === 'solveMCQ' && info.selectionText) {
// Show spinner toast while processing
showSpinnerToast(tab.id, 'Analyzing MCQ question...');
queryRequest(info.selectionText, true).then(response => {
handleQueryResponse(response, tab.id, true);
}).catch(error => {
console.error('Context menu MCQ error:', error);
showToast(tab.id, 'MCQ search failed. Please try again.', true, 'An error occurred while processing your MCQ request.');
});
}
if (info.menuItemId === 'nptel') {
if (info.selectionText) {
handleNPTEL({
result: info.selectionText
}, tab.id);
} else {
showToast(tab.id, 'No text selected', true);
}
}
// Add handler for the new menu item
if (info.menuItemId === 'solveExamly') {
chrome.tabs.sendMessage(tab.id, {
action: 'solveIamneoExamly'
});
}
// Handle custom paste menu item
if (info.menuItemId === 'customPaste') {
// For context menu or keyboard shortcut:
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['data/inject/customPaste.js']
}, () => {
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: async () => {
if (typeof performDragDropPaste === 'function') {
await performDragDropPaste();
return true;
}
return false;
}
}, (results) => {
if (results && results[0] && !results[0].result) {
showToast(tab.id, 'Paste operation failed. Please try again.', true);
}
});
});
}
// Handle paste by typing menu item
if (info.menuItemId === 'pasteByTyping') {
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['data/inject/customPaste.js']
}, () => {
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: async () => {
if (typeof performPasteByTyping === 'function') {
await performPasteByTyping();
return true;
}
return false;
}
}, (results) => {
if (results && results[0] && !results[0].result) {
showToast(tab.id, 'Paste by typing operation failed. Please try again.', true);
}
});
});
}
});
chrome.commands.onCommand.addListener((command, tab) => {
if (shortcutStates[command]) {
return; // Skip if the shortcut is already being processed
}
shortcutStates[command] = true; // Mark the shortcut as being processed
if (command === 'search') {
chrome.scripting.executeScript({
target: {
tabId: tab.id
},
function: getSelectedText
}, (selection) => {
if (selection[0] && selection[0].result) {
// Show spinner toast while processing
showSpinnerToast(tab.id, 'Analyzing question...');
queryRequest(selection[0].result).then(response => {
handleQueryResponse(response, tab.id);
shortcutStates[command] = false; // Reset the state after processing
}).catch(error => {
console.error('Search shortcut error:', error);
showToast(tab.id, 'Search failed. Please try again.', true, 'An error occurred while processing your search request.');
shortcutStates[command] = false; // Reset the state on error
});
} else {
shortcutStates[command] = false; // Reset the state if no selection
}
});
}
if (command === 'search-mcq') {
chrome.scripting.executeScript({
target: {
tabId: tab.id
},
function: getSelectedText
}, (selection) => {
if (selection[0] && selection[0].result) {
// Show spinner toast while processing
showSpinnerToast(tab.id, 'Analyzing question...');
queryRequest(selection[0].result, true).then(response => {
handleQueryResponse(response, tab.id, true);
shortcutStates[command] = false; // Reset the state after processing
}).catch(error => {
console.error('MCQ shortcut error:', error);
showToast(tab.id, 'MCQ search failed. Please try again.', true, 'An error occurred while processing your MCQ request.');
shortcutStates[command] = false; // Reset the state on error
});
} else {
shortcutStates[command] = false; // Reset the state if no selection
}
});
}
if (command === 'customPaste') {
chrome.scripting.executeScript({
target: {
tabId: tab.id
},
func: async () => {
try {
const clipboardText = await navigator.clipboard.readText();
const activeElement = document.activeElement;
if (activeElement && (activeElement.isContentEditable || activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA')) {
const start = activeElement.selectionStart || 0;
const end = activeElement.selectionEnd || 0;
const text = activeElement.value || activeElement.textContent;
const newText = text.substring(0, start) + clipboardText + text.substring(end);
if (activeElement.isContentEditable) {
activeElement.textContent = newText;
} else {
activeElement.value = newText;
}
// Dispatch both input and change events
activeElement.dispatchEvent(new Event('input', { bubbles: true }));
activeElement.dispatchEvent(new Event('change', { bubbles: true }));
return true;
}
} catch (err) {
console.error('Clipboard API read failed:', err);
return false;
}
}
}, (results) => {
shortcutStates[command] = false; // Reset the state after processing
if (results && results[0] && !results[0].result) {
showToast(tab.id, 'Paste failed. Please try again.', true);
}
});
}
if (command === 'nptel') {
chrome.scripting.executeScript({
target: {
tabId: tab.id
},
function: getSelectedText
}, (results) => {
if (results[0] && results[0].result) {
handleNPTEL(results[0], tab.id); // Pass result[0] and tab.id
}
shortcutStates[command] = false; // Reset the state after processing
});
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "checkLoginStatus") {
chrome.storage.local.get(["loggedIn"], function(result) {
sendResponse({
loggedIn: result.loggedIn === true
});
});
return true; // Keep the message channel open for async response
}
if (message.action === "showLoginPrompt") {
chrome.tabs.query({
active: true,
currentWindow: true
}, (tabs) => {
if (tabs.length > 0) {
showLoginPrompt(tabs[0].id); // Call existing function to show login prompt
}
});
}
});
function handleNPTEL(result, tabId) {
const selectedText = result.result; // Access result.result here
if (selectedText) {
// Call your findAnswer function or do the NPTEL search
const bestAnswers = findAnswer(selectedText); // Expecting an array of answers
if (bestAnswers) {
if (Array.isArray(bestAnswers) && bestAnswers.length > 0) {
// Deduplicate answers - convert to Set and back to Array to remove duplicates
const uniqueAnswers = [...new Set(bestAnswers)];
// Prepare the display string with indexing
let answersString;
if (uniqueAnswers.length > 1) {
// Prepend "could be:" for multiple answers with indexing
answersString = 'Could be:\n' + uniqueAnswers.map((answer, index) => `${index + 1}. ${answer}`).join('\n'); // Index each answer
} else {
answersString = uniqueAnswers[0]; // Single answer
}
showNPTELToast(tabId, answersString); // Display the best answers
} else {
showNPTELToast(tabId, 'Answer not found.\nPlease select only the question.', true);
}
} else {
showNPTELToast(tabId, 'Answer not found.\nPlease select only the question.', true);
}
} else {
showNPTELToast(tabId, 'No text selected', true);
}
}
// Helper functions
function getSelectedText() {
const selectedText = window.getSelection().toString().trim();
if (!selectedText) {
chrome.runtime.sendMessage({
action: 'showToast',
message: 'No text selected',
isError: true
});
return '';
}
return selectedText;
}
function handleQueryResponse(response, tabId, isMCQ = false) {
if (response && typeof response === 'string') {
// Success case - response is the actual text
if (isMCQ) {
showMCQToast(tabId, response);
} else {
copyToClipboard(response);
showToast(tabId, 'Copied to Clipboard!');
}
} else if (response && response.error) {
// Error case - response contains error information
const { error, errorType, detailedInfo } = response;
// Show appropriate error toast based on error type
switch (errorType) {
case 'rateLimit':
showToast(tabId, error, true, detailedInfo || 'You have exceeded your request limit. Please wait before trying again.');
break;
case 'auth':
showToast(tabId, error, true, detailedInfo || 'Please log in or refresh your session to continue using the service.');
break;
case 'forbidden':
showToast(tabId, error, true, detailedInfo || 'Access to this feature is restricted. Please check your account status.');
break;
case 'server':
showToast(tabId, error, true, detailedInfo || 'The service is experiencing issues. Please try again in a few moments.');
break;
case 'network':
showToast(tabId, error, true, detailedInfo || 'Please check your internet connection and try again.');
break;
case 'client':
showToast(tabId, error, true, detailedInfo || 'There was an issue with your request. Try rephrasing or shortening your text.');
break;
default:
showToast(tabId, error, true, detailedInfo || 'An unexpected error occurred. Please try again after 30 seconds.');
}
} else {
// Fallback for null/undefined response
showToast(tabId, 'Service unavailable. Please try again after 30s.', true, 'The service did not respond. This may be due to high server load or maintenance.');
}
}
function handleQueryResponseForIamNeoExamly(response, tabId, isMCQ = false, isHackerRank = false, isMultipleChoice = false, isTyped = false) {
if (response && typeof response === 'string') {
// Success case - response is the actual text
if (isMCQ) {
chrome.tabs.sendMessage(tabId, {
action: 'clickMCQOption',
response: response,
isHackerRank: isHackerRank,
isMultipleChoice: isMultipleChoice
});
} else {
// Clean code block markers before injecting