LinkUp-P2P-Chat/app.js

459 lines
14 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';
2024-06-03 22:33:39 -04:00
import Hyperdrive from 'hyperdrive';
import Corestore from 'corestore';
2024-06-08 16:13:20 -04:00
import { EventEmitter } from 'events';
2024-06-09 07:00:42 -04:00
import fs from "fs";
2024-06-09 03:38:53 -04:00
const storagePath = `./storage/`;
const store = new Corestore(storagePath);
2024-06-03 22:33:39 -04:00
const drive = new Hyperdrive(store);
await drive.ready();
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
let swarm;
let registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {};
let peerCount = 0;
let currentRoom = null;
2024-06-08 16:13:20 -04:00
const eventEmitter = new EventEmitter();
2024-06-08 15:16:28 -04:00
// Define servePort at the top level
let servePort;
// Object to store all the information we want to save
let config = {
userName: '',
userAvatar: '',
rooms: []
};
2024-06-09 07:00:42 -04:00
// Function to get a random port between 1337 and 2223
function getRandomPort() {
2024-06-08 17:08:30 -04:00
return Math.floor(Math.random() * (65535 - 49152 + 1)) + 49152;
}
2024-06-08 15:16:28 -04:00
async function initialize() {
swarm = new Hyperswarm();
servePort = getRandomPort();
2024-06-08 15:16:28 -04:00
const serve = new ServeDrive({ port: servePort, get: ({ key, filename, version }) => drive });
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 joinChatRoomButton = document.querySelector('#join-chat-room');
const messageForm = document.querySelector('#message-form');
const toggleSetupBtn = document.querySelector('#toggle-setup-btn');
const removeRoomBtn = document.querySelector('#remove-room-btn');
const attachFileButton = document.getElementById('attach-file');
const fileInput = document.getElementById('file-input');
2024-06-08 15:16:28 -04:00
if (registerForm) {
registerForm.addEventListener('submit', registerUser);
}
if (selectAvatarButton) {
selectAvatarButton.addEventListener('click', () => {
document.querySelector('#avatar-file').click();
});
}
if (createChatRoomButton) {
createChatRoomButton.addEventListener('click', createChatRoom);
}
if (joinChatRoomButton) {
joinChatRoomButton.addEventListener('click', joinChatRoom);
}
if (messageForm) {
messageForm.addEventListener('submit', sendMessage);
}
if (toggleSetupBtn) {
toggleSetupBtn.addEventListener('click', toggleSetupView);
}
if (removeRoomBtn) {
removeRoomBtn.addEventListener('click', leaveRoom);
2024-06-03 19:23:14 -04:00
}
if (attachFileButton) {
attachFileButton.addEventListener('click', () => fileInput.click());
}
if (fileInput) {
fileInput.addEventListener('change', async (event) => {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = async (event) => {
const buffer = new Uint8Array(event.target.result);
const filePath = `/files/${file.name}`;
await drive.put(filePath, buffer);
const fileUrl = `http://localhost:${servePort}${filePath}`;
2024-06-09 07:00:42 -04:00
sendFileMessage(config.userName, fileUrl, file.type, config.userAvatar);
};
reader.readAsArrayBuffer(file);
}
});
}
2024-06-03 22:33:39 -04:00
2024-06-09 02:50:05 -04:00
const configExists = fs.existsSync("./config.json");
if (configExists) {
2024-06-09 03:03:23 -04:00
config = JSON.parse(fs.readFileSync("./config.json", 'utf8'));
console.log("Read config from file:", config)
2024-06-09 03:38:53 -04:00
// Update port in URLs
config.userAvatar = updatePortInUrl(config.userAvatar);
2024-06-09 02:50:05 -04:00
config.rooms.forEach(room => {
2024-06-09 03:08:29 -04:00
addRoomToListWithoutWritingToConfig(room);
2024-06-09 02:50:05 -04:00
});
2024-06-09 03:38:53 -04:00
for (let user in registeredUsers) {
registeredUsers[user] = updatePortInUrl(registeredUsers[user]);
}
2024-06-09 02:50:05 -04:00
}
2024-06-08 15:16:28 -04:00
const registerDiv = document.querySelector('#register');
2024-06-09 02:50:05 -04:00
if (registerDiv && !configExists) {
2024-06-08 15:16:28 -04:00
registerDiv.classList.remove('hidden');
}
2024-06-03 22:33:39 -04:00
2024-06-08 16:15:55 -04:00
eventEmitter.on('onMessage', async (messageObj) => {
2024-06-08 16:13:20 -04:00
if (messageObj.type === 'icon') {
const username = messageObj.username;
const avatarBuffer = Buffer.from(messageObj.avatar, 'base64');
2024-06-08 16:15:55 -04:00
await drive.put(`/icons/${username}.png`, avatarBuffer);
2024-06-08 16:13:20 -04:00
updateIcon(username, avatarBuffer);
} else if (messageObj.type === 'file') {
2024-06-09 07:00:42 -04:00
addFileMessage(messageObj.name, messageObj.fileName, messageObj.fileUrl, messageObj.fileType, messageObj.avatar);
2024-06-08 16:13:20 -04:00
} else {
onMessageAdded(messageObj.name, messageObj.message, messageObj.avatar);
}
});
2024-06-08 15:16:28 -04:00
swarm.on('connection', async (connection, info) => {
peerCount++;
updatePeerCount();
2024-06-08 15:52:44 -04:00
console.log('Peer connected, current peer count:', peerCount);
2024-06-08 15:16:28 -04:00
2024-06-08 15:40:58 -04:00
// Send the current user's icon to the new peer
2024-06-09 06:39:15 -04:00
const iconBuffer = await drive.get(`/icons/${config.userName}.png`);
if (iconBuffer) {
const iconMessage = JSON.stringify({
type: 'icon',
username: config.userName,
avatar: iconBuffer.toString('base64'),
});
connection.write(iconMessage);
2024-06-08 15:06:24 -04:00
}
2024-06-08 16:13:20 -04:00
connection.on('data', (data) => {
2024-06-08 15:16:28 -04:00
const messageObj = JSON.parse(data.toString());
2024-06-08 16:13:20 -04:00
eventEmitter.emit('onMessage', messageObj);
2024-06-03 19:43:33 -04:00
});
2024-06-03 19:42:30 -04:00
2024-06-08 15:16:28 -04:00
connection.on('close', () => {
peerCount--;
updatePeerCount();
2024-06-08 15:52:44 -04:00
console.log('Peer disconnected, current peer count:', peerCount);
2024-06-08 15:06:24 -04:00
});
2024-06-08 15:16:28 -04:00
});
2024-06-03 19:42:30 -04:00
2024-06-08 15:16:28 -04:00
swarm.on('error', (err) => {
console.error('Swarm error:', err);
});
2024-06-03 19:42:30 -04:00
2024-06-08 15:16:28 -04:00
swarm.on('close', () => {
console.log('Swarm closed');
});
}
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
function registerUser(e) {
e.preventDefault();
const regUsername = document.querySelector('#reg-username').value;
2024-06-08 15:06:24 -04:00
2024-06-08 15:16:28 -04:00
if (registeredUsers[regUsername]) {
alert('Username already taken. Please choose another.');
return;
2024-06-03 19:23:14 -04:00
}
2024-06-08 15:16:28 -04:00
const avatarFile = document.querySelector('#avatar-file').files[0];
if (avatarFile) {
const reader = new FileReader();
2024-06-08 16:15:55 -04:00
reader.onload = async (event) => {
2024-06-08 15:16:28 -04:00
const buffer = new Uint8Array(event.target.result);
2024-06-08 16:15:55 -04:00
await drive.put(`/icons/${regUsername}.png`, buffer);
config.userAvatar = `http://localhost:${servePort}/icons/${regUsername}.png`; // Set the correct URL
2024-06-09 03:38:53 -04:00
registeredUsers[regUsername] = `http://localhost:${servePort}/icons/${regUsername}.png`; // Use placeholder URL
2024-06-08 15:16:28 -04:00
localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers));
continueRegistration(regUsername);
};
reader.readAsArrayBuffer(avatarFile);
} else {
continueRegistration(regUsername);
2024-06-03 19:23:14 -04:00
}
2024-06-08 15:16:28 -04:00
}
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
async function continueRegistration(regUsername) {
const loadingDiv = document.querySelector('#loading');
const setupDiv = document.querySelector('#setup');
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
if (!regUsername) {
alert('Please enter a username.');
return;
2024-06-03 19:23:14 -04:00
}
config.userName = regUsername;
2024-06-08 15:16:28 -04:00
setupDiv.classList.remove('hidden');
document.querySelector('#register').classList.add('hidden');
loadingDiv.classList.add('hidden');
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
const randomTopic = crypto.randomBytes(32);
document.querySelector('#chat-room-topic').innerText = truncateHash(b4a.toString(randomTopic, 'hex'));
writeConfigToFile("./config.json");
2024-06-08 15:16:28 -04:00
}
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
async function createChatRoom() {
const topicBuffer = crypto.randomBytes(32);
const topic = b4a.toString(topicBuffer, 'hex');
addRoomToList(topic);
joinSwarm(topicBuffer);
}
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
async function joinChatRoom(e) {
e.preventDefault();
const topicStr = document.querySelector('#join-chat-room-topic').value;
const topicBuffer = b4a.from(topicStr, 'hex');
addRoomToList(topicStr);
joinSwarm(topicBuffer);
}
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
async function joinSwarm(topicBuffer) {
if (currentRoom) {
currentRoom.destroy();
}
2024-06-08 15:16:28 -04:00
document.querySelector('#setup').classList.add('hidden');
document.querySelector('#loading').classList.remove('hidden');
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
const discovery = swarm.join(topicBuffer, { client: true, server: true });
await discovery.flushed();
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
const topic = b4a.toString(topicBuffer, 'hex');
document.querySelector('#chat-room-topic').innerText = topic; // Set full topic here
document.querySelector('#loading').classList.add('hidden');
document.querySelector('#chat').classList.remove('hidden');
2024-06-08 15:16:28 -04:00
currentRoom = discovery;
clearMessages();
}
2024-06-08 15:16:28 -04:00
function addRoomToList(topic) {
const roomList = document.querySelector('#room-list');
const roomItem = document.createElement('li');
roomItem.textContent = truncateHash(topic);
roomItem.dataset.topic = topic;
roomItem.addEventListener('click', () => switchRoom(topic));
roomList.appendChild(roomItem);
config.rooms.push(topic);
writeConfigToFile("./config.json");
2024-06-08 15:16:28 -04:00
}
2024-06-09 03:08:29 -04:00
function addRoomToListWithoutWritingToConfig(topic) {
const roomList = document.querySelector('#room-list');
const roomItem = document.createElement('li');
roomItem.textContent = truncateHash(topic);
roomItem.dataset.topic = topic;
roomItem.addEventListener('click', () => switchRoom(topic));
roomList.appendChild(roomItem);
}
2024-06-08 15:16:28 -04:00
function switchRoom(topic) {
const topicBuffer = b4a.from(topic, 'hex');
joinSwarm(topicBuffer);
}
2024-06-08 15:16:28 -04:00
function leaveRoom() {
if (currentRoom) {
const topic = b4a.toString(currentRoom.topic, 'hex');
const roomItem = document.querySelector(`li[data-topic="${topic}"]`);
if (roomItem) {
roomItem.remove();
}
2024-06-09 04:09:58 -04:00
2024-06-09 04:17:20 -04:00
config.rooms = config.rooms.filter(e => e !== topic);
2024-06-09 04:09:58 -04:00
writeConfigToFile("./config.json");
2024-06-08 15:16:28 -04:00
currentRoom.destroy();
currentRoom = null;
}
2024-06-08 15:16:28 -04:00
document.querySelector('#chat').classList.add('hidden');
document.querySelector('#setup').classList.remove('hidden');
}
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
function sendMessage(e) {
e.preventDefault();
const message = document.querySelector('#message').value;
document.querySelector('#message').value = '';
2024-06-03 19:23:14 -04:00
onMessageAdded(config.userName, message, config.userAvatar);
2024-06-08 15:16:28 -04:00
const messageObj = JSON.stringify({
type: 'message',
name: config.userName,
2024-06-08 15:16:28 -04:00
message,
avatar: config.userAvatar,
2024-06-09 04:02:45 -04:00
topic: b4a.toString(currentRoom.topic, 'hex'),
2024-06-10 10:19:36 -04:00
peers: [...swarm.connections].map(peer => peer.remotePublicKey.toString('hex')).push(swarm.keyPair.publicKey.toString('hex')),
2024-06-08 15:16:28 -04:00
timestamp: Date.now(),
2024-06-09 04:09:07 -04:00
readableTimestamp: new Date().toLocaleString(), // Added human-readable timestamp
2024-06-08 15:16:28 -04:00
});
const peers = [...swarm.connections];
for (const peer of peers) {
peer.write(messageObj);
2024-06-03 19:23:14 -04:00
}
2024-06-08 15:16:28 -04:00
}
2024-06-03 19:23:14 -04:00
2024-06-09 07:00:42 -04:00
function sendFileMessage(name, fileUrl, fileType, avatar) {
const fileName = fileUrl.split('/').pop();
const messageObj = JSON.stringify({
type: 'file',
name,
fileName,
2024-06-09 07:00:42 -04:00
fileUrl,
fileType,
avatar,
timestamp: Date.now(),
});
const peers = [...swarm.connections];
for (const peer of peers) {
peer.write(messageObj);
}
addFileMessage(name, fileName, fileUrl, fileType, avatar);
}
function addFileMessage(from, fileName, fileUrl, fileType, avatar) {
const $div = document.createElement('div');
$div.classList.add('message');
const $img = document.createElement('img');
2024-06-09 07:00:42 -04:00
$img.src = avatar || 'https://via.placeholder.com/40';
$img.classList.add('avatar');
$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;
$content.appendChild($header);
if (fileType.startsWith('image/')) {
const $image = document.createElement('img');
2024-06-09 07:00:42 -04:00
$image.src = fileUrl;
$image.alt = fileName;
$image.classList.add('attached-image');
$content.appendChild($image);
} else {
const $fileLink = document.createElement('a');
2024-06-09 07:00:42 -04:00
$fileLink.href = fileUrl;
$fileLink.textContent = `File: ${fileName}`;
$fileLink.download = fileName;
$content.appendChild($fileLink);
}
$div.appendChild($content);
document.querySelector('#messages').appendChild($div);
scrollToBottom();
}
2024-06-08 15:22:50 -04:00
function updatePeerCount() {
2024-06-08 16:08:53 -04:00
const peerCountElement = document.querySelector('#peers-count');
2024-06-08 15:22:50 -04:00
if (peerCountElement) {
2024-06-08 16:08:53 -04:00
peerCountElement.textContent = peerCount; // Display the actual peer count
2024-06-08 15:22:50 -04:00
}
}
2024-06-08 15:16:28 -04:00
function scrollToBottom() {
2024-06-09 07:00:42 -04:00
var container = document.getElementById("messages-container");
2024-06-08 15:16:28 -04:00
container.scrollTop = container.scrollHeight;
}
2024-06-04 01:00:24 -04:00
2024-06-08 15:16:28 -04:00
function onMessageAdded(from, message, avatar) {
const $div = document.createElement('div');
$div.classList.add('message');
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
const $img = document.createElement('img');
2024-06-09 07:00:42 -04:00
2024-06-09 05:35:37 -04:00
$img.src = updatePortInUrl(avatar) || 'https://via.placeholder.com/40'; // Default to a placeholder image if avatar URL is not provided
2024-06-09 07:00:42 -04:00
console.log(updatePortInUrl(avatar))
$img.classList.add('avatar');
2024-06-08 15:16:28 -04:00
$div.appendChild($img);
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
const $content = document.createElement('div');
$content.classList.add('message-content');
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
const $header = document.createElement('div');
$header.classList.add('message-header');
$header.textContent = from;
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
const $text = document.createElement('div');
$text.classList.add('message-text');
2024-06-04 00:03:14 -04:00
2024-06-08 15:16:28 -04:00
const md = window.markdownit();
const markdownContent = md.render(message);
$text.innerHTML = markdownContent;
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
$content.appendChild($header);
$content.appendChild($text);
$div.appendChild($content);
2024-06-03 19:23:14 -04:00
2024-06-08 15:16:28 -04:00
document.querySelector('#messages').appendChild($div);
scrollToBottom();
}
2024-06-03 22:33:39 -04:00
2024-06-08 15:16:28 -04:00
function truncateHash(hash) {
return `${hash.slice(0, 6)}...${hash.slice(-6)}`;
}
2024-06-08 15:16:28 -04:00
async function updateIcon(username, avatarBuffer) {
const userIcon = document.querySelector(`img[src*="${username}.png"]`);
if (userIcon) {
2024-06-08 16:15:55 -04:00
const avatarBlob = new Blob([avatarBuffer], { type: 'image/png' });
const avatarUrl = URL.createObjectURL(avatarBlob);
userIcon.src = avatarUrl;
config.userAvatar = avatarUrl;
2024-06-09 07:00:42 -04:00
writeConfigToFile("./config.json");
2024-06-04 00:57:28 -04:00
}
2024-06-08 15:16:28 -04:00
}
2024-06-04 00:57:28 -04:00
2024-06-08 15:16:28 -04:00
function clearMessages() {
const messagesContainer = document.querySelector('#messages');
while (messagesContainer.firstChild) {
messagesContainer.removeChild(messagesContainer.firstChild);
}
2024-06-08 15:16:28 -04:00
}
2024-06-08 15:16:28 -04:00
function toggleSetupView() {
const setupDiv = document.querySelector('#setup');
setupDiv.classList.toggle('hidden');
}
function writeConfigToFile(filePath) {
fs.writeFile(filePath, JSON.stringify(config), (err) => {
if (err) return console.error(err);
2024-06-09 07:00:42 -04:00
console.log("File has been created");
});
}
2024-06-09 03:38:53 -04:00
function updatePortInUrl(url) {
if (!url) return url;
const urlObject = new URL(url);
urlObject.port = servePort;
return urlObject.toString();
}
2024-06-09 07:00:42 -04:00
initialize();