openvidu-node-client: Added .prettierrc file and formated the code

pull/780/head
csantosm 2023-02-22 23:23:43 +01:00
parent e10198f501
commit 027e85052a
18 changed files with 897 additions and 900 deletions

View File

@ -0,0 +1,10 @@
{
"singleQuote": true,
"printWidth": 140,
"trailingComma": "none",
"semi": true,
"bracketSpacing": true,
"useTabs": false,
"jsxSingleQuote": true,
"tabWidth": 4
}

View File

@ -24,7 +24,6 @@ import { IceServerProperties } from './IceServerProperties';
* See {@link Session.connections} * See {@link Session.connections}
*/ */
export class Connection { export class Connection {
/** /**
* Identifier of the Connection. You can call methods {@link Session.forceDisconnect} * Identifier of the Connection. You can call methods {@link Session.forceDisconnect}
* or {@link Session.updateConnection} passing this property as parameter * or {@link Session.updateConnection} passing this property as parameter
@ -119,7 +118,6 @@ export class Connection {
* @hidden * @hidden
*/ */
resetWithJson(json): Connection { resetWithJson(json): Connection {
this.connectionId = json.connectionId; this.connectionId = json.connectionId;
this.status = json.status; this.status = json.status;
this.createdAt = json.createdAt; this.createdAt = json.createdAt;
@ -139,7 +137,7 @@ export class Connection {
this.connectionProperties.adaptativeBitrate = json.adaptativeBitrate; this.connectionProperties.adaptativeBitrate = json.adaptativeBitrate;
this.connectionProperties.onlyPlayWithSubscribers = json.onlyPlayWithSubscribers; this.connectionProperties.onlyPlayWithSubscribers = json.onlyPlayWithSubscribers;
this.connectionProperties.networkCache = json.networkCache; this.connectionProperties.networkCache = json.networkCache;
this.connectionProperties.customIceServers = json.customIceServers ?? [] this.connectionProperties.customIceServers = json.customIceServers ?? [];
} else { } else {
this.connectionProperties = { this.connectionProperties = {
type: json.type, type: json.type,
@ -152,21 +150,19 @@ export class Connection {
onlyPlayWithSubscribers: json.onlyPlayWithSubscribers, onlyPlayWithSubscribers: json.onlyPlayWithSubscribers,
networkCache: json.networkCache, networkCache: json.networkCache,
customIceServers: json.customIceServers ?? [] customIceServers: json.customIceServers ?? []
} };
} }
this.role = json.role; this.role = json.role;
this.serverData = json.serverData; this.serverData = json.serverData;
// publishers may be null // publishers may be null
if (json.publishers != null) { if (json.publishers != null) {
// 1. Array to store fetched Publishers and later remove closed ones // 1. Array to store fetched Publishers and later remove closed ones
const fetchedPublisherIds: string[] = []; const fetchedPublisherIds: string[] = [];
json.publishers.forEach(jsonPublisher => { json.publishers.forEach((jsonPublisher) => {
const publisherObj: Publisher = new Publisher(jsonPublisher); const publisherObj: Publisher = new Publisher(jsonPublisher);
fetchedPublisherIds.push(publisherObj.streamId); fetchedPublisherIds.push(publisherObj.streamId);
let storedPublisher = this.publishers.find(c => c.streamId === publisherObj.streamId); let storedPublisher = this.publishers.find((c) => c.streamId === publisherObj.streamId);
if (!!storedPublisher) { if (!!storedPublisher) {
// 2. Update existing Publisher // 2. Update existing Publisher
@ -183,16 +179,14 @@ export class Connection {
this.publishers.splice(i, 1); this.publishers.splice(i, 1);
} }
} }
} }
// subscribers may be null // subscribers may be null
if (json.subscribers != null) { if (json.subscribers != null) {
// 1. Array to store fetched Subscribers and later remove closed ones // 1. Array to store fetched Subscribers and later remove closed ones
const fetchedSubscriberIds: string[] = []; const fetchedSubscriberIds: string[] = [];
json.subscribers.forEach(jsonSubscriber => { json.subscribers.forEach((jsonSubscriber) => {
fetchedSubscriberIds.push(jsonSubscriber.streamId) fetchedSubscriberIds.push(jsonSubscriber.streamId);
if (this.subscribers.indexOf(jsonSubscriber.streamId) === -1) { if (this.subscribers.indexOf(jsonSubscriber.streamId) === -1) {
// 2. Add new Subscriber // 2. Add new Subscriber
this.subscribers.push(jsonSubscriber.streamId); this.subscribers.push(jsonSubscriber.streamId);
@ -214,7 +208,7 @@ export class Connection {
* @hidden * @hidden
*/ */
equalTo(other: Connection): boolean { equalTo(other: Connection): boolean {
let equals: boolean = ( let equals: boolean =
this.connectionId === other.connectionId && this.connectionId === other.connectionId &&
this.status === other.status && this.status === other.status &&
this.createdAt === other.createdAt && this.createdAt === other.createdAt &&
@ -234,18 +228,19 @@ export class Connection {
this.platform === other.platform && this.platform === other.platform &&
this.clientData === other.clientData && this.clientData === other.clientData &&
this.subscribers.length === other.subscribers.length && this.subscribers.length === other.subscribers.length &&
this.publishers.length === other.publishers.length); this.publishers.length === other.publishers.length;
if (equals) { if (equals) {
if (this.connectionProperties.kurentoOptions != null) { if (this.connectionProperties.kurentoOptions != null) {
equals = JSON.stringify(this.connectionProperties.kurentoOptions) === JSON.stringify(other.connectionProperties.kurentoOptions); equals =
JSON.stringify(this.connectionProperties.kurentoOptions) === JSON.stringify(other.connectionProperties.kurentoOptions);
} else { } else {
equals = (this.connectionProperties.kurentoOptions === other.connectionProperties.kurentoOptions); equals = this.connectionProperties.kurentoOptions === other.connectionProperties.kurentoOptions;
} }
} }
if (equals) { if (equals) {
if (this.connectionProperties.customIceServers != null) { if (this.connectionProperties.customIceServers != null) {
// Order alphabetically Ice servers using url just to keep the same list order. // Order alphabetically Ice servers using url just to keep the same list order.
const simpleIceComparator = (a: IceServerProperties, b: IceServerProperties) => (a.url > b.url) ? 1 : -1 const simpleIceComparator = (a: IceServerProperties, b: IceServerProperties) => (a.url > b.url ? 1 : -1);
const sortedIceServers = this.connectionProperties.customIceServers.sort(simpleIceComparator); const sortedIceServers = this.connectionProperties.customIceServers.sort(simpleIceComparator);
const sortedOtherIceServers = other.connectionProperties.customIceServers.sort(simpleIceComparator); const sortedOtherIceServers = other.connectionProperties.customIceServers.sort(simpleIceComparator);
equals = JSON.stringify(sortedIceServers) === JSON.stringify(sortedOtherIceServers); equals = JSON.stringify(sortedIceServers) === JSON.stringify(sortedOtherIceServers);
@ -280,5 +275,4 @@ export class Connection {
this.connectionProperties.role = newConnectionProperties.role; this.connectionProperties.role = newConnectionProperties.role;
} }
} }
} }

View File

@ -20,7 +20,6 @@ import { ConnectionType } from './ConnectionType';
import { OpenViduRole } from './OpenViduRole'; import { OpenViduRole } from './OpenViduRole';
export interface ConnectionProperties { export interface ConnectionProperties {
/** /**
* Type of Connection. The {@link ConnectionType} dictates what properties will have effect: * Type of Connection. The {@link ConnectionType} dictates what properties will have effect:
* *
@ -85,11 +84,11 @@ export interface ConnectionProperties {
* **Only for {@link ConnectionType.WEBRTC}** * **Only for {@link ConnectionType.WEBRTC}**
*/ */
kurentoOptions?: { kurentoOptions?: {
videoMaxRecvBandwidth?: number, videoMaxRecvBandwidth?: number;
videoMinRecvBandwidth?: number, videoMinRecvBandwidth?: number;
videoMaxSendBandwidth?: number, videoMaxSendBandwidth?: number;
videoMinSendBandwidth?: number, videoMinSendBandwidth?: number;
allowedFilters?: string[] allowedFilters?: string[];
}; };
/** /**

View File

@ -19,7 +19,6 @@
* See {@link Session.createConnection} * See {@link Session.createConnection}
*/ */
export enum ConnectionType { export enum ConnectionType {
/** /**
* WebRTC connection. This is the normal type of Connection for a regular user * WebRTC connection. This is the normal type of Connection for a regular user
* connecting to a session from an application. * connecting to a session from an application.

View File

@ -16,7 +16,6 @@
*/ */
export interface IceServerProperties { export interface IceServerProperties {
/** /**
* Set the url for the ICE Server you want to use. * Set the url for the ICE Server you want to use.
* It should follow a valid format: * It should follow a valid format:
@ -46,5 +45,4 @@ export interface IceServerProperties {
* This parameter should be defined only for TURN, not for STUN ICE Servers. * This parameter should be defined only for TURN, not for STUN ICE Servers.
*/ */
credential?: string; credential?: string;
} }

View File

@ -19,7 +19,6 @@
* See {@link SessionProperties.mediaMode} * See {@link SessionProperties.mediaMode}
*/ */
export enum MediaMode { export enum MediaMode {
/** /**
* _(not available yet)_ The session will attempt to transmit streams directly between clients * _(not available yet)_ The session will attempt to transmit streams directly between clients
*/ */

File diff suppressed because it is too large Load Diff

View File

@ -19,7 +19,6 @@
* See {@link TokenOptions.role} * See {@link TokenOptions.role}
*/ */
export enum OpenViduRole { export enum OpenViduRole {
/** /**
* Can subscribe to published Streams of other users * Can subscribe to published Streams of other users
*/ */

View File

@ -15,14 +15,12 @@
* *
*/ */
/** /**
* See {@link Connection.publishers} * See {@link Connection.publishers}
* *
* This is a backend representation of a published media stream (see [OpenVidu Browser Stream class](/en/stable/api/openvidu-browser/classes/Stream.html)) * This is a backend representation of a published media stream (see [OpenVidu Browser Stream class](/en/stable/api/openvidu-browser/classes/Stream.html))
*/ */
export class Publisher { export class Publisher {
/** /**
* Unique identifier of the [Stream](/en/stable/api/openvidu-browser/classes/Stream.html) associated to this Publisher. * Unique identifier of the [Stream](/en/stable/api/openvidu-browser/classes/Stream.html) associated to this Publisher.
* Each Publisher is paired with only one Stream, so you can identify each Publisher by its * Each Publisher is paired with only one Stream, so you can identify each Publisher by its
@ -109,5 +107,4 @@ export class Publisher {
this.videoDimensions === other.videoDimensions this.videoDimensions === other.videoDimensions
); );
} }
} }

View File

@ -22,7 +22,6 @@ import { RecordingLayout } from './RecordingLayout';
* See {@link OpenVidu.startRecording} * See {@link OpenVidu.startRecording}
*/ */
export class Recording { export class Recording {
/** /**
* Recording unique identifier * Recording unique identifier
*/ */
@ -63,7 +62,6 @@ export class Recording {
*/ */
properties: RecordingProperties; properties: RecordingProperties;
/* tslint:disable:no-string-literal */ /* tslint:disable:no-string-literal */
/** /**
* @hidden * @hidden
@ -77,37 +75,44 @@ export class Recording {
this.url = json['url']; this.url = json['url'];
this.status = json['status']; this.status = json['status'];
this.properties = { this.properties = {
name: (json['name'] != null) ? json['name'] : this.id, name: json['name'] != null ? json['name'] : this.id,
hasAudio: (json['hasAudio'] != null) ? !!json['hasAudio'] : Recording.DefaultRecordingPropertiesValues.hasAudio, hasAudio: json['hasAudio'] != null ? !!json['hasAudio'] : Recording.DefaultRecordingPropertiesValues.hasAudio,
hasVideo: (json['hasVideo'] != null) ? !!json['hasVideo'] : Recording.DefaultRecordingPropertiesValues.hasVideo, hasVideo: json['hasVideo'] != null ? !!json['hasVideo'] : Recording.DefaultRecordingPropertiesValues.hasVideo,
outputMode: (json['outputMode'] != null) ? json['outputMode'] : Recording.DefaultRecordingPropertiesValues.outputMode, outputMode: json['outputMode'] != null ? json['outputMode'] : Recording.DefaultRecordingPropertiesValues.outputMode,
mediaNode: json['mediaNode'] mediaNode: json['mediaNode']
}; };
if ((this.properties.outputMode.toString() === Recording.OutputMode[Recording.OutputMode.COMPOSED] if (
|| this.properties.outputMode.toString() === Recording.OutputMode[Recording.OutputMode.COMPOSED_QUICK_START]) (this.properties.outputMode.toString() === Recording.OutputMode[Recording.OutputMode.COMPOSED] ||
&& this.properties.hasVideo) { this.properties.outputMode.toString() === Recording.OutputMode[Recording.OutputMode.COMPOSED_QUICK_START]) &&
this.properties.recordingLayout = (json['recordingLayout'] != null) ? json['recordingLayout'] : Recording.DefaultRecordingPropertiesValues.recordingLayout; this.properties.hasVideo
this.properties.resolution = (json['resolution'] != null) ? json['resolution'] : Recording.DefaultRecordingPropertiesValues.resolution; ) {
this.properties.frameRate = (json['frameRate'] != null) ? Number(json['frameRate']) : Recording.DefaultRecordingPropertiesValues.frameRate; this.properties.recordingLayout =
this.properties.shmSize = (json['shmSize'] != null) ? Number(json['shmSize']) : Recording.DefaultRecordingPropertiesValues.shmSize; json['recordingLayout'] != null ? json['recordingLayout'] : Recording.DefaultRecordingPropertiesValues.recordingLayout;
this.properties.resolution =
json['resolution'] != null ? json['resolution'] : Recording.DefaultRecordingPropertiesValues.resolution;
this.properties.frameRate =
json['frameRate'] != null ? Number(json['frameRate']) : Recording.DefaultRecordingPropertiesValues.frameRate;
this.properties.shmSize =
json['shmSize'] != null ? Number(json['shmSize']) : Recording.DefaultRecordingPropertiesValues.shmSize;
if (this.properties.recordingLayout.toString() === RecordingLayout[RecordingLayout.CUSTOM]) { if (this.properties.recordingLayout.toString() === RecordingLayout[RecordingLayout.CUSTOM]) {
this.properties.customLayout = (json['customLayout'] != null) ? json['customLayout'] : ''; this.properties.customLayout = json['customLayout'] != null ? json['customLayout'] : '';
} }
} }
if (this.properties.outputMode.toString() === Recording.OutputMode[Recording.OutputMode.INDIVIDUAL]) { if (this.properties.outputMode.toString() === Recording.OutputMode[Recording.OutputMode.INDIVIDUAL]) {
this.properties.ignoreFailedStreams = (json['ignoreFailedStreams'] != null) ? !!json['ignoreFailedStreams'] : Recording.DefaultRecordingPropertiesValues.ignoreFailedStreams; this.properties.ignoreFailedStreams =
json['ignoreFailedStreams'] != null
? !!json['ignoreFailedStreams']
: Recording.DefaultRecordingPropertiesValues.ignoreFailedStreams;
} }
} }
/* tslint:enable:no-string-literal */ /* tslint:enable:no-string-literal */
} }
export namespace Recording { export namespace Recording {
/** /**
* See {@link Recording.status} * See {@link Recording.status}
*/ */
export enum Status { export enum Status {
/** /**
* The recording is starting (cannot be stopped). Some recording may not go * The recording is starting (cannot be stopped). Some recording may not go
* through this status and directly reach "started" status * through this status and directly reach "started" status
@ -142,7 +147,6 @@ export namespace Recording {
* See {@link RecordingProperties.outputMode} * See {@link RecordingProperties.outputMode}
*/ */
export enum OutputMode { export enum OutputMode {
/** /**
* Record all streams in a grid layout in a single archive * Record all streams in a grid layout in a single archive
*/ */
@ -181,10 +185,9 @@ export namespace Recording {
static readonly hasVideo: boolean = true; static readonly hasVideo: boolean = true;
static readonly outputMode: Recording.OutputMode = Recording.OutputMode.COMPOSED; static readonly outputMode: Recording.OutputMode = Recording.OutputMode.COMPOSED;
static readonly recordingLayout: RecordingLayout = RecordingLayout.BEST_FIT; static readonly recordingLayout: RecordingLayout = RecordingLayout.BEST_FIT;
static readonly resolution: string = "1280x720"; static readonly resolution: string = '1280x720';
static readonly frameRate: number = 25; static readonly frameRate: number = 25;
static readonly shmSize: number = 536870912; static readonly shmSize: number = 536870912;
static readonly ignoreFailedStreams: boolean = false; static readonly ignoreFailedStreams: boolean = false;
} }
} }

View File

@ -19,7 +19,6 @@
* See {@link RecordingProperties.recordingLayout} * See {@link RecordingProperties.recordingLayout}
*/ */
export enum RecordingLayout { export enum RecordingLayout {
/** /**
* All the videos are evenly distributed, taking up as much space as possible * All the videos are evenly distributed, taking up as much space as possible
*/ */

View File

@ -19,7 +19,6 @@
* See {@link SessionProperties.recordingMode} * See {@link SessionProperties.recordingMode}
*/ */
export enum RecordingMode { export enum RecordingMode {
/** /**
* The session is recorded automatically as soon as the first client publishes a stream to the session. It is automatically stopped * The session is recorded automatically as soon as the first client publishes a stream to the session. It is automatically stopped
* after last user leaves the session (or until you call {@link OpenVidu.stopRecording}). * after last user leaves the session (or until you call {@link OpenVidu.stopRecording}).

View File

@ -22,7 +22,6 @@ import { RecordingLayout } from './RecordingLayout';
* See {@link OpenVidu.startRecording} * See {@link OpenVidu.startRecording}
*/ */
export interface RecordingProperties { export interface RecordingProperties {
/** /**
* Name of the Recording. The video file will be named after this property. * Name of the Recording. The video file will be named after this property.
* You can access this same value in your clients on recording events * You can access this same value in your clients on recording events
@ -122,6 +121,5 @@ export interface RecordingProperties {
*/ */
mediaNode?: { mediaNode?: {
id: string; id: string;
} };
} }

View File

@ -30,7 +30,6 @@ import { RecordingProperties } from './RecordingProperties';
import { IceServerProperties } from './IceServerProperties'; import { IceServerProperties } from './IceServerProperties';
export class Session { export class Session {
/** /**
* Unique identifier of the Session * Unique identifier of the Session
*/ */
@ -110,21 +109,18 @@ export class Session {
return new Promise<string>((resolve, reject) => { return new Promise<string>((resolve, reject) => {
const data = JSON.stringify({ const data = JSON.stringify({
session: this.sessionId, session: this.sessionId,
role: (!!tokenOptions && !!tokenOptions.role) ? tokenOptions.role : null, role: !!tokenOptions && !!tokenOptions.role ? tokenOptions.role : null,
data: (!!tokenOptions && !!tokenOptions.data) ? tokenOptions.data : null, data: !!tokenOptions && !!tokenOptions.data ? tokenOptions.data : null,
kurentoOptions: (!!tokenOptions && !!tokenOptions.kurentoOptions) ? tokenOptions.kurentoOptions : null kurentoOptions: !!tokenOptions && !!tokenOptions.kurentoOptions ? tokenOptions.kurentoOptions : null
}); });
axios.post( axios
this.ov.host + OpenVidu.API_TOKENS, .post(this.ov.host + OpenVidu.API_TOKENS, data, {
data,
{
headers: { headers: {
'Authorization': this.ov.basicAuth, Authorization: this.ov.basicAuth,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
} })
) .then((res) => {
.then(res => {
if (res.status === 200) { if (res.status === 200) {
// SUCCESS response from openvidu-server. Resolve token // SUCCESS response from openvidu-server. Resolve token
resolve(res.data.token); resolve(res.data.token);
@ -132,7 +128,8 @@ export class Session {
// ERROR response from openvidu-server. Resolve HTTP status // ERROR response from openvidu-server. Resolve HTTP status
reject(new Error(res.status.toString())); reject(new Error(res.status.toString()));
} }
}).catch(error => { })
.catch((error) => {
this.ov.handleError(error, reject); this.ov.handleError(error, reject);
}); });
}); });
@ -149,28 +146,28 @@ export class Session {
public createConnection(connectionProperties?: ConnectionProperties): Promise<Connection> { public createConnection(connectionProperties?: ConnectionProperties): Promise<Connection> {
return new Promise<Connection>((resolve, reject) => { return new Promise<Connection>((resolve, reject) => {
const data = JSON.stringify({ const data = JSON.stringify({
type: (!!connectionProperties && !!connectionProperties.type) ? connectionProperties.type : null, type: !!connectionProperties && !!connectionProperties.type ? connectionProperties.type : null,
data: (!!connectionProperties && !!connectionProperties.data) ? connectionProperties.data : null, data: !!connectionProperties && !!connectionProperties.data ? connectionProperties.data : null,
record: !!connectionProperties ? connectionProperties.record : null, record: !!connectionProperties ? connectionProperties.record : null,
role: (!!connectionProperties && !!connectionProperties.role) ? connectionProperties.role : null, role: !!connectionProperties && !!connectionProperties.role ? connectionProperties.role : null,
kurentoOptions: (!!connectionProperties && !!connectionProperties.kurentoOptions) ? connectionProperties.kurentoOptions : null, kurentoOptions:
rtspUri: (!!connectionProperties && !!connectionProperties.rtspUri) ? connectionProperties.rtspUri : null, !!connectionProperties && !!connectionProperties.kurentoOptions ? connectionProperties.kurentoOptions : null,
rtspUri: !!connectionProperties && !!connectionProperties.rtspUri ? connectionProperties.rtspUri : null,
adaptativeBitrate: !!connectionProperties ? connectionProperties.adaptativeBitrate : null, adaptativeBitrate: !!connectionProperties ? connectionProperties.adaptativeBitrate : null,
onlyPlayWithSubscribers: !!connectionProperties ? connectionProperties.onlyPlayWithSubscribers : null, onlyPlayWithSubscribers: !!connectionProperties ? connectionProperties.onlyPlayWithSubscribers : null,
networkCache: (!!connectionProperties && (connectionProperties.networkCache != null)) ? connectionProperties.networkCache : null, networkCache:
customIceServers: (!!connectionProperties && (!!connectionProperties.customIceServers != null)) ? connectionProperties.customIceServers : null !!connectionProperties && connectionProperties.networkCache != null ? connectionProperties.networkCache : null,
customIceServers:
!!connectionProperties && !!connectionProperties.customIceServers != null ? connectionProperties.customIceServers : null
}); });
axios.post( axios
this.ov.host + OpenVidu.API_SESSIONS + '/' + this.sessionId + '/connection', .post(this.ov.host + OpenVidu.API_SESSIONS + '/' + this.sessionId + '/connection', data, {
data,
{
headers: { headers: {
'Authorization': this.ov.basicAuth, Authorization: this.ov.basicAuth,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
} })
) .then((res) => {
.then(res => {
if (res.status === 200) { if (res.status === 200) {
// SUCCESS response from openvidu-server. Store and resolve Connection // SUCCESS response from openvidu-server. Store and resolve Connection
const connection = new Connection(res.data); const connection = new Connection(res.data);
@ -183,7 +180,8 @@ export class Session {
// ERROR response from openvidu-server. Resolve HTTP status // ERROR response from openvidu-server. Resolve HTTP status
reject(new Error(res.status.toString())); reject(new Error(res.status.toString()));
} }
}).catch(error => { })
.catch((error) => {
this.ov.handleError(error, reject); this.ov.handleError(error, reject);
}); });
}); });
@ -197,26 +195,25 @@ export class Session {
*/ */
public close(): Promise<void> { public close(): Promise<void> {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
axios.delete( axios
this.ov.host + OpenVidu.API_SESSIONS + '/' + this.sessionId, .delete(this.ov.host + OpenVidu.API_SESSIONS + '/' + this.sessionId, {
{
headers: { headers: {
'Authorization': this.ov.basicAuth, Authorization: this.ov.basicAuth,
'Content-Type': 'application/x-www-form-urlencoded' 'Content-Type': 'application/x-www-form-urlencoded'
} }
} })
) .then((res) => {
.then(res => {
if (res.status === 204) { if (res.status === 204) {
// SUCCESS response from openvidu-server // SUCCESS response from openvidu-server
const indexToRemove: number = this.ov.activeSessions.findIndex(s => s.sessionId === this.sessionId); const indexToRemove: number = this.ov.activeSessions.findIndex((s) => s.sessionId === this.sessionId);
this.ov.activeSessions.splice(indexToRemove, 1); this.ov.activeSessions.splice(indexToRemove, 1);
resolve(); resolve();
} else { } else {
// ERROR response from openvidu-server. Resolve HTTP status // ERROR response from openvidu-server. Resolve HTTP status
reject(new Error(res.status.toString())); reject(new Error(res.status.toString()));
} }
}).catch(error => { })
.catch((error) => {
this.ov.handleError(error, reject); this.ov.handleError(error, reject);
}); });
}); });
@ -235,16 +232,14 @@ export class Session {
public fetch(): Promise<boolean> { public fetch(): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => { return new Promise<boolean>((resolve, reject) => {
const beforeJSON: string = JSON.stringify(this, this.removeCircularOpenViduReference); const beforeJSON: string = JSON.stringify(this, this.removeCircularOpenViduReference);
axios.get( axios
this.ov.host + OpenVidu.API_SESSIONS + '/' + this.sessionId + '?pendingConnections=true', .get(this.ov.host + OpenVidu.API_SESSIONS + '/' + this.sessionId + '?pendingConnections=true', {
{
headers: { headers: {
'Authorization': this.ov.basicAuth, Authorization: this.ov.basicAuth,
'Content-Type': 'application/x-www-form-urlencoded' 'Content-Type': 'application/x-www-form-urlencoded'
} }
} })
) .then((res) => {
.then(res => {
if (res.status === 200) { if (res.status === 200) {
// SUCCESS response from openvidu-server // SUCCESS response from openvidu-server
this.resetWithJson(res.data); this.resetWithJson(res.data);
@ -256,7 +251,8 @@ export class Session {
// ERROR response from openvidu-server. Resolve HTTP status // ERROR response from openvidu-server. Resolve HTTP status
reject(new Error(res.status.toString())); reject(new Error(res.status.toString()));
} }
}).catch(error => { })
.catch((error) => {
this.ov.handleError(error, reject); this.ov.handleError(error, reject);
}); });
}); });
@ -282,20 +278,19 @@ export class Session {
public forceDisconnect(connection: string | Connection): Promise<void> { public forceDisconnect(connection: string | Connection): Promise<void> {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
const connectionId: string = typeof connection === 'string' ? connection : (<Connection>connection).connectionId; const connectionId: string = typeof connection === 'string' ? connection : (<Connection>connection).connectionId;
axios.delete( axios
this.ov.host + OpenVidu.API_SESSIONS + '/' + this.sessionId + '/connection/' + connectionId, .delete(this.ov.host + OpenVidu.API_SESSIONS + '/' + this.sessionId + '/connection/' + connectionId, {
{
headers: { headers: {
'Authorization': this.ov.basicAuth, Authorization: this.ov.basicAuth,
'Content-Type': 'application/x-www-form-urlencoded' 'Content-Type': 'application/x-www-form-urlencoded'
} }
}) })
.then(res => { .then((res) => {
if (res.status === 204) { if (res.status === 204) {
// SUCCESS response from openvidu-server // SUCCESS response from openvidu-server
// Remove connection from connections array // Remove connection from connections array
let connectionClosed; let connectionClosed;
this.connections = this.connections.filter(con => { this.connections = this.connections.filter((con) => {
if (con.connectionId !== connectionId) { if (con.connectionId !== connectionId) {
return true; return true;
} else { } else {
@ -305,13 +300,13 @@ export class Session {
}); });
// Remove every Publisher of the closed connection from every subscriber list of other connections // Remove every Publisher of the closed connection from every subscriber list of other connections
if (!!connectionClosed) { if (!!connectionClosed) {
connectionClosed.publishers.forEach(publisher => { connectionClosed.publishers.forEach((publisher) => {
this.connections.forEach(con => { this.connections.forEach((con) => {
con.subscribers = con.subscribers.filter(subscriber => { con.subscribers = con.subscribers.filter((subscriber) => {
// tslint:disable:no-string-literal // tslint:disable:no-string-literal
if (!!subscriber['streamId']) { if (!!subscriber['streamId']) {
// Subscriber with advanced webRtc configuration properties // Subscriber with advanced webRtc configuration properties
return (subscriber['streamId'] !== publisher.streamId); return subscriber['streamId'] !== publisher.streamId;
// tslint:enable:no-string-literal // tslint:enable:no-string-literal
} else { } else {
// Regular string subscribers // Regular string subscribers
@ -321,7 +316,9 @@ export class Session {
}); });
}); });
} else { } else {
console.warn("The closed connection wasn't fetched in OpenVidu Node Client. No changes in the collection of active connections of the Session"); console.warn(
"The closed connection wasn't fetched in OpenVidu Node Client. No changes in the collection of active connections of the Session"
);
} }
this.updateActiveConnectionsArray(); this.updateActiveConnectionsArray();
console.log("Connection '" + connectionId + "' closed"); console.log("Connection '" + connectionId + "' closed");
@ -331,7 +328,7 @@ export class Session {
reject(new Error(res.status.toString())); reject(new Error(res.status.toString()));
} }
}) })
.catch(error => { .catch((error) => {
this.ov.handleError(error, reject); this.ov.handleError(error, reject);
}); });
}); });
@ -355,31 +352,29 @@ export class Session {
public forceUnpublish(publisher: string | Publisher): Promise<void> { public forceUnpublish(publisher: string | Publisher): Promise<void> {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
const streamId: string = typeof publisher === 'string' ? publisher : (<Publisher>publisher).streamId; const streamId: string = typeof publisher === 'string' ? publisher : (<Publisher>publisher).streamId;
axios.delete( axios
this.ov.host + OpenVidu.API_SESSIONS + '/' + this.sessionId + '/stream/' + streamId, .delete(this.ov.host + OpenVidu.API_SESSIONS + '/' + this.sessionId + '/stream/' + streamId, {
{
headers: { headers: {
'Authorization': this.ov.basicAuth, Authorization: this.ov.basicAuth,
'Content-Type': 'application/x-www-form-urlencoded' 'Content-Type': 'application/x-www-form-urlencoded'
} }
} })
) .then((res) => {
.then(res => {
if (res.status === 204) { if (res.status === 204) {
// SUCCESS response from openvidu-server // SUCCESS response from openvidu-server
this.connections.forEach(connection => { this.connections.forEach((connection) => {
// Try to remove the Publisher from the Connection publishers collection // Try to remove the Publisher from the Connection publishers collection
connection.publishers = connection.publishers.filter(pub => pub.streamId !== streamId); connection.publishers = connection.publishers.filter((pub) => pub.streamId !== streamId);
// Try to remove the Publisher from the Connection subscribers collection // Try to remove the Publisher from the Connection subscribers collection
if (!!connection.subscribers && connection.subscribers.length > 0) { if (!!connection.subscribers && connection.subscribers.length > 0) {
// tslint:disable:no-string-literal // tslint:disable:no-string-literal
if (!!connection.subscribers[0]['streamId']) { if (!!connection.subscribers[0]['streamId']) {
// Subscriber with advanced webRtc configuration properties // Subscriber with advanced webRtc configuration properties
connection.subscribers = connection.subscribers.filter(sub => sub['streamId'] !== streamId); connection.subscribers = connection.subscribers.filter((sub) => sub['streamId'] !== streamId);
// tslint:enable:no-string-literal // tslint:enable:no-string-literal
} else { } else {
// Regular string subscribers // Regular string subscribers
connection.subscribers = connection.subscribers.filter(sub => sub !== streamId); connection.subscribers = connection.subscribers.filter((sub) => sub !== streamId);
} }
} }
}); });
@ -390,7 +385,8 @@ export class Session {
// ERROR response from openvidu-server. Resolve HTTP status // ERROR response from openvidu-server. Resolve HTTP status
reject(new Error(res.status.toString())); reject(new Error(res.status.toString()));
} }
}).catch(error => { })
.catch((error) => {
this.ov.handleError(error, reject); this.ov.handleError(error, reject);
}); });
}); });
@ -423,17 +419,14 @@ export class Session {
*/ */
public updateConnection(connectionId: string, connectionProperties: ConnectionProperties): Promise<Connection | undefined> { public updateConnection(connectionId: string, connectionProperties: ConnectionProperties): Promise<Connection | undefined> {
return new Promise<any>((resolve, reject) => { return new Promise<any>((resolve, reject) => {
axios.patch( axios
this.ov.host + OpenVidu.API_SESSIONS + "/" + this.sessionId + "/connection/" + connectionId, .patch(this.ov.host + OpenVidu.API_SESSIONS + '/' + this.sessionId + '/connection/' + connectionId, connectionProperties, {
connectionProperties,
{
headers: { headers: {
'Authorization': this.ov.basicAuth, Authorization: this.ov.basicAuth,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
} })
) .then((res) => {
.then(res => {
if (res.status === 200) { if (res.status === 200) {
console.log('Connection ' + connectionId + ' updated'); console.log('Connection ' + connectionId + ' updated');
} else { } else {
@ -442,7 +435,7 @@ export class Session {
return; return;
} }
// Update the actual Connection object with the new options // Update the actual Connection object with the new options
const existingConnection: Connection = this.connections.find(con => con.connectionId === connectionId); const existingConnection: Connection = this.connections.find((con) => con.connectionId === connectionId);
if (!existingConnection) { if (!existingConnection) {
// The updated Connection is not available in local map // The updated Connection is not available in local map
const newConnection: Connection = new Connection(res.data); const newConnection: Connection = new Connection(res.data);
@ -455,7 +448,8 @@ export class Session {
this.updateActiveConnectionsArray(); this.updateActiveConnectionsArray();
resolve(existingConnection); resolve(existingConnection);
} }
}).catch(error => { })
.catch((error) => {
this.ov.handleError(error, reject); this.ov.handleError(error, reject);
}); });
}); });
@ -473,28 +467,22 @@ export class Session {
*/ */
public getSessionHttp(): Promise<string> { public getSessionHttp(): Promise<string> {
return new Promise<string>((resolve, reject) => { return new Promise<string>((resolve, reject) => {
if (!!this.sessionId) { if (!!this.sessionId) {
resolve(this.sessionId); resolve(this.sessionId);
} }
this.sanitizeDefaultSessionProperties(this.properties); this.sanitizeDefaultSessionProperties(this.properties);
const data = JSON.stringify( const data = JSON.stringify(this.properties);
this.properties
);
axios.post( axios
this.ov.host + OpenVidu.API_SESSIONS, .post(this.ov.host + OpenVidu.API_SESSIONS, data, {
data,
{
headers: { headers: {
'Authorization': this.ov.basicAuth, Authorization: this.ov.basicAuth,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
} })
) .then((res) => {
.then(res => {
if (res.status === 200) { if (res.status === 200) {
// SUCCESS response from openvidu-server. Resolve token // SUCCESS response from openvidu-server. Resolve token
this.sessionId = res.data.id; this.sessionId = res.data.id;
@ -512,7 +500,8 @@ export class Session {
// ERROR response from openvidu-server. Resolve HTTP status // ERROR response from openvidu-server. Resolve HTTP status
reject(new Error(res.status.toString())); reject(new Error(res.status.toString()));
} }
}).catch(error => { })
.catch((error) => {
if (!!error.response && error.response.status === 409) { if (!!error.response && error.response.status === 409) {
// 'customSessionId' already existed // 'customSessionId' already existed
this.sessionId = this.properties.customSessionId; this.sessionId = this.properties.customSessionId;
@ -559,10 +548,10 @@ export class Session {
// 1. Array to store fetched connections and later remove closed ones // 1. Array to store fetched connections and later remove closed ones
const fetchedConnectionIds: string[] = []; const fetchedConnectionIds: string[] = [];
json.connections.content.forEach(jsonConnection => { json.connections.content.forEach((jsonConnection) => {
const connectionObj: Connection = new Connection(jsonConnection); const connectionObj: Connection = new Connection(jsonConnection);
fetchedConnectionIds.push(connectionObj.connectionId); fetchedConnectionIds.push(connectionObj.connectionId);
let storedConnection = this.connections.find(c => c.connectionId === connectionObj.connectionId); let storedConnection = this.connections.find((c) => c.connectionId === connectionObj.connectionId);
if (!!storedConnection) { if (!!storedConnection) {
// 2. Update existing Connection // 2. Update existing Connection
@ -581,14 +570,13 @@ export class Session {
} }
// Order connections by time of creation // Order connections by time of creation
this.connections.sort((c1, c2) => (c1.createdAt > c2.createdAt) ? 1 : ((c2.createdAt > c1.createdAt) ? -1 : 0)); this.connections.sort((c1, c2) => (c1.createdAt > c2.createdAt ? 1 : c2.createdAt > c1.createdAt ? -1 : 0));
// Order Ice candidates in connection properties // Order Ice candidates in connection properties
this.connections.forEach(connection => { this.connections.forEach((connection) => {
if (connection.connectionProperties.customIceServers != null && if (connection.connectionProperties.customIceServers != null && connection.connectionProperties.customIceServers.length > 0) {
connection.connectionProperties.customIceServers.length > 0) {
// Order alphabetically Ice servers using url just to keep the same list order. // Order alphabetically Ice servers using url just to keep the same list order.
const simpleIceComparator = (a: IceServerProperties, b: IceServerProperties) => (a.url > b.url) ? 1 : -1 const simpleIceComparator = (a: IceServerProperties, b: IceServerProperties) => (a.url > b.url ? 1 : -1);
connection.connectionProperties.customIceServers.sort(simpleIceComparator); connection.connectionProperties.customIceServers.sort(simpleIceComparator);
} }
}); });
@ -601,14 +589,13 @@ export class Session {
* @hidden * @hidden
*/ */
equalTo(other: Session): boolean { equalTo(other: Session): boolean {
let equals: boolean = ( let equals: boolean =
this.sessionId === other.sessionId && this.sessionId === other.sessionId &&
this.createdAt === other.createdAt && this.createdAt === other.createdAt &&
this.recording === other.recording && this.recording === other.recording &&
this.broadcasting === other.broadcasting && this.broadcasting === other.broadcasting &&
this.connections.length === other.connections.length && this.connections.length === other.connections.length &&
JSON.stringify(this.properties) === JSON.stringify(other.properties) JSON.stringify(this.properties) === JSON.stringify(other.properties);
);
if (equals) { if (equals) {
let i = 0; let i = 0;
while (equals && i < this.connections.length) { while (equals && i < this.connections.length) {
@ -637,7 +624,7 @@ export class Session {
*/ */
private updateActiveConnectionsArray() { private updateActiveConnectionsArray() {
this.activeConnections = []; this.activeConnections = [];
this.connections.forEach(con => { this.connections.forEach((con) => {
if (con.status === 'active') { if (con.status === 'active') {
this.activeConnections.push(con); this.activeConnections.push(con);
} }
@ -648,10 +635,9 @@ export class Session {
* @hidden * @hidden
*/ */
private sanitizeDefaultSessionProperties(props: SessionProperties) { private sanitizeDefaultSessionProperties(props: SessionProperties) {
props.mediaMode = props.mediaMode != null ? props.mediaMode : MediaMode.ROUTED;
props.mediaMode = (props.mediaMode != null) ? props.mediaMode : MediaMode.ROUTED; props.recordingMode = props.recordingMode != null ? props.recordingMode : RecordingMode.MANUAL;
props.recordingMode = (props.recordingMode != null) ? props.recordingMode : RecordingMode.MANUAL; props.customSessionId = props.customSessionId != null ? props.customSessionId : '';
props.customSessionId = (props.customSessionId != null) ? props.customSessionId : '';
// Remove null values: either set, or undefined // Remove null values: either set, or undefined
props.mediaNode = props.mediaNode ?? undefined; props.mediaNode = props.mediaNode ?? undefined;
@ -661,22 +647,51 @@ export class Session {
if (!props.defaultRecordingProperties) { if (!props.defaultRecordingProperties) {
props.defaultRecordingProperties = {}; props.defaultRecordingProperties = {};
} }
props.defaultRecordingProperties.name = (props.defaultRecordingProperties?.name != null) ? props.defaultRecordingProperties.name : ''; props.defaultRecordingProperties.name = props.defaultRecordingProperties?.name != null ? props.defaultRecordingProperties.name : '';
props.defaultRecordingProperties.hasAudio = (props.defaultRecordingProperties?.hasAudio != null) ? props.defaultRecordingProperties.hasAudio : Recording.DefaultRecordingPropertiesValues.hasAudio; props.defaultRecordingProperties.hasAudio =
props.defaultRecordingProperties.hasVideo = (props.defaultRecordingProperties?.hasVideo != null) ? props.defaultRecordingProperties.hasVideo : Recording.DefaultRecordingPropertiesValues.hasVideo; props.defaultRecordingProperties?.hasAudio != null
props.defaultRecordingProperties.outputMode = (props.defaultRecordingProperties?.outputMode != null) ? props.defaultRecordingProperties.outputMode : Recording.DefaultRecordingPropertiesValues.outputMode; ? props.defaultRecordingProperties.hasAudio
: Recording.DefaultRecordingPropertiesValues.hasAudio;
props.defaultRecordingProperties.hasVideo =
props.defaultRecordingProperties?.hasVideo != null
? props.defaultRecordingProperties.hasVideo
: Recording.DefaultRecordingPropertiesValues.hasVideo;
props.defaultRecordingProperties.outputMode =
props.defaultRecordingProperties?.outputMode != null
? props.defaultRecordingProperties.outputMode
: Recording.DefaultRecordingPropertiesValues.outputMode;
props.defaultRecordingProperties.mediaNode = props.defaultRecordingProperties?.mediaNode; props.defaultRecordingProperties.mediaNode = props.defaultRecordingProperties?.mediaNode;
if ((props.defaultRecordingProperties.outputMode === Recording.OutputMode.COMPOSED || props.defaultRecordingProperties.outputMode == Recording.OutputMode.COMPOSED_QUICK_START) && props.defaultRecordingProperties.hasVideo) { if (
props.defaultRecordingProperties.recordingLayout = (props.defaultRecordingProperties.recordingLayout != null) ? props.defaultRecordingProperties.recordingLayout : Recording.DefaultRecordingPropertiesValues.recordingLayout; (props.defaultRecordingProperties.outputMode === Recording.OutputMode.COMPOSED ||
props.defaultRecordingProperties.resolution = (props.defaultRecordingProperties.resolution != null) ? props.defaultRecordingProperties.resolution : Recording.DefaultRecordingPropertiesValues.resolution; props.defaultRecordingProperties.outputMode == Recording.OutputMode.COMPOSED_QUICK_START) &&
props.defaultRecordingProperties.frameRate = (props.defaultRecordingProperties.frameRate != null) ? props.defaultRecordingProperties.frameRate : Recording.DefaultRecordingPropertiesValues.frameRate; props.defaultRecordingProperties.hasVideo
props.defaultRecordingProperties.shmSize = (props.defaultRecordingProperties.shmSize != null) ? props.defaultRecordingProperties.shmSize : Recording.DefaultRecordingPropertiesValues.shmSize; ) {
props.defaultRecordingProperties.recordingLayout =
props.defaultRecordingProperties.recordingLayout != null
? props.defaultRecordingProperties.recordingLayout
: Recording.DefaultRecordingPropertiesValues.recordingLayout;
props.defaultRecordingProperties.resolution =
props.defaultRecordingProperties.resolution != null
? props.defaultRecordingProperties.resolution
: Recording.DefaultRecordingPropertiesValues.resolution;
props.defaultRecordingProperties.frameRate =
props.defaultRecordingProperties.frameRate != null
? props.defaultRecordingProperties.frameRate
: Recording.DefaultRecordingPropertiesValues.frameRate;
props.defaultRecordingProperties.shmSize =
props.defaultRecordingProperties.shmSize != null
? props.defaultRecordingProperties.shmSize
: Recording.DefaultRecordingPropertiesValues.shmSize;
if (props.defaultRecordingProperties.recordingLayout === RecordingLayout.CUSTOM) { if (props.defaultRecordingProperties.recordingLayout === RecordingLayout.CUSTOM) {
props.defaultRecordingProperties.customLayout = (props.defaultRecordingProperties.customLayout != null) ? props.defaultRecordingProperties.customLayout : ''; props.defaultRecordingProperties.customLayout =
props.defaultRecordingProperties.customLayout != null ? props.defaultRecordingProperties.customLayout : '';
} }
} }
if (props.defaultRecordingProperties.outputMode === Recording.OutputMode.INDIVIDUAL) { if (props.defaultRecordingProperties.outputMode === Recording.OutputMode.INDIVIDUAL) {
props.defaultRecordingProperties.ignoreFailedStreams = (props.defaultRecordingProperties?.ignoreFailedStreams != null) ? props.defaultRecordingProperties.ignoreFailedStreams : Recording.DefaultRecordingPropertiesValues.ignoreFailedStreams; props.defaultRecordingProperties.ignoreFailedStreams =
props.defaultRecordingProperties?.ignoreFailedStreams != null
? props.defaultRecordingProperties.ignoreFailedStreams
: Recording.DefaultRecordingPropertiesValues.ignoreFailedStreams;
} }
this.formatMediaNodeObjectIfNecessary(props.defaultRecordingProperties); this.formatMediaNodeObjectIfNecessary(props.defaultRecordingProperties);
@ -693,5 +708,4 @@ export class Session {
} }
} }
} }
} }

View File

@ -24,7 +24,6 @@ import { VideoCodec } from './VideoCodec';
* See {@link OpenVidu.createSession} * See {@link OpenVidu.createSession}
*/ */
export interface SessionProperties { export interface SessionProperties {
/** /**
* How the media streams will be sent and received by your clients: routed through OpenVidu Media Node * How the media streams will be sent and received by your clients: routed through OpenVidu Media Node
* (`MediaMode.ROUTED`) or attempting direct p2p connections (`MediaMode.RELAYED`, _not available yet_) * (`MediaMode.ROUTED`) or attempting direct p2p connections (`MediaMode.RELAYED`, _not available yet_)
@ -68,7 +67,7 @@ export interface SessionProperties {
*/ */
mediaNode?: { mediaNode?: {
id: string; id: string;
} };
/** /**
* Define which video codec will be forcibly used for this session. * Define which video codec will be forcibly used for this session.

View File

@ -21,7 +21,6 @@ import { OpenViduRole } from './OpenViduRole';
* @deprecated Use {@link ConnectionProperties} instead * @deprecated Use {@link ConnectionProperties} instead
*/ */
export interface TokenOptions { export interface TokenOptions {
/** /**
* The role assigned to this token * The role assigned to this token
* *
@ -59,10 +58,10 @@ export interface TokenOptions {
* - `allowedFilters`: names of the filters the user owning the token will be able to apply. See [Voice and video filters](/en/stable/advanced-features/filters/) * - `allowedFilters`: names of the filters the user owning the token will be able to apply. See [Voice and video filters](/en/stable/advanced-features/filters/)
*/ */
kurentoOptions?: { kurentoOptions?: {
videoMaxRecvBandwidth?: number, videoMaxRecvBandwidth?: number;
videoMinRecvBandwidth?: number, videoMinRecvBandwidth?: number;
videoMaxSendBandwidth?: number, videoMaxSendBandwidth?: number;
videoMinSendBandwidth?: number, videoMinSendBandwidth?: number;
allowedFilters?: string[] allowedFilters?: string[];
}; };
} }

View File

@ -6,5 +6,5 @@ export enum VideoCodec {
NONE = 'NONE', NONE = 'NONE',
VP8 = 'VP8', VP8 = 'VP8',
VP9 = 'VP9', VP9 = 'VP9',
H264 = 'H264', H264 = 'H264'
} }