-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopup.js
1438 lines (1252 loc) · 55.2 KB
/
popup.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
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
// Add this debounce function at the top of your file
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
async function getFingerprint() {
// Ensure FingerprintJS is loaded
if (typeof FingerprintJS === 'undefined') {
console.error('FingerprintJS is not loaded');
return null;
}
const fp = await FingerprintJS.load();
const result = await fp.get();
return result.visitorId;
}
function displayError(errorMessage) {
const resultContainer = document.getElementById('resultContainer');
const summaryContainer = document.getElementById('summaryContainer');
const resultDiv = document.getElementById('resultDiv');
const copyButton = document.getElementById('copyButton');
const summaryHeader = document.querySelector('.summary-header');
// Hide summary-related elements
if (summaryContainer) summaryContainer.style.display = 'none';
if (copyButton) copyButton.style.display = 'none';
if (summaryHeader) summaryHeader.style.display = 'none';
// Clear previous content
if (resultDiv) resultDiv.innerHTML = '';
const errorDiv = document.createElement('div');
errorDiv.className = 'error-message user-friendly';
errorDiv.innerHTML = `
<h3>Oops!</h3>
<p>${errorMessage}</p>
`;
if (resultDiv) resultDiv.appendChild(errorDiv);
if (resultContainer) resultContainer.style.display = 'block';
// Only add the "Open Settings" button if it's the API key error
if (errorMessage.includes('Enter your API key')) {
const openSettingsBtn = document.createElement('button');
openSettingsBtn.id = 'openSettingsBtn';
openSettingsBtn.className = 'action-button';
openSettingsBtn.textContent = 'Open Settings';
openSettingsBtn.addEventListener('click', function() {
const settingsModal = document.getElementById('settingsModal');
if (settingsModal) {
settingsModal.style.display = 'block';
loadApiKeysIntoSettingsForm();
}
});
errorDiv.appendChild(openSettingsBtn);
}
}
document.addEventListener('DOMContentLoaded', function() {
const inputText = document.getElementById('inputText');
const modelSelect = document.getElementById('modelSelect');
const summarizeBtn = document.getElementById('summarizeBtn');
const resultDiv = document.getElementById('resultDiv');
const settingsBtn = document.getElementById('settingsBtn');
const settingsModal = document.getElementById('settingsModal');
const closeSettingsBtn = document.getElementById('closeSettingsBtn');
const saveSettingsBtn = document.getElementById('saveSettingsBtn');
const copyButton = document.getElementById('copyButton');
const ttsButton = document.getElementById('ttsButton');
const ttsVoiceSelect = document.getElementById('ttsVoiceSelect');
const exportButton = document.getElementById('exportButton');
const inputContainer = document.getElementById("inputContainer");
const loaderContainer = document.getElementById("loaderContainer");
const darkModeToggle = document.getElementById('darkModeToggle');
let lastInput = '';
let lastModel = '';
let currentAudio = null;
let preloadedAudio = null;
let isPreloading = false;
let ttsEndpointUrl = 'https://you_server_endpoint/tts'; // Default URL
let currentActivityId = null;
let activityData = {};
let lastActivityType = null;
let lastActivityTime = 0;
let currentSessionId = null;
feather.replace();
fetchTtsEndpointUrl();
// Check for saved dark mode preference
if (localStorage.getItem('darkMode') === 'enabled') {
document.body.classList.add('dark-mode');
}
// Dark mode toggle functionality
darkModeToggle.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
if (document.body.classList.contains('dark-mode')) {
localStorage.setItem('darkMode', 'enabled');
} else {
localStorage.setItem('darkMode', null);
}
});
function charCounter(inputField) {
const maxLength = inputField.getAttribute("maxlength");
const currentLength = inputField.value.length;
const progressBar = document.getElementById("progress-bar");
const remChars = document.getElementById("remaining-chars");
const progressContainer = document.getElementById("progressContainer");
const progressWidth = (currentLength / maxLength) * 100;
progressBar.style.width = `${progressWidth}%`;
remChars.style.display = "none";
if (progressWidth <= 60) {
progressBar.style.backgroundColor = "rgb(19, 160, 19)";
} else if (progressWidth > 60 && progressWidth < 85) {
progressBar.style.backgroundColor = "rgb(236, 157, 8)";
} else {
progressBar.style.backgroundColor = "rgb(241, 9, 9)";
remChars.innerHTML = `${maxLength - currentLength} characters left`;
remChars.style.display = "block";
}
// Show progress container only when there's input
progressContainer.style.display = currentLength > 0 ? "block" : "none";
}
inputText.oninput = () => charCounter(inputText);
// Initially hide the progress container
const progressContainer = document.getElementById("progressContainer");
progressContainer.style.display = "none";
// Update the export button event listener
if (exportButton) {
exportButton.addEventListener('click', debounce(function() {
exportSummary();
updateActivity('summary_exported');
}, 300)); // 300ms debounce time
}
function showToast(message) {
let toast = document.getElementById('toast');
if (!toast) {
toast = document.createElement('div');
toast.id = 'toast';
document.body.appendChild(toast);
}
toast.textContent = message;
toast.className = 'show';
setTimeout(() => { toast.className = toast.className.replace('show', ''); }, 3000);
}
function showWelcomeToast(message) {
showToast(message);
if (typeof confetti === 'function') {
confetti({
particleCount: 100,
spread: 70,
origin: { y: 0.6 },
disableForReducedMotion: true
});
} else {
console.warn('Confetti function not available');
}
}
async function getApiKey(keyName) {
return new Promise((resolve) => {
chrome.storage.local.get([keyName], function(result) {
const apiKey = result[keyName];
if (apiKey && apiKey.trim() !== '') {
resolve(apiKey);
} else {
resolve(null);
}
});
});
}
function openSettingsModal() {
const settingsModal = document.getElementById('settingsModal');
if (settingsModal) {
settingsModal.style.display = 'block';
loadApiKeysIntoSettingsForm();
}
}
async function fetchUrlContent(url) {
try {
const response = await fetch(url);
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('text/html')) {
const text = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(text, 'text/html');
return doc.body.innerText;
} else {
return await response.text();
}
} catch (error) {
throw error;
}
}
async function sendSummarizeRequest(input, model, apiKey) {
try {
const userId = await getUserId();
let requestData = {
input,
model,
user_id: userId
};
if (apiKey) {
requestData.api_key = apiKey;
}
const response = await fetch('https://you_server_endpoint/summarize', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestData)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.summary) {
return data.summary;
} else if (data.error) {
throw new Error(data.error);
} else {
throw new Error('Unexpected response format');
}
} catch (error) {
// Instead of logging to console, we'll throw the error to be handled by the caller
throw new Error(`Failed to summarize: ${error.message}`);
}
}
function debugLog(message) {
// Debug logging removed for production
}
async function getUserId() {
return new Promise((resolve) => {
chrome.storage.sync.get(['userId'], function(result) {
if (result.userId) {
resolve(result.userId);
} else {
const newUserId = generateUUID();
chrome.storage.sync.set({userId: newUserId}, function() {
resolve(newUserId);
});
}
});
});
}
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function beautifySummary(summary) {
// Split the summary into paragraphs
const paragraphs = summary.split('\n').filter(p => p.trim() !== '');
// Create HTML for each paragraph
const htmlParagraphs = paragraphs.map(p => `<p>${p}</p>`).join('');
return htmlParagraphs;
}
function showLoader() {
if (loaderContainer) {
loaderContainer.style.display = 'flex';
// Hide other elements
document.getElementById('resultContainer').style.display = 'none';
inputContainer.style.display = 'none';
progressContainer.style.display = 'none';
modelSelect.style.display = 'none';
summarizeBtn.style.display = 'none';
}
}
function hideLoader() {
if (loaderContainer) {
loaderContainer.style.display = 'none';
// Show other elements
inputContainer.style.display = 'block';
progressContainer.style.display = 'block';
modelSelect.style.display = 'inline-block';
summarizeBtn.style.display = 'inline-block';
// resultContainer will be shown by displaySummary or displayError
}
}
// Your existing charCounter function remains the same
// Update your summarize function to use showLoader and hideLoader
// async function summarize() {
// showLoader();
// try {
// // Your existing summarization logic
// } catch (error) {
// // Error handling
// } finally {
// hideLoader();
// }
// }
// Make sure to call summarize when the summarize button is clicked
document.getElementById('summarizeBtn').addEventListener('click', summarize);
function toggleSummarizeButton(disabled) {
if (summarizeBtn) {
summarizeBtn.disabled = disabled;
summarizeBtn.style.opacity = disabled ? '0.5' : '1';
summarizeBtn.style.cursor = disabled ? 'not-allowed' : 'pointer';
}
}
function isInputValid(input) {
const minLength = 200; // Minimum length for text input
const urlPattern = /https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi;
// Trim the input and get its length
const trimmedInput = input.trim();
const inputLength = trimmedInput.length;
// Check if the input contains URLs
const urlMatches = trimmedInput.match(urlPattern);
if (urlMatches && urlMatches.length > 1) {
displayError('Please enter only one URL or paste the privacy policy text directly. Multiple URLs are not supported.');
return false;
}
// If it's a single URL, it's valid
if (urlMatches && urlMatches.length === 1 && urlMatches[0] === trimmedInput) {
return true;
}
// For non-URL input, check the length
if (inputLength < minLength) {
displayError(`Please enter at least ${minLength} characters or a valid URL.`);
return false;
}
// If we've reached here, the input is valid (either long enough text or a single URL within text)
return true;
}
if (summarizeBtn) {
summarizeBtn.addEventListener('click', async function(event) {
event.preventDefault();
const input = inputText.value.trim();
//console.log("Input:", input);
if (input === '') {
displayError('Please enter some text or a URL to summarize.');
return;
}
if (isInputValid(input)) {
debounce(summarize, 300)();
}
});
}
const maxRetries = 3;
async function summarize() {
try {
// if (!(await checkApiKeyAndOpenSettings())) {
// return;
// }
const inputText = document.getElementById('inputText').value.trim();
const model = document.getElementById('modelSelect').value;
const userId = await getUserId();
let token = await getValidToken();
const startTime = Date.now();
const maxInputLength = 50000;
if (inputText.length > maxInputLength) {
displayError(`Input is too long. Please limit your input to ${maxInputLength} characters.`);
return;
}
const urlRegex = /https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi;
const urlMatches = inputText.match(urlRegex);
if (urlMatches && urlMatches.length > 1) {
displayError('Please enter only one URL or paste the privacy policy text directly. Multiple URLs are not supported.');
return;
}
showLoader();
let isUrl = false;
let scrapedContent = null;
if (urlMatches && urlMatches.length === 1) {
isUrl = true;
const url = urlMatches[0];
try {
scrapedContent = await scrapeWebsite(url);
} catch (error) {
displayError(`Failed to scrape website: ${error.message}`);
return;
}
} else if (inputText.includes('http://') || inputText.includes('https://')) {
displayError('Invalid URL format. Please enter a valid URL or paste the privacy policy text directly.');
return;
}
if (!isInputValid(inputText)) {
return; // The error message is already displayed by isInputValid
}
const freeSummariesLeft = await getFreeSummariesCount();
let apiKey = await getApiKey(`${model}ApiKey`);
if (freeSummariesLeft <= 0 && !apiKey) {
throw new Error('No free summaries left and no valid API key provided');
}
const useServerSideKey = freeSummariesLeft > 0;
let response;
for (let retryCount = 0; retryCount < maxRetries; retryCount++) {
try {
response = await fetch('https://you_server_endpoint/summarize', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
input: inputText,
model: model,
user_id: userId,
is_url: isUrl,
searched_data: inputText,
scrape_data: scrapedContent,
api_key: useServerSideKey ? 'server_side' : apiKey
})
});
if (response.ok) {
break;
}
const errorData = await response.json();
if (response.status === 400 && errorData.error.includes("Failed to scrape website content")) {
throw new Error('Unable to access the website content. Please try pasting the privacy policy text directly.');
} else if (response.status === 403 && errorData.error === "No free summaries left") {
throw new Error('No free summaries left');
} else if (response.status === 503) {
if (retryCount === maxRetries - 1) {
throw new Error('Server temporarily unavailable. Please try again later.');
}
await new Promise(resolve => setTimeout(resolve, 1000 * (retryCount + 1)));
} else if (response.status === 403) {
//console.log('Received 403 error, attempting to refresh token');
await new Promise(resolve => setTimeout(resolve, 1000)); // Add a 1-second delay
token = await requestNewToken();
if (!token) {
throw new Error('Failed to refresh authentication token');
}
} else {
throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
}
} catch (error) {
if (retryCount === maxRetries - 1) {
throw error; // Rethrow the error if it's the last retry
}
console.error(`Attempt ${retryCount + 1} failed:`, error);
}
}
if (!response || !response.ok) {
throw new Error('Failed to get a valid response after retries');
}
const result = await response.json();
if (result.error) {
throw new Error(result.error);
}
displaySummary(result.summary, model);
updateFreeSummariesDisplay(result.free_summaries_left);
currentSessionId = result.session_id; // Store the session_id
// Start a new session here
startNewSession({
model: model,
isUrl: isUrl,
input: inputText,
scrapeData: scrapedContent
});
const activityData = {
model_selected: model,
searched_for: isUrl ? 'url' : 'text',
searched_data: inputText,
scrape_data: scrapedContent,
request_time: (Date.now() - startTime) / 1000, // Convert to seconds
tts_used: false,
copied_summary: false,
summary_exported: false
};
// Reset activity flags
lastActivityType = null;
lastActivityTime = 0;
await sendUserActivity(activityData);
} catch (error) {
console.error('Summarize error:', error);
if (error.message.includes('Unable to access the website content')) {
displayError('Unable to access the website content. Please try pasting the privacy policy text directly.');
} else if (error.message.includes('No free summaries left')) {
displayError('You have used all your free summaries. Please enter your API key to continue.');
openSettingsModal();
} else if (error.message === 'Server temporarily unavailable. Please try again later.') {
displayError('Server is temporarily unavailable. Please try again in a few moments.');
} else {
displayError(`Failed to summarize: ${error.message}`);
}
} finally {
hideLoader();
}
}
async function checkApiKeyAndOpenSettings() {
const freeSummariesLeft = await getFreeSummariesCount();
const model = document.getElementById('modelSelect').value;
const apiKey = await getApiKey(`${model}ApiKey`);
if (freeSummariesLeft <= 0 && !apiKey) {
displayError('You have used all your free summaries. Please enter your API key to continue.');
openSettingsModal();
return false;
}
return true;
}
async function scrapeWebsite(url) {
try {
const token = await getValidToken();
const response = await fetch('https://you_server_endpoint/scrape', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ url: url })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.content;
} catch (error) {
console.error('Error scraping website:', error);
throw error;
}
}
async function getFreeSummariesCount() {
try {
const token = await getValidToken();
const response = await fetch('https://you_server_endpoint/get_free_summaries_count', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
user_id: await getUserId()
})
});
if (response.status === 403) {
return 0; // No free summaries left
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.free_summaries_left !== undefined ? data.free_summaries_left : 0;
} catch (error) {
console.error('Error fetching free summaries count:', error);
return 0;
}
}
function closeSettingsModal() {
if (settingsModal) {
settingsModal.style.display = 'none';
}
}
if (settingsBtn && settingsModal) {
settingsBtn.addEventListener('click', function() {
settingsModal.style.display = 'block';
loadApiKeysIntoSettingsForm();
});
}
if (closeSettingsBtn) {
closeSettingsBtn.addEventListener('click', function(event) {
event.preventDefault(); // Prevent any default action
event.stopPropagation(); // Stop the event from bubbling up
closeSettingsModal();
});
}
if (saveSettingsBtn) {
saveSettingsBtn.addEventListener('click', function() {
const gpt4oMiniApiKey = document.getElementById('gpt4oMiniApiKeyInput').value;
const claudeApiKey = document.getElementById('claudeApiKeyInput').value;
const geminiApiKey = document.getElementById('geminiApiKeyInput').value;
const mistralApiKey = document.getElementById('mistralApiKeyInput').value;
const newVoice = document.getElementById('ttsVoiceSelect').value;
chrome.storage.local.set({
'gpt-4o-miniApiKey': gpt4oMiniApiKey,
'claude-3-5-sonnet-20240620ApiKey': claudeApiKey,
'gemini-1.5-flash-8bApiKey': geminiApiKey,
'mistral-small-latestApiKey': mistralApiKey,
'ttsVoice': newVoice
}, function() {
closeSettingsModal();
updateModelSelectOptions();
showToast("Settings saved successfully!");
});
});
}
if (settingsModal) {
window.addEventListener('click', function(event) {
if (event.target == settingsModal) {
closeSettingsModal();
}
});
}
function formatSummary(summary) {
// Remove any leading HTML tags
summary = summary.replace(/^<[^>]+>/, '');
const sections = summary.split(/<h[1-6]>/);
let formattedSummary = '<div class="summary-content">';
sections.forEach((section, index) => {
if (section.trim()) {
const [title, ...content] = section.split('</h');
if (index > 0) { // Skip the first split as it's before the first header
const headerLevel = summary.match(new RegExp(`<h(\\d)>${title}`))[1];
formattedSummary += `<h${headerLevel}>${title}</h${headerLevel}>`;
}
if (content.length > 0) {
const contentText = content.join('</h'); // Rejoin any accidental splits
const listItems = contentText.split(/(?:^|\n)[-•]/);
if (listItems.length > 1) {
formattedSummary += '<ul>';
listItems.forEach((item) => {
const trimmedItem = item.trim();
if (trimmedItem) {
formattedSummary += `<li>${trimmedItem}</li>`;
}
});
formattedSummary += '</ul>';
} else {
formattedSummary += `<p>${contentText.trim()}</p>`;
}
}
}
});
formattedSummary += '</div>';
return formattedSummary;
}
function displaySummary(summary, model) {
const resultContainer = document.getElementById('resultContainer');
const summaryContainer = document.getElementById('summaryContainer');
const resultDiv = document.getElementById('resultDiv');
const copyButton = document.getElementById('copyButton');
const summaryHeader = document.querySelector('.summary-header');
// Show summary-related elements
summaryContainer.style.display = 'block';
copyButton.style.display = 'inline-block';
summaryHeader.style.display = 'flex';
// Clear previous content
summaryContainer.innerHTML = '';
resultDiv.innerHTML = '';
// Add this line to standardize the response
const standardizedSummary = standardizeModelResponse(summary, model);
// Then use standardizedSummary instead of summary when setting the HTML content
summaryContainer.innerHTML = standardizedSummary;
// Add the disclaimer
resultDiv.innerHTML = `
<div class="disclaimer">
<h4>Disclaimer:</h4>
<p>This tool is for informational purposes only. Always read the full privacy policy for complete information.</p>
</div>
`;
resultContainer.style.display = 'block';
showToast("Preparing audio. It will be available soon.");
preloadAudioWithCurrentSettings();
}
function updateFreeSummariesDisplay(count) {
const counterElement = document.getElementById('freeSummariesCounter');
if (counterElement) {
const newCount = Math.max(0, count);
counterElement.textContent = `Free summaries left: ${newCount}`;
counterElement.style.display = 'block';
}
}
async function fetchAndUpdateFreeSummariesCount() {
try {
const userId = await getUserId();
const token = await getValidToken();
const response = await fetch('https://you_server_endpoint/get_free_summaries_count', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
user_id: userId
})
});
const data = await response.json();
const count = data.free_summaries_left !== undefined ? data.free_summaries_left : 0;
updateFreeSummariesDisplay(count);
return count;
} catch (error) {
console.error('Error fetching free summaries count:', error);
updateFreeSummariesDisplay(0);
return 0;
}
}
// Add this function to check for saved API keys and update the model select options
async function updateModelSelectOptions() {
const modelSelect = document.getElementById('modelSelect');
const models = [
{ value: 'gpt-4o-mini', name: 'GPT-4o-mini', keyName: 'gpt-4o-miniApiKey' },
{ value: 'claude-3-5-sonnet-20240620', name: 'Claude', keyName: 'claude-3-5-sonnet-20240620ApiKey' }, // Updated model name
{ value: 'gemini-1.5-flash-8b', name: 'Gemini', keyName: 'gemini-1.5-flash-8bApiKey' },
{ value: 'mistral-small-latest', name: 'Mistral', keyName: 'mistral-small-latestApiKey' }
];
// Clear existing options
modelSelect.innerHTML = '';
for (const model of models) {
const apiKey = await getApiKey(model.keyName);
const option = document.createElement('option');
option.value = model.value;
option.textContent = `${model.name}${apiKey ? ' (Key Set)' : ''}`;
modelSelect.appendChild(option);
}
}
// Call this function when the popup is loaded
updateModelSelectOptions();
// Add this function to handle the copy button
if (copyButton) {
copyButton.addEventListener('click', debounce(function() {
const summaryContainer = document.getElementById('summaryContainer');
if (summaryContainer) {
const summaryText = summaryContainer.innerText;
navigator.clipboard.writeText(summaryText).then(() => {
showToast("Summary copied to clipboard!");
updateActivity('copied_summary');
}).catch(err => {
console.error('Failed to copy summary: ', err);
showToast("Failed to copy summary. Please try again.");
});
} else {
console.error('Summary container not found');
showToast("Error: Summary not available");
}
}, 300)); // 300ms debounce time
}
// Add this function to load API keys into the settings form
function loadApiKeysIntoSettingsForm() {
chrome.storage.local.get(['gpt-4o-miniApiKey', 'claude-3-5-sonnet-20240620ApiKey', 'gemini-1.5-flash-8bApiKey', 'mistral-small-latestApiKey'], function(result) {
const gpt4oMiniInput = document.getElementById('gpt4oMiniApiKeyInput');
const claudeInput = document.getElementById('claudeApiKeyInput');
const geminiInput = document.getElementById('geminiApiKeyInput');
const mistralInput = document.getElementById('mistralApiKeyInput');
if (gpt4oMiniInput) gpt4oMiniInput.value = result['gpt-4o-miniApiKey'] || '';
if (claudeInput) claudeInput.value = result['claude-3-5-sonnet-20240620ApiKey'] || '';
if (geminiInput) geminiInput.value = result['gemini-1.5-flash-8bApiKey'] || '';
if (mistralInput) mistralInput.value = result['mistral-small-latestApiKey'] || '';
});
}
// Load saved voice preference
chrome.storage.local.get(['ttsVoice'], function(result) {
if (result.ttsVoice) {
ttsVoiceSelect.value = result.ttsVoice;
}
});
// Save voice preference when changed
ttsVoiceSelect.addEventListener('change', function() {
const newVoice = ttsVoiceSelect.value;
chrome.storage.local.set({ ttsVoice: newVoice }, function() {
showToast("Voice updated. Preparing new audio...");
preloadAudioWithCurrentSettings();
});
});
ttsButton.addEventListener('click', function() {
if (currentAudio) {
if (currentAudio.paused) {
currentAudio.play().catch(e => {
showToast("Error playing audio. Please try again.");
});
ttsButton.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="6" y="4" width="4" height="16"></rect>
<rect x="14" y="4" width="4" height="16"></rect>
</svg>
`;
} else {
currentAudio.pause();
ttsButton.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M11 5L6 9H2v6h4l5 4V5zM19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"></path>
</svg>
`;
}
} else if (preloadedAudio) {
currentAudio = preloadedAudio;
currentAudio.play().catch(e => {
showToast("Error playing audio. Please try again.");
});
ttsButton.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="6" y="4" width="4" height="16"></rect>
<rect x="14" y="4" width="4" height="16"></rect>
</svg>
`;
currentAudio.onended = function() {
ttsButton.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M11 5L6 9H2v6h4l5 4V5zM19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"></path>
</svg>
`;
currentAudio = null;
};
} else if (isPreloading) {
showToast("Audio is being prepared. Please wait a moment and try again.");
} else {
showToast("Audio is not available. Please generate a new summary and try again.");
preloadAudioWithCurrentSettings(); // Attempt to preload audio again
}
});
function standardizeModelResponse(response, model) {
let standardizedResponse = response;
// Remove introductory text
tandardizedResponse = standardizedResponse.replace(/^(Here's a summary of the privacy policy.*?:?\s*)?(based on the requested categories:\s*)?/i, '');
// Remove concluding phrases
standardizedResponse = standardizedResponse.replace(/\s*(Let me know if|If you have any|Please let me know|Is there anything else).*?$/i, '');
// Convert problematic characters to proper bullet points
standardizedResponse = standardizedResponse
.replace(/•/g, '•')
.replace(/[\u2022\u2023\u2043]/g, '•')
.trim();
// Standardize headers (including ###)
standardizedResponse = standardizedResponse.replace(/^(#{1,6})\s*(.*?)$/gm, (match, hashes, title) => {
const level = Math.min(hashes.length, 6); // Ensure header level is between 1 and 6
return `<h${level}>${title.trim()}</h${level}>`;
});
// Handle headers with ** and convert to proper HTML headers
standardizedResponse = standardizedResponse.replace(/^\*\*(.*?)\*\*$/gm, (match, content) => {
return `<h3>${content.trim()}</h3>`;
});
// Handle inline bold text (if any remains after header conversion)
standardizedResponse = standardizedResponse.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
// Convert numbered lists to HTML ordered lists
let inOrderedList = false;
standardizedResponse = standardizedResponse.split('\n').map((line, index, array) => {
const trimmedLine = line.trim();
const numberMatch = trimmedLine.match(/^(\d+)\.\s(.*)$/);
if (numberMatch) {
if (!inOrderedList) {
inOrderedList = true;
return `<ol><li>${numberMatch[2]}</li>`;
}
return `<li>${numberMatch[2]}</li>`;
} else if (inOrderedList) {
inOrderedList = false;
return `</ol>${line}`;
} else {
return line;
}
}).join('\n');
if (inOrderedList) {
standardizedResponse += '</ol>';
}
// Convert bullet points to HTML list items
let inList = false;
standardizedResponse = standardizedResponse.split('\n').map(line => {
const trimmedLine = line.trim();
if (trimmedLine.startsWith('- ') || trimmedLine.startsWith('• ')) {
if (!inList) {
inList = true;
return '<ul><li>' + trimmedLine.substring(2) + '</li>';
}
return '<li>' + trimmedLine.substring(2) + '</li>';
} else if (inList) {
inList = false;
return '</ul>' + line;
} else {
return '<p>' + line + '</p>';
}
}).join('');
if (inList) {
standardizedResponse += '</ul>';
}
// Wrap the entire response in a summary-content div
standardizedResponse = `<div class="summary-content">${standardizedResponse}</div>`;
return standardizedResponse;
}
// Update the preloadAudio function to handle GPT TTS response
function preloadAudio(text, voice, callback) {
isPreloading = true;
showToast("Preparing audio. It will be available soon.");
fetch(ttsEndpointUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
text: text,
voice: voice
})
})
.then(response => {
if (!response.ok) {
return response.json().then(errorData => {