Skip to content

Commit

Permalink
Merge branch 'dev' into fix-get-poll-responses
Browse files Browse the repository at this point in the history
  • Loading branch information
KaustubhKumar05 authored May 21, 2024
2 parents c82f7b5 + 3469f23 commit 0cd3a6e
Show file tree
Hide file tree
Showing 20 changed files with 233 additions and 151 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export class SubscribeStatsAnalytics extends BaseStatsAnalytics {
const getCalculatedJitterBufferDelay = (trackStats: HMSTrackStats) =>
trackStats.jitterBufferDelay &&
trackStats.jitterBufferEmittedCount &&
trackStats.jitterBufferDelay / trackStats.jitterBufferEmittedCount;
(trackStats.jitterBufferDelay / trackStats.jitterBufferEmittedCount) * 1000;

const calculatedJitterBufferDelay = getCalculatedJitterBufferDelay(trackStats);

Expand Down
1 change: 1 addition & 0 deletions packages/hms-video-store/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export type {
HMSQuizLeaderboardResponse,
HMSQuizLeaderboardSummary,
HMSTranscriptionInfo,
HMSICEServer,
} from './internal';

export { EventBus } from './events/EventBus';
Expand Down
13 changes: 12 additions & 1 deletion packages/hms-video-store/src/interfaces/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ import InitialSettings from './settings';
* @link https://docs.100ms.live/javascript/v2/features/preview
* @link https://docs.100ms.live/javascript/v2/features/join
*/

export type HMSICEServer = {
urls: string[];
userName?: string;
password?: string;
};

export interface HMSConfig {
/**
* the name of the peer, can be later accessed via peer.name and can also be changed mid call.
Expand Down Expand Up @@ -53,10 +60,14 @@ export interface HMSConfig {
*/
autoManageVideo?: boolean;
/**
* if this flag is enabled, wake lock will be acquired automatically(if supported) when joining the room, so the device
* if this flag is enabled, wake lock will be acquired automatically (if supported) when joining the room, so the device
* will be kept awake.
*/
autoManageWakeLock?: boolean;
/**
* use custom STUN/TURN servers for media connection (advanced)
*/
iceServers?: HMSICEServer[];
}

export interface HMSMidCallPreviewConfig {
Expand Down
2 changes: 2 additions & 0 deletions packages/hms-video-store/src/sdk/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,7 @@ export class HMSSdk implements HMSInterface {
this.localPeer!.peerId,
{ name: config.userName, metaData: config.metaData || '' },
config.autoVideoSubscribe,
config.iceServers,
)
.then((initConfig: InitConfig | void) => {
initSuccessful = true;
Expand Down Expand Up @@ -565,6 +566,7 @@ export class HMSSdk implements HMSInterface {
{ name: config.userName, metaData: config.metaData! },
config.initEndpoint!,
config.autoVideoSubscribe,
config.iceServers,
);
HMSLogger.d(this.TAG, `✅ Joined room ${roomId}`);
this.analyticsTimer.start(TimedEvent.PEER_LIST);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ export class WhiteboardInteractivityCenter implements HMSWhiteboardInteractivity
for (const whiteboard of whiteboards.values()) {
if (whiteboard.url) {
const response = await this.transport.signal.getWhiteboard({ id: whiteboard.id });
const localPeer = this.store.getLocalPeer();
const isOwner = localPeer?.customerUserId === response.owner;
const open = isOwner
? localPeer.role?.permissions.whiteboard?.includes('admin')
: response.permissions.length > 0;
const newWhiteboard: HMSWhiteboard = {
...whiteboard,
id: response.id,
Expand All @@ -86,7 +91,7 @@ export class WhiteboardInteractivityCenter implements HMSWhiteboardInteractivity
addr: response.addr,
owner: response.owner,
permissions: response.permissions,
open: response.permissions.length > 0,
open,
};

this.store.setWhiteboard(newWhiteboard);
Expand Down
17 changes: 11 additions & 6 deletions packages/hms-video-store/src/signal/init/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { InitConfig } from './models';
import { ErrorFactory } from '../../error/ErrorFactory';
import { HMSAction } from '../../error/HMSAction';
import { HMSICEServer } from '../../interfaces';
import { transformIceServerConfig } from '../../utils/ice-server-config';
import HMSLogger from '../../utils/logger';

const TAG = '[InitService]';
Expand All @@ -26,26 +28,26 @@ export default class InitService {
userAgent,
initEndpoint = 'https://prod-init.100ms.live',
region = '',
iceServers,
}: {
token: string;
peerId: string;
userAgent: string;
initEndpoint?: string;
region?: string;
iceServers?: HMSICEServer[];
}): Promise<InitConfig> {
HMSLogger.d(TAG, `fetchInitConfig: initEndpoint=${initEndpoint} token=${token} peerId=${peerId} region=${region} `);
const url = getUrl(initEndpoint, peerId, userAgent, region);
try {
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${token}`,
},
headers: { Authorization: `Bearer ${token}` },
});
try {
const config = await response.clone().json();
this.handleError(response, config);
HMSLogger.d(TAG, `config is ${JSON.stringify(config, null, 2)}`);
return transformInitConfig(config);
return transformInitConfig(config, iceServers);
} catch (err) {
const text = await response.text();
HMSLogger.e(TAG, 'json error', (err as Error).message, text);
Expand Down Expand Up @@ -78,9 +80,12 @@ export function getUrl(endpoint: string, peerId: string, userAgent: string, regi
}
}

export function transformInitConfig(config: any): InitConfig {
export function transformInitConfig(config: any, iceServers?: HMSICEServer[]): InitConfig {
return {
...config,
rtcConfiguration: { ...config.rtcConfiguration, iceServers: config.rtcConfiguration?.ice_servers },
rtcConfiguration: {
...config.rtcConfiguration,
iceServers: transformIceServerConfig(config.rtcConfiguration?.ice_servers, iceServers),
},
};
}
18 changes: 12 additions & 6 deletions packages/hms-video-store/src/transport/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { ErrorFactory } from '../error/ErrorFactory';
import { HMSAction } from '../error/HMSAction';
import { HMSException } from '../error/HMSException';
import { EventBus } from '../events/EventBus';
import { HMSRole } from '../interfaces';
import { HMSICEServer, HMSRole } from '../interfaces';
import { HMSLocalStream } from '../media/streams/HMSLocalStream';
import { HMSLocalTrack, HMSLocalVideoTrack, HMSTrack } from '../media/tracks';
import { TrackState } from '../notification-manager';
Expand Down Expand Up @@ -397,8 +397,9 @@ export default class HMSTransport {
peerId: string,
customData: { name: string; metaData: string },
autoSubscribeVideo = false,
iceServers?: HMSICEServer[],
): Promise<InitConfig | void> {
const initConfig = await this.connect(token, endpoint, peerId, customData, autoSubscribeVideo);
const initConfig = await this.connect(token, endpoint, peerId, customData, autoSubscribeVideo, iceServers);
this.state = TransportState.Preview;
this.observer.onStateChange(this.state);
return initConfig;
Expand All @@ -410,11 +411,12 @@ export default class HMSTransport {
customData: { name: string; metaData: string },
initEndpoint: string,
autoSubscribeVideo = false,
iceServers?: HMSICEServer[],
): Promise<void> {
HMSLogger.d(TAG, 'join: started ⏰');
try {
if (!this.signal.isConnected || !this.initConfig) {
await this.connect(authToken, initEndpoint, peerId, customData, autoSubscribeVideo);
await this.connect(authToken, initEndpoint, peerId, customData, autoSubscribeVideo, iceServers);
}

this.validateNotDisconnected('connect');
Expand Down Expand Up @@ -447,6 +449,7 @@ export default class HMSTransport {
peerId: string,
customData: { name: string; metaData: string },
autoSubscribeVideo = false,
iceServers?: HMSICEServer[],
): Promise<InitConfig | void> {
this.setTransportStateForConnect();
this.joinParameters = new JoinParameters(
Expand All @@ -456,9 +459,10 @@ export default class HMSTransport {
customData.metaData,
endpoint,
autoSubscribeVideo,
iceServers,
);
try {
const response = await this.internalConnect(token, endpoint, peerId);
const response = await this.internalConnect(token, endpoint, peerId, iceServers);
return response;
} catch (error) {
const shouldRetry =
Expand All @@ -474,7 +478,7 @@ export default class HMSTransport {

if (shouldRetry) {
const task = async () => {
await this.internalConnect(token, endpoint, peerId);
await this.internalConnect(token, endpoint, peerId, iceServers);
return Boolean(this.initConfig && this.initConfig.endpoint);
};

Expand Down Expand Up @@ -898,7 +902,7 @@ export default class HMSTransport {
}
}

private async internalConnect(token: string, initEndpoint: string, peerId: string) {
private async internalConnect(token: string, initEndpoint: string, peerId: string, iceServers?: HMSICEServer[]) {
HMSLogger.d(TAG, 'connect: started ⏰');
const connectRequestedAt = new Date();
try {
Expand All @@ -908,6 +912,7 @@ export default class HMSTransport {
peerId,
userAgent: this.store.getUserAgent(),
initEndpoint,
iceServers,
});
const room = this.store.getRoom();
if (room) {
Expand Down Expand Up @@ -1093,6 +1098,7 @@ export default class HMSTransport {
this.joinParameters!.authToken,
this.joinParameters!.endpoint,
this.joinParameters!.peerId,
this.joinParameters!.iceServers,
);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { HMSICEServer } from '../../interfaces';

export class JoinParameters {
constructor(
public authToken: string,
Expand All @@ -6,5 +8,6 @@ export class JoinParameters {
public data: string = '',
public endpoint: string = 'https://prod-init.100ms.live/init',
public autoSubscribeVideo: boolean = false,
public iceServers?: HMSICEServer[],
) {}
}
11 changes: 11 additions & 0 deletions packages/hms-video-store/src/utils/ice-server-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { HMSICEServer } from '../interfaces';

export const transformIceServerConfig = (defaultConfig?: RTCIceServer[], iceServers?: HMSICEServer[]) => {
if (!iceServers || iceServers.length === 0) {
return defaultConfig;
}
const transformedIceServers = iceServers.map(server => {
return { urls: server.urls, credentialType: 'password', credential: server.password, username: server.userName };
});
return transformedIceServers;
};
36 changes: 10 additions & 26 deletions packages/hms-whiteboard/src/hooks/StoreClient.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { GrpcWebFetchTransport } from '@protobuf-ts/grpcweb-transport';
import { Value_Type } from '../grpc/sessionstore';
import { StoreClient } from '../grpc/sessionstore.client';
import { OPEN_WAIT_TIMEOUT } from '../utils';

interface OpenCallbacks<T> {
handleOpen: (values: T[]) => void;
handleChange: (key: string, value?: T) => void;
handleError: (error: Error) => void;
}

const WHITEBOARD_CLOSE_MESSAGE = 'client whiteboard close';
const WHITEBOARD_CLOSE_MESSAGE = 'client whiteboard abort';

export class SessionStore<T> {
private storeClient: StoreClient;
Expand All @@ -31,28 +32,23 @@ export class SessionStore<T> {
},
{ abort: this.abortController.signal },
);
/**
* on open, get key count to call handleOpen with the pre-existing values from the store
* retry if getKeysCount is called before open call is completed
*/
const keyCount = await this.retryForOpen(this.getKeysCount.bind(this));
const initialValues: T[] = [];
let initialised = false;

if (!keyCount) {
handleOpen([]);
}
// on open, wait to call handleOpen with the pre-existing values from the store
setTimeout(() => {
handleOpen(initialValues);
initialised = true;
}, OPEN_WAIT_TIMEOUT);

call.responses.onMessage(message => {
if (message.value) {
if (message.value?.data.oneofKind === 'str') {
const record = JSON.parse(message.value.data.str) as T;
if (initialValues.length === keyCount) {
if (initialised) {
handleChange(message.key, record);
} else {
initialValues.push(record);
if (initialValues.length === keyCount) {
handleOpen(initialValues);
}
}
}
} else {
Expand All @@ -61,7 +57,7 @@ export class SessionStore<T> {
});

call.responses.onError(error => {
if (error.message !== WHITEBOARD_CLOSE_MESSAGE) {
if (!error.message.includes('abort')) {
handleError(error);
}
});
Expand Down Expand Up @@ -103,16 +99,4 @@ export class SessionStore<T> {
delete(key: string) {
return this.storeClient.delete({ key });
}

private async retryForOpen<T>(fn: () => Promise<T>, retries = 3): Promise<T> {
try {
return await fn();
} catch (error) {
const shouldRetry = (error as Error).message.includes('peer not found') && retries > 0;
if (!shouldRetry) {
return Promise.reject(error);
}
return await this.retryForOpen(fn, retries - 1);
}
}
}
Loading

0 comments on commit 0cd3a6e

Please sign in to comment.