-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
1310 lines (1107 loc) · 43.2 KB
/
app.js
File metadata and controls
1310 lines (1107 loc) · 43.2 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
/** @typedef {import('pear-interface')} */ /* global Pear */
import Hyperswarm from "hyperswarm";
import crypto from "hypercore-crypto";
import b4a from "b4a";
const { teardown, updates } = Pear;
const swarm = new Hyperswarm();
teardown(() => swarm.destroy());
updates(() => Pear.reload());
// DECLARATION
const detailsPopUp = document.querySelector(".details--popUp");
const polls = {};
const shareLocationBtn = document.querySelector(".share--location--btn");
shareLocationBtn.addEventListener("click", getLocation);
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(sendLocation, showError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function sendLocation() {
const longitude = position.coords.longitude;
const latitude = position.coords.latitude;
console.log(longitude, latitude);
// Here you can send this message in the chat
sendMessage(locationMessage);
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
// CANVA CODE
// Canvas setup
const canvas = document.getElementById("whiteboard");
const context = canvas.getContext("2d");
const canvaPencil = document.querySelector("#canva--pencil--btn");
context.strokeStyle = "black";
context.lineWidth = 1;
let drawing = false;
let isDragging = false;
let draggedText = null; // Variable to hold the currently dragged text
let textObjects = []; // Array to hold text objects
function getMousePos(event) {
const rect = canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top,
};
}
let active = 0;
// Toggle pencil drawing mode
canvaPencil.addEventListener("click", (e) => {
e.preventDefault();
active++;
drawing = active % 2 === 1; // Toggle drawing mode based on active state
console.log(drawing ? "Pencil mode activated" : "Pencil mode deactivated");
canvaPencil.classList.toggle(".canva--highlight");
});
// Mouse down event for starting the drawing or dragging
let isDrawing = false; // Flag to track if the user is drawing
// Mouse down event for starting the drawing or dragging
canvas.addEventListener("mousedown", (e) => {
const pos = getMousePos(e);
if (isPointInText(pos.x, pos.y)) {
isDragging = true; // Set dragging state
draggedText = getTextAtPosition(pos.x, pos.y); // Get the dragged text object
} else if (drawing) {
isDrawing = true; // Set drawing state to true on mouse down
context.beginPath(); // Begin a new path each time the mouse is pressed
context.moveTo(pos.x, pos.y); // Set the start position for drawing
}
});
// Mouse move event for drawing or dragging
canvas.addEventListener("mousemove", (e) => {
const pos = getMousePos(e);
if (isDrawing && !isDragging) {
// Draw a line to the new mouse position if drawing state is active
context.lineTo(pos.x, pos.y);
context.stroke();
sendDrawingData("draw", pos.x, pos.y); // Send the drawing action to peers
} else if (isDragging && draggedText) {
// Update the dragged text position
draggedText.x = pos.x;
draggedText.y = pos.y;
clearCanvas(); // Clear the canvas to redraw everything
redrawAllTexts(); // Redraw all texts
}
});
// Mouse up event to stop drawing or dragging
canvas.addEventListener("mouseup", () => {
if (isDragging) {
isDragging = false; // Reset dragging state
} else if (isDrawing) {
isDrawing = false; // Stop drawing on mouse up
context.closePath(); // End the current drawing path
}
});
// Stop drawing or dragging if the mouse leaves the canvas
canvas.addEventListener("mouseleave", () => {
if (isDragging) {
isDragging = false;
} else if (isDrawing) {
isDrawing = false; // Stop drawing if the mouse leaves the canvas
context.closePath(); // Close the drawing path
}
});
// Handle clear canvas button
function clearCanvas() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
// Function to draw text and keep track of text objects
function drawText(text, x, y) {
context.fillStyle = "black";
context.font = "20px Arial";
context.fillText(text, x, y);
const textObject = { text, x, y };
textObjects.push(textObject); // Store the text object for future reference
// Send text drawing data to other peers
sendDrawingData("text", x, y, text); // Send the text action
}
// Button event for adding text
const drawTextBtn = document.getElementById("draw-text-btn");
drawTextBtn.addEventListener("click", () => {
const textInput = document.getElementById("text-input");
const text = textInput.value;
const x = 50; // X position to draw text
const y = 50; // Y position to draw text
drawText(text, x, y);
textInput.value = ""; // Clear the input field
});
// Function to check if mouse position is inside any text object
function isPointInText(mouseX, mouseY) {
return textObjects.some((textObject) => {
const textWidth = context.measureText(textObject.text).width;
const textHeight = 20; // Approximate text height
return (
mouseX >= textObject.x &&
mouseX <= textObject.x + textWidth &&
mouseY >= textObject.y - textHeight &&
mouseY <= textObject.y
);
});
}
// Function to get the text object at a specific position
function getTextAtPosition(mouseX, mouseY) {
return textObjects.find((textObject) => {
const textWidth = context.measureText(textObject.text).width;
const textHeight = 20; // Approximate text height
return (
mouseX >= textObject.x &&
mouseX <= textObject.x + textWidth &&
mouseY >= textObject.y - textHeight &&
mouseY <= textObject.y
);
});
}
// Function to redraw all texts on the canvas
function redrawAllTexts() {
context.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
textObjects.forEach((textObject) => {
drawText(textObject.text, textObject.x, textObject.y); // Redraw each text
});
}
// Updated sendDrawingData function
export function sendDrawingData(actionType, x, y, textContent) {
const drawingData = {
actionType, // Type of action: 'draw', 'text', 'clear'
x,
y,
textContent: textContent || "", // Optional text content
};
const messageBuffer = Buffer.from(JSON.stringify(drawingData));
const peers = [...swarm.connections];
for (const peer of peers) {
peer.write(messageBuffer);
}
}
// ********************************Image CODE*********************************//
// Function to convert an image to a Base64 string
function imageToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file); // Read file as Data URL (Base64 format)
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
}
// Handle image selection and send as a message
document
.querySelector("#image-upload")
.addEventListener("change", async (e) => {
const file = e.target.files[0]; // Get the selected image file
if (file) {
try {
const base64Image = await imageToBase64(file);
const messageData = {
name:
userName ||
b4a.toString(swarm.keyPair.publicKey, "hex").substr(0, 6),
message: base64Image,
isImage: true, // Flag to indicate the message is an image
};
// Convert the message data to a Buffer and send it to all peers
const messageBuffer = Buffer.from(JSON.stringify(messageData));
const peers = [...swarm.connections];
for (const peer of peers) peer.write(messageBuffer);
onMessageAdded("You", base64Image, true); // Display the image in sender's chat
} catch (error) {
console.error("Image conversion failed: ", error);
}
}
});
function convertVideoToBinary(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
// Event handler for successful file read
reader.onload = function (event) {
const arrayBuffer = event.target.result; // Contains binary data
resolve(arrayBuffer);
};
// Event handler for file read errors
reader.onerror = function (event) {
reject(new Error("Error reading file: " + event.target.error));
};
// Read the file as an ArrayBuffer
reader.readAsArrayBuffer(file);
});
}
document
.querySelector("#video-upload")
.addEventListener("change", async (e) => {
const videoFile = e.target.files[0];
if (videoFile) {
try {
const videoBinary = await convertVideoToBinary(videoFile);
const base64Video = b4a.toString(new Uint8Array(videoBinary), "base64");
console.log("Base64 Video Data:", base64Video); // Debugging line
const messageData = {
name:
userName ||
b4a.toString(swarm.keyPair.publicKey, "hex").substr(0, 6),
message: base64Video,
isVideo: true,
};
const messageBuffer = Buffer.from(JSON.stringify(messageData));
const peers = [...swarm.connections];
for (const peer of peers) peer.write(messageBuffer);
onMessageAdded("You", base64Video, false, false, false, true);
} catch (error) {
console.error("Video conversion failed: ", error);
}
}
});
document.querySelector("#file-upload").addEventListener("change", async (e) => {
const file = e.target.files[0]; // Get the selected file
if (file) {
try {
const base64Data = await fileToBase64(file);
const messageData = {
name:
userName || b4a.toString(swarm.keyPair.publicKey, "hex").substr(0, 6),
message: base64Data,
isFile: true,
fileType: file.type, // Store the file type for later processing
};
const messageBuffer = Buffer.from(JSON.stringify(messageData));
const peers = [...swarm.connections];
for (const peer of peers) peer.write(messageBuffer);
onMessageAdded(
"You",
base64Data,
false,
false,
false,
false,
false,
file.type
); // Display the file in sender's chat
} catch (error) {
console.error("File conversion failed: ", error);
}
}
});
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result); // Get the file data
reader.onerror = (error) => reject(error);
reader.readAsDataURL(file); // Read the file as Data URL (Base64 format)
});
}
document
.querySelector("#audio-upload")
.addEventListener("change", async (e) => {
const audioFile = e.target.files[0];
if (audioFile) {
try {
const audioData = await fileToBase64(audioFile); // Convert audio to Base64
const messageData = {
name:
userName ||
b4a.toString(swarm.keyPair.publicKey, "hex").substr(0, 6),
message: audioData,
isAudio: true,
};
const messageBuffer = Buffer.from(JSON.stringify(messageData));
const peers = [...swarm.connections];
for (const peer of peers) peer.write(messageBuffer);
onMessageAdded("You", audioData, false, false, false, false, true); // Display the audio in sender's chat
} catch (error) {
console.error("Audio conversion failed: ", error);
}
}
});
// **************************************************************************//
document.querySelector("#leaving--btn").addEventListener("click", (e) => {
e.preventDefault();
notifyUserLeft(); // Notify others that the user is leaving
setTimeout(() => location.reload(), 100); // Delay reload to allow message to send
});
// Function to notify other members that a user has left
function notifyUserLeft() {
document.querySelector(".leaving").classList.remove("hidden");
document.querySelector("#chat").classList.add("hidden");
console.log("Hidden removed");
const leaveMessage = {
system: true,
message: `${
userName || b4a.toString(swarm.keyPair.publicKey, "hex").substr(0, 6)
} has left the chat.`,
};
const leaveMessageBuffer = Buffer.from(JSON.stringify(leaveMessage));
const peers = [...swarm.connections];
for (const peer of peers) {
peer.write(leaveMessageBuffer);
}
userList = userList.filter((member) => member !== userName);
setTimeout(() => {
leavingDiv.classList.add("hidden");
}, 3000);
}
//******************************* POPUP Code**********************************//
let userName = "";
let isAdmin = false;
document.querySelector(".change--name").addEventListener("click", openPopUp);
const popup = document.querySelector(".popup");
const outerScreen = document.querySelector(".outerScreen");
function openPopUp() {
popup.classList.remove("hidden");
outerScreen.classList.remove("hidden");
}
outerScreen.addEventListener("click", closePopUp);
function closePopUp() {
popup.classList.add("hidden");
outerScreen.classList.add("hidden");
grp_PopUp.classList.add("hidden");
detailsPopUp.classList.add("hidden");
}
document.querySelector("#popup--form").addEventListener("submit", (e) => {
e.preventDefault();
const nameInput = document.querySelector("#popUp--input");
const newName = nameInput.value.trim();
if (newName !== "") {
console.log(`New name set: ${newName}`);
let prevName =
userName || b4a.toString(swarm.keyPair.publicKey, "hex").substr(0, 6);
userName = newName;
// Update userList by finding the index of prevName and changing their name to newName
const userIndex = userList.indexOf(prevName);
if (userIndex !== -1) {
userList[userIndex] = newName; // Update the name in the userList
} else {
userList.push(newName); // If prevName is not found, just add the new name
}
// Call this function to update the UI member list
// Hide the popup after the name is changed
popup.classList.add("hidden");
outerScreen.classList.add("hidden");
nameInput.value = "";
// Notify other peers about the name change
const changeName = {
system: true,
message: `${prevName} changed its name to ${newName}`,
};
const newNameMsgBuffer = Buffer.from(JSON.stringify(changeName));
const peers = [...swarm.connections];
for (const peer of peers) peer.write(newNameMsgBuffer);
updateMemberList();
} else {
console.log("Name input cannot be empty.");
}
});
const eraseBtn = document.getElementById("canva--erase--btn");
eraseBtn.addEventListener("click", () => {
clearCanvas();
});
//**************** END ******************//
function updateMemberList() {
const membersListElement = document.getElementById("members");
membersListElement.innerHTML = "";
userList.forEach((member) => {
console.log(member);
const listItem = document.createElement("li");
listItem.textContent = member;
membersListElement.appendChild(listItem);
});
}
// Member list show js
//
let userList = [];
swarm.on("connection", (peer) => {
const hexCode = b4a.toString(peer.remotePublicKey, "hex").substr(0, 6);
userList.push(hexCode);
updateMemberList();
peer.on("data", (message) => {
console.log("Message:", message);
const data = JSON.parse(message.toString()); // Parse the message data
console.log(b4a.toString(message, "hex"));
if (data.system) {
// Display system messages differently
onSystemMessageAdded(data.message);
if (data.message.includes("joined the chat")) {
const newMemberName = data.message.split(" ")[1];
if (!userList.includes(newMemberName)) {
userList.push(newMemberName);
updateMemberList();
}
}
if (data.message.includes("has left the chat")) {
const leftMemberName = data.message.split(" ")[0];
userList = userList.filter((members) => members !== leftMemberName);
updateMemberList();
}
} else if (data.actionType === "edit") {
const messageElements = document.querySelectorAll(
".message-item-left, .message-item-right"
);
messageElements.forEach((messageElement) => {
if (messageElement.textContent === data.originalMessage) {
messageElement.textContent = data.message;
}
});
} else if (data.isFile) {
const fileType = data.fileType;
onMessageAdded(
data.name,
data.message,
false,
false,
false,
false,
false,
fileType
);
} else if (data.action === "clear") {
clearCanvas(); // Call clearCanvas to clear the canvas
} else if (data.actionType === "draw") {
// Draw on the canvas based on the received coordinates
context.lineTo(data.x, data.y);
context.stroke();
context.moveTo(data.x, data.y);
} else {
const senderName = data.name || hexCode;
const receivedMessage = data.message;
const isImage = data.isImage;
const isAdmin = data.isAdmin;
const isSticker = data.isSticker;
const isVideo = data.isVideo;
const isAudio = data.isAudio;
onMessageAdded(
senderName,
receivedMessage,
isImage,
isAdmin,
isSticker,
isVideo,
isAudio
); // Display the message with the correct sender name
} // Display the message with the correct sender name
});
peer.on("error", (e) => console.log(`Connection Error: ${e}`));
});
swarm.on("update", () => {
document.querySelector("#peers-count").textContent =
swarm.connections.size + 1;
updateMemberList();
});
const createChatRoomBtn = document.querySelector("#create--chat--room--btn");
const grp_PopUp = document.querySelector("#grpName--popup");
createChatRoomBtn.addEventListener("click", grpPopUp);
document.querySelector("#join--form").addEventListener("submit", joinChatRoom);
document.querySelector("#message-form").addEventListener("submit", sendMessage);
document.querySelector("#message").addEventListener("keydown", (e) => {
if (e.key === "Enter") {
if (e.shiftKey) {
return;
}
e.preventDefault();
sendMessage(e);
}
});
function grpPopUp() {
grp_PopUp.classList.remove("hidden");
outerScreen.classList.remove("hidden");
document
.querySelector("#grp--popup--form")
.addEventListener("submit", (e) => {
e.preventDefault();
outerScreen.classList.add("hidden");
const groupNameInput = document.querySelector("#grp--popUp--input");
const groupName = groupNameInput.value.trim();
if (groupName) {
createChatRoom(groupName); // Call createChatRoom with the group name
grp_PopUp.classList.add("hidden"); // Close the popup
groupNameInput.value = ""; // Clear the input field
} else {
console.log("Group name cannot be empty.");
}
});
}
async function createChatRoom(groupName) {
console.log("Clicked the create btn");
const seedBuffer = crypto.randomBytes(32);
joinSwarm(seedBuffer);
isAdmin = true;
const grpName = document.querySelectorAll(".grpName--text");
grpName.forEach((grp) => {
grp.textContent = groupName;
});
}
async function joinChatRoom(e) {
console.log("Clicked the join btn");
e.preventDefault();
const seedStr = document.querySelector("#join--room--btn--seed").value;
const seedBuffer = b4a.from(seedStr, "hex");
joinSwarm(seedBuffer);
}
async function joinSwarm(seedBuffer) {
document.querySelector("#setup").classList.add("hidden");
document.querySelector(".loading").classList.remove("hidden");
const discovery = swarm.join(seedBuffer, { client: true, server: true });
await discovery.flushed();
const seed = b4a.toString(seedBuffer, "hex");
document.querySelector("#chat-room-seed").innerHTML = seed;
document.querySelector(".loading").classList.add("hidden");
document.querySelector("#chat").classList.remove("hidden");
const joinName =
userName || b4a.toString(swarm.keyPair.publicKey, "hex").substr(0, 6);
userList.push(joinName);
updateMemberList();
const joinMessage = {
system: true,
message: `🥳 ${joinName} joined the chat 🥂🥂`,
};
const joinMessageBuffer = Buffer.from(JSON.stringify(joinMessage));
const peers = [...swarm.connections];
for (const peer of peers) peer.write(joinMessageBuffer);
}
// weather function
async function getWeather(city) {
const apiKey = "4e3e22861d59c5931b50082d9eecadb3"; // Replace with your OpenWeatherMap API key
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
try {
const response = await fetch(apiUrl); // Use await here
if (!response.ok) throw new Error("City not found");
const weatherData = await response.json(); // Await the JSON parsing
return weatherData;
} catch (error) {
console.error("Error fetching weather data:", error);
return null;
}
}
function sendMessage(e) {
e.preventDefault();
const message = document.querySelector("#message").value;
document.querySelector("#message").value = "";
if (message.trim() === "") return;
const name =
userName || b4a.toString(swarm.keyPair.publicKey, "hex").substr(0, 6); // Use the sender's name or 'You'
// Prepare the message data as an object for regular messages
const messageData = {
name: name,
message: message,
isImage: false,
isAdmin: isAdmin,
};
// Convert the message data to a Buffer and send it to all peers
const messageBuffer = Buffer.from(JSON.stringify(messageData));
const peers = [...swarm.connections];
for (const peer of peers) peer.write(messageBuffer);
onMessageAdded("You", message, false, isAdmin); // Display the message in the sender's system
}
const fixedColors = ["#FF5733", "#33FF57", "#D2FF72", "#FF33A6", "#F9E400"];
// Function to get a color from the fixed array based on a user's identifier
function getColorFromUserKey(userKey) {
const index = Math.abs(userKey.hashCode()) % fixedColors.length;
return fixedColors[index];
}
// Utility function to create a consistent hash code from a string
String.prototype.hashCode = function () {
let hash = 0;
for (let i = 0; i < this.length; i++) {
hash = this.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
};
function onMessageAdded(
senderName,
message,
isImage,
isAdmin = false,
isSticker = false,
isVideo = false,
isAudio = false,
fileType = ""
) {
const messagesContainer = document.querySelector("#messages");
// Create the message wrapper
const messageDiv = document.createElement("div");
messageDiv.classList.add("message--div");
// TimeElement
const currentTime = new Date();
const timeString = currentTime.toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
});
// Create a time element
const timeElement = document.createElement("span");
timeElement.classList.add(
senderName === "You" ? "message-time-right" : "message-time-left"
); // Add a class for styling
timeElement.textContent = timeString;
const menuBtn = document.createElement("button");
const menuBtnImg = document.createElement("img");
menuBtnImg.src = `./assets/menu.png`;
menuBtnImg.classList.add("message--menu--img");
menuBtn.appendChild(menuBtnImg);
menuBtn.classList.add(
senderName === "You" ? "message--menu--right" : "message--menu--left"
);
messageDiv.appendChild(menuBtn);
menuBtn.addEventListener("click", (e) => {
e.preventDefault();
messagePopUp(e, messageDiv, senderName);
});
// Append the time element to the messageDiv
if (fileType) {
const messageElement = document.createElement("div");
messageElement.classList.add(
senderName === "You" ? "message-item-right" : "message-item-left"
);
const fileLink = document.createElement("a");
fileLink.style.color = "#eee";
fileLink.href = message; // The Base64 data URL
fileLink.download = "shared-file"; // Default file name
fileLink.textContent = `Download ${fileType}`;
messageElement.appendChild(fileLink);
messageDiv.appendChild(messageElement);
} else {
if (isAudio) {
const audioElement = document.createElement("audio");
audioElement.src = message;
audioElement.controls = true;
audioElement.classList.add(
senderName === "You" ? "audio-right" : "audio-left"
);
messageDiv.appendChild(audioElement);
} else if (isSticker) {
const stickerElement = document.createElement("img");
stickerElement.src = message;
stickerElement.alt = "Sticker";
stickerElement.classList.add(
senderName === "You" ? "sticker-img-right" : "sticker-img-left"
);
messageDiv.appendChild(stickerElement);
} else if (isVideo) {
const videoContainer = document.createElement("div");
videoContainer.classList.add(
senderName === "You" ? "video-item-right" : "video-item-left"
);
const videoElement = document.createElement("video");
videoElement.src = "data:video/mp4;base64," + message; // Use Base64 string
videoElement.controls = true;
videoElement.style.maxWidth = "100%"; // Ensure it fits within the container
videoContainer.appendChild(videoElement);
messageDiv.appendChild(videoContainer);
} else if (isImage) {
// Create a separate container for images
const imageContainer = document.createElement("div");
imageContainer.classList.add(
senderName === "You" ? "image-item-right" : "image-item-left"
);
const imgElement = document.createElement("img");
imgElement.src = message;
imgElement.style.maxWidth = "100%";
const downloadImg = document.createElement("a");
downloadImg.href = message;
downloadImg.download = "shared-image";
downloadImg.classList.add(
senderName === "You"
? "img--download--btn--right"
: "img--download--btn--left"
);
downloadImg.textContent = "Download";
imageContainer.appendChild(imgElement);
imageContainer.appendChild(downloadImg);
messageDiv.appendChild(imageContainer);
} else {
// Create the message content element for text
const messageElement = document.createElement("div");
messageElement.classList.add(
senderName === "You" ? "message-item-right" : "message-item-left"
);
if (message.startsWith("clip://")) {
// Extract the clipboard text by removing the clip:// part
const clipboardText = message.replace("clip://", "");
// Create a span to hold the clipboard text
const clipboardDiv = document.createElement("div");
clipboardDiv.textContent = clipboardText;
// Create a button to allow copying the text to the clipboard
const clipButton = document.createElement("button");
clipboardDiv.classList.add(
senderName === "You" ? "clipBoardDiv--right" : "clipBoardDiv--left"
);
clipButton.classList.add("clipBtn");
clipButton.textContent = "Copy";
clipButton.addEventListener("click", (e) => {
navigator.clipboard.writeText(clipboardText).then(() => {
clipButton.textContent = "Copied";
console.log("Text copied to clipboard:" + clipboardText);
setTimeout(() => {
clipButton.textContent = "Copy";
}, 2000);
});
});
// Append the clipboard text and the button to the message element
messageDiv.appendChild(clipboardDiv);
clipboardDiv.appendChild(clipButton);
} else if (message.startsWith("image://")) {
const imgUrl = message.replace("image://", "");
const imageContainer = document.createElement("div");
imageContainer.classList.add(
senderName === "You" ? "image-item-right" : "image-item-left"
);
const imgElement = document.createElement("img");
imgElement.src = imgUrl;
imgElement.style.width = "100%";
const downloadImg = document.createElement("a");
downloadImg.href = message;
downloadImg.download = "shared-image";
downloadImg.classList.add(
senderName === "You"
? "img--download--btn--right"
: "img--download--btn--left"
);
downloadImg.textContent = "Download";
imageContainer.appendChild(imgElement);
imageContainer.appendChild(downloadImg);
messageDiv.appendChild(imageContainer);
} else if (message.startsWith("video://")) {
const videoUrl = message.replace("video://", "").trim();
// Create container
const videoContainer = document.createElement("div");
videoContainer.classList.add(
senderName === "You" ? "video-item-right" : "video-item-left"
);
let videoElement;
// Check if the link is a YouTube URL
if (videoUrl.includes("youtube.com") || videoUrl.includes("youtu.be")) {
// Convert YouTube URL to embeddable format
let videoId;
if (videoUrl.includes("youtu.be")) {
videoId = videoUrl.split("/").pop(); // Extract ID from youtu.be link
} else {
videoId = new URL(videoUrl).searchParams.get("v"); // Extract ID from youtube.com link
}
const embedUrl = `https://www.youtube.com/embed/${videoId}`;
// Create iframe element
videoElement = document.createElement("iframe");
videoElement.src = embedUrl;
videoElement.setAttribute("frameborder", "0");
videoElement.setAttribute("allowfullscreen", "true");
} else {
// Handle non-YouTube links as direct video
videoElement = document.createElement("video");
videoElement.controls = true;
videoElement.width = 320;
// Create source element for the video
const sourceElement = document.createElement("source");
sourceElement.src = videoUrl;
sourceElement.type = "video/mp4";
videoElement.appendChild(sourceElement);
// Add fallback message for unsupported browsers
videoElement.innerHTML +=
"Your browser does not support the video tag.";
}
// Append video or iframe to the container
videoContainer.appendChild(videoElement);
messageDiv.appendChild(videoContainer);
} else if (message.startsWith("weather://")) {
const city = message.replace("weather://", "").trim();
console.log(`Fetching weather for city: ${city}`); // Log the city being searched
// Create a container for weather data
const weatherContainer = document.createElement("div");
weatherContainer.classList.add(
senderName === "You" ? "weather-item-right" : "weather-item-left"
);
getWeather(city)
.then((weatherData) => {
if (weatherData) {
// Format the weather data to display
const weatherInfo = `
<div class="weather--card">
<span class="blob"></span>
<p style="font-size: 12px; color: #ddd;">${weatherData.name}:</p>
<span style="display: flex; align-items: top; margin-top: 4px; margin-bottom: 10px;">
<h1 style="font-weight: 900;">${weatherData.main.temp}</h1><p style="font-size: 12px;">°C</p>
</span>
<span>
<p style="color: #777;">Weather: ${weatherData.weather[0].description}</p>
<p style="color: #777;">Humidity: ${weatherData.main.humidity}%</p>
<p style="color: #777;">Humidity: ${weatherData.wind.speed} m/s</p>
</span>
</div>
`;
// Create and append weather data to the message div
weatherContainer.innerHTML = weatherInfo;
} else {
weatherContainer.innerHTML =
"Error: Could not fetch weather data.";
weatherContainer.classList.add("error-message");
}
messageDiv.appendChild(weatherContainer);
})
.catch((err) => {
console.error("Error fetching weather data:", err);
weatherContainer.innerHTML = "Error: Could not fetch weather data.";
messageDiv.appendChild(weatherContainer);