mirror of
https://github.com/schlagmichdoch/PairDrop.git
synced 2025-04-20 15:06:15 -04:00
Version 2 initial commit
This commit is contained in:
parent
81252d301c
commit
663db5cbb3
99 changed files with 2448 additions and 27650 deletions
34
client/scripts/network-v2.js
Normal file
34
client/scripts/network-v2.js
Normal file
|
@ -0,0 +1,34 @@
|
|||
class ServerConnection {
|
||||
|
||||
}
|
||||
|
||||
class Connection {
|
||||
|
||||
}
|
||||
|
||||
class WSConnection extends Connection {
|
||||
|
||||
}
|
||||
|
||||
class RTCConnection extends Connection {
|
||||
|
||||
}
|
||||
|
||||
class Peer {
|
||||
|
||||
constructor(serverConnection) {
|
||||
this._ws = new WSConnection(serverConnection);
|
||||
this._rtc = new RTCConnection(serverConnection);
|
||||
this._fileReceiver = new FileReceiver(this);
|
||||
this._fileSender = new FileSender(this);
|
||||
}
|
||||
|
||||
send(message) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class Peers {
|
||||
|
||||
}
|
475
client/scripts/network.js
Normal file
475
client/scripts/network.js
Normal file
|
@ -0,0 +1,475 @@
|
|||
class ServerConnection {
|
||||
|
||||
constructor() {
|
||||
this._connect();
|
||||
Events.on('beforeunload', e => this._disconnect(), false);
|
||||
}
|
||||
|
||||
_connect() {
|
||||
const ws = new WebSocket(this._endpoint());
|
||||
ws.binaryType = 'arraybuffer';
|
||||
ws.onopen = e => console.log('WS: server connection opened');
|
||||
ws.onmessage = e => this._onMessage(e.data);
|
||||
ws.onclose = e => this._onDisconnect();
|
||||
ws.onerror = e => console.error(e);
|
||||
this._socket = ws;
|
||||
clearTimeout(this._reconnectTimer);
|
||||
}
|
||||
|
||||
_onMessage(msg) {
|
||||
msg = JSON.parse(msg);
|
||||
console.log('WS:', msg);
|
||||
switch (msg.type) {
|
||||
case 'peers':
|
||||
Events.fire('peers', msg.peers);
|
||||
break;
|
||||
case 'peer-joined':
|
||||
Events.fire('peer-joined', msg.peer);
|
||||
break;
|
||||
case 'peer-left':
|
||||
Events.fire('peer-left', msg.peerId);
|
||||
break;
|
||||
case 'signal':
|
||||
Events.fire('signal', msg);
|
||||
break;
|
||||
case 'ping':
|
||||
this.send({ type: 'pong' });
|
||||
break;
|
||||
default:
|
||||
console.error('WS: unkown message type', msg)
|
||||
}
|
||||
}
|
||||
|
||||
send(message) {
|
||||
if (this._socket.readyState !== this._socket.OPEN) return;
|
||||
this._socket.send(JSON.stringify(message));
|
||||
}
|
||||
|
||||
_endpoint() {
|
||||
// hack to detect if deployment or development environment
|
||||
const protocol = location.protocol.startsWith('https') ? 'wss' : 'ws';
|
||||
const host = location.hostname.startsWith('localhost') ? 'localhost:3000' : (location.host + '/server');
|
||||
const webrtc = window.isRtcSupported ? '/webrtc' : '/fallback';
|
||||
const url = protocol + '://' + host + webrtc;
|
||||
return url;
|
||||
}
|
||||
|
||||
_disconnect() {
|
||||
this.send({ type: 'disconnect' });
|
||||
this._socket.close();
|
||||
}
|
||||
|
||||
_onDisconnect() {
|
||||
console.log('WS: server disconnected');
|
||||
Events.fire('notify-user', 'Connection lost. Retry in 5 seconds...');
|
||||
clearTimeout(this._reconnectTimer);
|
||||
this._reconnectTimer = setTimeout(_ => this._connect(), 5000);
|
||||
}
|
||||
}
|
||||
|
||||
class Peer {
|
||||
|
||||
constructor(serverConnection, peerId) {
|
||||
this._server = serverConnection;
|
||||
this._peerId = peerId;
|
||||
this._filesQueue = [];
|
||||
this._busy = false;
|
||||
}
|
||||
|
||||
sendJSON(message) {
|
||||
this._send(JSON.stringify(message));
|
||||
}
|
||||
|
||||
sendFiles(files) {
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
this._filesQueue.push(files[i]);
|
||||
}
|
||||
if (this._busy) return;
|
||||
this._dequeueFile();
|
||||
}
|
||||
|
||||
_dequeueFile() {
|
||||
if (!this._filesQueue.length) return;
|
||||
this._busy = true;
|
||||
const file = this._filesQueue.shift();
|
||||
this._sendFile(file);
|
||||
}
|
||||
|
||||
_sendFile(file) {
|
||||
this.sendJSON({
|
||||
type: 'header',
|
||||
name: file.name,
|
||||
mime: file.type,
|
||||
size: file.size,
|
||||
});
|
||||
this._chunker = new FileChunker(file,
|
||||
chunk => this._send(chunk),
|
||||
offset => this._onPartitionEnd(offset));
|
||||
this._chunker.nextPartition();
|
||||
}
|
||||
|
||||
_onPartitionEnd(offset) {
|
||||
this.sendJSON({ type: 'partition', offset: offset });
|
||||
}
|
||||
|
||||
_onReceivedPartitionEnd(offset) {
|
||||
this.sendJSON({ type: 'partition_received', offset: offset });
|
||||
}
|
||||
|
||||
_sendNextPartition() {
|
||||
if (!this._chunker || this._chunker.isFileEnd()) return;
|
||||
this._chunker.nextPartition();
|
||||
}
|
||||
|
||||
_sendProgress(progress) {
|
||||
this.sendJSON({ type: 'progress', progress: progress });
|
||||
}
|
||||
|
||||
_onMessage(message) {
|
||||
if (typeof message !== 'string') {
|
||||
this._onChunkReceived(message);
|
||||
return;
|
||||
}
|
||||
message = JSON.parse(message);
|
||||
console.log('RTC:', message);
|
||||
switch (message.type) {
|
||||
case 'header':
|
||||
this._onFileHeader(message);
|
||||
break;
|
||||
case 'partition':
|
||||
this._onReceivedPartitionEnd(message);
|
||||
break;
|
||||
case 'partition_received':
|
||||
this._sendNextPartition();
|
||||
break;
|
||||
case 'progress':
|
||||
this._onDownloadProgress(message.progress);
|
||||
break;
|
||||
case 'transfer-complete':
|
||||
this._onTransferCompleted();
|
||||
break;
|
||||
case 'text':
|
||||
this._onTextReceived(message);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
_onFileHeader(header) {
|
||||
this._lastProgress = 0;
|
||||
this._digester = new FileDigester({
|
||||
name: header.name,
|
||||
mime: header.mime,
|
||||
size: header.size
|
||||
}, file => this._onFileReceived(file));
|
||||
}
|
||||
|
||||
_onChunkReceived(chunk) {
|
||||
this._digester.unchunk(chunk);
|
||||
const progress = this._digester.progress;
|
||||
this._onDownloadProgress(progress);
|
||||
|
||||
// occasionally notify sender about our progress
|
||||
if (progress - this._lastProgress < 0.01) return;
|
||||
this._lastProgress = progress;
|
||||
this._sendProgress(progress);
|
||||
}
|
||||
|
||||
_onDownloadProgress(progress) {
|
||||
Events.fire('file-progress', {
|
||||
sender: this._peerId,
|
||||
progress: progress
|
||||
});
|
||||
}
|
||||
|
||||
_onFileReceived(proxyFile) {
|
||||
Events.fire('file-received', proxyFile);
|
||||
this.sendJSON({ type: 'transfer-complete' });
|
||||
// this._digester = null;
|
||||
}
|
||||
|
||||
_onTransferCompleted() {
|
||||
this._onDownloadProgress(1);
|
||||
this._reader = null;
|
||||
this._busy = false;
|
||||
this._dequeueFile();
|
||||
Events.fire('notify-user', 'File transfer completed.');
|
||||
}
|
||||
|
||||
sendText(text) {
|
||||
this.sendJSON({
|
||||
type: 'text',
|
||||
text: btoa(unescape(encodeURIComponent(text)))
|
||||
});
|
||||
}
|
||||
|
||||
_onTextReceived(message) {
|
||||
Events.fire('text-received', {
|
||||
text: decodeURIComponent(escape(atob(message.text))),
|
||||
sender: this._peerId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class RTCPeer extends Peer {
|
||||
|
||||
constructor(serverConnection, peerId) {
|
||||
super(serverConnection, peerId);
|
||||
if (!peerId) return; // we will listen for a caller
|
||||
this._start(peerId, true);
|
||||
}
|
||||
|
||||
_start(peerId, isCaller) {
|
||||
if (!this._peer) {
|
||||
this._isCaller = isCaller;
|
||||
this._peerId = peerId;
|
||||
this._peer = new RTCPeerConnection(RTCPeer.config);
|
||||
this._peer.onicecandidate = e => this._onIceCandidate(e);
|
||||
this._peer.onconnectionstatechange = e => console.log('RTC: state changed:', this._peer.connectionState);
|
||||
}
|
||||
|
||||
if (isCaller) {
|
||||
this._createChannel();
|
||||
} else {
|
||||
this._peer.ondatachannel = e => this._onChannelOpened(e);
|
||||
}
|
||||
}
|
||||
|
||||
_createChannel() {
|
||||
const channel = this._peer.createDataChannel('data-channel', { reliable: true });
|
||||
channel.binaryType = 'arraybuffer';
|
||||
channel.onopen = e => this._onChannelOpened(e)
|
||||
this._peer.createOffer(d => this._onDescription(d), e => this._onError(e));
|
||||
}
|
||||
|
||||
_onDescription(description) {
|
||||
// description.sdp = description.sdp.replace('b=AS:30', 'b=AS:1638400');
|
||||
this._peer.setLocalDescription(description,
|
||||
_ => this._sendSignal({ sdp: description }),
|
||||
e => this._onError(e));
|
||||
}
|
||||
|
||||
_onIceCandidate(event) {
|
||||
if (!event.candidate) return;
|
||||
this._sendSignal({ ice: event.candidate });
|
||||
}
|
||||
|
||||
_sendSignal(signal) {
|
||||
signal.type = 'signal';
|
||||
signal.to = this._peerId;
|
||||
this._server.send(signal);
|
||||
}
|
||||
|
||||
onServerMessage(message) {
|
||||
if (!this._peer) this._start(message.sender, false);
|
||||
const conn = this._peer;
|
||||
|
||||
if (message.sdp) {
|
||||
this._peer.setRemoteDescription(new RTCSessionDescription(message.sdp), () => {
|
||||
if (message.sdp.type !== 'offer') return;
|
||||
this._peer.createAnswer(d => this._onDescription(d), e => this._onError(e));
|
||||
}, e => this._onError(e));
|
||||
} else if (message.ice) {
|
||||
this._peer.addIceCandidate(new RTCIceCandidate(message.ice));
|
||||
}
|
||||
}
|
||||
|
||||
_onChannelOpened(event) {
|
||||
console.log('RTC: channel opened with', this._peerId);
|
||||
const channel = event.channel || event.target;
|
||||
channel.onmessage = e => this._onMessage(e.data);
|
||||
channel.onclose = e => this._onChannelClosed();
|
||||
this._channel = channel;
|
||||
}
|
||||
|
||||
_onChannelClosed() {
|
||||
console.log('RTC: channel closed ', this._peerId);
|
||||
if (!this.isCaller) return;
|
||||
this._start(this._peerId, true); // reopen the channel
|
||||
}
|
||||
|
||||
_send(message) {
|
||||
this._channel.send(message);
|
||||
}
|
||||
|
||||
_onError(error) {
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
refresh() {
|
||||
// check if channel open. otherwise create one
|
||||
if (this._peer && this._channel && this._channel.readyState !== 'open') return;
|
||||
this._createChannel(this._peerId, this._isCaller);
|
||||
}
|
||||
}
|
||||
|
||||
class PeersManager {
|
||||
|
||||
constructor(serverConnection) {
|
||||
this.peers = {};
|
||||
this._server = serverConnection;
|
||||
Events.on('signal', e => this._onMessage(e.detail));
|
||||
Events.on('peers', e => this._onPeers(e.detail));
|
||||
Events.on('files-selected', e => this._onFilesSelected(e.detail));
|
||||
Events.on('send-text', e => this._onSendText(e.detail));
|
||||
Events.on('peer-left', e => this._onPeerLeft(e.detail));
|
||||
}
|
||||
|
||||
_onMessage(message) {
|
||||
if (!this.peers[message.sender]) {
|
||||
this.peers[message.sender] = new RTCPeer(this._server);
|
||||
}
|
||||
this.peers[message.sender].onServerMessage(message);
|
||||
}
|
||||
|
||||
_onPeers(peers) {
|
||||
peers.forEach(peer => {
|
||||
if (this.peers[peer.id]) {
|
||||
this.peers[peer.id].refresh();
|
||||
return;
|
||||
}
|
||||
if (window.isRtcSupported && peer.rtcSupported) {
|
||||
this.peers[peer.id] = new RTCPeer(this._server, peer.id);
|
||||
} else {
|
||||
this.peers[peer.id] = new WSPeer(this._server, peer.id);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
sendTo(peerId, message) {
|
||||
this.peers[peerId].send(message);
|
||||
}
|
||||
|
||||
_onFilesSelected(message) {
|
||||
this.peers[message.to].sendFiles(message.files);
|
||||
}
|
||||
|
||||
_onSendText(message) {
|
||||
this.peers[message.to].sendText(message.text);
|
||||
}
|
||||
|
||||
_onPeerLeft(peerId) {
|
||||
const peer = this.peers[peerId];
|
||||
delete this.peers[peerId];
|
||||
if (!peer || !peer._peer) return;
|
||||
peer._peer.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class WSPeer {
|
||||
_send(message) {
|
||||
message.to = this._peerId;
|
||||
this._server.send(message);
|
||||
}
|
||||
}
|
||||
|
||||
class FileChunker {
|
||||
|
||||
constructor(file, onChunk, onPartitionEnd) {
|
||||
this._chunkSize = 64000;
|
||||
this._maxPartitionSize = 1e6;
|
||||
this._offset = 0;
|
||||
this._partitionSize = 0;
|
||||
this._file = file;
|
||||
this._onChunk = onChunk;
|
||||
this._onPartitionEnd = onPartitionEnd;
|
||||
this._reader = new FileReader();
|
||||
this._reader.addEventListener('load', e => this._onChunkRead(e.target.result));
|
||||
}
|
||||
|
||||
nextPartition() {
|
||||
this._partitionSize = 0;
|
||||
this._readChunk();
|
||||
}
|
||||
|
||||
_readChunk() {
|
||||
const chunk = this._file.slice(this._offset, this._offset + this._chunkSize);
|
||||
this._reader.readAsArrayBuffer(chunk);
|
||||
}
|
||||
|
||||
_onChunkRead(chunk) {
|
||||
this._offset += chunk.byteLength;
|
||||
this._partitionSize += chunk.byteLength;
|
||||
this._onChunk(chunk);
|
||||
if (this._isPartitionEnd() || this.isFileEnd()) {
|
||||
this._onPartitionEnd(this._partitionSize);
|
||||
return;
|
||||
}
|
||||
this._readChunk();
|
||||
}
|
||||
|
||||
repeatPartition() {
|
||||
this._offset -= this._partitionSize;
|
||||
this._nextPartition();
|
||||
}
|
||||
|
||||
_isPartitionEnd() {
|
||||
return this._partitionSize >= this._maxPartitionSize;
|
||||
}
|
||||
|
||||
isFileEnd() {
|
||||
return this._offset > this._file.size;
|
||||
}
|
||||
|
||||
get progress() {
|
||||
return this._offset / this._file.size;
|
||||
}
|
||||
}
|
||||
|
||||
class FileDigester {
|
||||
constructor(meta, callback) {
|
||||
this._buffer = [];
|
||||
this._bytesReceived = 0;
|
||||
this._size = meta.size;
|
||||
this._mime = meta.mime || 'application/octet-stream';
|
||||
this._name = meta.name;
|
||||
this._callback = callback;
|
||||
}
|
||||
|
||||
unchunk(chunk) {
|
||||
this._buffer.push(chunk);
|
||||
this._bytesReceived += chunk.byteLength || chunk.size;
|
||||
const totalChunks = this._buffer.length;
|
||||
this.progress = this._bytesReceived / this._size;
|
||||
if (this._bytesReceived < this._size) return;
|
||||
|
||||
let received = new Blob(this._buffer, { type: this._mime }); // pass a useful mime type here
|
||||
let url = URL.createObjectURL(received);
|
||||
this._callback({
|
||||
name: this._name,
|
||||
mime: this._mime,
|
||||
size: this._size,
|
||||
url: url
|
||||
});
|
||||
this._callback = null;
|
||||
}
|
||||
}
|
||||
|
||||
class Events {
|
||||
static fire(type, detail) {
|
||||
window.dispatchEvent(new CustomEvent(type, { detail: detail }));
|
||||
}
|
||||
|
||||
static on(type, callback) {
|
||||
return window.addEventListener(type, callback, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
window.isRtcSupported = !!(window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection);
|
||||
|
||||
RTCPeer.config = {
|
||||
'iceServers': [{
|
||||
urls: 'stun:stun.stunprotocol.org:3478'
|
||||
}, {
|
||||
urls: 'stun:stun.l.google.com:19302'
|
||||
}, {
|
||||
urls: 'turn:turn.bistri.com:80',
|
||||
credential: 'homeo',
|
||||
username: 'homeo'
|
||||
}, {
|
||||
urls: 'turn:turn.anyfirewall.com:443?transport=tcp',
|
||||
credential: 'webrtc',
|
||||
username: 'webrtc'
|
||||
}]
|
||||
}
|
521
client/scripts/ui.js
Normal file
521
client/scripts/ui.js
Normal file
|
@ -0,0 +1,521 @@
|
|||
const $ = query => document.getElementById(query);
|
||||
const $$ = query => document.body.querySelector(query);
|
||||
const isURL = text => /^((https?:\/\/|www)[^\s]+)/g.test(text.toLowerCase());
|
||||
const isDownloadSupported = (typeof document.createElement('a').download !== 'undefined');
|
||||
const isProductionEnvironment = !window.location.host.startsWith('localhost');
|
||||
|
||||
class PeersUI {
|
||||
|
||||
constructor() {
|
||||
Events.on('peer-joined', e => this._onPeerJoined(e.detail));
|
||||
Events.on('peer-left', e => this._onPeerLeft(e.detail));
|
||||
Events.on('peers', e => this._onPeers(e.detail));
|
||||
Events.on('file-progress', e => this._onFileProgress(e.detail));
|
||||
}
|
||||
|
||||
_onPeerJoined(peer) {
|
||||
if (document.getElementById(peer.id)) return;
|
||||
const peerUI = new PeerUI(peer);
|
||||
$$('x-peers').appendChild(peerUI.$el);
|
||||
}
|
||||
|
||||
_onPeers(peers) {
|
||||
this._clearPeers();
|
||||
peers.forEach(peer => this._onPeerJoined(peer));
|
||||
}
|
||||
|
||||
_onPeerLeft(peerId) {
|
||||
const peer = $(peerId);
|
||||
if (!peer) return;
|
||||
peer.remove();
|
||||
}
|
||||
|
||||
_onFileProgress(progress) {
|
||||
const peerId = progress.sender || progress.recipient;
|
||||
const peer = $(peerId);
|
||||
if (!peer) return;
|
||||
peer.ui.setProgress(progress.progress);
|
||||
}
|
||||
|
||||
_clearPeers() {
|
||||
const $peers = $$('x-peers').innerHTML = '';
|
||||
}
|
||||
}
|
||||
|
||||
class PeerUI {
|
||||
|
||||
html() {
|
||||
return `
|
||||
<label class="column center">
|
||||
<input type="file" multiple>
|
||||
<x-icon shadow="1">
|
||||
<svg class="icon"><use xlink:href="#"/></svg>
|
||||
</x-icon>
|
||||
<div class="progress">
|
||||
<div class="circle"></div>
|
||||
<div class="circle right"></div>
|
||||
</div>
|
||||
<div class="name font-subheading"></div>
|
||||
<div class="status font-body2"></div>
|
||||
</label>`
|
||||
}
|
||||
|
||||
constructor(peer) {
|
||||
this._peer = peer;
|
||||
this._initDom();
|
||||
this._bindListeners(this.$el);
|
||||
}
|
||||
|
||||
_initDom() {
|
||||
const el = document.createElement('x-peer');
|
||||
el.id = this._peer.id;
|
||||
el.innerHTML = this.html();
|
||||
el.ui = this;
|
||||
el.querySelector('svg use').setAttribute('xlink:href', this._icon());
|
||||
el.querySelector('.name').textContent = this._name();
|
||||
this.$el = el;
|
||||
this.$progress = el.querySelector('.progress');
|
||||
}
|
||||
|
||||
_bindListeners(el) {
|
||||
el.querySelector('input').addEventListener('change', e => this._onFilesSelected(e));
|
||||
el.addEventListener('drop', e => this._onDrop(e));
|
||||
el.addEventListener('dragend', e => this._onDragEnd(e));
|
||||
el.addEventListener('dragleave', e => this._onDragEnd(e));
|
||||
el.addEventListener('dragover', e => this._onDragOver(e));
|
||||
el.addEventListener('contextmenu', e => this._onRightClick(e));
|
||||
el.addEventListener('touchstart', e => this._onTouchStart(e));
|
||||
el.addEventListener('touchend', e => this._onTouchEnd(e));
|
||||
// prevent browser's default file drop behavior
|
||||
Events.on('dragover', e => e.preventDefault());
|
||||
Events.on('drop', e => e.preventDefault());
|
||||
}
|
||||
|
||||
_name() {
|
||||
if (this._peer.name.model) {
|
||||
return this._peer.name.os + ' ' + this._peer.name.model;
|
||||
}
|
||||
this._peer.name.os = this._peer.name.os.replace('Mac OS', 'Mac');
|
||||
return this._peer.name.os + ' ' + this._peer.name.browser;
|
||||
}
|
||||
|
||||
_icon() {
|
||||
const device = this._peer.name.device || this._peer.name;
|
||||
if (device.type === 'mobile') {
|
||||
return '#phone-iphone';
|
||||
}
|
||||
if (device.type === 'tablet') {
|
||||
return '#tablet-mac';
|
||||
}
|
||||
return '#desktop-mac';
|
||||
}
|
||||
|
||||
_onFilesSelected(e) {
|
||||
const $input = e.target;
|
||||
const files = $input.files;
|
||||
Events.fire('files-selected', {
|
||||
files: files,
|
||||
to: this._peer.id
|
||||
});
|
||||
$input.value = null; // reset input
|
||||
this.setProgress(0.01);
|
||||
}
|
||||
|
||||
setProgress(progress) {
|
||||
if (progress > 0) {
|
||||
this.$el.setAttribute('transfer', '1');
|
||||
}
|
||||
if (progress > 0.5) {
|
||||
this.$progress.classList.add('over50');
|
||||
} else {
|
||||
this.$progress.classList.remove('over50');
|
||||
}
|
||||
const degrees = `rotate(${360 * progress}deg)`;
|
||||
this.$progress.style.setProperty('--progress', degrees);
|
||||
if (progress >= 1) {
|
||||
this.setProgress(0);
|
||||
this.$el.removeAttribute('transfer');
|
||||
}
|
||||
}
|
||||
|
||||
_onDrop(e) {
|
||||
e.preventDefault();
|
||||
const files = e.dataTransfer.files;
|
||||
Events.fire('files-selected', {
|
||||
files: files,
|
||||
to: this._peer.id
|
||||
});
|
||||
this._onDragEnd();
|
||||
}
|
||||
|
||||
_onDragOver() {
|
||||
this.$el.setAttribute('drop', 1);
|
||||
}
|
||||
|
||||
_onDragEnd() {
|
||||
this.$el.removeAttribute('drop');
|
||||
}
|
||||
|
||||
_onRightClick(e) {
|
||||
e.preventDefault();
|
||||
Events.fire('text-recipient', this._peer.id);
|
||||
}
|
||||
|
||||
_onTouchStart(e) {
|
||||
this._touchStart = Date.now();
|
||||
this._touchTimer = setTimeout(_ => this._onTouchEnd(), 610);
|
||||
}
|
||||
|
||||
_onTouchEnd(e) {
|
||||
if (Date.now() - this._touchStart < 500) {
|
||||
clearTimeout(this._touchTimer);
|
||||
} else { // this was a long tap
|
||||
if (e) e.preventDefault();
|
||||
Events.fire('text-recipient', this._peer.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class Dialog {
|
||||
constructor(id) {
|
||||
this.$el = $(id);
|
||||
this.$el.querySelectorAll('[close]').forEach(el => el.addEventListener('click', e => this.hide()))
|
||||
this.$autoFocus = this.$el.querySelector('[autofocus]');
|
||||
}
|
||||
|
||||
show() {
|
||||
this.$el.setAttribute('show', 1);
|
||||
if (this.$autoFocus) this.$autoFocus.focus();
|
||||
}
|
||||
|
||||
hide() {
|
||||
this.$el.removeAttribute('show');
|
||||
document.activeElement.blur();
|
||||
window.blur();
|
||||
}
|
||||
}
|
||||
|
||||
class ReceiveDialog extends Dialog {
|
||||
|
||||
constructor() {
|
||||
super('receiveDialog');
|
||||
Events.on('file-received', e => {
|
||||
this._nextFile(e.detail);
|
||||
window.blop.play();
|
||||
});
|
||||
this._filesQueue = [];
|
||||
}
|
||||
|
||||
_nextFile(nextFile) {
|
||||
if (nextFile) this._filesQueue.push(nextFile);
|
||||
if (this._busy) return;
|
||||
this._busy = true;
|
||||
const file = this._filesQueue.shift();
|
||||
this._displayFile(file);
|
||||
}
|
||||
|
||||
_dequeueFile() {
|
||||
if (!this._filesQueue.length) { // nothing to do
|
||||
this._busy = false;
|
||||
return;
|
||||
}
|
||||
// dequeue next file
|
||||
setTimeout(_ => {
|
||||
this._busy = false;
|
||||
this._nextFile();
|
||||
}, 300);
|
||||
}
|
||||
|
||||
_displayFile(file) {
|
||||
const $a = this.$el.querySelector('#download');
|
||||
$a.href = file.url;
|
||||
$a.download = file.name;
|
||||
|
||||
this.$el.querySelector('#fileName').textContent = file.name;
|
||||
this.$el.querySelector('#fileSize').textContent = this._formatFileSize(file.size);
|
||||
this.show();
|
||||
|
||||
if (!isDownloadSupported) return;
|
||||
// $a.target = "_blank"; // fallback
|
||||
$a.target = "_system"; // fallback
|
||||
$a.href = 'external:' + $a.href;
|
||||
}
|
||||
|
||||
_formatFileSize(bytes) {
|
||||
if (bytes >= 1e9) {
|
||||
return (Math.round(bytes / 1e8) / 10) + ' GB';
|
||||
} else if (bytes >= 1e6) {
|
||||
return (Math.round(bytes / 1e5) / 10) + ' MB';
|
||||
} else if (bytes > 1000) {
|
||||
return Math.round(bytes / 1000) + ' KB';
|
||||
} else {
|
||||
return bytes + ' Bytes';
|
||||
}
|
||||
}
|
||||
|
||||
hide() {
|
||||
super.hide();
|
||||
this._dequeueFile();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class SendTextDialog extends Dialog {
|
||||
constructor() {
|
||||
super('sendTextDialog');
|
||||
Events.on('text-recipient', e => this._onRecipient(e.detail))
|
||||
this.$text = this.$el.querySelector('#textInput');
|
||||
const button = this.$el.querySelector('form');
|
||||
button.addEventListener('submit', e => this._send(e));
|
||||
}
|
||||
|
||||
_onRecipient(recipient) {
|
||||
this._recipient = recipient;
|
||||
this.show();
|
||||
this.$text.setSelectionRange(0, this.$text.value.length)
|
||||
}
|
||||
|
||||
_send(e) {
|
||||
e.preventDefault();
|
||||
Events.fire('send-text', {
|
||||
to: this._recipient,
|
||||
text: this.$text.value
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class ReceiveTextDialog extends Dialog {
|
||||
constructor() {
|
||||
super('receiveTextDialog');
|
||||
Events.on('text-received', e => this._onText(e.detail))
|
||||
this.$text = this.$el.querySelector('#text');
|
||||
const $copy = this.$el.querySelector('#copy');
|
||||
copy.addEventListener('click', _ => this._onCopy());
|
||||
}
|
||||
|
||||
_onText(e) {
|
||||
this.$text.innerHTML = '';
|
||||
const text = e.text;
|
||||
if (isURL(text)) {
|
||||
const $a = document.createElement('a');
|
||||
$a.href = text;
|
||||
$a.target = '_blank';
|
||||
$a.textContent = text;
|
||||
this.$text.appendChild($a);
|
||||
} else {
|
||||
this.$text.textContent = text;
|
||||
}
|
||||
this.show();
|
||||
window.blop.play();
|
||||
}
|
||||
|
||||
_onCopy() {
|
||||
if (!document.copy(this.$text.textContent)) return;
|
||||
Events.fire('notify-user', 'Copied to clipboard');
|
||||
}
|
||||
}
|
||||
|
||||
class Toast extends Dialog {
|
||||
constructor() {
|
||||
super('toast');
|
||||
Events.on('notify-user', e => this._onNotfiy(e.detail));
|
||||
}
|
||||
|
||||
_onNotfiy(message) {
|
||||
this.$el.textContent = message;
|
||||
this.show();
|
||||
setTimeout(_ => this.hide(), 3000);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class Notifications {
|
||||
|
||||
constructor() {
|
||||
// Check if the browser supports notifications
|
||||
if (!('Notification' in window)) return;
|
||||
// Check whether notification permissions have already been granted
|
||||
|
||||
if (Notification.permission !== 'granted') {
|
||||
this.$button = $('notification');
|
||||
this.$button.removeAttribute('hidden');
|
||||
this.$button.addEventListener('click', e => this._requestPermission());
|
||||
}
|
||||
Events.on('text-received', e => this._messageNotification(e.detail.text));
|
||||
Events.on('file-received', e => this._downloadNotification(e.detail.name));
|
||||
}
|
||||
|
||||
_requestPermission() {
|
||||
Notification.requestPermission(permission => {
|
||||
if (permission !== 'granted') {
|
||||
Events.fire('notify-user', Notifications.PERMISSION_ERROR || 'Error');
|
||||
return;
|
||||
}
|
||||
this._notify('Even more snappy sharing!');
|
||||
this.$button.setAttribute('hidden', 1);
|
||||
});
|
||||
}
|
||||
|
||||
_notify(message, body) {
|
||||
var img = '/images/logo_transparent_128x128.png';
|
||||
return new Notification(message, {
|
||||
body: body,
|
||||
icon: img,
|
||||
vibrate: [200, 100, 200, 100, 200, 100, 400],
|
||||
});
|
||||
}
|
||||
|
||||
_messageNotification(message) {
|
||||
if (isURL(message)) {
|
||||
const notification = this._notify(message, 'Click to open link');
|
||||
notification.onclick = e => window.open(message, '_blank', null, true);
|
||||
} else {
|
||||
const notification = this._notify(message, 'Click to copy text');
|
||||
notification.onclick = e => document.copy(message);
|
||||
}
|
||||
}
|
||||
|
||||
_downloadNotification(message) {
|
||||
const notification = this._notify(message, 'Click to download');
|
||||
if (window.isDownloadSupported) return;
|
||||
notification.onclick = e => {
|
||||
document.querySelector('x-dialog [download]').click();
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class Snapdrop {
|
||||
constructor() {
|
||||
const server = new ServerConnection();
|
||||
const peers = new PeersManager(server);
|
||||
const peersUI = new PeersUI();
|
||||
Events.on('load', e => {
|
||||
const receiveDialog = new ReceiveDialog();
|
||||
const sendTextDialog = new SendTextDialog();
|
||||
const receiveTextDialog = new ReceiveTextDialog();
|
||||
const toast = new Toast();
|
||||
const notifications = new Notifications();
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const snapdrop = new Snapdrop();
|
||||
|
||||
document.copy = text => {
|
||||
// A <span> contains the text to copy
|
||||
const span = document.createElement('span');
|
||||
span.textContent = text;
|
||||
span.style.whiteSpace = 'pre'; // Preserve consecutive spaces and newlines
|
||||
|
||||
// Paint the span outside the viewport
|
||||
span.style.position = 'absolute';
|
||||
span.style.left = '-9999px';
|
||||
span.style.top = '-9999px';
|
||||
|
||||
const win = window;
|
||||
const selection = win.getSelection();
|
||||
win.document.body.appendChild(span);
|
||||
|
||||
const range = win.document.createRange();
|
||||
selection.removeAllRanges();
|
||||
range.selectNode(span);
|
||||
selection.addRange(range);
|
||||
|
||||
let success = false;
|
||||
try {
|
||||
success = win.document.execCommand('copy');
|
||||
} catch (err) {}
|
||||
|
||||
selection.removeAllRanges();
|
||||
span.remove();
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
if ('serviceWorker' in navigator && isProductionEnvironment) {
|
||||
navigator.serviceWorker
|
||||
.register('/service-worker.js')
|
||||
.then(e => console.log("Service Worker Registered"));
|
||||
}
|
||||
|
||||
// Background Animation
|
||||
Events.on('load', () => {
|
||||
var requestAnimFrame = (function() {
|
||||
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
|
||||
function(callback) {
|
||||
window.setTimeout(callback, 1000 / 60);
|
||||
};
|
||||
})();
|
||||
var c = document.createElement('canvas');
|
||||
document.body.appendChild(c);
|
||||
var style = c.style;
|
||||
style.width = '100%';
|
||||
style.position = 'absolute';
|
||||
style.zIndex = -1;
|
||||
var ctx = c.getContext('2d');
|
||||
var x0, y0, w, h, dw;
|
||||
|
||||
function init() {
|
||||
w = window.innerWidth;
|
||||
h = window.innerHeight;
|
||||
c.width = w;
|
||||
c.height = h;
|
||||
var offset = h > 380 ? 100 : 65;
|
||||
x0 = w / 2;
|
||||
y0 = h - offset;
|
||||
dw = Math.max(w, h, 1000) / 13;
|
||||
drawCircles();
|
||||
}
|
||||
window.onresize = init;
|
||||
|
||||
function drawCicrle(radius) {
|
||||
ctx.beginPath();
|
||||
var color = Math.round(255 * (1 - radius / Math.max(w, h)));
|
||||
ctx.strokeStyle = 'rgba(' + color + ',' + color + ',' + color + ',0.1)';
|
||||
ctx.arc(x0, y0, radius, 0, 2 * Math.PI);
|
||||
ctx.stroke();
|
||||
ctx.lineWidth = 2;
|
||||
}
|
||||
|
||||
var step = 0;
|
||||
|
||||
function drawCircles() {
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
for (var i = 0; i < 8; i++) {
|
||||
drawCicrle(dw * i + step % dw);
|
||||
}
|
||||
step += 1;
|
||||
}
|
||||
|
||||
var loading = true;
|
||||
|
||||
function animate() {
|
||||
if (loading || step % dw < dw - 5) {
|
||||
requestAnimFrame(function() {
|
||||
drawCircles();
|
||||
animate();
|
||||
});
|
||||
}
|
||||
}
|
||||
window.animateBackground = function(l) {
|
||||
loading = l;
|
||||
animate();
|
||||
};
|
||||
init();
|
||||
animate();
|
||||
setTimeout(e => window.animateBackground(false), 3000);
|
||||
});
|
||||
|
||||
Notifications.PERMISSION_ERROR = `
|
||||
Notifications permission has been blocked
|
||||
as the user has dismissed the permission prompt several times.
|
||||
This can be reset in Page Info
|
||||
which can be accessed by clicking the lock icon next to the URL.`;
|
||||
|
||||
document.body.onclick = e => { // safari hack to fix audio
|
||||
document.body.onclick = null;
|
||||
if (!(/.*Version.*Safari.*/.test(navigator.userAgent))) return;
|
||||
blop.play();
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue