LinkUp-P2P-Chat/app.js

284 lines
8.2 KiB
JavaScript
Raw Normal View History

2024-06-03 19:23:14 -04:00
import Hyperswarm from 'hyperswarm';
import crypto from 'hypercore-crypto';
import b4a from 'b4a';
import ServeDrive from 'serve-drive';
import Localdrive from 'localdrive';
2024-06-03 20:04:15 -04:00
import fs from 'fs';
2024-06-03 22:33:39 -04:00
import Hyperdrive from 'hyperdrive';
import Corestore from 'corestore';
const store = new Corestore('./storage');
const drive = new Hyperdrive(store);
await drive.ready();
2024-06-03 19:23:14 -04:00
let swarm;
2024-06-03 19:43:33 -04:00
let userName = 'Anonymous';
let userAvatar = '';
2024-06-03 20:04:15 -04:00
let registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {};
2024-06-03 19:23:14 -04:00
let peerCount = 0;
async function initialize() {
swarm = new Hyperswarm();
const servePort = 1337;
2024-06-03 20:04:15 -04:00
const serve = new ServeDrive({ port: servePort, get: ({ key, filename, version }) => drive });
2024-06-03 19:23:14 -04:00
await serve.ready();
console.log('Listening on http://localhost:' + serve.address().port);
const registerForm = document.querySelector('#register-form');
const selectAvatarButton = document.querySelector('#select-avatar');
const createChatRoomButton = document.querySelector('#create-chat-room');
const joinForm = document.querySelector('#join-form');
const messageForm = document.querySelector('#message-form');
if (registerForm) {
registerForm.addEventListener('submit', registerUser);
}
if (selectAvatarButton) {
selectAvatarButton.addEventListener('click', () => {
document.querySelector('#avatar-file').click();
});
}
if (createChatRoomButton) {
createChatRoomButton.addEventListener('click', createChatRoom);
}
if (joinForm) {
joinForm.addEventListener('submit', joinChatRoom);
}
if (messageForm) {
messageForm.addEventListener('submit', sendMessage);
}
2024-06-04 00:03:14 -04:00
const savedUser = localStorage.getItem('currentUser');
if (savedUser) {
const user = JSON.parse(savedUser);
userName = user.username;
userAvatar = user.avatar || '';
2024-06-03 20:04:15 -04:00
const setupDiv = document.querySelector('#setup');
2024-06-04 00:03:14 -04:00
if (setupDiv) {
2024-06-03 23:22:13 -04:00
setupDiv.classList.remove('hidden');
2024-06-04 00:03:14 -04:00
}
} else {
const registerDiv = document.querySelector('#register');
if (registerDiv) {
2024-06-03 20:04:15 -04:00
registerDiv.classList.remove('hidden');
}
}
2024-06-03 22:33:39 -04:00
swarm.on('connection', async (connection, info) => {
2024-06-03 19:43:33 -04:00
peerCount++;
updatePeerCount();
2024-06-03 22:33:39 -04:00
// Send the current user's icon to the new peer
const iconBuffer = await drive.get(`/icons/${userName}.png`);
if (iconBuffer) {
const iconMessage = JSON.stringify({
type: 'icon',
username: userName,
avatar: iconBuffer.toString('base64'),
});
connection.write(iconMessage);
}
2024-06-03 19:53:10 -04:00
connection.on('data', async (data) => {
2024-06-03 19:43:33 -04:00
const messageObj = JSON.parse(data.toString());
2024-06-03 20:04:15 -04:00
if (messageObj.type === 'icon') {
// Save icon to local directory
const username = messageObj.username;
const avatarBuffer = Buffer.from(messageObj.avatar, 'base64');
await drive.put(`/icons/${username}.png`, avatarBuffer);
2024-06-03 22:33:39 -04:00
updateIcon(username, avatarBuffer);
2024-06-03 19:53:10 -04:00
} else {
onMessageAdded(messageObj.name, messageObj.message, messageObj.avatar);
}
2024-06-03 19:43:33 -04:00
});
2024-06-03 22:33:39 -04:00
2024-06-03 19:43:33 -04:00
connection.on('close', () => {
peerCount--;
updatePeerCount();
});
});
2024-06-03 19:42:30 -04:00
2024-06-03 19:43:33 -04:00
swarm.on('error', (err) => {
console.error('Swarm error:', err);
});
2024-06-03 19:42:30 -04:00
2024-06-03 19:43:33 -04:00
swarm.on('close', () => {
console.log('Swarm closed.');
});
2024-06-03 19:42:30 -04:00
}
2024-06-03 19:23:14 -04:00
function updatePeerCount() {
const peersCountElement = document.querySelector('#peers-count');
if (peersCountElement) {
peersCountElement.textContent = peerCount;
}
}
async function registerUser(e) {
e.preventDefault();
const regUsernameInput = document.querySelector('#reg-username');
if (!regUsernameInput) {
alert('Username input element not found.');
return;
}
const regUsername = regUsernameInput.value.trim();
if (!regUsername) {
alert('Please enter a username.');
return;
}
const loadingDiv = document.querySelector('#loading');
loadingDiv.classList.remove('hidden');
const newUser = { username: regUsername, avatar: '' };
localStorage.setItem('currentUser', JSON.stringify(newUser));
const fileInput = document.querySelector('#avatar-file');
if (fileInput && fileInput.files.length > 0) {
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = async () => {
const fileBuffer = Buffer.from(reader.result);
2024-06-03 20:04:15 -04:00
await drive.put(`/icons/${regUsername}.png`, fileBuffer);
userAvatar = `http://localhost:1337/icons/${regUsername}.png`;
// Save avatar URL to localStorage
2024-06-03 19:23:14 -04:00
localStorage.setItem('avatarURL', userAvatar);
2024-06-03 22:33:39 -04:00
// Broadcast the icon to all connected peers
const iconMessage = JSON.stringify({
type: 'icon',
username: regUsername,
avatar: fileBuffer.toString('base64'),
});
const peers = [...swarm.connections];
for (const peer of peers) {
peer.write(iconMessage);
}
2024-06-03 19:23:14 -04:00
};
reader.readAsArrayBuffer(file);
}
continueRegistration(regUsername);
}
async function continueRegistration(regUsername) {
const loadingDiv = document.querySelector('#loading');
const setupDiv = document.querySelector('#setup');
if (!regUsername) {
alert('Please enter a username.');
return;
}
userName = regUsername;
setupDiv.classList.remove('hidden');
document.querySelector('#register').classList.add('hidden');
loadingDiv.classList.add('hidden');
document.querySelector('#join-chat-room').addEventListener('click', joinChatRoom);
const randomTopic = crypto.randomBytes(32);
document.querySelector('#chat-room-topic').innerText = b4a.toString(randomTopic, 'hex');
}
async function createChatRoom() {
2024-06-03 20:04:15 -04:00
// Generate a new random topic (32 byte string)
2024-06-03 19:23:14 -04:00
const topicBuffer = crypto.randomBytes(32);
joinSwarm(topicBuffer);
}
async function joinChatRoom(e) {
e.preventDefault();
const topicStr = document.querySelector('#join-chat-room-topic').value;
const topicBuffer = b4a.from(topicStr, 'hex');
joinSwarm(topicBuffer);
}
async function joinSwarm(topicBuffer) {
document.querySelector('#setup').classList.add('hidden');
document.querySelector('#loading').classList.remove('hidden');
2024-06-03 20:04:15 -04:00
// Join the swarm with the topic. Setting both client/server to true means that this app can act as both.
2024-06-03 19:23:14 -04:00
const discovery = swarm.join(topicBuffer, { client: true, server: true });
await discovery.flushed();
const topic = b4a.toString(topicBuffer, 'hex');
document.querySelector('#chat-room-topic').innerText = topic;
document.querySelector('#loading').classList.add('hidden');
document.querySelector('#chat').classList.remove('hidden');
}
function sendMessage(e) {
e.preventDefault();
const message = document.querySelector('#message').value;
document.querySelector('#message').value = '';
onMessageAdded(userName, message, userAvatar);
2024-06-03 20:04:15 -04:00
// Send the message to all peers (that you are connected to)
2024-06-03 19:23:14 -04:00
const messageObj = JSON.stringify({
type: 'message',
name: userName,
message,
avatar: userAvatar,
timestamp: Date.now(),
});
const peers = [...swarm.connections];
for (const peer of peers) {
peer.write(messageObj);
}
}
2024-06-04 00:26:32 -04:00
function scrollToBottom() {
var container = document.getElementById("messages-container");
container.scrollTop = container.scrollHeight;
}
2024-06-03 19:23:14 -04:00
function onMessageAdded(from, message, avatar) {
2024-06-04 00:26:32 -04:00
2024-06-03 19:23:14 -04:00
const $div = document.createElement('div');
$div.classList.add('message');
const $img = document.createElement('img');
$img.src = avatar || 'https://via.placeholder.com/40';
$div.appendChild($img);
const $content = document.createElement('div');
$content.classList.add('message-content');
const $header = document.createElement('div');
$header.classList.add('message-header');
$header.textContent = from;
const $text = document.createElement('div');
2024-06-04 00:03:14 -04:00
$text.classList.add('message-text');
2024-06-04 00:26:32 -04:00
// Render Markdown content
const md = window.markdownit();
$text.innerHTML = md.render(message);
2024-06-03 19:23:14 -04:00
$content.appendChild($header);
$content.appendChild($text);
$div.appendChild($content);
document.querySelector('#messages').appendChild($div);
2024-06-04 00:26:32 -04:00
scrollToBottom();
2024-06-03 19:23:14 -04:00
2024-06-04 00:26:32 -04:00
}
2024-06-03 22:33:39 -04:00
async function updateIcon(username, avatarBuffer) {
// Update the icon in the local HTML if necessary
// This can be adjusted as per your needs
const userIcon = document.querySelector(`img[src*="${username}.png"]`);
if (userIcon) {
userIcon.src = URL.createObjectURL(new Blob([avatarBuffer]));
}
}
initialize();