-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsidepanel.js
More file actions
4836 lines (4133 loc) · 160 KB
/
sidepanel.js
File metadata and controls
4836 lines (4133 loc) · 160 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
const state = {
coverImage: null,
coverSourceType: null,
coverImageFile: null, // Store original file for upload
images: [],
activeTabId: null,
activeWindowId: null,
imageSelectionVisible: false,
pageTitle: '',
pageUrl: '',
lastLoadedUrl: '', // Track URL that was successfully loaded (for change detection)
authToken: null,
userInfo: null,
isLoggedIn: false,
// Treasury selection state
selectedTreasuries: [], // Array of { id: number, name: string, spaceType: number } - SAVED selections
tempSelectedTreasuries: [], // Temporary selections in modal - only saved on "Save" click
availableTreasuries: [], // All treasuries from API
treasurySearchQuery: '', // Current search filter
treasuriesCacheTime: 0, // Timestamp of last treasury fetch
treasuriesFetchPromise: null, // In-flight fetch promise to avoid duplicate requests
// x402 payment state
payToVisit: false, // Payment toggle (default off)
paymentAmount: '0.01', // Default payment amount in USD
articleVisibility: 0, // 0=public, 1=private
// Create treasury modal state
createTreasuryAvatarFile: null,
createTreasuryAvatarUrl: null,
createTreasuryCoverFile: null,
createTreasuryCoverUrl: null,
isUploadingTreasuryImage: false,
createTreasuryVisibility: 0, // 0=public, 1=private
// Search state
searchQuery: '',
searchActiveTab: 'all',
searchResults: { articles: [], spaces: [], users: [] },
searchLoading: false,
searchPageIndex: { articles: 1, spaces: 1, users: 1 },
searchHasMore: { articles: false, spaces: false, users: false },
// Notification state
notifications: [],
notificationActiveTab: 'treasury', // 'treasury', 'comment', 'earning'
notificationLoading: false,
notificationPageIndex: 1,
notificationHasMore: false,
// Individual notification counts per category
notificationCounts: {
treasureCount: 0,
commentCount: 0,
earningCount: 0,
totalCount: 0
},
// Traces state - others who curated this URL
traces: [],
tracesLoading: false,
tracesCurrentUrl: '',
tracesCount: 0
};
const elements = {};
// ========== Local storage functions for token management ==========
function saveAuthToken(token) {
try {
localStorage.setItem('copus_auth_token', token);
} catch (error) {
console.error('Failed to save auth token:', error);
}
}
function loadAuthToken() {
try {
const token = localStorage.getItem('copus_auth_token');
return token;
} catch (error) {
console.error('Failed to load auth token:', error);
return null;
}
}
function clearAuthToken() {
try {
localStorage.removeItem('copus_auth_token');
} 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.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');
// Search elements
elements.searchIcon = document.getElementById('search-icon');
elements.searchView = document.getElementById('search-view');
elements.searchBackButton = document.getElementById('search-back-button');
elements.searchInput = document.getElementById('search-input');
elements.searchClearButton = document.getElementById('search-clear-button');
elements.searchTabs = document.getElementById('search-tabs');
elements.searchLoading = document.getElementById('search-loading');
elements.searchEmpty = document.getElementById('search-empty');
elements.searchNoResults = document.getElementById('search-no-results');
elements.searchResultsList = document.getElementById('search-results-list');
// Notification elements (header)
elements.notificationBell = document.getElementById('notification-bell');
elements.notificationBadge = document.getElementById('notification-badge');
elements.notificationCount = document.getElementById('notification-count');
// Notification view elements
elements.notificationView = document.getElementById('notification-view');
elements.notificationBackButton = document.getElementById('notification-back-button');
elements.markAllReadButton = document.getElementById('mark-all-read-button');
elements.notificationTabs = document.getElementById('notification-tabs');
elements.notificationLoading = document.getElementById('notification-loading');
elements.notificationEmpty = document.getElementById('notification-empty');
elements.notificationList = document.getElementById('notification-list');
elements.notificationLoadMore = document.getElementById('notification-load-more');
// Traces elements (others who curated this URL)
elements.tracesIcon = document.getElementById('traces-icon');
elements.tracesView = document.getElementById('traces-view');
elements.tracesBackButton = document.getElementById('traces-back-button');
elements.tracesList = document.getElementById('traces-list');
// Treasury selection elements
elements.treasurySelectButton = document.getElementById('treasury-select-button');
elements.treasurySelectText = document.getElementById('treasury-select-text');
elements.treasuryModal = document.getElementById('treasury-selection-modal');
elements.treasuryModalClose = document.getElementById('treasury-modal-close');
elements.treasurySearchInput = document.getElementById('treasury-search-input');
elements.treasuryList = document.getElementById('treasury-list');
elements.treasuryCreateTrigger = document.getElementById('treasury-create-trigger');
elements.treasuryModalCancel = document.getElementById('treasury-modal-cancel');
elements.treasuryModalSave = document.getElementById('treasury-modal-save');
// Create Treasury Modal elements
elements.createTreasuryModal = document.getElementById('create-treasury-modal');
elements.createTreasuryBackdrop = document.getElementById('create-treasury-backdrop');
elements.createTreasuryClose = document.getElementById('create-treasury-close');
elements.createTreasuryName = document.getElementById('create-treasury-name');
elements.createTreasuryDescription = document.getElementById('create-treasury-description');
elements.createTreasuryDescCounter = document.getElementById('create-treasury-desc-counter');
elements.createTreasuryAvatar = document.getElementById('create-treasury-avatar');
elements.avatarUploadArea = document.getElementById('avatar-upload-area');
elements.avatarEmpty = document.getElementById('avatar-empty');
elements.avatarPreview = document.getElementById('avatar-preview');
elements.avatarRemove = document.getElementById('avatar-remove');
elements.createTreasuryCover = document.getElementById('create-treasury-cover');
elements.coverUploadArea = document.getElementById('cover-upload-area');
elements.treasuryCoverEmpty = document.getElementById('treasury-cover-empty');
elements.treasuryCoverPreview = document.getElementById('treasury-cover-preview');
elements.treasuryCoverRemove = document.getElementById('treasury-cover-remove');
elements.createTreasuryCancel = document.getElementById('create-treasury-cancel');
elements.createTreasurySubmit = document.getElementById('create-treasury-submit');
// Private toggle elements (curation form)
elements.curatePrivateCheckbox = document.getElementById('curate-private-checkbox');
elements.curatePrivatePill = document.getElementById('curate-private-pill');
elements.recommendationRequired = document.getElementById('recommendation-required');
elements.coverRequired = document.getElementById('cover-required');
// Private toggle elements (create treasury modal)
elements.createTreasuryPrivateCheckbox = document.getElementById('create-treasury-private-checkbox');
elements.createTreasuryPrivatePill = document.getElementById('create-treasury-private-pill');
// 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;
}
// First priority: og:image (standard SEO meta tag)
const ogImage = images.find(img => img.isOgImage === true);
if (ogImage) {
return ogImage;
}
// Fallback: find the largest suitable image
const scoredImages = images
.filter(img => {
const width = img.width || 0;
const height = img.height || 0;
// Filter out tiny images
return width >= 100 && height >= 100;
})
.sort((a, b) => {
const areaA = (a.width || 0) * (a.height || 0);
const areaB = (b.width || 0) * (b.height || 0);
return areaB - areaA;
});
return scoredImages[0] || images[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 fetch image via background script (bypasses CORS)
async function fetchImageViaBackground(imageUrl) {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage(
{ type: 'fetchImageAsDataUrl', url: imageUrl },
(response) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
if (!response || !response.success) {
reject(new Error(response?.error || 'Background fetch failed'));
return;
}
resolve({
dataUrl: response.dataUrl,
mimeType: response.mimeType,
size: response.size
});
}
);
});
}
// Helper function to convert data URL or image URL to File object
async function convertImageToFile(imageSrc, fileName = 'cover-image.png') {
try {
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);
}
const file = new File([arrayBuffer], fileName, { type: mimeType });
return file;
} else {
// Handle regular URLs (detected images) - may have CORS issues
// Try direct fetch first
try {
const response = await fetch(imageSrc, { mode: 'cors' });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const blob = await response.blob();
if (blob.size === 0) {
throw new Error('Empty blob received');
}
const mimeType = blob.type || 'image/png';
// Handle special MIME types like 'image/svg+xml' -> 'svg'
let extension = mimeType.split('/')[1] || 'png';
if (extension.includes('+')) {
extension = extension.split('+')[0]; // 'svg+xml' -> 'svg'
}
const file = new File([blob], `${fileName.split('.')[0]}.${extension}`, { type: mimeType });
return file;
} catch (fetchError) {
console.warn('[Copus Extension] Direct fetch failed (likely CORS), trying background script:', fetchError.message);
// Fallback 1: Use background script to fetch (bypasses CORS)
try {
const bgResult = await fetchImageViaBackground(imageSrc);
// Convert data URL to File
const dataUrlParts = bgResult.dataUrl.split(',');
const mimeMatch = dataUrlParts[0].match(/data:([^;]+);/);
const mimeType = mimeMatch ? mimeMatch[1] : bgResult.mimeType || '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);
}
// Handle special MIME types like 'image/svg+xml' -> 'svg'
let extension = mimeType.split('/')[1] || 'png';
if (extension.includes('+')) {
extension = extension.split('+')[0]; // 'svg+xml' -> 'svg'
}
const file = new File([arrayBuffer], `${fileName.split('.')[0]}.${extension}`, { type: mimeType });
return file;
} catch (bgError) {
console.warn('[Copus Extension] Background fetch failed, trying canvas approach:', bgError.message);
// Fallback 2: Use canvas to convert image (works for cross-origin if image is already loaded)
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = 'anonymous'; // Try to request with CORS
img.onload = () => {
try {
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth || img.width;
canvas.height = img.naturalHeight || img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
canvas.toBlob((blob) => {
if (blob && blob.size > 0) {
const file = new File([blob], fileName, { type: 'image/png' });
resolve(file);
} else {
reject(new Error('Canvas toBlob failed - image may be tainted by CORS'));
}
}, 'image/png', 0.95);
} catch (canvasError) {
reject(new Error('Canvas conversion failed: ' + canvasError.message));
}
};
img.onerror = () => {
reject(new Error('Failed to load image for canvas conversion'));
};
// Set src after handlers to ensure they fire
img.src = imageSrc;
});
}
}
}
} catch (error) {
console.error('[Copus Extension] Error converting image to file:', error);
throw new Error('Failed to convert image: ' + error.message);
}
}
async function uploadImageToS3(file) {
try {
// 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');
}
if (!result.copus_token) {
throw new Error('Please log in to upload images. No authentication token found.');
}
const formData = new FormData();
formData.append('file', file);
const headers = {
'Authorization': `Bearer ${result.copus_token}`
};
const apiBaseUrl = getApiBaseUrl();
const uploadUrl = `${apiBaseUrl}/client/common/uploadImage2S3`;
// Add timeout to prevent hanging on slow uploads
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 120000); // 120 second timeout for large uploads
let response;
try {
response = await fetch(uploadUrl, {
method: 'POST',
headers: headers,
body: formData,
signal: controller.signal
});
clearTimeout(timeoutId);
} catch (error) {
clearTimeout(timeoutId);
console.error('[Copus Extension] Fetch error:', error);
if (error.name === 'AbortError') {
throw new Error('Image upload timed out after 120 seconds');
}
// Check if it's a CORS error
if (error.message.includes('Failed to fetch') || error.message.includes('NetworkError')) {
throw new Error('Network error: Please check your connection or try again. The server may have rejected the request (CORS).');
}
throw error;
}
// Get response text first for debugging
const responseText = await response.text();
if (!response.ok) {
// Try to parse error message from response
try {
const errorData = JSON.parse(responseText);
throw new Error(errorData.msg || errorData.message || `Image upload failed (${response.status})`);
} catch (parseError) {
throw new Error(`Image upload failed (${response.status}): ${responseText.substring(0, 200)}`);
}
}
let responseData;
try {
responseData = JSON.parse(responseText);
} catch (parseError) {
throw new Error('Invalid JSON response from upload API: ' + responseText.substring(0, 200));
}
// 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 - check multiple possible response formats
let imageUrl = null;
if (responseData.data) {
if (typeof responseData.data === 'string') {
imageUrl = responseData.data;
} else if (responseData.data.url) {
imageUrl = responseData.data.url;
}
}
if (!imageUrl) {
imageUrl = responseData.url || responseData.imageUrl;
}
if (!imageUrl) {
console.error('Response structure:', JSON.stringify(responseData, null, 2));
throw new Error('No image URL returned from upload API');
}
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;
// 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() {
window.close();
}
function goBackToMain() {
elements.imageSelectionView.hidden = true;
elements.compactMain.hidden = false;
}
function openImageSelectionView() {
// Don't proceed if button is disabled
if (elements.imageSelectionToggle.disabled) {
return;
}
// Load page data only when user clicks detect
if (!Array.isArray(state.images) || state.images.length === 0) {
// Load page data on demand
loadPageData(state.activeTabId).then(() => {
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;
}
showImageSelection();
}
function showImageSelection() {
// 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) {
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() {
// Show cropper for detected image (same as uploaded image)
imageCropper.showFromUrl(image.src, (croppedFile) => {
if (croppedFile) {
// Cropping succeeded - use cropped image
const reader = new FileReader();
reader.onload = function(e) {
setCoverImage({ src: e.target.result }, 'page', croppedFile);
goBackToMain();
};
reader.readAsDataURL(croppedFile);
}
// If cancelled (croppedFile is null), stay in image selection view
});
});
elements.imageSelectionGrid.appendChild(button);
});
}
// Show 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) => {
const timeoutId = setTimeout(() => {
reject(new Error('Page data fetch timeout'));
}, 400);
chrome.tabs.sendMessage(tabId, { type: 'collectPageData' }, (response) => {
clearTimeout(timeoutId);
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve(response);
});
});
}
// Fetch page data with retry - waits for React Helmet to potentially update og:image
// Used for SPA navigation where meta tags might update after initial render
async function fetchPageDataWithRetry(tabId) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error('Page data fetch timeout'));
}, 3000); // Longer timeout since we're waiting for og:image to update
chrome.tabs.sendMessage(tabId, { type: 'collectPageDataWithRetry' }, (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 {
// 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) {
updateNotificationBadge(0);
return;
}
// Fetch unread count from API (plugin-specific endpoint)
const apiBaseUrl = getApiBaseUrl();
const response = await fetch(`${apiBaseUrl}/client/user/msg/countMsg`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${result.copus_token}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const responseData = await response.json();
// Handle API response format: { status: 1, data: { commentCount, earningCount, totalCount, treasureCount } }
let counts = { treasureCount: 0, commentCount: 0, earningCount: 0, totalCount: 0 };
if (responseData.status === 1 && responseData.data) {
// New detailed format with individual counts
if (typeof responseData.data === 'object' && responseData.data.totalCount !== undefined) {
counts = {
treasureCount: responseData.data.treasureCount || 0,
commentCount: responseData.data.commentCount || 0,
earningCount: responseData.data.earningCount || 0,
totalCount: responseData.data.totalCount || 0
};
} else if (typeof responseData.data === 'number') {
// Legacy format where data is just a number
counts.totalCount = responseData.data;
}
} else if (typeof responseData === 'number') {
counts.totalCount = responseData;
} else if (responseData.count !== undefined) {
counts.totalCount = responseData.count;
}
// Store counts in state
state.notificationCounts = counts;
updateNotificationBadge(counts.totalCount);
updateNotificationTabBadges(counts);
} else {
updateNotificationBadge(0);
}
} catch (error) {
console.error('[Copus Extension] Error fetching notification count:', error);
updateNotificationBadge(0);
}
}
function updateNotificationBadge(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';
}
}
// Update red dots on notification tabs based on individual counts
function updateNotificationTabBadges(counts) {
const tabs = document.querySelectorAll('.notification-tab');
tabs.forEach(tab => {
const tabType = tab.dataset.tab;
let hasUnread = false;
if (tabType === 'treasury') {
hasUnread = counts.treasureCount > 0;
} else if (tabType === 'comment') {
hasUnread = counts.commentCount > 0;
} else if (tabType === 'earning') {
hasUnread = counts.earningCount > 0;
}
// Find or create the red dot element
let dot = tab.querySelector('.tab-unread-dot');
if (hasUnread) {
if (!dot) {
dot = document.createElement('span');
dot.className = 'tab-unread-dot';
tab.appendChild(dot);
}
dot.style.display = 'block';
} else if (dot) {
dot.style.display = 'none';
}
});
}
// Start periodic polling for notification count (every 60 seconds, like mainsite)
let notificationPollInterval = null;
function startNotificationPolling() {
if (notificationPollInterval) return; // Already polling
notificationPollInterval = setInterval(() => {
// Only poll if user is logged in
if (state.isLoggedIn) {
fetchUnreadNotificationCount();
}
}, 60000); // 60 seconds
}
function stopNotificationPolling() {
if (notificationPollInterval) {
clearInterval(notificationPollInterval);
notificationPollInterval = null;
}
}
function handleSearchClick() {
// Open the search view
openSearchView();
}
// ========== Search Functions ==========
function openSearchView() {
if (elements.searchView) {
elements.searchView.hidden = false;
// Hide main content but keep header visible for back navigation
if (elements.compactMain) elements.compactMain.hidden = true;
// Hide header
const header = document.querySelector('.compact-header');
if (header) header.hidden = true;
// Hide image selection view if open
if (elements.imageSelectionView) elements.imageSelectionView.hidden = true;
// Focus the search input
setTimeout(() => {
elements.searchInput?.focus();
}, 100);
}
}
function closeSearchView() {
if (elements.searchView) {
elements.searchView.hidden = true;
// Show main content
if (elements.compactMain) elements.compactMain.hidden = false;
// Show header
const header = document.querySelector('.compact-header');
if (header) header.hidden = false;
// Clear search state
state.searchQuery = '';
state.searchResults = { articles: [], spaces: [], users: [] };
state.searchActiveTab = 'all';
if (elements.searchInput) elements.searchInput.value = '';
updateSearchUI();
}
}
async function performSearch(query, tab = 'all') {
if (!query.trim()) {
state.searchResults = { articles: [], spaces: [], users: [] };
updateSearchUI();
return;
}
state.searchLoading = true;
state.searchQuery = query;
updateSearchUI();
const apiBaseUrl = getApiBaseUrl();
try {
if (tab === 'all') {
// Fetch all categories in parallel
const [articlesRes, spacesRes, usersRes] = await Promise.all([
fetchSearchResults(`${apiBaseUrl}/client/home/searchArticle`, query, 1, 6),
fetchSearchResults(`${apiBaseUrl}/client/home/searchSpace`, query, 1, 6),
fetchSearchResults(`${apiBaseUrl}/client/home/searchUser`, query, 1, 6)
]);
state.searchResults = {
articles: articlesRes.data || [],
spaces: spacesRes.data || [],
users: usersRes.data || []
};
state.searchHasMore = {
articles: articlesRes.pageIndex < articlesRes.pageCount,
spaces: spacesRes.pageIndex < spacesRes.pageCount,
users: usersRes.pageIndex < usersRes.pageCount
};
} else if (tab === 'works') {
const res = await fetchSearchResults(`${apiBaseUrl}/client/home/searchArticle`, query, 1, 20);
state.searchResults.articles = res.data || [];
state.searchHasMore.articles = res.pageIndex < res.pageCount;
state.searchPageIndex.articles = 1;
} else if (tab === 'treasuries') {
const res = await fetchSearchResults(`${apiBaseUrl}/client/home/searchSpace`, query, 1, 20);
state.searchResults.spaces = res.data || [];
state.searchHasMore.spaces = res.pageIndex < res.pageCount;
state.searchPageIndex.spaces = 1;
} else if (tab === 'users') {
const res = await fetchSearchResults(`${apiBaseUrl}/client/home/searchUser`, query, 1, 20);