diff options
author | Marvin Borner | 2019-01-23 18:05:42 +0100 |
---|---|---|
committer | Marvin Borner | 2019-01-23 18:05:42 +0100 |
commit | 3a876b2f3bd7d41b3a720ac48a831d41c425dbbc (patch) | |
tree | 6855e49d6306190ab57b90c014638b26de84f448 /public/scripts/chat.js | |
parent | 6f9cd73f5b8273ab659554e541e52af786789bac (diff) |
Added basic encryption functions
Diffstat (limited to 'public/scripts/chat.js')
-rw-r--r-- | public/scripts/chat.js | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/public/scripts/chat.js b/public/scripts/chat.js new file mode 100644 index 0000000..b2f2816 --- /dev/null +++ b/public/scripts/chat.js @@ -0,0 +1,68 @@ +const $ = require('jquery'); +const nanoid = require('nanoid'); + +let connectedUserId, connectedUser; +const userId = nanoid(); +const peer = new Peer(userId, {host: '127.0.0.1', port: 4242, path: '/', debug: 3}); + +// Peer events +peer.on('open', id => console.log('[LOG] Your ID is', id)); +peer.on('error', err => console.error(err)); +peer.on('connection', conn => { + connectedUser = conn; + console.log('[LOG] Connected with', conn.peer); + conn.on('data', message => receivedMessage(message)); +}); + +/** + * Connects to an user via his id + * @param id + */ +function connect(id) { + const connectionId = nanoid(); + console.log('[LOG] Connecting to', id); + console.log('[LOG] Your connection ID is', connectionId); + connectedUser = peer.connect(id, {label: connectionId, reliable: true}); + connectedUserId = id; + + // setup listener + connectedUser.on('open', () => { + // TODO: Activate chat or sth + // TODO: Send public key + }); + + connectedUser.on('data', message => receivedMessage(message)) +} + +/** + * Sends a message to the user with which you're currently connected + * @param message + */ +function sendMessage(message) { + console.log(`[LOG] Sending message ${message} to ${connectedUserId}`); + connectedUser.send(message); + receivedMessage(message, true); +} + +/** + * Renders the incoming messages + * @param message + * @param self + */ +function receivedMessage(message, self = false) { + if (self) { + $('#messages').append(`<span style="color: green">${message}</span><br>`); + } else { + $('#messages').append(`${message}<br>`); + } +} + +/** + * Events after load + */ +$(document).ready(() => { + $('#add_user_id').on('click', () => connect($('#user_id').val())); + $('#send_message').on('click', () => sendMessage($('#message').val())); + + $('[toggle-contact-modal]').on('click', () => $('#add_contact_modal').toggleClass('is-active')) +}); |