-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
2037 lines (1688 loc) · 79.8 KB
/
app.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
document.addEventListener("DOMContentLoaded", () => {
// *************** //
// ** Constants ** //
// *************** //
const defaultRelays = [
'wss://relay.damus.io',
'wss://relay.primal.net',
'wss://relay.nostr.band'
];
const torRelays = [
'ws://oxtrdevav64z64yb7x6rjg4ntzqjhedm5b5zjqulugknhzr46ny2qbad.onion',
'ws://2jsnlhfnelig5acq6iacydmzdbdmg7xwunm4xl6qwbvzacw4lwrjmlyd.onion',
'ws://nostrnetl6yd5whkldj3vqsxyyaq3tkuspy23a3qgx7cdepb4564qgqd.onion'
];
const rateLimitSeconds = 30; // 30-second delay between note sending
const localStorageKey = 'lastSubmitTime';
const eventIdsStorageKey = 'submittedEventIds';
const followingKey = 'followingPubkeys';
const targetRateLimitStorageKey = 'targetSubmissions';
// ********************* //
// ** State variables ** //
// ********************* //
const seenEventIds = new Set();
const seenReplyEventIds = new Set();
const profileCache = {};
const profileFetchQueue = {};
const wsRelays = {};
let rootEventId = null;
let lastEventId = null;
let currentTimeline = 'following'; // Defaults to 'Following'
// ****************** //
// ** DOM Elements ** //
// ****************** //
const form = document.getElementById('eventForm');
const noteInput = document.getElementById('note');
const replyChainCheckbox = document.getElementById('replyChain');
const relayHopCheckbox = document.getElementById('relayHop');
const torRelaysCheckbox = document.getElementById('torRelays');
const submitButton = form.querySelector('button');
const spinner = submitButton.querySelector('.spinner');
const relayList = document.getElementById('relayList');
const searchModal = document.getElementById('searchModal');
const closeSearchModal = document.getElementById('closeSearchModal');
const searchResults = document.getElementById('searchResults');
const profileView = document.getElementById('profileView');
const backButton = document.getElementById('backButton');
const modalProfileBanner = document.getElementById('modalProfileBanner');
const modalProfileAvatar = document.getElementById('modalProfileAvatar');
const modalProfileName = document.getElementById('modalProfileName');
const modalProfileNip05 = document.getElementById('modalProfileNip05');
const modalProfileAbout = document.getElementById('modalProfileAbout');
const modalProfileLnurl = document.getElementById('modalProfileLnurl');
const modalProfileFeed = document.getElementById('modalProfileFeed');
const searchInput = document.getElementById('searchInput');
const followingToggle = document.getElementById('followingToggle');
const globalToggle = document.getElementById('globalToggle');
const modalFollowButton = document.getElementById('modalFollowButton');
const searchModalFollowButton = document.getElementById('searchModalFollowButton');
// ****************************** //
// ** Initialization Functions ** //
// ****************************** //
// Function to handle switching timelines
function switchTimeline(timeline) {
if (currentTimeline === timeline) return;
currentTimeline = timeline;
const followingFeed = document.getElementById('followingFeed');
const globalFeed = document.getElementById('globalFeed');
if (timeline === 'following') {
followingToggle.className = 'toggle-active';
globalToggle.className = 'toggle-inactive';
followingFeed.style.display = 'block';
globalFeed.style.display = 'none';
// No need to fetch the timeline again, just show the existing one
} else if (timeline === 'global') {
followingToggle.className = 'toggle-inactive';
globalToggle.className = 'toggle-active';
followingFeed.style.display = 'none';
globalFeed.style.display = 'block';
fetchTimeline(); // Continue fetching events for Global
}
}
// Function to update the relay list display
function updateRelayList() {
relayList.innerHTML = '';
let selectedRelays;
if (torRelaysCheckbox.checked) {
selectedRelays = torRelays;
} else {
selectedRelays = defaultRelays;
}
selectedRelays.forEach(relayUrl => {
const relayItem = document.createElement('li');
relayItem.textContent = relayUrl;
relayList.appendChild(relayItem);
});
}
// *********************** //
// ** Profile Functions ** //
// *********************** //
// Profile view in search results
function openProfileView(pubkey) {
if (!pubkey) {
console.error('pubkey is undefined when opening profile view.');
return;
}
const profile = getProfile(pubkey);
// Set the pubkey as a data attribute on the banner for easy access
modalProfileBanner.setAttribute('data-pubkey', pubkey); // Ensure this is the correct element
updateProfileView(profile);
updateFollowButton(pubkey, searchModalFollowButton);
modalProfileFeed.innerHTML = '';
fetchUserNotes(pubkey, modalProfileFeed, false);
// Switch from search results to profile view
searchResults.style.display = 'none';
profileView.style.display = 'block';
backButton.style.display = 'block';
searchModalFollowButton.style.display = 'block';
}
function updateProfileView(profile) {
modalProfileBanner.src = profile.banner;
modalProfileAvatar.src = profile.avatar;
modalProfileName.textContent = profile.name;
modalProfileNip05.textContent = profile.nip05 ? `NIP-05: ${profile.nip05}` : '';
modalProfileAbout.textContent = profile.about ? `About: ${profile.about}` : '';
modalProfileLnurl.textContent = profile.lnurl ? `⚡ ${profile.lnurl}` : '';
}
// Reset the modal to its initial state
function resetModal() {
searchResults.style.display = 'none';
profileView.style.display = 'none';
backButton.style.display = 'none';
searchResults.innerHTML = '';
modalProfileFeed.innerHTML = '';
}
// Function to fetch user notes and display them in the profile view
function fetchUserNotes(pubkey, feedElement, isProfileModal = false) {
const userRelays = [...defaultRelays];
const subscriptionId = generateRandomHex(32);
const aggregatedEvents = new Map();
userRelays.forEach(relayUrl => {
const ws = new WebSocket(relayUrl);
let isResolved = false;
ws.onopen = () => {
isResolved = true;
console.log(`Fetching user notes from relay: ${relayUrl}`);
const reqMessage = JSON.stringify([
"REQ",
subscriptionId,
{ kinds: [1], authors: [pubkey], limit: 50 }
]);
ws.send(reqMessage);
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg[0] === "EVENT") {
const nostrEvent = msg[2];
// Deduplicate by event ID
if (!aggregatedEvents.has(nostrEvent.id)) {
aggregatedEvents.set(nostrEvent.id, nostrEvent);
insertSortedEvent(nostrEvent, feedElement, isProfileModal);
}
}
};
ws.onerror = (error) => {
console.error(`Error fetching user notes from relay ${relayUrl}:`, error);
};
ws.onclose = () => {
console.log(`Closed connection to relay: ${relayUrl}`);
};
});
// Function to insert events in real-time, keeping the feed sorted
function insertSortedEvent(event, feedElement, isProfileModal) {
const noteItem = createTimelineItem(event);
const timestamp = event.created_at;
// Find the correct position to insert the new event
let inserted = false;
for (let i = 0; i < feedElement.children.length; i++) {
const existingTimestamp = parseInt(feedElement.children[i].getAttribute('data-timestamp'), 10);
if (timestamp > existingTimestamp) {
feedElement.insertBefore(noteItem, feedElement.children[i]);
inserted = true;
break;
}
}
// If no position is found, append to the end
if (!inserted) {
feedElement.appendChild(noteItem);
}
}
}
// Function to insert a user note into the profile view
function insertUserNoteInProfileView(event) {
const noteItem = createTimelineItem(event);
modalProfileFeed.appendChild(noteItem);
}
// Function to fetch user profile (kind 0) and update the cache
function fetchUserProfile(pubkey, relayUrl, callback) {
// If the profile is already in cache, use it
if (profileCache[pubkey]) {
callback(profileCache[pubkey]);
return;
}
// If a fetch for this pubkey is already in progress, queue the callback
if (profileFetchQueue[pubkey]) {
profileFetchQueue[pubkey].push(callback);
return;
}
// Otherwise, start a new fetch and create a queue for this pubkey
profileFetchQueue[pubkey] = [callback];
const ws = new WebSocket(relayUrl);
ws.onopen = () => {
console.log(`Fetching profile for pubkey: ${pubkey} from relay: ${relayUrl}`);
const subscriptionId = generateRandomHex(32);
const reqMessage = JSON.stringify([
"REQ",
subscriptionId,
{ kinds: [0], authors: [pubkey] }
]);
ws.send(reqMessage);
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg[0] === "EVENT") {
const profileEvent = msg[2];
if (profileEvent.kind === 0) {
// Cache the profile data
cacheProfile(profileEvent);
// Resolve all queued callbacks with the fetched profile data
const profile = getProfile(profileEvent.pubkey);
profileFetchQueue[pubkey].forEach(cb => cb(profile));
delete profileFetchQueue[pubkey];
ws.close();
}
}
};
ws.onerror = (error) => {
console.error(`Error fetching profile from relay ${relayUrl}:`, error);
ws.close();
};
ws.onclose = () => {
console.log(`Closed connection to relay after fetching profile: ${relayUrl}`);
};
}
function cacheProfile(event) {
const pubkey = event.pubkey;
const profile = JSON.parse(event.content);
profileCache[pubkey] = {
name: profile.name || `${pubkey.slice(0, 6)}...${pubkey.slice(-4)}`,
avatar: profile.picture || generatePixelArtAvatar(pubkey),
banner: profile.banner || './images/anon-banner.png',
nip05: profile.nip05 || '',
about: profile.about || '',
lnurl: profile.lud16 || profile.lud06 || ''
};
}
function getProfile(pubkey) {
if (profileCache[pubkey]) {
return profileCache[pubkey];
} else {
// Return a default profile if not cached
return {
name: `${pubkey.slice(0, 6)}...${pubkey.slice(-4)}`,
avatar: generatePixelArtAvatar(pubkey),
banner: './images/anon-banner.png',
nip05: '',
about: '',
lnurl: ''
};
}
}
function generatePixelArtAvatar(seed) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const size = 8;
const scale = 12;
const avatarSize = 40;
const hash = hashString(seed);
canvas.width = avatarSize;
canvas.height = avatarSize;
// Apply a random background color
const backgroundColor = getRandomBackgroundColor(hash);
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, avatarSize, avatarSize);
// Generate the 8x8 pattern
for (let y = 0; y < size; y++) {
for (let x = 0; x < size / 2; x++) {
const isFilled = hash.charCodeAt((y * size) + x) % 2 === 0;
ctx.fillStyle = isFilled ? getRandomColor(hash, x, y) : backgroundColor;
ctx.fillRect(x * scale, y * scale, scale, scale);
ctx.fillRect((size - x - 1) * scale, y * scale, scale, scale);
}
}
return canvas.toDataURL();
}
function getRandomBackgroundColor(hash) {
const r = (hash.charCodeAt(0) * 31) % 255;
const g = (hash.charCodeAt(1) * 31) % 255;
const b = (hash.charCodeAt(2) * 31) % 255;
return `rgb(${r}, ${g}, ${b})`;
}
function getRandomColor(hash, x, y) {
const r = (hash.charCodeAt((x + y) % hash.length) * 31) % 255;
const g = (hash.charCodeAt((y + 1) % hash.length) * 31) % 255;
const b = (hash.charCodeAt((x + 2) % hash.length) * 31) % 255;
return `rgb(${r}, ${g}, ${b})`;
}
function openProfileModal(pubkey) {
if (!pubkey) {
console.error('pubkey is undefined when opening profile modal.');
return;
}
const profile = getProfile(pubkey);
// Set the pubkey as a data attribute on the banner for easy access
profileBanner.setAttribute('data-pubkey', pubkey);
// Update the modal with cached data
profileBanner.src = profile.banner;
profileAvatar.src = profile.avatar;
profileName.textContent = profile.name;
profileNip05.textContent = profile.nip05 ? `NIP-05: ${profile.nip05}` : '';
profileAbout.textContent = profile.about ? `About: ${profile.about}` : '';
profileLnurl.textContent = profile.lnurl ? `⚡ ${profile.lnurl}` : '';
updateFollowButton(pubkey, modalFollowButton);
// Clear previous notes
profileFeed.innerHTML = '';
// Fetch the user's notes and populate the profile feed
fetchUserNotes(pubkey, profileFeed, true);
profileModal.style.display = 'flex';
modalFollowButton.style.display = 'block'; // Ensure the follow button is visible
}
function closeProfileModal() {
profileModal.style.display = 'none';
}
function updateReplyItemWithProfile(replyItem, pubkey) {
const profile = getProfile(pubkey);
// Update the author's name and avatar in the reply item
const authorNameElement = replyItem.querySelector('.author');
const avatarElement = replyItem.querySelector('.avatar');
if (authorNameElement) {
authorNameElement.textContent = profile.name;
}
if (avatarElement) {
avatarElement.src = profile.avatar;
}
}
// Function to update the follow button state
function updateFollowButton(pubkey, button) {
const following = getFollowingPubkeys();
if (following.includes(pubkey)) {
button.textContent = 'Unfollow';
} else {
button.textContent = 'Follow';
}
}
// Function to handle follow/unfollow actions
function toggleFollow(pubkey, button) {
if (!pubkey) {
console.error('Cannot toggle follow state; pubkey is null');
return;
}
let following = getFollowingPubkeys();
console.log('Current following list before toggle:', following);
if (following.includes(pubkey)) {
// Unfollow: Remove the pubkey from the list
following = following.filter(pk => pk !== pubkey);
console.log(`Unfollowed ${pubkey}. Updated following list:`, following);
button.textContent = 'Follow';
} else {
// Follow: Add the pubkey to the list
following.push(pubkey);
console.log(`Followed ${pubkey}. Updated following list:`, following);
button.textContent = 'Unfollow';
}
// Update the localStorage with the new following list
localStorage.setItem(followingKey, JSON.stringify(following));
console.log('Updated localStorage:', localStorage.getItem(followingKey));
// Refresh the following timeline to include notes from newly followed users
fetchFollowingTimeline();
}
// Get the list of followed pubkeys from localStorage
function getFollowingPubkeys() {
const following = JSON.parse(localStorage.getItem(followingKey)) || [];
console.log('Fetched following list from localStorage:', following);
return following;
}
// ************************ //
// ** Timeline Functions ** //
// ************************ //
// Function to fetch the timeline for followed users
function fetchFollowingTimeline() {
const followingFeed = document.getElementById('followingFeed');
followingFeed.innerHTML = ''; // Clear the existing following timeline
showSpinner(followingFeed); // Show spinner for following timeline
// Close and clear existing WebSocket connections
for (const relayUrl in wsRelays) {
if (wsRelays[relayUrl]) {
wsRelays[relayUrl].close();
delete wsRelays[relayUrl];
}
}
const following = getFollowingPubkeys();
if (following.length === 0) {
// Create and insert the "not following anyone" message directly in the following timeline
const noFollowingMessage = document.createElement('div');
noFollowingMessage.className = 'no-following-message';
noFollowingMessage.textContent = 'You are not following anyone yet.';
followingFeed.appendChild(noFollowingMessage);
hideSpinner(followingFeed); // Hide the spinner since there's no content to load
return;
}
for (const relayUrl of defaultRelays) {
const ws = new WebSocket(relayUrl);
wsRelays[relayUrl] = ws;
ws.onopen = () => {
const subscriptionId = generateRandomHex(32);
const reqMessage = JSON.stringify([
"REQ",
subscriptionId,
{ kinds: [1], authors: following, limit: 100 }
]);
ws.send(reqMessage);
// Subscribe to kind 0 events to get display names and avatars
const profileReqMessage = JSON.stringify([
"REQ",
generateRandomHex(32),
{ kinds: [0], authors: following }
]);
ws.send(profileReqMessage);
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg[0] === "EVENT") {
const nostrEvent = msg[2];
if (nostrEvent.kind === 0) {
// Cache the profile data
cacheProfile(nostrEvent);
// Update any existing timeline items with the new profile data
updateTimelineItemsWithProfileData(nostrEvent.pubkey);
} else if (nostrEvent.kind === 1 && !seenEventIds.has(nostrEvent.id)) {
seenEventIds.add(nostrEvent.id);
// Immediately render the timeline item
const newTimelineItem = createTimelineItem(nostrEvent);
followingFeed.append(newTimelineItem);
hideSpinner(followingFeed); // Hide spinner on first message
}
}
};
ws.onerror = (error) => {
console.error(`Error fetching following timeline from relay ${relayUrl}:`, error);
hideSpinner(followingFeed); // Hide spinner on error
};
ws.onclose = () => {
console.log(`Closed connection to relay: ${relayUrl}`);
delete wsRelays[relayUrl];
};
}
}
// Function to fetch the global timeline
function fetchTimeline() {
const globalFeed = document.getElementById('globalFeed');
globalFeed.innerHTML = ''; // Clear the existing global timeline
showSpinner(globalFeed); // Show spinner for global timeline
for (const relayUrl of defaultRelays) {
subscribeToRelayForGlobalFeed(relayUrl);
}
}
function createTimelineItem(event) {
const timelineItem = document.createElement('div');
timelineItem.className = 'timeline-item';
const authorHex = event.pubkey;
// Get the author's display name and avatar
const { name: authorName, avatar: authorAvatar } = getProfile(authorHex);
// Convert the Unix timestamp to a human-readable format
const timestamp = new Date(event.created_at * 1000).toLocaleString();
// Convert image URLs in the content to <img> tags
const contentWithImages = convertMediaUrlsToElements(event.content);
// Construct the HTML structure
timelineItem.innerHTML = `
<div class="timeline-header">
<img src="${authorAvatar}" alt="${authorName}'s avatar" class="avatar">
<span class="author" data-pubkey="${authorHex}">${authorName}</span>
<span class="timestamp">${timestamp}</span>
</div>
<p>${contentWithImages}</p>
<span class="reply-icon" data-note-id="${event.id}">↩️</span>
`;
// Add event listener to reply icon
const replyIcon = timelineItem.querySelector('.reply-icon');
if (replyIcon) {
replyIcon.addEventListener('click', () => {
handleReplyIconClick(timelineItem, event.id);
});
}
// Add event listener to author's name
const authorNameElement = timelineItem.querySelector('.author');
if (authorNameElement) {
authorNameElement.addEventListener('click', () => {
openProfileModal(authorHex);
});
}
// Add event listener to avatar image
const avatarElement = timelineItem.querySelector('.avatar');
if (avatarElement) {
avatarElement.addEventListener('click', () => {
openProfileModal(authorHex);
});
}
return timelineItem;
}
function createTimelineItemForSearch(event) {
const timelineItem = document.createElement('div');
timelineItem.className = 'timeline-item';
const authorHex = event.pubkey;
// Get the author's display name and avatar
const { name: authorName, avatar: authorAvatar } = getProfile(authorHex);
// Convert the Unix timestamp to a human-readable format
const timestamp = new Date(event.created_at * 1000).toLocaleString();
// Convert image URLs in the content to <img> tags
const contentWithImages = convertMediaUrlsToElements(event.content);
timelineItem.innerHTML = `
<div class="timeline-header">
<img src="${authorAvatar}" alt="${authorName}'s avatar" class="avatar">
<span class="author" data-pubkey="${authorHex}">${authorName}</span>
<span class="timestamp">${timestamp}</span>
</div>
<p>${contentWithImages}</p>
<span class="reply-icon" data-note-id="${event.id}">↩️</span>
`;
const replyIcon = timelineItem.querySelector('.reply-icon');
replyIcon.addEventListener('click', () => {
handleReplyIconClick(timelineItem, event.id);
});
const authorNameElement = timelineItem.querySelector('.author');
const avatarElement = timelineItem.querySelector('.avatar');
// Determine which profile modal to open based on the context
const openProfile = () => {
if (searchModal.style.display === 'flex') {
openProfileView(authorHex); // Open profile in the search modal
} else {
openProfileModal(authorHex); // Open the regular profile modal
}
};
authorNameElement.addEventListener('click', openProfile);
avatarElement.addEventListener('click', openProfile);
return timelineItem;
}
// Function to update timeline items with new profile data
function updateTimelineItemsWithProfileData(pubkey) {
const profile = getProfile(pubkey);
const timelineItems = document.querySelectorAll(`.timeline-item .author[data-pubkey="${pubkey}"]`);
timelineItems.forEach(item => {
const avatarElement = item.closest('.timeline-header').querySelector('.avatar');
item.textContent = profile.name;
avatarElement.src = profile.avatar;
});
}
function subscribeToRelayForGlobalFeed(relayUrl) {
const ws = new WebSocket(relayUrl);
wsRelays[relayUrl] = ws;
ws.onopen = () => {
console.log(`Connected to relay: ${relayUrl}`);
// Send a REQ message to subscribe to text notes (kind 1)
const subscriptionId = generateRandomHex(32);
const reqMessage = JSON.stringify([
"REQ",
subscriptionId,
{ kinds: [1], limit: 100 } // Add the limit filter here
]);
ws.send(reqMessage);
console.log(`Subscribed to relay ${relayUrl} with message: ${reqMessage}`);
// Subscribe to kind 0 events to get display names and avatars
const profileReqMessage = JSON.stringify([
"REQ",
generateRandomHex(32),
{ kinds: [0] }
]);
ws.send(profileReqMessage);
console.log(`Subscribed to relay ${relayUrl} for user profiles with message: ${profileReqMessage}`);
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg[0] === "EVENT") {
const nostrEvent = msg[2];
if (nostrEvent.kind === 0) {
// Cache the profile data as it comes in
cacheProfile(nostrEvent);
// Update any existing timeline items with the new profile data
updateTimelineItemsWithProfileData(nostrEvent.pubkey);
} else if (nostrEvent.kind === 1 && !seenEventIds.has(nostrEvent.id)) {
seenEventIds.add(nostrEvent.id);
const newTimelineItem = createTimelineItem(nostrEvent);
const globalFeed = document.getElementById('globalFeed');
globalFeed.prepend(newTimelineItem);
hideSpinner(globalFeed); // Hide spinner after the first message
}
}
};
ws.onerror = (error) => {
console.error(`Error with relay ${relayUrl}:`, error);
const globalFeed = document.getElementById('globalFeed');
hideSpinner(globalFeed); // Hide spinner on error
};
ws.onclose = () => {
console.log(`Disconnected from relay: ${relayUrl}`);
delete wsRelays[relayUrl];
};
}
// Function to fetch replies for specific saved event IDs
function fetchReplies() {
const repliesFeed = document.getElementById('repliesFeed');
repliesFeed.innerHTML = ''; // Clear the existing replies feed
showSpinner(repliesFeed); // Show spinner for replies feed
const eventIds = getSavedEventIds();
if (eventIds.length === 0) {
console.log('No event IDs found to fetch replies for.');
hideSpinner(repliesFeed); // Hide spinner if no event IDs
return;
}
for (const relayUrl of defaultRelays) {
subscribeToRepliesInitialLoad(relayUrl, eventIds);
}
}
// ****************************** //
// ** Reply Handling Functions ** //
// ****************************** //
function handleReplyIconClick(timelineItem, eventId) {
// Check if a reply textarea already exists
let replyTextarea = timelineItem.querySelector('.reply-textarea');
let sendReplyButton = timelineItem.querySelector('.send-reply-button');
let replyForm = timelineItem.querySelector('.reply-form');
if (!replyTextarea) {
// Create a new reply form with textarea, checkboxes, and button
replyForm = document.createElement('div');
replyForm.className = 'reply-form';
replyTextarea = document.createElement('textarea');
replyTextarea.className = 'reply-textarea';
replyTextarea.rows = 4;
replyTextarea.placeholder = 'Write your reply...';
sendReplyButton = document.createElement('button');
sendReplyButton.className = 'send-reply-button';
sendReplyButton.textContent = 'Send Reply';
// Create checkboxes for reply options with tooltips
const replyOptions = document.createElement('div');
replyOptions.className = 'checkbox-group';
replyOptions.innerHTML = `
<div class="checkbox-container">
<input type="checkbox" class="reply-chain-checkbox">
<label for="replyChain">Reply chain</label>
<div class="tooltip">ℹ️
<span class="tooltiptext">Enable this to link your notes as replies in a threaded conversation, maintaining the context within a linked chain of notes.</span>
</div>
</div>
<div class="checkbox-container">
<input type="checkbox" class="relay-hop-checkbox">
<label for="relayHop">Relay hop</label>
<div class="tooltip">ℹ️
<span class="tooltiptext">Relay hopping adds obfuscation by spreading notes across different relays randomly, making it harder for any single relay to correlate and track the notes.</span>
</div>
</div>
<div class="checkbox-container">
<input type="checkbox" class="tor-relays-checkbox">
<label for="torRelays">Tor relays</label>
<div class="tooltip">ℹ️
<span class="tooltiptext">Use only relays behind onion services for added anonymity.</span>
</div>
</div>
`;
// Append the textarea, checkboxes, and button to the reply form
replyForm.appendChild(replyTextarea);
replyForm.appendChild(replyOptions);
replyForm.appendChild(sendReplyButton);
// Append the reply form to the timeline item
timelineItem.appendChild(replyForm);
// Add event listener to the send button
sendReplyButton.addEventListener('click', () => {
sendReply(replyTextarea.value, eventId, timelineItem, replyForm);
});
} else {
// Toggle the visibility of the existing reply form
const isHidden = replyForm.style.display === 'none';
replyForm.style.display = isHidden ? 'block' : 'none';
}
}
async function sendReply(content, parentId, timelineItem, replyForm) {
const sendReplyButton = replyForm.querySelector('.send-reply-button');
const spinner = document.createElement('div');
spinner.className = 'spinner';
sendReplyButton.appendChild(spinner);
const replyStatusNote = replyForm.querySelector('.note') || document.createElement('div');
replyStatusNote.className = 'note';
replyStatusNote.style.display = 'none';
replyForm.appendChild(replyStatusNote);
try {
const currentTime = Math.floor(Date.now() / 1000);
const lastSubmitTime = parseInt(localStorage.getItem(localStorageKey), 10) || 0;
const timeSinceLastSubmit = currentTime - lastSubmitTime;
if (timeSinceLastSubmit < rateLimitSeconds) {
const timeLeft = rateLimitSeconds - timeSinceLastSubmit;
showReplyNote(`Please wait ${timeLeft} second(s) before submitting again.`, 'warning', replyStatusNote);
resetReplyFormState(spinner, sendReplyButton);
return;
}
spinner.style.display = 'inline-block';
sendReplyButton.disabled = true;
// Generate a new key pair for each reply
const sk = NostrTools.generateSecretKey();
const pubKey = NostrTools.getPublicKey(sk);
// Determine the selected relays
const torRelaysChecked = replyForm.querySelector('.tor-relays-checkbox').checked;
let selectedRelays;
if (torRelaysChecked) {
selectedRelays = torRelays;
} else {
selectedRelays = defaultRelays;
}
// Generate and send kind 0 event (anon profile)
const kind0Event = createAnonKind0Event(pubKey, sk);
let kind0Success = false;
const replyChainChecked = replyForm.querySelector('.reply-chain-checkbox').checked;
const relayHopChecked = replyForm.querySelector('.relay-hop-checkbox').checked;
if (relayHopChecked) {
kind0Success = await sendNoteToRelayWithHop(kind0Event, selectedRelays);
} else {
kind0Success = await sendNoteToRelayDirect(kind0Event, selectedRelays);
}
// Proceed only if kind 0 event was sent successfully
if (!kind0Success) {
showReplyNote('Failed to send profile data. Please try again.', 'error', replyStatusNote);
resetReplyFormState(spinner, sendReplyButton);
return;
}
// Generate a hash of the reply content
const contentHash = hashString(content);
// Check for duplicate submissions
let previousSubmissions = JSON.parse(localStorage.getItem('submittedContentHashes')) || [];
const oneHourAgo = Math.floor(Date.now() / 1000) - 3600;
// Filter out old submissions (older than 1 hour)
previousSubmissions = previousSubmissions.filter(entry => entry.timestamp > oneHourAgo);
// Check if the current content hash is already in the recent submissions
if (previousSubmissions.some(entry => entry.hash === contentHash)) {
showReplyNote('Duplicate submission detected. Please modify your reply before resubmitting.', 'warning', replyStatusNote);
resetReplyFormState(spinner, sendReplyButton);
return;
}
const tags = [["e", parentId, "", "reply"]];
let targetKeys = [parentId]; // Start with the parent event ID for rate limiting
if (replyChainChecked && lastEventId) {
tags.push(["e", lastEventId, "", "reply"]);
if (rootEventId && !tags.some(tag => tag[1] === rootEventId)) {
tags.unshift(["e", rootEventId, "", "root"]);
targetKeys.push(rootEventId); // Include the root event ID in rate limiting
}
}
// Handle mentions and hashtags in the reply content
const nip19Regex = /([a-z]{1,}[1][qpzry9x8gf2tvdw0s3jn54khce6mua7l]{6,})/gi;
const hashtagRegex = /#\w+/g;
const matches = content.match(nip19Regex);
if (matches) {
for (const match of matches) {
try {
const decoded = NostrTools.nip19.decode(match);
const hexKey = decoded.data;
if (decoded.type === 'note' || decoded.type === 'npub' || decoded.type === 'nprofile') {
tags.push([decoded.type === 'note' ? "e" : "p", hexKey, "", "mention"]);
targetKeys.push(hexKey); // Add the mentioned note or pubkey as a target for rate limiting
}
} catch (error) {
console.error('Error decoding NIP-19 identifier:', error);
}
}
}
// Handle hashtags
const hashtags = content.match(hashtagRegex);
if (hashtags) {
for (const tag of hashtags) {
tags.push(["t", tag.substring(1)]);
targetKeys.push(tag.toLowerCase());
}
}
// Apply rate limiting to all target keys
for (const targetKey of targetKeys) {
if (!checkAndUpdateRateLimit(targetKey)) {
showReplyNote(`You have reached the limit of 10 replies per hour to this note, pubkey, or hashtag. Please try again later.`, 'warning', replyStatusNote);
resetReplyFormState(spinner, sendReplyButton);
return;
}
}
const eventTemplate = {
kind: 1,
pubkey: pubKey,
created_at: Math.floor(Date.now() / 1000),
tags: tags,
content: content
};
const signedEvent = NostrTools.finalizeEvent(eventTemplate, sk);
const replyEventId = signedEvent.id;
try {
let relaySuccess = false;
if (relayHopChecked) {
let availableRelays = [...selectedRelays];
while (!relaySuccess && availableRelays.length > 0) {
const randomIndex = Math.floor(Math.random() * availableRelays.length);
const randomRelay = availableRelays[randomIndex];
const relayResult = await sendNoteToRelay(randomRelay, signedEvent);
if (relayResult.success) {
relaySuccess = true;
const eventLink = `https://njump.me/${replyEventId}`;
showReplyNote(`Anon reply sent successfully via relay hop! <a href="${eventLink}" target="_blank">View Event</a>`, 'success', replyStatusNote);
timelineItem.querySelector('.reply-textarea').value = '';
// Store the content hash with the current timestamp to prevent duplicate submissions
previousSubmissions.push({ hash: contentHash, timestamp: currentTime });
localStorage.setItem('submittedContentHashes', JSON.stringify(previousSubmissions));
localStorage.setItem(localStorageKey, currentTime);
renewReplySubscriptions();
} else {
availableRelays.splice(randomIndex, 1);
console.warn(`Relay hop failed for relay: ${randomRelay}. Trying another relay...`);
}
}
if (!relaySuccess) {
showReplyNote('Relay hopping failed for all relays. Please try again later.', 'error', replyStatusNote);
}
} else {
const relayResults = await Promise.all(
selectedRelays.map(relayUrl => sendNoteToRelay(relayUrl, signedEvent))
);
const successfulRelays = relayResults.filter(result => result.success).length;