-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1958 lines (1634 loc) · 70.7 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>NostrPostr</title>
<!-- Favicon for most browsers -->
<link rel="icon" href="/img/favicon_io/favicon.ico" type="image/x-icon">
<!-- PNG icons for better resolution -->
<link rel="icon" type="image/png" sizes="32x32" href="/img/favicon_io/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/img/favicon_io/favicon-16x16.png">
<!-- Apple Touch Icon (for iOS) -->
<link rel="apple-touch-icon" href="/img/favicon_io/apple-touch-icon.png">
<!-- Web Manifest (for PWAs) -->
<link rel="manifest" href="/img/favicon_io/site.webmanifest">
<script src="https://bundle.run/[email protected]"></script>
<script src="https://bundle.run/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/easy.qrcode.min.js"></script>
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="backgroundImages.js"></script>
<script src="background.js"></script>
<script src="font.js"></script>
<script src="fontList.js"></script>
<script src="crypto-js.min.js"></script>
<script src="dec.js"></script>
<script src="bech32.js"></script>
<script src="note1.js"></script>
<!-- <script src="footer.js"></script> // IS AT THE BOTTOM-->
</head>
<body>
<div id="dim-overlay" class="dim-overlay"></div>
<div>
<img id="avatarIcon" class="avatar-icon" src="" alt="Avatar" title="Change ID">
<p id="nostrNameDisplay" class="nostr-name"></p> <!-- Display for nostr_name -->
<h1 id="mainTitle">Freedom to Speak</h1>
<h4 id="subTitle">No Names. Just Unfiltered Truth.</h4>
<div id="paragraphContainer">
<p id="customParagraph" style="margin-top: 1rem;" data-full-content=""></p>
<a href="#" id="readMoreLink" style="display: none;">Read more</a>
</div>
</div>
<div id="warningMessage" style="display: none; color: red; text-align: center; font-size: 2rem; margin: 20px; margin-bottom: 3%;">
<strong>Posting is only available on custom websites. If you'd like to create one, use </strong>
<a href="urlmkr.html" style="color: rgb(30, 255, 0); text-decoration: underline;">URLmkr</a>.
</div>
<!-- <textarea id="userMessage" maxlength="280" oninput="adjustHeight(this)"></textarea> -->
<div class="editor-container">
<textarea id="userMessage" maxlength="280" oninput="updateMarkdown()" placeholder="Type your message..."></textarea>
<div id="markdownPreview" class="overlay markdown-preview"></div>
</div>
<div id="charCount">0/280</div>
<button id="sendMessageBtn" disabled>send
<img src="https://user-images.githubusercontent.com/99301796/219719339-5eff628c-3470-4cc3-81eb-404f8902de9f.gif" id="animatedImg"/>
</button>
<p id="statusMessage"></p>
<p id="relayWarning" style="color:red; display:none; background-color: rgba(0, 0, 0, 0.672);">
Possible connection error! <br>
None of the relays are available please try later. <br>
<span style="color: rgb(239, 219, 0);">Would you like to try the default relays listed bellow?</span> <br>
<span style="color: #00ff5599;">relay.nostr.band, relay.damus.io,
njump.me, relay.snort.social and nos.lol?</span> <br>
<button id="useDefaultRelaysBtn">Yes</button>
<button id="closeRelayWarning">No</button>
</p>
<div id="eventDetails"></div>
<footer class="footerDynamic">
<a href="about.html">About</a> |
<a href="FAQ.html">FAQ</a> |
<a href="urlmkr.html">URLmkr</a> |
<button id="showHistoryBtn" title="a History data of all the posted notes from this device">Show History</button>
</footer>
<!-- Modal for viewing notes -->
<div id="notesModal">
<div id="notesModalContent">
<div id="notesHeader">
<button id="downloadDataBtn">Download Data</button>
</div>
<div id="dynamicContent"></div> <!-- Dynamic content (notes) goes here -->
<div class="panic-container">
<button id="wipeStorageBtn">
❌ Delete All Data (Panic Btn) ❌
</button>
</div>
</div>
</div>
<!-- enter password modal -->
<div id="passwordModal" class="active">
<div>
<h3>Enter Password</h3>
<p id="passwordHint" style="display: none; text-align: center; margin-top: 10px; color: #555;">Password hint:</p>
<input type="password" id="passwordInput" placeholder="Password">
<button id="submitPassword">Submit</button>
<p id="passwordError" style="color: red;">Invalid password. Please try again.</p>
</div>
</div>
<!-- saved passwords notifications -->
<div id="passwordNotification">
<p>
You've already unlocked this page.
To lock it again, press the button below.
</p>
<button id="clearHashes">Clear Stored Hashes</button>
</div>
<!-- modal for viewing media items -->
<div class="fullscreen-modal">
<span class="close-btn">×</span>
<div class="modal-content"></div>
</div>
<!-- QR Code Modal -->
<div id="qr-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.8); justify-content: center; align-items: center;">
<div style="z-index: 10001; background: #fff; padding: 20px; border-radius: 8px; text-align: center;">
<div id="qr-code"></div>
<div id="qr-title">Scan with Nostr app</div>
<button id="close_qr_button" class="copy-button" style="background: #ff4d4d;">Close</button>
</div>
</div>
<script>
// Function to load JSON files
async function loadJson(file) {
const response = await fetch(file);
return response.json();
}
const avatarStyles = {
1: "croodles",
2: "adventurer-neutral",
3: "avataaars",
4: "avataaars-neutral",
5: "big-ears",
6: "big-ears-neutral",
7: "big-smile",
8: "bottts",
9: "bottts-neutral",
10: "adventurer",
11: "croodles-neutral",
12: "fun-emoji",
13: "icons",
14: "identicon",
15: "rings",
16: "lorelei",
17: "lorelei-neutral",
18: "micah",
19: "miniavs",
20: "notionists",
21: "notionists-neutral",
22: "open-peeps",
23: "personas",
24: "pixel-art",
25: "pixel-art-neutral",
26: "shapes",
27: "thumbs",
28: "dylan",
29: "glass",
// 30: "initials",
};
// Function to generate DiceBear avatar URL from public key
function getAvatarUrl(pubkey) {
const storedAvatarUrl = localStorage.getItem("avatar_url");
// If avatar exists in localStorage, return it
if (storedAvatarUrl) {
return storedAvatarUrl;
}
// Otherwise, get avatar style from query parameters (for new IDs)
const { a } = getQueryParams();
const seed = encodeURIComponent(pubkey);
// Determine avatar style or fallback to croodles
const avatarStyle = avatarStyles[a] || "croodles";
// Return generated URL
return `https://api.dicebear.com/9.x/${avatarStyle}/svg?seed=${seed}`;
}
// Function to update the avatar
function updateAvatar() {
const avatar = document.getElementById("avatarIcon");
// Generate URL based on public key and chosen avatar style
const avatarUrl = pub
? getAvatarUrl(pub) + `&cacheBust=${Date.now()}` // Bust cache to force new fetch
: getAvatarUrl("placeholder");
avatar.src = avatarUrl;
console.log("Updated Avatar URL:", avatarUrl);
}
// Function to update the displayed nostr_name under the avatar
function updateNostrNameDisplay() {
const nostrNameDisplay = document.getElementById("nostrNameDisplay");
const nostrName = localStorage.getItem("nostr_name");
if (nostrName) {
nostrNameDisplay.textContent = nostrName;
} else {
// If nostr_name doesn't exist, generate a fallback name
nostrNameDisplay.textContent = generateRandomFallback();
}
}
function applyRandomTiltForNostrName() {
const nostrName = document.getElementById('nostrNameDisplay');
const randomTilt = Math.floor(Math.random() * 31) - 15; // Tilt between -30 to 30 degrees
nostrName.style.transform = `rotate(${randomTilt}deg)`;
}
const randomAvatarStyle = Math.floor(Math.random() * Object.keys(avatarStyles).length) + 1;
function getQueryParams() {
const params = new URLSearchParams(window.location.search);
return {
f: params.has("f") ? params.get("f") : null, // Include font only if present
t: params.has("t") ? params.get("t") : null, // Include title only if present
s: params.has("s") ? params.get("s") : null, // Include subtitle only if present
p: params.get("p") || "", // Paragraph
m: params.get("m") || "", // Message
h: params.get("h") ? params.get("h").split(",").filter(Boolean) : [], // Hashtag
r: params.get("r") ? params.get("r").split(",") : [], // Relay
l: parseInt(params.get("l")) || 280, // Length of a message
b: params.get("b") || "", // Background
// a: parseInt(params.get("a")) || 1, // Avatar style (defaults to 1)
a: parseInt(params.get("a")) || randomAvatarStyle, // Avatar style (defaults to random)
ln: params.get("ln") || "" // Lightning address (reverse format)
};
}
async function setDynamicContent() {
const urlParams = new URLSearchParams(window.location.search); // Define urlParams here
const { t, s, p, m, h, r, l, b } = getQueryParams();
const maxLength = 300; // Maximum characters before truncating
// Handle the title and subtitle
document.getElementById("mainTitle").textContent = t || "Freedom to Speak"; // Show only if `t` exists
document.getElementById("subTitle").textContent = s || "No Names. Just Unfiltered Truth"; // Show only if `s` exists
const paragraph = document.getElementById("customParagraph");
const readMoreLink = document.getElementById("readMoreLink");
if (p) {
// Replace media links first
let processedContent = replaceMediaLinks(p); // Replace media links
// Store the processed content for truncation and expansion
paragraph.setAttribute('data-full-content', processedContent);
// console.log("Content before truncation on page load:", paragraph.innerHTML);
paragraph.setAttribute('data-npub-processed', 'true'); // Mark as processed
// // Truncate content for initial view
// truncateParagraph(paragraph);
// Replace `nostr:npub` strings in the content
processedContent = await replaceNpubStrings(processedContent); // Replace `nostr:npub`
// Truncate content for initial view
truncateParagraph(paragraph);
// Show the "Read More" link
readMoreLink.style.display = "inline";
// Fetch note1 events in the processed content
fetchNote1Strings(processedContent, r);
readMoreLink.onclick = async (e) => {
e.preventDefault();
const expanded = paragraph.getAttribute('data-expanded') === "true";
if (expanded) {
// Collapse content
truncateParagraph(paragraph);
readMoreLink.textContent = "Read more";
paragraph.setAttribute('data-expanded', "false");
} else {
// Expand content
let expandedContent = paragraph.getAttribute('data-full-content');
expandedContent = replaceMediaLinks(expandedContent); // Reapply media links to expanded content
expandedContent = await replaceNpubStrings(expandedContent);
// Skip reprocessing if already processed
// Ensure `replaceNpubStrings` is applied only to raw content
if (!paragraph.getAttribute("data-npub-processed")) {
expandedContent = replaceMediaLinks(expandedContent);
expandedContent = await replaceNpubStrings(expandedContent);
paragraph.setAttribute("data-npub-processed", "true");
}
paragraph.innerHTML = expandedContent;
readMoreLink.textContent = "Close";
paragraph.setAttribute('data-expanded', "true");
// Fetch embedded `note1` events in the expanded content
fetchNote1Strings(paragraph.innerHTML, r);
// Reapply modal listeners
applyModalListenersToMedia(paragraph);
markLikedEvents(); // Mark likes on expanded content
}
};
// Reapply modal listeners
applyModalListenersToMedia(paragraph);
// Fetch `note1` events in the truncated content
fetchNote1Strings(paragraph.innerHTML, r);
// Mark likes for initially visible events
markLikedEvents();
} else {
// If no `p` parameter is provided, set default content and process random GIF links
// List of media links
const mediaLinks = [
"https://media1.tenor.com/m/rec5dlPBK2cAAAAd/mr-bean-waiting.gif",
"https://media1.tenor.com/m/4EElxXeHiZwAAAAC/forrest-gump-wave.gif",
"https://media1.tenor.com/m/g6JYL4ILCFsAAAAd/on-cookies.gif",
"https://media1.tenor.com/m/g_94qXGDaicAAAAd/counter-travolta.gif",
"https://media1.tenor.com/m/nO8QxT9B29kAAAAd/wtf-what-the-fuck.gif",
"https://media1.tenor.com/m/IvyuPtEfzhoAAAAd/matrix.gif",
"https://media1.tenor.com/m/WMe5rMx9OIcAAAAd/ostrich-m.gif",
"https://media1.tenor.com/m/zvke6dexeEEAAAAC/anonymous-mask.gif",
"https://media1.tenor.com/m/hemfK_5WFGcAAAAd/cookie-monster-waiting.gif",
"https://media1.tenor.com/m/TRhQGkZGzfEAAAAd/bh187-v-for-vendetta.gif",
"https://media1.tenor.com/m/FSp-pDzKXKsAAAAC/girls-kissing-tired.gif",
"https://media1.tenor.com/m/f6KifE_p2DAAAAAd/leyendo-hora-de-aventura.gif",
"https://media1.tenor.com/m/veoNy8bkTLMAAAAd/blink-kid.gif",
];
// Pick a random link from the list
const randomLink = mediaLinks[Math.floor(Math.random() * mediaLinks.length)];
// Process the selected link
let fallbackContent = randomLink;
fallbackContent = replaceMediaLinks(fallbackContent); // Process fallback content
replaceNpubStrings(expandedContent);
paragraph.innerHTML = fallbackContent; // Directly set processed content
readMoreLink.style.display = "none"; // Hide "Read more" if no additional content
}
const userMessage = document.getElementById("userMessage");
userMessage.setAttribute("data-hashtags", h.join(","));
userMessage.setAttribute("maxlength", l);
if (m) {
userMessage.value = m;
userMessage.disabled = true;
document.getElementById("sendMessageBtn").disabled = false;
}
document.getElementById("charCount").textContent = `0/${l}`;
if (r.length > 0) {
setRelays(r);
} else {
setRelays([
"wss://relay.nostr.band",
"wss://relay.damus.io",
"wss://njump.me",
"wss://relay.snort.social",
"wss://nos.lol",
]);
}
if (b && backgroundImages[b]) {
document.body.style.backgroundImage = `url('img/background/${backgroundImages[b]}')`;
document.body.style.backgroundRepeat = "repeat";
}
// if (sendMessageBtn.disabled) {
// sendMessageBtn.title = "Please use this tool with custom websites and not random posting";
// }
if (!urlParams.toString()) {
sendMessageBtn.title = "Send button disabled. Build s custom website with URLmkr tool for posting.";
avatarIcon.title = "Avatar disabled. ID change is only allowed on custom websites. Build one with URLmkr";
}
}
// // helper function scans the paragraph for note1 strings and invokes fetchNote1Event function
// function fetchNote1Strings(content, relays) {
// const note1Matches = content.match(/note1\w+/g) || [];
// note1Matches.forEach(note1String => {
// const { eventId } = decodeNote1(note1String) || {};
// if (eventId) fetchNote1Event(eventId, relays, note1String);
// });
// }
// Helper function scans the paragraph for nostr:note1 strings and invokes fetchNote1Event function
function fetchNote1Strings(content, relays) {
const note1Matches = content.match(/nostr:note1\w+/g) || [];
note1Matches.forEach(note1String => {
const { eventId } = decodeNote1(note1String) || {};
if (eventId) fetchNote1Event(eventId, relays, note1String); // Fetch event for nostr:note1
});
// Handle plain note1 strings by showing them as raw text
const plainNote1Matches = content.match(/\bnote1\w+\b(?!:)/g) || [];
plainNote1Matches.forEach(note1String => {
content = content.replace(
note1String,
`<span style="color: gray;">${note1String}</span>` // Render plain note1 as gray text
);
});
return content;
}
async function truncateParagraph(paragraph) {
const maxLength = 300; // Limit for truncation
const fullContent = paragraph.getAttribute('data-full-content');
// console.log("Full content for truncation:", fullContent);
if (!fullContent) return;
// Temporarily remove note1 placeholders for clean truncation
const tempContent = fullContent.replace(/<div class="note-box">[\s\S]*?<\/div>/g, '[note1]');
let truncatedText = tempContent.length > maxLength
? `${tempContent.substring(0, maxLength)}...`
: tempContent;
// Reinsert note1 placeholders into truncated content
let displayContent = truncatedText;
const noteBoxes = [...fullContent.matchAll(/<div class="note-box">[\s\S]*?<\/div>/g)];
noteBoxes.forEach(noteBox => {
displayContent = displayContent.replace('[note1]', noteBox[0]);
});
// Process media links after truncation
displayContent = replaceMediaLinks(displayContent);
// Ensure `replaceNpubStrings` is applied to truncated content
displayContent = await replaceNpubStrings(displayContent);
paragraph.innerHTML = displayContent;
paragraph.setAttribute('data-expanded', "false");
// console.log("Final truncated content:", paragraph.innerHTML);
// Fetch `note1` events in the truncated content
fetchNote1Strings(paragraph.innerHTML, getQueryParams().r);
// Reapply modal listeners
applyModalListenersToMedia(paragraph);
}
function replaceMediaLinks(content) {
// Match image and video URLs
const imageRegex = /(https?:\/\/\S+\.(?:png|jpe?g|gif|webp))(?![^<>]*>)/gi;
const videoRegex = /(https?:\/\/\S+\.(?:mp4|webm|ogg))(?![^<>]*>)/gi;
let imageIdCounter = 0; // Counter for unique image IDs
let videoIdCounter = 0; // Counter for unique video IDs
// Replace image URLs with <img> tags and assign unique IDs
content = content.replace(imageRegex, (match) => {
const id = `embedded-image-${imageIdCounter++}`;
return `<img id="${id}" src="${match}" alt="Embedded Image">`;
});
// Replace video URLs with <video> tags and assign unique IDs
content = content.replace(videoRegex, (match) => {
const id = `embedded-video-${videoIdCounter++}`;
return `
<video id="${id}" controls>
<source src="${match}" type="video/${match.split('.').pop()}">
Your browser does not support the video tag.
</video>
`;
});
return content;
}
// Modal for media content
document.addEventListener("DOMContentLoaded", () => {
// console.log("DOM fully loaded and parsed.");
// Select the existing modal elements
const modal = document.querySelector(".fullscreen-modal");
const modalContent = modal.querySelector(".modal-content");
const closeButton = modal.querySelector(".close-btn");
if (!modal || !modalContent || !closeButton) {
// console.error("Modal structure is missing in the HTML. Please ensure it exists.");
return;
}
// console.log("Modal structure found. Setting up event listeners.");
// Function to handle modal interactions
const setupModal = () => {
// Close modal on click of close button
closeButton.addEventListener("click", () => {
// console.log("Close button clicked. Hiding modal.");
modal.classList.remove("active");
modalContent.innerHTML = ""; // Clear modal content
});
// Close modal on outside click
modal.addEventListener("click", (e) => {
if (e.target === modal) {
// console.log("Modal background clicked. Hiding modal.");
modal.classList.remove("active");
modalContent.innerHTML = ""; // Clear modal content
}
});
};
// Set up modal close interactions
setupModal();
// Apply modal listeners globally on page load
const paragraph = document.querySelector("#customParagraph");
if (paragraph) {
applyModalListenersToMedia(paragraph);
}
// Reapply listeners after dynamic content updates
document.addEventListener("contentUpdated", () => {
// console.log("Dynamic content updated. Reapplying modal listeners.");
if (paragraph) {
applyModalListenersToMedia(paragraph);
}
});
});
// Refactored applyModalListenersToMedia function
function applyModalListenersToMedia(container) {
// console.log("Applying modal listeners for media items in the container.");
const mediaItems = container.querySelectorAll('img[id^="embedded-image-"], video[id^="embedded-video-"]');
if (mediaItems.length === 0) {
// console.warn("No media items found to attach event listeners.");
return;
}
mediaItems.forEach((media) => {
// Avoid duplicate event listeners
if (media.dataset.modalListener === "true") return;
media.addEventListener("click", () => {
// console.log("Media item clicked:", media);
const modal = document.querySelector(".fullscreen-modal");
const modalContent = modal.querySelector(".modal-content");
const clone = media.cloneNode(true);
clone.style.maxWidth = "100%";
clone.style.maxHeight = "100%";
modalContent.innerHTML = ""; // Clear previous content
modalContent.appendChild(clone);
modal.classList.add("active");
// console.log("Modal activated.");
});
// Mark media item as having a listener attached
media.dataset.modalListener = "true";
});
}
// NPUB handling
const npubDefaultRelays = [
"wss://relay.damus.io",
"wss://njump.me",
"wss://nos.lol"
];
/**
* Converts a `nostr:npub` string to a hexadecimal public key.
*/
function npubToHex(npub) {
// Remove the "nostr:" prefix if it exists
const bech32String = npub.replace("nostr:", "");
// Decode the Bech32 string
const decoded = bech32.decode(bech32String);
// Convert words to bytes (5-bit to 8-bit conversion)
const bytes = bech32.fromWords(decoded.words);
// Convert bytes to a hexadecimal string
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
// document.addEventListener("DOMContentLoaded", () => {
// const testNpub = "nostr:npub1r0rs5q2gk0e3dk3nlc7gnu378ec6cnlenqp8a3cjhyzu6f8k5sgs4sq9ac";
// console.log("Hexadecimal Key:", npubToHex(testNpub));
// });
/**
* Searches metadata for a given hex public key using default relays.
*/
async function searchMetadata(hex) {
for (const relay of defaultRelays) {
try {
const socket = new WebSocket(relay);
// Return a Promise to handle async WebSocket interactions
return new Promise((resolve, reject) => {
socket.onopen = () => {
// Send a subscription request for kind 0 events for the given public key
const subscriptionId = `sub_${Date.now()}`;
const subscriptionMessage = JSON.stringify([
"REQ", subscriptionId, { kinds: [0], authors: [hex] }
]);
socket.send(subscriptionMessage);
};
socket.onmessage = (event) => {
const message = JSON.parse(event.data);
// Check if the message contains a kind 0 event
if (message[0] === "EVENT" && message[2].kind === 0) {
const metadata = JSON.parse(message[2].content);
socket.close();
resolve(metadata); // Resolve with the parsed metadata
}
};
socket.onerror = (error) => {
console.warn(`WebSocket error on relay: ${relay}`, error);
socket.close();
reject(`Failed to fetch metadata from relay: ${relay}`);
};
socket.onclose = () => {
// Reject if the connection closes without metadata
reject(`Connection closed before receiving metadata from relay: ${relay}`);
};
});
} catch (error) {
console.warn(`Failed to fetch metadata from relay: ${relay}`, error);
}
}
// Return a default empty metadata if no relay succeeds
return { name: null };
}
/**
* Generates a profile link for a given hex public key.
*/
function generateProfileLink(hex) {
return `https://njump.me/p/${hex}`;
}
/**
* Processes a single `nostr:npub` string into its replacement HTML.
*/
async function processNpub(npub) {
try {
const hex = npubToHex(npub);
const metadata = await searchMetadata(hex);
console.log("Metadata:", metadata); // Log metadata
const userName = metadata.name
? `@${metadata.name}` // Add "@" prefix if name exists
: `${npub.substring(0, 6)}...${npub.slice(-4)}`;
const nip05 = metadata.nip05 || npub; // Use NIP-05 or fallback to npub
const profileLink = generateProfileLink(hex); // Generate profile link
return `<a href="${generateProfileLink(hex)}" title="${nip05}">${userName}</a>`;
} catch (error) {
console.error(`Error processing npub: ${npub}`, error);
return `<span title="${npub}">${npub.substring(0, 6)}...${npub.slice(-4)}</span>`;
}
}
/**
* Replaces all `nostr:npub` strings in the provided content with the processed HTML.
*/
async function replaceNpubStrings(content) {
const matches = content.match(/nostr:npub\w+/g) || [];
// Use a Set to track processed npub strings to avoid duplicate replacements
const uniqueMatches = new Set(matches);
for (const npub of uniqueMatches) {
// Skip already replaced links
const alreadyProcessedRegex = new RegExp(
`<a [^>]*href=[^>]*>${npub.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
"g"
);
if (alreadyProcessedRegex.test(content)) continue;
const replacement = await processNpub(npub);
// Safely replace the original `nostr:npub` string in the content
const regex = new RegExp(npub.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
content = content.replace(regex, replacement);
}
console.log("Original Content:", content);
console.log("Matches Found:", matches);
console.log("Processed Content:", content);
return content;
}
/**
* Updates the paragraph content dynamically, processing `nostr:npub` strings.
*/
async function updateParagraphContent() {
const paragraph = document.getElementById("customParagraph");
const fullContent = paragraph.getAttribute("data-full-content");
if (fullContent) {
const processedContent = await replaceNpubStrings(fullContent);
paragraph.innerHTML = processedContent;
}
}
// Run the function after the DOM is fully loaded
document.addEventListener("DOMContentLoaded", updateParagraphContent);
// END - NPUB handling
function setRelays(customRelays) {
relaySubscriptions = [];
sockets.forEach((socket) => socket.close());
sockets = [];
let allRelaysFailed = true;
customRelays.forEach((url) => {
let socket = new WebSocket(url);
socket.onmessage = async function (m) {
var [, i, e] = JSON.parse(m.data),
{ kind, c } = e || {};
if (!e || e === true) return;
console.log("msg:", e);
};
socket.onopen = async function (e) {
console.log("connected to " + url);
allRelaysFailed = false;
var i = b2h(utils.randomPrivateKey()).substring(0, 16),
f = { authors: [pub] },
sub = ["REQ", i, f];
console.log("Subscription:", sub);
socket.send(JSON.stringify(sub));
relaySubscriptions.push({ socket, url });
};
socket.onerror = function (e) {
console.log(`Failed to connect to ${url}`);
};
sockets.push(socket);
});
setTimeout(() => {
if (allRelaysFailed) {
document.getElementById("relayWarning").style.display = "block";
}
}, 5000);
}
var h2b = (h) =>
Uint8Array.from(h.match(/.{1,2}/g).map((b) => parseInt(b, 16))),
b2h = (b) => b.reduce((s, b) => s + b.toString(16).padStart(2, "0"), ""),
{ schnorr, utils } = nobleSecp256k1,
sha256 = utils.sha256,
pk,
pub,
storePrivateKey = false,
sockets = [],
relaySubscriptions = [];
async function generateNewKeys() {
const { ln } = getQueryParams(); // Get the ln parameter during key generation
// Clear existing avatar URL to ensure a new one is generated
localStorage.removeItem("avatar_url");
localStorage.removeItem("liked_events"); // Clear liked events to prevent adoption by the new ID
localStorage.removeItem("posted_hashes"); // Clear liked events to prevent adoption by the new ID
pk = b2h(utils.randomPrivateKey());
pub = nobleSecp256k1.getPublicKey(pk, true).substring(2);
const avatarUrl = getAvatarUrl(pub); // Generate avatar URL based on pubkey
const randomName = await generateRandomName(); // Generate random nostr_name
// Store ln (lightning address) if available
if (ln && ln !== '') {
const reversedLn = ln.split('').reverse().join('');
localStorage.setItem("ln_param", reversedLn); // Store reversed ln address
}
// Store keys and avatar URL in localStorage
localStorage.setItem("nostr_pk", pk);
localStorage.setItem("nostr_pub", pub);
localStorage.setItem("avatar_url", avatarUrl); // Store avatar URL
localStorage.setItem("nostr_name", randomName); // Store the generated name
localStorage.setItem("acc_created_at", Math.floor(Date.now() / 1000)); // Store current account birthday
// Store in HEX.json for record keeping
const fileName = `HEX${pub}.json`;
const eventData = {
pubkey: pub,
pk: pk,
avatar: avatarUrl,
name: randomName, // Store the name in the local storage for this key
created_at: Math.floor(Date.now() / 1000),
};
localStorage.setItem(fileName, JSON.stringify(eventData));
// Post Metadata to Relays (NIP-05 kind 0)
postMetadata(pub, avatarUrl, randomName);
// Update .well-known/nostr.json on the server
await updateNostrJson(randomName, pub);
updateAvatar();
updateNostrNameDisplay(); // Update the nostr_name display immediately
// console.log(`New keys generated. Avatar URL: ${avatarUrl}`);
// console.log("Generated name:", randomName);
// --- Modal for Key generation with Alert ---
const storeKeyResponse = confirm(
"A random Nostr ID was created.\n\n" +
"Do you want to store the private key in your device memory for future use in other clients?\n\n" +
"By clicking 'OK', the private key will be stored locally on your device. To access it later, visit the 'Show History' button at the bottom of the page."
);
if (storeKeyResponse) {
storePrivateKey = true;
localStorage.setItem("store_private_key", storePrivateKey);
localStorage.setItem("nostr_pk", pk);
alert("Private key stored successfully!");
} else {
storePrivateKey = false;
localStorage.setItem("store_private_key", storePrivateKey);
alert("Private key was not stored.");
}
}
// Fallback - Generate random string for errors
function generateRandomFallback() {
const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
return Array.from(
{ length: 10 },
() => chars[Math.floor(Math.random() * chars.length)]
).join("");
}
// Function to generate random name from adjectives and nouns
async function generateRandomName() {
try {
const adjectives = await loadJson("adjectives.json");
const nouns = await loadJson("nouns.json");
const randomNumber = String(
Math.floor(Math.random() * 21) + 1
).padStart(2, "0"); // 01 to 21
const randomAdjective =
adjectives[Math.floor(Math.random() * adjectives.length)];
const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];
return `${randomAdjective}_${randomNoun}_${randomNumber}`;
} catch (error) {
// console.error("Error generating random name:", error);
return generateRandomFallback(); // Return random string if JSON fails
}
}
// Kind 0
async function postMetadata() {
const { ln } = getQueryParams();
let name = localStorage.getItem("nostr_name"); // Get the name from localStorage
const avatarUrl = localStorage.getItem("avatar_url") || getAvatarUrl(pub); // Fetch existing avatar or regenerate
// If name is missing, generate and store it
if (!name) {
name = await generateRandomName();
localStorage.setItem("nostr_name", name);
}
// Decode the lightning address if ln exists and is not empty
let lud16Value = `${name.toLowerCase()}@postanote.org`; // Default to nostrName
if (ln && ln !== '') {
lud16Value = decodeURIComponent(ln.split('').reverse().join('')); // Reverse and decode
}
// Array of banner URLs
const bannerUrls = [
"https://i.ibb.co/Qc5BWcb/Notes-fallin-from-the-sky.webp",
"https://i.ibb.co/JnscKRr/bookclub.webp",
"https://i.ibb.co/hf3pMzd/papernotes.webp",
"https://i.ibb.co/93Gw99b/notes-In-Restaurant.webp",
"https://i.ibb.co/WxyZ6SW/notes-Adventure.webp"
];
// Pick a random banner URL
const randomBanner = bannerUrls[Math.floor(Math.random() * bannerUrls.length)];
// const nostrName = `[email protected]`; // Create nip05 address
const nostrName = `${name.toLowerCase()}@postanote.org`; // Create nip05 address <- Future unique names added to the .well-known folder
const currentTime = Math.floor(Date.now() / 1000);
// Metadata structure
const metadata = {
lud16: lud16Value, // lightning address as [email protected]) Can be custom if ln= in URL is included
lud06: "", // Old lightning addresses style
picture: avatarUrl,
name: name,
about: "Apparently, I'm one of the Nostriches posting random thoughts and notes the plebs set me up for. I didn't know I signed up for this, but here we are.",
website: "https://postanote.org",
banner: randomBanner, // Use random banner
display_name: name,
nip05: nostrName,
pubkey: pub,
npub: "",
created_at: currentTime,
// is_deleted: false
};
const metadataEvent = {
pubkey: pub,
content: JSON.stringify(metadata), // Stringified JSON as required by NIP-01
created_at: currentTime,
kind: 0, // Kind 0 for metadata
tags: [
[
"alt",
`Random Nostrich ${name} who's avatar was created with dicebear.com API for use in postanote.org`,
],
// ["i", `nostr:${name}`, b2h(await sha256(new TextEncoder().encode(name)))]
],
};
// Generate event ID and signature
metadataEvent.id = b2h(
await sha256(
new TextEncoder().encode(
JSON.stringify([
0,
metadataEvent.pubkey,
metadataEvent.created_at,
metadataEvent.kind,
metadataEvent.tags,
metadataEvent.content,
])
)
)
);
metadataEvent.sig = await schnorr.sign(metadataEvent.id, pk);
// Send to relays
relaySubscriptions.forEach(({ socket, url }) => {
socket.send(JSON.stringify(["EVENT", metadataEvent]));
console.log(`Metadata event sent to ${url}`);
});
// console.log("Metadata event:", metadataEvent);
// Update the HEX.json for the generated profile
const fileName = `HEX${pub}.json`;
const storedProfile = JSON.parse(localStorage.getItem(fileName)) || {};
storedProfile.nostr_name = name;
localStorage.setItem(fileName, JSON.stringify(storedProfile));
// Post to .well-known/nostr.json (via fetch or server-side script)
updateNostrJson(name, pub);
}