@capgo/capacitor-stream-call v0.0.62
@capgo/capacitor-stream-call
A Capacitor plugin that uses the Stream Video SDK to enable video calling functionality in your app.
Installation
npm install @capgo/capacitor-stream-call
npx cap syncConfiguration
iOS Setup
1. API Key Configuration
Add your Stream Video API key to ios/App/App/Info.plist:
<dict>
<key>CAPACITOR_STREAM_VIDEO_APIKEY</key>
<string>your_api_key_here</string>
<!-- other keys -->
</dict>2. Localization (Optional)
To support multiple languages:
Add localization files to your Xcode project:
/App/App/en.lproj/Localizable.strings/App/App/en.lproj/Localizable.stringsdict
Add translations in
Localizable.strings:
"stream.video.call.incoming" = "Incoming call from %@";
"stream.video.call.accept" = "Accept";
"stream.video.call.reject" = "Reject";
"stream.video.call.hangup" = "Hang up";
"stream.video.call.joining" = "Joining...";
"stream.video.call.reconnecting" = "Reconnecting...";- Configure localization in your
AppDelegate.swift:
import StreamVideo
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Appearance.localizationProvider = { key, table in
Bundle.main.localizedString(forKey: key, value: nil, table: table)
}
return true
}
}Android Setup
1. API Key Configuration
Add your Stream Video API key to android/app/src/main/res/values/strings.xml:
<string name="CAPACITOR_STREAM_VIDEO_APIKEY">your_api_key_here</string>2. MainActivity Configuration
Modify your MainActivity.java to handle incoming calls:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Enable activity to show over lock screen
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O_MR1) {
setShowWhenLocked(true);
setTurnScreenOn(true);
} else {
getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | android.view.WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
}3. Application Class Configuration
Create or modify your Application class to initialize the plugin:
import ee.forgr.capacitor.streamcall.StreamCallPlugin;
@Override
public void onCreate() {
super.onCreate();
// Initialize Firebase
com.google.firebase.FirebaseApp.initializeApp(this);
// Pre-initialize StreamCall plugin
try {
StreamCallPlugin.preLoadInit(this, this);
} catch (Exception e) {
Log.e("App", "Failed to pre-initialize StreamVideo Plugin", e);
}
}Note: If you don't have an Application class, you need to create one and reference it in your
AndroidManifest.xmlwithandroid:name=".YourApplicationClass".
4. Localization (Optional)
Add string resources for different languages:
Default (values/strings.xml):
<resources>
<string name="stream_video_call_incoming">Incoming call from %1$s</string>
<string name="stream_video_call_accept">Accept</string>
<string name="stream_video_call_reject">Reject</string>
<string name="stream_video_call_hangup">Hang up</string>
<string name="stream_video_call_joining">Joining...</string>
<string name="stream_video_call_reconnecting">Reconnecting...</string>
</resources>French (values-fr/strings.xml):
<resources>
<string name="stream_video_call_incoming">Appel entrant de %1$s</string>
<string name="stream_video_call_accept">Accepter</string>
<string name="stream_video_call_reject">Refuser</string>
<string name="stream_video_call_hangup">Raccrocher</string>
<string name="stream_video_call_joining">Connexion...</string>
<string name="stream_video_call_reconnecting">Reconnexion...</string>
</resources>Displaying Caller Information
When receiving incoming calls, you can access caller information including name, user ID, and profile image. This information is automatically extracted from the call data and passed through the event system.
Getting Caller Information
The caller information is available in two ways:
1. Through Call Events
The callEvent listener provides caller information for incoming calls:
StreamCall.addListener('callEvent', (event) => {
if (event.state === 'ringing' && event.caller) {
console.log('Incoming call from:', event.caller.name || event.caller.userId);
console.log('Caller image:', event.caller.imageURL);
// Update your UI to show caller information
showIncomingCallUI(event.caller);
}
});2. Through Incoming Call Events (Android lock-screen)
The incomingCall listener also includes caller information:
StreamCall.addListener('incomingCall', (payload) => {
if (payload.caller) {
console.log('Lock-screen call from:', payload.caller.name || payload.caller.userId);
// Update your lock-screen UI
updateLockScreenUI(payload.caller);
}
});Caller Information Structure
interface CallMember {
userId: string; // User ID (always present)
name?: string; // Display name (optional)
imageURL?: string; // Profile image URL (optional)
role?: string; // User role (optional)
}Example Implementation
Here's how to implement a proper incoming call screen with caller information:
export class CallService {
private callerInfo: CallMember | null = null;
constructor() {
this.setupCallListeners();
}
private setupCallListeners() {
StreamCall.addListener('callEvent', (event) => {
if (event.state === 'ringing') {
this.callerInfo = event.caller || null;
this.showIncomingCallScreen();
} else if (event.state === 'joined' || event.state === 'left') {
this.callerInfo = null;
this.hideIncomingCallScreen();
}
});
// Android lock-screen support
if (Capacitor.getPlatform() === 'android') {
StreamCall.addListener('incomingCall', (payload) => {
this.callerInfo = payload.caller || null;
this.showLockScreenIncomingCall();
});
}
}
private showIncomingCallScreen() {
const callerName = this.callerInfo?.name || 'Unknown Caller';
const callerImage = this.callerInfo?.imageURL || 'default-avatar.png';
// Update your UI components
document.getElementById('caller-name').textContent = callerName;
document.getElementById('caller-image').src = callerImage;
document.getElementById('incoming-call-screen').style.display = 'block';
}
}API
login(...)logout()call(...)endCall()setMicrophoneEnabled(...)setCameraEnabled(...)addListener('callEvent', ...)addListener('incomingCall', ...)removeAllListeners()acceptCall()rejectCall()isCameraEnabled()getCallStatus()setSpeaker(...)switchCamera(...)getCallInfo(...)- Interfaces
- Type Aliases
- Enums
login(...)
login(options: LoginOptions) => Promise<SuccessResponse>Login to Stream Video service
| Param | Type | Description |
|---|---|---|
options | LoginOptions | - Login configuration |
Returns: Promise<SuccessResponse>
logout()
logout() => Promise<SuccessResponse>Logout from Stream Video service
Returns: Promise<SuccessResponse>
call(...)
call(options: CallOptions) => Promise<SuccessResponse>Initiate a call to another user
| Param | Type | Description |
|---|---|---|
options | CallOptions | - Call configuration |
Returns: Promise<SuccessResponse>
endCall()
endCall() => Promise<SuccessResponse>End the current call
Returns: Promise<SuccessResponse>
setMicrophoneEnabled(...)
setMicrophoneEnabled(options: { enabled: boolean; }) => Promise<SuccessResponse>Enable or disable microphone
| Param | Type | Description |
|---|---|---|
options | { enabled: boolean; } | - Microphone state |
Returns: Promise<SuccessResponse>
setCameraEnabled(...)
setCameraEnabled(options: { enabled: boolean; }) => Promise<SuccessResponse>Enable or disable camera
| Param | Type | Description |
|---|---|---|
options | { enabled: boolean; } | - Camera state |
Returns: Promise<SuccessResponse>
addListener('callEvent', ...)
addListener(eventName: 'callEvent', listenerFunc: (event: CallEvent) => void) => Promise<{ remove: () => Promise<void>; }>Add listener for call events
| Param | Type | Description |
|---|---|---|
eventName | 'callEvent' | - Name of the event to listen for |
listenerFunc | (event: CallEvent) => void | - Callback function |
Returns: Promise<{ remove: () => Promise<void>; }>
addListener('incomingCall', ...)
addListener(eventName: 'incomingCall', listenerFunc: (event: IncomingCallPayload) => void) => Promise<{ remove: () => Promise<void>; }>Listen for lock-screen incoming call (Android only). Fired when the app is shown by full-screen intent before user interaction.
| Param | Type |
|---|---|
eventName | 'incomingCall' |
listenerFunc | (event: IncomingCallPayload) => void |
Returns: Promise<{ remove: () => Promise<void>; }>
removeAllListeners()
removeAllListeners() => Promise<void>Remove all event listeners
acceptCall()
acceptCall() => Promise<SuccessResponse>Accept an incoming call
Returns: Promise<SuccessResponse>
rejectCall()
rejectCall() => Promise<SuccessResponse>Reject an incoming call
Returns: Promise<SuccessResponse>
isCameraEnabled()
isCameraEnabled() => Promise<CameraEnabledResponse>Check if camera is enabled
Returns: Promise<CameraEnabledResponse>
getCallStatus()
getCallStatus() => Promise<CallEvent>Get the current call status
Returns: Promise<CallEvent>
setSpeaker(...)
setSpeaker(options: { name: string; }) => Promise<SuccessResponse>Set speakerphone on
| Param | Type | Description |
|---|---|---|
options | { name: string; } | - Speakerphone name |
Returns: Promise<SuccessResponse>
switchCamera(...)
switchCamera(options: { camera: 'front' | 'back'; }) => Promise<SuccessResponse>Switch camera
| Param | Type | Description |
|---|---|---|
options | { camera: 'front' | 'back'; } | - Camera to switch to |
Returns: Promise<SuccessResponse>
getCallInfo(...)
getCallInfo(options: { callId: string; }) => Promise<CallEvent>Get detailed information about an active call including caller details
| Param | Type | Description |
|---|---|---|
options | { callId: string; } | - Options containing the call ID |
Returns: Promise<CallEvent>
Interfaces
SuccessResponse
| Prop | Type | Description |
|---|---|---|
success | boolean | Whether the operation was successful |
LoginOptions
| Prop | Type | Description |
|---|---|---|
token | string | Stream Video API token |
userId | string | User ID for the current user |
name | string | Display name for the current user |
imageURL | string | Optional avatar URL for the current user |
apiKey | string | Stream Video API key |
magicDivId | string | ID of the HTML element where the video will be rendered |
pushNotificationsConfig | PushNotificationsConfig |
PushNotificationsConfig
| Prop | Type |
|---|---|
pushProviderName | string |
voipProviderName | string |
CallOptions
| Prop | Type | Description |
|---|---|---|
userIds | string[] | User ID of the person to call |
type | CallType | Type of call, defaults to 'default' |
ring | boolean | Whether to ring the other user, defaults to true |
team | string | Team name to call |
video | boolean | Whether to start the call with video enabled, defaults to false |
CallEvent
| Prop | Type | Description |
|---|---|---|
callId | string | ID of the call |
state | CallState | Current state of the call |
userId | string | User ID of the participant in the call who triggered the event |
reason | string | Reason for the call state change, if applicable |
caller | CallMember | Information about the caller (for incoming calls) |
members | CallMember[] | List of call members |
CallState
CallState is the current state of the call as seen by an SFU.
| Prop | Type | Description |
|---|---|---|
participants | Participant[] | participants is the list of participants in the call. In large calls, the list could be truncated in which case, the list of participants contains fewer participants than the counts returned in participant_count. Anonymous participants are NOT included in the list. |
startedAt | Timestamp | started_at is the time the call session actually started. |
participantCount | ParticipantCount | participant_count contains the summary of the counts. |
pins | Pin[] | the list of pins in the call. Pins are ordered in descending order (most important first). |
Participant
those who are online in the call
| Prop | Type | Description |
|---|---|---|
userId | string | |
sessionId | string | |
publishedTracks | TrackType[] | map of track id to track type |
joinedAt | Timestamp | |
trackLookupPrefix | string | |
connectionQuality | ConnectionQuality | |
isSpeaking | boolean | |
isDominantSpeaker | boolean | |
audioLevel | number | |
name | string | |
image | string | |
custom | Struct | |
roles | string[] |
Timestamp
A Timestamp represents a point in time independent of any time zone or local calendar, encoded as a count of seconds and fractions of seconds at nanosecond resolution. The count is relative to an epoch at UTC midnight on January 1, 1970, in the proleptic Gregorian calendar which extends the Gregorian calendar backwards to year one.
All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap second table is needed for interpretation, using a 24-hour linear smear.
The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By restricting to that range, we ensure that we can convert to and from RFC 3339 date strings.
Examples
Example 1: Compute Timestamp from POSIX time().
<a href="#timestamp">Timestamp</a> timestamp;
timestamp.set_seconds(time(NULL));
timestamp.set_nanos(0);Example 2: Compute Timestamp from POSIX gettimeofday().
struct timeval tv;
gettimeofday(&tv, NULL);
<a href="#timestamp">Timestamp</a> timestamp;
timestamp.set_seconds(tv.tv_sec);
timestamp.set_nanos(tv.tv_usec * 1000);Example 3: Compute Timestamp from Win32 GetSystemTimeAsFileTime().
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
// A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
// is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
<a href="#timestamp">Timestamp</a> timestamp;
timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));Example 4: Compute Timestamp from Java System.currentTimeMillis().
long millis = System.currentTimeMillis();
<a href="#timestamp">Timestamp</a> timestamp = <a href="#timestamp">Timestamp</a>.newBuilder().setSeconds(millis / 1000)
.setNanos((int) ((millis % 1000) * 1000000)).build();Example 5: Compute Timestamp from Java Instant.now().
Instant now = Instant.now();
<a href="#timestamp">Timestamp</a> timestamp =
<a href="#timestamp">Timestamp</a>.newBuilder().setSeconds(now.getEpochSecond())
.setNanos(now.getNano()).build();Example 6: Compute Timestamp from current time in Python.
timestamp = <a href="#timestamp">Timestamp</a>()
timestamp.GetCurrentTime()JSON Mapping
In JSON format, the Timestamp type is encoded as a string in the RFC 3339 format. That is, the format is "{year}-{month}-{day}T{hour}:{min}:{sec}.{frac_sec}Z" where {year} is always expressed using four digits while {month}, {day}, {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone is required. A proto3 JSON serializer should always use UTC (as indicated by "Z") when printing the Timestamp type and a proto3 JSON parser should be able to accept both UTC and other timezones (as indicated by an offset).
For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past 01:30 UTC on January 15, 2017.
In JavaScript, one can convert a Date object to this format using the
standard
toISOString()
method. In Python, a standard datetime.datetime object can be converted
to this format using
strftime with
the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
the Joda Time's ISODateTimeFormat.dateTime() to obtain a formatter capable of generating timestamps in this format.
| Prop | Type | Description |
|---|---|---|
seconds | string | Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive. |
nanos | number | Non-negative fractions of a second at nanosecond resolution. Negative second values with fractions must still have non-negative nanos values that count forward in time. Must be from 0 to 999,999,999 inclusive. |
Struct
Struct represents a structured data value, consisting of fields
which map to dynamically typed values. In some languages, Struct
might be supported by a native representation. For example, in
scripting languages like JS a struct is represented as an
object. The details of that representation are described together
with the proto support for the language.
The JSON representation for Struct is JSON object.
| Prop | Type | Description |
|---|---|---|
fields | { key: string: Value; } | Unordered map of dynamically typed values. |
Value
Value represents a dynamically typed value which can be either
null, a number, a string, a boolean, a recursive struct value, or a
list of values. A producer of value is expected to set one of these
variants. Absence of any variant indicates an error.
The JSON representation for Value is JSON value.
| Prop | Type |
|---|---|
kind | { oneofKind: 'nullValue'; nullValue: NullValue; } | { oneofKind: 'numberValue'; numberValue: number; } | { oneofKind: 'stringValue'; stringValue: string; } | { oneofKind: 'boolValue'; boolValue: boolean; } | { oneofKind: 'structValue'; structValue: Struct; } | { oneofKind: 'listValue'; listValue: ListValue; } | { oneofKind: undefined; } |
ListValue
ListValue is a wrapper around a repeated field of values.
The JSON representation for ListValue is JSON array.
| Prop | Type | Description |
|---|---|---|
values | Value[] | Repeated field of dynamically typed values. |
ParticipantCount
| Prop | Type | Description |
|---|---|---|
total | number | Total number of participants in the call including the anonymous participants. |
anonymous | number | Total number of anonymous participants in the call. |
Pin
| Prop | Type | Description |
|---|---|---|
userId | string | the user to pin |
sessionId | string | the user sesion_id to pin, if not provided, applies to all sessions |
CallMember
| Prop | Type | Description |
|---|---|---|
userId | string | User ID of the member |
name | string | Display name of the user |
imageURL | string | Profile image URL of the user |
role | string | Role of the user in the call |
IncomingCallPayload
| Prop | Type | Description |
|---|---|---|
cid | string | Full call CID (e.g. default:123) |
type | 'incoming' | Event type (currently always "incoming") |
caller | CallMember | Information about the caller |
CameraEnabledResponse
| Prop | Type |
|---|---|
enabled | boolean |
Type Aliases
CallType
'default' | 'audio_room' | 'livestream' | 'development'
CallState
'idle' | 'ringing' | 'joining' | 'reconnecting' | 'joined' | 'leaving' | 'left' | 'created' | 'session_started' | 'rejected' | 'missed' | 'accepted' | 'ended' | 'unknown'
Enums
TrackType
| Members | Value |
|---|---|
UNSPECIFIED | 0 |
AUDIO | 1 |
VIDEO | 2 |
SCREEN_SHARE | 3 |
SCREEN_SHARE_AUDIO | 4 |
ConnectionQuality
| Members | Value |
|---|---|
UNSPECIFIED | 0 |
POOR | 1 |
GOOD | 2 |
EXCELLENT | 3 |
NullValue
| Members | Value | Description |
|---|---|---|
NULL_VALUE | 0 | Null value. |
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
7 months ago
7 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago