diff --git a/openvidu-browser/src/OpenVidu/Connection.ts b/openvidu-browser/src/OpenVidu/Connection.ts index 4a13ce0c..87776d15 100644 --- a/openvidu-browser/src/OpenVidu/Connection.ts +++ b/openvidu-browser/src/OpenVidu/Connection.ts @@ -20,6 +20,12 @@ import { Stream } from './Stream'; import { ConnectionOptions } from '../OpenViduInternal/Interfaces/Private/ConnectionOptions'; import { InboundStreamOptions } from '../OpenViduInternal/Interfaces/Private/InboundStreamOptions'; import { StreamOptionsServer } from '../OpenViduInternal/Interfaces/Private/StreamOptionsServer'; +import { OpenViduLogger } from '../OpenViduInternal/Logger/OpenViduLogger'; + +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); /** @@ -85,7 +91,7 @@ export class Connection { // Connection is local msg += '(local)'; } - console.info(msg); + logger.info(msg); } @@ -96,7 +102,7 @@ export class Connection { */ sendIceCandidate(candidate: RTCIceCandidate): void { - console.debug((!!this.stream.outboundStreamOpts ? 'Local' : 'Remote') + 'candidate for' + + logger.debug((!!this.stream.outboundStreamOpts ? 'Local' : 'Remote') + 'candidate for' + this.connectionId, candidate); this.session.openvidu.sendRequest('onIceCandidate', { @@ -106,7 +112,7 @@ export class Connection { sdpMLineIndex: candidate.sdpMLineIndex }, (error, response) => { if (error) { - console.error('Error sending ICE candidate: ' + logger.error('Error sending ICE candidate: ' + JSON.stringify(error)); } }); @@ -138,7 +144,7 @@ export class Connection { this.addStream(stream); }); - console.info("Remote 'Connection' with 'connectionId' [" + this.connectionId + '] is now configured for receiving Streams with options: ', this.stream.inboundStreamOpts); + logger.info("Remote 'Connection' with 'connectionId' [" + this.connectionId + '] is now configured for receiving Streams with options: ', this.stream.inboundStreamOpts); } /** diff --git a/openvidu-browser/src/OpenVidu/EventDispatcher.ts b/openvidu-browser/src/OpenVidu/EventDispatcher.ts index dbb5984d..726a0d93 100644 --- a/openvidu-browser/src/OpenVidu/EventDispatcher.ts +++ b/openvidu-browser/src/OpenVidu/EventDispatcher.ts @@ -17,6 +17,12 @@ import { Event as Event } from '../OpenViduInternal/Events/Event'; import EventEmitter = require('wolfy87-eventemitter'); +import { OpenViduLogger } from '../OpenViduInternal/Logger/OpenViduLogger'; + +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); export abstract class EventDispatcher { @@ -68,9 +74,9 @@ export abstract class EventDispatcher { onAux(type: string, message: string, handler: (event: Event) => void): EventDispatcher { const arrowHandler = event => { if (event) { - console.info(message, event); + logger.info(message, event); } else { - console.info(message); + logger.info(message); } handler(event); }; @@ -85,9 +91,9 @@ export abstract class EventDispatcher { onceAux(type: string, message: string, handler: (event: Event) => void): EventDispatcher { const arrowHandler = event => { if (event) { - console.info(message, event); + logger.info(message, event); } else { - console.info(message); + logger.info(message); } handler(event); // Remove handler from map after first and only execution diff --git a/openvidu-browser/src/OpenVidu/Filter.ts b/openvidu-browser/src/OpenVidu/Filter.ts index b045fba7..134c56c4 100644 --- a/openvidu-browser/src/OpenVidu/Filter.ts +++ b/openvidu-browser/src/OpenVidu/Filter.ts @@ -20,7 +20,12 @@ import { FilterEvent } from '../OpenViduInternal/Events/FilterEvent'; import { StreamPropertyChangedEvent } from '../OpenViduInternal/Events/StreamPropertyChangedEvent'; import { OpenViduError, OpenViduErrorName } from '../OpenViduInternal/Enums/OpenViduError'; import { ObjMap } from '../OpenViduInternal/Interfaces/Private/ObjMap'; +import { OpenViduLogger } from '../OpenViduInternal/Logger/OpenViduLogger'; +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); /** * **WARNING**: experimental option. This interface may change in the near future @@ -67,6 +72,7 @@ export class Filter { * @hidden */ stream: Stream; + private logger: OpenViduLogger; /** @@ -86,14 +92,14 @@ export class Filter { */ execMethod(method: string, params: Object): Promise { return new Promise((resolve, reject) => { - console.info('Executing filter method to stream ' + this.stream.streamId); + logger.info('Executing filter method to stream ' + this.stream.streamId); let stringParams; if (typeof params !== 'string') { try { stringParams = JSON.stringify(params); } catch (error) { const errorMsg = "'params' property must be a JSON formatted object"; - console.error(errorMsg); + logger.error(errorMsg); reject(errorMsg); } } else { @@ -104,14 +110,14 @@ export class Filter { { streamId: this.stream.streamId, method, params: stringParams }, (error, response) => { if (error) { - console.error('Error executing filter method for Stream ' + this.stream.streamId, error); + logger.error('Error executing filter method for Stream ' + this.stream.streamId, error); if (error.code === 401) { reject(new OpenViduError(OpenViduErrorName.OPENVIDU_PERMISSION_DENIED, "You don't have permissions to execute a filter method")); } else { reject(error); } } else { - console.info('Filter method successfully executed on Stream ' + this.stream.streamId); + logger.info('Filter method successfully executed on Stream ' + this.stream.streamId); const oldValue = (Object).assign({}, this.stream.filter); this.stream.filter.lastExecMethod = { method, params: JSON.parse(stringParams) }; this.stream.session.emitEvent('streamPropertyChanged', [new StreamPropertyChangedEvent(this.stream.session, this.stream, 'filter', this.stream.filter, oldValue, 'execFilterMethod')]); @@ -134,13 +140,13 @@ export class Filter { */ addEventListener(eventType: string, handler: (event: FilterEvent) => void): Promise { return new Promise((resolve, reject) => { - console.info('Adding filter event listener to event ' + eventType + ' to stream ' + this.stream.streamId); + logger.info('Adding filter event listener to event ' + eventType + ' to stream ' + this.stream.streamId); this.stream.session.openvidu.sendRequest( 'addFilterEventListener', { streamId: this.stream.streamId, eventType }, (error, response) => { if (error) { - console.error('Error adding filter event listener to event ' + eventType + 'for Stream ' + this.stream.streamId, error); + logger.error('Error adding filter event listener to event ' + eventType + 'for Stream ' + this.stream.streamId, error); if (error.code === 401) { reject(new OpenViduError(OpenViduErrorName.OPENVIDU_PERMISSION_DENIED, "You don't have permissions to add a filter event listener")); } else { @@ -148,7 +154,7 @@ export class Filter { } } else { this.handlers[eventType] = handler; - console.info('Filter event listener to event ' + eventType + ' successfully applied on Stream ' + this.stream.streamId); + logger.info('Filter event listener to event ' + eventType + ' successfully applied on Stream ' + this.stream.streamId); resolve(); } } @@ -166,13 +172,13 @@ export class Filter { */ removeEventListener(eventType: string): Promise { return new Promise((resolve, reject) => { - console.info('Removing filter event listener to event ' + eventType + ' to stream ' + this.stream.streamId); + logger.info('Removing filter event listener to event ' + eventType + ' to stream ' + this.stream.streamId); this.stream.session.openvidu.sendRequest( 'removeFilterEventListener', { streamId: this.stream.streamId, eventType }, (error, response) => { if (error) { - console.error('Error removing filter event listener to event ' + eventType + 'for Stream ' + this.stream.streamId, error); + logger.error('Error removing filter event listener to event ' + eventType + 'for Stream ' + this.stream.streamId, error); if (error.code === 401) { reject(new OpenViduError(OpenViduErrorName.OPENVIDU_PERMISSION_DENIED, "You don't have permissions to add a filter event listener")); } else { @@ -180,7 +186,7 @@ export class Filter { } } else { delete this.handlers[eventType]; - console.info('Filter event listener to event ' + eventType + ' successfully removed on Stream ' + this.stream.streamId); + logger.info('Filter event listener to event ' + eventType + ' successfully removed on Stream ' + this.stream.streamId); resolve(); } } diff --git a/openvidu-browser/src/OpenVidu/LocalRecorder.ts b/openvidu-browser/src/OpenVidu/LocalRecorder.ts index 3dcc8ea5..958cd913 100644 --- a/openvidu-browser/src/OpenVidu/LocalRecorder.ts +++ b/openvidu-browser/src/OpenVidu/LocalRecorder.ts @@ -18,12 +18,17 @@ import { Stream } from './Stream'; import { LocalRecorderState } from '../OpenViduInternal/Enums/LocalRecorderState'; import platform = require('platform'); +import { OpenViduLogger } from '../OpenViduInternal/Logger/OpenViduLogger'; /** * @hidden */ declare var MediaRecorder: any; +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); /** @@ -57,23 +62,23 @@ export class LocalRecorder { /** * Starts the recording of the Stream. [[state]] property must be `READY`. After method succeeds is set to `RECORDING` - * + * * @param mimeType The [MediaRecorder.mimeType](https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/mimeType) to be used to record this Stream. * Make sure the platform supports it or the promise will return an error. If this parameter is not provided, the MediaRecorder will use the default codecs available in the platform - * + * * @returns A Promise (to which you can optionally subscribe to) that is resolved if the recording successfully started and rejected with an Error object if not */ record(mimeType?: string): Promise { return new Promise((resolve, reject) => { try { if (typeof MediaRecorder === 'undefined') { - console.error('MediaRecorder not supported on your browser. See compatibility in https://caniuse.com/#search=MediaRecorder'); + logger.error('MediaRecorder not supported on your browser. See compatibility in https://caniuse.com/#search=MediaRecorder'); throw (Error('MediaRecorder not supported on your browser. See compatibility in https://caniuse.com/#search=MediaRecorder')); } if (this.state !== LocalRecorderState.READY) { throw (Error('\'LocalRecord.record()\' needs \'LocalRecord.state\' to be \'READY\' (current value: \'' + this.state + '\'). Call \'LocalRecorder.clean()\' or init a new LocalRecorder before')); } - console.log("Starting local recording of stream '" + this.stream.streamId + "' of connection '" + this.connectionId + "'"); + logger.log("Starting local recording of stream '" + this.stream.streamId + "' of connection '" + this.connectionId + "'"); let options = {}; if (typeof MediaRecorder.isTypeSupported === 'function') { @@ -83,10 +88,10 @@ export class LocalRecorder { } options = { mimeType }; } else { - console.log('No mimeType parameter provided. Using default codecs'); + logger.log('No mimeType parameter provided. Using default codecs'); } } else { - console.warn('MediaRecorder#isTypeSupported is not supported. Using default codecs'); + logger.warn('MediaRecorder#isTypeSupported is not supported. Using default codecs'); } this.mediaRecorder = new MediaRecorder(this.stream.getMediaStream(), options); @@ -101,11 +106,11 @@ export class LocalRecorder { }; this.mediaRecorder.onerror = (e) => { - console.error('MediaRecorder error: ', e); + logger.error('MediaRecorder error: ', e); }; this.mediaRecorder.onstart = () => { - console.log('MediaRecorder started (state=' + this.mediaRecorder.state + ')'); + logger.log('MediaRecorder started (state=' + this.mediaRecorder.state + ')'); }; this.mediaRecorder.onstop = () => { @@ -113,15 +118,15 @@ export class LocalRecorder { }; this.mediaRecorder.onpause = () => { - console.log('MediaRecorder paused (state=' + this.mediaRecorder.state + ')'); + logger.log('MediaRecorder paused (state=' + this.mediaRecorder.state + ')'); }; this.mediaRecorder.onresume = () => { - console.log('MediaRecorder resumed (state=' + this.mediaRecorder.state + ')'); + logger.log('MediaRecorder resumed (state=' + this.mediaRecorder.state + ')'); }; this.mediaRecorder.onwarning = (e) => { - console.log('MediaRecorder warning: ' + e); + logger.log('MediaRecorder warning: ' + e); }; this.state = LocalRecorderState.RECORDING; @@ -361,7 +366,7 @@ export class LocalRecorder { /* Private methods */ private onStopDefault(): void { - console.log('MediaRecorder stopped (state=' + this.mediaRecorder.state + ')'); + logger.log('MediaRecorder stopped (state=' + this.mediaRecorder.state + ')'); this.blob = new Blob(this.chunks, { type: 'video/webm' }); this.chunks = []; diff --git a/openvidu-browser/src/OpenVidu/OpenVidu.ts b/openvidu-browser/src/OpenVidu/OpenVidu.ts index 9091a9d9..8d44515e 100644 --- a/openvidu-browser/src/OpenVidu/OpenVidu.ts +++ b/openvidu-browser/src/OpenVidu/OpenVidu.ts @@ -26,6 +26,7 @@ import { PublisherProperties } from '../OpenViduInternal/Interfaces/Public/Publi import { CustomMediaStreamConstraints } from '../OpenViduInternal/Interfaces/Private/CustomMediaStreamConstraints'; import { OpenViduError, OpenViduErrorName } from '../OpenViduInternal/Enums/OpenViduError'; import { VideoInsertMode } from '../OpenViduInternal/Enums/VideoInsertMode'; +import { OpenViduLogger } from '../OpenViduInternal/Logger/OpenViduLogger'; import * as screenSharingAuto from '../OpenViduInternal/ScreenSharing/Screen-Capturing-Auto'; import * as screenSharing from '../OpenViduInternal/ScreenSharing/Screen-Capturing'; @@ -54,6 +55,10 @@ const packageJson = require('../../package.json'); * @hidden */ declare var cordova: any; +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); /** * Entrypoint of OpenVidu Browser library. @@ -114,9 +119,8 @@ export class OpenVidu { constructor() { this.libraryVersion = packageJson.version; - - console.info("'OpenVidu' initialized"); - console.info("openvidu-browser version: " + this.libraryVersion); + logger.info("'OpenVidu' initialized"); + logger.info("openvidu-browser version: " + this.libraryVersion); if (platform.os!!.family === 'iOS' || platform.os!!.family === 'Android') { // Listen to orientationchange only on mobile devices @@ -175,7 +179,7 @@ export class OpenVidu { }, (error, response) => { if (error) { - console.error("Error sending 'streamPropertyChanged' event", error); + logger.error("Error sending 'streamPropertyChanged' event", error); } else { this.session.emitEvent('streamPropertyChanged', [new StreamPropertyChangedEvent(this.session, publisher.stream, 'videoDimensions', publisher.stream.videoDimensions, { width: oldWidth, height: oldHeight }, 'deviceRotated')]); publisher.emitEvent('streamPropertyChanged', [new StreamPropertyChangedEvent(publisher, publisher.stream, 'videoDimensions', publisher.stream.videoDimensions, { width: oldWidth, height: oldHeight }, 'deviceRotated')]); @@ -476,7 +480,7 @@ export class OpenVidu { resolve(devices); } }).catch((error) => { - console.error('Error getting devices', error); + logger.error('Error getting devices', error); reject(error); }); }); @@ -641,10 +645,7 @@ export class OpenVidu { * Disable all logging except error level */ enableProdMode(): void { - console.log = () => { }; - console.debug = () => { }; - console.info = () => { }; - console.warn = () => { }; + logger.enableProdMode(); } /* tslint:enable:no-empty */ @@ -758,7 +759,7 @@ export class OpenVidu { if (!this.checkScreenSharingCapabilities()) { const error = new OpenViduError(OpenViduErrorName.SCREEN_SHARING_NOT_SUPPORTED, 'You can only screen share in desktop Chrome, Firefox, Opera or Electron. Detected client: ' + platform.name); - console.error(error); + logger.error(error); reject(error); } else { @@ -784,19 +785,19 @@ export class OpenVidu { if (!!error || !!screenConstraints.mandatory && screenConstraints.mandatory.chromeMediaSource === 'screen') { if (error === 'permission-denied' || error === 'PermissionDeniedError') { const error = new OpenViduError(OpenViduErrorName.SCREEN_CAPTURE_DENIED, 'You must allow access to one window of your desktop'); - console.error(error); + logger.error(error); reject(error); } else { const extensionId = this.advancedConfiguration.screenShareChromeExtension!.split('/').pop()!!.trim(); screenSharing.getChromeExtensionStatus(extensionId, status => { if (status === 'installed-disabled') { const error = new OpenViduError(OpenViduErrorName.SCREEN_EXTENSION_DISABLED, 'You must enable the screen extension'); - console.error(error); + logger.error(error); reject(error); } if (status === 'not-installed') { const error = new OpenViduError(OpenViduErrorName.SCREEN_EXTENSION_NOT_INSTALLED, (this.advancedConfiguration.screenShareChromeExtension)); - console.error(error); + logger.error(error); reject(error); } }); @@ -823,20 +824,20 @@ export class OpenVidu { const extensionUrl = !!this.advancedConfiguration.screenShareChromeExtension ? this.advancedConfiguration.screenShareChromeExtension : 'https://chrome.google.com/webstore/detail/openvidu-screensharing/lfcgfepafnobdloecchnfaclibenjold'; const err = new OpenViduError(OpenViduErrorName.SCREEN_EXTENSION_NOT_INSTALLED, extensionUrl); - console.error(err); + logger.error(err); reject(err); } else if (error === 'installed-disabled') { const err = new OpenViduError(OpenViduErrorName.SCREEN_EXTENSION_DISABLED, 'You must enable the screen extension'); - console.error(err); + logger.error(err); reject(err); } else if (error === 'permission-denied') { const err = new OpenViduError(OpenViduErrorName.SCREEN_CAPTURE_DENIED, 'You must allow access to one window of your desktop'); - console.error(err); + logger.error(err); reject(err); } else { const err = new OpenViduError(OpenViduErrorName.GENERIC_ERROR, 'Unknown error when accessing screen share'); - console.error(err); - console.error(error); + logger.error(err); + logger.error(error); reject(err); } } else { @@ -904,7 +905,7 @@ export class OpenVidu { callback = params; params = {}; } - console.debug('Sending request: {method:"' + method + '", params: ' + JSON.stringify(params) + '}'); + logger.debug('Sending request: {method:"' + method + '", params: ' + JSON.stringify(params) + '}'); this.jsonRpcClient.send(method, params, callback); } @@ -981,7 +982,7 @@ export class OpenVidu { /* Private methods */ private disconnectCallback(): void { - console.warn('Websocket connection lost'); + logger.warn('Websocket connection lost'); if (this.isRoomAvailable()) { this.session.onLostConnection('networkDisconnect'); } else { @@ -990,7 +991,7 @@ export class OpenVidu { } private reconnectingCallback(): void { - console.warn('Websocket connection lost (reconnecting)'); + logger.warn('Websocket connection lost (reconnecting)'); if (!this.isRoomAvailable()) { alert('Connection error. Please reload page.'); } else { @@ -999,12 +1000,12 @@ export class OpenVidu { } private reconnectedCallback(): void { - console.warn('Websocket reconnected'); + logger.warn('Websocket reconnected'); if (this.isRoomAvailable()) { this.sendRequest('connect', { sessionId: this.session.connection.rpcSessionId }, (error, response) => { if (!!error) { - console.error(error); - console.warn('Websocket was able to reconnect to OpenVidu Server, but your Connection was already destroyed due to timeout. You are no longer a participant of the Session and your media streams have been destroyed'); + logger.error(error); + logger.warn('Websocket was able to reconnect to OpenVidu Server, but your Connection was already destroyed due to timeout. You are no longer a participant of the Session and your media streams have been destroyed'); this.session.onLostConnection("networkDisconnect"); this.jsonRpcClient.close(4101, "Reconnection fault"); } else { @@ -1021,7 +1022,7 @@ export class OpenVidu { if (this.session !== undefined && this.session instanceof Session) { return true; } else { - console.warn('Session instance not found'); + logger.warn('Session instance not found'); return false; } } diff --git a/openvidu-browser/src/OpenVidu/Publisher.ts b/openvidu-browser/src/OpenVidu/Publisher.ts index 0ee8363d..b7988606 100644 --- a/openvidu-browser/src/OpenVidu/Publisher.ts +++ b/openvidu-browser/src/OpenVidu/Publisher.ts @@ -29,12 +29,18 @@ import { OpenViduError, OpenViduErrorName } from '../OpenViduInternal/Enums/Open import { VideoInsertMode } from '../OpenViduInternal/Enums/VideoInsertMode'; import platform = require('platform'); +import { OpenViduLogger } from '../OpenViduInternal/Logger/OpenViduLogger'; + +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); /** * Packs local media streams. Participants can publish it to a session. Initialized with [[OpenVidu.initPublisher]] method - * + * * ### Available event listeners (and events dispatched) - * + * * - accessAllowed * - accessDenied * - accessDialogOpened @@ -132,7 +138,7 @@ export class Publisher extends StreamManager { }, (error, response) => { if (error) { - console.error("Error sending 'streamPropertyChanged' event", error); + logger.error("Error sending 'streamPropertyChanged' event", error); } else { this.session.emitEvent('streamPropertyChanged', [new StreamPropertyChangedEvent(this.session, this.stream, 'audioActive', value, !value, 'publishAudio')]); this.emitEvent('streamPropertyChanged', [new StreamPropertyChangedEvent(this, this.stream, 'audioActive', value, !value, 'publishAudio')]); @@ -140,7 +146,7 @@ export class Publisher extends StreamManager { }); } this.stream.audioActive = value; - console.info("'Publisher' has " + (value ? 'published' : 'unpublished') + ' its audio stream'); + logger.info("'Publisher' has " + (value ? 'published' : 'unpublished') + ' its audio stream'); } } @@ -179,7 +185,7 @@ export class Publisher extends StreamManager { }, (error, response) => { if (error) { - console.error("Error sending 'streamPropertyChanged' event", error); + logger.error("Error sending 'streamPropertyChanged' event", error); } else { this.session.emitEvent('streamPropertyChanged', [new StreamPropertyChangedEvent(this.session, this.stream, 'videoActive', value, !value, 'publishVideo')]); this.emitEvent('streamPropertyChanged', [new StreamPropertyChangedEvent(this, this.stream, 'videoActive', value, !value, 'publishVideo')]); @@ -187,7 +193,7 @@ export class Publisher extends StreamManager { }); } this.stream.videoActive = value; - console.info("'Publisher' has " + (value ? 'published' : 'unpublished') + ' its video stream'); + logger.info("'Publisher' has " + (value ? 'published' : 'unpublished') + ' its video stream'); } } @@ -279,14 +285,14 @@ export class Publisher extends StreamManager { * Replaces the current video or audio track with a different one. This allows you to replace an ongoing track with a different one * without having to renegotiate the whole WebRTC connection (that is, initializing a new Publisher, unpublishing the previous one * and publishing the new one). - * + * * You can get this new MediaStreamTrack by using the native Web API or simply with [[OpenVidu.getUserMedia]] method. - * + * * **WARNING: this method has been proven to work, but there may be some combinations of published/replaced tracks that may be incompatible between them and break the connection in OpenVidu Server. A complete renegotiation may be the only solution in this case** - * + * * @param track The [MediaStreamTrack](https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack) object to replace the current one. If it is an audio track, the current audio track will be the replaced one. If it * is a video track, the current video track will be the replaced one. - * + * * @returns A Promise (to which you can optionally subscribe to) that is resolved if the track was successfully replaced and rejected with an Error object in other case */ replaceTrack(track: MediaStreamTrack): Promise { @@ -483,7 +489,7 @@ export class Publisher extends StreamManager { }, (error, response) => { if (error) { - console.error("Error sending 'streamPropertyChanged' event", error); + logger.error("Error sending 'streamPropertyChanged' event", error); } else { this.session.emitEvent('streamPropertyChanged', [new StreamPropertyChangedEvent(this.session, this.stream, 'videoDimensions', this.stream.videoDimensions, oldValue, 'screenResized')]); this.emitEvent('streamPropertyChanged', [new StreamPropertyChangedEvent(this, this.stream, 'videoDimensions', this.stream.videoDimensions, oldValue, 'screenResized')]); @@ -534,7 +540,7 @@ export class Publisher extends StreamManager { }; const getMediaError = error => { - console.error(error); + logger.error(error); this.clearPermissionDialogTimer(startTime, timeForDialogEvent); if (error.name === 'Error') { // Safari OverConstrainedError has as name property 'Error' instead of 'OverConstrainedError' diff --git a/openvidu-browser/src/OpenVidu/Session.ts b/openvidu-browser/src/OpenVidu/Session.ts index 5acf3363..a5cc5240 100644 --- a/openvidu-browser/src/OpenVidu/Session.ts +++ b/openvidu-browser/src/OpenVidu/Session.ts @@ -41,14 +41,20 @@ import { OpenViduError, OpenViduErrorName } from '../OpenViduInternal/Enums/Open import { VideoInsertMode } from '../OpenViduInternal/Enums/VideoInsertMode'; import platform = require('platform'); +import { OpenViduLogger } from '../OpenViduInternal/Logger/OpenViduLogger'; + +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); /** * Represents a video call. It can also be seen as a videoconference room where multiple users can connect. * Participants who publish their videos to a session can be seen by the rest of users connected to that specific session. * Initialized with [[OpenVidu.initSession]] method. - * + * * ### Available event listeners (and events dispatched) - * + * * - connectionCreated ([[ConnectionEvent]]) * - connectionDestroyed ([[ConnectionEvent]]) * - sessionDisconnected ([[SessionDisconnectedEvent]]) @@ -62,7 +68,7 @@ import platform = require('platform'); * - recordingStopped ([[RecordingEvent]]) * - reconnecting * - reconnected - * + * */ export class Session extends EventDispatcher { @@ -265,11 +271,11 @@ export class Session extends EventDispatcher { completionHandler = param4; } - console.info('Subscribing to ' + stream.connection.connectionId); + logger.info('Subscribing to ' + stream.connection.connectionId); stream.subscribe() .then(() => { - console.info('Subscribed correctly to ' + stream.connection.connectionId); + logger.info('Subscribed correctly to ' + stream.connection.connectionId); if (completionHandler !== undefined) { completionHandler(undefined); } @@ -329,16 +335,16 @@ export class Session extends EventDispatcher { unsubscribe(subscriber: Subscriber): void { const connectionId = subscriber.stream.connection.connectionId; - console.info('Unsubscribing from ' + connectionId); + logger.info('Unsubscribing from ' + connectionId); this.openvidu.sendRequest( 'unsubscribeFromVideo', { sender: subscriber.stream.connection.connectionId }, (error, response) => { if (error) { - console.error('Error unsubscribing from ' + connectionId, error); + logger.error('Error unsubscribing from ' + connectionId, error); } else { - console.info('Unsubscribed correctly from ' + connectionId); + logger.info('Unsubscribed correctly from ' + connectionId); } subscriber.stream.disposeWebRtcPeer(); subscriber.stream.disposeMediaStream(); @@ -421,21 +427,21 @@ export class Session extends EventDispatcher { const stream = publisher.stream; if (!stream.connection) { - console.error('The associated Connection object of this Publisher is null', stream); + logger.error('The associated Connection object of this Publisher is null', stream); return; } else if (stream.connection !== this.connection) { - console.error('The associated Connection object of this Publisher is not your local Connection.' + + logger.error('The associated Connection object of this Publisher is not your local Connection.' + "Only moderators can force unpublish on remote Streams via 'forceUnpublish' method", stream); return; } else { - console.info('Unpublishing local media (' + stream.connection.connectionId + ')'); + logger.info('Unpublishing local media (' + stream.connection.connectionId + ')'); this.openvidu.sendRequest('unpublishVideo', (error, response) => { if (error) { - console.error(error); + logger.error(error); } else { - console.info('Media unpublished correctly'); + logger.info('Media unpublished correctly'); } }); @@ -468,20 +474,20 @@ export class Session extends EventDispatcher { */ forceDisconnect(connection: Connection): Promise { return new Promise((resolve, reject) => { - console.info('Forcing disconnect for connection ' + connection.connectionId); + logger.info('Forcing disconnect for connection ' + connection.connectionId); this.openvidu.sendRequest( 'forceDisconnect', { connectionId: connection.connectionId }, (error, response) => { if (error) { - console.error('Error forcing disconnect for Connection ' + connection.connectionId, error); + logger.error('Error forcing disconnect for Connection ' + connection.connectionId, error); if (error.code === 401) { reject(new OpenViduError(OpenViduErrorName.OPENVIDU_PERMISSION_DENIED, "You don't have permissions to force a disconnection")); } else { reject(error); } } else { - console.info('Forcing disconnect correctly for Connection ' + connection.connectionId); + logger.info('Forcing disconnect correctly for Connection ' + connection.connectionId); resolve(); } } @@ -507,20 +513,20 @@ export class Session extends EventDispatcher { */ forceUnpublish(stream: Stream): Promise { return new Promise((resolve, reject) => { - console.info('Forcing unpublish for stream ' + stream.streamId); + logger.info('Forcing unpublish for stream ' + stream.streamId); this.openvidu.sendRequest( 'forceUnpublish', { streamId: stream.streamId }, (error, response) => { if (error) { - console.error('Error forcing unpublish for Stream ' + stream.streamId, error); + logger.error('Error forcing unpublish for Stream ' + stream.streamId, error); if (error.code === 401) { reject(new OpenViduError(OpenViduErrorName.OPENVIDU_PERMISSION_DENIED, "You don't have permissions to force an unpublishing")); } else { reject(error); } } else { - console.info('Forcing unpublish correctly for Stream ' + stream.streamId); + logger.info('Forcing unpublish correctly for Stream ' + stream.streamId); resolve(); } } @@ -693,7 +699,7 @@ export class Session extends EventDispatcher { this.getConnection(response.id, '') .then(connection => { - console.warn('Connection ' + response.id + ' already exists in connections list'); + logger.warn('Connection ' + response.id + ' already exists in connections list'); }) .catch(openViduError => { const connection = new Connection(this, response); @@ -728,7 +734,7 @@ export class Session extends EventDispatcher { this.ee.emitEvent('connectionDestroyed', [new ConnectionEvent(false, this, 'connectionDestroyed', connection, msg.reason)]); }) .catch(openViduError => { - console.error(openViduError); + logger.error(openViduError); }); } @@ -801,7 +807,7 @@ export class Session extends EventDispatcher { connection.removeStream(streamId); }) .catch(openViduError => { - console.error(openViduError); + logger.error(openViduError); }); } } @@ -823,7 +829,7 @@ export class Session extends EventDispatcher { */ onNewMessage(msg): void { - console.info('New signal: ' + JSON.stringify(msg)); + logger.info('New signal: ' + JSON.stringify(msg)); const strippedType: string = !!msg.type ? msg.type.replace(/^(signal:)/, '') : undefined; @@ -839,7 +845,7 @@ export class Session extends EventDispatcher { } }) .catch(openViduError => { - console.error(openViduError); + logger.error(openViduError); }); } else { // Signal sent by server @@ -895,7 +901,7 @@ export class Session extends EventDispatcher { stream.streamManager.emitEvent('streamPropertyChanged', [new StreamPropertyChangedEvent(stream.streamManager, stream, msg.property, msg.newValue, oldValue, msg.reason)]); } } else { - console.error("No stream with streamId '" + msg.streamId + "' found for connection '" + msg.connectionId + "' on 'streamPropertyChanged' event"); + logger.error("No stream with streamId '" + msg.streamId + "' found for connection '" + msg.connectionId + "' on 'streamPropertyChanged' event"); } }; @@ -909,7 +915,7 @@ export class Session extends EventDispatcher { callback(connection); }) .catch(openViduError => { - console.error(openViduError); + logger.error(openViduError); }); } } @@ -940,12 +946,12 @@ export class Session extends EventDispatcher { .then(connection => { const stream = connection.stream; stream.getWebRtcPeer().addIceCandidate(candidate).catch(error => { - console.error('Error adding candidate for ' + stream.streamId + logger.error('Error adding candidate for ' + stream.streamId + ' stream of endpoint ' + msg.endpointName + ': ' + error); }); }) .catch(openViduError => { - console.error(openViduError); + logger.error(openViduError); }); } @@ -953,14 +959,14 @@ export class Session extends EventDispatcher { * @hidden */ onSessionClosed(msg): void { - console.info('Session closed: ' + JSON.stringify(msg)); + logger.info('Session closed: ' + JSON.stringify(msg)); const s = msg.sessionId; if (s !== undefined) { this.ee.emitEvent('session-closed', [{ session: s }]); } else { - console.warn('Session undefined on session closed', msg); + logger.warn('Session undefined on session closed', msg); } } @@ -968,7 +974,7 @@ export class Session extends EventDispatcher { * @hidden */ onLostConnection(reason: string): void { - console.warn('Lost connection in Session ' + this.sessionId); + logger.warn('Lost connection in Session ' + this.sessionId); if (!!this.sessionId && !this.connection.disposed) { this.leave(true, reason); } @@ -978,7 +984,7 @@ export class Session extends EventDispatcher { * @hidden */ onRecoveredConnection(): void { - console.info('Recovered connection in Session ' + this.sessionId); + logger.info('Recovered connection in Session ' + this.sessionId); this.reconnectBrokenStreams(); this.ee.emitEvent('reconnected', []); } @@ -987,14 +993,14 @@ export class Session extends EventDispatcher { * @hidden */ onMediaError(params): void { - console.error('Media error: ' + JSON.stringify(params)); + logger.error('Media error: ' + JSON.stringify(params)); const err = params.error; if (err) { this.ee.emitEvent('error-media', [{ error: err }]); } else { - console.warn('Received undefined media error. Params:', params); + logger.warn('Received undefined media error. Params:', params); } } @@ -1021,7 +1027,7 @@ export class Session extends EventDispatcher { const streamId: string = response.streamId; this.getConnection(connectionId, 'No connection found for connectionId ' + connectionId) .then(connection => { - console.info('Filter event dispatched'); + logger.info('Filter event dispatched'); const stream: Stream = connection.stream; stream.filter.handlers[response.eventType](new FilterEvent(stream.filter, response.eventType, response.data)); }); @@ -1031,24 +1037,24 @@ export class Session extends EventDispatcher { * @hidden */ reconnectBrokenStreams(): void { - console.info('Re-establishing media connections...'); + logger.info('Re-establishing media connections...'); let someReconnection = false; // Re-establish Publisher stream if (!!this.connection.stream && this.connection.stream.streamIceConnectionStateBroken()) { - console.warn('Re-establishing Publisher ' + this.connection.stream.streamId); + logger.warn('Re-establishing Publisher ' + this.connection.stream.streamId); this.connection.stream.initWebRtcPeerSend(true); someReconnection = true; } // Re-establish Subscriber streams for (let remoteConnection of Object.values(this.remoteConnections)) { if (!!remoteConnection.stream && remoteConnection.stream.streamIceConnectionStateBroken()) { - console.warn('Re-establishing Subscriber ' + remoteConnection.stream.streamId); + logger.warn('Re-establishing Subscriber ' + remoteConnection.stream.streamId); remoteConnection.stream.initWebRtcPeerReceive(true); someReconnection = true; } } if (!someReconnection) { - console.info('There were no media streams in need of a reconnection'); + logger.info('There were no media streams in need of a reconnection'); } } @@ -1065,13 +1071,13 @@ export class Session extends EventDispatcher { leave(forced: boolean, reason: string): void { forced = !!forced; - console.info('Leaving Session (forced=' + forced + ')'); + logger.info('Leaving Session (forced=' + forced + ')'); if (!!this.connection) { if (!this.connection.disposed && !forced) { this.openvidu.sendRequest('leaveRoom', (error, response) => { if (error) { - console.error(error); + logger.error(error); } this.openvidu.closeWs(); }); @@ -1088,7 +1094,7 @@ export class Session extends EventDispatcher { sessionDisconnectEvent.callDefaultBehavior(); } } else { - console.warn('You were not connected to the session ' + this.sessionId); + logger.warn('You were not connected to the session ' + this.sessionId); } } @@ -1264,8 +1270,8 @@ export class Session extends EventDispatcher { { urls: [stunUrl] }, { urls: [turnUrl1, turnUrl2], username: turnUsername, credential: turnCredential } ]; - console.log("STUN/TURN server IP: " + coturnIp); - console.log('TURN temp credentials [' + turnUsername + ':' + turnCredential + ']'); + logger.log("STUN/TURN server IP: " + coturnIp); + logger.log('TURN temp credentials [' + turnUsername + ':' + turnCredential + ']'); } if (!!role) { this.openvidu.role = role; @@ -1274,9 +1280,9 @@ export class Session extends EventDispatcher { this.openvidu.webrtcStatsInterval = +webrtcStatsInterval; } if (!!openviduServerVersion) { - console.info("openvidu-server version: " + openviduServerVersion); + logger.info("openvidu-server version: " + openviduServerVersion); if (openviduServerVersion !== this.openvidu.libraryVersion) { - console.error('OpenVidu Server (' + openviduServerVersion + + logger.error('OpenVidu Server (' + openviduServerVersion + ') and OpenVidu Browser (' + this.openvidu.libraryVersion + ') versions do NOT match. There may be incompatibilities') } @@ -1286,7 +1292,7 @@ export class Session extends EventDispatcher { this.openvidu.httpUri = 'https://' + url.host; } else { - console.error('Token "' + token + '" is not valid') + logger.error('Token "' + token + '" is not valid') } } diff --git a/openvidu-browser/src/OpenVidu/Stream.ts b/openvidu-browser/src/OpenVidu/Stream.ts index 3a7dfd06..1f77c4af 100644 --- a/openvidu-browser/src/OpenVidu/Stream.ts +++ b/openvidu-browser/src/OpenVidu/Stream.ts @@ -36,6 +36,12 @@ import { OpenViduError, OpenViduErrorName } from '../OpenViduInternal/Enums/Open */ import hark = require('hark'); import platform = require('platform'); +import { OpenViduLogger } from '../OpenViduInternal/Logger/OpenViduLogger'; +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); + /** @@ -252,7 +258,7 @@ export class Stream extends EventDispatcher { this.ee.on('mediastream-updated', () => { this.streamManager.updateMediaStream(this.mediaStream); - console.debug('Video srcObject [' + this.mediaStream + '] updated in stream [' + this.streamId + ']'); + logger.debug('Video srcObject [' + this.mediaStream + '] updated in stream [' + this.streamId + ']'); }); } @@ -294,7 +300,7 @@ export class Stream extends EventDispatcher { */ applyFilter(type: string, options: Object): Promise { return new Promise((resolve, reject) => { - console.info('Applying filter to stream ' + this.streamId); + logger.info('Applying filter to stream ' + this.streamId); options = !!options ? options : {}; if (typeof options !== 'string') { options = JSON.stringify(options); @@ -304,14 +310,14 @@ export class Stream extends EventDispatcher { { streamId: this.streamId, type, options }, (error, response) => { if (error) { - console.error('Error applying filter for Stream ' + this.streamId, error); + logger.error('Error applying filter for Stream ' + this.streamId, error); if (error.code === 401) { reject(new OpenViduError(OpenViduErrorName.OPENVIDU_PERMISSION_DENIED, "You don't have permissions to apply a filter")); } else { reject(error); } } else { - console.info('Filter successfully applied on Stream ' + this.streamId); + logger.info('Filter successfully applied on Stream ' + this.streamId); const oldValue: Filter = this.filter; this.filter = new Filter(type, options); this.filter.stream = this; @@ -331,20 +337,20 @@ export class Stream extends EventDispatcher { */ removeFilter(): Promise { return new Promise((resolve, reject) => { - console.info('Removing filter of stream ' + this.streamId); + logger.info('Removing filter of stream ' + this.streamId); this.session.openvidu.sendRequest( 'removeFilter', { streamId: this.streamId }, (error, response) => { if (error) { - console.error('Error removing filter for Stream ' + this.streamId, error); + logger.error('Error removing filter for Stream ' + this.streamId, error); if (error.code === 401) { reject(new OpenViduError(OpenViduErrorName.OPENVIDU_PERMISSION_DENIED, "You don't have permissions to remove a filter")); } else { reject(error); } } else { - console.info('Filter successfully removed from Stream ' + this.streamId); + logger.info('Filter successfully removed from Stream ' + this.streamId); const oldValue = this.filter; delete this.filter; this.session.emitEvent('streamPropertyChanged', [new StreamPropertyChangedEvent(this.session, this, 'filter', this.filter, oldValue, 'applyFilter')]); @@ -358,7 +364,7 @@ export class Stream extends EventDispatcher { /** * Returns the internal RTCPeerConnection object associated to this stream (https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection) - * + * * @returns Native RTCPeerConnection Web API object */ getRTCPeerConnection(): RTCPeerConnection { @@ -367,7 +373,7 @@ export class Stream extends EventDispatcher { /** * Returns the internal MediaStream object associated to this stream (https://developer.mozilla.org/en-US/docs/Web/API/MediaStream) - * + * * @returns Native MediaStream Web API object */ getMediaStream(): MediaStream { @@ -461,7 +467,7 @@ export class Stream extends EventDispatcher { this.webRtcPeer.dispose(); this.stopWebRtcStats(); } - console.info((!!this.outboundStreamOpts ? 'Outbound ' : 'Inbound ') + "WebRTCPeer from 'Stream' with id [" + this.streamId + '] is now closed'); + logger.info((!!this.outboundStreamOpts ? 'Outbound ' : 'Inbound ') + "WebRTCPeer from 'Stream' with id [" + this.streamId + '] is now closed'); } /** @@ -493,7 +499,7 @@ export class Stream extends EventDispatcher { } delete this.speechEvent; } - console.info((!!this.outboundStreamOpts ? 'Local ' : 'Remote ') + "MediaStream from 'Stream' with id [" + this.streamId + '] is now disposed'); + logger.info((!!this.outboundStreamOpts ? 'Local ' : 'Remote ') + "MediaStream from 'Stream' with id [" + this.streamId + '] is now disposed'); } /** @@ -766,7 +772,7 @@ export class Stream extends EventDispatcher { return false; } if (this.isLocal && !!this.session.openvidu.advancedConfiguration.forceMediaReconnectionAfterNetworkDrop) { - console.warn('OpenVidu Browser advanced configuration option "forceMediaReconnectionAfterNetworkDrop" is enabled. Publisher stream ' + this.streamId + 'will force a reconnection'); + logger.warn('OpenVidu Browser advanced configuration option "forceMediaReconnectionAfterNetworkDrop" is enabled. Publisher stream ' + this.streamId + 'will force a reconnection'); return true; } const iceConnectionState: RTCIceConnectionState = this.getRTCPeerConnection().iceConnectionState; @@ -812,7 +818,7 @@ export class Stream extends EventDispatcher { }; const successCallback = (sdpOfferParam) => { - console.debug('Sending SDP offer to publish as ' + logger.debug('Sending SDP offer to publish as ' + this.streamId, sdpOfferParam); const method = reconnect ? 'reconnectStream' : 'publishVideo'; @@ -864,7 +870,7 @@ export class Stream extends EventDispatcher { this.ee.emitEvent('stream-created-by-publisher', []); } this.initWebRtcStats(); - console.info("'Publisher' (" + this.streamId + ") successfully " + (reconnect ? "reconnected" : "published") + " to session"); + logger.info("'Publisher' (" + this.streamId + ") successfully " + (reconnect ? "reconnected" : "published") + " to session"); resolve(); }) .catch(error => { @@ -901,7 +907,7 @@ export class Stream extends EventDispatcher { audio: this.inboundStreamOpts.hasAudio, video: this.inboundStreamOpts.hasVideo }; - console.debug("'Session.subscribe(Stream)' called. Constraints of generate SDP offer", + logger.debug("'Session.subscribe(Stream)' called. Constraints of generate SDP offer", offerConstraints); const options = { onicecandidate: this.connection.sendIceCandidate.bind(this.connection), @@ -911,7 +917,7 @@ export class Stream extends EventDispatcher { }; const successCallback = (sdpOfferParam) => { - console.debug('Sending SDP offer to subscribe to ' + logger.debug('Sending SDP offer to subscribe to ' + this.streamId, sdpOfferParam); const method = reconnect ? 'reconnectStream' : 'receiveVideoFrom'; @@ -935,7 +941,7 @@ export class Stream extends EventDispatcher { } const needsTimeoutOnProcessAnswer = this.session.countDownForIonicIosSubscribersActive; this.webRtcPeer.processAnswer(response.sdpAnswer, needsTimeoutOnProcessAnswer).then(() => { - console.info("'Subscriber' (" + this.streamId + ") successfully " + (reconnect ? "reconnected" : "subscribed")); + logger.info("'Subscriber' (" + this.streamId + ") successfully " + (reconnect ? "reconnected" : "subscribed")); this.remotePeerSuccessfullyEstablished(); this.initWebRtcStats(); resolve(); @@ -972,7 +978,7 @@ export class Stream extends EventDispatcher { } } } - console.debug('Peer remote stream', this.mediaStream); + logger.debug('Peer remote stream', this.mediaStream); if (!!this.mediaStream) { @@ -1121,7 +1127,7 @@ export class Stream extends EventDispatcher { } - console.log(finalReport); + logger.log(finalReport); } }); })); @@ -1182,7 +1188,7 @@ export class Stream extends EventDispatcher { if (report.type === 'remote-inbound-rtp' || report.type === 'remote-outbound-rtp') { } - console.log(finalReport); + logger.log(finalReport); } }) }) diff --git a/openvidu-browser/src/OpenVidu/StreamManager.ts b/openvidu-browser/src/OpenVidu/StreamManager.ts index 1bf157ab..e9f588b2 100644 --- a/openvidu-browser/src/OpenVidu/StreamManager.ts +++ b/openvidu-browser/src/OpenVidu/StreamManager.ts @@ -24,6 +24,11 @@ import { VideoElementEvent } from '../OpenViduInternal/Events/VideoElementEvent' import { VideoInsertMode } from '../OpenViduInternal/Enums/VideoInsertMode'; import platform = require('platform'); +import { OpenViduLogger } from '../OpenViduInternal/Logger/OpenViduLogger'; +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); /** * Interface in charge of displaying the media streams in the HTML DOM. This wraps any [[Publisher]] and [[Subscriber]] object. @@ -32,14 +37,14 @@ import platform = require('platform'); * The use of StreamManager wrapper is particularly useful when you don't need to differentiate between Publisher or Subscriber streams or just * want to directly manage your own video elements (even more than one video element per Stream). This scenario is pretty common in * declarative, MVC frontend frameworks such as Angular, React or Vue.js - * + * * ### Available event listeners (and events dispatched) - * + * * - videoElementCreated ([[VideoElementEvent]]) * - videoElementDestroyed ([[VideoElementEvent]]) * - streamPlaying ([[StreamManagerEvent]]) * - streamAudioVolumeChange ([[StreamManagerEvent]]) - * + * */ export class StreamManager extends EventDispatcher { @@ -127,14 +132,14 @@ export class StreamManager extends EventDispatcher { this.canPlayListener = () => { if (this.stream.isLocal()) { if (!this.stream.displayMyRemote()) { - console.info("Your local 'Stream' with id [" + this.stream.streamId + '] video is now playing'); + logger.info("Your local 'Stream' with id [" + this.stream.streamId + '] video is now playing'); this.ee.emitEvent('videoPlaying', [new VideoElementEvent(this.videos[0].video, this, 'videoPlaying')]); } else { - console.info("Your own remote 'Stream' with id [" + this.stream.streamId + '] video is now playing'); + logger.info("Your own remote 'Stream' with id [" + this.stream.streamId + '] video is now playing'); this.ee.emitEvent('remoteVideoPlaying', [new VideoElementEvent(this.videos[0].video, this, 'remoteVideoPlaying')]); } } else { - console.info("Remote 'Stream' with id [" + this.stream.streamId + '] video is now playing'); + logger.info("Remote 'Stream' with id [" + this.stream.streamId + '] video is now playing'); this.ee.emitEvent('videoPlaying', [new VideoElementEvent(this.videos[0].video, this, 'videoPlaying')]); } this.ee.emitEvent('streamPlaying', [new StreamManagerEvent(this, 'streamPlaying', undefined)]); @@ -262,7 +267,7 @@ export class StreamManager extends EventDispatcher { canplayListenerAdded: false }); - console.info('New video element associated to ', this); + logger.info('New video element associated to ', this); return returnNumber; } @@ -337,7 +342,7 @@ export class StreamManager extends EventDispatcher { * Updates the current configuration for the [[PublisherSpeakingEvent]] feature and the [StreamManagerEvent.streamAudioVolumeChange](/en/stable/api/openvidu-browser/classes/streammanagerevent.html) feature for this specific * StreamManager audio stream, overriding the global options set with [[OpenVidu.setAdvancedConfiguration]]. This way you can customize the audio events options * for each specific StreamManager and change them dynamically. - * + * * @param publisherSpeakingEventsOptions New options to be applied to this StreamManager's audio stream. It is an object which includes the following optional properties: * - `interval`: (number) how frequently the analyser polls the audio stream to check if speaking has started/stopped or audio volume has changed. Default **100** (ms) * - `threshold`: (number) the volume at which _publisherStartSpeaking_, _publisherStopSpeaking_ events will be fired. Default **-50** (dB) @@ -380,7 +385,7 @@ export class StreamManager extends EventDispatcher { if (!video.id) { video.id = (this.remote ? 'remote-' : 'local-') + 'video-' + this.stream.streamId; - // DEPRECATED property: assign once the property id if the user provided a valid targetElement + // DEPRECATED property: assign once the property id if the user provided a valid targetElement if (!this.id && !!this.targetElement) { this.id = video.id; } @@ -434,7 +439,7 @@ export class StreamManager extends EventDispatcher { this.videos[i].video.removeEventListener('canplay', this.canPlayListener); this.videos.splice(i, 1); disassociated = true; - console.info('Video element disassociated from ', this); + logger.info('Video element disassociated from ', this); break; } } diff --git a/openvidu-browser/src/OpenVidu/Subscriber.ts b/openvidu-browser/src/OpenVidu/Subscriber.ts index 55a0cf9f..f0336b39 100644 --- a/openvidu-browser/src/OpenVidu/Subscriber.ts +++ b/openvidu-browser/src/OpenVidu/Subscriber.ts @@ -18,7 +18,12 @@ import { Stream } from './Stream'; import { StreamManager } from './StreamManager'; import { SubscriberProperties } from '../OpenViduInternal/Interfaces/Public/SubscriberProperties'; +import { OpenViduLogger } from '../OpenViduInternal/Logger/OpenViduLogger'; +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); /** * Packs remote media streams. Participants automatically receive them when others publish their streams. Initialized with [[Session.subscribe]] method @@ -48,7 +53,7 @@ export class Subscriber extends StreamManager { this.stream.getMediaStream().getAudioTracks().forEach((track) => { track.enabled = value; }); - console.info("'Subscriber' has " + (value ? 'subscribed to' : 'unsubscribed from') + ' its audio stream'); + logger.info("'Subscriber' has " + (value ? 'subscribed to' : 'unsubscribed from') + ' its audio stream'); return this; } @@ -60,7 +65,7 @@ export class Subscriber extends StreamManager { this.stream.getMediaStream().getVideoTracks().forEach((track) => { track.enabled = value; }); - console.info("'Subscriber' has " + (value ? 'subscribed to' : 'unsubscribed from') + ' its video stream'); + logger.info("'Subscriber' has " + (value ? 'subscribed to' : 'unsubscribed from') + ' its video stream'); return this; } diff --git a/openvidu-browser/src/OpenViduInternal/Events/SessionDisconnectedEvent.ts b/openvidu-browser/src/OpenViduInternal/Events/SessionDisconnectedEvent.ts index 935168c9..050c694e 100644 --- a/openvidu-browser/src/OpenViduInternal/Events/SessionDisconnectedEvent.ts +++ b/openvidu-browser/src/OpenViduInternal/Events/SessionDisconnectedEvent.ts @@ -17,6 +17,12 @@ import { Event } from './Event'; import { Session } from '../../OpenVidu/Session'; +import { OpenViduLogger } from '../Logger/OpenViduLogger'; + +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); /** @@ -49,7 +55,7 @@ export class SessionDisconnectedEvent extends Event { */ callDefaultBehavior() { - console.info("Calling default behavior upon '" + this.type + "' event dispatched by 'Session'"); + logger.info("Calling default behavior upon '" + this.type + "' event dispatched by 'Session'"); const session = this.target; diff --git a/openvidu-browser/src/OpenViduInternal/Events/StreamEvent.ts b/openvidu-browser/src/OpenViduInternal/Events/StreamEvent.ts index d04c556e..88d57dff 100644 --- a/openvidu-browser/src/OpenViduInternal/Events/StreamEvent.ts +++ b/openvidu-browser/src/OpenViduInternal/Events/StreamEvent.ts @@ -19,7 +19,12 @@ import { Event } from './Event'; import { Publisher } from '../../OpenVidu/Publisher'; import { Session } from '../../OpenVidu/Session'; import { Stream } from '../../OpenVidu/Stream'; +import { OpenViduLogger } from '../Logger/OpenViduLogger'; +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); /** * Defines the following events: @@ -66,11 +71,11 @@ export class StreamEvent extends Event { if (this.target instanceof Session) { // Remote Stream - console.info("Calling default behavior upon '" + this.type + "' event dispatched by 'Session'"); + logger.info("Calling default behavior upon '" + this.type + "' event dispatched by 'Session'"); this.stream.disposeWebRtcPeer(); } else if (this.target instanceof Publisher) { // Local Stream - console.info("Calling default behavior upon '" + this.type + "' event dispatched by 'Publisher'"); + logger.info("Calling default behavior upon '" + this.type + "' event dispatched by 'Publisher'"); clearInterval((this.target).screenShareResizeInterval); this.stream.isLocalStreamReadyToPublish = false; diff --git a/openvidu-browser/src/OpenViduInternal/Logger/OpenViduLogger.ts b/openvidu-browser/src/OpenViduInternal/Logger/OpenViduLogger.ts new file mode 100644 index 00000000..3f4fbc01 --- /dev/null +++ b/openvidu-browser/src/OpenViduInternal/Logger/OpenViduLogger.ts @@ -0,0 +1,48 @@ +export class OpenViduLogger { + + private static instance: OpenViduLogger; + private logger: Console = window.console; + private LOG_FNS = [this.logger.log, this.logger.debug, this.logger.info, this.logger.warn, this.logger.error]; + private isProdMode = false; + + private constructor() {} + + static getInstance(): OpenViduLogger { + if(!OpenViduLogger.instance){ + OpenViduLogger.instance = new OpenViduLogger(); + } + return OpenViduLogger.instance; + } + + log(...args: any[]){ + if (!this.isProdMode) { + this.LOG_FNS[0].apply(this.logger, arguments); + } + } + + debug(...args: any[]) { + if (!this.isProdMode) { + this.LOG_FNS[1].apply(this.logger, arguments); + } + } + + info(...args: any[]) { + if (!this.isProdMode) { + this.LOG_FNS[2].apply(this.logger, arguments); + } + } + + warn(...args: any[]) { + if (!this.isProdMode) { + this.LOG_FNS[3].apply(this.logger, arguments); + } + } + + error(...args: any[]) { + this.LOG_FNS[4].apply(this.logger, arguments); + } + + enableProdMode(){ + this.isProdMode = true; + } +} \ No newline at end of file diff --git a/openvidu-browser/src/OpenViduInternal/WebRtcPeer/WebRtcPeer.ts b/openvidu-browser/src/OpenViduInternal/WebRtcPeer/WebRtcPeer.ts index 6fc8f458..43e4bb26 100644 --- a/openvidu-browser/src/OpenViduInternal/WebRtcPeer/WebRtcPeer.ts +++ b/openvidu-browser/src/OpenViduInternal/WebRtcPeer/WebRtcPeer.ts @@ -18,6 +18,12 @@ import freeice = require('freeice'); import uuid = require('uuid'); import platform = require('platform'); +import { OpenViduLogger } from '../Logger/OpenViduLogger'; +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); + export interface WebRtcPeerConfiguration { mediaConstraints: { @@ -98,7 +104,7 @@ export class WebRtcPeer { * This method frees the resources used by WebRtcPeer */ dispose() { - console.debug('Disposing WebRtcPeer'); + logger.debug('Disposing WebRtcPeer'); if (this.pc) { if (this.pc.signalingState === 'closed') { return; @@ -130,7 +136,7 @@ export class WebRtcPeer { offerToReceiveVideo: (this.configuration.mode !== 'sendonly' && offerVideo) }; - console.debug('RTCPeerConnection constraints: ' + JSON.stringify(constraints)); + logger.debug('RTCPeerConnection constraints: ' + JSON.stringify(constraints)); if (platform.name === 'Safari' && platform.ua!!.indexOf('Safari') !== -1) { // Safari (excluding Ionic), at least on iOS just seems to support unified plan, whereas in other browsers is not yet ready and considered experimental @@ -149,14 +155,14 @@ export class WebRtcPeer { this.pc .createOffer() .then(offer => { - console.debug('Created SDP offer'); + logger.debug('Created SDP offer'); return this.pc.setLocalDescription(offer); }) .then(() => { const localDescription = this.pc.localDescription; if (!!localDescription) { - console.debug('Local description set', localDescription.sdp); + logger.debug('Local description set', localDescription.sdp); resolve(localDescription.sdp); } else { reject('Local description is not defined'); @@ -168,13 +174,13 @@ export class WebRtcPeer { // Rest of platforms this.pc.createOffer(constraints).then(offer => { - console.debug('Created SDP offer'); + logger.debug('Created SDP offer'); return this.pc.setLocalDescription(offer); }) .then(() => { const localDescription = this.pc.localDescription; if (!!localDescription) { - console.debug('Local description set', localDescription.sdp); + logger.debug('Local description set', localDescription.sdp); resolve(localDescription.sdp); } else { reject('Local description is not defined'); @@ -195,7 +201,7 @@ export class WebRtcPeer { type: 'answer', sdp: sdpAnswer }; - console.debug('SDP answer received, setting remote description'); + logger.debug('SDP answer received, setting remote description'); if (this.pc.signalingState === 'closed') { reject('RTCPeerConnection is closed'); @@ -205,7 +211,7 @@ export class WebRtcPeer { if (needsTimeoutOnProcessAnswer) { // 400 ms have not elapsed yet since first remote stream triggered Stream#initWebRtcPeerReceive setTimeout(() => { - console.info('setRemoteDescription run after timeout for Ionic iOS device'); + logger.info('setRemoteDescription run after timeout for Ionic iOS device'); this.pc.setRemoteDescription(new RTCSessionDescription(answer)).then(() => resolve()).catch(error => reject(error)); }, 250); } else { @@ -224,7 +230,7 @@ export class WebRtcPeer { */ addIceCandidate(iceCandidate: RTCIceCandidate): Promise { return new Promise((resolve, reject) => { - console.debug('Remote ICE candidate received', iceCandidate); + logger.debug('Remote ICE candidate received', iceCandidate); this.remoteCandidatesQueue.push(iceCandidate); switch (this.pc.signalingState) { case 'closed': @@ -251,25 +257,25 @@ export class WebRtcPeer { switch (iceConnectionState) { case 'disconnected': // Possible network disconnection - console.warn('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') change to "disconnected". Possible network disconnection'); + logger.warn('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') change to "disconnected". Possible network disconnection'); break; case 'failed': - console.error('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') to "failed"'); + logger.error('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') to "failed"'); break; case 'closed': - console.log('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') change to "closed"'); + logger.log('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') change to "closed"'); break; case 'new': - console.log('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') change to "new"'); + logger.log('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') change to "new"'); break; case 'checking': - console.log('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') change to "checking"'); + logger.log('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') change to "checking"'); break; case 'connected': - console.log('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') change to "connected"'); + logger.log('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') change to "connected"'); break; case 'completed': - console.log('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') change to "completed"'); + logger.log('IceConnectionState of RTCPeerConnection ' + this.id + ' (' + otherId + ') change to "completed"'); break; } } diff --git a/openvidu-browser/src/OpenViduInternal/WebRtcStats/WebRtcStats.ts b/openvidu-browser/src/OpenViduInternal/WebRtcStats/WebRtcStats.ts index f08b6beb..502adc0e 100644 --- a/openvidu-browser/src/OpenViduInternal/WebRtcStats/WebRtcStats.ts +++ b/openvidu-browser/src/OpenViduInternal/WebRtcStats/WebRtcStats.ts @@ -19,6 +19,12 @@ import { Stream } from '../../OpenVidu/Stream'; import platform = require('platform'); +import { OpenViduLogger } from '../Logger/OpenViduLogger'; +/** + * @hidden + */ +const logger: OpenViduLogger = OpenViduLogger.getInstance(); + export class WebRtcStats { @@ -67,14 +73,14 @@ export class WebRtcStats { if (!!elastestInstrumentation) { // ElasTest instrumentation object found in local storage - console.warn('WebRtc stats enabled for stream ' + this.stream.streamId + ' of connection ' + this.stream.connection.connectionId); + logger.warn('WebRtc stats enabled for stream ' + this.stream.streamId + ' of connection ' + this.stream.connection.connectionId); this.webRtcStatsEnabled = true; const instrumentation = JSON.parse(elastestInstrumentation); this.statsInterval = instrumentation.webrtc.interval; // Interval in seconds - console.warn('localStorage item: ' + JSON.stringify(instrumentation)); + logger.warn('localStorage item: ' + JSON.stringify(instrumentation)); this.webRtcStatsIntervalId = setInterval(() => { this.sendStatsToHttpEndpoint(instrumentation); @@ -83,13 +89,13 @@ export class WebRtcStats { return; } - console.debug('WebRtc stats not enabled'); + logger.debug('WebRtc stats not enabled'); } public stopWebRtcStats() { if (this.webRtcStatsEnabled) { clearInterval(this.webRtcStatsIntervalId); - console.warn('WebRtc stats stopped for disposed stream ' + this.stream.streamId + ' of connection ' + this.stream.connection.connectionId); + logger.warn('WebRtc stats stopped for disposed stream ' + this.stream.streamId + ' of connection ' + this.stream.connection.connectionId); } } @@ -167,7 +173,7 @@ export class WebRtcStats { http.onreadystatechange = () => { // Call a function when the state changes. if (http.readyState === 4 && http.status === 200) { - console.log('WebRtc stats successfully sent to ' + url + ' for stream ' + this.stream.streamId + ' of connection ' + this.stream.connection.connectionId); + logger.log('WebRtc stats successfully sent to ' + url + ' for stream ' + this.stream.streamId + ' of connection ' + this.stream.connection.connectionId); } }; http.send(json); @@ -364,16 +370,16 @@ export class WebRtcStats { } }; - this.getStatsAgnostic(this.stream.getRTCPeerConnection(), f, (error) => { console.log(error); }); + this.getStatsAgnostic(this.stream.getRTCPeerConnection(), f, (error) => { logger.log(error); }); } private standardizeReport(response) { - console.log(response); + logger.log(response); const standardReport = {}; if (platform.name!.indexOf('Firefox') !== -1) { Object.keys(response).forEach(key => { - console.log(response[key]); + logger.log(response[key]); }); return response; }