Compare commits

..

20 Commits

Author SHA1 Message Date
4ae2f4cbe8 Update package.json 2024-11-23 01:53:15 -05:00
7c874fab21 Auto Join Guild on Create 2024-07-08 00:57:58 -04:00
f125cad87c change screenshot 2024-07-08 00:41:46 -04:00
cb88b16606 Readd Markdown Support + Syntax Highlights and DOMPurify is used to sanitize HTML content to prevent XSS attacks. 2024-07-07 23:42:17 -04:00
94ea9b6840 Merge pull request 'Feat: Adding GUILDS!' (#12) from guilds into main
Reviewed-on: #12
2024-07-07 23:01:33 -04:00
7eddd45f79 Only auto play on peers 2024-07-07 22:49:15 -04:00
70bc69ddea auto play audio messages 2024-07-07 22:45:55 -04:00
aa70e42fdc change internal agent prefix 2024-07-07 22:40:22 -04:00
c530a8d69c Add back file menu 2024-07-07 22:39:31 -04:00
084cb02a11 fix icon message 2024-07-07 22:00:13 -04:00
a0c7eb1561 fix 2024-07-07 21:52:57 -04:00
43e9890235 readd updateIcon 2024-07-07 21:49:13 -04:00
ed4625275d init all guild topics on start 2024-07-07 21:40:52 -04:00
55875f468c more test 2024-07-07 21:30:09 -04:00
e0ad9c7067 more test 2024-07-07 21:21:55 -04:00
d423031cfb more test 2024-07-07 21:14:17 -04:00
181d011b8d more test 2024-07-07 21:08:30 -04:00
6cfbb36d35 Merge branch 'guilds' of git.ssh.surf:snxraven/LinkUp-P1P-Chat into guilds 2024-07-07 20:51:41 -04:00
da1bf28e3d test 2024-07-07 20:51:12 -04:00
a1b11f7ae6 test 2024-07-07 20:46:59 -04:00
5 changed files with 175 additions and 24 deletions

124
app.js
View File

@ -7,6 +7,22 @@ import Corestore from 'corestore';
import { EventEmitter } from 'events';
import fs from 'fs';
import handleCommand from './commands.js';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import DOMPurify from 'dompurify';
const md = new MarkdownIt({
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return '<pre class="hljs"><code>' +
hljs.highlight(str, { language: lang }).value +
'</code></pre>';
} catch (__) {}
}
return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
}
});
const agentAvatarPath = './assets/agent.png';
let agentAvatar = '';
@ -141,6 +157,7 @@ async function initialize() {
loadConfigFromFile();
renderGuildList();
await connectToAllRooms();
await joinAllGuilds(); // Ensure the app joins all guilds on startup
}
if (!configExists) {
@ -155,9 +172,10 @@ async function initialize() {
hljs.highlightAll();
});
document.addEventListener('createGuild', (event) => {
document.addEventListener('createGuild', async (event) => {
const { guildName } = event.detail;
createGuild(guildName);
await joinAllGuilds(); // Ensure the app joins all guilds on startup
});
document.addEventListener('addRoomToGuild', (event) => {
@ -179,11 +197,22 @@ async function initialize() {
console.log('Event switchRoom with roomTopic:', roomTopic);
switchRoom(guildTopic, roomTopic);
});
document.addEventListener('joinGuildRequest', (event) => {
const { guildTopic } = event.detail;
joinGuildRequest(guildTopic);
});
} catch (error) {
console.error('Error during initialization:', error);
}
}
async function joinAllGuilds() {
for (const guildTopic in config.guilds) {
await joinGuildRequest(guildTopic);
}
}
function setupEventListeners() {
const registerForm = document.querySelector('#register-form');
const selectAvatarButton = document.querySelector('#select-avatar');
@ -195,6 +224,7 @@ function setupEventListeners() {
const attachFileButton = document.getElementById('attach-file');
const fileInput = document.getElementById('file-input');
const talkButton = document.getElementById('talk-btn');
const joinGuildBtn = document.getElementById('join-guild');
if (registerForm) {
registerForm.addEventListener('submit', registerUser);
@ -234,6 +264,14 @@ function setupEventListeners() {
if (talkButton) {
setupTalkButton();
}
if (joinGuildBtn) {
joinGuildBtn.addEventListener('click', () => {
const guildTopic = document.getElementById('join-guild-topic').value.trim();
if (guildTopic) {
joinGuildRequest(guildTopic);
}
});
}
// Add event listeners only for room items
document.querySelectorAll('.room-item').forEach(item => {
@ -249,7 +287,7 @@ function setupEventListeners() {
});
}
function handleIncomingMessage(messageObj) {
function handleIncomingMessage(messageObj, connection) {
console.log('Received message:', messageObj); // Debugging log
if (messageObj.type === 'icon') {
@ -347,7 +385,25 @@ function handleIncomingMessage(messageObj) {
renderGuildList();
joinGuild(guildTopic);
}
} else {
} else if (messageObj.type === 'guildRequest') {
const guildTopic = messageObj.guildTopic;
const guild = config.guilds[guildTopic];
if (guild) {
const guildResponseMessage = JSON.stringify({
type: 'guildResponse',
guildData: JSON.stringify({
guildTopic,
guildAlias: guild.alias,
rooms: guild.rooms,
owner: guild.owner
})
});
connection.write(guildResponseMessage);
}
} else if (messageObj.type === 'guildResponse') {
const guildData = messageObj.guildData;
processGuild(guildData);
} else {
console.error('Received unknown message type:', messageObj);
}
}
@ -360,7 +416,7 @@ async function handleConnection(connection, info) {
if (iconBuffer) {
const iconMessage = JSON.stringify({
type: 'icon',
username: config.userName,
name: config.userName,
avatar: b4a.toString(iconBuffer, 'base64'),
timestamp: Date.now()
});
@ -399,7 +455,7 @@ async function handleConnection(connection, info) {
connection.write(guildJoinMessage);
}
} else {
eventEmitter.emit('onMessage', messageObj);
eventEmitter.emit('onMessage', messageObj, connection);
}
});
@ -1037,6 +1093,10 @@ function addAudioMessage(name, audioUrl, avatar, topic) {
const audioElement = document.createElement('audio');
audioElement.src = audioUrl;
audioElement.controls = true;
// Autoplay only if the message is from a peer
if (name !== config.userName) {
audioElement.autoplay = true;
}
audioElement.classList.add('message-audio');
messageContent.appendChild(senderName);
@ -1077,7 +1137,7 @@ function addMessage(name, message, avatar, topic) {
const messageText = document.createElement('div');
messageText.classList.add('message-text');
messageText.innerHTML = message;
messageText.innerHTML = DOMPurify.sanitize(md.render(message));
messageContent.appendChild(senderName);
messageContent.appendChild(messageText);
@ -1088,6 +1148,19 @@ function addMessage(name, message, avatar, topic) {
if (topic === currentTopic()) {
container.scrollTop = container.scrollHeight;
}
hljs.highlightAll(); // Re-highlight all code blocks
}
async function updateIcon(username, avatarBuffer) {
const userIcon = document.querySelector(`img[src*="${username}.png"]`);
if (userIcon) {
const avatarBlob = new Blob([avatarBuffer], { type: 'image/png' });
const avatarUrl = URL.createObjectURL(avatarBlob);
userIcon.src = updatePortInUrl(avatarUrl);
config.userAvatar = avatarUrl;
writeConfigToFile("./config.json");
}
}
function clearMessages() {
@ -1110,8 +1183,7 @@ async function sendMessage(e) {
const timestamp = Date.now();
console.log("Sending message to current topic:", topic); // Add logging
if (message.startsWith('~')) {
if (message.startsWith('>')) {
await handleCommand(message, {
eventEmitter,
currentTopic: topic, // Pass the current topic as a string
@ -1121,7 +1193,8 @@ async function sendMessage(e) {
leaveRoom,
createRoom,
listFiles,
deleteFile
deleteFile,
servePort
});
return;
}
@ -1133,7 +1206,7 @@ async function sendMessage(e) {
const messageObj = JSON.stringify({
type: 'message',
name: config.userName,
avatar: config.userAvatar,
avatar: updatePortInUrl(config.userAvatar),
topic: topic,
timestamp: timestamp,
message
@ -1207,4 +1280,35 @@ function handleFileInput(event) {
}
}
async function joinGuildRequest(guildTopic) {
const guildTopicBuffer = b4a.from(guildTopic, 'hex');
if (!activeRooms.some(room => room.topic === guildTopic)) {
try {
const swarm = new Hyperswarm();
const discovery = swarm.join(guildTopicBuffer, { client: true, server: true });
await discovery.flushed();
swarm.on('connection', (connection, info) => {
handleConnection(connection, info);
// Request guild information from peers
const guildRequestMessage = JSON.stringify({
type: 'guildRequest',
guildTopic
});
connection.write(guildRequestMessage);
});
activeRooms.push({ topic: guildTopic, swarm, discovery });
console.log('Joined guild topic:', guildTopic); // Debugging log
updatePeerCount();
} catch (error) {
console.error('Error joining swarm for guild topic:', guildTopic, error);
}
}
}
window.joinGuildRequest = joinGuildRequest;
initialize();

View File

@ -11,7 +11,7 @@ if (fs.existsSync(agentAvatarPath)) {
}
export default async function handleCommand(command, context) {
const { eventEmitter, currentTopic, clearMessages, addMessage, joinRoom, leaveRoom, createRoom, listFiles } = context;
const { eventEmitter, currentTopic, clearMessages, addMessage, joinRoom, leaveRoom, createRoom, listFiles, deleteFile, servePort } = context;
console.log("Context received in handleCommand:", context); // Add logging
@ -23,39 +23,82 @@ export default async function handleCommand(command, context) {
console.log("Current topic:", currentTopic); // Add logging to check the current topic
switch (cmd) {
case '~clear':
case '>clear':
clearMessages(currentTopic);
break;
case '~ping':
case '>ping':
addMessage('LinkUp', 'pong', agentAvatar, currentTopic);
break;
case '~help':
addMessage('LinkUp', 'Available commands:\n- ~clear\n- ~ping\n- ~help\n- ~join [topic]\n- ~leave\n- ~create [alias]\n- ~list-files', agentAvatar, currentTopic);
case '>help':
addMessage('LinkUp', 'Available commands:\n- >clear\n- >ping\n- >help\n- >join [topic]\n- >leave\n- >create [alias]\n- >list-files', agentAvatar, currentTopic);
break;
case '~join':
case '>join':
if (restArgs) {
await joinRoom(currentTopic, restArgs);
} else {
addMessage('LinkUp', 'Usage: ~join [topic]', agentAvatar, currentTopic);
addMessage('LinkUp', 'Usage: >join [topic]', agentAvatar, currentTopic);
}
break;
case '~leave':
case '>leave':
leaveRoom(currentTopic);
break;
case '~create':
case '>create':
if (restArgs) {
await createRoom(currentTopic, restArgs);
} else {
addMessage('LinkUp', 'Usage: ~create [alias]', agentAvatar, currentTopic);
addMessage('LinkUp', 'Usage: >create [alias]', agentAvatar, currentTopic);
}
break;
case '~list-files':
case '>list-files':
const files = await listFiles();
const fileList = files.length > 0 ? files.map(file => `- ${file}`).join('\n') : 'No files available';
addMessage('LinkUp', `Available files:\n${fileList}`, agentAvatar, currentTopic);
// Render the file list with delete buttons
renderFileList(files, deleteFile, servePort);
break;
default:
addMessage('LinkUp', `Unknown command: ${cmd}`, agentAvatar, currentTopic);
console.log('Unknown command:', command);
}
}
function renderFileList(files, deleteFile, servePort) {
const container = document.querySelector('#messages');
if (!container) {
console.error('Element #messages not found');
return;
}
const fileList = document.createElement('ul');
files.forEach(file => {
const listItem = document.createElement('li');
const fileButton = document.createElement('button');
fileButton.textContent = file.trim();
fileButton.onclick = () => downloadFile(file.trim(), servePort);
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.onclick = async () => {
await deleteFile(file);
listItem.remove();
};
listItem.appendChild(fileButton);
listItem.appendChild(deleteButton);
fileList.appendChild(listItem);
});
container.appendChild(fileList);
}
function downloadFile(filename, servePort) {
const url = `http://localhost:${servePort}/files/${filename}`;
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 251 KiB

After

Width:  |  Height:  |  Size: 55 KiB

View File

@ -185,7 +185,7 @@
joinGuildBtn.addEventListener('click', async (event) => {
const guildTopic = document.getElementById('join-guild-topic').value.trim();
if (guildTopic) {
await processGuild(guildTopic);
await joinGuildRequest(guildTopic);
}
});
@ -254,4 +254,4 @@
}
</script>
</body>
</html>
</html>

View File

@ -11,7 +11,8 @@
"minWidth": 955,
"minHeight": 547,
"width": 955
}
},
"links": ["http://127.0.0.1", "http://localhost", "https://ka-f.fontawesome.com", "https://cdn.jsdelivr.net", "https://cdnjs.cloudflare.com"]
},
"license": "Apache-2.0",
"devDependencies": {
@ -24,12 +25,15 @@
"dependencies": {
"b4a": "^1.6.6",
"corestore": "^6.18.2",
"dompurify": "^3.1.6",
"dotenv": "^16.4.5",
"electron": "^30.0.8",
"highlight.js": "^11.10.0",
"hypercore-crypto": "^3.4.1",
"hyperdrive": "^11.8.1",
"hyperswarm": "^4.7.14",
"localdrive": "^1.11.4",
"markdown-it": "^14.1.0",
"marked": "^12.0.2",
"serve-drive": "^5.0.8"
}