This repository has been archived by the owner on Jun 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sender.js
218 lines (188 loc) · 7.23 KB
/
sender.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
(function() {
let uid;
let lastPeerId = null;
let peer = null;
let peerId = null;
let conn = null;
const recipientInput = document.getElementById('receiver-id');
const statusEl = document.getElementById('status');
const messageEl = document.getElementById('message');
const btnSend = document.querySelector('.send');
const sendInput = document.getElementById('sendInput');
const btnClear= document.querySelector('.clearMsg');
const btnConnect = document.querySelector('.connect');
const hide = document.querySelector('.hide');
const url = window.location.href.replace("sender.html", "");
var msgJson = JSON.parse('{"visibility": "visible", "message": ""}');
function init() {
// ... new Peer([id], [options])
peer = new Peer(null, {
debug: 2 // Prints errors and warnings
});
peer.on('open', function(id) {
// Workaround for peer.reconnect deleting previous id
if(peer.id === null) {
console.log('Received null ID from peer open');
peer.id = lastPeerId;
} else {
lastPeerId = peer.id;
}
console.log(`ID: ${peer.id}`);
statusEl.textContent = 'Awaiting connection...'; // DIFF
});
peer.on('connection', function(newConn) {
// Deny incoming connections
newConn.on('open', function() {
newConn.send('Sender does not accept incoming connections.');
setTimeout(() => { newConn.close(); }, 500);
});
});
peer.on('disconnected', function() {
statusEl.textContent = 'Connection lost.';
console.log('Connection lost.');
// Workaround for peer.reconnect deleting previous id
peer.id = lastPeerId;
peer._lastServerId = lastPeerId;
peer.reconnect();
});
peer.on('close', function() {
conn = null;
statusEl.textContent = 'Connection closed. Please Refresh.';
console.log('Connection closed. Please Refresh.');
});
peer.on('error', function(err) {
console.log(`Error: ${err}`);
alert(`${err}`);
})
}
function join() {
// Close old connection
if(conn) {
conn.close();
}
// console.log('url param id:' + getUrlParam('id'));
// if(getUrlParam('id') !== null) recipientInput.value = getUrlParam('id');
// conn = peer.connect(recipientInput.value, {
// reliable: true
// });
conn = peer.connect(uid, {
reliable: true
});
conn.on('open', function() {
// document.querySelectorAll('#hide').display=none;
statusEl.textContent = `Connected to: ${conn.peer}`;
console.log(`Connected to: ${conn.peer}`);
// Check URL parameters for commands that should be sent right away
const command = getUrlParam('command');
if(command) {
conn.send(command);
}
});
conn.on('data', function(data64) {
// msg = DOMPurify.sanitize(data, { USE_PROFILES: { html: false } });
// const data = structuredClone(atob(data64));
// msg = decodeURIComponent(atob(data["message"]));
let data = JSON.parse(decodeURIComponent(atob(data64)));
msg = data["message"];
if(data["visibility"] === "hidden"){
console.log('Data received.');
addMessage(`<p class="peerMsg">>#######(Secret message)</p>`);
} else{
console.log('Data received.', msg);
addMessage(`<p style="word-wrap: break-word; overflow-wrap: break-word;" class="peerMsg">>${msg}</p>`);
}
writeClipboard(msg);
});
conn.on('close', function() {
statusEl.textContent = 'Connection closed.';
});
}
// if(getUrlParam('id') !== null){join();}
/*
Get first "GET style" parameter from href.
This enables delivering an initial command upon page load.
*/
function getUrlParam(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
const regexS = "[\\?&]" + name + "=([^&#]*)";
const regex = new RegExp(regexS);
const results = regex.exec(window.location.href);
if (results === null)
return null;
else
return results[1];
}
function addMessage(msg) {
// msg = DOMPurify.sanitize(msg, { USE_PROFILES: { html: false } });
messageEl.innerHTML = msg+document.getElementById('message').innerHTML;
}
function clearMessages() {
messageEl.innerHTML = '';
addMessage('(Messages cleared)');
}
async function writeClipboard(data) {
try {
await navigator.clipboard.writeText(data);
console.log('message in clipboard');
} catch (err) {
console.error('Failed to copy: ', err);
}
}
function readAndSendClipboard(){
navigator.clipboard.readText().then(function(clipboardText) {
console.log(clipboardText);
sendMessage(clipboardText);
});
}
function sendMessage(data){
if(conn && conn.open) {
msg = DOMPurify.sanitize(data, { USE_PROFILES: { html: false } });
msgJson["message"] = msg;
// Clear the input field
sendInput.value = '';
conn.send(btoa(encodeURIComponent(JSON.stringify(msgJson))));
console.log(`Sent: ${msgJson}`);
if(msgJson["visibility"] === "hidden"){
addMessage(`<p class="selfMsg">(Secret message)#######<</p>`);
}else addMessage(`<p style="word-wrap: break-word; overflow-wrap: break-word;" class="selfMsg">${msg}< </p>`);
} else {
console.log('Connection is closed.');
}
}
document.querySelector('.past-clipbrd').addEventListener('click', () => {
readAndSendClipboard();
});
btnClear.addEventListener('click', clearMessages);
sendInput.addEventListener('keypress', function(event) {
// If used pressed 'Enter'
if(event.key === 'Enter') {
btnSend.click();
}
});
// send message
btnSend.addEventListener('click', () => {
sendMessage(sendInput.value);
});
hide.addEventListener('click', () => {
if(msgJson["visibility"] == "visible"){
hide.src = 'hidden.png';
msgJson["visibility"] = "hidden";
}
else{
hide.src = 'open.png';
msgJson["visibility"] = "visible";
}
})
init();
if(getUrlParam('id') !== null){
uid = getUrlParam('id');
console.log('url param id:' + uid);
};
btnConnect.addEventListener('click', () => {
uid = recipientInput.value;
join();
});
setTimeout(()=>{
join();
}, 1000)
})();