Put all log prompts into new Logger class; Only log debugging logs to console if PairDrop is in debug mode; Implement activation of debug mode via URL argument (?debug=true)

This commit is contained in:
schlagmichdoch 2024-02-05 15:42:27 +01:00
parent b61de4eb87
commit 6de97e7ff1
8 changed files with 144 additions and 114 deletions

View file

@ -10,7 +10,7 @@ class BrowserTabsConnector {
} }
_onMessage(e) { _onMessage(e) {
console.log('Broadcast:', e.data) Logger.debug('Broadcast:', e.data)
switch (e.data.type) { switch (e.data.type) {
case 'self-display-name-changed': case 'self-display-name-changed':
Events.fire('self-display-name-changed', e.data.detail); Events.fire('self-display-name-changed', e.data.detail);

View file

@ -67,7 +67,7 @@ class Localization {
Localization.$htmlRoot.setAttribute('lang', locale); Localization.$htmlRoot.setAttribute('lang', locale);
console.log("Page successfully translated", Logger.debug("Page successfully translated",
`System language: ${Localization.systemLocale}`, `System language: ${Localization.systemLocale}`,
`Selected language: ${locale}` `Selected language: ${locale}`
); );
@ -145,7 +145,7 @@ class Localization {
translation = translationObj[lastKey]; translation = translationObj[lastKey];
} catch (e) { } catch (e) {
console.error(e); Logger.error(e);
} }
if (!translation) { if (!translation) {
@ -179,7 +179,7 @@ class Localization {
} }
catch (e) { catch (e) {
// Log warnings and help calls // Log warnings and help calls
console.warn(e); Logger.warn(e);
Localization.logTranslationMissingOrBroken(key, attr, data, useDefault); Localization.logTranslationMissingOrBroken(key, attr, data, useDefault);
Localization.logHelpCallKey(key, attr); Localization.logHelpCallKey(key, attr);
Localization.logHelpCall(); Localization.logHelpCall();
@ -192,7 +192,7 @@ class Localization {
else { else {
// Is not default locale yet // Is not default locale yet
// Get translation for default language with same arguments // Get translation for default language with same arguments
console.log(`Using default language ${Localization.defaultLocale.toUpperCase()} instead.`); Logger.debug(`Using default language ${Localization.defaultLocale.toUpperCase()} instead.`);
translation = this.getTranslation(key, attr, data, true); translation = this.getTranslation(key, attr, data, true);
} }
} }
@ -205,11 +205,11 @@ class Localization {
? Localization.defaultLocale.toUpperCase() ? Localization.defaultLocale.toUpperCase()
: Localization.locale.toUpperCase(); : Localization.locale.toUpperCase();
console.warn(`Missing or broken translation for language ${usedLocale}.\n`, 'key:', key, 'attr:', attr, 'data:', data); Logger.warn(`Missing or broken translation for language ${usedLocale}.\n`, 'key:', key, 'attr:', attr, 'data:', data);
} }
static logHelpCall() { static logHelpCall() {
console.log("Help translating PairDrop: https://hosted.weblate.org/engage/pairdrop/"); Logger.warn("Help translating PairDrop: https://hosted.weblate.org/engage/pairdrop/");
} }
static logHelpCallKey(key, attr) { static logHelpCallKey(key, attr) {
@ -219,7 +219,7 @@ class Localization {
? key ? key
: `${key}_${attr}`; : `${key}_${attr}`;
console.warn(`Translate this string here: https://hosted.weblate.org/browse/pairdrop/pairdrop-spa/${locale}/?q=${keyComplete}`); Logger.warn(`Translate this string here: https://hosted.weblate.org/browse/pairdrop/pairdrop-spa/${locale}/?q=${keyComplete}`);
} }
static escapeHTML(unsafeText) { static escapeHTML(unsafeText) {

View file

@ -1,3 +1,23 @@
class Logger {
static debug(message, ...optionalParams) {
if (window.debugMode) {
console.debug("DEBUG:", message, ...optionalParams);
}
}
static log(message, ...optionalParams) {
console.log("LOG:", message, ...optionalParams);
}
static warn(message, ...optionalParams) {
console.warn("WARN:", message, ...optionalParams);
}
static error(message, ...optionalParams) {
console.error("ERROR:", message, ...optionalParams);
}
}
class PairDrop { class PairDrop {
constructor() { constructor() {
@ -34,14 +54,14 @@ class PairDrop {
this.initialize() this.initialize()
.then(_ => { .then(_ => {
console.log("Initialization completed."); Logger.log("Initialization completed.");
}); });
} }
async initialize() { async initialize() {
// Translate page before fading in // Translate page before fading in
await this.localization.setInitialTranslation() await this.localization.setInitialTranslation()
console.log("Initial translation successful."); Logger.log("Initial translation successful.");
// Show "Loading..." until connected to WsServer // Show "Loading..." until connected to WsServer
await this.footerUI.showLoading(); await this.footerUI.showLoading();
@ -56,16 +76,16 @@ class PairDrop {
await this.backgroundCanvas.fadeIn(); await this.backgroundCanvas.fadeIn();
// Load deferred assets // Load deferred assets
console.log("Load deferred assets..."); Logger.log("Load deferred assets...");
await this.loadDeferredAssets(); await this.loadDeferredAssets();
console.log("Loading of deferred assets completed."); Logger.log("Loading of deferred assets completed.");
console.log("Hydrate UI..."); Logger.log("Hydrate UI...");
await this.hydrate(); await this.hydrate();
console.log("UI hydrated."); Logger.log("UI hydrated.");
// Evaluate url params as soon as ws is connected // Evaluate url params as soon as ws is connected
console.log("Evaluate URL params as soon as websocket connection is established."); Logger.log("Evaluate URL params as soon as websocket connection is established.");
Events.on('ws-connected', _ => this.evaluateUrlParams(), {once: true}); Events.on('ws-connected', _ => this.evaluateUrlParams(), {once: true});
} }
@ -74,7 +94,7 @@ class PairDrop {
navigator.serviceWorker navigator.serviceWorker
.register('service-worker.js') .register('service-worker.js')
.then(serviceWorker => { .then(serviceWorker => {
console.log('Service Worker registered'); Logger.log('Service Worker registered');
window.serviceWorker = serviceWorker window.serviceWorker = serviceWorker
}); });
} }
@ -133,10 +153,10 @@ class PairDrop {
return new Promise( async (resolve) => { return new Promise( async (resolve) => {
try { try {
await this.loadStyleSheet(url); await this.loadStyleSheet(url);
console.log(`Stylesheet loaded successfully: ${url}`); Logger.log(`Stylesheet loaded successfully: ${url}`);
resolve(); resolve();
} catch (error) { } catch (error) {
console.error('Error loading stylesheet:', error); Logger.error('Error loading stylesheet:', error);
} }
}); });
} }
@ -156,10 +176,10 @@ class PairDrop {
return new Promise( async (resolve) => { return new Promise( async (resolve) => {
try { try {
await this.loadScript(url); await this.loadScript(url);
console.log(`Script loaded successfully: ${url}`); Logger.log(`Script loaded successfully: ${url}`);
resolve(); resolve();
} catch (error) { } catch (error) {
console.error('Error loading script:', error); Logger.error('Error loading script:', error);
} }
}); });
} }
@ -229,12 +249,17 @@ class PairDrop {
this.publicRoomDialog._createPublicRoom(); this.publicRoomDialog._createPublicRoom();
} }
} }
else if (urlParams.has("debug") && urlParams.get("debug") === "true") {
window.debugMode = true;
}
// remove url params from url if (!window.debugMode) {
const urlWithoutParams = getUrlWithoutArguments(); // remove url params from url
window.history.replaceState({}, "Rewrite URL", urlWithoutParams); const urlWithoutParams = getUrlWithoutArguments();
window.history.replaceState({}, "Rewrite URL", urlWithoutParams);
}
console.log("URL params evaluated."); Logger.log("URL params evaluated.");
} }
} }

View file

@ -27,16 +27,16 @@ class ServerConnection {
} }
_getConfig() { _getConfig() {
console.log("Loading config...") Logger.log("Loading config...")
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest(); let xhr = new XMLHttpRequest();
xhr.addEventListener("load", () => { xhr.addEventListener("load", () => {
if (xhr.status === 200) { if (xhr.status === 200) {
// Config received // Config received
let config = JSON.parse(xhr.responseText); let config = JSON.parse(xhr.responseText);
console.log("Config loaded:", config) Logger.log("Config loaded:", config)
this._config = config; window._config = config;
Events.fire('config', config); Events.fire('config-loaded');
resolve() resolve()
} else if (xhr.status < 200 || xhr.status >= 300) { } else if (xhr.status < 200 || xhr.status >= 300) {
retry(xhr); retry(xhr);
@ -86,7 +86,7 @@ class ServerConnection {
} }
_onOpen() { _onOpen() {
console.log('WS: server connected'); Logger.log('WS: server connected');
Events.fire('ws-connected'); Events.fire('ws-connected');
if (this._isReconnect) { if (this._isReconnect) {
Events.fire('notify-user', Localization.getTranslation("notifications.connected")); Events.fire('notify-user', Localization.getTranslation("notifications.connected"));
@ -136,7 +136,9 @@ class ServerConnection {
_onMessage(message) { _onMessage(message) {
const messageJSON = JSON.parse(message); const messageJSON = JSON.parse(message);
if (messageJSON.type !== 'ping' && messageJSON.type !== 'ws-relay') console.log('WS receive:', messageJSON); if (messageJSON.type !== 'ping' && messageJSON.type !== 'ws-relay') {
Logger.debug('WS receive:', messageJSON);
}
switch (messageJSON.type) { switch (messageJSON.type) {
case 'ws-config': case 'ws-config':
this._setWsConfig(messageJSON.wsConfig); this._setWsConfig(messageJSON.wsConfig);
@ -195,17 +197,19 @@ class ServerConnection {
Events.fire('ws-relay', {peerId: messageJSON.sender.id, message: message}); Events.fire('ws-relay', {peerId: messageJSON.sender.id, message: message});
} }
else { else {
console.log("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; break;
default: default:
console.error('WS receive: unknown message type', messageJSON); Logger.error('WS receive: unknown message type', messageJSON);
} }
} }
send(msg) { send(msg) {
if (!this._isConnected()) return; if (!this._isConnected()) return;
if (msg.type !== 'pong' && msg.type !== 'ws-relay') console.log("WS send:", msg) if (msg.type !== 'pong' && msg.type !== 'ws-relay') {
Logger.debug("WS send:", msg)
}
this._socket.send(JSON.stringify(msg)); this._socket.send(JSON.stringify(msg));
} }
@ -223,7 +227,7 @@ class ServerConnection {
.addPeerIdToLocalStorage() .addPeerIdToLocalStorage()
.then(peerId => { .then(peerId => {
if (!peerId) return; if (!peerId) return;
console.log("successfully added peerId to localStorage"); Logger.debug("successfully added peerId to localStorage");
// Only now join rooms // Only now join rooms
Events.fire('join-ip-room'); Events.fire('join-ip-room');
@ -239,8 +243,8 @@ class ServerConnection {
_endpoint() { _endpoint() {
const protocol = location.protocol.startsWith('https') ? 'wss' : 'ws'; const protocol = location.protocol.startsWith('https') ? 'wss' : 'ws';
// Check whether the instance specifies another signaling server otherwise use the current instance for signaling // Check whether the instance specifies another signaling server otherwise use the current instance for signaling
let wsServerDomain = this._config.signalingServer let wsServerDomain = window._config.signalingServer
? this._config.signalingServer ? window._config.signalingServer
: location.host + location.pathname; : location.host + location.pathname;
let wsUrl = new URL(protocol + '://' + wsServerDomain + 'server'); let wsUrl = new URL(protocol + '://' + wsServerDomain + 'server');
@ -264,7 +268,7 @@ class ServerConnection {
BrowserTabsConnector BrowserTabsConnector
.removePeerIdFromLocalStorage(peerId) .removePeerIdFromLocalStorage(peerId)
.then(_ => { .then(_ => {
console.log("successfully removed peerId from localStorage"); Logger.debug("successfully removed peerId from localStorage");
}); });
if (!this._socket) return; if (!this._socket) return;
@ -277,7 +281,7 @@ class ServerConnection {
} }
_onDisconnect() { _onDisconnect() {
console.log('WS: server disconnected'); Logger.log('WS: server disconnected');
setTimeout(() => { setTimeout(() => {
this._isReconnect = true; this._isReconnect = true;
Events.fire('ws-disconnected'); Events.fire('ws-disconnected');
@ -303,7 +307,7 @@ class ServerConnection {
} }
_onError(e) { _onError(e) {
console.error(e); Logger.error(e);
} }
_reconnect() { _reconnect() {
@ -385,7 +389,9 @@ class Peer {
PersistentStorage PersistentStorage
.deleteRoomSecret(this._getPairSecret()) .deleteRoomSecret(this._getPairSecret())
.then(deletedRoomSecret => { .then(deletedRoomSecret => {
if (deletedRoomSecret) console.log("Successfully deleted duplicate room secret with same peer: ", deletedRoomSecret); if (deletedRoomSecret) {
Logger.debug("Successfully deleted duplicate room secret with same peer: ", deletedRoomSecret);
}
}); });
} }
@ -398,7 +404,7 @@ class Peer {
&& this._isCaller) { && this._isCaller) {
// increase security by initiating the increase of the roomSecret length // increase security by initiating the increase of the roomSecret length
// from 64 chars (<v1.7.0) to 256 chars (v1.7.0+) // from 64 chars (<v1.7.0) to 256 chars (v1.7.0+)
console.log('RoomSecret is regenerated to increase security') Logger.debug('RoomSecret is regenerated to increase security')
Events.fire('regenerate-room-secret', this._getPairSecret()); Events.fire('regenerate-room-secret', this._getPairSecret());
} }
} }
@ -467,7 +473,7 @@ class Peer {
try { try {
dataUrl = await getThumbnailAsDataUrl(files[0], 400, null, 0.9); dataUrl = await getThumbnailAsDataUrl(files[0], 400, null, 0.9);
} catch (e) { } catch (e) {
console.error(e); Logger.error(e);
} }
} }
@ -525,7 +531,7 @@ class Peer {
this._sendTransferAbortion(); this._sendTransferAbortion();
return; return;
} }
console.log("Resend requested from offset:", offset) Logger.debug("Resend requested from offset:", offset)
this._chunker._resendFromOffset(offset); this._chunker._resendFromOffset(offset);
} }
@ -570,7 +576,7 @@ class Peer {
this._onDisplayNameChanged(message); this._onDisplayNameChanged(message);
break; break;
default: default:
console.warn('RTC: Unknown message type:', message.type); Logger.warn('RTC: Unknown message type:', message.type);
} }
} }
@ -681,7 +687,7 @@ class Peer {
let size = Math.round(10 * fileBlob.size / 1000000) / 10; let size = Math.round(10 * fileBlob.size / 1000000) / 10;
let speed = Math.round(100 * fileBlob.size / 1000000 / duration) / 100; let speed = Math.round(100 * fileBlob.size / 1000000 / duration) / 100;
console.log(`File received.\n\nSize: ${size} MB\tDuration: ${duration} s\tSpeed: ${speed} MB/s`); Logger.log(`File received.\n\nSize: ${size} MB\tDuration: ${duration} s\tSpeed: ${speed} MB/s`);
this._sendMessage({type: 'file-transfer-complete', success: true, size: size, duration: duration, speed: speed}); this._sendMessage({type: 'file-transfer-complete', success: true, size: size, duration: duration, speed: speed});
@ -715,12 +721,12 @@ class Peer {
this._chunker = null; this._chunker = null;
if (!message.success) { if (!message.success) {
console.warn('File could not be sent'); 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: null});
return; return;
} }
console.log(`File sent.\n\nSize: ${message.size} MB\tDuration: ${message.duration} s\tSpeed: ${message.speed} MB/s`); Logger.log(`File sent.\n\nSize: ${message.size} MB\tDuration: ${message.duration} s\tSpeed: ${message.speed} MB/s`);
if (this._filesQueue.length) { if (this._filesQueue.length) {
this._dequeueFile(); this._dequeueFile();
@ -776,7 +782,7 @@ class Peer {
PersistentStorage PersistentStorage
.updateRoomSecretDisplayName(roomSecret, message.displayName) .updateRoomSecretDisplayName(roomSecret, message.displayName)
.then(roomSecretEntry => { .then(roomSecretEntry => {
console.log(`Successfully updated DisplayName for roomSecretEntry ${roomSecretEntry.key}`); Logger.debug(`Successfully updated DisplayName for roomSecretEntry ${roomSecretEntry.key}`);
}) })
} }
@ -855,7 +861,7 @@ class RTCPeer extends Peer {
this._evaluatePendingInboundMessages() this._evaluatePendingInboundMessages()
.then((count) => { .then((count) => {
if (count) { if (count) {
console.log("Pending inbound messages evaluated."); Logger.debug("Pending inbound messages evaluated.");
} }
}); });
} }
@ -874,36 +880,36 @@ class RTCPeer extends Peer {
} }
async _onNegotiationNeeded() { async _onNegotiationNeeded() {
console.log('RTC: Negotiation needed'); Logger.debug('RTC: Negotiation needed');
if (this._isCaller) { if (this._isCaller) {
// Creating offer if required // Creating offer if required
console.log('RTC: Creating offer'); Logger.debug('RTC: Creating offer');
const description = await this._conn.createOffer(); const description = await this._conn.createOffer();
await this._handleLocalDescription(description); await this._handleLocalDescription(description);
} }
} }
_onSignalingStateChanged() { _onSignalingStateChanged() {
console.log('RTC: Signaling state changed:', this._conn.signalingState); Logger.debug('RTC: Signaling state changed:', this._conn.signalingState);
} }
_onIceConnectionStateChange() { _onIceConnectionStateChange() {
console.log('RTC: ICE connection state changed:', this._conn.iceConnectionState); Logger.debug('RTC: ICE connection state changed:', this._conn.iceConnectionState);
} }
_onIceGatheringStateChanged() { _onIceGatheringStateChanged() {
console.log('RTC: ICE gathering state changed:', this._conn.iceConnectionState); Logger.debug('RTC: ICE gathering state changed:', this._conn.iceConnectionState);
} }
_onConnectionStateChange() { _onConnectionStateChange() {
console.log('RTC: Connection state changed:', this._conn.connectionState); Logger.debug('RTC: Connection state changed:', this._conn.connectionState);
switch (this._conn.connectionState) { switch (this._conn.connectionState) {
case 'disconnected': case 'disconnected':
this._refresh(); this._refresh();
break; break;
case 'failed': case 'failed':
console.warn('RTC connection failed'); Logger.warn('RTC connection failed');
// Todo: if error is "TURN server needed" -> fallback to WS if activated // Todo: if error is "TURN server needed" -> fallback to WS if activated
this._refresh(); this._refresh();
} }
@ -914,7 +920,7 @@ class RTCPeer extends Peer {
} }
_onIceCandidateError(error) { _onIceCandidateError(error) {
console.error(error); Logger.error(error);
} }
_openMessageChannel() { _openMessageChannel() {
@ -944,7 +950,7 @@ class RTCPeer extends Peer {
} }
_onChannelOpened(e) { _onChannelOpened(e) {
console.log(`RTC: Channel ${e.target.label} opened with`, this._peerId); Logger.debug(`RTC: Channel ${e.target.label} opened with`, this._peerId);
// wait until all channels are open // wait until all channels are open
if (!this._stable()) return; if (!this._stable()) return;
@ -962,30 +968,30 @@ class RTCPeer extends Peer {
} }
_onChannelClosed(e) { _onChannelClosed(e) {
console.log(`RTC: Channel ${e.target.label} closed`, this._peerId); Logger.debug(`RTC: Channel ${e.target.label} closed`, this._peerId);
this._refresh(); this._refresh();
} }
_onChannelError(e) { _onChannelError(e) {
console.warn(`RTC: Channel ${e.target.label} error`, this._peerId); Logger.warn(`RTC: Channel ${e.target.label} error`, this._peerId);
console.error(e.error); Logger.error(e.error);
} }
async _handleLocalDescription(localDescription) { async _handleLocalDescription(localDescription) {
await this._conn.setLocalDescription(localDescription); await this._conn.setLocalDescription(localDescription);
console.log("RTC: Sending local description"); Logger.debug("RTC: Sending local description");
this._sendSignal({ signalType: 'description', description: localDescription }); this._sendSignal({ signalType: 'description', description: localDescription });
} }
async _handleRemoteDescription(remoteDescription) { async _handleRemoteDescription(remoteDescription) {
console.log("RTC: Received remote description"); Logger.debug("RTC: Received remote description");
await this._conn.setRemoteDescription(remoteDescription); await this._conn.setRemoteDescription(remoteDescription);
if (!this._isCaller) { if (!this._isCaller) {
// Creating answer if required // Creating answer if required
console.log('RTC: Creating answer'); Logger.debug('RTC: Creating answer');
const localDescription = await this._conn.createAnswer(); const localDescription = await this._conn.createAnswer();
await this._handleLocalDescription(localDescription); await this._handleLocalDescription(localDescription);
} }
@ -994,7 +1000,7 @@ class RTCPeer extends Peer {
_handleLocalCandidate(candidate) { _handleLocalCandidate(candidate) {
if (this.localIceCandidatesSent) return; if (this.localIceCandidatesSent) return;
console.log("RTC: Local candidate created", candidate); Logger.debug("RTC: Local candidate created", candidate);
if (candidate === null) { if (candidate === null) {
this.localIceCandidatesSent = true; this.localIceCandidatesSent = true;
@ -1007,7 +1013,7 @@ class RTCPeer extends Peer {
async _handleRemoteCandidate(candidate) { async _handleRemoteCandidate(candidate) {
if (this.remoteIceCandidatesReceived) return; if (this.remoteIceCandidatesReceived) return;
console.log("RTC: Received remote candidate", candidate); Logger.debug("RTC: Received remote candidate", candidate);
if (candidate === null) { if (candidate === null) {
this.remoteIceCandidatesReceived = true; this.remoteIceCandidatesReceived = true;
@ -1021,7 +1027,7 @@ class RTCPeer extends Peer {
let inboundMessagesEvaluatedCount = 0; let inboundMessagesEvaluatedCount = 0;
while (this.pendingInboundMessages.length > 0) { while (this.pendingInboundMessages.length > 0) {
const message = this.pendingInboundMessages.shift(); const message = this.pendingInboundMessages.shift();
console.log("Evaluate pending inbound message:", message); Logger.debug("Evaluate pending inbound message:", message);
await this._onServerSignalMessage(message); await this._onServerSignalMessage(message);
inboundMessagesEvaluatedCount++; inboundMessagesEvaluatedCount++;
} }
@ -1042,7 +1048,7 @@ class RTCPeer extends Peer {
await this._handleRemoteCandidate(message.candidate); await this._handleRemoteCandidate(message.candidate);
break; break;
default: default:
console.warn('Unknown signalType:', message.signalType); Logger.warn('Unknown signalType:', message.signalType);
break; break;
} }
} }
@ -1115,7 +1121,7 @@ class RTCPeer extends Peer {
} }
_sendViaMessageChannel(message) { _sendViaMessageChannel(message) {
console.log('RTC Send:', message); Logger.debug('RTC Send:', message);
this._messageChannel.send(JSON.stringify(message)); this._messageChannel.send(JSON.stringify(message));
} }
@ -1147,12 +1153,11 @@ class RTCPeer extends Peer {
} }
_onMessage(message) { _onMessage(message) {
// Todo: Test speed increase without prints? --> print only on debug mode via URL argument `?debug_mode=true` Logger.debug('RTC Receive:', JSON.parse(message));
console.log('RTC Receive:', JSON.parse(message));
try { try {
message = JSON.parse(message); message = JSON.parse(message);
} catch (e) { } catch (e) {
console.warn("RTCPeer: Received JSON is malformed"); Logger.warn("RTCPeer: Received JSON is malformed");
return; return;
} }
super._onMessage(message); super._onMessage(message);
@ -1255,7 +1260,7 @@ class WSPeer extends Peer {
} }
_onMessage(message) { _onMessage(message) {
console.log('WS Receive:', message); Logger.debug('WS Receive:', message);
super._onMessage(message); super._onMessage(message);
} }
@ -1273,7 +1278,7 @@ class WSPeer extends Peer {
message = JSON.parse(message).message; message = JSON.parse(message).message;
} }
catch (e) { catch (e) {
console.warn("WSPeer: Received JSON is malformed"); Logger.warn("WSPeer: Received JSON is malformed");
return; return;
} }
@ -1383,7 +1388,7 @@ class PeersManager {
this.peers[peerId] = new WSPeer(this._server, isCaller, peerId, roomType, roomId); this.peers[peerId] = new WSPeer(this._server, isCaller, peerId, roomType, roomId);
} }
else { else {
console.warn("Websocket fallback is not activated on this instance.\n" + Logger.warn("Websocket fallback is not activated on this instance.\n" +
"Activate WebRTC in this browser or ask the admin of this instance to activate the websocket fallback.") "Activate WebRTC in this browser or ask the admin of this instance to activate the websocket fallback.")
} }
} }
@ -1423,7 +1428,7 @@ class PeersManager {
_onPeerLeft(message) { _onPeerLeft(message) {
if (this._peerExists(message.peerId) && !this._webRtcSupported(message.peerId)) { if (this._peerExists(message.peerId) && !this._webRtcSupported(message.peerId)) {
console.log('WSPeer left:', message.peerId); Logger.debug('WSPeer left:', message.peerId);
} }
if (message.disconnect === true) { if (message.disconnect === true) {
// if user actively disconnected from PairDrop server, disconnect all peer to peer connections immediately // if user actively disconnected from PairDrop server, disconnect all peer to peer connections immediately
@ -1436,7 +1441,7 @@ class PeersManager {
.removeOtherPeerIdsFromLocalStorage() .removeOtherPeerIdsFromLocalStorage()
.then(peerIds => { .then(peerIds => {
if (!peerIds) return; if (!peerIds) return;
console.log("successfully removed other peerIds from localStorage"); Logger.debug("successfully removed other peerIds from localStorage");
}); });
} }
} }
@ -1514,7 +1519,7 @@ class PeersManager {
PersistentStorage PersistentStorage
.updateRoomSecret(message.oldRoomSecret, message.newRoomSecret) .updateRoomSecret(message.oldRoomSecret, message.newRoomSecret)
.then(_ => { .then(_ => {
console.log("successfully regenerated room secret"); Logger.debug("successfully regenerated room secret");
Events.fire("room-secrets", [message.newRoomSecret]); Events.fire("room-secrets", [message.newRoomSecret]);
}) })
} }

View file

@ -7,19 +7,18 @@ class PersistentStorage {
const DBOpenRequest = window.indexedDB.open('pairdrop_store', 5); const DBOpenRequest = window.indexedDB.open('pairdrop_store', 5);
DBOpenRequest.onerror = e => { DBOpenRequest.onerror = e => {
PersistentStorage.logBrowserNotCapable(); PersistentStorage.logBrowserNotCapable();
console.log('Error initializing database: '); Logger.error('Error initializing database:', e);
console.log(e)
}; };
DBOpenRequest.onsuccess = _ => { DBOpenRequest.onsuccess = _ => {
console.log('Database initialised.'); Logger.debug('Database initialised.');
}; };
DBOpenRequest.onupgradeneeded = async e => { DBOpenRequest.onupgradeneeded = async e => {
const db = e.target.result; const db = e.target.result;
const txn = e.target.transaction; const txn = e.target.transaction;
db.onerror = e => console.log('Error loading database: ' + e); db.onerror = e => Logger.error('Error loading database:', e);
console.log(`Upgrading IndexedDB database from version ${e.oldVersion} to version ${e.newVersion}`); Logger.debug(`Upgrading IndexedDB database from version ${e.oldVersion} to version ${e.newVersion}`);
if (e.oldVersion === 0) { if (e.oldVersion === 0) {
// initiate v1 // initiate v1
@ -54,7 +53,7 @@ class PersistentStorage {
} }
static logBrowserNotCapable() { static logBrowserNotCapable() {
console.log("This browser does not support IndexedDB. Paired devices will be gone after the browser is closed."); Logger.log("This browser does not support IndexedDB. Paired devices will be gone after the browser is closed.");
} }
static set(key, value) { static set(key, value) {
@ -66,7 +65,7 @@ class PersistentStorage {
const objectStore = transaction.objectStore('keyval'); const objectStore = transaction.objectStore('keyval');
const objectStoreRequest = objectStore.put(value, key); const objectStoreRequest = objectStore.put(value, key);
objectStoreRequest.onsuccess = _ => { objectStoreRequest.onsuccess = _ => {
console.log(`Request successful. Added key-pair: ${key} - ${value}`); Logger.debug(`Request successful. Added key-pair: ${key} - ${value}`);
resolve(value); resolve(value);
}; };
} }
@ -85,7 +84,7 @@ class PersistentStorage {
const objectStore = transaction.objectStore('keyval'); const objectStore = transaction.objectStore('keyval');
const objectStoreRequest = objectStore.get(key); const objectStoreRequest = objectStore.get(key);
objectStoreRequest.onsuccess = _ => { objectStoreRequest.onsuccess = _ => {
console.log(`Request successful. Retrieved key-pair: ${key} - ${objectStoreRequest.result}`); Logger.debug(`Request successful. Retrieved key-pair: ${key} - ${objectStoreRequest.result}`);
resolve(objectStoreRequest.result); resolve(objectStoreRequest.result);
} }
} }
@ -104,7 +103,7 @@ class PersistentStorage {
const objectStore = transaction.objectStore('keyval'); const objectStore = transaction.objectStore('keyval');
const objectStoreRequest = objectStore.delete(key); const objectStoreRequest = objectStore.delete(key);
objectStoreRequest.onsuccess = _ => { objectStoreRequest.onsuccess = _ => {
console.log(`Request successful. Deleted key: ${key}`); Logger.debug(`Request successful. Deleted key: ${key}`);
resolve(); resolve();
}; };
} }
@ -128,7 +127,7 @@ class PersistentStorage {
'auto_accept': false 'auto_accept': false
}); });
objectStoreRequest.onsuccess = e => { objectStoreRequest.onsuccess = e => {
console.log(`Request successful. RoomSecret added: ${e.target.result}`); Logger.debug(`Request successful. RoomSecret added: ${e.target.result}`);
resolve(); resolve();
} }
} }
@ -145,7 +144,7 @@ class PersistentStorage {
for (let i = 0; i < roomSecrets.length; i++) { for (let i = 0; i < roomSecrets.length; i++) {
secrets.push(roomSecrets[i].secret); secrets.push(roomSecrets[i].secret);
} }
console.log(`Request successful. Retrieved ${secrets.length} room_secrets`); Logger.debug(`Request successful. Retrieved ${secrets.length} room_secrets`);
return(secrets); return(secrets);
} catch (e) { } catch (e) {
this.logBrowserNotCapable(); this.logBrowserNotCapable();
@ -182,13 +181,13 @@ class PersistentStorage {
objectStoreRequestKey.onsuccess = e => { objectStoreRequestKey.onsuccess = e => {
const key = e.target.result; const key = e.target.result;
if (!key) { if (!key) {
console.log(`Nothing to retrieve. Entry for room_secret not existing: ${roomSecret}`); Logger.debug(`Nothing to retrieve. Entry for room_secret not existing: ${roomSecret}`);
resolve(); resolve();
return; return;
} }
const objectStoreRequestRetrieval = objectStore.get(key); const objectStoreRequestRetrieval = objectStore.get(key);
objectStoreRequestRetrieval.onsuccess = e => { objectStoreRequestRetrieval.onsuccess = e => {
console.log(`Request successful. Retrieved entry for room_secret: ${key}`); Logger.debug(`Request successful. Retrieved entry for room_secret: ${key}`);
resolve({ resolve({
"entry": e.target.result, "entry": e.target.result,
"key": key "key": key
@ -215,14 +214,14 @@ class PersistentStorage {
const objectStoreRequestKey = objectStore.index("secret").getKey(roomSecret); const objectStoreRequestKey = objectStore.index("secret").getKey(roomSecret);
objectStoreRequestKey.onsuccess = e => { objectStoreRequestKey.onsuccess = e => {
if (!e.target.result) { if (!e.target.result) {
console.log(`Nothing to delete. room_secret not existing: ${roomSecret}`); Logger.debug(`Nothing to delete. room_secret not existing: ${roomSecret}`);
resolve(); resolve();
return; return;
} }
const key = e.target.result; const key = e.target.result;
const objectStoreRequestDeletion = objectStore.delete(key); const objectStoreRequestDeletion = objectStore.delete(key);
objectStoreRequestDeletion.onsuccess = _ => { objectStoreRequestDeletion.onsuccess = _ => {
console.log(`Request successful. Deleted room_secret: ${key}`); Logger.debug(`Request successful. Deleted room_secret: ${key}`);
resolve(roomSecret); resolve(roomSecret);
} }
objectStoreRequestDeletion.onerror = e => { objectStoreRequestDeletion.onerror = e => {
@ -245,7 +244,7 @@ class PersistentStorage {
const objectStore = transaction.objectStore('room_secrets'); const objectStore = transaction.objectStore('room_secrets');
const objectStoreRequest = objectStore.clear(); const objectStoreRequest = objectStore.clear();
objectStoreRequest.onsuccess = _ => { objectStoreRequest.onsuccess = _ => {
console.log('Request successful. All room_secrets cleared'); Logger.debug('Request successful. All room_secrets cleared');
resolve(); resolve();
}; };
} }
@ -287,7 +286,7 @@ class PersistentStorage {
const objectStoreRequestUpdate = objectStore.put(updatedRoomSecretEntry, roomSecretEntry.key); const objectStoreRequestUpdate = objectStore.put(updatedRoomSecretEntry, roomSecretEntry.key);
objectStoreRequestUpdate.onsuccess = e => { objectStoreRequestUpdate.onsuccess = e => {
console.log(`Request successful. Updated room_secret: ${roomSecretEntry.key}`); Logger.debug(`Request successful. Updated room_secret: ${roomSecretEntry.key}`);
resolve({ resolve({
"entry": updatedRoomSecretEntry, "entry": updatedRoomSecretEntry,
"key": roomSecretEntry.key "key": roomSecretEntry.key

View file

@ -238,7 +238,7 @@ class FooterUI {
if (!displayName) return; if (!displayName) return;
console.log("Retrieved edited display name:", displayName) Logger.debug("Retrieved edited display name:", displayName)
Events.fire('self-display-name-changed', displayName); Events.fire('self-display-name-changed', displayName);
} }
@ -275,7 +275,7 @@ class FooterUI {
Events.fire('notify-user', Localization.getTranslation("notifications.display-name-changed-permanently")); Events.fire('notify-user', Localization.getTranslation("notifications.display-name-changed-permanently"));
}) })
.catch(_ => { .catch(_ => {
console.log("This browser does not support IndexedDB. Use localStorage instead."); Logger.debug("This browser does not support IndexedDB. Use localStorage instead.");
localStorage.setItem('edited_display_name', newDisplayName); localStorage.setItem('edited_display_name', newDisplayName);
Events.fire('notify-user', Localization.getTranslation("notifications.display-name-changed-temporarily")); Events.fire('notify-user', Localization.getTranslation("notifications.display-name-changed-temporarily"));
}) })
@ -287,7 +287,7 @@ class FooterUI {
else { else {
PersistentStorage.delete('edited_display_name') PersistentStorage.delete('edited_display_name')
.catch(_ => { .catch(_ => {
console.log("This browser does not support IndexedDB. Use localStorage instead.") Logger.debug("This browser does not support IndexedDB. Use localStorage instead.")
localStorage.removeItem('edited_display_name'); localStorage.removeItem('edited_display_name');
}) })
.finally(() => { .finally(() => {

View file

@ -181,7 +181,7 @@ class PeersUI {
PersistentStorage PersistentStorage
.updateRoomSecretDisplayName(roomSecret, displayName) .updateRoomSecretDisplayName(roomSecret, displayName)
.then(roomSecretEntry => { .then(roomSecretEntry => {
console.log(`Successfully updated DisplayName for roomSecretEntry ${roomSecretEntry.key}`); Logger.debug(`Successfully updated DisplayName for roomSecretEntry ${roomSecretEntry.key}`);
}) })
} }
@ -306,7 +306,7 @@ class PeersUI {
this.$shareModeImageThumb.removeAttribute('hidden'); this.$shareModeImageThumb.removeAttribute('hidden');
} catch (e) { } catch (e) {
console.error(e); Logger.error(e);
this.$shareModeFileThumb.removeAttribute('hidden'); this.$shareModeFileThumb.removeAttribute('hidden');
} }
} else { } else {
@ -338,7 +338,7 @@ class PeersUI {
this.shareMode.files = files; this.shareMode.files = files;
this.shareMode.text = text; this.shareMode.text = text;
console.log('Share mode activated.'); Logger.debug('Share mode activated.');
Events.fire('share-mode-changed', { Events.fire('share-mode-changed', {
active: true, active: true,
@ -386,7 +386,7 @@ class PeersUI {
this.$shareModeEditBtn.removeEventListener('click', this._editShareTextCallback); this.$shareModeEditBtn.removeEventListener('click', this._editShareTextCallback);
this.$shareModeEditBtn.setAttribute('hidden', true); this.$shareModeEditBtn.setAttribute('hidden', true);
console.log('Share mode deactivated.') Logger.debug('Share mode deactivated.')
Events.fire('share-mode-changed', { active: false }); Events.fire('share-mode-changed', { active: false });
} }
@ -1062,7 +1062,7 @@ class ReceiveFileDialog extends ReceiveDialog {
this.$shareBtn.onclick = _ => { this.$shareBtn.onclick = _ => {
navigator.share({files: files}) navigator.share({files: files})
.catch(err => { .catch(err => {
console.error(err); Logger.error(err);
}); });
} }
} }
@ -1099,7 +1099,7 @@ class ReceiveFileDialog extends ReceiveDialog {
minutes = minutes.length < 2 ? "0" + minutes : minutes; minutes = minutes.length < 2 ? "0" + minutes : minutes;
filenameDownload = `PairDrop_files_${year+month+date}_${hours+minutes}.zip`; filenameDownload = `PairDrop_files_${year+month+date}_${hours+minutes}.zip`;
} catch (e) { } catch (e) {
console.error(e); Logger.error(e);
downloadZipped = false; downloadZipped = false;
} }
} }
@ -1148,10 +1148,10 @@ class ReceiveFileDialog extends ReceiveDialog {
this.createPreviewElement(files[0]) this.createPreviewElement(files[0])
.then(canPreview => { .then(canPreview => {
if (canPreview) { if (canPreview) {
console.log('the file is able to preview'); Logger.debug('the file is able to preview');
} }
else { else {
console.log('the file is not able to preview'); Logger.debug('the file is not able to preview');
} }
}) })
.catch(r => console.error(r)); .catch(r => console.error(r));
@ -2291,7 +2291,7 @@ class Base64Dialog extends Dialog {
this.$pasteBtn.addEventListener('click', _ => this._clickCallback()); this.$pasteBtn.addEventListener('click', _ => this._clickCallback());
} }
else { else {
console.log("`navigator.clipboard.readText()` is not available on your browser.\nOn Firefox you can set `dom.events.asyncClipboard.readText` to true under `about:config` for convenience.") Logger.log("`navigator.clipboard.readText()` is not available on your browser.\nOn Firefox you can set `dom.events.asyncClipboard.readText` to true under `about:config` for convenience.")
this.$pasteBtn.setAttribute('hidden', true); this.$pasteBtn.setAttribute('hidden', true);
this.$fallbackTextarea.setAttribute('placeholder', Localization.getTranslation("dialogs.base64-paste-to-send", null, {type: translateType})); this.$fallbackTextarea.setAttribute('placeholder', Localization.getTranslation("dialogs.base64-paste-to-send", null, {type: translateType}));
this.$fallbackTextarea.removeAttribute('hidden'); this.$fallbackTextarea.removeAttribute('hidden');
@ -2323,7 +2323,7 @@ class Base64Dialog extends Dialog {
} }
catch(e) { catch(e) {
Events.fire('notify-user', Localization.getTranslation("notifications.clipboard-content-incorrect")); Events.fire('notify-user', Localization.getTranslation("notifications.clipboard-content-incorrect"));
console.log("Clipboard content is incorrect.") Logger.warn("Clipboard content is incorrect.")
} }
this.hide(); this.hide();
} }
@ -2342,7 +2342,7 @@ class Base64Dialog extends Dialog {
} }
catch (e) { catch (e) {
Events.fire('notify-user', Localization.getTranslation("notifications.text-content-incorrect")); Events.fire('notify-user', Localization.getTranslation("notifications.text-content-incorrect"));
console.log("Text content incorrect."); Logger.warn("Text content incorrect.");
} }
this.hide(); this.hide();
@ -2357,7 +2357,7 @@ class Base64Dialog extends Dialog {
} }
catch (e) { catch (e) {
Events.fire('notify-user', Localization.getTranslation("notifications.file-content-incorrect")); Events.fire('notify-user', Localization.getTranslation("notifications.file-content-incorrect"));
console.log("File content incorrect."); Logger.warn("File content incorrect.");
} }
this.hide(); this.hide();
@ -2380,10 +2380,11 @@ class AboutUI {
this.$blueskyBtn = $('bluesky-btn'); this.$blueskyBtn = $('bluesky-btn');
this.$customBtn = $('custom-btn'); this.$customBtn = $('custom-btn');
this.$privacypolicyBtn = $('privacypolicy-btn'); this.$privacypolicyBtn = $('privacypolicy-btn');
Events.on('config', e => this._onConfig(e.detail.buttons)); Events.on('config-loaded', _ => this._onConfigLoaded());
} }
async _onConfig(btnConfig) { async _onConfigLoaded() {
const btnConfig = window._config.buttons
await this._evaluateBtnConfig(this.$donationBtn, btnConfig.donation_button); await this._evaluateBtnConfig(this.$donationBtn, btnConfig.donation_button);
await this._evaluateBtnConfig(this.$twitterBtn, btnConfig.twitter_button); await this._evaluateBtnConfig(this.$twitterBtn, btnConfig.twitter_button);
await this._evaluateBtnConfig(this.$mastodonBtn, btnConfig.mastodon_button); await this._evaluateBtnConfig(this.$mastodonBtn, btnConfig.mastodon_button);
@ -2674,7 +2675,7 @@ class WebFileHandlersUI {
if (!"launchQueue" in window) return; if (!"launchQueue" in window) return;
launchQueue.setConsumer(async launchParams => { launchQueue.setConsumer(async launchParams => {
console.log("Launched with: ", launchParams); Logger.log("Launched with: ", launchParams);
if (!launchParams.files.length) return; if (!launchParams.files.length) return;

View file

@ -539,7 +539,7 @@ function getThumbnailAsDataUrl(file, width = undefined, height = undefined, qual
let dataUrl = canvas.toDataURL("image/jpeg", quality); let dataUrl = canvas.toDataURL("image/jpeg", quality);
resolve(dataUrl); resolve(dataUrl);
} catch (e) { } catch (e) {
console.error(e); Logger.error(e);
reject(new Error(`Could not create an image thumbnail from type ${file.type}`)); reject(new Error(`Could not create an image thumbnail from type ${file.type}`));
} }
}) })