Skip to content

Commit

Permalink
Add p2p dms
Browse files Browse the repository at this point in the history
  • Loading branch information
n9lsjr committed Mar 5, 2025
1 parent f5d9c21 commit e07c2ce
Show file tree
Hide file tree
Showing 9 changed files with 107 additions and 101 deletions.
35 changes: 27 additions & 8 deletions src/backend/beam.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const { saveMsg } = require('./database.cjs')
const sanitizeHtml = require('sanitize-html')
const progress = require("progress-stream");
const {createWriteStream, createReadStream} = require("fs");
const { sleep, sanitize_pm_message, randomKey, hash } = require('./utils.cjs');
const { sleep, sanitize_pm_message, randomKey, hash, parse_call } = require('./utils.cjs');
const { ipcMain } = require('electron')
const {Hugin} = require('./account.cjs');
const { keychain, get_new_peer_keys } = require('./crypto.cjs');
Expand All @@ -18,7 +18,7 @@ let downloadDirectory

ipcMain.on("end-beam", async (e, chat) => {
console.log("end beam");
end_beam(chat);
end_beam(chat, true);
})

//FILES
Expand Down Expand Up @@ -113,7 +113,7 @@ const beam_event = (beam, chat, key) => {
const addr = chat.substring(0,99)
const msgKey = chat.substring(99,163)
active_beams.push({key, chat: addr, beam})
Hugin.send('new-beam', {key, chat: addr})
Hugin.send('new-beam', {key, chat: addr, hugin: addr + msgKey})
beam.on('remote-address', function ({ host, port }) {
if (!host) console.log('Could not find the host')
else console.log('Connected to DHT with' + host + ':' + port)
Expand All @@ -138,6 +138,7 @@ const beam_event = (beam, chat, key) => {

beam.on('end', () => {
console.log('Chat beam ended on event')
end_beam(addr, true)
})

beam.on('error', function (e) {
Expand Down Expand Up @@ -167,11 +168,13 @@ const decrpyt_beam_message = async (str, msgKey) => {
decrypted_message.k = msgKey
decrypted_message.sent = false
const [message, address, key, timestamp] = sanitize_pm_message(decrypted_message)

if (!message) return


const [text, data, call] = is_call(decrypted_message.msg, address, false, timestamp)

const newMsg = {
msg: message,
msg: call ? text : message,
chat: address,
sent: false,
timestamp: timestamp,
Expand All @@ -184,6 +187,22 @@ const decrpyt_beam_message = async (str, msgKey) => {
saveMsg(message, address, false, timestamp)
}

const is_call = (message, address, sent, timestamp) => {
//Checking if private msg is a call
const [text, data, is_call, if_sent] = parse_call(message, address, sent, true, timestamp)

if (text === "Audio call started" || text === "Video call started" && is_call && !if_sent) {
//Incoming calll
Hugin.send('call-incoming', data)
return [text, true]
} else if (text === "Call answered" && is_call && !if_sent) {
//Callback
Hugin.send('got-callback', data)
return [text, true]
}
return ['',false]
}

const send_beam_message = (message, to) => {
const active = active_beams.find(a => a.chat === to)
active.beam.write(message)
Expand All @@ -201,10 +220,10 @@ const end_file_beam = async (chat, key) => {
}


const end_beam = async (chat, file = false) => {
const end_beam = async (chat, close) => {
const active = active_beams.find(a => a.chat === chat)
if (!active) return
Hugin.send('stop-beam', chat)
Hugin.send('stop-beam', chat, close)
active.beam.end()
await sleep(2000)
active.beam.destroy()
Expand Down
107 changes: 32 additions & 75 deletions src/backend/messages.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,18 @@ const {
removeMessages,
removeContact,
addGroup,
removeGroup,
unBlockContact,
loadBlockList,
blockContact,
getGroupReply,
printGroup,
getGroups,
loadGroups,
deleteMessage,
addRoom,
loadRooms,
addRoomKeys,
getRooms,
removeRoom} = require("./database.cjs")
const {
trimExtra,
sanitize_pm_message,
parse_call,
sanitize_pm_message,
sleep,
hexToUint,
randomKey,
Expand Down Expand Up @@ -159,6 +153,8 @@ ipcMain.on('send-msg', (e, msg, receiver, off_chain, grp, beam) => {
//Listens for event from frontend and saves contact and nickname.
ipcMain.on('add-chat', async (e, hugin_address, nickname, first) => {
save_contact(hugin_address, nickname, first)
const key = await key_derivation_hash(hugin_address.substring(0,99))
await new_beam(key, hugin_address, false);
})


Expand Down Expand Up @@ -190,11 +186,12 @@ ipcMain.on('expand-sdp', (e, data, address) => {

//BEAM

ipcMain.on("beam", async (e, link, chat, send = false, offchain = false) => {
let beamMessage = await new_beam(link, chat, send);
ipcMain.on("beam", async (e, chat, send = false, beam = false) => {
const key = await key_derivation_hash(chat.substring(0,99))
let beamMessage = await new_beam(key, chat, send);
if (beamMessage === "Error") return
if (!beamMessage) return
send_message(beamMessage.msg, beamMessage.chat, offchain)
if (beam) send_message(beamMessage.msg, beamMessage.chat, offchain)
});

//SWARM
Expand All @@ -207,62 +204,28 @@ ipcMain.on('end-swarm', async (e, key) => {
end_swarm(key)
})


//TORRENT

ipcMain.on('download-torrent', (e, file) => {
download_torrent(file)
})

const download_torrent = (file) => {
return
// const client = new WebTorrent({utp: true, dht: false})
// const path = Hugin.downloadDir
// Hugin.send('downloading', file)
// client.add(file.message, { path: path, utp: true }, torrent => {
// console.log("torrent added!")
// torrent.on('download', function (bytes) {
// console.log("Downloading!!!! --------->")
// Hugin.send('download-file-progress', {
// fileName: file.fileName,
// progress: torrent.progress,
// group: file.group,
// chat: file.group,
// path
// })
// } )
// torrent.on('done', () => {
// console.log("Downloaded torrent!")
// Hugin.send('downloading-torrent')
// console.log('torrent download finished')
// })
// })
const peer_dms = async () => {
const contacts = await getConversations()
for (const c of contacts) {
const hashDerivation = await key_derivation_hash(c.chat)
const beam = await new_beam(hashDerivation, c.chat + c.key, false)
if (beam === "Error") continue
if (!beam) continue
}

}

ipcMain.on('upload-torrent', (e, [fileName, path, size, time, group, hash]) => {
return
// console.log("Upload this!", path, fileName, size, time)
// const client = new WebTorrent()
// Hugin.send('uploading', {fileName, progress: 0, size, chat: group, time, hash})
// client.seed(path, {}, (torrent) => {
// console.log('Client is seeding ' + torrent.magnetURI)
// torrent.on('wire', (wire, addr) => {
// Hugin.send('torrent-connection')
// Hugin.send('uploading-torrent')
// })
// torrent.on('upload', function (uploaded) {
// console.log("Uploaded", uploaded)
// Hugin.send('upload-file-progress', {fileName, progress: (uploaded / size) * 100, chat: group, time})
// })
// const message = {m: 'TORRENT://' + torrent.magnetURI, g: group, t: time}

// send_group_message(message, false, false)
// })

})
async function key_derivation_hash(chat) {
const [privateSpendKey, privateViewKey] = keychain.getPrivKeys()
const recvAddr = await Address.fromAddress(chat)
const recvPubKey = recvAddr.m_keys.m_viewKeys.m_publicKey
const derivation = await crypto.generateKeyDerivation(recvPubKey, privateViewKey);
return await crypto.cn_fast_hash(derivation)
}

const start_message_syncer = async () => {
//Load knownTxsIds to backgroundSyncMessages on startup
peer_dms()
known_keys = Hugin.known_keys
block_list = Hugin.block_list
await background_sync_messages(await load_checked_txs())
Expand Down Expand Up @@ -598,6 +561,9 @@ async function fetch_hugin_messages() {

async function send_message(message, receiver, off_chain = false, group = false, beam_this = false) {
//Assert address length
console.log("Send message!", message)
console.log("offchain", off_chain)
console.log("beam_this", beam_this)
if (receiver.length !== 163) {
return
}
Expand Down Expand Up @@ -1170,17 +1136,6 @@ async function save_message(msg, offchain = false) {
if (!message) return

if (await messageExists(timestamp)) return

//Checking if private msg is a call
let [text, data, is_call, if_sent] = parse_call(msg.msg, addr, sent, offchain, timestamp)

if (text === "Audio call started" || text === "Video call started" && is_call && !if_sent) {
//Incoming calll
Hugin.send('call-incoming', data)
} else if (text === "Call answered" && is_call && !if_sent) {
//Callback
Hugin.send('got-callback', data)
}

//If sent set addr to chat instead of from
if (msg.chat && sent) {
Expand All @@ -1193,7 +1148,6 @@ async function save_message(msg, offchain = false) {
await save_contact(hugin)
}

message = sanitizeHtml(text)
let newMsg = await saveMsg(message, addr, sent, timestamp, offchain)
if (sent) {
//If sent, update conversation list
Expand Down Expand Up @@ -1234,6 +1188,9 @@ async function save_contact(hugin_address, nickname = false, first = false) {
t: Date.now(),
})
known_keys.pop(key)
} else {
const key = await key_derivation_hash(addr)
await new_beam(key, hugin_address, false);
}
}

Expand All @@ -1256,12 +1213,12 @@ function get_sdp(data)
if (data.type == 'offer')
{
let parsed_data = `${data.video ? 'Δ' : 'Λ'}` + parse_sdp(data.data, false)
send_message(parsed_data, data.contact, data.offchain, data.group)
send_message(parsed_data, data.contact, true, data.group, true)
}
else if (data.type == 'answer')
{
let parsed_data = `${data.video ? 'δ' : 'λ'}` + parse_sdp(data.data, true)
send_message(parsed_data, data.contact, data.offchain, data.group)
send_message(parsed_data, data.contact, true, data.group, true)
}
}

Expand Down
19 changes: 13 additions & 6 deletions src/backend/storage.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -151,11 +151,14 @@ async beam_started(beam, upload, key, topic, file, room) {
console.log("----:::::::::::::::::::----")
console.log("------BEAM CONNECTED------")
console.log("----:::::::::::::::::::----")
if (upload) {
//upload
this.upload(beam, file, topic)
} else {
this.download(beam, file, topic, room)
try {
if (upload) {
this.upload(beam, file, topic)
} else {
this.download(beam, file, topic, room)
}
} catch(e) {

}
})

Expand Down Expand Up @@ -184,7 +187,11 @@ async upload(beam, file, topic) {
const stream = Readable.from(send)
stream.on('data', data => {
console.log("Sending data ------>", data)
beam.write(data)
try {
beam.write(data)
} catch(e) {
console.log("Error writing data.")
}
})
}

Expand Down
2 changes: 0 additions & 2 deletions src/backend/swarm.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -581,12 +581,10 @@ const request_file = async (address, topic, file, room) => {

const process_files = async (data, active, con, topic) => {
//Check if the latest 10 files are in sync
console.log("PROCESS FILES")
if (Hugin.syncImages.some(a => a === topic)) {
if (!Array.isArray(data.files)) return 'Ban'
if (data.files.length > 10) return 'Ban'
for (const file of data.files) {
console.log("File", file.fileName)
if (!check_hash(file.hash)) continue
if (downloading.some(a => a === file.hash)) continue
if (Hugin.get_files().some(a => a.time === file.time)) continue
Expand Down
4 changes: 1 addition & 3 deletions src/lib/components/chat/ChatBubble.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,8 @@
}
const joinBeam = () => {
let key = beam_key
if (key === "new") return
clicked = true
window.api.createBeam(key, $user.activeChat.chat + $user.activeChat.key)
window.api.createBeam($user.activeChat.chat + $user.activeChat.key)
$beam.active.push({
chat: $user.activeChat.chat,
connected: false,
Expand Down
16 changes: 15 additions & 1 deletion src/lib/components/chat/Contact.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
import {createEventDispatcher} from 'svelte'
import {fade} from 'svelte/transition'
import {get_avatar, getColorFromHash} from '$lib/utils/hugin-utils.js'
import {notify, user, webRTC} from '$lib/stores/user.js'
import {notify, user, webRTC, beam} from '$lib/stores/user.js'
import { isLatin } from '$lib/utils/utils'
export let contact
let thisCall = false
let beamInvite = false
let asian = false
let online = false
$: counter = $notify.unread.filter(a => a.type === 'message' && contact.chat === a.chat).length
$: if (contact.msg.substring(0,7) === "BEAM://") {
Expand Down Expand Up @@ -43,6 +44,14 @@ const rename = () => {
})
dispatch('openRename')
}
$: {
if ($beam.active.length) {
online = $beam.active.some(a => a.chat == contact.chat && a.connected);
} else {
online = false
}
}
</script>

<div
Expand All @@ -51,6 +60,7 @@ const rename = () => {
out:fade
class:rgb="{thisCall}"
class:active="{contact.chat === $user.activeChat.chat}"
class:online={online}
on:click="{() => printThis(contact)}"
>

Expand Down Expand Up @@ -162,4 +172,8 @@ p {
.big {
font-size: 17px;
}
.online {
box-shadow: inset 10px 0 7px -7px var(--success-color);
}
</style>
Loading

0 comments on commit e07c2ce

Please sign in to comment.