merge master into branch

This commit is contained in:
schlagmichdoch 2023-03-03 17:40:10 +01:00
commit 002b31a113
13 changed files with 585 additions and 498 deletions

View file

@ -1,6 +1,5 @@
const $ = query => document.getElementById(query);
const $$ = query => document.body.querySelector(query);
const isURL = text => /^(https?:\/\/|www)[^\s]+$/g.test(text.toLowerCase());
window.isProductionEnvironment = !window.location.host.startsWith('localhost');
window.iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
window.android = /android/i.test(navigator.userAgent);
@ -28,7 +27,7 @@ class PeersUI {
Events.on('activate-paste-mode', e => this._activatePasteMode(e.detail.files, e.detail.text));
this.peers = {};
this.$cancelPasteModeBtn = $('cancel-paste-mode-btn');
this.$cancelPasteModeBtn = $('cancel-paste-mode');
this.$cancelPasteModeBtn.addEventListener('click', _ => this._cancelPasteMode());
Events.on('dragover', e => this._onDragOver(e));
@ -79,7 +78,6 @@ class PeersUI {
async _saveDisplayName(newDisplayName) {
newDisplayName = newDisplayName.replace(/(\n|\r|\r\n)/, '')
console.debug(newDisplayName)
const savedDisplayName = await this._getSavedDisplayName();
if (newDisplayName === savedDisplayName) return;
@ -118,6 +116,8 @@ class PeersUI {
_changePeerDisplayName(peerId, displayName) {
this.peers[peerId].name.displayName = displayName;
const peerIdNode = $(peerId);
console.debug(peerIdNode)
console.debug(displayName)
if (peerIdNode && displayName) peerIdNode.querySelector('.name').textContent = displayName;
}
@ -548,10 +548,14 @@ class Dialog {
class ReceiveDialog extends Dialog {
constructor(id) {
super(id);
this.$fileDescriptionNode = this.$el.querySelector('.file-description');
this.$fileSizeNode = this.$el.querySelector('.file-size');
this.$previewBox = this.$el.querySelector('.file-preview')
this.$fileDescription = this.$el.querySelector('.file-description');
this.$displayName = this.$el.querySelector('.display-name');
this.$fileStem = this.$el.querySelector('.file-stem');
this.$fileExtension = this.$el.querySelector('.file-extension');
this.$fileOther = this.$el.querySelector('.file-other');
this.$fileSize = this.$el.querySelector('.file-size');
this.$previewBox = this.$el.querySelector('.file-preview');
this.$receiveTitle = this.$el.querySelector('h2:first-of-type');
}
_formatFileSize(bytes) {
@ -567,6 +571,26 @@ class ReceiveDialog extends Dialog {
return bytes + ' Bytes';
}
}
_parseFileData(displayName, files, imagesOnly, totalSize) {
if (files.length > 1) {
let fileOtherText = ` and ${files.length - 1} other `;
if (files.length === 2) {
fileOtherText += imagesOnly ? 'image' : 'file';
} else {
fileOtherText += imagesOnly ? 'images' : 'files';
}
this.$fileOther.innerText = fileOtherText;
}
const fileName = files[0].name;
const fileNameSplit = fileName.split('.');
const fileExtension = '.' + fileNameSplit[fileNameSplit.length - 1];
this.$fileStem.innerText = fileName.substring(0, fileName.length - fileExtension.length);
this.$fileExtension.innerText = fileExtension;
this.$displayName.innerText = displayName;
this.$fileSize.innerText = this._formatFileSize(totalSize);
}
}
class ReceiveFileDialog extends ReceiveDialog {
@ -574,24 +598,25 @@ class ReceiveFileDialog extends ReceiveDialog {
constructor() {
super('receive-file-dialog');
this.$shareOrDownloadBtn = this.$el.querySelector('#share-or-download');
this.$receiveTitleNode = this.$el.querySelector('#receive-title')
this.$downloadBtn = this.$el.querySelector('#download-btn');
this.$shareBtn = this.$el.querySelector('#share-btn');
Events.on('files-received', e => this._onFilesReceived(e.detail.sender, e.detail.files, e.detail.request));
Events.on('files-received', e => this._onFilesReceived(e.detail.sender, e.detail.files, e.detail.imagesOnly, e.detail.totalSize));
this._filesQueue = [];
}
_onFilesReceived(sender, files, request) {
this._nextFiles(sender, files, request);
_onFilesReceived(sender, files, imagesOnly, totalSize) {
const displayName = $(sender).ui._displayName()
this._filesQueue.push({peer: sender, displayName: displayName, files: files, imagesOnly: imagesOnly, totalSize: totalSize});
this._nextFiles();
window.blop.play();
}
_nextFiles(sender, nextFiles, nextRequest) {
if (nextFiles) this._filesQueue.push({peerId: sender, files: nextFiles, request: nextRequest});
_nextFiles() {
if (this._busy) return;
this._busy = true;
const {peerId, files, request} = this._filesQueue.shift();
this._displayFiles(peerId, files, request);
const {peer, displayName, files, imagesOnly, totalSize} = this._filesQueue.shift();
this._displayFiles(peer, displayName, files, imagesOnly, totalSize);
}
_dequeueFile() {
@ -623,7 +648,6 @@ class ReceiveFileDialog extends ReceiveDialog {
let element = document.createElement(previewElement[mime]);
element.src = URL.createObjectURL(file);
element.controls = true;
element.classList.add('element-preview');
element.onload = _ => {
this.$previewBox.appendChild(element);
resolve(true)
@ -634,30 +658,32 @@ class ReceiveFileDialog extends ReceiveDialog {
});
}
async _displayFiles(peerId, files, request) {
if (this.continueCallback) this.$shareOrDownloadBtn.removeEventListener("click", this.continueCallback);
let url;
let title;
let filenameDownload;
let descriptor = request.imagesOnly ? "Image" : "File";
let size = this._formatFileSize(request.totalSize);
let description = files[0].name;
let shareInsteadOfDownload = (window.iOS || window.android) && !!navigator.share && navigator.canShare({files});
async _displayFiles(peerId, displayName, files, imagesOnly, totalSize) {
this._parseFileData(displayName, files, imagesOnly, totalSize);
let descriptor, url, filenameDownload;
if (files.length === 1) {
url = URL.createObjectURL(files[0])
title = `PairDrop - ${descriptor} Received`
filenameDownload = files[0].name;
descriptor = imagesOnly ? 'Image' : 'File';
} else {
title = `PairDrop - ${files.length} ${descriptor}s Received`
description += ` and ${files.length-1} other ${descriptor.toLowerCase()}`;
if(files.length>2) description += "s";
descriptor = imagesOnly ? 'Images' : 'Files';
}
this.$receiveTitle.innerText = `${descriptor} Received`;
if(!shareInsteadOfDownload) {
const canShare = (window.iOS || window.android) && !!navigator.share && navigator.canShare({files});
if (canShare) {
this.$shareBtn.removeAttribute('hidden');
this.$shareBtn.onclick = _ => {
navigator.share({files: files})
.catch(err => {
console.error(err);
});
}
}
let downloadZipped = false;
if (files.length > 1) {
downloadZipped = true;
try {
let bytesCompleted = 0;
zipper.createNewZipWriter();
for (let i=0; i<files.length; i++) {
@ -665,7 +691,7 @@ class ReceiveFileDialog extends ReceiveDialog {
onprogress: (progress) => {
Events.fire('set-progress', {
peerId: peerId,
progress: (bytesCompleted + progress) / request.totalSize,
progress: (bytesCompleted + progress) / totalSize,
status: 'process'
})
}
@ -685,47 +711,58 @@ class ReceiveFileDialog extends ReceiveDialog {
let minutes = now.getMinutes().toString();
minutes = minutes.length < 2 ? "0" + minutes : minutes;
filenameDownload = `PairDrop_files_${year+month+date}_${hours+minutes}.zip`;
} catch (e) {
console.error(e);
downloadZipped = false;
}
}
this.$receiveTitleNode.textContent = title;
this.$fileDescriptionNode.textContent = description;
this.$fileSizeNode.textContent = size;
if (shareInsteadOfDownload) {
this.$shareOrDownloadBtn.innerText = "Share";
this.continue = _ => {
navigator.share({files: files})
.catch(err => console.error(err));
this.$downloadBtn.innerText = "Download";
this.$downloadBtn.onclick = _ => {
if (downloadZipped) {
let tmpZipBtn = document.createElement("a");
tmpZipBtn.download = filenameDownload;
tmpZipBtn.href = url;
tmpZipBtn.click();
} else {
this._downloadFilesIndividually(files);
}
this.continueCallback = _ => this.continue();
} else {
this.$shareOrDownloadBtn.innerText = "Download again";
this.continue = _ => {
let tmpBtn = document.createElement("a");
tmpBtn.download = filenameDownload;
tmpBtn.href = url;
tmpBtn.click();
};
this.continueCallback = _ => {
this.continue();
this.hide();
};
}
this.$shareOrDownloadBtn.addEventListener("click", this.continueCallback);
if (!canShare) {
this.$downloadBtn.innerText = "Download again";
}
Events.fire('notify-user', `${descriptor} downloaded successfully`);
this.$downloadBtn.style.pointerEvents = "none";
setTimeout(_ => this.$downloadBtn.style.pointerEvents = "unset", 2000);
};
this.createPreviewElement(files[0]).finally(_ => {
document.title = `PairDrop - ${files.length} Files received`;
document.title = files.length === 1
? 'File received - PairDrop'
: `${files.length} Files received - PairDrop`;
document.changeFavicon("images/favicon-96x96-notification.png");
this.show();
Events.fire('set-progress', {peerId: peerId, progress: 1, status: 'process'})
this.continue();
this.show();
if (canShare) {
this.$shareBtn.click();
} else {
this.$downloadBtn.click();
}
}).catch(r => console.error(r));
}
_downloadFilesIndividually(files) {
let tmpBtn = document.createElement("a");
for (let i=0; i<files.length; i++) {
tmpBtn.download = files[i].name;
tmpBtn.href = URL.createObjectURL(files[i]);
tmpBtn.click();
}
}
hide() {
this.$shareOrDownloadBtn.removeAttribute('href');
this.$shareOrDownloadBtn.removeAttribute('download');
this.$shareBtn.setAttribute('hidden', '');
this.$previewBox.innerHTML = '';
super.hide();
this._dequeueFile();
@ -737,11 +774,6 @@ class ReceiveRequestDialog extends ReceiveDialog {
constructor() {
super('receive-request-dialog');
this.$requestingPeerDisplayNameNode = this.$el.querySelector('#receive-request-dialog .display-name');
this.$fileStemNode = this.$el.querySelector('#file-stem');
this.$fileExtensionNode = this.$el.querySelector('#file-extension');
this.$fileOtherNode = this.$el.querySelector('#file-other');
this.$acceptRequestBtn = this.$el.querySelector('#accept-request');
this.$declineRequestBtn = this.$el.querySelector('#decline-request');
this.$acceptRequestBtn.addEventListener('click', _ => this._respondToFileTransferRequest(true));
@ -773,32 +805,18 @@ class ReceiveRequestDialog extends ReceiveDialog {
_showRequestDialog(request, peerId) {
this.correspondingPeerId = peerId;
this.$requestingPeerDisplayNameNode.innerText = $(peerId).ui._displayName();
const fileName = request.header[0].name;
const fileNameSplit = fileName.split('.');
const fileExtension = '.' + fileNameSplit[fileNameSplit.length - 1];
this.$fileStemNode.innerText = fileName.substring(0, fileName.length - fileExtension.length);
this.$fileExtensionNode.innerText = fileExtension
if (request.header.length >= 2) {
let fileOtherText = ` and ${request.header.length - 1} other `;
fileOtherText += request.imagesOnly ? 'image' : 'file';
if (request.header.length > 2) fileOtherText += "s";
this.$fileOtherNode.innerText = fileOtherText;
}
this.$fileSizeNode.innerText = this._formatFileSize(request.totalSize);
const displayName = $(peerId).ui._displayName();
this._parseFileData(displayName, request.header, request.imagesOnly, request.totalSize);
if (request.thumbnailDataUrl?.substring(0, 22) === "data:image/jpeg;base64") {
let element = document.createElement('img');
element.src = request.thumbnailDataUrl;
element.classList.add('element-preview');
this.$previewBox.appendChild(element)
}
document.title = 'PairDrop - File Transfer Requested';
this.$receiveTitle.innerText = `${request.imagesOnly ? 'Image' : 'File'} Transfer Request`
document.title = `${request.imagesOnly ? 'Image' : 'File'} Transfer Requested - PairDrop`;
document.changeFavicon("images/favicon-96x96-notification.png");
this.show();
}
@ -833,7 +851,7 @@ class PairDeviceDialog extends Dialog {
this.$clearSecretsBtn = $('clear-pair-devices');
this.$footerInstructionsPairedDevices = $('and-by-paired-devices');
let createJoinForm = this.$el.querySelector('form');
createJoinForm.addEventListener('submit', _ => this._onSubmit());
createJoinForm.addEventListener('submit', e => this._onSubmit(e));
this.$el.querySelector('[close]').addEventListener('click', _ => this._pairDeviceCancel())
this.$inputRoomKeyChars.forEach(el => el.addEventListener('input', e => this._onCharsInput(e)));
@ -912,7 +930,7 @@ class PairDeviceDialog extends Dialog {
})
this.$submitBtn.removeAttribute("disabled");
if (document.activeElement === this.$inputRoomKeyChars[5]) {
this._onSubmit();
this._pairDeviceJoin(this.inputRoomKey);
}
}
}
@ -962,7 +980,8 @@ class PairDeviceDialog extends Dialog {
return url.href;
}
_onSubmit() {
_onSubmit(e) {
e.preventDefault();
this._pairDeviceJoin(this.inputRoomKey);
}
@ -1049,14 +1068,19 @@ class ClearDevicesDialog extends Dialog {
super('clear-devices-dialog');
$('clear-pair-devices').addEventListener('click', _ => this._onClearPairDevices());
let clearDevicesForm = this.$el.querySelector('form');
clearDevicesForm.addEventListener('submit', _ => this._onSubmit());
clearDevicesForm.addEventListener('submit', e => this._onSubmit(e));
}
_onClearPairDevices() {
this.show();
}
_onSubmit() {
_onSubmit(e) {
e.preventDefault();
this._clearRoomSecrets();
}
_clearRoomSecrets() {
Events.fire('clear-room-secrets');
this.hide();
}
@ -1067,10 +1091,10 @@ class SendTextDialog extends Dialog {
super('send-text-dialog');
Events.on('text-recipient', e => this._onRecipient(e.detail.peerId, e.detail.deviceName));
this.$text = this.$el.querySelector('#text-input');
this.$peerDisplayName = this.$el.querySelector('#send-text-dialog .display-name');
this.$peerDisplayName = this.$el.querySelector('.display-name');
this.$form = this.$el.querySelector('form');
this.$submit = this.$el.querySelector('button[type="submit"]');
this.$form.addEventListener('submit', _ => this._send());
this.$form.addEventListener('submit', e => this._onSubmit(e));
this.$text.addEventListener('input', e => this._onChange(e));
Events.on("keydown", e => this._onKeyDown(e));
}
@ -1112,6 +1136,11 @@ class SendTextDialog extends Dialog {
sel.addRange(range);
}
_onSubmit(e) {
e.preventDefault();
this._send();
}
_send() {
Events.fire('send-text', {
to: this.correspondingPeerId,
@ -1135,7 +1164,7 @@ class ReceiveTextDialog extends Dialog {
Events.on("keydown", e => this._onKeyDown(e));
this.$receiveTextPeerDisplayNameNode = this.$el.querySelector('#receive-text-dialog .display-name');
this.$displayNameNode = this.$el.querySelector('.display-name');
this._receiveTextQueue = [];
}
@ -1153,6 +1182,7 @@ class ReceiveTextDialog extends Dialog {
_onText(text, peerId) {
window.blop.play();
this._receiveTextQueue.push({text: text, peerId: peerId});
this._setDocumentTitleMessages();
if (this.$el.attributes["show"]) return;
this._dequeueRequests();
}
@ -1164,23 +1194,35 @@ class ReceiveTextDialog extends Dialog {
}
_showReceiveTextDialog(text, peerId) {
this.$receiveTextPeerDisplayNameNode.innerText = $(peerId).ui._displayName();
this.$displayNameNode.innerText = $(peerId).ui._displayName();
if (isURL(text)) {
const $a = document.createElement('a');
$a.href = text;
$a.target = '_blank';
$a.textContent = text;
this.$text.innerHTML = '';
this.$text.appendChild($a);
} else {
this.$text.textContent = text;
this.$text.innerText = text;
this.$text.classList.remove('text-center');
// Beautify text if text is short
if (text.length < 2000) {
// replace urls with actual links
this.$text.innerHTML = this.$text.innerHTML.replace(/((https?:\/\/|www)[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\-._~:\/?#\[\]@!$&'()*+,;=]+)/g, url => {
return `<a href="${url}" target="_blank">${url}</a>`;
});
if (!/\s/.test(text)) {
this.$text.classList.add('text-center');
}
}
document.title = 'PairDrop - Message Received';
this._setDocumentTitleMessages();
document.changeFavicon("images/favicon-96x96-notification.png");
this.show();
}
_setDocumentTitleMessages() {
document.title = !this._receiveTextQueue.length
? 'Message Received - PairDrop'
: `${this._receiveTextQueue.length + 1} Messages Received - PairDrop`;
}
async _onCopy() {
await navigator.clipboard.writeText(this.$text.textContent);
Events.fire('notify-user', 'Copied to clipboard');
@ -1253,7 +1295,7 @@ class Base64ZipDialog extends Dialog {
}
_setPasteBtnToProcessing() {
this.$pasteBtn.pointerEvents = "none";
this.$pasteBtn.style.pointerEvents = "none";
this.$pasteBtn.innerText = "Processing...";
}
@ -1398,7 +1440,7 @@ class Notifications {
_messageNotification(message, peerId) {
if (document.visibilityState !== 'visible') {
const peerDisplayName = $(peerId).ui._displayName();
if (isURL(message)) {
if (/^((https?:\/\/|www)[abcdefghijklmnopqrstuvwxyz0123456789\-._~:\/?#\[\]@!$&'()*+,;=]+)$/.test(message.toLowerCase())) {
const notification = this._notify(`Link received by ${peerDisplayName} - Click to open`, message);
this._bind(notification, _ => window.open(message, '_blank', null, true));
} else {
@ -1459,7 +1501,7 @@ class NetworkStatusUI {
constructor() {
Events.on('offline', _ => this._showOfflineMessage());
Events.on('online', _ => this._showOnlineMessage());
Events.on('ws-connected', _ => this._showOnlineMessage());
Events.on('ws-connected', _ => this._onWsConnected());
Events.on('ws-disconnected', _ => this._onWsDisconnected());
if (!navigator.onLine) this._showOfflineMessage();
}
@ -1470,17 +1512,16 @@ class NetworkStatusUI {
}
_showOnlineMessage() {
window.animateBackground(true);
if (!this.firstConnect) {
this.firstConnect = true;
return;
}
Events.fire('notify-user', 'You are back online');
window.animateBackground(true);
}
_onWsConnected() {
window.animateBackground(true);
}
_onWsDisconnected() {
window.animateBackground(false);
if (!this.firstConnect) this.firstConnect = true;
}
}
@ -1836,8 +1877,8 @@ Events.on('load', () => {
let x0, y0, w, h, dw, offset;
function init() {
w = window.innerWidth;
h = window.innerHeight;
w = document.documentElement.clientWidth;
h = document.documentElement.clientHeight;
c.width = w;
c.height = h;
offset = $$('footer').offsetHeight - 32;