Compare commits

..

2 Commits

4 changed files with 238 additions and 220 deletions

View File

@@ -93,6 +93,7 @@
"file-other-description-file": "and 1 other file",
"file-other-description-image-plural": "and {{count}} other images",
"file-other-description-file-plural": "and {{count}} other files",
"text-message-description": "A large text message",
"title-image": "Image",
"title-file": "File",
"title-image-plural": "Images",
@@ -171,6 +172,7 @@
"file-received-plural": "{{count}} Files Received",
"file-transfer-requested": "File Transfer Requested",
"image-transfer-requested": "Image Transfer Requested",
"message-transfer-requested": "Message Transfer Requested",
"message-received": "Message Received",
"message-received-plural": "{{count}} Messages Received"
},

View File

@@ -137,7 +137,6 @@ class PairDrop {
let stylesheet = document.createElement('link');
stylesheet.rel = 'preload';
stylesheet.as = 'style';
stylesheet.defer = true;
stylesheet.href = url;
stylesheet.onload = _ => {
stylesheet.onload = null;

View File

@@ -63,8 +63,8 @@ class ServerConnection {
}
_setWsConfig(wsConfig) {
window._wsConfig = wsConfig;
Events.fire('ws-config-loaded');
this._wsConfig = wsConfig;
Events.fire('ws-config', wsConfig);
}
_connect() {
@@ -137,7 +137,7 @@ class ServerConnection {
_onMessage(message) {
const messageJSON = JSON.parse(message);
if (messageJSON.type !== 'ping' && messageJSON.type !== 'ws-relay') {
Logger.debug('WS Receive:', messageJSON);
Logger.debug('WS receive:', messageJSON);
}
switch (messageJSON.type) {
case 'ws-config':
@@ -193,15 +193,15 @@ class ServerConnection {
break;
case 'ws-relay':
// ws-fallback
if (window._wsConfig.wsFallback) {
if (this._wsConfig.wsFallback) {
Events.fire('ws-relay', {peerId: messageJSON.sender.id, message: message});
}
else {
Logger.warn("WS Receive: message type is for websocket fallback only but websocket fallback is not activated on this instance.")
Logger.warn("WS receive: message type is for websocket fallback only but websocket fallback is not activated on this instance.")
}
break;
default:
Logger.error('WS Receive: unknown message type', messageJSON);
Logger.error('WS receive: unknown message type', messageJSON);
}
}
@@ -331,6 +331,8 @@ class Peer {
this._isCaller = isCaller;
this._peerId = peerId;
this._maxMessageSize = 65536; // 64 KB
this._roomIds = {};
this._updateRoomIds(roomType, roomId);
@@ -352,14 +354,15 @@ class Peer {
// tidy up sender
this._filesRequested = null;
this._requestSent = null;
this._chunker = null;
// tidy up receiver
this._pendingRequest = null;
this._acceptedRequest = null;
this._requestPending = null;
this._requestAccepted = null;
this._totalBytesReceived = 0;
this._digester = null;
this._filesReceived = [];
this._filesReceived = null;
// disable NoSleep if idle
Events.fire('evaluate-no-sleep');
@@ -497,7 +500,7 @@ class Peer {
await this._onState(message.state);
break;
case 'transfer-request':
await this._onTransferRequest(message);
await this._onTransferRequest(message.request);
break;
case 'transfer-request-response':
this._onTransferRequestResponse(message);
@@ -624,7 +627,7 @@ class Peer {
}
// File Sender Only
async _sendFileTransferRequest(files) {
async _sendFileTransferRequest(files, fileIsMessage = false) {
this._state = Peer.STATE_PREPARE;
Events.fire('set-progress', {peerId: this._peerId, progress: 0, status: 'prepare'});
@@ -642,6 +645,13 @@ class Peer {
if (files[i].type.split('/')[0] !== 'image') imagesOnly = false;
}
// request type 'images', 'files' or 'message
const filesType = fileIsMessage
? 'message'
: imagesOnly
? 'images'
: 'files';
let dataUrl = "";
if (files[0].type.split('/')[0] === 'image') {
try {
@@ -654,13 +664,18 @@ class Peer {
this._state = Peer.STATE_TRANSFER_REQUEST_SENT;
Events.fire('set-progress', {peerId: this._peerId, progress: 0, status: 'wait'});
this._filesRequested = files;
this._sendMessage({type: 'transfer-request',
const request = {
header: header,
totalSize: totalSize,
imagesOnly: imagesOnly,
filesType: filesType,
thumbnailDataUrl: dataUrl
};
this._filesRequested = files;
this._requestSent = request;
this._sendMessage({type: 'transfer-request',
request: request
});
}
@@ -675,7 +690,7 @@ class Peer {
if (message.reason === 'ram-exceed-ios') {
Events.fire('notify-user', Localization.getTranslation('notifications.ram-exceed-ios'));
}
Events.fire('set-progress', {peerId: this._peerId, progress: 0, status: null});
Events.fire('set-progress', {peerId: this._peerId, progress: 0, status: 'idle'});
this._reset();
return;
}
@@ -748,7 +763,7 @@ class Peer {
if (!message.success) {
Logger.warn('File could not be sent');
Events.fire('set-progress', {peerId: this._peerId, progress: 0, status: null});
Events.fire('set-progress', {peerId: this._peerId, progress: 0, status: 'idle'});
this._reset();
return;
}
@@ -760,6 +775,9 @@ class Peer {
return;
}
// If files sent was message -> abort and wait for text-received message
if (this._requestSent.filesType === 'message') return;
// No more files in queue. Transfer is complete
this._reset();
Events.fire('set-progress', {peerId: this._peerId, progress: 0, status: 'transfer-complete'});
@@ -770,7 +788,7 @@ class Peer {
// File Receiver Only
async _onTransferRequest(request) {
// Only accept one request at a time per peer
if (this._pendingRequest) {
if (this._requestPending) {
this._sendTransferRequestResponse(false);
return;
}
@@ -790,7 +808,7 @@ class Peer {
}
this._state = Peer.STATE_TRANSFER_REQUEST_RECEIVED;
this._pendingRequest = request;
this._requestPending = request;
// Automatically accept request if auto-accept is set to true via the Edit Paired Devices Dialog
if (this._autoAccept) {
@@ -827,7 +845,7 @@ class Peer {
if (accepted) {
this._state = Peer.STATE_RECEIVE_PROCEEDING;
this._busy = true;
this._acceptedRequest = this._pendingRequest;
this._requestAccepted = this._requestPending;
this._lastProgress = 0;
this._totalBytesReceived = 0;
this._filesReceived = [];
@@ -892,7 +910,7 @@ class Peer {
// While transferring -> round progress to 4th digit. After transferring, set it to 1.
let progress = this._digester
? Math.floor(1e4 * (this._totalBytesReceived + this._digester._bytesReceived) / this._acceptedRequest.totalSize) / 1e4
? Math.floor(1e4 * (this._totalBytesReceived + this._digester._bytesReceived) / this._requestAccepted.totalSize) / 1e4
: 1;
Events.fire('set-progress', {peerId: this._peerId, progress: progress, status: 'receive'});
@@ -913,26 +931,34 @@ class Peer {
this._singleFileReceiveComplete(file);
// If less files received than header accepted -> wait for next file
if (this._filesReceived.length < this._acceptedRequest.header.length) return;
if (this._filesReceived.length < this._requestAccepted.header.length) return;
// We are done receiving
Events.fire('set-progress', {peerId: this._peerId, progress: 1, status: 'receive'});
// If filesType is 'message' evaluate files as text
if (this._requestAccepted.filesType === 'message') {
this._textReceivedAsFile();
return;
}
// fileType is 'images' or 'files'
this._allFilesReceiveComplete();
}
_fitsAcceptedHeader(header) {
if (!this._acceptedRequest) {
if (!this._requestAccepted) {
return false;
}
const positionFile = this._filesReceived.length;
if (positionFile > this._acceptedRequest.header.length - 1) {
if (positionFile > this._requestAccepted.header.length - 1) {
return false;
}
// Check if file header fits
const acceptedHeader = this._acceptedRequest.header[positionFile];
const acceptedHeader = this._requestAccepted.header[positionFile];
const sameSize = header.size === acceptedHeader.size;
const sameType = header.mime === acceptedHeader.mime;
@@ -955,8 +981,11 @@ class Peer {
// Log speed from request to receive
Logger.log(`File received.\n\nSize: ${size} MB\tDuration: ${duration} s\tSpeed: ${speed} MB/s`);
// include for compatibility with 'Snapdrop & PairDrop for Android' app
Events.fire('file-received', file);
// Prevent App from downloading message txt file
if (this._requestAccepted.filesType !== 'message') {
// include for compatibility with 'Snapdrop & PairDrop for Android' app
Events.fire('file-received', file);
}
this._filesReceived.push(file);
@@ -967,55 +996,102 @@ class Peer {
Events.fire('files-received', {
peerId: this._peerId,
files: this._filesReceived,
imagesOnly: this._acceptedRequest.imagesOnly,
totalSize: this._acceptedRequest.totalSize
filesType: this._requestAccepted.filesType,
totalSize: this._requestAccepted.totalSize
});
this._reset();
}
// Message Sender Only
_sendText(text) {
_base64encode(text) {
return btoa(unescape(encodeURIComponent(text)));
}
async _sendText(text) {
this._state = Peer.STATE_TEXT_SENT;
const unescaped = btoa(unescape(encodeURIComponent(text)));
this._sendMessage({ type: 'text', text: unescaped });
// Send text base64 encoded
const base64encoded = this._base64encode(text);
const message = {type: 'text', text: base64encoded};
// If text too big for connection -> send as file instead
if (JSON.stringify(message).length > this._maxMessageSize) {
await this._sendTextAsFile(text);
return;
}
this._sendMessage(message);
}
async _sendTextAsFile(text) {
// send text in chunks by using the file transfer api
const file = new File([text], "pairdrop-message.txt", { type: 'text/plain' });
await this._sendFileTransferRequest([file], true);
}
_onTextReceiveComplete() {
if (this._state !== Peer.STATE_TEXT_SENT) {
if (this._state !== Peer.STATE_TEXT_SENT && this._state !== Peer.STATE_TRANSFER_PROCEEDING) {
this._sendState();
return;
}
this._reset();
Events.fire('set-progress', { peerId: this._peerId, progress: 0, status: 'idle' });
Events.fire('notify-user', Localization.getTranslation("notifications.message-transfer-completed"));
}
// Message Receiver Only
_onText(message) {
if (!message.text) return;
_base64decodeMessage(base64encoded){
let decoded = "";
try {
const escaped = decodeURIComponent(escape(atob(message.text)));
Events.fire('text-received', { text: escaped, peerId: this._peerId });
this._sendMessage({ type: 'text-receive-complete' });
decoded = decodeURIComponent(escape(atob(base64encoded)));
}
catch (e) {
Logger.error(e);
}
return decoded;
}
_onText(message) {
if (this._state !== Peer.STATE_IDLE) {
this._abortTransfer();
return;
}
if (!message.text) return;
const text = this._base64decodeMessage(message.text);
Events.fire('text-received', { text: text, peerId: this._peerId });
this._sendMessage({ type: 'text-receive-complete' });
}
_textReceivedAsFile() {
// Use FileReader to unpack text from file
const reader = new FileReader();
reader.addEventListener("load", _ => {
Events.fire('text-received', { text: reader.result, peerId: this._peerId });
});
reader.readAsText(this._filesReceived[0]);
Events.fire('set-progress', { peerId: this._peerId, progress: 1, status: 'idle' });
this._sendMessage({ type: 'text-receive-complete' });
this._reset();
}
}
class RTCPeer extends Peer {
constructor(serverConnection, isCaller, peerId, roomType, roomId) {
constructor(serverConnection, isCaller, peerId, roomType, roomId, rtcConfig) {
super(serverConnection, isCaller, peerId, roomType, roomId);
this.rtcSupported = true;
this.rtcConfig = window._wsConfig.rtcConfig;
this.rtcConfig = rtcConfig;
this.pendingInboundServerSignalMessages = [];
this.pendingOutboundMessages = [];
this.errorCount = 0;
this._connect();
}
@@ -1117,13 +1193,14 @@ class RTCPeer extends Peer {
Logger.debug('RTC: Connection state changed:', this._conn.connectionState);
switch (this._conn.connectionState) {
case 'connected':
this.errorCount = 0;
this._setMaxMessageSize();
break;
case 'disconnected':
this._refresh();
break;
case 'failed':
Logger.warn('RTC connection failed');
// Todo: if error is "TURN server needed" -> fallback to WS if activated
this._refresh();
}
}
@@ -1132,28 +1209,8 @@ class RTCPeer extends Peer {
this._handleLocalCandidate(event.candidate);
}
_onIceCandidateError(event) {
this.errorCount++
// Todo: remove this
// Todo: test which errorCode is thrown on "TURN server needed" and what other codes are relevant
console.debug(this.errorCount, event.errorCode, event)
Logger.error(event);
if (event.errorCode === 701) {
this._retryOrFallback();
}
}
_retryOrFallback() {
// If fallback is activated, fallback to WS Peer if third retry fails
if (this.errorCount > 3 && window._wsConfig.wsFallback) {
Events.fire('fallback-to-ws', { peerId: this._peerId });
this._sendFallbackToWs();
}
else {
this._refresh();
}
_onIceCandidateError(error) {
Logger.error(error);
}
_openMessageChannel() {
@@ -1188,7 +1245,7 @@ class RTCPeer extends Peer {
// wait until all channels are open
if (!this._stable()) return;
Events.fire('peer-connected', { peerId: this._peerId, connectionHash: this.getConnectionHash(), rtcSupported: this.rtcSupported });
Events.fire('peer-connected', {peerId: this._peerId, connectionHash: this.getConnectionHash()});
super._onPeerConnected();
this._sendPendingOutboundMessaged();
@@ -1349,26 +1406,18 @@ class RTCPeer extends Peer {
_sendSignal(message) {
message.type = 'signal';
this._sendMessageViaServer(message);
}
_sendFallbackToWs() {
const message = {
type: 'ws-relay',
message: {
type: 'fallback-to-ws'
}
};
this._sendMessageViaServer(message);
}
_sendMessageViaServer(message) {
message.to = this._peerId;
message.roomType = this._getRoomTypes()[0];
message.roomId = this._roomIds[this._getRoomTypes()[0]];
this._server.send(message);
}
_setMaxMessageSize() {
this._maxMessageSize = this._conn && this._conn.sctp
? this._conn.sctp.maxMessageSize
: 262144; // 256 kB
}
async _sendFile(file) {
this._chunker = new FileChunkerRTC(
file,
@@ -1382,7 +1431,7 @@ class RTCPeer extends Peer {
}
async _onMessage(message) {
Logger.debug('RTCPeer Receive:', JSON.parse(message));
Logger.debug('RTC Receive:', JSON.parse(message));
try {
message = JSON.parse(message);
} catch (e) {
@@ -1427,6 +1476,8 @@ class WSPeer extends Peer {
this.rtcSupported = false;
this.signalSuccessful = false;
this._maxMessageSize = 65536; // 64 KB
if (!this._isCaller) return; // we will listen for a caller
this._sendSignal();
@@ -1481,7 +1532,7 @@ class WSPeer extends Peer {
}
async _onMessage(message) {
Logger.debug('WSPeer Receive:', message);
Logger.debug('WS Receive:', message);
await super._onMessage(message);
}
@@ -1527,44 +1578,39 @@ class PeersManager {
constructor(serverConnection) {
this.peers = {};
this._server = serverConnection;
// Initiation
Events.on('signal', e => this._onSignal(e.detail));
Events.on('peers', e => this._onPeers(e.detail));
// File / Message transfer
Events.on('files-selected', e => this._onFilesSelected(e.detail));
Events.on('respond-to-files-transfer-request', e => this._onRespondToFileTransferRequest(e.detail))
Events.on('send-text', e => this._onSendText(e.detail));
// Peer
Events.on('peer-left', e => this._onPeerLeft(e.detail));
Events.on('peer-joined', e => this._onPeerJoined(e.detail));
Events.on('peer-connected', e => this._onPeerConnected(e.detail.peerId));
Events.on('peer-disconnected', e => this._onPeerDisconnected(e.detail));
// WS-Peer specific
Events.on('ws-disconnected', _ => this._onWsDisconnected());
Events.on('ws-relay', e => this._onWsRelay(e.detail.peerId, e.detail.message));
Events.on('fallback-to-ws', e => this._onFallbackToWs(e.detail.peerId));
// Rooms and secrets: this device closes connection
// this device closes connection
Events.on('room-secrets-deleted', e => this._onRoomSecretsDeleted(e.detail));
Events.on('leave-public-room', e => this._onLeavePublicRoom(e.detail));
// Rooms and secrets: other peer closes connection
// peer closes connection
Events.on('secret-room-deleted', e => this._onSecretRoomDeleted(e.detail));
// Room secret, displayname, auto-accept
Events.on('room-secret-regenerated', e => this._onRoomSecretRegenerated(e.detail));
Events.on('display-name', e => this._onDisplayName(e.detail.displayName));
Events.on('self-display-name-changed', e => this._notifyPeersDisplayNameChanged(e.detail));
Events.on('notify-peer-display-name-changed', e => this._notifyPeerDisplayNameChanged(e.detail));
Events.on('auto-accept-updated', e => this._onAutoAcceptUpdated(e.detail.roomSecret, e.detail.autoAccept));
Events.on('ws-disconnected', _ => this._onWsDisconnected());
Events.on('ws-relay', e => this._onWsRelay(e.detail.peerId, e.detail.message));
Events.on('ws-config', e => this._onWsConfig(e.detail));
// NoSleep evaluation
Events.on('evaluate-no-sleep', _ => this._onEvaluateNoSleep());
}
_onWsConfig(wsConfig) {
this._wsConfig = wsConfig;
}
_onSignal(message) {
const peerId = message.sender.id;
this.peers[peerId]._onServerSignalMessage(message);
@@ -1610,9 +1656,9 @@ class PeersManager {
_createPeer(isCaller, peerId, roomType, roomId, rtcSupported) {
if (window.isRtcSupported && rtcSupported) {
this.peers[peerId] = new RTCPeer(this._server, isCaller, peerId, roomType, roomId);
this.peers[peerId] = new RTCPeer(this._server, isCaller, peerId, roomType, roomId, this._wsConfig.rtcConfig);
}
else if (window._wsConfig.wsFallback) {
else if (this._wsConfig.wsFallback) {
this.peers[peerId] = new WSPeer(this._server, isCaller, peerId, roomType, roomId);
}
else {
@@ -1632,20 +1678,11 @@ class PeersManager {
}
_onWsRelay(peerId, message) {
if (!window._wsConfig.wsFallback) return;
if (!this._wsConfig.wsFallback) return;
const peer = this.peers[peerId];
if (!peer) return;
// Check if RTCPeer wants to fall back to WS fallback
if (peer.rtcSupported && JSON.parse(message).message.type === 'fallback-to-ws') {
this._onFallbackToWs(peerId);
return;
}
// Relay messages to WSPeers only
if (peer.rtcSupported) return;
if (!peer || peer.rtcSupported) return;
peer._onWsRelay(message);
}
@@ -1659,31 +1696,28 @@ class PeersManager {
await this.peers[message.to]._sendFileTransferRequest(files);
}
_onSendText(message) {
this.peers[message.to]._sendText(message.text);
async _onSendText(message) {
await this.peers[message.to]._sendText(message.text);
}
_onPeerLeft(message) {
if (this._peerExists(message.peerId) && !this._webRtcSupported(message.peerId)) {
Logger.debug('WSPeer left:', message.peerId);
}
else if (message.disconnect !== true) {
// if RTCPeer and disconnect is false -> abort and wait for reconnect
return;
}
if (message.disconnect === true) {
// if user actively disconnected from PairDrop server, disconnect all peer to peer connections immediately
this._disconnectOrRemoveRoomTypeByPeerId(message.peerId, message.roomType);
// if user actively disconnected from PairDrop server or is WSPeer, disconnect all peer to peer connections immediately
this._disconnectOrRemoveRoomTypeByPeerId(message.peerId, message.roomType);
// If no peers are connected anymore, we can safely assume that no other tab on the same browser is connected:
// Tidy up peerIds in localStorage
if (Object.keys(this.peers).length === 0) {
BrowserTabsConnector
.removeOtherPeerIdsFromLocalStorage()
.then(peerIds => {
if (!peerIds) return;
Logger.debug("successfully removed other peerIds from localStorage");
});
// If no peers are connected anymore, we can safely assume that no other tab on the same browser is connected:
// Tidy up peerIds in localStorage
if (Object.keys(this.peers).length === 0) {
BrowserTabsConnector
.removeOtherPeerIdsFromLocalStorage()
.then(peerIds => {
if (!peerIds) return;
Logger.debug("successfully removed other peerIds from localStorage");
});
}
}
}
@@ -1700,7 +1734,7 @@ class PeersManager {
}
_onWsDisconnected() {
if (!window._wsConfig || !window._wsConfig.wsFallback) return;
if (!this._wsConfig || !this._wsConfig.wsFallback) return;
for (const peerId in this.peers) {
if (!this._webRtcSupported(peerId)) {
@@ -1709,28 +1743,6 @@ class PeersManager {
}
}
_onFallbackToWs(peerId) {
const peer = this.peers[peerId];
if (!peer || !window._wsConfig.wsFallback) return;
peer._onDisconnected();
const isCaller = peer._isCaller;
const roomType = peer._getRoomTypes()[0];
const roomId = peer._roomIds[roomType];
// create WSPeer with same arguments
this._createPeer(isCaller, peerId, roomType, roomId, false);
// add missing room ids
for (let i = 1; i < peer._roomIds.length; i++) {
let roomType = peer._getRoomTypes()[i];
let roomId = peer._roomIds[roomType];
this.peers[peerId]._updateRoomIds(roomType, roomId);
}
}
_onPeerDisconnected(peerId) {
const peer = this.peers[peerId];
delete this.peers[peerId];
@@ -1890,7 +1902,7 @@ class FileChunkerRTC extends FileChunker {
this._chunkSize = peerConnection && peerConnection.sctp
? Math.min(peerConnection.sctp.maxMessageSize, 1048576) // 1 MB max
: 262144; // 256 KB
: 262144; // 256 kB
this._peerConnection = peerConnection;
this._dataChannel = dataChannel;

View File

@@ -25,7 +25,7 @@ class PeersUI {
this.shareMode.text = "";
Events.on('peer-joined', e => this._onPeerJoined(e.detail.peer, e.detail.roomType, e.detail.roomId));
Events.on('peer-connected', e => this._onPeerConnected(e.detail.peerId, e.detail.connectionHash, e.detail.rtcSupported));
Events.on('peer-connected', e => this._onPeerConnected(e.detail.peerId, e.detail.connectionHash));
Events.on('peer-connecting', e => this._onPeerConnecting(e.detail));
Events.on('peer-disconnected', e => this._onPeerDisconnected(e.detail));
Events.on('peers', e => this._onPeers(e.detail));
@@ -110,12 +110,12 @@ class PeersUI {
this.peerUIs[peer.id] = peerUI;
}
_onPeerConnected(peerId, connectionHash, rtcSupported) {
_onPeerConnected(peerId, connectionHash) {
const peerUI = this.peerUIs[peerId];
if (!peerUI) return;
peerUI._peerConnected(true, connectionHash, rtcSupported);
peerUI._peerConnected(true, connectionHash);
this._addPeerUIIfMissing(peerUI);
}
@@ -423,8 +423,8 @@ class PeerUI {
this._connected = false;
this._currentProgress = 0;
this._currentStatus = null
this._oldStatus = null;
this._currentStatus = 'idle';
this._oldStatus = 'idle';
this._progressQueue = [];
@@ -598,22 +598,20 @@ class PeerUI {
});
}
_peerConnected(connected = true, connectionHash = "", rtcSupported = false) {
_peerConnected(connected = true, connectionHash = "") {
if (connected) {
this._connected = true;
// on reconnect
this.setStatus(this._oldStatus);
this._oldStatus = null;
this._oldStatus = 'idle';
this._peer.rtcSupported = rtcSupported;
this._connectionHash = connectionHash;
this.updateTypesClassList();
}
else {
this._connected = false;
if (!this._oldStatus && this._currentStatus !== "connect") {
if (this._oldStatus === 'idle' && this._currentStatus !== "connect") {
// save old status when reconnecting
this._oldStatus = this._currentStatus;
}
@@ -789,10 +787,10 @@ class PeerUI {
clearTimeout(this.statusTimeout);
if (!status) {
if (status === 'idle') {
this.$el.removeAttribute('status');
this.$el.querySelector('.status').innerHTML = '';
this._currentStatus = null;
this._currentStatus = 'idle';
return;
}
@@ -814,7 +812,7 @@ class PeerUI {
if (["transfer-complete", "receive-complete", "error"].includes(status)) {
this.statusTimeout = setTimeout(() => {
this.setProgress(0, null);
this.setProgress(0, 'idle');
}, 10000);
}
}
@@ -1033,30 +1031,35 @@ class ReceiveDialog extends Dialog {
}
}
_parseFileData(displayName, connectionHash, files, imagesOnly, totalSize, badgeClassName) {
let fileOther = "";
if (files.length === 2) {
fileOther = imagesOnly
? Localization.getTranslation("dialogs.file-other-description-image")
: Localization.getTranslation("dialogs.file-other-description-file");
_parseFileData(displayName, connectionHash, files, filesType, totalSize, badgeClassName) {
if (filesType === 'message') {
this.$fileOther.innerText = Localization.getTranslation("dialogs.text-message-description");
}
else if (files.length > 2) {
fileOther = imagesOnly
? Localization.getTranslation("dialogs.file-other-description-image-plural", null, {count: files.length - 1})
: Localization.getTranslation("dialogs.file-other-description-file-plural", null, {count: files.length - 1});
else {
let fileOther = "";
if (files.length === 2) {
fileOther = filesType === 'images'
? Localization.getTranslation("dialogs.file-other-description-image")
: Localization.getTranslation("dialogs.file-other-description-file");
}
else if (files.length > 2) {
fileOther = filesType === 'images'
? Localization.getTranslation("dialogs.file-other-description-image-plural", null, {count: files.length - 1})
: Localization.getTranslation("dialogs.file-other-description-file-plural", null, {count: files.length - 1});
}
const fileName = files[0].name;
const fileNameSplit = fileName.split('.');
const fileExtension = '.' + fileNameSplit[fileNameSplit.length - 1];
const fileStem = fileName.substring(0, fileName.length - fileExtension.length);
this.$fileOther.innerText = fileOther;
this.$fileStem.innerText = fileStem;
this.$fileExtension.innerText = fileExtension;
}
const fileName = files[0].name;
const fileNameSplit = fileName.split('.');
const fileExtension = '.' + fileNameSplit[fileNameSplit.length - 1];
const fileStem = fileName.substring(0, fileName.length - fileExtension.length);
this.$fileSize.innerText = this._formatFileSize(totalSize);
const fileSize = this._formatFileSize(totalSize);
this.$fileOther.innerText = fileOther;
this.$fileStem.innerText = fileStem;
this.$fileExtension.innerText = fileExtension;
this.$fileSize.innerText = fileSize;
this.$displayName.innerText = displayName;
this.$displayName.title = connectionHash;
this.$displayName.classList.remove("badge-room-ip", "badge-room-secret", "badge-room-public-id");
@@ -1072,12 +1075,12 @@ class ReceiveFileDialog extends ReceiveDialog {
this.$downloadBtn = this.$el.querySelector('#download-btn');
this.$shareBtn = this.$el.querySelector('#share-btn');
Events.on('files-received', e => this._onFilesReceived(e.detail.peerId, e.detail.files, e.detail.imagesOnly, e.detail.totalSize));
Events.on('files-received', e => this._onFilesReceived(e.detail.peerId, e.detail.files, e.detail.filesType, e.detail.totalSize));
this._filesDataQueue = [];
}
async _onFilesReceived(peerId, files, imagesOnly, totalSize) {
const descriptor = this._getDescriptor(files, imagesOnly);
async _onFilesReceived(peerId, files, filesType, totalSize) {
const descriptor = this._getDescriptor(files, filesType);
const displayName = $(peerId).ui._displayName();
const connectionHash = $(peerId).ui._connectionHash;
const badgeClassName = $(peerId).ui._badgeClassName();
@@ -1085,7 +1088,7 @@ class ReceiveFileDialog extends ReceiveDialog {
this._filesDataQueue.push({
peerId: peerId,
files: files,
imagesOnly: imagesOnly,
filesType: filesType,
totalSize: totalSize,
descriptor: descriptor,
displayName: displayName,
@@ -1128,7 +1131,7 @@ class ReceiveFileDialog extends ReceiveDialog {
this._data.displayName,
this._data.connectionHash,
this._data.files,
this._data.imagesOnly,
this._data.filesType,
this._data.totalSize,
this._data.badgeClassName
);
@@ -1154,15 +1157,15 @@ class ReceiveFileDialog extends ReceiveDialog {
return window.iOS && this._data.totalSize > 250000000;
}
_getDescriptor(files, imagesOnly) {
_getDescriptor(files, filesType) {
let descriptor;
if (files.length === 1) {
descriptor = imagesOnly
descriptor = filesType === 'images'
? Localization.getTranslation("dialogs.title-image")
: Localization.getTranslation("dialogs.title-file");
}
else {
descriptor = imagesOnly
descriptor = filesType === 'images'
? Localization.getTranslation("dialogs.title-image-plural")
: Localization.getTranslation("dialogs.title-file-plural");
}
@@ -1501,15 +1504,17 @@ class ReceiveRequestDialog extends ReceiveDialog {
_showRequestDialog(request, peerId) {
this.correspondingPeerId = peerId;
const transferRequestTitleTranslation = request.imagesOnly
? Localization.getTranslation('document-titles.image-transfer-requested')
: Localization.getTranslation('document-titles.file-transfer-requested');
const transferRequestTitleTranslation = request.filesType === 'message'
? Localization.getTranslation('document-titles.message-transfer-requested')
: request.filesType === 'images'
? Localization.getTranslation('document-titles.image-transfer-requested')
: Localization.getTranslation('document-titles.file-transfer-requested');
const displayName = $(peerId).ui._displayName();
const connectionHash = $(peerId).ui._connectionHash;
const badgeClassName = $(peerId).ui._badgeClassName();
this._parseFileData(displayName, connectionHash, request.header, request.imagesOnly, request.totalSize, badgeClassName);
this._parseFileData(displayName, connectionHash, request.header, request.filesType, request.totalSize, badgeClassName);
this._addThumbnailToPreviewBox(request.thumbnailDataUrl);
this.$receiveTitle.innerText = transferRequestTitleTranslation;
@@ -2314,6 +2319,11 @@ class SendTextDialog extends Dialog {
text: this.$text.innerText
});
this.hide();
}
hide() {
super.hide();
this.$submit.setAttribute('disabled', true);
setTimeout(() => this.$text.innerText = "", 300);
}
}
@@ -2741,7 +2751,7 @@ class Notifications {
Events.on('text-received', e => this._messageNotification(e.detail.text, e.detail.peerId));
Events.on('files-received', e => this._downloadNotification(e.detail.files, e.detail.imagesOnly));
Events.on('files-received', e => this._downloadNotification(e.detail.files, e.detail.filesType));
Events.on('files-transfer-request', e => this._requestNotification(e.detail.request, e.detail.peerId));
// Todo on 'files-transfer-request-abort' remove notification
}
@@ -2825,31 +2835,26 @@ class Notifications {
}
_requestNotification(request, peerId) {
if (document.visibilityState !== 'visible') {
let imagesOnly = request.header.every(header => header.mime.split('/')[0] === 'image');
let displayName = $(peerId).querySelector('.name').textContent;
// Do not notify user if page is visible
if (document.visibilityState === 'visible') return;
let descriptor;
if (request.header.length === 1) {
descriptor = imagesOnly
? Localization.getTranslation("dialogs.title-image")
: Localization.getTranslation("dialogs.title-file");
}
else {
descriptor = imagesOnly
? Localization.getTranslation("dialogs.title-image-plural")
: Localization.getTranslation("dialogs.title-file-plural");
}
const clickToShowTranslation = Localization.getTranslation("notifications.click-to-show");
const displayName = $(peerId).querySelector('.name').textContent;
let title = Localization
.getTranslation("notifications.request-title", null, {
name: displayName,
count: request.header.length,
descriptor: descriptor.toLowerCase()
});
const transferRequestTitleTranslation = request.filesType === 'message'
? Localization.getTranslation('document-titles.message-transfer-requested')
: request.filesType === 'images'
? Localization.getTranslation('document-titles.image-transfer-requested')
: Localization.getTranslation('document-titles.file-transfer-requested');
const notification = this._notify(title, Localization.getTranslation("notifications.click-to-show"));
}
let title = Localization
.getTranslation("notifications.request-title", null, {
name: displayName,
count: request.header.length,
descriptor: transferRequestTitleTranslation.toLowerCase()
});
this._notify(title, clickToShowTranslation);
}
_download(notification) {