diff --git a/calls/android/authentication.mdx b/calls/android/authentication.mdx index e2d53d89..8d3027ff 100644 --- a/calls/android/authentication.mdx +++ b/calls/android/authentication.mdx @@ -44,24 +44,24 @@ if (loggedInUser != null) { The `getLoggedInUser()` method returns a `CallUser` object if a user is logged in, or `null` if no session exists. -## Login with UID and API Key +## Login with UID and Auth Key This method is suitable for development and testing. For production apps, use [Auth Token login](#login-with-auth-token) instead. **Security Notice** -Using the API Key directly in client code is not recommended for production. Use Auth Token authentication for enhanced security. +Using the Auth Key directly in client code is not recommended for production. Use Auth Token authentication for enhanced security. ```kotlin val uid = "cometchat-uid-1" // Replace with your user's UID -val apiKey = "API_KEY" // Replace with your API Key +val authKey = "AUTH_KEY" // Replace with your Auth Key if (CometChatCalls.getLoggedInUser() == null) { - CometChatCalls.login(uid, apiKey, object : CometChatCalls.CallbackListener() { + CometChatCalls.login(uid, authKey, object : CometChatCalls.CallbackListener() { override fun onSuccess(user: CallUser) { Log.d(TAG, "Login successful: ${user.uid}") } @@ -78,10 +78,10 @@ if (CometChatCalls.getLoggedInUser() == null) { ```java String uid = "cometchat-uid-1"; // Replace with your user's UID -String apiKey = "API_KEY"; // Replace with your API Key +String authKey = "AUTH_KEY"; // Replace with your Auth Key if (CometChatCalls.getLoggedInUser() == null) { - CometChatCalls.login(uid, apiKey, new CometChatCalls.CallbackListener() { + CometChatCalls.login(uid, authKey, new CometChatCalls.CallbackListener() { @Override public void onSuccess(CallUser user) { Log.d(TAG, "Login successful: " + user.getUid()); @@ -102,12 +102,12 @@ if (CometChatCalls.getLoggedInUser() == null) { | Parameter | Type | Description | |-----------|------|-------------| | `uid` | String | The unique identifier of the user to login | -| `apiKey` | String | Your CometChat API Key | +| `authKey` | String | Your CometChat Auth Key | | `listener` | CallbackListener | Callback for success/error handling | ## Login with Auth Token -This is the recommended authentication method for production applications. The Auth Token is generated server-side, keeping your API Key secure. +This is the recommended authentication method for production applications. The Auth Token is generated server-side, keeping your Auth Key secure. ### Auth Token Flow @@ -210,6 +210,6 @@ Common authentication errors: |------------|-------------| | `ERROR_INVALID_UID` | The provided UID is empty or invalid | | `ERROR_UID_WITH_SPACE` | The UID contains spaces (not allowed) | -| `ERROR_API_KEY_NOT_FOUND` | The API Key is missing or invalid | +| `ERROR_API_KEY_NOT_FOUND` | The Auth Key is missing or invalid | | `ERROR_BLANK_AUTHTOKEN` | The Auth Token is empty | | `ERROR_LOGIN_IN_PROGRESS` | A login operation is already in progress | diff --git a/calls/android/overview.mdx b/calls/android/overview.mdx index 395688a8..b785e3ce 100644 --- a/calls/android/overview.mdx +++ b/calls/android/overview.mdx @@ -22,12 +22,11 @@ Use this Calls SDK directly only if you need custom call UI or advanced control. Before integrating the Calls SDK, ensure you have: -1. **CometChat Account**: [Sign up](https://app.cometchat.com/signup) and create an app to get your App ID, Region, and API Key +1. **CometChat Account**: [Sign up](https://app.cometchat.com/signup) and create an app to get your App ID, Region, and Auth Key 2. **CometChat Users**: Users must exist in CometChat to use calling features. For testing, create users via the [Dashboard](https://app.cometchat.com) or [REST API](/rest-api/chat-apis/users/create-user). Authentication is handled by the Calls SDK - see [Authentication](/calls/android/authentication) 3. **Android Requirements**: - Minimum SDK: API Level 24 (Android 7.0) - AndroidX compatibility -4. **Permissions**: Camera and microphone permissions for video/audio calls ## Call Flow diff --git a/calls/ios/authentication.mdx b/calls/ios/authentication.mdx index 058c8032..8916257c 100644 --- a/calls/ios/authentication.mdx +++ b/calls/ios/authentication.mdx @@ -42,24 +42,24 @@ if (loggedInUser != nil) { The `getLoggedInUser()` method returns a `CallsUser` object if a user is logged in, or `nil` if no session exists. -## Login with UID and API Key +## Login with UID and Auth Key This method is suitable for development and testing. For production apps, use [Auth Token login](#login-with-auth-token) instead. **Security Notice** -Using the API Key directly in client code is not recommended for production. Use Auth Token authentication for enhanced security. +Using the Auth Key directly in client code is not recommended for production. Use Auth Token authentication for enhanced security. ```swift let uid = "cometchat-uid-1" // Replace with your user's UID -let apiKey = "API_KEY" // Replace with your API Key +let authKey = "AUTH_KEY" // Replace with your Auth Key if CometChatCalls.getLoggedInUser() == nil { - CometChatCalls.login(UID: uid, apiKey: apiKey, onSuccess: { user in + CometChatCalls.login(UID: uid, authKey: authKey, onSuccess: { user in print("Login successful: \(user.uid ?? "")") }, onError: { error in print("Login failed: \(error.errorDescription)") @@ -72,11 +72,11 @@ if CometChatCalls.getLoggedInUser() == nil { ```objectivec NSString *uid = @"cometchat-uid-1"; // Replace with your user's UID -NSString *apiKey = @"API_KEY"; // Replace with your API Key +NSString *authKey = @"AUTH_KEY"; // Replace with your Auth Key if ([CometChatCalls getLoggedInUser] == nil) { [CometChatCalls loginWithUID:uid - apiKey:apiKey + authKey:authKey onSuccess:^(CallsUser * user) { NSLog(@"Login successful: %@", user.uid); } onError:^(CometChatCallException error) { @@ -92,13 +92,13 @@ if ([CometChatCalls getLoggedInUser] == nil) { | Parameter | Type | Description | |-----------|------|-------------| | `UID` | String | The unique identifier of the user to login | -| `apiKey` | String | Your CometChat API Key | +| `authKey` | String | Your CometChat Auth Key | | `onSuccess` | Closure | Closure called with `CallsUser` on success | | `onError` | Closure | Closure called with error on failure | ## Login with Auth Token -This is the recommended authentication method for production applications. The Auth Token is generated server-side, keeping your API Key secure. +This is the recommended authentication method for production applications. The Auth Token is generated server-side, keeping your Auth Key secure. ### Auth Token Flow @@ -183,6 +183,6 @@ Common authentication errors: |------------|-------------| | `ERROR_INVALID_UID` | The provided UID is empty or invalid | | `ERROR_UID_WITH_SPACE` | The UID contains spaces (not allowed) | -| `ERROR_API_KEY_NOT_FOUND` | The API Key is missing or invalid | +| `ERROR_API_KEY_NOT_FOUND` | The Auth Key is missing or invalid | | `ERROR_BLANK_AUTHTOKEN` | The Auth Token is empty | | `ERROR_AUTHTOKEN_WITH_SPACE` | The Auth Token contains spaces | diff --git a/calls/ios/overview.mdx b/calls/ios/overview.mdx index 9436784c..62e634e7 100644 --- a/calls/ios/overview.mdx +++ b/calls/ios/overview.mdx @@ -22,13 +22,12 @@ Use this Calls SDK directly only if you need custom call UI or advanced control. Before integrating the Calls SDK, ensure you have: -1. **CometChat Account**: [Sign up](https://app.cometchat.com/signup) and create an app to get your App ID, Region, and API Key +1. **CometChat Account**: [Sign up](https://app.cometchat.com/signup) and create an app to get your App ID, Region, and Auth Key 2. **CometChat Users**: Users must exist in CometChat to use calling features. For testing, create users via the [Dashboard](https://app.cometchat.com) or [REST API](/rest-api/chat-apis/users/create-user). Authentication is handled by the Calls SDK - see [Authentication](/calls/ios/authentication) 3. **iOS Requirements**: - Minimum iOS version: 16.0 - Xcode 14.0 or later - Swift 5.0 or later -4. **Permissions**: Camera and microphone permissions for video/audio calls ## Call Flow diff --git a/calls/javascript/actions.mdx b/calls/javascript/actions.mdx index 116f9523..68e64779 100644 --- a/calls/javascript/actions.mdx +++ b/calls/javascript/actions.mdx @@ -17,7 +17,7 @@ CometChatCalls.muteAudio(); ### Unmute Audio -Unmutes your local microphone, resuming audio transmission. +Unmutes your local microphone, resuming audio transmission to other participants. ```javascript CometChatCalls.unMuteAudio(); @@ -27,7 +27,7 @@ CometChatCalls.unMuteAudio(); ### Pause Video -Turns off your local camera, stopping video transmission. Other participants see your avatar. +Turns off your local camera, stopping video transmission to other participants. ```javascript CometChatCalls.pauseVideo(); @@ -35,7 +35,7 @@ CometChatCalls.pauseVideo(); ### Resume Video -Turns on your local camera, resuming video transmission. +Turns on your local camera, resuming video transmission to other participants. ```javascript CometChatCalls.resumeVideo(); @@ -43,7 +43,7 @@ CometChatCalls.resumeVideo(); ### Switch Camera -Toggles between front and back cameras (on supported devices). +Toggles between front and back cameras (on supported mobile devices). ```javascript CometChatCalls.switchCamera(); @@ -61,7 +61,7 @@ CometChatCalls.startScreenSharing(); ### Stop Screen Sharing -Stops the current screen share. +Stops sharing your screen with other participants. ```javascript CometChatCalls.stopScreenSharing(); @@ -71,7 +71,7 @@ CometChatCalls.stopScreenSharing(); ### Start Recording -Begins server-side recording of the call. All participants are notified. +Begins server-side recording of the call. ```javascript CometChatCalls.startRecording(); @@ -83,7 +83,7 @@ Recording requires the feature to be enabled for your CometChat app. ### Stop Recording -Stops the current recording. The recording is saved and accessible via the dashboard. +Stops the current ongoing recording. The recording is saved and accessible via the dashboard. ```javascript CometChatCalls.stopRecording(); @@ -93,7 +93,7 @@ CometChatCalls.stopRecording(); ### Mute Participant -Mutes a specific participant's audio. This is a moderator action. +Mutes a specific participant's audio. ```javascript CometChatCalls.muteParticipant(participantId); @@ -105,7 +105,7 @@ CometChatCalls.muteParticipant(participantId); ### Pause Participant Video -Pauses a specific participant's video. This is a moderator action. +Pauses a specific participant's video. ```javascript CometChatCalls.pauseParticipantVideo(participantId); @@ -117,7 +117,7 @@ CometChatCalls.pauseParticipantVideo(participantId); ### Pin Participant -Pins a participant to keep them prominently displayed regardless of who is speaking. +Pins a participant to the main view. ```javascript CometChatCalls.pinParticipant(participantId, type); @@ -126,11 +126,11 @@ CometChatCalls.pinParticipant(participantId, type); | Parameter | Type | Description | |-----------|------|-------------| | `participantId` | String | The participant's unique identifier | -| `type` | String | The participant type | +| `type` | String | The type of the participant (e.g., `"human"` or `"screen-share"`) | ### Unpin Participant -Removes the pin, returning to automatic speaker highlighting. +Unpins the currently pinned participant, returning to the default layout behavior. ```javascript CometChatCalls.unpinParticipant(); @@ -151,8 +151,8 @@ CometChatCalls.setLayout("SPOTLIGHT"); | Value | Description | |-------|-------------| | `TILE` | Grid layout with equally-sized tiles | -| `SIDEBAR` | Main speaker with participants in a sidebar | -| `SPOTLIGHT` | Large view for active speaker, small tiles for others | +| `SIDEBAR` | Main speaker/screen in large view, other participants in a sidebar | +| `SPOTLIGHT` | Large view for active speaker, small tiles for other | ## Raise Hand @@ -342,21 +342,3 @@ Sets the video input device by device ID. CometChatCalls.setVideoInputDevice(deviceId); ``` -## Picture-in-Picture - -### Enable Picture-in-Picture Layout - -Enables Picture-in-Picture mode for the call. - -```javascript -CometChatCalls.enablePictureInPictureLayout(); -``` - -### Disable Picture-in-Picture Layout - -Disables Picture-in-Picture mode. - -```javascript -CometChatCalls.disablePictureInPictureLayout(); -``` - diff --git a/calls/javascript/angular-integration.mdx b/calls/javascript/angular-integration.mdx index 28b83405..e549276a 100644 --- a/calls/javascript/angular-integration.mdx +++ b/calls/javascript/angular-integration.mdx @@ -7,11 +7,8 @@ This guide walks you through integrating the CometChat Calls SDK into an Angular ## Prerequisites -Before you begin, ensure you have: -- A CometChat account with an app created ([Sign up](https://app.cometchat.com/signup)) -- Your App ID, Region, and API Key from the CometChat Dashboard -- An Angular 14+ project -- Node.js 16+ installed +Before you begin, make sure you've completed the [prerequisites](/calls/javascript/overview#prerequisites) from the Overview page. You'll also need: +- An Angular project ## Step 1: Install the SDK @@ -43,7 +40,7 @@ interface User { export class CometChatCallsService { private readonly APP_ID = "YOUR_APP_ID"; // Replace with your App ID private readonly REGION = "YOUR_REGION"; // Replace with your Region - private readonly API_KEY = "YOUR_API_KEY"; // Replace with your API Key + private readonly AUTH_KEY = "YOUR_AUTH_KEY"; // Replace with your Auth Key // Observable state private isReadySubject = new BehaviorSubject(false); @@ -77,7 +74,7 @@ export class CometChatCallsService { // Step 3: Login if not already logged in if (!loggedInUser) { - loggedInUser = await CometChatCalls.login(uid, this.API_KEY); + loggedInUser = await CometChatCalls.login(uid, this.AUTH_KEY); } this.userSubject.next(loggedInUser as User); diff --git a/calls/javascript/authentication.mdx b/calls/javascript/authentication.mdx index 71dc99b3..f77291ab 100644 --- a/calls/javascript/authentication.mdx +++ b/calls/javascript/authentication.mdx @@ -28,23 +28,23 @@ if (loggedInUser) { The `getLoggedInUser()` method returns a user object if a user is logged in, or `null` if no session exists. -## Login with UID and API Key +## Login with UID and Auth Key This method is suitable for development and testing. For production apps, use [Auth Token login](#login-with-auth-token) instead. **Security Notice** -Using the API Key directly in client code is not recommended for production. Use Auth Token authentication for enhanced security. +Using the Auth Key directly in client code is not recommended for production. Use Auth Token authentication for enhanced security. ```javascript const uid = "cometchat-uid-1"; // Replace with your user's UID -const apiKey = "API_KEY"; // Replace with your API Key +const authKey = "AUTH_KEY"; // Replace with your Auth Key if (!CometChatCalls.getLoggedInUser()) { try { - const user = await CometChatCalls.login(uid, apiKey); + const user = await CometChatCalls.login(uid, authKey); console.log("Login successful:", user.uid); } catch (error) { console.error("Login failed:", error.errorDescription); @@ -57,11 +57,11 @@ if (!CometChatCalls.getLoggedInUser()) { | Parameter | Type | Description | |-----------|------|-------------| | `uid` | String | The unique identifier of the user to login | -| `apiKey` | String | Your CometChat API Key | +| `authKey` | String | Your CometChat Auth Key | ## Login with Auth Token -This is the recommended authentication method for production applications. The Auth Token is generated server-side, keeping your API Key secure. +This is the recommended authentication method for production applications. The Auth Token is generated server-side, keeping your Auth Key secure. ### Auth Token Flow @@ -144,7 +144,7 @@ Common authentication errors: |------------|-------------| | `ERROR_INVALID_UID` | The provided UID is empty or invalid | | `ERROR_UID_WITH_SPACE` | The UID contains spaces (not allowed) | -| `ERROR_API_KEY_NOT_FOUND` | The API Key is missing or invalid | +| `ERROR_API_KEY_NOT_FOUND` | The Auth Key is missing or invalid | | `ERROR_BLANK_AUTHTOKEN` | The Auth Token is empty | | `ERROR_AUTHTOKEN_WITH_SPACE` | The Auth Token contains spaces (not allowed) | | `ERROR_LOGIN_IN_PROGRESS` | A login operation is already in progress | diff --git a/calls/javascript/call-layouts.mdx b/calls/javascript/call-layouts.mdx index aa9b6c8a..cd2c376a 100644 --- a/calls/javascript/call-layouts.mdx +++ b/calls/javascript/call-layouts.mdx @@ -17,13 +17,13 @@ The CometChat Calls SDK provides three layout modes to display participants duri Configure the initial layout when joining a session using the `layout` property in session settings: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { layout: "TILE", // or "SIDEBAR" or "SPOTLIGHT" // ... other settings }; -await CometChatCalls.joinSession(callToken, callSettings, container); +await CometChatCalls.joinSession(callToken, sessionSettings, container); ``` ## Change Layout During Call @@ -55,8 +55,8 @@ CometChatCalls.addEventListener("onCallLayoutChanged", (layout) => { To prevent users from changing the layout, hide the layout change button: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { hideChangeLayoutButton: true, // ... other settings }; diff --git a/calls/javascript/custom-control-panel.mdx b/calls/javascript/custom-control-panel.mdx index 0bdae429..7b0aeb0b 100644 --- a/calls/javascript/custom-control-panel.mdx +++ b/calls/javascript/custom-control-panel.mdx @@ -9,13 +9,13 @@ Build a custom control panel by hiding the default UI and using the SDK's action Hide the built-in control panel when joining a session: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { hideControlPanel: true, // ... other settings }; -await CometChatCalls.joinSession(callToken, callSettings, container); +await CometChatCalls.joinSession(callToken, sessionSettings, container); ``` ## Build Custom Controls @@ -113,8 +113,8 @@ CometChatCalls.addEventListener("onScreenShareStopped", () => { Instead of hiding the entire control panel, you can hide specific buttons: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { hideControlPanel: false, hideLeaveSessionButton: false, hideToggleAudioButton: false, diff --git a/calls/javascript/idle-timeout.mdx b/calls/javascript/idle-timeout.mdx index b6216142..6336bf89 100644 --- a/calls/javascript/idle-timeout.mdx +++ b/calls/javascript/idle-timeout.mdx @@ -15,14 +15,14 @@ The idle timeout feature automatically ends a call session when you're the only Set the timeout periods when joining a session: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { idleTimeoutPeriodBeforePrompt: 60000, // 60 seconds before showing prompt idleTimeoutPeriodAfterPrompt: 120000, // 120 seconds after prompt before ending // ... other settings }; -await CometChatCalls.joinSession(callToken, callSettings, container); +await CometChatCalls.joinSession(callToken, sessionSettings, container); ``` | Property | Type | Default | Description | @@ -45,8 +45,8 @@ CometChatCalls.addEventListener("onSessionTimedOut", () => { To effectively disable the idle timeout, set very long timeout periods: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { idleTimeoutPeriodBeforePrompt: 86400000, // 24 hours idleTimeoutPeriodAfterPrompt: 86400000, // 24 hours // ... other settings diff --git a/calls/javascript/in-call-chat.mdx b/calls/javascript/in-call-chat.mdx index 62e06d18..96890c12 100644 --- a/calls/javascript/in-call-chat.mdx +++ b/calls/javascript/in-call-chat.mdx @@ -11,8 +11,8 @@ Enable text messaging during calls by integrating the in-call chat feature. The By default, the chat button is hidden. To show it: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { hideChatButton: false, // ... other settings }; diff --git a/calls/javascript/ionic-integration.mdx b/calls/javascript/ionic-integration.mdx index 77de909c..cf1a6e2f 100644 --- a/calls/javascript/ionic-integration.mdx +++ b/calls/javascript/ionic-integration.mdx @@ -3,1327 +3,38 @@ title: "Ionic Integration" sidebarTitle: "Ionic" --- -This guide walks you through integrating the CometChat Calls SDK into an Ionic application. By the end, you'll have a working video call implementation with proper authentication and lifecycle handling. This guide covers Ionic with Angular, React, and Vue. +The CometChat Calls SDK integration for Ionic works the same as the underlying framework you're using. Follow the relevant integration guide to get started: - -For native mobile features like CallKit, VoIP push notifications, and background handling, consider using the native [iOS](/calls/ios/overview) or [Android](/calls/android/overview) SDKs. - - -## Prerequisites - -Before you begin, ensure you have: -- A CometChat account with an app created ([Sign up](https://app.cometchat.com/signup)) -- Your App ID, Region, and API Key from the CometChat Dashboard -- An Ionic project (Angular, React, or Vue) -- Node.js 16+ installed -- Ionic CLI installed (`npm install -g @ionic/cli`) - -## Step 1: Install the SDK - -Install the CometChat Calls SDK package: - -```bash -npm install @cometchat/calls-sdk-javascript -``` - -## Ionic Angular - -### Step 2: Create the Service - -Create a service that handles SDK initialization, authentication, and call operations. The service waits for the Ionic platform to be ready before initializing: - -```typescript -// src/app/services/cometchat-calls.service.ts -import { Injectable } from "@angular/core"; -import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; -import { Platform } from "@ionic/angular"; -import { BehaviorSubject } from "rxjs"; - -interface User { - uid: string; - name: string; - avatar?: string; -} - -@Injectable({ - providedIn: "root", -}) -export class CometChatCallsService { - private initialized = false; - private _isReady$ = new BehaviorSubject(false); - private _user$ = new BehaviorSubject(null); - private _error$ = new BehaviorSubject(null); - - isReady$ = this._isReady$.asObservable(); - user$ = this._user$.asObservable(); - error$ = this._error$.asObservable(); - - // Replace with your CometChat credentials - private readonly APP_ID = "YOUR_APP_ID"; - private readonly REGION = "YOUR_REGION"; - private readonly API_KEY = "YOUR_API_KEY"; - - constructor(private platform: Platform) {} - - async initAndLogin(uid: string): Promise { - try { - // Wait for Ionic platform to be ready - await this.platform.ready(); - - if (this.initialized) { - return true; - } - - // Step 1: Initialize the SDK - const initResult = await CometChatCalls.init({ - appId: this.APP_ID, - region: this.REGION, - }); - - if (!initResult.success) { - throw new Error("SDK initialization failed"); - } - - // Step 2: Check if already logged in - let loggedInUser = CometChatCalls.getLoggedInUser(); - - // Step 3: Login if not already logged in - if (!loggedInUser) { - loggedInUser = await CometChatCalls.login(uid, this.API_KEY); - } - - this.initialized = true; - this._user$.next(loggedInUser); - this._isReady$.next(true); - return true; - } catch (err: any) { - console.error("CometChat Calls setup failed:", err); - this._error$.next(err.message || "Setup failed"); - return false; - } - } - - getLoggedInUser(): User | null { - return this._user$.value; - } - - async generateToken(sessionId: string) { - return CometChatCalls.generateToken(sessionId); - } - - async joinSession(token: string, settings: any, container: HTMLElement) { - return CometChatCalls.joinSession(token, settings, container); - } +- [React Integration](/calls/javascript/react-integration) — for Ionic React +- [Angular Integration](/calls/javascript/angular-integration) — for Ionic Angular +- [Vue Integration](/calls/javascript/vue-integration) — for Ionic Vue - leaveSession() { - CometChatCalls.leaveSession(); - } +## Native Permissions - muteAudio() { - CometChatCalls.muteAudio(); - } +When building for native platforms using Capacitor or Cordova, you need to add camera and microphone permissions for the call functionality to work. - unMuteAudio() { - CometChatCalls.unMuteAudio(); - } +### Android - pauseVideo() { - CometChatCalls.pauseVideo(); - } +Add the following permissions to your `android/app/src/main/AndroidManifest.xml`: - resumeVideo() { - CometChatCalls.resumeVideo(); - } - - addEventListener(event: string, callback: Function) { - return CometChatCalls.addEventListener(event as any, callback as any); - } -} +```xml + + + ``` +### iOS -### Step 3: Initialize in App Component - -Initialize the SDK and login when the app starts: - -```typescript -// src/app/app.component.ts -import { Component, OnInit } from "@angular/core"; -import { CometChatCallsService } from "./services/cometchat-calls.service"; - -@Component({ - selector: "app-root", - templateUrl: "app.component.html", -}) -export class AppComponent implements OnInit { - constructor(private callsService: CometChatCallsService) {} +Add the following keys to your `ios/App/App/Info.plist`: - ngOnInit() { - // In a real app, get this from your authentication system - const currentUserId = "cometchat-uid-1"; - this.callsService.initAndLogin(currentUserId); - } -} +```xml +NSCameraUsageDescription +This app requires access to the camera to make video calls. +NSMicrophoneUsageDescription +This app requires access to the microphone to make audio and video calls. ``` -### Step 4: Create the Call Page - -Create a call page component that handles joining sessions, media controls, and cleanup: - -```typescript -// src/app/pages/call/call.page.ts -import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from "@angular/core"; -import { ActivatedRoute } from "@angular/router"; -import { NavController } from "@ionic/angular"; -import { CometChatCallsService } from "../../services/cometchat-calls.service"; -import { Subscription } from "rxjs"; - -@Component({ - selector: "app-call", - templateUrl: "./call.page.html", - styleUrls: ["./call.page.scss"], -}) -export class CallPage implements OnInit, OnDestroy { - @ViewChild("callContainer", { static: true }) callContainer!: ElementRef; - - sessionId: string = ""; - isReady = false; - isJoined = false; - isJoining = false; - isMuted = false; - isVideoOff = false; - error: string | null = null; - - private unsubscribers: Function[] = []; - private subscriptions: Subscription[] = []; - - constructor( - private route: ActivatedRoute, - private navCtrl: NavController, - private callsService: CometChatCallsService - ) {} - - ngOnInit() { - this.sessionId = this.route.snapshot.paramMap.get("sessionId") || ""; - - // Subscribe to ready state - this.subscriptions.push( - this.callsService.isReady$.subscribe((ready) => { - this.isReady = ready; - if (ready && this.sessionId) { - this.joinCall(); - } - }), - this.callsService.error$.subscribe((err) => { - this.error = err; - }) - ); - } - - ngOnDestroy() { - this.cleanup(); - this.subscriptions.forEach((sub) => sub.unsubscribe()); - } - - private async joinCall() { - if (!this.callContainer?.nativeElement) return; - - this.isJoining = true; - this.error = null; - - try { - // Register event listeners before joining - this.unsubscribers = [ - this.callsService.addEventListener("onSessionJoined", () => { - this.isJoined = true; - this.isJoining = false; - }), - this.callsService.addEventListener("onSessionLeft", () => { - this.isJoined = false; - this.navCtrl.back(); - }), - this.callsService.addEventListener("onAudioMuted", () => { - this.isMuted = true; - }), - this.callsService.addEventListener("onAudioUnMuted", () => { - this.isMuted = false; - }), - this.callsService.addEventListener("onVideoPaused", () => { - this.isVideoOff = true; - }), - this.callsService.addEventListener("onVideoResumed", () => { - this.isVideoOff = false; - }), - ]; - - // Generate a call token for this session - const tokenResult = await this.callsService.generateToken(this.sessionId); - - // Join the call session - await this.callsService.joinSession( - tokenResult.token, - { - sessionType: "VIDEO", - layout: "TILE", - startAudioMuted: false, - startVideoPaused: false, - }, - this.callContainer.nativeElement - ); - } catch (err: any) { - console.error("Failed to join call:", err); - this.error = err.message || "Failed to join call"; - this.isJoining = false; - } - } - - toggleAudio() { - this.isMuted ? this.callsService.unMuteAudio() : this.callsService.muteAudio(); - } - - toggleVideo() { - this.isVideoOff ? this.callsService.resumeVideo() : this.callsService.pauseVideo(); - } - - leaveCall() { - this.callsService.leaveSession(); - } - - private cleanup() { - this.unsubscribers.forEach((unsub) => unsub()); - this.unsubscribers = []; - this.callsService.leaveSession(); - } -} -``` - - -### Step 5: Create the Call Page Template - -Create the HTML template for the call page with video container and controls: - -```html - - - -
- -

Initializing...

-
- - -
- -

{{ error }}

- Retry -
- - -
- - -
- -

Joining call...

-
- - -
- - - - - - - - - - - -
-
-``` - -```scss -/* src/app/pages/call/call.page.scss */ -.call-container { - width: 100%; - height: calc(100% - 80px); - background-color: #1a1a1a; -} - -.call-controls { - display: flex; - justify-content: center; - gap: 16px; - padding: 16px; - background-color: #f5f5f5; -} - -.loading-container, -.error-container, -.joining-overlay { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - height: 100%; - gap: 16px; -} - -.joining-overlay { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - background-color: rgba(0, 0, 0, 0.7); - color: white; - z-index: 100; -} -``` - -### Step 6: Create the Home Page - -Create a home page where users can enter a session ID and join a call: - -```typescript -// src/app/pages/home/home.page.ts -import { Component } from "@angular/core"; -import { Router } from "@angular/router"; -import { CometChatCallsService } from "../../services/cometchat-calls.service"; - -@Component({ - selector: "app-home", - templateUrl: "./home.page.html", -}) -export class HomePage { - sessionId = ""; - isReady$ = this.callsService.isReady$; - user$ = this.callsService.user$; - error$ = this.callsService.error$; - - constructor( - private router: Router, - private callsService: CometChatCallsService - ) {} - - joinCall() { - if (this.sessionId) { - this.router.navigate(["/call", this.sessionId]); - } - } -} -``` - -```html - - - - CometChat Calls - - - - -
- {{ error }} -
- -
- -

Loading...

-
- -
-

- Logged in as: {{ user.name || user.uid }} -

- - - Session ID - - - - - Join Call - -
-
-``` - - -## Ionic React - -### Step 2: Create the Provider - -Create a context provider that handles SDK initialization and authentication: - -```tsx -// src/providers/CometChatCallsProvider.tsx -import { createContext, useContext, useEffect, useState, ReactNode } from "react"; -import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; -import { isPlatform } from "@ionic/react"; - -interface User { - uid: string; - name: string; - avatar?: string; -} - -interface CometChatCallsContextType { - isReady: boolean; - user: User | null; - error: string | null; -} - -const CometChatCallsContext = createContext({ - isReady: false, - user: null, - error: null, -}); - -// Replace with your CometChat credentials -const APP_ID = "YOUR_APP_ID"; -const REGION = "YOUR_REGION"; -const API_KEY = "YOUR_API_KEY"; - -interface ProviderProps { - children: ReactNode; - uid: string; -} - -export function CometChatCallsProvider({ children, uid }: ProviderProps) { - const [isReady, setIsReady] = useState(false); - const [user, setUser] = useState(null); - const [error, setError] = useState(null); - - useEffect(() => { - async function initAndLogin() { - try { - // Step 1: Initialize the SDK - const initResult = await CometChatCalls.init({ - appId: APP_ID, - region: REGION, - }); - - if (!initResult.success) { - throw new Error("SDK initialization failed"); - } - - // Step 2: Check if already logged in - let loggedInUser = CometChatCalls.getLoggedInUser(); - - // Step 3: Login if not already logged in - if (!loggedInUser) { - loggedInUser = await CometChatCalls.login(uid, API_KEY); - } - - setUser(loggedInUser); - setIsReady(true); - } catch (err: any) { - console.error("CometChat Calls setup failed:", err); - setError(err.message || "Setup failed"); - } - } - - if (uid) { - initAndLogin(); - } - }, [uid]); - - return ( - - {children} - - ); -} - -export function useCometChatCalls(): CometChatCallsContextType { - return useContext(CometChatCallsContext); -} -``` - -### Step 3: Wrap Your App - -Add the provider to your app's root component: - -```tsx -// src/App.tsx -import { IonApp, IonRouterOutlet, setupIonicReact } from "@ionic/react"; -import { IonReactRouter } from "@ionic/react-router"; -import { Route } from "react-router-dom"; -import { CometChatCallsProvider } from "./providers/CometChatCallsProvider"; -import HomePage from "./pages/Home"; -import CallPage from "./pages/Call"; - -setupIonicReact(); - -const App: React.FC = () => { - // In a real app, get this from your authentication system - const currentUserId = "cometchat-uid-1"; - - return ( - - - - - - - - - - - ); -}; - -export default App; -``` - -### Step 4: Create the Call Page - -Create a call page that handles joining sessions, media controls, and cleanup: - -```tsx -// src/pages/Call.tsx -import { useEffect, useRef, useState } from "react"; -import { - IonContent, - IonPage, - IonButton, - IonIcon, - IonSpinner, - useIonRouter -} from "@ionic/react"; -import { mic, micOff, videocam, videocamOff, call } from "ionicons/icons"; -import { useParams } from "react-router-dom"; -import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; -import { useCometChatCalls } from "../providers/CometChatCallsProvider"; - -const CallPage: React.FC = () => { - const { sessionId } = useParams<{ sessionId: string }>(); - const { isReady, error: initError } = useCometChatCalls(); - const router = useIonRouter(); - const containerRef = useRef(null); - - // Call state - const [isJoined, setIsJoined] = useState(false); - const [isJoining, setIsJoining] = useState(false); - const [isMuted, setIsMuted] = useState(false); - const [isVideoOff, setIsVideoOff] = useState(false); - const [error, setError] = useState(null); - - const unsubscribersRef = useRef([]); - - useEffect(() => { - if (!isReady || !containerRef.current || !sessionId) return; - - async function joinCall() { - setIsJoining(true); - setError(null); - - try { - // Register event listeners before joining - unsubscribersRef.current = [ - CometChatCalls.addEventListener("onSessionJoined", () => { - setIsJoined(true); - setIsJoining(false); - }), - CometChatCalls.addEventListener("onSessionLeft", () => { - setIsJoined(false); - router.goBack(); - }), - CometChatCalls.addEventListener("onAudioMuted", () => setIsMuted(true)), - CometChatCalls.addEventListener("onAudioUnMuted", () => setIsMuted(false)), - CometChatCalls.addEventListener("onVideoPaused", () => setIsVideoOff(true)), - CometChatCalls.addEventListener("onVideoResumed", () => setIsVideoOff(false)), - ]; - - // Generate a call token for this session - const tokenResult = await CometChatCalls.generateToken(sessionId); - - // Join the call session - await CometChatCalls.joinSession( - tokenResult.token, - { - sessionType: "VIDEO", - layout: "TILE", - startAudioMuted: false, - startVideoPaused: false, - }, - containerRef.current! - ); - } catch (err: any) { - console.error("Failed to join call:", err); - setError(err.message || "Failed to join call"); - setIsJoining(false); - } - } - - joinCall(); - - return () => { - unsubscribersRef.current.forEach((unsub) => unsub()); - unsubscribersRef.current = []; - CometChatCalls.leaveSession(); - }; - }, [isReady, sessionId, router]); - - // Control handlers - const toggleAudio = () => { - isMuted ? CometChatCalls.unMuteAudio() : CometChatCalls.muteAudio(); - }; - - const toggleVideo = () => { - isVideoOff ? CometChatCalls.resumeVideo() : CometChatCalls.pauseVideo(); - }; - - const leaveCall = () => { - CometChatCalls.leaveSession(); - }; - - // Loading state - if (!isReady) { - return ( - - - -

Initializing...

-
-
- ); - } - - // Error state - if (error || initError) { - return ( - - -

- Error: {error || initError} -

- window.location.reload()}>Retry -
-
- ); - } - - return ( - - - {/* Video container - SDK renders the call UI here */} -
- - {/* Joining overlay */} - {isJoining && ( -
- -

Joining call...

-
- )} - - {/* Call controls */} - {isJoined && ( -
- - - - - - - - - -
- )} - - - ); -}; - -export default CallPage; -``` - - -### Step 5: Create the Home Page - -Create a home page where users can enter a session ID and join a call: - -```tsx -// src/pages/Home.tsx -import { useState } from "react"; -import { - IonContent, - IonPage, - IonHeader, - IonToolbar, - IonTitle, - IonItem, - IonLabel, - IonInput, - IonButton, - IonSpinner, - IonText, - useIonRouter -} from "@ionic/react"; -import { useCometChatCalls } from "../providers/CometChatCallsProvider"; - -const HomePage: React.FC = () => { - const { isReady, user, error } = useCometChatCalls(); - const router = useIonRouter(); - const [sessionId, setSessionId] = useState(""); - - const joinCall = () => { - if (sessionId) { - router.push(`/call/${sessionId}`); - } - }; - - return ( - - - - CometChat Calls - - - - {error && ( - -

{error}

-
- )} - - {!isReady ? ( -
- -

Loading...

-
- ) : ( - <> -

Logged in as: {user?.name || user?.uid}

- - - Session ID - setSessionId(e.detail.value || "")} - placeholder="Enter Session ID" - /> - - - - Join Call - - - )} -
-
- ); -}; - -export default HomePage; -``` - -## Ionic Vue - -### Step 2: Create the Composable - -Create a composable that handles SDK initialization and authentication: - -```typescript -// src/composables/useCometChatCalls.ts -import { ref, readonly } from "vue"; -import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; - -interface User { - uid: string; - name: string; - avatar?: string; -} - -// Replace with your CometChat credentials -const APP_ID = "YOUR_APP_ID"; -const REGION = "YOUR_REGION"; -const API_KEY = "YOUR_API_KEY"; - -// Shared state across all components -const isReady = ref(false); -const user = ref(null); -const error = ref(null); -const initialized = ref(false); - -export function useCometChatCalls() { - async function initAndLogin(uid: string): Promise { - if (initialized.value) { - return isReady.value; - } - - try { - // Step 1: Initialize the SDK - const initResult = await CometChatCalls.init({ - appId: APP_ID, - region: REGION, - }); - - if (!initResult.success) { - throw new Error("SDK initialization failed"); - } - - // Step 2: Check if already logged in - let loggedInUser = CometChatCalls.getLoggedInUser(); - - // Step 3: Login if not already logged in - if (!loggedInUser) { - loggedInUser = await CometChatCalls.login(uid, API_KEY); - } - - user.value = loggedInUser; - isReady.value = true; - initialized.value = true; - return true; - } catch (err: any) { - console.error("CometChat Calls setup failed:", err); - error.value = err.message || "Setup failed"; - return false; - } - } - - return { - isReady: readonly(isReady), - user: readonly(user), - error: readonly(error), - initAndLogin, - }; -} -``` - -### Step 3: Initialize in App Component - -Initialize the SDK and login when the app starts: - -```vue - - - - -``` - -### Step 4: Create the Call Page - -Create a call page that handles joining sessions, media controls, and cleanup: - -```vue - - - - - - -``` - - -### Step 5: Create the Home Page - -Create a home page where users can enter a session ID and join a call: - -```vue - - - - -``` - -### Step 6: Configure Routes - -Set up the router with the home and call pages: - -```typescript -// src/router/index.ts -import { createRouter, createWebHistory } from "@ionic/vue-router"; -import { RouteRecordRaw } from "vue-router"; -import HomePage from "../views/HomePage.vue"; -import CallPage from "../views/CallPage.vue"; - -const routes: Array = [ - { - path: "/", - component: HomePage, - }, - { - path: "/call/:sessionId", - component: CallPage, - }, -]; - -const router = createRouter({ - history: createWebHistory(import.meta.env.BASE_URL), - routes, -}); - -export default router; -``` - -## Related Documentation - -For more detailed information on specific topics covered in this guide, refer to the main documentation: - -- [Setup](/calls/javascript/setup) - Detailed SDK installation and initialization -- [Authentication](/calls/javascript/authentication) - Login methods and user management -- [Session Settings](/calls/javascript/session-settings) - All available call configuration options -- [Join Session](/calls/javascript/join-session) - Session joining and token generation -- [Events](/calls/javascript/events) - Complete list of event listeners -- [Actions](/calls/javascript/actions) - All available call control methods -- [Call Layouts](/calls/javascript/call-layouts) - Layout options and customization -- [Participant Management](/calls/javascript/participant-management) - Managing call participants + +TODO: Update the link +Check out the full sample app on [GitHub](https://github.com/cometchat/cometchat-calls-sdk-javascript-ionic-sample-app). + diff --git a/calls/javascript/join-session.mdx b/calls/javascript/join-session.mdx index b4e88361..f03753f3 100644 --- a/calls/javascript/join-session.mdx +++ b/calls/javascript/join-session.mdx @@ -62,17 +62,17 @@ The `generateToken()` method uses the auth token of the currently logged-in user Use the generated token to join the session along with your call settings and container element. -```javascript +```typescript const container = document.getElementById("call-container"); -const callSettings = { +const sessionSettings: SessionSettings = { sessionType: "VIDEO", layout: "TILE", startAudioMuted: false, startVideoPaused: false, }; -const result = await CometChatCalls.joinSession(callToken, callSettings, container); +const result = await CometChatCalls.joinSession(callToken, sessionSettings, container); if (result.error) { console.error("Failed to join session:", result.error); @@ -84,7 +84,7 @@ if (result.error) { | Parameter | Type | Description | |-----------|------|-------------| | `callToken` | String | Previously generated call token | -| `callSettings` | Object | Configuration for the session (see [Session Settings](/calls/javascript/session-settings)) | +| `sessionSettings` | Object | Configuration for the session (see [Session Settings](/calls/javascript/session-settings)) | | `container` | HTMLElement | Container element for the call UI | The method returns an object with: @@ -96,7 +96,7 @@ The method returns an object with: ## Complete Example -```javascript +```typescript const sessionId = "SESSION_ID"; const container = document.getElementById("call-container"); @@ -105,7 +105,7 @@ try { const tokenResult = await CometChatCalls.generateToken(sessionId); // Step 2: Configure session settings - const callSettings = { + const sessionSettings: SessionSettings = { sessionType: "VIDEO", layout: "TILE", startAudioMuted: false, @@ -115,7 +115,7 @@ try { // Step 3: Join session const joinResult = await CometChatCalls.joinSession( tokenResult.token, - callSettings, + sessionSettings, container ); diff --git a/calls/javascript/nextjs-integration.mdx b/calls/javascript/nextjs-integration.mdx index d59b3721..10c943a6 100644 --- a/calls/javascript/nextjs-integration.mdx +++ b/calls/javascript/nextjs-integration.mdx @@ -3,555 +3,13 @@ title: "Next.js Integration" sidebarTitle: "Next.js" --- -This guide walks you through integrating the CometChat Calls SDK into a Next.js application. By the end, you'll have a working video call implementation with proper server-side rendering handling and authentication. - -## Prerequisites - -Before you begin, ensure you have: -- A CometChat account with an app created ([Sign up](https://app.cometchat.com/signup)) -- Your App ID, Region, and API Key from the CometChat Dashboard -- A Next.js project (App Router or Pages Router) -- Node.js 16+ installed - -## Important: Client-Side Only - -The CometChat Calls SDK uses browser APIs (WebRTC, DOM) that are not available during server-side rendering. You must ensure the SDK only loads and runs on the client side. This guide shows you how to handle this properly with both the App Router and Pages Router. - -## Step 1: Install the SDK - -Install the CometChat Calls SDK package: - -```bash -npm install @cometchat/calls-sdk-javascript -``` - -## Step 2: Configure Environment Variables - -Add your CometChat credentials to `.env.local`. The `NEXT_PUBLIC_` prefix makes these variables available in the browser: - -```env -NEXT_PUBLIC_COMETCHAT_APP_ID=your_app_id -NEXT_PUBLIC_COMETCHAT_REGION=us -NEXT_PUBLIC_COMETCHAT_API_KEY=your_api_key -``` +The CometChat Calls SDK integration for Next.js is the same as [React](/calls/javascript/react-integration). Follow the React integration guide to get started. -Never expose your API Key in production client-side code. Use a backend service to generate auth tokens securely. The API Key approach shown here is for development and testing only. +The CometChat Calls SDK relies on browser APIs (WebRTC, DOM) and does not support server-side rendering. All SDK usage — initialization, login, joining sessions, and rendering call UI — must happen on the client side only. Make sure your components that use the SDK are client components (e.g., using the `"use client"` directive). -## Step 3: Create the Provider - -Create a context provider that handles SDK initialization and user authentication. The `"use client"` directive ensures this component only runs in the browser. - -```tsx -// providers/CometChatCallsProvider.tsx -"use client"; - -import { createContext, useContext, useEffect, useState, ReactNode } from "react"; - -interface User { - uid: string; - name: string; - avatar?: string; -} - -interface CometChatCallsContextType { - isReady: boolean; - user: User | null; - error: string | null; - CometChatCalls: any; -} - -const CometChatCallsContext = createContext({ - isReady: false, - user: null, - error: null, - CometChatCalls: null, -}); - -interface ProviderProps { - children: ReactNode; - uid: string; -} - -export function CometChatCallsProvider({ children, uid }: ProviderProps) { - const [isReady, setIsReady] = useState(false); - const [user, setUser] = useState(null); - const [error, setError] = useState(null); - const [CometChatCalls, setCometChatCalls] = useState(null); - - useEffect(() => { - async function initAndLogin() { - try { - // Dynamic import ensures the SDK only loads on the client - const { CometChatCalls: SDK } = await import("@cometchat/calls-sdk-javascript"); - - // Step 1: Initialize the SDK - const initResult = await SDK.init({ - appId: process.env.NEXT_PUBLIC_COMETCHAT_APP_ID!, - region: process.env.NEXT_PUBLIC_COMETCHAT_REGION!, - }); - - if (!initResult.success) { - throw new Error("SDK initialization failed"); - } - - // Step 2: Check if already logged in - let loggedInUser = SDK.getLoggedInUser(); - - // Step 3: Login if not already logged in - if (!loggedInUser) { - loggedInUser = await SDK.login( - uid, - process.env.NEXT_PUBLIC_COMETCHAT_API_KEY! - ); - } - - setCometChatCalls(SDK); - setUser(loggedInUser); - setIsReady(true); - } catch (err: any) { - console.error("CometChat Calls setup failed:", err); - setError(err.message || "Setup failed"); - } - } - - if (uid) { - initAndLogin(); - } - }, [uid]); - - return ( - - {children} - - ); -} - -export function useCometChatCalls(): CometChatCallsContextType { - return useContext(CometChatCallsContext); -} -``` - -## Step 4: Add Provider to Layout (App Router) - -Wrap your application with the provider. Since the provider is a client component, you can still use it in a server component layout: - -```tsx -// app/layout.tsx -import { CometChatCallsProvider } from "@/providers/CometChatCallsProvider"; - -export default function RootLayout({ children }: { children: React.ReactNode }) { - // In a real app, get this from your authentication system - const currentUserId = "cometchat-uid-1"; - - return ( - - - - {children} - - - - ); -} -``` - -## Step 5: Create the Call Component - -Build a client-side call component that handles joining sessions, media controls, and cleanup. The component uses the SDK instance from the context provider: - -```tsx -// components/CallScreen.tsx -"use client"; - -import { useEffect, useRef, useState } from "react"; -import { useCometChatCalls } from "@/providers/CometChatCallsProvider"; - -interface CallScreenProps { - sessionId: string; - onCallEnd?: () => void; -} - -export default function CallScreen({ sessionId, onCallEnd }: CallScreenProps) { - const { isReady, CometChatCalls } = useCometChatCalls(); - const containerRef = useRef(null); - - // Call state - const [isJoined, setIsJoined] = useState(false); - const [isJoining, setIsJoining] = useState(false); - const [isMuted, setIsMuted] = useState(false); - const [isVideoOff, setIsVideoOff] = useState(false); - const [error, setError] = useState(null); - - // Store unsubscribe functions for cleanup - const unsubscribersRef = useRef([]); - - useEffect(() => { - // Don't proceed if SDK isn't ready or container isn't mounted - if (!isReady || !CometChatCalls || !containerRef.current || !sessionId) return; - - async function joinCall() { - setIsJoining(true); - setError(null); - - try { - // Register event listeners before joining - unsubscribersRef.current = [ - CometChatCalls.addEventListener("onSessionJoined", () => { - setIsJoined(true); - setIsJoining(false); - }), - CometChatCalls.addEventListener("onSessionLeft", () => { - setIsJoined(false); - onCallEnd?.(); - }), - CometChatCalls.addEventListener("onAudioMuted", () => setIsMuted(true)), - CometChatCalls.addEventListener("onAudioUnMuted", () => setIsMuted(false)), - CometChatCalls.addEventListener("onVideoPaused", () => setIsVideoOff(true)), - CometChatCalls.addEventListener("onVideoResumed", () => setIsVideoOff(false)), - ]; - - // Generate a call token for this session - const tokenResult = await CometChatCalls.generateToken(sessionId); - - // Join the call session - const joinResult = await CometChatCalls.joinSession( - tokenResult.token, - { - sessionType: "VIDEO", - layout: "TILE", - startAudioMuted: false, - startVideoPaused: false, - }, - containerRef.current - ); - - if (joinResult.error) { - throw new Error(joinResult.error.message); - } - } catch (err: any) { - console.error("Failed to join call:", err); - setError(err.message || "Failed to join call"); - setIsJoining(false); - } - } - - joinCall(); - - // Cleanup when component unmounts - return () => { - unsubscribersRef.current.forEach((unsub) => unsub()); - unsubscribersRef.current = []; - CometChatCalls?.leaveSession(); - }; - }, [isReady, CometChatCalls, sessionId, onCallEnd]); - - // Control handlers - const toggleAudio = () => { - isMuted ? CometChatCalls.unMuteAudio() : CometChatCalls.muteAudio(); - }; - - const toggleVideo = () => { - isVideoOff ? CometChatCalls.resumeVideo() : CometChatCalls.pauseVideo(); - }; - - const leaveCall = () => { - CometChatCalls.leaveSession(); - }; - - // Loading state - if (!isReady) { - return
Initializing...
; - } - - // Error state - if (error) { - return ( -
-

Error: {error}

- -
- ); - } - - return ( -
- {/* Video container - SDK renders the call UI here */} -
- - {/* Loading overlay */} - {isJoining && ( -
Joining call...
- )} - - {/* Call controls */} - {isJoined && ( -
- - - -
- )} -
- ); -} -``` - -## Step 6: Create the Call Page - -Create a page that uses the call component. This example shows a simple interface where users can enter a session ID and join a call: - -```tsx -// app/page.tsx -"use client"; - -import { useState } from "react"; -import { useCometChatCalls } from "@/providers/CometChatCallsProvider"; -import CallScreen from "@/components/CallScreen"; - -export default function HomePage() { - const { isReady, user, error } = useCometChatCalls(); - const [sessionId, setSessionId] = useState(""); - const [isInCall, setIsInCall] = useState(false); - - if (error) { - return ( -
-

Error: {error}

-
- ); - } - - if (!isReady) { - return ( -
-

Loading...

-
- ); - } - - if (isInCall) { - return ( - setIsInCall(false)} - /> - ); - } - - return ( -
-

CometChat Calls

-

Logged in as: {user?.name || user?.uid}

- -
- setSessionId(e.target.value)} - className="w-full p-3 border rounded-lg" - /> - -
-
- ); -} -``` - -## Dynamic Route for Call Sessions - -For a cleaner URL structure, create a dynamic route that accepts the session ID as a parameter: - -```tsx -// app/call/[sessionId]/page.tsx -"use client"; - -import { useParams, useRouter } from "next/navigation"; -import CallScreen from "@/components/CallScreen"; - -export default function CallPage() { - const params = useParams(); - const router = useRouter(); - const sessionId = params.sessionId as string; - - return ( - router.push("/")} - /> - ); -} -``` - -## Pages Router Setup - -If you're using the Pages Router instead of the App Router, use dynamic imports to prevent server-side rendering of the SDK: - -```tsx -// pages/_app.tsx -import type { AppProps } from "next/app"; -import dynamic from "next/dynamic"; - -const CometChatCallsProvider = dynamic( - () => import("@/providers/CometChatCallsProvider").then(mod => mod.CometChatCallsProvider), - { ssr: false } -); - -export default function App({ Component, pageProps }: AppProps) { - const currentUserId = "cometchat-uid-1"; - - return ( - - - - ); -} -``` - -```tsx -// pages/call/[sessionId].tsx -import dynamic from "next/dynamic"; -import { useRouter } from "next/router"; - -const CallScreen = dynamic(() => import("@/components/CallScreen"), { - ssr: false, - loading: () =>
Loading call...
, -}); - -export default function CallPage() { - const router = useRouter(); - const { sessionId } = router.query; - - if (!sessionId) { - return
Loading...
; - } - - return ( - router.push("/")} - /> - ); -} -``` - -## Custom Hook (Optional) - -For more complex applications, extract call logic into a reusable hook: - -```tsx -// hooks/useCall.ts -"use client"; - -import { useState, useCallback, useRef, useEffect } from "react"; -import { useCometChatCalls } from "@/providers/CometChatCallsProvider"; - -export function useCall() { - const { CometChatCalls, isReady } = useCometChatCalls(); - const [isInCall, setIsInCall] = useState(false); - const [isMuted, setIsMuted] = useState(false); - const [isVideoOff, setIsVideoOff] = useState(false); - const [participants, setParticipants] = useState([]); - const unsubscribersRef = useRef([]); - - const joinCall = useCallback(async (sessionId: string, container: HTMLElement, settings = {}) => { - if (!CometChatCalls) return; - - // Setup listeners - unsubscribersRef.current = [ - CometChatCalls.addEventListener("onAudioMuted", () => setIsMuted(true)), - CometChatCalls.addEventListener("onAudioUnMuted", () => setIsMuted(false)), - CometChatCalls.addEventListener("onVideoPaused", () => setIsVideoOff(true)), - CometChatCalls.addEventListener("onVideoResumed", () => setIsVideoOff(false)), - CometChatCalls.addEventListener("onParticipantListChanged", setParticipants), - CometChatCalls.addEventListener("onSessionLeft", () => setIsInCall(false)), - ]; - - const tokenResult = await CometChatCalls.generateToken(sessionId); - await CometChatCalls.joinSession( - tokenResult.token, - { sessionType: "VIDEO", layout: "TILE", ...settings }, - container - ); - setIsInCall(true); - }, [CometChatCalls]); - - const leaveCall = useCallback(() => { - CometChatCalls?.leaveSession(); - unsubscribersRef.current.forEach((unsub) => unsub()); - unsubscribersRef.current = []; - setIsInCall(false); - }, [CometChatCalls]); - - const toggleAudio = useCallback(() => { - isMuted ? CometChatCalls?.unMuteAudio() : CometChatCalls?.muteAudio(); - }, [CometChatCalls, isMuted]); - - const toggleVideo = useCallback(() => { - isVideoOff ? CometChatCalls?.resumeVideo() : CometChatCalls?.pauseVideo(); - }, [CometChatCalls, isVideoOff]); - - // Cleanup on unmount - useEffect(() => { - return () => { - unsubscribersRef.current.forEach((unsub) => unsub()); - }; - }, []); - - return { - isReady, - isInCall, - isMuted, - isVideoOff, - participants, - joinCall, - leaveCall, - toggleAudio, - toggleVideo, - }; -} -``` - -## Related Documentation - -For more detailed information on specific topics covered in this guide, refer to the main documentation: - -- [Setup](/calls/javascript/setup) - Detailed SDK installation and initialization -- [Authentication](/calls/javascript/authentication) - Login methods and user management -- [Session Settings](/calls/javascript/session-settings) - All available call configuration options -- [Join Session](/calls/javascript/join-session) - Session joining and token generation -- [Events](/calls/javascript/events) - Complete list of event listeners -- [Actions](/calls/javascript/actions) - All available call control methods -- [Call Layouts](/calls/javascript/call-layouts) - Layout options and customization -- [Participant Management](/calls/javascript/participant-management) - Managing call participants + +TODO: Update the link +Check out the full sample app on [GitHub](https://github.com/cometchat/cometchat-calls-sdk-javascript-nextjs-sample-app). + diff --git a/calls/javascript/overview.mdx b/calls/javascript/overview.mdx index 7c381e4b..d0ec575d 100644 --- a/calls/javascript/overview.mdx +++ b/calls/javascript/overview.mdx @@ -8,24 +8,23 @@ The CometChat Calls SDK enables real-time voice and video calling capabilities i **Faster Integration with UI Kits** -If you're using CometChat UI Kits, voice and video calling can be quickly integrated: -- Incoming & outgoing call screens +If you're using CometChat UI Kits, voice and video calling can be quickly integrated with pre-built components: +- Incoming and outgoing call screens - Call buttons with one-tap calling - Call logs with history 👉 [React UI Kit Calling Integration](/ui-kit/react/calling-integration) -Use this Calls SDK directly only if you need custom call UI or advanced control. +Use the Calls SDK directly if you need more granular control over the calling implementation or want to build a custom calling interface. For faster integration with pre-built UI components, explore our UI Kit SDKs. ## Prerequisites Before integrating the Calls SDK, ensure you have: -1. **CometChat Account**: [Sign up](https://app.cometchat.com/signup) and create an app to get your App ID, Region, and API Key +1. **CometChat Account**: [Sign up](https://app.cometchat.com/signup) and create an app to get your App ID, Region, and Auth Key 2. **CometChat Users**: Users must exist in CometChat to use calling features. For testing, create users via the [Dashboard](https://app.cometchat.com) or [REST API](/rest-api/chat-apis/users/create-user). Authentication is handled by the Calls SDK - see [Authentication](/calls/javascript/authentication) 3. **Browser Requirements**: See [Browser Compatibility](#browser-compatibility) below -4. **Permissions**: Camera and microphone permissions for video/audio calls ## Browser Compatibility @@ -37,8 +36,6 @@ The Calls SDK requires a modern browser with WebRTC support: | Firefox | 68+ | Full support | | Safari | 12.1+ | Full support | | Edge | 79+ | Chromium-based | -| Opera | 60+ | Full support | -| Samsung Internet | 12+ | Full support | ### Requirements @@ -53,7 +50,6 @@ The Calls SDK requires a modern browser with WebRTC support: | Chrome for Android | ✅ Full support | | Safari for iOS | ✅ iOS 12.1+ | | Firefox for Android | ✅ Full support | -| Samsung Internet | ✅ Full support | For native mobile apps, consider using the [iOS](/calls/ios/overview) or [Android](/calls/android/overview) SDKs for better performance and native features like CallKit/VoIP. @@ -87,23 +83,6 @@ Get started quickly with framework-specific guides that include complete setup, -## Call Flow - -```mermaid -sequenceDiagram - participant App - participant CometChatCalls - - App->>CometChatCalls: init() - App->>CometChatCalls: login() - App->>CometChatCalls: generateToken() - App->>CometChatCalls: joinSession() - CometChatCalls-->>App: Session joined - App->>CometChatCalls: Actions (mute, pause, etc.) - CometChatCalls-->>App: Event callbacks - App->>CometChatCalls: leaveSession() -``` - ## Features diff --git a/calls/javascript/participant-management.mdx b/calls/javascript/participant-management.mdx index 105430f9..dd43e12d 100644 --- a/calls/javascript/participant-management.mdx +++ b/calls/javascript/participant-management.mdx @@ -129,8 +129,8 @@ CometChatCalls.addEventListener("onDominantSpeakerChanged", (participant) => { Control visibility of the participant list button: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { hideParticipantListButton: false, // Show the button // ... other settings }; diff --git a/calls/javascript/picture-in-picture.mdx b/calls/javascript/picture-in-picture.mdx deleted file mode 100644 index 1648a701..00000000 --- a/calls/javascript/picture-in-picture.mdx +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: "Picture-in-Picture" -sidebarTitle: "Picture-in-Picture" ---- - -Picture-in-Picture (PiP) allows the call video to continue playing in a floating window while users interact with other content on the page or other browser tabs. - -## Enable Picture-in-Picture - -Enable PiP mode during a call: - -```javascript -CometChatCalls.enablePictureInPictureLayout(); -``` - -## Disable Picture-in-Picture - -Return to the normal call view: - -```javascript -CometChatCalls.disablePictureInPictureLayout(); -``` - -## Browser Support - -Picture-in-Picture support varies by browser: - -| Browser | Support | Notes | -|---------|---------|-------| -| Chrome | ✅ Full support | Chrome 70+ | -| Edge | ✅ Full support | Chromium-based | -| Safari | ✅ Full support | Safari 13.1+ | -| Firefox | ⚠️ Limited | Behind flag in some versions | -| Opera | ✅ Full support | Opera 57+ | - -## Check PiP Support - -Before enabling PiP, check if the browser supports it: - -```javascript -function isPiPSupported() { - return document.pictureInPictureEnabled || false; -} - -if (isPiPSupported()) { - CometChatCalls.enablePictureInPictureLayout(); -} else { - console.log("Picture-in-Picture not supported in this browser"); -} -``` - -## PiP Events - -The SDK doesn't provide specific PiP events, but you can listen to the browser's native PiP events on the video element if needed: - -```javascript -// If you have access to the video element -videoElement.addEventListener("enterpictureinpicture", () => { - console.log("Entered PiP mode"); -}); - -videoElement.addEventListener("leavepictureinpicture", () => { - console.log("Left PiP mode"); -}); -``` - -## User-Initiated PiP - -Browsers typically require PiP to be triggered by a user gesture (click, tap). Wrap the enable call in a button handler: - -```javascript -document.getElementById("pip-btn").addEventListener("click", () => { - CometChatCalls.enablePictureInPictureLayout(); -}); -``` - -## Auto-PiP on Tab Switch - -Some browsers support automatic PiP when switching tabs. This is a browser-level feature and may require user permission. - -```javascript -// Check if auto-PiP is available (Chrome) -if ("documentPictureInPicture" in window) { - // Document PiP API available -} -``` - -## Styling Considerations - -When PiP is active: -- The main call container may appear empty or show a placeholder -- Consider showing a message indicating the call is in PiP mode -- Provide a button to exit PiP and return to the full view - -```javascript -let isPiPActive = false; - -function togglePiP() { - if (isPiPActive) { - CometChatCalls.disablePictureInPictureLayout(); - isPiPActive = false; - } else { - CometChatCalls.enablePictureInPictureLayout(); - isPiPActive = true; - } - updateUI(); -} - -function updateUI() { - const placeholder = document.getElementById("pip-placeholder"); - placeholder.style.display = isPiPActive ? "block" : "none"; -} -``` - diff --git a/calls/javascript/raise-hand.mdx b/calls/javascript/raise-hand.mdx index b012761d..b633fbef 100644 --- a/calls/javascript/raise-hand.mdx +++ b/calls/javascript/raise-hand.mdx @@ -50,8 +50,8 @@ CometChatCalls.addEventListener("onParticipantHandLowered", (participant) => { To hide the raise hand button from the control panel: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { hideRaiseHandButton: true, // ... other settings }; diff --git a/calls/javascript/react-integration.mdx b/calls/javascript/react-integration.mdx index 132a1435..bb64802e 100644 --- a/calls/javascript/react-integration.mdx +++ b/calls/javascript/react-integration.mdx @@ -3,15 +3,12 @@ title: "React Integration" sidebarTitle: "React" --- -This guide walks you through integrating the CometChat Calls SDK into a React application. By the end, you'll have a working video call implementation with proper state management and lifecycle handling. +This guide walks you through integrating the CometChat Calls SDK into a React application. By the end, you'll have a working video call implementation with proper lifecycle handling. ## Prerequisites -Before you begin, ensure you have: -- A CometChat account with an app created ([Sign up](https://app.cometchat.com/signup)) -- Your App ID, Region, and API Key from the CometChat Dashboard -- A React project (Create React App, Vite, or similar) -- Node.js 16+ installed +Before you begin, make sure you've completed the [prerequisites](/calls/javascript/overview#prerequisites) from the Overview page. You'll also need: +- A React project ## Step 1: Install the SDK @@ -23,420 +20,120 @@ npm install @cometchat/calls-sdk-javascript ## Step 2: Initialize and Login -Create a provider component to handle SDK initialization and authentication. This ensures the SDK is ready before any call components render. +### Initialize -```jsx -// src/providers/CometChatCallsProvider.jsx -import { createContext, useContext, useEffect, useState } from "react"; +Initialize the SDK with your app credentials. Call this once when your application starts. + +```javascript import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; -const CometChatCallsContext = createContext({ - isReady: false, - user: null, - error: null, +const { error } = await CometChatCalls.init({ + appId: "APP_ID", // Replace with your App ID + region: "REGION", // Replace with your Region (us, eu, in) + authKey: "AUTH_KEY", // (Optional) Replace with your Auth Key }); -const APP_ID = "YOUR_APP_ID"; // Replace with your App ID -const REGION = "YOUR_REGION"; // Replace with your Region (us, eu, in) -const API_KEY = "YOUR_API_KEY"; // Replace with your API Key - -export function CometChatCallsProvider({ children, uid }) { - const [isReady, setIsReady] = useState(false); - const [user, setUser] = useState(null); - const [error, setError] = useState(null); - - useEffect(() => { - async function initAndLogin() { - try { - // Step 1: Initialize the SDK - const initResult = await CometChatCalls.init({ - appId: APP_ID, - region: REGION, - }); - - if (!initResult.success) { - throw new Error("SDK initialization failed"); - } - - // Step 2: Check if already logged in - let loggedInUser = CometChatCalls.getLoggedInUser(); - - // Step 3: Login if not already logged in - if (!loggedInUser) { - loggedInUser = await CometChatCalls.login(uid, API_KEY); - } - - setUser(loggedInUser); - setIsReady(true); - } catch (err) { - console.error("CometChat Calls setup failed:", err); - setError(err.message || "Setup failed"); - } - } - - if (uid) { - initAndLogin(); - } - }, [uid]); - - return ( - - {children} - - ); -} - -export function useCometChatCalls() { - return useContext(CometChatCallsContext); +if (error) { + console.error("CometChatCalls initialization failed:", error); +} else { + console.log("CometChatCalls initialized successfully"); } ``` -## Step 3: Wrap Your App - -Add the provider to your app's root component: +### Login -```jsx -// src/App.jsx -import { CometChatCallsProvider } from "./providers/CometChatCallsProvider"; -import CallPage from "./pages/CallPage"; - -function App() { - // In a real app, get this from your authentication system - const currentUserId = "cometchat-uid-1"; - - return ( - - - - ); -} +Log in the user with their UID. Ensure the SDK is initialized before calling `login()`. -export default App; +```javascript +CometChatCalls.login("UID") // Replace with your user's UID + .then((user) => { + console.log("Logged in successfully", user); + }); ``` -## Step 4: Create the Call Component +## Step 3: Generate Token -Build a call component that handles joining, controls, and cleanup: +Generate a call token for the session. The call token is required to authenticate the user for that particular session. -```jsx -// src/components/CallScreen.jsx -import { useEffect, useRef, useState } from "react"; -import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; -import { useCometChatCalls } from "../providers/CometChatCallsProvider"; +```javascript +CometChatCalls.generateToken("SESSION_ID") // Replace with your Session ID + .then(({ token }) => { + console.log("token", token); + }); +``` -export default function CallScreen({ sessionId, onCallEnd }) { - const { isReady } = useCometChatCalls(); - const containerRef = useRef(null); - - // Call state - const [isJoined, setIsJoined] = useState(false); - const [isJoining, setIsJoining] = useState(false); - const [isMuted, setIsMuted] = useState(false); - const [isVideoOff, setIsVideoOff] = useState(false); - const [error, setError] = useState(null); - - // Store unsubscribe functions for cleanup - const unsubscribersRef = useRef([]); +## Step 4: Join Session - useEffect(() => { - // Don't proceed if SDK isn't ready or container isn't mounted - if (!isReady || !containerRef.current || !sessionId) return; - - async function joinCall() { - setIsJoining(true); - setError(null); - - try { - // Register event listeners before joining - unsubscribersRef.current = [ - CometChatCalls.addEventListener("onSessionJoined", () => { - setIsJoined(true); - setIsJoining(false); - }), - CometChatCalls.addEventListener("onSessionLeft", () => { - setIsJoined(false); - onCallEnd?.(); - }), - CometChatCalls.addEventListener("onAudioMuted", () => setIsMuted(true)), - CometChatCalls.addEventListener("onAudioUnMuted", () => setIsMuted(false)), - CometChatCalls.addEventListener("onVideoPaused", () => setIsVideoOff(true)), - CometChatCalls.addEventListener("onVideoResumed", () => setIsVideoOff(false)), - ]; - - // Generate a call token for this session - const tokenResult = await CometChatCalls.generateToken(sessionId); - - // Join the call session - const joinResult = await CometChatCalls.joinSession( - tokenResult.token, - { - sessionType: "VIDEO", - layout: "TILE", - startAudioMuted: false, - startVideoPaused: false, - }, - containerRef.current - ); - - if (joinResult.error) { - throw new Error(joinResult.error.message); - } - } catch (err) { - console.error("Failed to join call:", err); - setError(err.message || "Failed to join call"); - setIsJoining(false); - } - } +Use the generated token to join the session along with your call settings and a container element. - joinCall(); +```typescript +const containerRef = useRef(null); - // Cleanup when component unmounts - return () => { - unsubscribersRef.current.forEach((unsub) => unsub()); - unsubscribersRef.current = []; - CometChatCalls.leaveSession(); - }; - }, [isReady, sessionId, onCallEnd]); - - // Control handlers - const toggleAudio = () => { - isMuted ? CometChatCalls.unMuteAudio() : CometChatCalls.muteAudio(); - }; - - const toggleVideo = () => { - isVideoOff ? CometChatCalls.resumeVideo() : CometChatCalls.pauseVideo(); - }; - - const leaveCall = () => { - CometChatCalls.leaveSession(); - }; - - // Loading state - if (!isReady) { - return
Initializing...
; - } - - // Error state - if (error) { - return ( -
-

Error: {error}

- -
- ); - } +const sessionSettings: SessionSettings = {}; +CometChatCalls.joinSession(token, sessionSettings, containerRef.current); - return ( -
- {/* Video container - SDK renders the call UI here */} -
- - {/* Loading overlay */} - {isJoining && ( -
Joining call...
- )} - - {/* Call controls */} - {isJoined && ( -
- - - -
- )} -
- ); -} +// In your JSX +//
``` -## Step 5: Use the Call Component - -Create a page that uses the call component: +For all available call settings options, see [Session Settings](/calls/javascript/session-settings). -```jsx -// src/pages/CallPage.jsx -import { useState } from "react"; -import { useCometChatCalls } from "../providers/CometChatCallsProvider"; -import CallScreen from "../components/CallScreen"; +## Step 5: Full Example -export default function CallPage() { - const { isReady, user, error } = useCometChatCalls(); - const [sessionId, setSessionId] = useState(""); - const [isInCall, setIsInCall] = useState(false); +Here's a complete React component that initializes the SDK, logs in, generates a token, and joins a call session inside a `useEffect`: - if (error) { - return
Error: {error}
; - } - - if (!isReady) { - return
Loading...
; - } - - if (isInCall) { - return ( - setIsInCall(false)} - /> - ); - } - - return ( -
-

CometChat Calls

-

Logged in as: {user?.name || user?.uid}

- -
- setSessionId(e.target.value)} - style={{ width: "100%", padding: "12px", marginBottom: "10px" }} - /> - -
-
- ); -} -``` - -## Custom Hook (Optional) +```tsx +import { useEffect, useRef } from "react"; +import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; -For more complex applications, extract call logic into a reusable hook: +export default function CallScreen() { + const containerRef = useRef(null); -```jsx -// src/hooks/useCall.js -import { useState, useCallback, useRef, useEffect } from "react"; -import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; + useEffect(() => { + async function startCall() { + // 1. Initialize + const { error } = await CometChatCalls.init({ + appId: "APP_ID", // Replace with your App ID + region: "REGION", // Replace with your Region (us, eu, in) + authKey: "AUTH_KEY", // (Optional) Replace with your Auth Key + }); + + if (error) { + console.error("CometChatCalls initialization failed:", error); + return; + } -export function useCall() { - const [isInCall, setIsInCall] = useState(false); - const [isMuted, setIsMuted] = useState(false); - const [isVideoOff, setIsVideoOff] = useState(false); - const [participants, setParticipants] = useState([]); - const unsubscribersRef = useRef([]); - - const joinCall = useCallback(async (sessionId, container, settings = {}) => { - // Setup listeners - unsubscribersRef.current = [ - CometChatCalls.addEventListener("onAudioMuted", () => setIsMuted(true)), - CometChatCalls.addEventListener("onAudioUnMuted", () => setIsMuted(false)), - CometChatCalls.addEventListener("onVideoPaused", () => setIsVideoOff(true)), - CometChatCalls.addEventListener("onVideoResumed", () => setIsVideoOff(false)), - CometChatCalls.addEventListener("onParticipantListChanged", setParticipants), - CometChatCalls.addEventListener("onSessionLeft", () => setIsInCall(false)), - ]; - - const tokenResult = await CometChatCalls.generateToken(sessionId); - await CometChatCalls.joinSession( - tokenResult.token, - { sessionType: "VIDEO", layout: "TILE", ...settings }, - container - ); - setIsInCall(true); - }, []); + // 2. Login + await CometChatCalls.login("UID"); // Replace with your user's UID - const leaveCall = useCallback(() => { - CometChatCalls.leaveSession(); - unsubscribersRef.current.forEach((unsub) => unsub()); - unsubscribersRef.current = []; - setIsInCall(false); - }, []); + // 3. Generate Token + const { token } = await CometChatCalls.generateToken("SESSION_ID"); // Replace with your Session ID - const toggleAudio = useCallback(() => { - isMuted ? CometChatCalls.unMuteAudio() : CometChatCalls.muteAudio(); - }, [isMuted]); + // 4. Join Session + const sessionSettings: SessionSettings = {}; + CometChatCalls.joinSession(token, sessionSettings, containerRef.current); + } - const toggleVideo = useCallback(() => { - isVideoOff ? CometChatCalls.resumeVideo() : CometChatCalls.pauseVideo(); - }, [isVideoOff]); + startCall(); - // Cleanup on unmount - useEffect(() => { return () => { - unsubscribersRef.current.forEach((unsub) => unsub()); + CometChatCalls.leaveSession(); }; }, []); - return { - isInCall, - isMuted, - isVideoOff, - participants, - joinCall, - leaveCall, - toggleAudio, - toggleVideo, - }; + return ( +
+ ); } ``` -## TypeScript Support - -The SDK includes TypeScript definitions. Here's a typed version of the provider: - -```tsx -// src/providers/CometChatCallsProvider.tsx -import { createContext, useContext, useEffect, useState, ReactNode } from "react"; -import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; - -interface User { - uid: string; - name: string; - avatar?: string; -} - -interface CometChatCallsContextType { - isReady: boolean; - user: User | null; - error: string | null; -} - -const CometChatCallsContext = createContext({ - isReady: false, - user: null, - error: null, -}); - -interface ProviderProps { - children: ReactNode; - uid: string; -} - -export function CometChatCallsProvider({ children, uid }: ProviderProps) { - // ... same implementation as above -} - -export function useCometChatCalls(): CometChatCallsContextType { - return useContext(CometChatCallsContext); -} -``` + +TODO: Update the link +Check out the full sample app on [GitHub](https://github.com/cometchat/cometchat-calls-sdk-javascript-react-sample-app). + ## Related Documentation @@ -450,4 +147,3 @@ For more detailed information on specific topics covered in this guide, refer to - [Actions](/calls/javascript/actions) - All available call control methods - [Call Layouts](/calls/javascript/call-layouts) - Layout options and customization - [Participant Management](/calls/javascript/participant-management) - Managing call participants - diff --git a/calls/javascript/recording.mdx b/calls/javascript/recording.mdx index ada4a3d4..2fcbe27d 100644 --- a/calls/javascript/recording.mdx +++ b/calls/javascript/recording.mdx @@ -13,13 +13,13 @@ Recording must be enabled for your CometChat app. Contact support if you need to Configure recording to start automatically when the session begins: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { autoStartRecording: true, // ... other settings }; -await CometChatCalls.joinSession(callToken, callSettings, container); +await CometChatCalls.joinSession(callToken, sessionSettings, container); ``` ## Manual Recording Control @@ -82,8 +82,8 @@ CometChatCalls.addEventListener("onParticipantStoppedRecording", (participant) = By default, the recording button is hidden. To show it: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { hideRecordingButton: false, // ... other settings }; diff --git a/calls/javascript/ringing.mdx b/calls/javascript/ringing.mdx index ad54370b..99ffcce3 100644 --- a/calls/javascript/ringing.mdx +++ b/calls/javascript/ringing.mdx @@ -46,8 +46,8 @@ await CometChat.init(appId, new CometChat.AppSettingsBuilder() await CometChatCalls.init({ appId, region }); // Login to both -await CometChat.login(uid, apiKey); -await CometChatCalls.login(uid, apiKey); +await CometChat.login(uid, authKey); +await CometChatCalls.login(uid, authKey); ``` ## Initiate a Call diff --git a/calls/javascript/screen-sharing.mdx b/calls/javascript/screen-sharing.mdx index d3c70c38..d5adca78 100644 --- a/calls/javascript/screen-sharing.mdx +++ b/calls/javascript/screen-sharing.mdx @@ -62,8 +62,8 @@ CometChatCalls.addEventListener("onParticipantStoppedScreenShare", (participant) To hide the screen sharing button from the control panel: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { hideScreenSharingButton: true, // ... other settings }; diff --git a/calls/javascript/session-settings.mdx b/calls/javascript/session-settings.mdx index d2948b67..ec84bd10 100644 --- a/calls/javascript/session-settings.mdx +++ b/calls/javascript/session-settings.mdx @@ -9,8 +9,8 @@ The session settings object allows you to customize every aspect of your call se These are pre-session configurations that must be set before joining a call. Once configured, pass the settings object to the `joinSession()` method. Settings cannot be changed after the session has started, though many features can be controlled dynamically during the call using call actions. -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { sessionType: "VIDEO", layout: "TILE", startAudioMuted: false, @@ -243,8 +243,8 @@ hideNetworkIndicator: true ## Complete Example -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { // Session configuration sessionType: "VIDEO", layout: "TILE", diff --git a/calls/javascript/setup.mdx b/calls/javascript/setup.mdx index 3a81c0a4..06075f90 100644 --- a/calls/javascript/setup.mdx +++ b/calls/javascript/setup.mdx @@ -42,14 +42,17 @@ The initialization requires a configuration object with the following properties |-----------|------|----------|-------------| | `appId` | String | Yes | Your CometChat App ID | | `region` | String | Yes | Your app region (`us`, `eu`, or `in`) | +| `authKey` | String | No | Your CometChat App's Auth Key | ```javascript const appId = "APP_ID"; // Replace with your App ID const region = "REGION"; // Replace with your Region ("us", "eu", or "in") +const authKey = "AUTH_KEY"; // Replace with your Auth Key (optional) const callAppSettings = { appId: appId, region: region, + authKey: authKey, }; const result = await CometChatCalls.init(callAppSettings); @@ -68,39 +71,3 @@ The `init()` method returns an object with: | `success` | Boolean | `true` if initialization succeeded | | `error` | Object \| null | Error details if initialization failed | -## Browser Requirements - -The Calls SDK requires a modern browser with WebRTC support: - -| Browser | Minimum Version | -|---------|-----------------| -| Chrome | 72+ | -| Firefox | 68+ | -| Safari | 12.1+ | -| Edge | 79+ | - - -HTTPS is required for camera and microphone access in production. Localhost is exempt from this requirement during development. - - -## Permissions - -The browser will prompt users for camera and microphone permissions when joining a call. Ensure your application handles permission denials gracefully. - -```javascript -// Check if permissions are granted -async function checkMediaPermissions() { - try { - const stream = await navigator.mediaDevices.getUserMedia({ - video: true, - audio: true - }); - stream.getTracks().forEach(track => track.stop()); - return true; - } catch (error) { - console.error("Media permissions denied:", error); - return false; - } -} -``` - diff --git a/calls/javascript/share-invite.mdx b/calls/javascript/share-invite.mdx index 7865d62a..312e4832 100644 --- a/calls/javascript/share-invite.mdx +++ b/calls/javascript/share-invite.mdx @@ -11,8 +11,8 @@ Allow participants to share call invitations with others using the share invite By default, the share invite button is hidden. To show it: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { hideShareInviteButton: false, // ... other settings }; diff --git a/calls/javascript/virtual-background.mdx b/calls/javascript/virtual-background.mdx index bae8b1da..ffc3cf91 100644 --- a/calls/javascript/virtual-background.mdx +++ b/calls/javascript/virtual-background.mdx @@ -63,8 +63,8 @@ CometChatCalls.hideVirtualBackgroundDialog(); To hide the virtual background button from the control panel: -```javascript -const callSettings = { +```typescript +const sessionSettings: SessionSettings = { hideVirtualBackgroundButton: true, // ... other settings }; diff --git a/calls/javascript/vue-integration.mdx b/calls/javascript/vue-integration.mdx index 2cd5a425..f9843b94 100644 --- a/calls/javascript/vue-integration.mdx +++ b/calls/javascript/vue-integration.mdx @@ -3,15 +3,12 @@ title: "Vue Integration" sidebarTitle: "Vue" --- -This guide walks you through integrating the CometChat Calls SDK into a Vue.js application. By the end, you'll have a working video call implementation with proper state management and lifecycle handling. +This guide walks you through integrating the CometChat Calls SDK into a Vue.js application. By the end, you'll have a working video call implementation with proper lifecycle handling. ## Prerequisites -Before you begin, ensure you have: -- A CometChat account with an app created ([Sign up](https://app.cometchat.com/signup)) -- Your App ID, Region, and API Key from the CometChat Dashboard +Before you begin, make sure you've completed the [prerequisites](/calls/javascript/overview#prerequisites) from the Overview page. You'll also need: - A Vue 3 project (Vite, Vue CLI, or Nuxt) -- Node.js 16+ installed ## Step 1: Install the SDK @@ -32,7 +29,7 @@ import { CometChatCalls } from "@cometchat/calls-sdk-javascript"; const APP_ID = "YOUR_APP_ID"; // Replace with your App ID const REGION = "YOUR_REGION"; // Replace with your Region (us, eu, in) -const API_KEY = "YOUR_API_KEY"; // Replace with your API Key +const AUTH_KEY = "YOUR_AUTH_KEY"; // Replace with your Auth Key // Shared state across all components const isReady = ref(false); @@ -67,7 +64,7 @@ export function useCometChatCalls() { // Step 3: Login if not already logged in if (!loggedInUser) { - loggedInUser = await CometChatCalls.login(uid, API_KEY); + loggedInUser = await CometChatCalls.login(uid, AUTH_KEY); } user.value = loggedInUser; diff --git a/calls/react-native/overview.mdx b/calls/react-native/overview.mdx index eb018fe0..bd1018e4 100644 --- a/calls/react-native/overview.mdx +++ b/calls/react-native/overview.mdx @@ -22,14 +22,13 @@ Use this Calls SDK directly only if you need custom call UI or advanced control. Before integrating the Calls SDK, ensure you have: -1. **CometChat Account**: [Sign up](https://app.cometchat.com/signup) and create an app to get your App ID, Region, and API Key +1. **CometChat Account**: [Sign up](https://app.cometchat.com/signup) and create an app to get your App ID, Region, and Auth Key 2. **CometChat Users**: Users must exist in CometChat to use calling features. For testing, create users via the [Dashboard](https://app.cometchat.com) or [REST API](/rest-api/chat-apis/users/create-user). Authentication is handled by the Calls SDK - see [Authentication](/calls/react-native/authentication) 3. **React Native Requirements**: - React Native 0.71 or later - Node.js 18 or later - iOS: Minimum iOS 13.0, Xcode 14.0+ - Android: Minimum SDK API Level 24 (Android 7.0) -4. **Permissions**: Camera and microphone permissions for video/audio calls ## Call Flow