-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
1933 lines (1620 loc) · 68.9 KB
/
Copy pathpopup.js
File metadata and controls
1933 lines (1620 loc) · 68.9 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
console.log('Popup script loaded');
const state = {
coverImage: null,
coverSourceType: null,
coverImageFile: null, // Store original file for upload
images: [],
activeTabId: null,
activeWindowId: null,
imageSelectionVisible: false,
pageTitle: '',
pageUrl: '',
authToken: null,
userInfo: null,
isLoggedIn: false,
selectedTopic: 'life', // Default to life topic
// x402 payment state
payToVisit: false, // Payment toggle (default off)
paymentAmount: '0.001' // Default payment amount in USDC
};
const elements = {};
// ========== Recent Categories Utility Functions ==========
const RECENT_CATEGORIES_KEY = 'copus_recent_categories';
const MAX_RECENT_CATEGORIES = 5;
/**
* Get recently used categories from localStorage
*/
function getRecentCategories() {
try {
const stored = localStorage.getItem(RECENT_CATEGORIES_KEY);
if (!stored) return [];
return JSON.parse(stored);
} catch (error) {
console.error('[Recent Categories] Error reading:', error);
return [];
}
}
/**
* Add a category to recently used list
*/
function addRecentCategory(categoryId, categoryName) {
try {
let recentCategories = getRecentCategories();
// Remove existing entry for this category
recentCategories = recentCategories.filter(cat => cat.id !== categoryId);
// Add to the beginning of the list
recentCategories.unshift({
id: categoryId,
name: categoryName,
timestamp: Date.now()
});
// Keep only the most recent MAX_RECENT_CATEGORIES
recentCategories = recentCategories.slice(0, MAX_RECENT_CATEGORIES);
localStorage.setItem(RECENT_CATEGORIES_KEY, JSON.stringify(recentCategories));
console.log('[Recent Categories] Saved:', categoryName);
} catch (error) {
console.error('[Recent Categories] Error saving:', error);
}
}
/**
* Sort categories to show recently used ones first
*/
function sortCategoriesByRecent(categories) {
const recentCategories = getRecentCategories();
const recentIds = new Set(recentCategories.map(cat => cat.id));
// Split into recent and non-recent
const recent = [];
const others = [];
categories.forEach(category => {
const categoryId = category.id || category.value;
if (recentIds.has(categoryId)) {
recent.push(category);
} else {
others.push(category);
}
});
// Sort recent categories by their timestamp (most recent first)
recent.sort((a, b) => {
const aId = a.id || a.value;
const bId = b.id || b.value;
const aRecent = recentCategories.find(cat => cat.id === aId);
const bRecent = recentCategories.find(cat => cat.id === bId);
return (bRecent?.timestamp || 0) - (aRecent?.timestamp || 0);
});
console.log('[Recent Categories] Sorted:', recent.length, 'recent,', others.length, 'others');
// Combine: recent first, then others
return [...recent, ...others];
}
// ========== Local storage functions for token management ==========
function saveAuthToken(token) {
try {
localStorage.setItem('copus_auth_token', token);
console.log('Auth token saved to local storage');
} catch (error) {
console.error('Failed to save auth token:', error);
}
}
function loadAuthToken() {
try {
const token = localStorage.getItem('copus_auth_token');
console.log('Auth token loaded from local storage:', token ? 'Found' : 'Not found');
return token;
} catch (error) {
console.error('Failed to load auth token:', error);
return null;
}
}
function clearAuthToken() {
try {
localStorage.removeItem('copus_auth_token');
console.log('Auth token cleared from local storage');
} catch (error) {
console.error('Failed to clear auth token:', error);
}
}
function cacheElements() {
// Login screen elements
elements.loginScreen = document.getElementById('login-screen');
elements.loginButton = document.getElementById('login-button');
elements.mainContainer = document.getElementById('main-container');
// Main app elements
elements.pageUrlDisplay = document.getElementById('page-url-display');
elements.pageTitleInput = document.getElementById('page-title-input');
elements.coverContainer = document.getElementById('cover-container');
elements.coverEmpty = document.getElementById('cover-empty');
elements.coverPreview = document.getElementById('cover-preview');
elements.coverRemove = document.getElementById('cover-remove');
elements.coverUpload = document.getElementById('cover-upload');
elements.coverScreenshot = document.getElementById('cover-screenshot');
elements.imageSelectionToggle = document.getElementById('toggle-detected-images');
elements.topicSelect = document.getElementById('topic-select');
elements.recommendationInput = document.getElementById('recommendation-input');
elements.charCounter = document.getElementById('char-counter');
elements.titleCharCounter = document.getElementById('title-char-counter');
elements.publishButton = document.getElementById('publish-button');
elements.cancelButton = document.getElementById('cancel-button');
elements.statusMessage = document.getElementById('status-message');
elements.toast = document.getElementById('toast');
elements.compactMain = document.querySelector('.compact-main');
elements.imageSelectionView = document.getElementById('image-selection-view');
elements.imageSelectionGrid = document.getElementById('image-selection-grid');
elements.goBackButton = document.getElementById('go-back-button');
// Notification elements
elements.notificationBell = document.getElementById('notification-bell');
elements.notificationBadge = document.getElementById('notification-badge');
elements.notificationCount = document.getElementById('notification-count');
// x402 Payment elements
elements.payToVisitToggle = document.getElementById('pay-to-visit-toggle');
elements.paymentDetails = document.getElementById('payment-details');
elements.paymentAmount = document.getElementById('payment-amount');
elements.estimatedIncome = document.getElementById('estimated-income');
}
function showToast(message, type = 'success') {
const toast = document.getElementById('toast');
if (!toast) return;
// Clear any existing classes and content
toast.className = 'toast';
toast.textContent = message;
// Add type-specific styling
if (type === 'error') {
toast.classList.add('error');
} else if (type === 'success') {
toast.classList.add('success');
}
// Show the toast
toast.classList.add('show');
// Auto-hide after 3 seconds
setTimeout(() => {
toast.classList.remove('show');
}, 3000);
}
// Legacy function for compatibility
function setStatus(message, type = 'info') {
if (type === 'error' || type === 'success') {
showToast(message, type);
}
}
function setCoverImage(coverImage, sourceType, originalFile = null) {
state.coverImage = coverImage;
state.coverSourceType = sourceType;
state.coverImageFile = originalFile; // Store original file for upload
if (coverImage && coverImage.src) {
elements.coverPreview.src = coverImage.src;
elements.coverPreview.hidden = false;
elements.coverEmpty.hidden = true;
elements.coverRemove.hidden = false;
elements.coverContainer.classList.add('cover-container--has-image');
} else {
elements.coverPreview.hidden = true;
elements.coverEmpty.hidden = false;
elements.coverRemove.hidden = true;
elements.coverContainer.classList.remove('cover-container--has-image');
if (elements.coverUpload) {
elements.coverUpload.value = '';
}
state.coverImageFile = null; // Clear file reference
}
updateImageSelectionHighlight();
}
function clearCoverImage() {
setCoverImage(null, null);
// No status message needed for cover removal
}
function updateImageSelectionHighlight() {
// No longer needed since we removed the inline image selection
// Images are now shown in a popup window
}
function determineMainImage(images) {
if (!Array.isArray(images) || images.length === 0) {
return null;
}
const sorted = [...images].sort((a, b) => {
const areaA = (a.width || 0) * (a.height || 0);
const areaB = (b.width || 0) * (b.height || 0);
return areaB - areaA;
});
return sorted[0] || null;
}
function updateDetectedImagesButton(images) {
if (!elements.imageSelectionToggle) {
return;
}
// Button will be enabled/disabled based on images
// Update button text based on whether images are detected or not
const detectSvg = `<svg width="20" height="20" viewBox="0 0 26 26" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12.9948 0.500006C10.5996 0.498025 8.25482 1.18784 6.24185 2.48663C6.0933 2.58469 5.98943 2.73746 5.95283 2.91173C5.91623 3.08601 5.94987 3.26769 6.04642 3.41729C6.14297 3.56688 6.29463 3.67229 6.46843 3.71059C6.64223 3.7489 6.82412 3.71701 6.97455 3.62185C8.57635 2.58919 10.4173 1.98755 12.3195 1.8751V7.6424C11.131 7.79321 10.0262 8.33508 9.1791 9.18276C8.33195 10.0305 7.79043 11.1359 7.63971 12.3252H1.87609C1.99486 10.3308 2.64799 8.40516 3.76691 6.75044L3.97287 8.20662C3.9958 8.36899 4.07696 8.51746 4.2012 8.62438C4.32544 8.7313 4.4843 8.78936 4.64816 8.78775H4.74608C4.92338 8.76263 5.08344 8.66808 5.19109 8.52489C5.29873 8.3817 5.34513 8.2016 5.32008 8.02418L4.89127 4.99356C4.86617 4.81615 4.77168 4.65598 4.62858 4.54827C4.48548 4.44057 4.30549 4.39414 4.12819 4.4192L1.10288 4.8449C0.923777 4.86955 0.761796 4.96437 0.652568 5.10852C0.543339 5.25266 0.49581 5.43433 0.520436 5.61354C0.545062 5.79275 0.639826 5.95484 0.783881 6.06413C0.927937 6.17343 1.10948 6.22099 1.28858 6.19635L2.63917 6.00377C1.02956 8.38917 0.291884 11.2573 0.550688 14.1239C0.809493 16.9904 2.04892 19.6798 4.05971 21.738C6.07049 23.7961 8.72944 25.0969 11.5876 25.4206C14.4457 25.7444 17.328 25.0714 19.7477 23.5151C19.8963 23.4171 20.0001 23.2643 20.0367 23.09C20.0733 22.9157 20.0397 22.7341 19.9431 22.5845C19.8466 22.4349 19.6949 22.3295 19.5211 22.2912C19.3473 22.2529 19.1654 22.2848 19.015 22.3799C17.4132 23.4126 15.5722 24.0142 13.6701 24.1267V18.3594C14.8586 18.2085 15.9633 17.6667 16.8105 16.819C17.6576 15.9713 18.1991 14.8659 18.3499 13.6766H24.1135C23.9947 15.671 23.3416 17.5966 22.2227 19.2513L22.0167 17.7951C21.9916 17.6159 21.8964 17.454 21.7521 17.345C21.6077 17.2361 21.426 17.1889 21.2469 17.214C21.0678 17.2391 20.906 17.3344 20.797 17.4788C20.6881 17.6233 20.641 17.8051 20.6661 17.9843L21.0949 21.0251C21.1179 21.1874 21.199 21.3359 21.3232 21.4428C21.4475 21.5498 21.6063 21.6078 21.7702 21.6062H21.8647L24.8799 21.1805C25.059 21.1559 25.221 21.061 25.3302 20.9169C25.4395 20.7727 25.487 20.5911 25.4624 20.4119C25.4377 20.2327 25.343 20.0706 25.1989 19.9613C25.0549 19.852 24.8733 19.8044 24.6942 19.8291L23.3436 20.0216C24.6191 18.1413 25.3583 15.9487 25.4816 13.6795C25.6049 11.4103 25.1076 9.1504 24.0434 7.14282C22.9791 5.13524 21.3881 3.45594 19.4414 2.2855C17.4946 1.11506 15.2659 0.497769 12.9948 0.500006ZM12.3195 24.1267C9.60389 23.9609 7.04272 22.8068 5.11894 20.8817C3.19515 18.9567 2.0417 16.3939 1.87609 13.6766H7.63971C7.79043 14.8659 8.33195 15.9713 9.1791 16.819C10.0262 17.6667 11.131 18.2085 12.3195 18.3594V24.1267ZM15.0207 13.6766H16.9858C16.845 14.5053 16.4503 15.2698 15.8563 15.8642C15.2623 16.4586 14.4983 16.8536 13.6701 16.9944V15.028C13.6701 14.8488 13.5989 14.677 13.4723 14.5502C13.3456 14.4235 13.1739 14.3523 12.9948 14.3523C12.8157 14.3523 12.6439 14.4235 12.5173 14.5502C12.3906 14.677 12.3195 14.8488 12.3195 15.028V16.9944C11.4913 16.8536 10.7273 16.4586 10.1333 15.8642C9.53924 15.2698 9.14454 14.5053 9.0038 13.6766H10.9689C11.148 13.6766 11.3198 13.6054 11.4464 13.4787C11.573 13.352 11.6442 13.1801 11.6442 13.0009C11.6442 12.8217 11.573 12.6498 11.4464 12.5231C11.3198 12.3963 11.148 12.3252 10.9689 12.3252H9.0038C9.14454 11.4964 9.53924 10.7319 10.1333 10.1375C10.7273 9.54314 11.4913 9.14819 12.3195 9.00736V10.9737C12.3195 11.1529 12.3906 11.3248 12.5173 11.4515C12.6439 11.5782 12.8157 11.6494 12.9948 11.6494C13.1739 11.6494 13.3456 11.5782 13.4723 11.4515C13.5989 11.3248 13.6701 11.1529 13.6701 10.9737V9.00736C14.4983 9.14819 15.2623 9.54314 15.8563 10.1375C16.4503 10.7319 16.845 11.4964 16.9858 12.3252H15.0207C14.8416 12.3252 14.6698 12.3963 14.5432 12.5231C14.4165 12.6498 14.3454 12.8217 14.3454 13.0009C14.3454 13.1801 14.4165 13.352 14.5432 13.4787C14.6698 13.6054 14.8416 13.6766 15.0207 13.6766ZM18.3499 12.3252C18.1991 11.1359 17.6576 10.0305 16.8105 9.18276C15.9633 8.33508 14.8586 7.79321 13.6701 7.6424V1.8751C16.3857 2.04082 18.9468 3.19501 20.8706 5.12002C22.7944 7.04503 23.9479 9.60783 24.1135 12.3252H18.3499Z" fill="currentColor"/>
</svg>`;
if (!Array.isArray(images) || images.length === 0) {
// No images - make button transparent and disabled
elements.imageSelectionToggle.innerHTML = `${detectSvg}<span>Detect</span>`;
elements.imageSelectionToggle.disabled = true;
elements.imageSelectionToggle.style.opacity = '0.4';
elements.imageSelectionToggle.style.cursor = 'not-allowed';
} else {
// Images found - show count beside text and enable button
elements.imageSelectionToggle.innerHTML = `${detectSvg}<span>Detect (${images.length})</span>`;
elements.imageSelectionToggle.disabled = false;
elements.imageSelectionToggle.style.opacity = '1';
elements.imageSelectionToggle.style.cursor = 'pointer';
}
}
// Helper function to convert data URL or image URL to File object
async function convertImageToFile(imageSrc, fileName = 'cover-image.png') {
try {
console.log('Converting image to file:', fileName);
let response;
if (imageSrc.startsWith('data:')) {
// Handle data URLs (screenshots, uploaded files)
const dataUrlParts = imageSrc.split(',');
const mimeMatch = dataUrlParts[0].match(/data:([^;]+);/);
const mimeType = mimeMatch ? mimeMatch[1] : 'image/png';
const byteString = atob(dataUrlParts[1]);
const arrayBuffer = new ArrayBuffer(byteString.length);
const uint8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < byteString.length; i++) {
uint8Array[i] = byteString.charCodeAt(i);
}
return new File([arrayBuffer], fileName, { type: mimeType });
} else {
// Handle regular URLs (detected images)
response = await fetch(imageSrc);
if (!response.ok) {
throw new Error('Failed to fetch image from URL');
}
const blob = await response.blob();
const mimeType = blob.type || 'image/png';
const extension = mimeType.split('/')[1] || 'png';
return new File([blob], `${fileName.split('.')[0]}.${extension}`, { type: mimeType });
}
} catch (error) {
console.error('Error converting image to file:', error);
throw new Error('Failed to convert image: ' + error.message);
}
}
async function uploadImageToS3(file) {
try {
console.log('[Copus Extension] Uploading image to S3:', file.name, file.size, file.type);
// Get authentication token
let result = { copus_token: null };
if (chrome?.storage?.local) {
result = await chrome.storage.local.get(['copus_token']);
} else {
result.copus_token = localStorage.getItem('copus_token');
}
const formData = new FormData();
formData.append('file', file);
const headers = {};
// Add authorization header if token is available
if (result.copus_token) {
headers['Authorization'] = `Bearer ${result.copus_token}`;
console.log('[Copus Extension] Added Authorization header for image upload');
} else {
console.warn('[Copus Extension] No auth token found for image upload');
}
const apiBaseUrl = getApiBaseUrl();
const response = await fetch(`${apiBaseUrl}/client/common/uploadImage2S3`, {
method: 'POST',
headers: headers,
body: formData
});
console.log('Image upload response status:', response.status);
if (!response.ok) {
throw new Error('Image upload failed (' + response.status + ')');
}
const responseData = await response.json();
console.log('Image upload response:', responseData);
// Check API-level status code (S3 upload API uses status: 1 for success)
if (responseData.status && responseData.status !== 1) {
throw new Error(responseData.msg || 'Image upload API error (status: ' + responseData.status + ')');
}
// Return the uploaded image URL
const imageUrl = responseData.data || responseData.url || responseData.imageUrl;
if (!imageUrl) {
throw new Error('No image URL returned from upload API');
}
console.log('Image uploaded successfully:', imageUrl);
return imageUrl;
} catch (error) {
console.error('Image upload error:', error);
throw error;
}
}
function updateCharacterCount() {
const text = elements.recommendationInput.value;
const count = text.length;
const maxLength = 1000;
elements.charCounter.textContent = count + '/' + maxLength;
// Remove existing classes
elements.charCounter.classList.remove('near-limit', 'at-limit');
// Add appropriate class based on character count
if (count >= maxLength) {
elements.charCounter.classList.add('at-limit');
} else if (count >= maxLength * 0.9) { // 90% of limit
elements.charCounter.classList.add('near-limit');
}
}
function updateTitleCharCounter() {
const text = elements.pageTitleInput.value;
const count = text.length;
const maxLength = 75;
elements.titleCharCounter.textContent = count + '/' + maxLength;
// Remove existing classes
elements.titleCharCounter.classList.remove('near-limit', 'at-limit');
// Add appropriate class based on character count
if (count >= maxLength) {
elements.titleCharCounter.classList.add('at-limit');
} else if (count >= maxLength * 0.9) { // 90% of limit (68 characters)
elements.titleCharCounter.classList.add('near-limit');
}
}
function handleTopicSelection(event) {
const topicId = event.target.value;
if (!topicId) return;
// Update state
state.selectedTopic = topicId;
console.log('Topic selected:', topicId);
// Track this category as recently used
const selectedOption = event.target.options[event.target.selectedIndex];
const categoryName = selectedOption.textContent;
addRecentCategory(parseInt(topicId), categoryName);
}
// Get the selected category ID (now comes directly from API)
function getTopicCategoryId(selectedValue) {
// The selectedValue is now the category ID from the API
const categoryId = parseInt(selectedValue);
return categoryId || 0;
}
function handleCancel() {
console.log('Cancel button clicked, closing window');
window.close();
}
function goBackToMain() {
console.log('goBackToMain called');
elements.imageSelectionView.hidden = true;
elements.compactMain.hidden = false;
}
function openImageSelectionView() {
// Don't proceed if button is disabled
if (elements.imageSelectionToggle.disabled) {
return;
}
console.log('openImageSelectionView called, current images:', state.images);
// Load page data only when user clicks detect
if (!Array.isArray(state.images) || state.images.length === 0) {
console.log('No images cached, loading page data...');
// Load page data on demand
loadPageData(state.activeTabId).then(() => {
console.log('Page data loaded, images found:', state.images ? state.images.length : 0);
if (Array.isArray(state.images) && state.images.length > 0) {
showImageSelection();
}
// Don't show error message when no images detected
}).catch(error => {
console.error('Failed to load page data:', error);
// Don't show error message
});
return;
}
console.log('Using cached images, showing selection...');
showImageSelection();
}
function showImageSelection() {
console.log('showImageSelection called with', state.images.length, 'images');
// Clear and populate the image grid
elements.imageSelectionGrid.innerHTML = '';
if (!Array.isArray(state.images) || state.images.length === 0) {
elements.imageSelectionGrid.innerHTML = '<div class="image-selection__empty">No images detected on this page.</div>';
} else {
state.images.forEach(function(image, index) {
console.log('Creating image option', index, ':', image.src);
const button = document.createElement('button');
button.type = 'button';
button.className = 'image-option';
const img = document.createElement('img');
img.src = image.src;
img.alt = 'Detected image option';
button.appendChild(img);
button.addEventListener('click', function() {
console.log('Image selected:', image.src);
setCoverImage({ src: image.src }, 'page');
// No status message needed for image selection
goBackToMain();
});
elements.imageSelectionGrid.appendChild(button);
});
}
// Show image selection view
console.log('Switching to image selection view');
elements.compactMain.hidden = true;
elements.imageSelectionView.hidden = false;
}
async function queryActiveTab() {
return new Promise((resolve) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
resolve(tabs[0]);
});
});
}
async function fetchPageData(tabId) {
return new Promise((resolve, reject) => {
// Reduce timeout for faster fallback
const timeoutId = setTimeout(() => {
reject(new Error('Page data fetch timeout'));
}, 500); // Reduced to 500ms for faster failure
chrome.tabs.sendMessage(tabId, { type: 'collectPageData' }, (response) => {
clearTimeout(timeoutId);
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve(response);
});
});
}
function initializeTestToken() {
// For testing purposes, save the test token if no token exists
const testToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIsImxhc3RQYXNzd29yZFJlc2V0VGltZSI6MTc1ODc4MzgzNiwibGFzdExvZ2luVGltZSI6MTc1ODc4NDAyMywiZXhwIjoxNzkwMzIwMDIzLCJpYXQiOjE3NTg3ODQwMjN9.Nr51Ydw68FhTZEELyQeNeKAZXDLzZsFhJXGtqCasSRw';
try {
const existingToken = localStorage.getItem('copus_auth_token');
if (!existingToken) {
localStorage.setItem('copus_auth_token', testToken);
state.authToken = testToken;
} else {
state.authToken = existingToken;
}
} catch (error) {
// Fallback if localStorage fails
state.authToken = testToken;
}
}
// Quick token existence check (no API call)
async function quickTokenCheck() {
try {
let result = { copus_token: null };
if (chrome?.storage?.local) {
result = await chrome.storage.local.get(['copus_token']);
} else {
// Fallback to localStorage
result.copus_token = localStorage.getItem('copus_token');
}
// Return true if token exists and looks like a JWT
if (result.copus_token && result.copus_token.split('.').length === 3) {
return true;
}
return false;
} catch (error) {
console.error('[Copus Extension] Quick token check failed:', error);
return false;
}
}
// Notification functions
async function fetchUnreadNotificationCount() {
try {
console.log('[Copus Extension] Fetching unread notification count...');
// Check if user is authenticated
let result = { copus_token: null };
if (chrome?.storage?.local) {
result = await chrome.storage.local.get(['copus_token']);
} else {
result.copus_token = localStorage.getItem('copus_token');
}
if (!result.copus_token) {
console.log('[Copus Extension] No token found, setting unread count to 0');
updateNotificationBadge(0);
return;
}
// Fetch unread count from API (plugin-specific endpoint)
const apiBaseUrl = getApiBaseUrl();
const response = await fetch(`${apiBaseUrl}/plugin/plugin/user/msg/countMsg`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${result.copus_token}`,
'Content-Type': 'application/json'
}
});
console.log('[Copus Extension] Notification API response status:', response.status);
if (response.ok) {
const responseData = await response.json();
console.log('[Copus Extension] Notification API response:', responseData);
// Handle different API response formats (same logic as main site)
let unreadCount = 0;
if (typeof responseData === 'number') {
unreadCount = responseData;
} else if (responseData.data !== undefined && typeof responseData.data === 'number') {
unreadCount = responseData.data;
} else if (responseData.status === 1 && responseData.data !== undefined) {
unreadCount = typeof responseData.data === 'number' ? responseData.data : 0;
} else if (responseData.count !== undefined && typeof responseData.count === 'number') {
unreadCount = responseData.count;
}
console.log('[Copus Extension] Unread notification count:', unreadCount);
updateNotificationBadge(unreadCount);
} else {
console.log('[Copus Extension] Failed to fetch notification count, setting to 0');
updateNotificationBadge(0);
}
} catch (error) {
console.error('[Copus Extension] Error fetching notification count:', error);
updateNotificationBadge(0);
}
}
function updateNotificationBadge(count) {
console.log('[Copus Extension] Updating notification badge with count:', count);
if (!elements.notificationBadge || !elements.notificationCount) {
console.warn('[Copus Extension] Notification badge elements not found');
return;
}
if (count > 0) {
elements.notificationBadge.style.display = 'flex';
elements.notificationCount.textContent = count > 99 ? '99+' : count.toString();
} else {
elements.notificationBadge.style.display = 'none';
}
}
function handleNotificationClick() {
console.log('[Copus Extension] Notification bell clicked, redirecting to notifications page');
if (chrome?.tabs?.create) {
chrome.tabs.create({
url: 'https://copus.network/notification'
});
} else {
// Fallback - open in same window
window.open('https://copus.network/notification', '_blank');
}
// Close the popup after opening notifications page
window.close();
}
// Helper function to get the API base URL
function getApiBaseUrl() {
// Production API
return 'https://api-prod.copus.network';
}
// Authentication functions
async function checkAuthentication() {
try {
console.log('[Copus Extension] Checking authentication...');
// Check if chrome.storage is available, fallback to localStorage
let result = { copus_token: null, copus_user: null };
if (chrome?.storage?.local) {
result = await chrome.storage.local.get(['copus_token', 'copus_user']);
console.log('[Copus Extension] Chrome storage result:', result);
} else {
console.warn('[Copus Extension] Chrome storage API not available, using localStorage fallback');
// Fallback to localStorage (less reliable but better than nothing)
try {
result.copus_token = localStorage.getItem('copus_token');
result.copus_user = localStorage.getItem('copus_user');
if (result.copus_user) {
result.copus_user = JSON.parse(result.copus_user);
}
console.log('[Copus Extension] localStorage fallback result:', result);
} catch (error) {
console.error('[Copus Extension] localStorage fallback failed:', error);
}
}
if (!result.copus_token) {
console.log('[Copus Extension] No token found in storage');
return { authenticated: false };
}
console.log('[Copus Extension] Token found, validating...');
// Use plugin-specific userInfo endpoint
const apiBaseUrl = getApiBaseUrl();
const apiUrl = `${apiBaseUrl}/plugin/plugin/user/userInfo`;
console.log('[Copus Extension] Using API URL:', apiUrl);
// Verify token validity by making a test API call with the plugin endpoint
const response = await fetch(apiUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${result.copus_token}`,
'Content-Type': 'application/json'
}
});
console.log('[Copus Extension] API response status:', response.status);
if (response.ok) {
const userData = await response.json();
console.log('[Copus Extension] Token is valid');
console.log('[Copus Extension] Full API response:', JSON.stringify(userData, null, 2));
console.log('[Copus Extension] User data structure:', userData.data);
console.log('[Copus Extension] User faceUrl field exists:', 'faceUrl' in (userData.data || {}));
console.log('[Copus Extension] User faceUrl value:', userData.data?.faceUrl);
console.log('[Copus Extension] User faceUrl type:', typeof userData.data?.faceUrl);
console.log('[Copus Extension] User avatar field exists:', 'avatar' in (userData.data || {}));
console.log('[Copus Extension] User avatar value:', userData.data?.avatar);
console.log('[Copus Extension] User avatarUrl field exists:', 'avatarUrl' in (userData.data || {}));
console.log('[Copus Extension] User avatarUrl value:', userData.data?.avatarUrl);
console.log('[Copus Extension] User profileImage field exists:', 'profileImage' in (userData.data || {}));
console.log('[Copus Extension] User profileImage value:', userData.data?.profileImage);
// Update storage with latest user data
if (chrome?.storage?.local) {
await chrome.storage.local.set({
'copus_user': userData.data
});
}
return {
authenticated: true,
user: userData.data
};
} else {
console.log('[Copus Extension] Token is invalid, removing...');
// Token is invalid, remove it
if (chrome?.storage?.local) {
await chrome.storage.local.remove(['copus_token', 'copus_user']);
}
return { authenticated: false };
}
} catch (error) {
console.error('[Copus Extension] Authentication check failed:', error);
return { authenticated: false };
}
}
function showLoginScreen() {
console.log('[Copus Extension] Showing login screen');
elements.loginScreen.style.display = 'flex';
elements.mainContainer.style.display = 'none';
state.isLoggedIn = false;
}
function showMainApp(user = null) {
console.log('[Copus Extension] Showing main app');
elements.loginScreen.style.display = 'none';
elements.mainContainer.style.display = 'flex';
state.isLoggedIn = true;
state.userInfo = user;
// Update user avatar if available
if (user) {
updateUserAvatar(user);
}
}
function updateUserAvatar(user) {
console.log('[Copus Extension] updateUserAvatar called with user:', JSON.stringify(user, null, 2));
const avatarElement = document.querySelector('.avatar div');
console.log('[Copus Extension] Avatar element found:', !!avatarElement);
if (avatarElement && user) {
console.log('[Copus Extension] User object keys:', Object.keys(user));
console.log('[Copus Extension] User faceUrl:', user.faceUrl);
console.log('[Copus Extension] User avatar:', user.avatar);
console.log('[Copus Extension] User avatarUrl:', user.avatarUrl);
console.log('[Copus Extension] User profileImage:', user.profileImage);
console.log('[Copus Extension] User username:', user.username);
// Use the same avatar logic as the main site
// Priority: user.faceUrl (if exists and not empty) → user.avatar → local default profile SVG
const avatarUrl = user.faceUrl ||
user.avatar ||
'profile-default.svg'; // Use local SVG file matching main site
console.log('[Copus Extension] Final avatar URL:', avatarUrl);
console.log('[Copus Extension] Avatar source:', user.faceUrl ? 'user faceUrl' : user.avatar ? 'user avatar' : 'profile-default.svg');
// Test if the image loads successfully
const testImg = new Image();
testImg.onload = function() {
console.log('[Copus Extension] ✅ Image loaded successfully from:', avatarUrl);
avatarElement.style.backgroundImage = `url(${avatarUrl})`;
avatarElement.style.backgroundSize = 'cover';
avatarElement.style.backgroundPosition = 'center';
avatarElement.style.borderRadius = '50%';
avatarElement.textContent = ''; // Remove the placeholder
};
testImg.onerror = function() {
console.error('[Copus Extension] ❌ Failed to load image:', avatarUrl);
console.error('[Copus Extension] Image error event:', this);
console.error('[Copus Extension] Falling back to user initial');
// Use fallback - user initial
const initial = user.username ? user.username.charAt(0).toUpperCase() : 'U';
avatarElement.textContent = initial;
avatarElement.style.backgroundImage = 'none';
};
// Add additional debugging for the image loading process
testImg.onabort = function() {
console.error('[Copus Extension] Image loading aborted:', avatarUrl);
};
console.log('[Copus Extension] Starting image load test...');
testImg.src = avatarUrl;
// Add click handler to redirect to My treasury page
avatarElement.style.cursor = 'pointer';
avatarElement.title = 'Go to My Treasury';
// Remove any existing click handlers
avatarElement.onclick = null;
// Add new click handler
avatarElement.onclick = function() {
console.log('[Copus Extension] Redirecting to My treasury page');
if (chrome?.tabs?.create) {
chrome.tabs.create({
url: 'https://copus.network/my-treasury'
});
} else {
// Fallback - open in same window
window.open('https://copus.network/my-treasury', '_blank');
}
};
}
}
function handleLogin() {
console.log('[Copus Extension] Handling login click');
// Open the Copus login page in a new tab
chrome.tabs.create({
url: 'https://copus.network/login'
}, (tab) => {
console.log('[Copus Extension] Opened login tab:', tab.id);
});
// Close the popup after opening login page
window.close();
}
// Background validation without blocking UI
async function validateUserInBackground() {
console.log('[Copus Extension] Starting background authentication validation...');
// Force a fresh check by asking content scripts to re-validate tokens
try {
if (chrome?.tabs?.query) {
const tabs = await chrome.tabs.query({});
tabs.forEach(tab => {
if (tab.url && (tab.url.includes('localhost:5177') || tab.url.includes('copus'))) {
if (chrome?.tabs?.sendMessage) {
chrome.tabs.sendMessage(tab.id, { type: 'recheckAuth' }).catch(() => {
// Ignore errors if content script not available
});
}
}
});
}
} catch (error) {
console.log('[Copus Extension] Could not message content scripts:', error);
}
// Check authentication status
const authResult = await checkAuthentication();
if (!authResult.authenticated) {
console.log('[Copus Extension] Background validation: User not authenticated');
// Only switch to login if we're not already showing it
if (elements.loginScreen.style.display === 'none') {
showLoginScreen();
}
return;
}
console.log('[Copus Extension] Background validation: User authenticated');
// Update user info if we're showing the main app
if (elements.mainContainer.style.display === 'flex') {
state.isLoggedIn = true;
state.userInfo = authResult.user;
if (authResult.user) {
updateUserAvatar(authResult.user);
}
// Fetch notification count when user is authenticated
fetchUnreadNotificationCount();
// Fetch categories when user is authenticated
fetchCategories();
}
}
async function loginUser() {
console.log('[Copus Extension] Initializing authentication...');
// Force a fresh check by asking content scripts to re-validate tokens
try {
if (chrome?.tabs?.query) {
const tabs = await chrome.tabs.query({});
tabs.forEach(tab => {
if (tab.url && (tab.url.includes('localhost:5177') || tab.url.includes('copus'))) {
if (chrome?.tabs?.sendMessage) {
chrome.tabs.sendMessage(tab.id, { type: 'recheckAuth' }).catch(() => {
// Ignore errors if content script not available
});
}
}
});
}
} catch (error) {
console.log('[Copus Extension] Could not message content scripts:', error);
}
// Check authentication status
const authResult = await checkAuthentication();
if (!authResult.authenticated) {
console.log('[Copus Extension] User not authenticated, showing login screen');
showLoginScreen();
return;
}
console.log('[Copus Extension] User authenticated, showing main app');
showMainApp(authResult.user);
}
async function fetchCategories() {
try {
console.log('[Copus Extension] Fetching categories from API...');
// Get authentication token
let result = { copus_token: null };
if (chrome?.storage?.local) {
result = await chrome.storage.local.get(['copus_token']);
} else {
result.copus_token = localStorage.getItem('copus_token');
}
const headers = {
'Content-Type': 'application/json'
};
// Add authorization header if available
if (result.copus_token) {
headers['Authorization'] = `Bearer ${result.copus_token}`;
console.log('[Copus Extension] Added Authorization header for categories API');
}
// Add timeout to prevent hanging
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 second timeout
const apiBaseUrl = getApiBaseUrl();
const response = await fetch(`${apiBaseUrl}/plugin/plugin/author/article/categoryList`, {
method: 'GET',
headers: headers,
signal: controller.signal
});
clearTimeout(timeoutId);
console.log('[Copus Extension] Categories API response status:', response.status);