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
*/ */

View File

@ -25,11 +25,11 @@ import { SessionProperties } from './SessionProperties';
/** /**
* @hidden * @hidden
*/ */
interface ObjMap<T> { [s: string]: T; } interface ObjMap<T> {
[s: string]: T;
}
export class OpenVidu { export class OpenVidu {
private Buffer = require('buffer/').Buffer; private Buffer = require('buffer/').Buffer;
/** /**
@ -78,8 +78,6 @@ export class OpenVidu {
*/ */
static readonly API_BROADCAST_STOP: string = OpenVidu.API_BROADCAST + '/stop'; static readonly API_BROADCAST_STOP: string = OpenVidu.API_BROADCAST + '/stop';
/** /**
* Array of active sessions. **This value will remain unchanged since the last time method {@link OpenVidu.fetch} * Array of active sessions. **This value will remain unchanged since the last time method {@link OpenVidu.fetch}
* was called**. Exceptions to this rule are: * was called**. Exceptions to this rule are:
@ -123,12 +121,13 @@ export class OpenVidu {
public createSession(properties?: SessionProperties): Promise<Session> { public createSession(properties?: SessionProperties): Promise<Session> {
return new Promise<Session>((resolve, reject) => { return new Promise<Session>((resolve, reject) => {
const session = new Session(this, properties); const session = new Session(this, properties);
session.getSessionHttp() session
.then(response => { .getSessionHttp()
.then((response) => {
this.activeSessions.push(session); this.activeSessions.push(session);
resolve(session); resolve(session);
}) })
.catch(error => { .catch((error) => {
reject(error); reject(error);
}); });
}); });
@ -152,7 +151,6 @@ export class OpenVidu {
*/ */
public startRecording(sessionId: string, param2?: string | RecordingProperties): Promise<Recording> { public startRecording(sessionId: string, param2?: string | RecordingProperties): Promise<Recording> {
return new Promise<Recording>((resolve, reject) => { return new Promise<Recording>((resolve, reject) => {
let data; let data;
if (param2 != null) { if (param2 != null) {
@ -186,32 +184,34 @@ export class OpenVidu {
}); });
} }
axios.post( axios
this.host + OpenVidu.API_RECORDINGS_START, .post(this.host + OpenVidu.API_RECORDINGS_START, data, {
data,
{
headers: { headers: {
'Authorization': this.basicAuth, Authorization: this.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 (Recording in JSON format). Resolve new Recording // SUCCESS response from openvidu-server (Recording in JSON format). Resolve new Recording
const r: Recording = new Recording(res.data); const r: Recording = new Recording(res.data);
const activeSession = this.activeSessions.find(s => s.sessionId === r.sessionId); const activeSession = this.activeSessions.find((s) => s.sessionId === r.sessionId);
if (!!activeSession) { if (!!activeSession) {
activeSession.recording = true; activeSession.recording = true;
} else { } else {
console.warn("No active session found for sessionId '" + r.sessionId + "'. This instance of OpenVidu Node Client didn't create this session"); console.warn(
"No active session found for sessionId '" +
r.sessionId +
"'. This instance of OpenVidu Node Client didn't create this session"
);
} }
resolve(r); resolve(r);
} 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.handleError(error, reject); this.handleError(error, reject);
}); });
}); });
@ -229,33 +229,34 @@ export class OpenVidu {
*/ */
public stopRecording(recordingId: string): Promise<Recording> { public stopRecording(recordingId: string): Promise<Recording> {
return new Promise<Recording>((resolve, reject) => { return new Promise<Recording>((resolve, reject) => {
axios
axios.post( .post(this.host + OpenVidu.API_RECORDINGS_STOP + '/' + recordingId, undefined, {
this.host + OpenVidu.API_RECORDINGS_STOP + '/' + recordingId,
undefined,
{
headers: { headers: {
'Authorization': this.basicAuth, Authorization: this.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 (Recording in JSON format). Resolve new Recording // SUCCESS response from openvidu-server (Recording in JSON format). Resolve new Recording
const r: Recording = new Recording(res.data); const r: Recording = new Recording(res.data);
const activeSession = this.activeSessions.find(s => s.sessionId === r.sessionId); const activeSession = this.activeSessions.find((s) => s.sessionId === r.sessionId);
if (!!activeSession) { if (!!activeSession) {
activeSession.recording = false; activeSession.recording = false;
} else { } else {
console.warn("No active session found for sessionId '" + r.sessionId + "'. This instance of OpenVidu Node Client didn't create this session"); console.warn(
"No active session found for sessionId '" +
r.sessionId +
"'. This instance of OpenVidu Node Client didn't create this session"
);
} }
resolve(r); resolve(r);
} 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.handleError(error, reject); this.handleError(error, reject);
}); });
}); });
@ -273,17 +274,14 @@ export class OpenVidu {
*/ */
public getRecording(recordingId: string): Promise<Recording> { public getRecording(recordingId: string): Promise<Recording> {
return new Promise<Recording>((resolve, reject) => { return new Promise<Recording>((resolve, reject) => {
axios
axios.get( .get(this.host + OpenVidu.API_RECORDINGS + '/' + recordingId, {
this.host + OpenVidu.API_RECORDINGS + '/' + recordingId,
{
headers: { headers: {
'Authorization': this.basicAuth, Authorization: this.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 (Recording in JSON format). Resolve new Recording // SUCCESS response from openvidu-server (Recording in JSON format). Resolve new Recording
resolve(new Recording(res.data)); resolve(new Recording(res.data));
@ -291,7 +289,8 @@ export class OpenVidu {
// 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.handleError(error, reject); this.handleError(error, reject);
}); });
}); });
@ -304,16 +303,13 @@ export class OpenVidu {
*/ */
public listRecordings(): Promise<Recording[]> { public listRecordings(): Promise<Recording[]> {
return new Promise<Recording[]>((resolve, reject) => { return new Promise<Recording[]>((resolve, reject) => {
axios
axios.get( .get(this.host + OpenVidu.API_RECORDINGS, {
this.host + OpenVidu.API_RECORDINGS,
{
headers: { headers: {
Authorization: this.basicAuth Authorization: this.basicAuth
} }
} })
) .then((res) => {
.then(res => {
if (res.status === 200) { if (res.status === 200) {
// SUCCESS response from openvidu-server (JSON arrays of recordings in JSON format). Resolve list of new recordings // SUCCESS response from openvidu-server (JSON arrays of recordings in JSON format). Resolve list of new recordings
const recordingArray: Recording[] = []; const recordingArray: Recording[] = [];
@ -322,13 +318,14 @@ export class OpenVidu {
recordingArray.push(new Recording(item)); recordingArray.push(new Recording(item));
} }
// Order recordings by time of creation (newest first) // Order recordings by time of creation (newest first)
recordingArray.sort((r1, r2) => (r1.createdAt < r2.createdAt) ? 1 : ((r2.createdAt < r1.createdAt) ? -1 : 0)); recordingArray.sort((r1, r2) => (r1.createdAt < r2.createdAt ? 1 : r2.createdAt < r1.createdAt ? -1 : 0));
resolve(recordingArray); resolve(recordingArray);
} 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.handleError(error, reject); this.handleError(error, reject);
}); });
}); });
@ -346,17 +343,14 @@ export class OpenVidu {
*/ */
public deleteRecording(recordingId: string): Promise<Error> { public deleteRecording(recordingId: string): Promise<Error> {
return new Promise<Error>((resolve, reject) => { return new Promise<Error>((resolve, reject) => {
axios
axios.delete( .delete(this.host + OpenVidu.API_RECORDINGS + '/' + recordingId, {
this.host + OpenVidu.API_RECORDINGS + '/' + recordingId,
{
headers: { headers: {
'Authorization': this.basicAuth, Authorization: this.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. Resolve undefined // SUCCESS response from openvidu-server. Resolve undefined
resolve(undefined); resolve(undefined);
@ -364,7 +358,8 @@ export class OpenVidu {
// 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.handleError(error, reject); this.handleError(error, reject);
}); });
}); });
@ -394,7 +389,6 @@ export class OpenVidu {
*/ */
public startBroadcast(sessionId: string, broadcastUrl: string, properties?: RecordingProperties): Promise<void> { public startBroadcast(sessionId: string, broadcastUrl: string, properties?: RecordingProperties): Promise<void> {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
let data; let data;
if (properties != undefined) { if (properties != undefined) {
@ -414,33 +408,35 @@ export class OpenVidu {
data = { data = {
session: sessionId, session: sessionId,
broadcastUrl broadcastUrl
} };
} }
axios.post( axios
this.host + OpenVidu.API_BROADCAST_START, .post(this.host + OpenVidu.API_BROADCAST_START, data, {
data,
{
headers: { headers: {
'Authorization': this.basicAuth, Authorization: this.basicAuth,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
} })
) .then((res) => {
.then(res => {
if (res.status === 200) { if (res.status === 200) {
const activeSession = this.activeSessions.find(s => s.sessionId === sessionId); const activeSession = this.activeSessions.find((s) => s.sessionId === sessionId);
if (!!activeSession) { if (!!activeSession) {
activeSession.broadcasting = true; activeSession.broadcasting = true;
} else { } else {
console.warn("No active session found for sessionId '" + sessionId + "'. This instance of OpenVidu Node Client didn't create this session"); console.warn(
"No active session found for sessionId '" +
sessionId +
"'. This instance of OpenVidu Node Client didn't create this session"
);
} }
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.handleError(error, reject); this.handleError(error, reject);
}); });
}); });
@ -458,31 +454,37 @@ export class OpenVidu {
*/ */
public stopBroadcast(sessionId: string): Promise<void> { public stopBroadcast(sessionId: string): Promise<void> {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
axios.post( axios
.post(
this.host + OpenVidu.API_BROADCAST_STOP, this.host + OpenVidu.API_BROADCAST_STOP,
{ session: sessionId }, { session: sessionId },
{ {
headers: { headers: {
'Authorization': this.basicAuth, Authorization: this.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 // SUCCESS response from openvidu-server
const activeSession = this.activeSessions.find(s => s.sessionId === sessionId); const activeSession = this.activeSessions.find((s) => s.sessionId === sessionId);
if (!!activeSession) { if (!!activeSession) {
activeSession.broadcasting = false; activeSession.broadcasting = false;
} else { } else {
console.warn("No active session found for sessionId '" + sessionId + "'. This instance of OpenVidu Node Client didn't create this session"); console.warn(
"No active session found for sessionId '" +
sessionId +
"'. This instance of OpenVidu Node Client didn't create this session"
);
} }
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.handleError(error, reject); this.handleError(error, reject);
}); });
}); });
@ -497,38 +499,31 @@ export class OpenVidu {
*/ */
public fetch(): Promise<boolean> { public fetch(): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => { return new Promise<boolean>((resolve, reject) => {
axios.get( axios
this.host + OpenVidu.API_SESSIONS + '?pendingConnections=true', .get(this.host + OpenVidu.API_SESSIONS + '?pendingConnections=true', {
{
headers: { headers: {
Authorization: this.basicAuth Authorization: this.basicAuth
} }
} })
) .then((res) => {
.then(res => {
if (res.status === 200) { if (res.status === 200) {
// Boolean to store if any Session has changed // Boolean to store if any Session has changed
let hasChanged = false; let hasChanged = false;
// 1. Array to store fetched sessionIds and later remove closed ones // 1. Array to store fetched sessionIds and later remove closed ones
const fetchedSessionIds: string[] = []; const fetchedSessionIds: string[] = [];
res.data.content.forEach(jsonSession => { res.data.content.forEach((jsonSession) => {
const fetchedSession: Session = new Session(this, jsonSession); const fetchedSession: Session = new Session(this, jsonSession);
fetchedSessionIds.push(fetchedSession.sessionId); fetchedSessionIds.push(fetchedSession.sessionId);
let storedSession = this.activeSessions.find(s => s.sessionId === fetchedSession.sessionId); let storedSession = this.activeSessions.find((s) => s.sessionId === fetchedSession.sessionId);
if (!!storedSession) { if (!!storedSession) {
// 2. Update existing Session // 2. Update existing Session
const changed: boolean = !storedSession.equalTo(fetchedSession); const changed: boolean = !storedSession.equalTo(fetchedSession);
storedSession.resetWithJson(jsonSession); storedSession.resetWithJson(jsonSession);
console.log("Available session '" + storedSession.sessionId + "' info fetched. Any change: " + changed); console.log("Available session '" + storedSession.sessionId + "' info fetched. Any change: " + changed);
hasChanged = hasChanged || changed; hasChanged = hasChanged || changed;
} else { } else {
// 3. Add new Session // 3. Add new Session
this.activeSessions.push(fetchedSession); this.activeSessions.push(fetchedSession);
console.log("New session '" + fetchedSession.sessionId + "' info fetched"); console.log("New session '" + fetchedSession.sessionId + "' info fetched");
@ -552,7 +547,8 @@ export class OpenVidu {
// 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.handleError(error, reject); this.handleError(error, reject);
}); });
}); });
@ -563,13 +559,12 @@ export class OpenVidu {
* @returns A map paring every existing sessionId with true or false depending on whether it has changed or not * @returns A map paring every existing sessionId with true or false depending on whether it has changed or not
*/ */
fetchWebRtc(): Promise<any> { fetchWebRtc(): Promise<any> {
// tslint:disable:no-string-literal // tslint:disable:no-string-literal
const addWebRtcStatsToConnections = (connection: Connection, connectionsExtendedInfo: any) => { const addWebRtcStatsToConnections = (connection: Connection, connectionsExtendedInfo: any) => {
const connectionExtended = connectionsExtendedInfo.find(c => c.connectionId === connection.connectionId); const connectionExtended = connectionsExtendedInfo.find((c) => c.connectionId === connection.connectionId);
if (!!connectionExtended) { if (!!connectionExtended) {
connection.publishers.forEach(pub => { connection.publishers.forEach((pub) => {
const publisherExtended = connectionExtended.publishers.find(p => p.streamId === pub.streamId); const publisherExtended = connectionExtended.publishers.find((p) => p.streamId === pub.streamId);
pub['webRtc'] = { pub['webRtc'] = {
kms: { kms: {
events: publisherExtended.events, events: publisherExtended.events,
@ -588,8 +583,8 @@ export class OpenVidu {
} }
}); });
const subscriberArray = []; const subscriberArray = [];
connection.subscribers.forEach(sub => { connection.subscribers.forEach((sub) => {
const subscriberExtended = connectionExtended.subscribers.find(s => s.streamId === sub); const subscriberExtended = connectionExtended.subscribers.find((s) => s.streamId === sub);
const subAux = {}; const subAux = {};
// Standard properties // Standard properties
subAux['streamId'] = sub; subAux['streamId'] = sub;
@ -633,18 +628,15 @@ export class OpenVidu {
}; };
}; };
return new Promise<{ changes: boolean, sessionChanges: ObjMap<boolean> }>((resolve, reject) => { return new Promise<{ changes: boolean; sessionChanges: ObjMap<boolean> }>((resolve, reject) => {
axios.get( axios
this.host + OpenVidu.API_SESSIONS + '?webRtcStats=true', .get(this.host + OpenVidu.API_SESSIONS + '?webRtcStats=true', {
{
headers: { headers: {
Authorization: this.basicAuth Authorization: this.basicAuth
} }
} })
) .then((res) => {
.then(res => {
if (res.status === 200) { if (res.status === 200) {
// Global changes // Global changes
let globalChanges = false; let globalChanges = false;
// Collection of sessionIds telling whether each one of them has changed or not // Collection of sessionIds telling whether each one of them has changed or not
@ -652,43 +644,42 @@ export class OpenVidu {
// 1. Array to store fetched sessionIds and later remove closed ones // 1. Array to store fetched sessionIds and later remove closed ones
const fetchedSessionIds: string[] = []; const fetchedSessionIds: string[] = [];
res.data.content.forEach(jsonSession => { res.data.content.forEach((jsonSession) => {
const fetchedSession: Session = new Session(this, jsonSession); const fetchedSession: Session = new Session(this, jsonSession);
fetchedSession.connections.forEach(connection => { fetchedSession.connections.forEach((connection) => {
addWebRtcStatsToConnections(connection, jsonSession.connections.content); addWebRtcStatsToConnections(connection, jsonSession.connections.content);
}); });
fetchedSessionIds.push(fetchedSession.sessionId); fetchedSessionIds.push(fetchedSession.sessionId);
let storedSession = this.activeSessions.find(s => s.sessionId === fetchedSession.sessionId); let storedSession = this.activeSessions.find((s) => s.sessionId === fetchedSession.sessionId);
if (!!storedSession) { if (!!storedSession) {
// 2. Update existing Session // 2. Update existing Session
let changed = !storedSession.equalTo(fetchedSession); let changed = !storedSession.equalTo(fetchedSession);
if (!changed) { // Check if server webrtc information has changed in any Publisher object (Session.equalTo does not check Publisher.webRtc auxiliary object) if (!changed) {
// Check if server webrtc information has changed in any Publisher object (Session.equalTo does not check Publisher.webRtc auxiliary object)
fetchedSession.connections.forEach((connection, index1) => { fetchedSession.connections.forEach((connection, index1) => {
for (let index2 = 0; (index2 < connection['publishers'].length && !changed); index2++) { for (let index2 = 0; index2 < connection['publishers'].length && !changed; index2++) {
changed = changed || JSON.stringify(connection['publishers'][index2]['webRtc']) !== JSON.stringify(storedSession.connections[index1]['publishers'][index2]['webRtc']); changed =
changed ||
JSON.stringify(connection['publishers'][index2]['webRtc']) !==
JSON.stringify(storedSession.connections[index1]['publishers'][index2]['webRtc']);
} }
}); });
} }
storedSession.resetWithJson(jsonSession); storedSession.resetWithJson(jsonSession);
storedSession.connections.forEach(connection => { storedSession.connections.forEach((connection) => {
addWebRtcStatsToConnections(connection, jsonSession.connections.content); addWebRtcStatsToConnections(connection, jsonSession.connections.content);
}); });
console.log("Available session '" + storedSession.sessionId + "' info fetched. Any change: " + changed); console.log("Available session '" + storedSession.sessionId + "' info fetched. Any change: " + changed);
sessionChanges[storedSession.sessionId] = changed; sessionChanges[storedSession.sessionId] = changed;
globalChanges = globalChanges || changed; globalChanges = globalChanges || changed;
} else { } else {
// 3. Add new Session // 3. Add new Session
this.activeSessions.push(fetchedSession); this.activeSessions.push(fetchedSession);
console.log("New session '" + fetchedSession.sessionId + "' info fetched"); console.log("New session '" + fetchedSession.sessionId + "' info fetched");
sessionChanges[fetchedSession.sessionId] = true; sessionChanges[fetchedSession.sessionId] = true;
globalChanges = true; globalChanges = true;
} }
}); });
@ -709,7 +700,8 @@ export class OpenVidu {
// 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.handleError(error, reject); this.handleError(error, reject);
}); });
}); });
@ -747,5 +739,4 @@ export class OpenVidu {
reject(new Error(error.message)); reject(new Error(error.message));
} }
} }
} }

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'
} }