5.2.0
The SDK creation factory. Create an instance of the SDK by calling this factory with the desired configurations. The SDK instance will be referred as 'api' throughout the rest of the documentation content.
(config)
The configuration object.
api
:
The SDK instance.
// Instantiate the SDK.
import { create } from 'kandy'
const client = create({
authentication: { ... },
logs: { ... },
...
});
// Use the SDK's API.
client.on( ... );
The configuration object. This object defines what different configuration values you can use when instantiating the SDK using the create function.
Configuration options for the Logs feature.
The SDK will log information about the operations it is performing. The amount of information will depend on how the Logs feature is configured.
The format of logs can also be customized by providing a LogHandler. This function will receive a LogEntry which it can handle as it sees fit. By default, the SDK will log information to the console. For more information, see the Logs feature description.
(Object)
Logs configs.
Name | Description |
---|---|
logs.logLevel string
(default 'debug' )
|
Log level to be set. See logger.levels . |
logs.handler logger.LogHandler?
|
The function to receive log entries from the SDK. If not provided, a default handler will be used that logs entries to the console. |
logs.logActions (Object | boolean)
(default false )
|
Options specifically for action logs when logLevel is at DEBUG+ levels. Set this to false to not output action logs. |
logs.logActions.handler logger.LogHandler?
|
The function to receive action log entries from the SDK. If not provided, a default handler will be used that logs actions to the console. |
logs.logActions.actionOnly boolean
(default false )
|
Only output information about the action itself. Omits the SDK context for when it occurred. |
logs.logActions.collapsed boolean
(default false )
|
Whether logs should be minimized when initially output. The full log is still output and can be inspected on the console. |
logs.logActions.diff boolean
(default false )
|
Include a diff of what SDK context was changed by the action. |
logs.logActions.level string
(default 'debug' )
|
Log level to be set on the action logs |
logs.logActions.exposePayloads boolean
(default true )
|
Allow action payloads to be exposed in the logs, potentially displaying sensitive information. |
Configuration options for the Authentication feature.
(Object)
Authentication configs.
Name | Description |
---|---|
authentication.server Object
|
Information for how to reach the platform. |
authentication.server.base string
|
Server to be used for requests. |
authentication.server.protocol string
(default https )
|
Protocol to be used for requests. |
authentication.server.port Number
(default 443 )
|
Port to be used for requests. |
authentication.clientCorrelator string
|
Unique ID for the client. This is required by the platform to identify an instance of the application used by the specific device. |
Configuration options for the call feature.
(Object)
The call configuration object.
Name | Description |
---|---|
call.defaultPeerConfig call.RTCPeerConnectionConfig?
|
A key-value dictionary that corresponds to the available RTCPeerConfiguration which is normally passed when creating an RTCPeerConnection. See RTCPeerConnection's configuration parameters for more information. This is the recommended way of setting ICE servers and other RTCPeerConnection-related configuration. |
call.iceCollectionIdealTimeout number
(default 1000 )
|
The amount of time to wait for an ideal candidate in milliseconds.
The default is 1000ms. An ideal list of candidates is a complete list of candidates considering the RTCPeerConnection configuration.
Note that this values will not be considered if a custom function is passed through the
iceCollectionCheckFunction
, and
any timeouts must be handled by the custom function.
|
call.iceCollectionMaxTimeout number
(default 3000 )
|
The maximum amount of time to wait for ICE collection in milliseconds.
The default is 3000ms. After this time has been reached, the call will proceed with the currently gathered candidates.
Note that this values will not be considered if a custom function is passed through the
iceCollectionCheckFunction
, and
any timeouts must be handled by the custom function.
|
call.iceCollectionCheckFunction Function?
|
Override the default IceCollectionCheckFunction to manually decide when to proceed with operations, error out, or wait for the appropriate states and candidates. The function will an object containing the ice collection info. See IceCollectionInfo for more details. The function must return a results object with details on how to proceed with the ICE collection check or operatiaon. See IceCollectionResult object for details on the format of the return object. By default, the check is to ensure at least one relay candidate has been collected. For more information, see IceCollectionCheckFunction . |
call.serverTurnCredentials boolean
(default true )
|
Whether server-provided TURN credentials should be used. |
call.sdpHandlers Array<call.SdpHandlerFunction>?
|
List of SDP handler functions to modify SDP. Advanced usage. |
call.removeH264Codecs boolean
(default true )
|
Whether to remove "H264" codec lines from incoming and outgoing SDP messages. |
call.removeBundling boolean
(default false )
|
Whether to remove a=group attributes to stop media bundling from incoming and outgoing SDP messages. |
call.mediaBrokerOnly boolean
(default false )
|
Whether all Calls will be anchored on the MediaBroker instead of being peer-to-peer. Set to true if the backend is configured for broker only mode. |
call.ringingFeedbackMode string
(default 'auto' )
|
The mode for sending ringing feedback to the Caller ('auto', 'manual').
By default, feedback will be automatically sent when a call has been received. In 'manual' mode, the application
must initiate the feedback being sent. See the
call.sendRingingFeedback
API for more info.
|
call.callAuditTimer number
(default 25000 )
|
Time interval, in milliseconds between call audits. |
call.mediaConnectionRetryDelay number
(default 3000 )
|
Delay, in milliseconds for the passive side of a call to wait before trying a media reconnection. |
Configuration options for the Connectivity feature. Can use pingPong (default) or keepAlive as the connectivity check.
Ping Pong: The responsibleParty (default 'client') sends "ping" messages to the other party (default 'server') on the websocket at regular intervals, and the other party is expected to respond with a "pong" message. This lets both sides know that the connection is still valid and that they can receive messages from each other.
Keep Alive: The responsibleParty (default 'client') sends "keepalive" messages to the other party (default 'server') on the websocket at regular intervals. This lets the responsibleParty know that the other party is still connected, and that it should "keep the connection alive".
Keep Alive is the older/simpler method where only one side (the server) has logic for handling the connection. The server knows that if it doesn't receive the keepalive messages, the client is gone and it should clean-up the connection/websocket. In Ping pong, both sides can handle the connection. Both sides can determine if the connection is gone because they will miss the ping or pong message from the other side. The benefit of ping pong is that both sides learn of possible issues sooner.
For more information on these methods refer to these documents:
https://en.wikipedia.org/wiki/Ping-pong_scheme
https://en.wikipedia.org/wiki/Keepalive
(Object)
Connectivity configs.
Name | Description |
---|---|
connectivity.method Object
|
Configuration for how connectivity checks should be made. |
connectivity.method.type String
(default 'pingPong' )
|
The method of connectivity checking to use:
keepAlive
or
pingPong
.
|
connectivity.method.responsibleParty String
(default 'client' )
|
Configures who is responsible for initiating the connectivity check:
client
or
server
.
|
connectivity.pingInterval Number
(default 30000 )
|
Time in between websocket ping attempts (milliseconds). Only used for when the client is responsible for ping/connCheck. |
connectivity.reconnectLimit Number
(default 5 )
|
Number of failed reconnect attempts before reporting an error. Can be set to 0 to not limit reconnection attempts. |
connectivity.reconnectDelay Number
(default 5000 )
|
Base time between websocket reconnect attempts (milliseconds). |
connectivity.reconnectTimeMultiplier Number
(default 1 )
|
Reconnect delay multiplier for subsequent attempts. The reconnect delay time will be multiplied by this after each failed reconnect attempt to increase the delay between attempts. eg. 5000ms then 10000ms then 20000ms delay if value is 2. |
connectivity.reconnectTimeLimit Number
(default 640000 )
|
Maximum time delay between reconnect attempts (milliseconds). Used in conjunction with
reconnectTimeMultiplier
to prevent overly long delays between reconnection attempts.
|
connectivity.autoReconnect Boolean
(default true )
|
Flag to determine whether reconnection will be attempted automatically after connectivity disruptions. |
connectivity.maxMissedPings Number
(default 3 )
|
Maximum pings sent (without receiving a response) before reporting an error. |
connectivity.checkConnectivity Boolean
(default true )
|
Flag to determine whether to enable connectivity checking or not. |
Configuration options for the Subscription feature.
(Object)
Subscription configs.
Name | Description |
---|---|
subscription.channelLifetime number
(default 3600 )
|
The amount of time (in seconds) for which to keep subscription channels up and alive. |
subscription.timeout number
(default 20 )
|
The amount of time (in seconds) allowed for the subscription/unsubscription process to take place before timing out. |
The 'api' is the type returned by the create function. It contains various top-level functions that pertain to SDK global instance as well as several nested namespaces that pertain to various features (e.g. call, contacts, presence, etc).
Returns the current version of the API.
Destroys the SDK, and removes its state, rendering the SDK unusable. Useful when a user logs out and their call data needs to be destroyed. The SDK must be recreated to be usable again. The destroy command is async, and will happen on the next tick so as not to interfere with any ongoing events.
// Instantiate the SDK.
import { create } from 'kandy'
const config = {
authentication: { ... },
logs: { ... },
...
}
let client = create(config);
client.on( ... )
// Use the SDK
...
// Destroy the SDK, then recreate on the next step
client.destroy()
client = create(config)
client.on( ... )
Update the configuration values for the SDK to use.
This API will only modify the configurations provided, leaving other configurations as they were originally set, by performing a merge of the new values into the previous values.
Please note that updating the call.removeH264Codecs configuration will not immediately change the SDP handlers used for a call. If you want to add or remove the h264 codec remover sdp handler you should follow this procedure:
Update the config for removeH264Codecs using the updateConfig API.
Update the sdp handler list using the setSdpHandlers API and provide any client defined SDP handler functions.
NOTE: You can get the currently defined SDP handler functions with the getConfig API.
Please note that the object provided to the updateConfig
API may be different
than the object retrieved from the getConfig API. This may happen when a format
change has happened and the SDK modifies the provided format to alleviate
backwards-compatibility issues. We recommend ensuring the configurations you
provide are as described by the config section.
// Instantiate the SDK with certain configs.
const client = create({
authentication: { ... },
logs: { ... },
...
})
// Modify a subsection of the configs at a later time.
// This will only update the specified configurations.
client.updateConfig({
logs: {
loglevel: 'DEBUG'
}
})
Add an event listener for the specified event type. The event is emitted by the SDK instance.
(string)
The event type for which to add the listener.
(Function)
The listener for the event type. The parameters of the listener depend on the event type.
// Listen for events of a specific type emitted by the SDK.
client.on('dummy:event', function (params) {
// Handle the event.
})
Retrieves information about the current user.
Object
:
user The user data.
string
:
user.username The username of the current user. Note that this username can take different encoded forms.
It's not meant to be displayed to a user.
string
:
user.token The current access token.
Sets the authentication tokens necessary to make requests to the platform. The access token provided establishes what can be accessed by the SDK. The identity token represents who is authenticated.
client.setTokens({
accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
idToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
})
Sets the authentication tokens necessary to make requests to the platform. The bearerAccessToken provided establishes what can be accessed by the SDK. The identity token represents who is authenticated.
(Object)
The credentials object.
Name | Description |
---|---|
credentials.bearerAccessToken string
|
A bearerAccessToken retrieved using the authentication APIs of the platform. The bearerAccessToken is same as the access token for the cpaas platform. |
credentials.idToken string
|
An identity token retrieved using the authentication APIs of the platform. |
client.setCredentials({
bearerAccessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
idToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
});
Retrieve information about the browser being used.
Browser information being defined indicates that the browser supports basic webRTC scenarios.
const details = client.getBrowserDetails()
log(`Browser in use: ${details.browser}, version ${details.version}.`)
An error occurred with server authorization.
This event will be emitted anytime a REST request to the server is rejected due to an authorization issue. This may occur for invalid credentials or expired tokens, depending on which form of authentication the application has chosen to use.
(Object)
Name | Description |
---|---|
params.error api.BasicError
|
The Basic error object. |
The 'call' namespace (within the 'api' type) is used to make audio and video calls to and from SIP users and PSTN phones.
Call functions are all part of the 'call' namespace.
Information about a Call.
Can be retrieved using the call.getAll or call.getById APIs.
Type: Object
(string)
: The ID of the call.
(user.UserID)
: A unique identifier (uri) of the person who made the call.
(user.UserID)
: A unique identifier (uri) of the person who receives the call.
(string)
: The direction in which the call was created. Can be 'outgoing' or 'incoming'.
(string)
: The current status of the call's media connection. See
call.mediaConnectionStates
for possible states.
(boolean)
: Indicates whether this call is currently being held locally.
(boolean)
: Indicates whether this call is currently being held remotely.
(Array<string>)
: A list of Track IDs that the call is sending to the remote participant.
(Array<string>)
: A list of Track IDs that the call is receiving from the remote participant.
(call.MediaOffered?)
: Information about what media was offered by the person who made the call.
(Object)
: Information about the other call participant.
(call.BandwidthControls)
: The bandwidth limitations set for the call.
(number)
: The start time of the call in milliseconds since the epoch.
(number?)
: The end time of the call in milliseconds since the epoch.
The MediaConstraint type defines the format for configuring media options.
Either the exact
or ideal
property should be provided. If both are present, the
exact
value will be used.
When the exact
value is provided, it will be the only value considered for the option.
If it cannot be used, the constraint will be considered an error.
When the ideal
value is provided, it will be considered as the optimal value for the option.
If it cannot be used, the closest acceptable value will be used instead.
A string value can be provided directly instead of using the MediaConstraint format.
Using a string directly is not recommended, since behaviour may differ depending
on browser and media property. For most properties, a direct string value will be
handled as ideal
behaviour, but some properties may follow the exact
behaviour
(eg. deviceId
).
Type: Object
(string?)
: The required value for the constraint. Other values will not be accepted.
(string?)
: The ideal value for the constraint. Other values will be considered if necessary.
// Specify video resolution when making a call.
client.call.make(destination, {
audio: true,
video: true,
videoOptions: {
// Set height and width constraints to ideally be 1280x720.
height: { ideal: 720 },
width: { ideal: 1280 }
}
})
The MediaOffered type defines what media capabilities are offered by the person making a call. This is an optional property and therefore may be null if it is not known or if it's associated with caller's side of the call.
Type: Object
(boolean)
: Specifies if any audio capability has been offered by the caller. If set to true, then the caller is capable of supporting at least one audio stream in the current call.
(boolean)
: Specifies if any video capability has been offered by the caller. If set to true, then the caller is capable of supporting at least one video stream in the current call.
The BandwidthControls type defines the format for configuring media and/or track bandwidth options. BandwidthControls only affect received remote tracks of the specified type.
Type: Object
(number?)
: The desired combined bandwidth bitrate in kilobits per second for all media in the call.
(number?)
: The desired bandwidth bitrate in kilobits per second for received remote audio.
(number?)
: The desired bandwidth bitrate in kilobits per second for received remote video.
// Specify received remote video bandwidth limits when making a call.
client.call.make(destination, mediaConstraints,
{
bandwidth: {
video: 5
}
}
)
The DSCPControls type defines the format for configuring network priorities (DSCP marking) for the media traffic.
If DSCPControls are not configured for a call the network priority of the traffic for all media kinds will be the default (i.e., "low").
Type: Object
(RTCPriorityType?)
: The desired network priority for audio traffic (see
RTCPriorityType Enum
for the list of possible values).
(RTCPriorityType?)
: The desired network priority for video traffic (see
RTCPriorityType Enum
for the list of possible values).
(RTCPriorityType?)
: The desired network priority for screen share traffic (see
RTCPriorityType Enum
for the list of possible values).
Configuration options for an RTCPeerConnection. It represents an RTCPeerConfiguration dictionary, whose parameters are documented here.
Type: Object
(string
= 'unified-plan'
)
The sdpSemantics to use (
'unified-plan'
or
'plan-b'
).
As 'plan-b' has become a deprecated option, it will therefore be removed in the future.
(number?)
An unsigned 16-bit integer value which specifies
the size of the prefetched ICE candidate pool. The default value is 0 (meaning no candidate prefetching will occur).
(string?)
The current ICE transport policy; if the policy isn't specified,
'all' is assumed by default. Possible values are: 'all', 'public', 'relay'.
(string?)
For further description on this and other properties,
see
RTCPeerConnection's configuration parameters
.
Type: Object
((Array<string> | string))
: Either an array of URLs for reaching out several ICE servers or a single URL for reaching one ICE server. See
RTCIceServers.urls documentation
to learn more about the actual url format.
(string?)
: The credential needed by the ICE server.
(string?)
: The credential needed by the ICE server.
This object is provided to the IceCollectionCheckFunction, and contains the necessary information about the call (i.e., call ID, current call operation), and information about the ongoing ICE collection, such as the list of all ICE candidates collected so far and the ICE gathering state.
Type: Object
(string)
: The ID of the call.
(string)
: The current operation of the call.
(string)
: The reason the check function was called. Three possible values:
'NewCandidate' - A new ICE candidate was collected. Note: there may be multiple new ICE candidates collected.
'IceGatheringStateChanged' - The ICE gathering state changed.
'Scheduled' - A scheduled call (for first invocation, and subsequent invocations based on
wait
value returned by
IceCollectionCheckFunction
.)
(Array<RTCIceCandidate>)
: An array of all ICE candidates collected so far.
(number)
: The time elapsed since the start of the ICE collection process.
(string)
: The current ICE gathering state.
See
RTCPeerConnection.iceGatheringState
.
(Object)
: The current configration for the RTCPeerConnection.
(string)
: The current local session description set on the peer.
The form of the ICE collection check function, the arguments that it receives, and the outputs expected.
This function is provided the necessary details of the current WebRTC session and ICE collection
(IceCollectionInfo), which it can use to dictate how to proceed with a call.
The function can be invoked for three different reasons:
a new ICE candidate was collected, the ICE gathering state changed, or a scheduled call based on the wait
time set after
an initial invocation of the function.
The function must then return an appropriate result object in the format of IceCollectionCheckResult
which will dictate how the call will proceed. An incorrect return object, or result type
, will cause the call to end with an error.
[Default] The default IceCollectionCheckFunction uses the following algorithm to determine if the call can proceed to negotiation:
iceGatheringState
is "complete" at any stage, then:
The ideal and max timeouts can be configured with the idealIceCollectionTimeout
and maxIceCollectionTimeout
properties of
the call config.
Type: Function
(call.IceCollectionInfo)
Information about the current status of the ICE candidate collection.
(Object)
Configurations provided to the SDK for ICE collection timeout boundaries.
Name | Description |
---|---|
iceTimeouts.iceCollectionIdealTimeout number
|
The amount of time to wait for ideal candidates, in milliseconds. See config.call for more information. |
iceTimeouts.iceCollectionMaxTimeout number
|
The maximum amount of time to wait for ICE collection, in milliseconds. See config.call for more information. |
call.IceCollectionCheckResult
:
Information on how to proceed with the call and/or ICE collection.
function isRelayCandidate (candidate) {
// NOTE: This would need to be different for Firefox since the `.type` property doesn't exist
// and we would need to parse it ourselves in the `.candidate` property.
return candidate.type === 'relay'
}
function myIceCollectionCheck ({ iceGatheringState, iceCandidates }, iceTimeouts) {
if (iceGatheringState === 'complete') {
if (iceCandidates.some(isRelayCandidate)) {
return { type: 'StartCall' }
} else {
return { type: 'Error', error: new Error('Failed to start call because there is no relay candidates.') }
}
} else {
return { type: 'Wait' }
}
}
Type: Object
(string)
: Indicates how the system should proceed with the call operation / ICE collection. The possible values are:
'StartCall' - instruct the system to start the call with the currently gathered ICE candidates and other information.
'Error' - instruct the system to fail the call with an error. The error to communicate to the user should be specified in the
error
property.
'Wait' - instruct the system to wait for the specified amount of time before triggering a new ICE collection check. The amount
of wait time should be specified in the
wait
property.
(string)
: An error to be sent the user when the
type
of the result is
IceCollectionCheckResultType.Error
(number)
: The amount of time (in milliseconds) to wait before triggering a new ICE collection check. This is only
valid if the
type
of result is
IceCollectionCheckResultType.Wait
. If a value is not provided, the ICE collection check function
will only be triggered for new candidates or when the ICE gathering state changes.
Type: Object
(string)
: The id corresponding to the call for which the handler is being run.
(RTCSdpType)
: The session description's type.
(string)
: The step that will occur after the SDP Handlers are run.
Will be either 'set' (the SDP will be set locally) or 'send' (the SDP will
be sent to the remote endpoint).
(string)
: Which end of the connection created the SDP.
The form of an SDP handler function and the expected arguments that it receives.
Type: Function
(Object)
The SDP so far (could have been modified by previous handlers).
(call.SdpHandlerInfo)
Additional information that might be useful when making SDP modifications.
(Object)
The SDP in its initial state.
Object
:
The resulting modified SDP based on the changes made by this function.
The state representation of a Media object. Media is a collection of Track objects.
Type: Object
(string)
: The ID of the Media object.
(boolean)
: Indicator on whether this media is local or remote.
(Array<call.TrackObject>)
: A list of Track objects that are contained in this Media object.
A Track is a stream of audio or video media from a single source.
Tracks can be retrieved using the Media module's getTrackById
API and manipulated with other functions of the Media module.
Type: Object
(boolean)
: Indicator of whether this Track is disabled or not. If disabled, it cannot be re-enabled.
(boolean)
: Indicator of whether this Track is a locally created one or is a remote one.
(string)
: The ID of the Track.
(string)
: The kind of Track this is (audio, video).
(string)
: The label of the device this Track uses.
(boolean)
: Indicator on whether this Track is muted or not.
(boolean)
: Indicator on whether this Track is receiving media from its source or not.
When true, the Track can be considered removed. This indicator is affected by actions outside the
control of the SDK, such as the remote endpoint of a Call stopping to send media for a remote Track,
or the browser temporarily disabling the SDK's access to a local Track's source.
(string)
: The state of this Track. Can be 'live' or 'ended'.
(string)
: The ID of the Media Stream that includes this Track.
A collection of media devices and their information.
Type: Object
(Array<call.DeviceInfo>)
: A list of camera device information.
(Array<call.DeviceInfo>)
: A list of microphone device information.
(Array<call.DeviceInfo>)
: A list of speaker device information.
Starts an outgoing call to a UserID or a PhoneNumber.
The call will be tracked by a unique ID that is returned by the API. The application will use this ID to identify and control the call after it has been initiated.
The call.getById API can be used to retrieve the current information about the call.
The progress of the operation will be tracked via the call:operation event.
The SDK will emit a call:start event locally when the operation completes. When the remote participant receives the call, a call:receive event will be emitted remotely for them.
The SDK requires access to the machine's media devices (e.g. microphone) in order to make a call. If it does not already have permissions to use the devices, the user may be prompted by the browser to give permissions.
((call.UserID | call.PhoneNumber))
The desired destination.
(Object)
The media options the call should be initialized with.
Name | Description |
---|---|
media.audio boolean
(default false )
|
Whether the call should have audio on start. Currently, audio-less calls are not supported. |
media.audioOptions Object?
|
Options for configuring the call's audio. |
media.audioOptions.deviceId call.MediaConstraint?
|
ID of the microphone to receive audio from. |
media.video boolean
(default false )
|
Whether the call should have video on start. |
media.videoOptions Object?
|
Options for configuring the call's video. |
media.videoOptions.deviceId call.MediaConstraint?
|
ID of the camera to receive video from. |
media.videoOptions.height call.MediaConstraint?
|
The height of the video. |
media.videoOptions.width call.MediaConstraint?
|
The width of the video. |
media.videoOptions.frameRate call.MediaConstraint?
|
The frame rate of the video. |
media.screen boolean
(default false )
|
Whether the call should have screenshare on start. (Note: Screensharing is not supported on iOS Safari.) |
media.screenOptions Object?
|
Options for configuring the call's screenShare. |
media.screenOptions.height call.MediaConstraint?
|
The height of the screenShare. |
media.screenOptions.width call.MediaConstraint?
|
The width of the screenShare. |
media.screenOptions.frameRate call.MediaConstraint?
|
The frame rate of the screenShare. |
(Object?)
Name | Description |
---|---|
options.bandwidth call.BandwidthControls?
|
Options for configuring media's bandwidth. |
options.dscpControls call.DSCPControls?
|
Options for configuring DSCP markings on the media traffic |
string
:
The generated ID of the newly created call.
// Listen for the event emitted after making a call.
client.on('call:start', function (params) {
const { callId, error } = params
if (error) {
// Call failed to initialize.
} else {
// Call was initialized, and the recipient user will be notified.
}
})
// Make an audio-only call.
const newCallId = client.call.make(destination, { audio: true })
Rejects an incoming call.
The specified call to reject must be in a ringing state with an incoming direction. The call will be ended as a result of the operation.
The progress of the operation will be tracked via the call:operation event.
The SDK will emit a call:stateChange event locally when the operation completes. The remote participant will be notified, through their own call:stateChange event, that the call was rejected.
(string)
The ID of the call to reject.
Answers an incoming call.
The specified call to answer must be in Initiated or Ringing state with an incoming direction. The call will become connected as a result of the operation.
The progress of the operation will be tracked via the call:operation event.
The SDK will emit a call:stateChange event locally when the operation completes. This indicates that the call has connected with the remote participant. The call.getById API can be used to retrieve the latest call state after the change. Further events will be emitted to indicate that the call has received media from the remote participant. See the call:newTrack event for more information about this.
The SDK requires access to the system's media devices (eg. microphone) in order to answer a call. If it does not already have permissions to use the devices, the user may be prompted by the browser to give permissions.
(string)
The ID of the call to answer.
(Object)
The media options the call should be initialized with.
Name | Description |
---|---|
media.audio boolean
(default false )
|
Whether the call should have audio on start. Currently, audio-less calls are not supported. |
media.audioOptions Object?
|
Options for configuring the call's audio. |
media.audioOptions.deviceId call.MediaConstraint?
|
ID of the microphone to receive audio from. |
media.video boolean
(default false )
|
Whether the call should have video on start. |
media.videoOptions Object?
|
Options for configuring the call's video. |
media.videoOptions.deviceId call.MediaConstraint?
|
ID of the camera to receive video from. |
media.videoOptions.height call.MediaConstraint?
|
The height of the video. |
media.videoOptions.width call.MediaConstraint?
|
The width of the video. |
media.videoOptions.frameRate call.MediaConstraint?
|
The frame rate of the video. |
media.screen boolean
(default false )
|
Whether the call should have screenshare on start. (Note: Screensharing is not supported on iOS Safari.) |
media.screenOptions Object?
|
Options for configuring the call's screenShare. |
media.screenOptions.height call.MediaConstraint?
|
The height of the screenShare. |
media.screenOptions.width call.MediaConstraint?
|
The width of the screenShare. |
media.screenOptions.frameRate call.MediaConstraint?
|
The frame rate of the screenShare. |
(Object?)
Name | Description |
---|---|
options.bandwidth call.BandwidthControls?
|
Options for configuring media's bandwidth. |
options.dscpControls call.DSCPControls?
|
Options for configuring DSCP markings on the media traffic |
Sends the "ringing feedback" notification to the remote participant of a call.
When using the 'manual' ringingFeedbackMode
configuration, the application
is responsible for transitioning the call into the Ringing
state. This
API will notify both ends of the call to enter Ringing
state at the same
time. The application may decide not to send the "ringing feedback"
notification by not using this API. The ringingFeedbackMode
configuration
must be set to 'manual' to use this API.
The specified call must be an incoming call in Initiated
state. The call
will enter Ringing
state as a result of the operation.
The SDK will emit a call:stateChange event locally when the operation completes. The remote participant will be notified of the operation through a call:stateChange event as well.
(string)
The ID of the call.
Ignores an incoming call.
The specified call to ignore must be in a ringing state with an incoming direction. The call will be ended as a result of the operation.
The progress of the operation will be tracked via the call:operation event.
The SDK will emit a call:stateChange event locally when the operation completes. The remote participant will not be notified that the call was ignored.
(string)
The ID of the call to ignore.
Puts a call on hold.
The specified call to hold must not already be locally held. Any/all media received from the remote participant will stop being received, and any/all media being sent to the remote participant will stop being sent.
Some call operations cannot be performed while the call is on hold. The call can be taken off hold with the call.unhold API.
The progress of the operation will be tracked via the call:operation event.
The SDK will emit a call:stateChange event locally when the operation completes. The remote participant will be notified of the operation through a call:stateChange event as well.
(string)
The ID of the call to hold.
Takes a call off hold.
The specified call to unhold must be locally held. If the call is not also remotely held, call media will be reconnected as it was before the call was held.
The progress of the operation will be tracked via the call:operation event.
The SDK will emit a call:stateChange event locally when the operation completes. The remote participant will be notified of the operation through a call:stateChange event as well.
(string)
The ID of the call to unhold.
Retrieves the information of all calls made during the current session.
Array<call.CallObject>
:
Call objects.
let calls = client.call.getAll()
let currentCalls = calls.filter(call => {
return call.state === client.call.states.CONNECTED
})
Retrieves the information of a single call with a specific call ID.
(string)
The ID of the call to retrieve.
call.CallObject
:
A call object.
Ends an ongoing call.
The SDK will stop any/all local media associated with the call. Events will be emitted to indicate which media tracks were stopped. See the call:trackEnded event for more information.
The progress of the operation will be tracked via the call:operation event.
The SDK will emit a call:stateChange event locally when the operation completes. The remote participant will be notified, through their own call:stateChange event, that the call was ended.
(string)
The ID of the call to end.
Add new media tracks to an ongoing call. Will get new media tracks from the specific sources to add to the call.
The progress of the operation will be tracked via the call:operation event.
The SDK will emit a call:newTrack event both for the local and remote users to indicate a track has been added to the Call.
(string)
The ID of the call to add media to.
(Object
= {}
)
The media options to add to the call.
Name | Description |
---|---|
media.audio boolean
(default false )
|
Whether to add audio to the call. |
media.video boolean
(default false )
|
Whether to add video to the call. |
media.screen boolean
(default false )
|
Whether to add the screenshare to the call. (Note: Screensharing is not supported on iOS Safari.) |
media.audioOptions Object?
|
Options for configuring the call's audio. |
media.audioOptions.deviceId call.MediaConstraint?
|
ID of the microphone to receive audio from. |
media.videoOptions Object?
|
Options for configuring the call's video. |
media.videoOptions.deviceId call.MediaConstraint?
|
ID of the camera to receive video from. |
media.videoOptions.height call.MediaConstraint?
|
The height of the video. |
media.videoOptions.width call.MediaConstraint?
|
The width of the video. |
media.videoOptions.frameRate call.MediaConstraint?
|
The frame rate of the video. |
media.screenOptions Object?
|
Options for configuring the call's screenShare. |
media.screenOptions.height call.MediaConstraint?
|
The height of the screenShare. |
media.screenOptions.width call.MediaConstraint?
|
The width of the screenShare. |
media.screenOptions.frameRate call.MediaConstraint?
|
The frame rate of the screenShare. |
(Object?
= {}
)
Name | Description |
---|---|
options.bandwidth call.BandwidthControls?
|
Options for configuring media's bandwidth. |
options.dscpControls call.DSCPControls?
|
Options for configuring DSCP markings on the media traffic |
Remove tracks from an ongoing call.
The progress of the operation will be tracked via the call:operation event.
The SDK will emit a call:trackEnded event for both the local and remote users to indicate that a track has been removed.
(string)
The ID of the call to remove media from.
(Array)
A list of track IDs to remove.
(Object?
= {}
)
Name | Description |
---|---|
options.bandwidth call.BandwidthControls?
|
Options for configuring media's bandwidth. |
Adds local video to an ongoing Call, to start sending to the remote participant.
Can only be used in a basic media scenario, where the Call does not already have video. For more advanced scenarios, the call.addMedia API can be used.
The progress of the operation will be tracked via the call:operation event.
The SDK will emit a call:newTrack event both for the local and remote users to indicate a track has been added to the Call.
(string)
ID of the call being acted on.
(Object?)
Options for configuring the call's video.
Name | Description |
---|---|
videoOptions.deviceId call.MediaConstraint?
|
ID of the camera to receive video from. |
videoOptions.height call.MediaConstraint?
|
The height of the video. |
videoOptions.width call.MediaConstraint?
|
The width of the video. |
videoOptions.frameRate call.MediaConstraint?
|
The frame rate of the video. |
(Object?)
Name | Description |
---|---|
options.bandwidth call.BandwidthControls?
|
Options for configuring media's bandwidth. |
options.dscpControls call.DSCPControls?
|
Options for configuring DSCP markings on the media traffic. |
Removes local video from an ongoing Call, stopping it from being sent to the remote participant.
Can only be used in a basic media scenario, where the Call has only one video track. For more advanced scenarios, the call.removeMedia API can be used.
The progress of the operation will be tracked via the call:operation event.
The SDK will emit a call:trackEnded event for both the local and remote users to indicate that a track has been removed.
(string)
ID of the call being acted on.
Adds local screenshare to an ongoing Call, to start sending to the remote participant.
The latest SDK release (v4.X+) has not yet implemented this API in the same way that it was available in previous releases (v3.X). In place of this API, the SDK has a more general API that can be used for this same behaviour.
The call.addMedia API can be used to perform the same behaviour
as startScreenshare
. {@link call.addMedia} is a general-purpose API
for adding media to a call, which covers the same functionality as
startScreenshare
. Selecting only screen options when using
call.addMedia will perform the same behaviour as using
startScreenshare
.
// Select media options for adding only screenshare.
const media = {
audio: false,
video: false,
screen: true,
screenOptions: { ... }
}
// Add the selected media to the call.
client.call.addMedia(callId, media)
Removes local screenshare from an ongoing Call, stopping it from being sent to the remote participant.
The latest SDK release (v4.X+) has not yet implemented this API in the same way that it was available in previous releases (v3.X). In place of this API, the SDK has a more general API that can be used for this same behaviour.
The call.removeMedia API can be used to perform the same
behaviour as stopScreenshare
. {@link call.removeMedia} is a
general-purpose API for removing media from a call, which covers the
same functionality as stopScreenshare
. Specifying only the screen
track when using call.removeMedia will perform the same
behaviour as using stopScreenshare
.
There is a caveat that if a Call has multiple video tracks (for example, both a video and a screen track), the SDK itself cannot yet differentiate one from the other. The application will need to know which track was the screen track in this scenario.
const call = client.call.getById(callId)
// Get the ID of any/all video tracks on the call.
const videoTracks = call.localTracks.filter(trackId => {
const track = call.media.getTrackById(trackId)
// Both video and screen tracks have kind of 'video'.
return track.kind === 'video'
})
// Pick out the screen track.
const screenTrack = videoTracks[0]
// Remove screen from the call.
client.call.removeMedia(callId, [ screenTrack ])
Send DTMF tones to a call's audio.
The provided tone can either be a single DTMF tone (eg. '1') or a sequence of DTMF tones (eg. '123') which will be played one after the other.
The specified call must be either in Connected, Ringing, or Early Media state, otherwise invoking this API will have no effect.
The tones will be sent as out-of-band tones if supported by the call, otherwise they will be added in-band to the call's audio.
The progress of the operation will be tracked via the call:operation event.
(string)
ID of the call being acted on.
(string)
DTMF tone(s) to send. Valid characters are ['0','1','2','3','4','5','6','7','8','9','#','*' and ','].
(number
= 100
)
The amount of time, in milliseconds, that each DTMF tone should last.
(number
= 70
)
The length of time, in milliseconds, to wait between tones.
Retrieve a snapshot of the low-level information of the Call through statistical report.
The data retrieved is a RTCStatsReport object, which contains many individual RTCStats. These are advanced statistics gathered by the browser providing insights into the Call at a certain point in time. Aggregating reports over a period of time would allow a low-level analysis of the Call for that period. As an example, this could be done to determine the media quality during the Call.
A Track ID can optionally be provided to get a report for a specific Track of the Call.
This API will return a promise which, when resolved, will contain the report of the particular call. The progress of the operation will be tracked via the call:operation event.
The SDK will emit a call:statsReceived event, after the operation completes, that has the report.
(string)
The ID of the Call to retrieve the report.
(string?)
ID of a Track being used by the Call. If not
provided, RTCStatsReport is generated for the Call itself.
client.on('call:statsReceived', function (params) {
// Iterate over each individual statistic inside the RTCPStatsReport.
params.result.forEach(stats => {
// Handle the data on its own or collate with previously gathered stats
// for analysis.
...
})
})
// Get a snapshot of the Call's stats.
// This may be done on a regular interval to collect data over time.
client.call.getStats(callId)
Replace a call's track with a new track of the same media type.
The operation will remove the old track from the call and add a new track to the call. This effectively allows for changing the track constraints (eg. device used) for an ongoing call.
Because it completely replaces an old track with a new one, the old track's state characteristics are not carried over in the new track's state. (e.g. if an old track's state was 'muted' and replacement of this track has occured, the new track's state will be 'unmuted', as this is its default state)
The progress of the operation will be tracked via the call:operation event.
The SDK will emit a call:trackReplaced event locally when the operation completes. The newly added track will need to be handled by the local application. The track will be replaced seamlessly for the remote application, which will not receive an event.
(string)
The ID of the call to replace the track of.
(string)
The ID of the track to replace.
(Object
= {}
)
The media options.
Name | Description |
---|---|
media.audio boolean
(default false )
|
Whether to create an audio track. |
media.audioOptions Object?
|
Options for configuring the audio track. |
media.audioOptions.deviceId call.MediaConstraint?
|
ID of the microphone to receive audio from. |
media.video boolean
(default false )
|
Whether to create a video track. |
media.videoOptions Object?
|
Options for configuring the video track. |
media.videoOptions.deviceId call.MediaConstraint?
|
ID of the camera to receive video from. |
media.videoOptions.height call.MediaConstraint?
|
The height of the video. |
media.videoOptions.width call.MediaConstraint?
|
The width of the video. |
media.videoOptions.frameRate call.MediaConstraint?
|
The frame rate of the video. |
const callId = ...
// Get the video track used by the call.
const videoTrack = ...
// Replace the specified video track of the call with a new
// video track.
client.call.replaceTrack(callId, videoTrack.id, {
// The track should be replaced with a video track using
// a specific device. This effectively changes the input
// device for an ongoing call.
video: true,
videoOptions: {
deviceId: cameraId
}
})
const callId = ...
// Get the video track used by the call.
const videoTrack = ...
// Can also replace the specified video track of the call with a new
// screen sharing track because screen sharing is delivered as a video stream to remote peer.
// User will then be prompted to pick a specific screen to share and thus the device id will be selected.
client.call.replaceTrack(callId, videoTrack.id, {
// The track should be replaced with a screen sharing track.
// Note that 'screenOptions' property is not mandatory, as API will use default values
// for properties like: width, height, frameRate.
screen: true
})
Retrieve the list of available and supported codecs based on the browser's capabilities for sending media.
This API will return a promise which, when resolved, it will contain the list of available and supported codecs. In addition, the SDK emits a call:availableCodecs event upon retrieving that list of codecs.
This API is a wrapper for the static method RTCRtpSender.getCapabilities(). Firefox browser does not currently support this method. Therefore, this API will not work on Firefox.
(string)
The kind of media, i.e., 'audio' or 'video', to get the list of available codecs of.
Set SDP Handler Functions that will be run as part of a pipeline for all future calls. This will replace any SDP Handlers that were previously set.
SDP handlers can be used to make modifications to the SDP (e.g., removing certain codecs) before they are processed or sent to the other side.
This is an advanced feature, changing the SDP handlers mid-call may cause unexpected behaviour in future call operations for that call.
(Array<call.SdpHandlerFunction>)
The list of SDP handler functions to modify SDP.
Possible states that a Call can be in.
A Call's state describes the current status of the Call. An application should use the state to understand how the Call, and any media associated with the Call, should be handled. Which state the Call is in defines how it can be interacted with, as certain operations can only be performed while in specific states, and tells an application whether the Call currently has media flowing between users. Unless stated otherwise, the Call's state pertains to both caller & callee.
The Call's state is a property of the CallObject, which can be retrieved using the call.getById or call.getAll APIs.
The SDK emits a call:stateChange event when a Call's state changes from one state to another.
Type: Object
(string)
: The (outgoing) call is being started. While in this state, no Call operations can be performed until Call gets into Initiated state.
(string)
: A call has been started and both the callee and caller may now perform further operations on the call object.
(string)
: The call has been received by both parties, and is waiting to be answered.
(string)
: The call has not been answered, but media
is already being received. This may be network-ringing media, IVR
system media, or other pre-answer medias. When early media is
supported, this state may replace the Ringing state. This is a state valid only for caller's side.
(string)
: The call was disconnected before it could be answered. This is a state valid only for callee's side.
(string)
: Both parties are connected and media is flowing.
(string)
: Both parties are connected but no media is flowing.
(string)
: The call has ended.
// Use the call states to know how to handle a change in the call.
client.on('call:stateChange', function (params) {
const call = client.call.getById(params.callId)
// Check if the call now has media flowing.
if (call.state === client.call.states.CONNECTED) {
// The call is now active, and can perform midcall operations.
}
})
Possible states that a Call's media connection can be in.
A Call's media connection state describes the current status of media within the call. An application should use this state to understand whether the Call participants are able to see/hear each other or may be experiencing connection issues. The media connection state can be used alongside the Call state to determine if media issues are occurring while the participants are expecting to be connected.
An important state to check for is the FAILED
state. This state signifies that there is no
media connection between the call participants and an action must be taken to resolve the
problem. Using the call.restartMedia API will attempt to reconnect the media. See
the call.restartMedia API description for more information.
These states are direct reflections of the possible RTCPeerConnection.iceConnectionState values.
The Call's media connection state is a property of the CallObject, which can be retrieved using the call.getById or call.getAll APIs.
The SDK emits a call:mediaConnectionChange event when a Call's media connection state changes from one state to another.
Type: Object
(string)
: The Call is initializing the local side of the connection and waiting on information from the remote side.
When the information is received, the state will transition into
checking
as the Call automatically begins the connection process.
(string)
: The Call has received information from the remote endpoint and is working to establish the media connection.
When finished, the state will transition to either
connected
or
failed
.
(string)
: A usable connection has been made and the Call will now have media.
The connection may not be optimal, though, so the Call will continue establishment to improve the connection before going into the
completed
state.
(string)
: The media connection process has fully completed and the optimal connection has been established. While in this state,
the Call endpoints will receive each other's media.
(string)
: Media has become disconnected and the Call endpoints have stopped receiving each other's media.
The Call will automatically attempt to reconnect, transitioning back to
completed
if successful or to
failed
if not.
(string)
: The connection has failed and cannot be recovered automatically. A full media connection refresh is required to reestablish a connection. See the
call.restartMedia
API.
(string)
: The connection has been shut down and is no longer in use.
// Use the media connection states to check the status of the media connection of the Call.
client.on('call:mediaConnectionChange', function (params) {
// Retrieve the state of the Call this event is for.
const call = client.call.getById(params.callId)
const mediaConnectionStates = client.call.mediaConnectionStates
// Check the mediaConnectionState to determine which scenario the call is in.
switch (call.mediaConnectionState) {
case mediaConnectionStates.CONNECTED:
case mediaConnectionStates.COMPLETED:
// Media established: The Call's media is connected. The Call's participants
// are able to see/hear each other.
// These states will occur after Call establishment.
...
break
case mediaConnectionStates.NEW:
case mediaConnectionStates.CHECKING:
case mediaConnectionStates.DISCONNECTED:
// Media pending: The Call's media is not connected. The Call is working
// to connect media automatically.
// These states will occur during Call establishment and may occur midcall if there are
// connection issues (eg. poor network quality) or a Call participant has changed (eg. transfer).
...
break
case mediaConnectionStates.FAILED:
// Media has failed. The call requires a media refresh to reestablish.
// This state will occur after the `DISCONNECTED` state is encountered.
...
break
case mediaConnectionStates.CLOSED:
// Media ended due to the Call being ended.
// This state will occur after Call establishment.
...
break
}
}
Attempt to re-establish a media connection for a call.
This API will perform a "refresh" operation on the call with the intention
of resolving media issues that may have been encountered. This API is only
necessary after the Call's mediaConnectionState
has entered the failed
state, but may be used in other scenarios.
After the operation completes successfully, the Call will be re-establishing
its media connection. By this time, or shortly after, the Call's
mediaConnectionState should have
transitioned to checking
(via a
{@link call.event:call:mediaConnectionChange call:mediaConnectionChange}
event) to signify the re-establishment. It will then transition to either
connected
or failed
state, similar to during the initial Call establishment.
If this operation fails, then the Call will not attempt the re-establishment
and will remain in the failed
mediaConnectionState.
Behaviour during the operation may differ slightly based on the browser.
Notably, Firefox will always transition to the checking
mediaConnectionState no matter what
the previous state was. Whereas Chrome will skip the checking
state,
transitioning directly to either connected
or failed
. This has the
implication for Chrome that if the state does not change (for example,
the Call is in the failed
state before the media restart operation,
and media re-establishment fails), then there will be no
call:mediaConnectionChange
event emitted. For this reason, Chrome-based applications may need a
short delay after receiving the call:mediaRestart
event before checking the Call's updated
mediaConnectionState to ensure the
application is acting on the "latest" state.
The SDK will emit a call:mediaRestart event when the operation completes.
The progress of the operation will be tracked via the call:operation event.
(string)
The ID of the call to act on.
The setDefaultDevices
API from previous SDK releases (3.X) has been
deprecated in the latest releases (4.X+). The SDK no longer keeps
track of "default devices" on behalf of the application.
The devices used for a call can be selected as part of the APIs for starting the call. Microphone and/or camera can be chosen in the call.make and call.answer APIs, and speaker can be chosen when the audio track is rendered with the media.renderTracks API.
Changes the camera and/or microphone used for a Call's media input.
The latest SDK release (v4.X+) has not yet implemented this API in the same way that it was available in previous releases (v3.X). In place of this API, the SDK has a more general API that can be used for this same behaviour.
The same behaviour as the changeInputDevices
API can be implemented
using the general-purpose call.replaceTrack API. This API can
be used to replace an existing media track with a new track of the
same type, allowing an application to change certain aspects of the
media, such as input device.
const call = client.call.getById(callId)
// Get the ID of the Call's video track.
const videoTrack = call.localTracks.find(trackId => {
const track = client.media.getTrackById(trackId)
return track.kind === 'video'
})
// Select the new video options.
const media = {
video: true,
videoOptions: {
deviceId: 'cameraId'
}
}
// Change the call's camera by replacing the video track.
client.call.replaceTrack(callId, videoTrack, media)
Changes the speaker used for a Call's audio output. Supported on browser's that support HTMLMediaElement.setSinkId().
The latest SDK release (v4.X+) has not yet implemented this API in the same way that it was available in previous releases (v3.X). In place of this API, the SDK has a more general API that can be used for this same behaviour.
The same behaviour as the changeSpeaker
API can be implemented by
re-rendering the Call's audio track. A speaker can be selected when
rendering an audio track, so changing a speaker can be simulated
by unrendering the track with media.removeTracks, then
re-rendering it with a new speaker with media.renderTracks.
const call = client.call.getById(callId)
// Get the ID of the Call's audio track.
const audioTrack = call.localTracks.find(trackId => {
const track = client.media.getTrackById(trackId)
return track.kind === 'audio'
})
// Where the audio track was previously rendered.
const audioContainer = ...
// Unrender the audio track we want to change speaker for.
client.media.removeTrack([ audioTrack ], audioContainer)
// Re-render the audio track with a new speaker.
client.media.renderTrack([ audioTrack ], audioContainer, {
speakerId: 'speakerId'
})
A call operation has either started, been updated, or finished.
Information about ongoing call operations are stored with the call information (see the call.getById API). This event indicates that an operation's information has been changed.
Local call operations will be tracked from start to finish. An operation may be updated as it progresses, based on the status of the operation. The operation status may be ongoing or pending, depending if the operation is waiting on activity on the local or remote end of the call, respectively.
Except in the case of slow-start operations, remote operations will only be tracked as a "finish", to indicate that it occurred.
(Object)
Name | Description |
---|---|
params.operation string
|
The call operation causing this event. |
params.transition string
|
The transition reason for the operation change. |
params.isLocal boolean
|
Flag indicating whether the operation was local or not. |
params.previous Object?
|
The operation information before this change. If the transition is to "start" the operation, there will be no previous information. |
params.previous.operation string?
|
The operation that was ongoing. |
params.previous.status string?
|
The operation status before this change. |
params.error api.BasicError?
|
An error object, if the operation was not successful. |
An outgoing call has been started.
Information about the Call can be retrieved using the call.getById API.
(Object)
Name | Description |
---|---|
params.callId string
|
The ID of the call. |
params.error api.BasicError?
|
An error object, if the operation was not successful. |
A new incoming call has been received.
Information about the Call can be retrieved using the call.getById API.
(Object)
Name | Description |
---|---|
params.callId string
|
The ID of the call. |
params.error api.BasicError?
|
An error object, if the operation was not successful. |
client.on('call:receive', function(params) {
// We have received a call, prompt the user to respond.
promptUser(client.call.getById(params.callId));
});
A Call's state has changed.
See call.states for information about call states.
(Object)
Name | Description |
---|---|
params.callId string
|
The ID of the Media object that was operated on. |
params.previous Object
|
The call's properties before the operation changed it. |
params.previous.state string
|
The previous state of the call. |
params.previous.localHold boolean?
|
The previous local hold state. Present when the state change was a hold/unhold operation. |
params.previous.remoteHold boolean?
|
The previous remote hold state. Present when the state change was a hold/unhold operation. |
params.transition Object?
|
|
params.transition.statusCode number?
|
The status code associated with the particular state change's reason. |
params.transition.reasonText string?
|
The reason for the state change. |
params.error api.BasicError?
|
An error object, if the operation was not successful. |
client.on('call:stateChange', function (params) {
const call = client.call.getById(params.callId)
const prevState = params.previous.state
log(`Call changed from ${prevState} to ${call.state} state.`)
// Handle the event depending on the new call state.
switch (call.state) {
case client.call.states.CONNECTED:
// Handle being on call with media.
break
case client.call.states.ENDED:
// Handle call ending.
break
...
}
})
New media has been added to the call.
Tracks have been added to the Call after an SDK operation. Both sides of the Call are now able to render these tracks.
Tracks are added to a Call when either the local or remote user adds new media to the Call, using the call.addMedia API for example, or when the Call is unheld with the call.unhold API.
Remote tracks are similarly added to a Call when new tracks are added by the remote user or either user unholds the call.
This event can indicate that multiple tracks have been removed by the same operation. For example, if the remote user added video to the call, this event would indicate a single, remote video track was added. If the local user unheld the call, this event would indicate that any tracks previously on the call have been re-added, both local and remote.
Information about a Track can be retrieved using the media.getTrackById API.
client.on('call:tracksAdded', function (params) {
// Get the information for each track.
const tracks = params.trackIds.map(client.media.getTrackById)
tracks.forEach(track => {
const { id, kind, isLocal } = track
// Handle the track depending whether it is audio vs. video and local vs. remote.
...
})
})
Tracks have been removed from the Call after an SDK operation. The tracks may still exist, but the media is not available to both sides of the Call any longer.
Tracks are removed from a Call when either the local or remote user stops the tracks, by using the call.removeMedia API for example, or when the Call is held with the call.hold API.
This event can indicate that multiple tracks have been removed by the same operation. For example, if the remote user removed video from the call, this event would indicate a single, remote video track was removed. If the local user held the call, this event would indicate that all tracks on the call have been removed, both local and remote.
Information about a Track can be retrieved using the media.getTrackById API.
client.on('call:tracksRemoved', function (params) {
// Get the information for each track.
const tracks = params.trackIds.map(client.media.getTrackById)
tracks.forEach(track => {
const { id, kind, isLocal } = track
// Handle the track depending whether it is audio vs. video and local vs. remote.
...
})
})
Stats have been retrieved for a Call or specific Track of a Call.
See the call.getStats API for more information.
(Object)
Name | Description |
---|---|
params.callId string
|
The ID of the Call to retrieve stats for. |
params.trackId string?
|
The ID of the Track to retrieve stats for. |
params.result Map
|
The RTCStatsReport. |
params.error api.BasicError?
|
An error object, if the operation was not successful. |
client.on('call:statsReceived', function (params) {
// Iterate over each individual statistic inside the RTCPStatsReport Map.
params.result.forEach(stat => {
...
})
})
A local Track has been replaced by the call.replaceTrack API.
This event is a combination of a track being removed from the Call and a new track being added to the Call. The previous Track's media is no longer available, similar to the call:tracksRemoved event, and the new Track is available in its place, similar to the call:tracksAdded event. The event includes information about the Track that was replaced to help an application replace it seamlessly.
(Object)
Name | Description |
---|---|
params.callId string
|
The ID of the call where a track was replaced. |
params.newTrackId string?
|
The ID of the new track that replaced the old track. |
params.oldTrack call.TrackObject?
|
State of the replaced track. |
params.error api.BasicError?
|
An error object, if the operation was not successful. |
client.on('call:trackReplaced', function (params) {
const { callId, oldTrack, newTrackId } = params
// Unrender the removed track.
handleTrackGone(oldTrack, callId)
// Render the added track.
const track = client.media.getTrackById(newTrackId)
handleTrackAdded(track, callId)
})
The list of available and supported codecs by the browser have been retrieved.
This event is emitted as a result of the call.getAvailableCodecs API. Please refer to the API for more information.
A Call's media connection state has been changed.
This event is emitted as a result of changes to the media connection of the Call. These state changes occur during call establishment, connection loss/re-establishment, call completion, etc.
To check the media connection state of a call, retrieve the call's information using the call.getById API,
and check the mediaConnectionState
property of the call.
See {@link call.mediaConnectionStates} for the list of possible values and descriptions.
A media restart operation for a Call has been attempted.
This event is emitted as a result of the call.restartMedia API being called. See the description for call.restartMedia for information about its usage.
The call:mediaConnectionChange event will also be emitted alongside this event when the media restart operation is successful.
(Object)
Name | Description |
---|---|
params.callId string
|
The ID of the Call that was acted on. |
params.error api.BasicError?
|
An error object, if the operation was not successful. |
client.on('call:mediaRestart', function (params) {
if (params.error) {
// The operation failed. May want to determine whether to re-attempt the
// operation (if the failure was simply a connectivity issue) or to
// consider the call's media irrecoverable.
...
} else {
// The call should be re-establishing media, with the call's
// `mediaConnectionState` being updated.
const mediaState = client.call.getById(params.callId).mediaConnectionState
...
}
})
The 'connection' namespace is used to connect and maintain connections between the SDK and one or more backend servers.
Information about a websocket connection.
Can be retrieved using the connection.getSocketState API.
Type: Object
(boolean)
: The state of the websocket connection.
(boolean)
: True if the client has sent a ping to the server and is still waiting for a pong response.
(Object)
: Information about how the websocket is being used.
(string)
: The SDK platform being used.
(number)
: How often the client will ping the server to test for websocket connectivity.
(number)
: How many times the SDK will try to reconnect a disconnected websocket.
(number)
: How long the SDK will wait before retrying websocket reconnection.
(number)
: Reconnect delay multiplier for subsequent attempts. The reconnect delay time will be multiplied by this after each failed reconnect attempt to increase the delay between attempts. eg. 5000ms then 10000ms then 20000ms delay if value is 2.
(number)
: Maximum time delay between reconnect attempts (milliseconds). Used in conjunction with
reconnectTimeMultiplier
to prevent overly long delays between reconnection attempts.
(boolean)
: Indicates if the SDK should automatically try reconnecting a disconnected websocket.
(number)
: How many missed pings before the SDK stops trying to reconnect a disconnected websocket.
(string)
: The mode used for authenticating with the server.
(Object)
: Information required to connect a websocket to the server.
wsInfo.protocol
string?
The protocol to use to connect a websocket.
wsInfo.server
string?
The domain name or IP address of the server to connect to.
wsInfo.port
number?
The port of the server to connect to.
wsInfo.url
string?
The URL path to use to request a websocket connection.
wsInfo.params
string?
Any additional params that might be required by the server to establish the websocket connection.
(number)
: The date and time that the last known contact with the server was.
Get the state of the websocket.
(string
= 'link'
)
Backend platform for which to request the websocket's state.
connection.WSConnectionObject
:
Details about the current websocket connection, including state and configuration.
Triggers a reset in the connection to the WebSocket being used for notifications. This can be used in scenarios where a network issue (undetectable by the SDK) is detected by an application.
If there is no WebSocket currently connected, this function has no effect. Calling this function will trigger all the normal WebSocket and connectivity lifecycle events as well as trigger re-connection processing that follows the configuration of the SDK. Calling this function always has the potential of causing some events being lost by the SDK and preventing proper operation.
The 'contacts' namespace allows users to store personal contacts to their account.
Add a contact to a user's personal address book.
Will trigger the contacts:new
event.
(Object)
The contact object.
Name | Description |
---|---|
contact.primaryContact string
|
The primary userId for the contact |
contact.contactId string
|
The contact's unique contact ID |
contact.firstName string?
|
The contact's first name |
contact.lastName string?
|
The contact's last name |
contact.email string?
|
The contact's email address |
contact.homePhoneNumber string?
|
The contact's home phone number |
contact.businessPhoneNumber string?
|
The contact's business phone number |
contact.mobilePhoneNumber string?
|
The contact's mobile phone number |
contact.list string?
|
The name of the contact list for which to add this contact to ("friends" by default) |
contact.buddy boolean?
|
Indicates whether or not the contact is a friend of the user |
Refreshes the local information about contacts. This will get new contacts from the platform.
Will trigger the contacts:change
event.
Update a contact from the user's personal address book.
Will trigger the contacts:change
event.
(Object)
The contact object.
Name | Description |
---|---|
contact.primaryContact string
|
The primary userId for the contact |
contact.contactId string
|
The contact's unique contact ID |
contact.firstName string?
|
The contact's first name |
contact.lastName string?
|
The contact's last name |
contact.email string?
|
The contact's email address |
contact.homePhoneNumber string?
|
The contact's home phone number |
contact.businessPhoneNumber string?
|
The contact's business phone number |
contact.mobilePhoneNumber string?
|
The contact's mobile phone number |
contact.list string?
|
The name of the contact list for which to add this contact to ("friends" by default) |
contact.buddy boolean?
|
Indicates whether or not the contact is a friend of the user |
A new contact has been added to the address book.
(Object)
The new contact.
The contacts list has changed.
client.on('contacts:change', function () {
// Get the updated list of contacts.
const contacts = client.contacts.getAll()
...
})
The messaging feature revolves around a 'conversation' namespace. It is responsible for storing the conversations and its messages, and returning conversation objects when requested.
See the "Conversation" and "Message" sections of the documentation for more details.
Available conversations can be retrieved using the conversation.get or conversation.getAll APIs.
Messaging functions are all part of the 'conversation' namespace. Ex: client.conversation.getAll
Possible types of conversations.
Type: Object
(string)
: A simple chat between two users.
(string)
: A chat between groups of users
(string)
: A chat using SMS.
// Use the chat types to fetch group conversations.
client.conversation.fetch({type: client.conversation.chatTypes.GROUP}) {
A Conversation object represents a conversation either between two users, or between a user and a group. A user can create a Conversation using conversation.create Messaging API.
A Conversation can be used to create messages to send using the Conversation and Messaging APIs Conversation.createMessage and Message.send functions.
Once a sender sends the initial message (within a conversation) to a recipient, there will be a conversation object saved in both sender and recipient's state.
Type: Object
(string)
: The ID/group ID of the remote user with which the current user is having a conversation.
(string)
: The ID of the current user who is having a conversation.
(number)
: The timestamp (milliseconds since epoch) of when a message was last received in this conversation.
This property applies only to conversation object stored in recipient's state.
(string)
: The last message received.
(Array<conversation.Message>)
: The array of message objects.
Creates and return a message object. You must specify a part. If this is a simple text message, provide a text
part as demonstrated in the example below.
If successful, the event messages:change will be emitted.
(conversation.Part)
The Part to add to the message.
conversation.Message
:
The newly created Message object.
conversation.createMessage({type: 'text', text: 'This is the message'});
Clears all messages in this conversation from local state.
If successful, the event messages:change will be emitted.
Gets either a subset or all available messages, associated with this conversation. In this context, available messages means whatever messages have been fetched so far, from backend. (i.e. they are locally stored).
(number
= 0
)
Specifies the start index value within the array of all available messages.
If not specified or invalid, its value will default to index 0.
(number?)
Specifies how many messages to return, starting with startIndex.
If not specified or invalid, then the last message returned will always be last message fetched so far.
Array<conversation.Message>
:
An array of messages.
Gets a specific message from this conversation.
(string)
The ID of the message to retrieve.
conversation.Message
:
A message object.
Deletes specified messages from this conversation. Provide an array of message IDs for the messages to be deleted.
If successful, the event messages:change will be emitted.
Delete the conversation.
If successful, the event messages:change will be emitted.
Subscribe to this conversation's messages list to receive notification of changes.
Function
:
The unsubscribe function.
Allows the user to fetch messages associated with a specific conversation to make them available.
When the operation is complete, a messages:change
event will be emitted.
Messages can then be retrieved using Conversation.getMessages.
The list of returned messages will always be time sorted so that the most recent mesage will be the first one in that list.
If successful, the event messages:change will be emitted.
(Object?)
Fetch options. Even though it's an optional parameter, user is encouraged to specify one in order to avoid a large amount of data being returned by backend.
Name | Description |
---|---|
options.amount number
(default 50 )
|
A maximum amount of messages to fetch.
If server has more messages then its response will include a
next
parameter which can be used
for subsequent fetch requests (i.e.
next
can be used for pagination)
|
options.next String?
|
A unique identifier, that can be used to fetch the next set of messages. It's value is provided by the backend (as part of a previous fetch response) and it should be used as-is, by subsequent client requests. |
options.untilTime number?
|
A Unix-like timestamp representing the delimiting date & time (up to the seconds) for those messages.
Therefore any messages, whose timestamp are smaller than untilTime (i.e. older), will not be returned by the server's response.
This parameter can be used to add an additional constraint (i.e. limit by time) as opposed to limit using an explicit amount.
It can be simultaneously used with
next
and/or
amount
parameters.
|
Sets the typing status of the conversation for the current user. Other participants will be notified of changes to the conversation's typing status.
If successful, the event isTypingList:change will be emitted.
(boolean)
Whether the user is typing or not
A Part is a custom object representing a section of the payload of a message. Messages can have one or many Parts.
Type: Object
(string)
: The text of the message. Messages with file or json attachments are still required to have text associated to it.
(Object?)
: The object corresponding to a json object to attach to a message. A
Part
cannot have both json and a file.
(File?)
: The file to attach to a message. A
Part
cannot have both json and a file.
A Message object is a means by which a sender can deliver information to a recipient.
Creating and sending a message:
The message object can be obtained through the Conversation.createMessage API on an existing conversation.
Messages have Parts which represent pieces of a message, such as a text part, a json object part or a file part. Once all the desired parts have been added to the message using the Message.addPart function, the message can then be sent using the Message.send function.
Once the sender sends a message, this message is saved in sender's state as an object. Similarly, once the recipient gets a message, this message is saved in recipient's state.
Retrieving a delivered message:
Once a message is delivered successfully, it can be obtained through the Conversation.getMessages or Conversation.getMessage API on an existing conversation.
Below are the properties pertaining to the message object, returned by Conversation.getMessage(s) APIs, for either sender or recipient.
Type: Object
(number)
: A Unix timestamp in seconds marking the time when the message was created by sender.
(Array<conversation.Part>)
: An array of Part Objects.
(string)
: The primary contact address of the sender.
(Array<string>)
: An array of primary contact addresses associated with various destinations to which the message is meant to be delivered.
(string)
: The unique id of the message. The message object (stored in sender's state) has a different id
than the one associated with the message object stored in recipient's state.
(string)
: The type of message that was sent. See
conversation.chatTypes
for valid types.
This property applies only to message objects stored in sender's state.
(boolean)
: Whether or not the recipient of the message is in the process of fetching the message attachment(s) using the provided link(s).
The fetching includes retrieval of message attachment(s) as well as retrieval of thumbnail(s) representing the attachment(s).
Sends the message.
Add an additional Part
to a message.
Creates a usable image link for the message in this Message
instance.
Fetches chat conversations that the current user is part of. This will refresh the available information with any new information from the server.
If successful, the event conversations:change will be emitted.
Available conversation information can be retrieved using the conversation.get or conversation.getAll Messaging APIs.
(Object?)
A configuration object to query for more specific results.
Name | Description |
---|---|
options.type string
(default 'chat-oneToOne' )
|
The type of conversation to fetch. See conversation.chatTypes for valid types. |
Retrieves a conversation object matching the User ID and Type provided if available.
Conversations are made available using the conversation.fetch or conversation.create Messaging APIs.
(string)
The User ID of the remote user with which the current user had a conversation.
(Object?)
Options used to query for more specific results.
Name | Description |
---|---|
options.type string
(default 'chat-oneToOne' )
|
The type of conversation to get. See conversation.chatTypes for valid types. |
conversation.Conversation
:
A Conversation object.
Creates and return a new conversation object. Any messages being sent through this Conversation object will be sent to the destination provided.
If successful, the event conversations:new will be emitted.
(string)
The ID of the remote user to create a conversation with. The ID will be changed to lowercase.
(Object?)
Options to use when creating a new conversation object.
Name | Description |
---|---|
options.type string
(default 'chat-oneToOne' )
|
The type of conversation to create. See conversation.chatTypes for valid types. |
conversation.Conversation
:
A Conversation object.
Retrieves all available conversations for the current user.
Conversations are made available using the conversation.fetch or conversation.create Messaging APIs.
Array<conversation.Conversation>
:
An array of Conversation objects.
A new conversation has been created.
(Array<Object>)
An array containing one object with information about the newly created conversation.
Name | Description |
---|---|
params.destination Array<string>
|
An array of destinations for messages created in this conversation. |
params.type string
|
The type of conversation created. See conversation.chatTypes for valid types. |
A change has occurred in the conversation list.
(Array<Object>)
An array of objects containing information about the conversations that have changed.
Name | Description |
---|---|
params.destination Array<string>
|
An array of destinations for messages in this conversation. |
params.type string
|
The type of conversation changed. See conversation.chatTypes for valid types. |
A change has occurred in a specific conversation's message list.
If a single message was created/edited, messageId
will be present.
(Object)
Name | Description |
---|---|
params.destination Array<string>
|
An array of destinations for the message affected. |
params.type string
|
The type of conversation. See conversation.chatTypes for valid types. |
params.messageId string?
|
The ID of the message affected. |
params.sender string?
|
The username of the sender. |
params.next string?
|
A unique identifier that can be used to fetch the next set of messages. This parameter is present only if a fetch request was issued on a chat conversation and only if there are more messages to fetch from backend. |
params.messageIds Array<string>?
|
The message IDs associated with the fetched messages. This parameter is present only if a fetch request was issued on a chat conversation. |
An error occurred with messaging.
(Object)
Name | Description |
---|---|
params.error api.BasicError
|
The Basic error object. |
The list of users that are currently typing has changed.
(Object)
Name | Description |
---|---|
params.destination Array<string>
|
An array of destinations in this conversation. |
params.sender string
|
The username of the sender that caused the event to fire. |
params.type string
|
The type of conversation. See conversation.chatTypes for valid types. |
params.state string
|
(active/idle) The current state of the sender that caused the event to fire. |
The 'groups' namespace provides an interface for an application to create and manage Groups for a User. Groups are used in conjunction with the Messaging feature to allow for group conversations.
Groups are persisted by the server. When the SDK is initialized, there will be no Group information available, but the groups.fetch API is used to make available any Groups that were created previously.
The creator of a Group is the Group's administrator.
Creates a Group.
The SDK will emit a group:new event locally when the operation completes. This event will include a Group ID that is used to uniquely identify the group.
Remote users added to the Group during creation will receive a
group:invitation_received
event, which will include information
about the Group. Group participants can be managed after creation
using the groups.addParticipant and
groups.removeParticipant APIs.
Group information will become available after the operation completes using the groups.get and groups.getAll APIs.
(Object)
Name | Description |
---|---|
params.participants Array<string>?
|
List of participants to invite to the group as part of creation. A participant's address should be in the form of their User ID. |
params.subject string?
|
Subject of the Group. |
params.name string
|
Name of the Group. |
params.image string?
|
HTTP URL of the image to be used as the Group's avatar. |
params.type string
|
Closed group indicates this is an invitation-based closed chat group. Only Closed supported. |
Fetches information about all Groups that the current user is a member of. This will refresh the available Groups with any new information from the server.
The SDK will emit a group:refresh event when the operation completes.
Information about an available Group can be retrieved using the groups.getAll or groups.get APIs.
Retrieves information about all Group invitations available.
The group:invitation_received event indicates that a new Group invitation is available.
Array<Invitations>
:
The list of Group invitations.
Leaves a Group.
The SDK will emit a group:change event when the operation completes.
(string)
The ID of the Group to leave.
Accepts an invitation to a Group.
The SDK will emit a group:change event when the operation completes.
(string)
The ID of the Group to accept an invitation to.
Rejects an invitation to a Group.
The SDK will emit a group:change event when the operation completes.
(string)
The ID of the Group to reject an invitation to.
Adds participant to a Group.
The SDK will emit a group:change event when the operation completes. The participant being added will receive a group:invitation_received event.
Removes a participant from a Group.
The SDK will emit a group:change event when the operation completes.
Deletes a Group.
The Group will no longer be available using the groups.get and groups.getAll APIs.
The SDK will emit a group:delete event for all participants in the Group.
(string)
The ID of the Group to delete.
A new Group has been created and its information is now available.
Information about an available Group can be retrieved using the groups.getAll or groups.get APIs.
// Set an event listener for new Groups being created.
client.on('group:new', params => {
const group = client.groups.get(params.groupId)
// Use the new group.
})
A Group has been deleted and is no longer available.
The latest information about the Group is provided as part of the event.
(Object)
Name | Description |
---|---|
params.group Object
|
The information about the Group that was deleted. |
params.group.id string
|
the Group ID of the deleted group |
params.group.image string
|
the group image of the deleted group |
params.group.name string
|
the group name of the deleted group |
params.group.participants Array
|
the participants of the group of the deleted group |
params.group.subject string
|
the subject for the group of the deleted group |
The list of Groups has been refreshed.
Any previously available Groups may have had their information updated, and any otherwise unknown Groups may now be available.
Information about an available Group can be retrieved using the groups.getAll or groups.get APIs.
An invitation to a Group has been received.
Information about a Group invitation can be retrieved using the groups.getInvitations API.
An error occurred with a Group operation.
(Object)
Name | Description |
---|---|
params.error api.BasicError
|
The Basic error object. |
The SDK has an internal logging system for providing information about its behaviour. The SDK will generate logs, at different levels for different types of information, which are routed to a "Log Handler" for consumption. An application can provide their own Log Handler (see config.logs) to customize how the logs are handled, or allow the default Log Handler to print the logs to the console.
The SDK's default Log Handler is merely a thin wrapper around the browser's
console API (ie. window.console
). It receives the log generated by the
SDK, called a "Log Entry", formats a
human-readable message with it, then uses the console to log it at the
appropriate level. This is important to be aware of, since your browser's
console may affect how you see the SDK's default log messages. Since the
default Log Handler uses the console's levels, the browser may filter
which messages are shown depending on which levels it has configured. For
a user that understands console log levels, this can be helpful for
filtering the logs to only the relevant information. But it can equally
be a hindrance by hiding the more detailed log messages (at the 'debug'
level), since browser can have this level hidden by default. For this
reason, we recommend providing a custom Log Handler to the SDK that is
better suited for your application and its users.
A LogEntry object is the data that the SDK compiles when information is logged. It contains both the logged information and meta-info about when and who logged it.
A LogHandler provided to the SDK (see config.logs) will need to handle LogEntry objects.
Type: Object
(number)
: When the log was created, based on UNIX epoch.
(string)
: The log function that was used to create the log.
(string)
: The level of severity the log.
(Object)
: The subject that the log is about.
(Array)
: The logged information, given to the Logger
method as parameters.
(Object?)
: Timing data, if the log method was a timer method.
function defaultLogHandler (logEntry) {
// Compile the meta info of the log for a prefix.
const { timestamp, level, target } = logEntry
let { method } = logEntry
const logInfo = `${timestamp} - ${target.type} - ${level}`
// Assume that the first message parameter is a string.
const [log, ...extra] = logEntry.messages
// For the timer methods, don't actually use the console methods.
// The Logger already did the timing, so simply log out the info.
if (['time', 'timeLog', 'timeEnd'].includes(method)) {
method = 'debug'
}
console[method](`${logInfo} - ${log}`, ...extra)
}
A LogHandler can be used to customize how the SDK should log information. By default, the SDK will log information to the console, but a LogHandler can be configured to change this behaviour.
A LogHandler can be provided to the SDK as part of its configuration (see config.logs). The SDK will then provide this function with the logged information.
Type: Function
(Object)
The LogEntry to be logged.
// Define a custom function to handle logs.
function logHandler (logEntry) {
// Compile the meta info of the log for a prefix.
const { timestamp, level, target } = logEntry
let { method } = logEntry
const logInfo = `${timestamp} - ${target.type} - ${level}`
// Assume that the first message parameter is a string.
const [log, ...extra] = logEntry.messages
// For the timer methods, don't actually use the console methods.
// The Logger already did the timing, so simply log out the info.
if (['time', 'timeLog', 'timeEnd'].includes(method)) {
method = 'debug'
}
console[method](`${logInfo} - ${log}`, ...extra)
}
// Provide the LogHandler as part of the SDK configurations.
const configs = { ... }
configs.logs.handler = logHandler
const client = create(configs)
Possible levels for the SDK logger.
The SDK will provide Log Entries to the Log Handler for all logs at or above the set log level. 'debug' is considered the lowest level and 'silent' the highest level. For example, if the current level is 'info', then the Log Handler will receive Log Entries for logs at 'info', 'warn', and 'error', but not for the 'debug' level.
(string)
: Nothing will be logged.
(string)
: Unhandled error information will be logged. If
the SDK encounters an issue it cannot resolve, the error will be included
in the logs. This likely points to an issue with the SDK itself or an
issue with how the SDK is being used.
(string)
: Warning messages for the application developer will
be logged. If the SDK encounters an issue that it can recover and continue,
a warning about the issue will be included in the logs. These logs point
to issues that need to be handled by the application. For example, providing
an invalid configuration to the SDK will cause a warning log that explains
the issue.
(string)
: General information about the SDK's operations will
be logged, outlining how the SDK is handling the operations. Reading through
these logs should provide a high-level view of what the SDK is doing,
and why it is doing it.
(string)
: Detailed information about the SDK's operations,
meant for debugging issues, will be logged. Specific information and relevant
operation data are provided for understanding the scenario that the SDK
was in during the operation.
The 'media' namespace provides an interface for interacting with Media that the SDK has access to. Media is used in conjunction with the Calls feature to manipulate and render the Tracks sent and received from a Call.
Media and Track objects are not created directly, but are created as part of Call operations. Media and Tracks will either be marked as "local" or "remote" depending on whether their source is the local user's machine or a remote user's machine.
The Media feature also keeps track of media devices that the user's machine can access. Any media device (eg. USB headset) connected to the machine can be used as a source for media. Available devices can be found using the media.getDevices API.
Retrieves the available media devices for use.
The devices:change event will be emitted when the available media devices have changed.
Object
:
The lists of camera, microphone, and speaker devices.
Retrieves an available Media object with a specific Media ID.
(string)
The ID of the Media to retrieve.
call.MediaObject
:
A Media object.
Retrieve an available Track object with a specific Track ID.
(string)
The ID of the Track to retrieve.
call.TrackObject
:
A Track object.
Requests permission to access media devices on the end-user's machine.
This API will trigger the browser to ask the end-user for permission to access their camera and/or microphone. These permissions are needed for the SDK to read information about the devices (the label, for example) and for using the devices for a call.
If the browser does not yet have permission, it will prompt the end-user with a small pop-up window, giving the user a chance to allow/deny the permissions. The behaviour of this pop-up window differs slightly based on the browser; it may automatically save the user's decision (such as in Chrome and Safari) or it may require the user to choose whether their decision should be saved (such as in Firefox).
This API is not required for proper usage of media and/or calls, but helps to prepare a user before a call is made or received. It allows an application to prompt the user for device permissions when it is convenient for them, rather than during call setup. If the user saves their decision, they will not be prompted again when the SDK accesses those devices for a call.
For device information, the media.getDevices API will retrieve the list of media devices available for the SDK to use. If this list is empty, or is missing information, it is likely that the browser does not have permission to access the device's information. We recommend using the media.initializeDevices API in this scenario if you would like to allow the end-user to select which device(s) they would like to use when they make a call, rather than using the system default.
The SDK will emit a devices:change event when the operation is successful or a devices:error event if an error is encountered.
// The SDK will ask for both audio and video permissions by default.
client.media.initializeDevices()
// The SDK will only ask for audio permissions.
client.media.initializeDevices({ audio: true, video: false })
Render Media Tracks in a container.
The container is specified by providing a CSS selector string that corresponds to the HTMLElement to act as the container.
(string)
A CSS selector string that uniquely
identifies an element. Ensure that special characters are properly
escaped.
// When a Call receives a new track, render it.
client.on('call:newTrack', function (params) {
const track = client.media.getTrackById(params.trackId)
const container = params.local ? localContainer : remoteContainer
// Render the Call's new track when it first becomes available.
client.media.renderTracks([ track.trackId ], container)
})
Remove Media Tracks from a container.
The container is specified by providing a CSS selector string that corresponds to the HTMLElement to act as the container.
Mutes the specified Tracks.
This API prevents the media of the specified Tracks from being rendered. Audio Tracks will become silent and video Tracks will be a black frame. This does not stop media from being received by those Tracks. The media simply cannot be used by the application while the Track is muted.
If a local Track being sent in a Call is muted, the Track will be noticeably muted for the remote user. If a remote Track received in a call is muted, the result will only be noticeable locally.
This mute operation acts on those specified Tracks directly. It does not act on the active Call as a whole.
The SDK will emit a media:muted event when a Track has been muted.
Unmutes the specified Tracks.
Media will resume its normal rendering for the Tracks. Like the 'muteTracks' API, this unmute operation acts on those specified Tracks directly. Therefore it does not act on active Call as a whole.
The SDK will emit a media:unmuted event when a Track has been unmuted.
The media devices available for use have changed.
Information about the available media devices can be retrieved using the media.getDevices API.
// Listen for changes to available media devices.
client.on('devices:change', function () {
// Retrieve the latest media device lists.
const devices = client.media.getDevices()
})
An error occurred while trying to access media devices.
The most common causes of this error are when the browser does not have permission from the end-user to access the devices, or when the browser cannot find a media device that fulfills the MediaConstraint(s) that was provided.
The specified Tracks have been muted.
A Track can be muted using the media.muteTracks API.
The specified Tracks have been unmuted.
A Track can be unmuted using the media.unmuteTracks API.
The specified Track has had its media source muted.
The Track is still active, but is not receiving media any longer. An audio track will be silent and a video track will be a black frame. It is possible for the track to start receiving media again (see the media:sourceUnmuted event).
This event is generated outside the control of the SDK. This will predominantely happen for a remote track during network issues, where media will lose frames and be "choppy". This may also happen for a local track if the browser or end-user stops allowing the SDK to access the media device, for example.
The specified Track has started receiving media from its source once again.
The Track returns to the state before it was muted (see the media:sourceMuted event), and will be able to display video or play audio once again.
This event is generated outside the control of the SDK, when the cause of the media source being muted had been undone.
The specified Track has been rendered into an element.
(Object)
Name | Description |
---|---|
params.trackIds Array<string>
|
The list of track id's that were rendered. |
params.selector string
|
The css selector used to identify the element the track is rendered into. |
params.error api.BasicError?
|
An error object, if the operation was not successful. |
A local Track has ended unexpectedly. The Track may still be part of a Call but has become disconnected from its media source and is not recoverable.
This event is emitted when an action other than an SDK operation stops the track. The most comon scenarios are when a device being used for a Call disconnects, any local tracks (such as audio from a bluetooth headset's microphone or video from a USB camera) from that device will be ended. Another scenario is for screensharing, where some browsers provide the ability to stop screensharing directly rather than through an SDK operation.
When a local track ends this way, it will still be part of the Call but will not have any media. The track can be removed from the call with the call.removeMedia API so the remote side of the Call knows the track has stopped, or the track can be replaced with a new track using the call.replaceTrack API to prevent any interruption.
The 'presence' namespace provides an interface for an application to set the User's presence information and to track other Users' presence information.
Presence information is persisted by the server. When the SDK is initialized, there will be no information available. Presence information will become available either by using presence.fetch or by subscribing for updates about other Users, using presence.subscribe.
Available presence information can be retrieved using presence.get or presence.getAll.
The PresenceStatus type defines the user's current status in terms of the user's availability to communicate/respond to other users in the network. An instance of this type can be obtained by invoking the presence.get function.
Reporting when a user is on the phone is enabled (by default), which means that presence update notifications will be sent whenever a user is in a call, as well as when the call has ended. This is a user preference enabled or disabled on server side, and it can only be changed on the server side.
The status is set to open as soon as a user subscribes for the presence service.
Type: Object
(string)
: The unique identifier for the user associated with this presence status.
(string)
: The current status the user has set for themselves. For supported values see
presence.statuses
.
(string)
: The current activity of the user.
For supported values see
presence.activities
.
(string)
: Additional message accompanying the status & activity.
(boolean)
: Whether the presence information has been loaded or is in the process of loading.
Possible presence activity values.
Type: Object
(string)
(string)
(string)
(string)
(string)
(string)
(string)
const { statuses, activities } = client.presence
// Use the values when updating presence.
client.presence.update(statuses.OPEN, activities.AVAILABLE)
Updates the presence information for the current user.
See presence.statuses and presence.activities for valid values.
The SDK will emit a presence:selfChange event when the operation completes. The updated presence information is available and can be retrieved with presence.getSelf.
Other users subscribed for this user's presence will receive a presence:change event.
Fetches presence information for the given users. This will refresh the available information with any new information from the server.
Available presence information an be retrieved using the presence.get or presence.getAll APIs.
Retrieves the presence information for the current user.
This information is set using the presence.update API.
Object
:
Presence information for the current user.
A presence update about a subscribed user has been received.
This event is generated as a result of presence.fetch or presence.update operations.
For the latter operation, the current user receives a presence update of another user that the current user is subscribed to.
The changed information can be retrieved using the presence.get API.
The current user's presence information has changed.
The changed information can be retrieved using the presence.getSelf API.
An error occurred with presence.
(Object)
Name | Description |
---|---|
params.error api.BasicError
|
The Basic error object. |
The 'request' namespace (within the 'api' type) is used to make network requests to the server.
Send a request to the underlying REST service with the appropriate configuration and authentication. This is a wrapper on top of the browser's fetch API and behaves very similarly but using SDK configuration for the base URL and authentication as well as SDK logging.
(string)
The full path of the resource to fetch from the underlying service. This should include any REST version
or user information. This path will be appended to the base URL according to SDK configuration.
(RequestInit)
An object containing any custom settings that you want to apply to the request. See
fetch API
for a full description and defaults.
// Send a REST request to the server
// Create a request options object following [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/fetch)
const requestOptions = {
method: 'POST',
body: JSON.stringify({
test: 123
})
}
// Note that you will need to subscribe for the `custom` service in order to
// receive notifications from the `externalnotification` service.
const response = await client.request.fetch('/rest/version/1/user/xyz@test.com/externalnotification', requestOptions)
A set of SdpHandlerFunctions for manipulating SDP information. These handlers are used to customize low-level call behaviour for very specific environments and/or scenarios.
Note that SDP handlers are exposed on the entry point of the SDK. They can be added during initialization of the SDK using the config.call.sdpHandlers configuration parameter. They can also be set after the SDK's creation by using the call.setSdpHandlers function.
import { create, sdpHandlers } from 'kandy';
const codecRemover = sdpHandlers.createCodecRemover(['VP8', 'VP9'])
const client = create({
call: {
sdpHandlers: [ codecRemover, <Your-SDP-Handler-Function>, ...]
}
})
// Through the Call API post-instantiation
client.call.setSdpHandlers([ codecRemover, <Your-SDP-Handler-Function>, ...])
This function creates an SDP handler that will remove codecs matching the selectors specified for SDP offers and answers.
In some scenarios it's necessary to remove certain codecs being offered by the SDK to remote parties. For example, some legacy call services limit the SDP length (usually to 4KB) and will reject calls that have SDP size above this amount.
While creating an SDP handler would allow a user to perform this type of manipulation, it is a non-trivial task that requires in-depth knowledge of WebRTC SDP.
To facilitate this common task, the createCodecRemover function creates a codec removal handler that can be used for this purpose. Applications can use this codec removal handler in combination with the call.getAvailableCodecs function in order to build logic to determine the best codecs to use for their application.
call.SdpHandlerFunction
:
The resulting SDP handler that will remove the codec.
import { create, sdpHandlers } from 'kandy';
const codecRemover = sdpHandlers.createCodecRemover([
// Remove all VP8 and VP9 codecs.
'VP8',
'VP9',
// Remove all H264 codecs with the specified FMTP parameters.
{
name: 'H264',
fmtpParams: ['profile-level-id=4d0032', 'packetization-mode=1']
}
])
const client = create({
call: {
sdpHandlers: [codecRemover]
}
})
The 'services' namespace allows an application to manage how they wish the SDK to receive communications from the platform. An application can subscribe to services in order to receive updates about that service for the current user. A feature generally requires a subscription for its service to be fully functional.
The services an application can subscribe to are based on the features included in the SDK. The list of available services can be retrieved using the services.getSubscriptions API. These values can be used with the services.subscribe API.
The channel used for subscriptions is the method for receiving the service
updates. The recommended channel is websocket
, where the SDK is able to
handle receiving the updates internally. Alternate channel methods, if a
websocket cannot be used, will be available in the future.
The ServiceDescriptor type defines the format for specifying how to subscribe for a certain service.
This is the service configuration object that needs to be passed (as part of an array of configuration objects) when calling
the services.subscribe function.
Only some plugins (call
, messaging
and presence
) support such configuration object that needs to be passed
to the subscribe function.
Type: Object
(string)
: The name of the available service user wants to subscribe to.
The available service names are
chat
,
presence
,
call
and
smsinbound
.
(Object?)
: An object containing any additional parameters required for subscribing to that service.
This is an optional property as not all service subscriptions require it.
// Subscribe to chat, presence & call services on a WebSocket channel.
client.services.subscribe([
{service: 'chat'},
{service: 'presence'},
{service: 'call'},
], 'websocket')
The SmsInboundServiceParams type defines the additional information when subscribing to SMS inbound service. This is the configuration object that needs to be passed as the value for the ServiceDescriptor.params property.
Type: Object
(string)
: An E164 formatted DID number.
The subscription created will provide notifications for inbound SMS messages destined for this address.
// Subscribe to smsinbound service on a WebSocket channel.
client.services.subscribe([
{service: 'smsinbound', params: {destinationAddress: '+18001234567'}}
], 'websocket')
Subscribes to platform notifications for an SDK service.
Subscriptions can only be made for services available to the SDK. See services.getSubscriptions for information about services.
Extra configurations can be provided for a subscription as part of its
"service configurations" object (see the services
parameter). This
configuration object must contain a service
property with the
service name, but may also include other properties as extra
subscription configurations.
The SDK currently only supports the websocket
channel as a subscription
type.
(Array<(string | services.ServiceDescriptor)>)
A list of service configurations.
// Subscribe for chat and SMS services.
const services = [
{ service: 'chat' },
// Specify extra configurations for certain services.
{ service: 'smsinbound', params: {destinationAddress: '<phoneNumber>' }}
]
client.services.subscribe(services)
Cancels existing subscriptions for platform notifications.
Existing subscriptions can be retrieved using the
services.getSubscriptions API. The subscribed
values are the
services that can be unsubscribed from.
(string
= 'websocket'
)
The method of how the service updates
are being received.
// Unsubscribe from chat and SMS services.
const services = [ 'chat', 'smsinbound' ]
client.services.unsubscribe(services)
Retrieves information about currently subscribed services and available services.
The available
values are the SDK's services that an application can
subscribe to receive notifications about. A feature generally
requires a subscription to its service in order to be fully functional.
The subscribed
values are the SDK's services that the application has
an active subscription for. Services are subscribed to using the
services.subscribe API.
Object
:
Lists of subscribed and available services.
// Get the lists of services.
const services = client.services.getSubscriptions()
// Figure out which available services don't have a subscription.
const notSubscribed = services.available.filter(service => {
return !services.subscribed.includes(service)
})
// Subscribe for all not-yet-subscribed services.
client.services.subscribe(notSubscribed)
Subscription information has changed.
The updated subscription information can be retrieved using the services.getSubscriptions API.
(Object)
Name | Description |
---|---|
params.reason string?
|
When unsolicited, the reason for the change. Reason can have (but not limited to) these values: 'GONE' - When Connection was terminated by the server. 'LOST_CONNECTION' - When internet connection was lost. 'WS_OVERRIDDEN' - When websocket was overridden by the server. |
An error occurred during a subscription operation.
The subscription information can be retrieved using the services.getSubscriptions API.
An attempt to extend the current user's subscription was made.
In a failure scenario, the current user is still connected, and further resubscription attempts will be made, but may become disconnected if the session expires.
(Object)
Name | Description |
---|---|
params.attemptNum number
|
The attempt number of this resubscription. |
params.isFailure boolean
|
Whether the resubscription failed or not. |
params.error api.BasicError?
|
The Basic error object. |
The 'user' namespace allows access to user information for users within the same domain.
The User data object.
Type: Object
(user.UserID)
: The User ID of the user.
(string)
: The email address of the user.
(string)
: The first name of the user.
(string)
: The last name of the user.
(string)
: The URL to get the photo of the user.
(string)
: Whether the user is a "buddy". Values can be "true" or "false".
Fetches information about a User.
The SDK will emit a users:change event after the operation completes. The User's information will then be available.
Information about an available User can be retrieved using the user.get API.
(string)
The User ID of the user.
Fetches information about the current User from directory. This API is simply a shortcut for the user.fetch(getUserInfo().identity) API.
The SDK will emit a users:change event after the operation completes. The User's information will then be available.
Information about an available User can be retrieved using the user.get API.
Retrieves information about a User, if available.
See the user.fetch and user.search APIs for details about making Users' information available.
(user.UserID)
The User ID of the user.
user.User
:
The User object for the specified user.
Retrieves information about all available Users.
See the user.fetch and user.search APIs for details about making Users' information available.
Searches the domain's directory for Users.
The SDK will emit a directory:change event after the operation completes. The search results will be provided as part of the event, and will also be available using the user.get and user.getAll APIs.
(Object)
The filter options for the search.
Name | Description |
---|---|
filters.userId user.UserID?
|
Matches the User ID of the user. |
filters.name string?
|
Matches the firstName or lastName. |
filters.firstName string?
|
Matches the firstName. |
filters.lastName string?
|
Matches the lastName. |
filters.userName string?
|
Matches the userName. |
filters.phoneNumber string?
|
Matches the phoneNumber. |
(Object?)
Sorting options.
Name | Description |
---|---|
options.sortBy string?
|
The User property to sort the results by. This can be any of the above listed filters. |
options.order string?
|
Order in which results are returned. Can be either "asc" or "desc". |
options.max number?
|
The maximum number of results to return. |
options.next string?
|
The pointer for a chunk of results, which may be returned from a previous query. |