UNPKG

talklynk-sdk

Version:

Official TalkLynk SDK for video calling and chat integration

437 lines (333 loc) • 10.3 kB
# TalkLynk SDK Official TypeScript/JavaScript SDK for integrating TalkLynk's video calling and chat capabilities into your applications. ## Features - šŸŽ„ **Video Calling** - High-quality WebRTC-based video calls - šŸ’¬ **Real-time Chat** - Instant messaging with typing indicators - šŸ–„ļø **Screen Sharing** - Share your screen with participants - šŸŽ™ļø **Audio Controls** - Mute/unmute functionality - šŸ“± **Mobile Ready** - Full mobile device support - šŸ”’ **Secure** - End-to-end encrypted communications - šŸ“Š **Recording** - Record video calls and conversations - šŸŽÆ **TypeScript** - Full TypeScript support with type definitions ## Installation ```bash npm install talklynk-video-sdk ``` ## Quick Start ```typescript import TalkLynkSDK from 'talklynk-video-sdk'; // Initialize the SDK const sdk = new TalkLynkSDK({ apiKey: 'your-api-key', userId: 'user-123', userName: 'John Doe', serverUrl: 'https://sdk.talklynk.com/api' // optional }); // Connect to TalkLynk servers await sdk.connect({ audio: true, video: true }); // Join a room const room = await sdk.joinRoom('room-id'); // Listen for events sdk.on('participantJoined', (participant) => { console.log('New participant:', participant); }); sdk.on('messageReceived', (message) => { console.log('New message:', message); }); // Send a message sdk.sendMessage({ type: 'text', content: 'Hello everyone!' }); ``` šŸ”— **Live Demo**: [https://sdk.talklynk.com/app](https://sdk.talklynk.com/app) šŸ“– **Integration Guide**: [INTEGRATION.md](./INTEGRATION.md) ## Configuration ### TalkLynkConfig ```typescript interface TalkLynkConfig { apiKey: string; // Your TalkLynk API key userId: string; // Unique user identifier userName: string; // Display name for the user serverUrl?: string; // Optional server URL (defaults to https://sdk.talklynk.com/api) tenantId?: string; // Optional tenant ID for multi-tenant applications pusher?: { // Optional Pusher configuration for real-time messaging key: string; // Pusher app key cluster: string; // Pusher cluster (e.g., 'us2') forceTLS?: boolean; // Force TLS (default: true) }; } ``` ## API Reference ### Core Methods #### `connect(options?: ConnectionOptions): Promise<void>` Connect to TalkLynk servers and optionally request media permissions. ```typescript await sdk.connect({ audio: true, // Request microphone access video: true, // Request camera access autoJoin: false // Automatically join last room }); ``` #### `disconnect(): void` Disconnect from TalkLynk servers and clean up resources. ```typescript sdk.disconnect(); ``` #### `createRoom(roomData: Partial<Room>): Promise<Room>` Create a new room. ```typescript const room = await sdk.createRoom({ name: 'My Meeting Room', type: 'video', settings: { maxParticipants: 10, recording: true } }); ``` #### `joinRoom(roomId: string, options?: ConnectionOptions): Promise<Room>` Join an existing room. ```typescript const room = await sdk.joinRoom('room-123', { audio: true, video: true }); ``` #### `leaveRoom(): Promise<void>` Leave the current room. ```typescript await sdk.leaveRoom(); ``` ### Media Methods #### `getUserMedia(constraints: MediaStreamConstraints): Promise<MediaStream>` Get user media (camera/microphone). ```typescript const stream = await sdk.getUserMedia({ video: true, audio: true }); ``` #### `getDisplayMedia(): Promise<MediaStream>` Start screen sharing. ```typescript const screenStream = await sdk.getDisplayMedia(); ``` #### `toggleAudio(): boolean` Toggle microphone on/off. Returns the new state. ```typescript const isEnabled = sdk.toggleAudio(); ``` #### `toggleVideo(): boolean` Toggle camera on/off. Returns the new state. ```typescript const isEnabled = sdk.toggleVideo(); ``` ### Chat Methods #### `sendMessage(message: Omit<Message, 'id' | 'timestamp' | 'userId' | 'userName'>): void` Send a message to the current room. ```typescript sdk.sendMessage({ type: 'text', content: 'Hello everyone!' }); ``` ### Recording Methods #### `startRecording(): Promise<void>` Start recording the current room. ```typescript await sdk.startRecording(); ``` #### `stopRecording(): Promise<string>` Stop recording and get the recording URL. ```typescript const recordingUrl = await sdk.stopRecording(); ``` ## Events The SDK uses an event-driven architecture. Listen for events using the `on` method: ```typescript // Connection events sdk.on('connected', () => console.log('Connected to TalkLynk')); sdk.on('disconnected', () => console.log('Disconnected from TalkLynk')); // Room events sdk.on('roomJoined', (room) => console.log('Joined room:', room)); sdk.on('roomLeft', () => console.log('Left room')); // Participant events sdk.on('participantJoined', (participant) => console.log('Participant joined:', participant)); sdk.on('participantLeft', (participant) => console.log('Participant left:', participant)); // Media events sdk.on('localStreamAvailable', (stream) => { // Attach local stream to video element const videoElement = document.getElementById('localVideo'); videoElement.srcObject = stream; }); sdk.on('remoteStreamAvailable', ({ participantId, stream }) => { // Attach remote stream to video element const videoElement = document.getElementById(`participant-${participantId}`); videoElement.srcObject = stream; }); sdk.on('audioToggled', (enabled) => console.log('Audio:', enabled ? 'enabled' : 'disabled')); sdk.on('videoToggled', (enabled) => console.log('Video:', enabled ? 'enabled' : 'disabled')); // Chat events sdk.on('messageReceived', (message) => console.log('New message:', message)); // Screen sharing events sdk.on('screenShareStarted', (stream) => console.log('Screen sharing started')); sdk.on('screenShareStopped', () => console.log('Screen sharing stopped')); // Recording events sdk.on('recordingStarted', () => console.log('Recording started')); sdk.on('recordingStopped', (recordingUrl) => console.log('Recording saved:', recordingUrl)); // Error handling sdk.on('error', (error) => console.error('SDK Error:', error)); ``` ## TypeScript Interfaces ### Room ```typescript interface Room { id: string; name: string; type: 'video' | 'audio' | 'chat'; participants: Participant[]; settings: RoomSettings; } ``` ### Participant ```typescript interface Participant { id: string; name: string; avatar?: string; isHost: boolean; isLocalUser: boolean; stream?: MediaStream; audioEnabled: boolean; videoEnabled: boolean; screenShareEnabled: boolean; } ``` ### Message ```typescript interface Message { id: string; type: 'text' | 'file' | 'system'; content: string; userId: string; userName: string; timestamp: Date; metadata?: any; } ``` ### RoomSettings ```typescript interface RoomSettings { audio: boolean; video: boolean; screenShare: boolean; chat: boolean; recording: boolean; maxParticipants: number; } ``` ## Example: React Integration ```tsx import React, { useEffect, useState } from 'react'; import TalkLynkSDK, { Participant, Message } from 'talklynk-video-sdk'; function VideoCall() { const [sdk, setSdk] = useState<TalkLynkSDK | null>(null); const [participants, setParticipants] = useState<Participant[]>([]); const [messages, setMessages] = useState<Message[]>([]); const [localStream, setLocalStream] = useState<MediaStream | null>(null); useEffect(() => { const initSDK = async () => { const newSdk = new TalkLynkSDK({ apiKey: 'your-api-key', userId: 'user-123', userName: 'John Doe' }); // Set up event listeners newSdk.on('localStreamAvailable', setLocalStream); newSdk.on('participantJoined', (participant) => { setParticipants(prev => [...prev, participant]); }); newSdk.on('messageReceived', (message) => { setMessages(prev => [...prev, message]); }); await newSdk.connect({ audio: true, video: true }); await newSdk.joinRoom('room-123'); setSdk(newSdk); }; initSDK(); return () => { sdk?.disconnect(); }; }, []); return ( <div> {/* Local video */} {localStream && ( <video ref={(el) => { if (el) el.srcObject = localStream; }} autoPlay muted playsInline /> )} {/* Remote participants */} {participants.map(participant => ( <div key={participant.id}> {participant.stream && ( <video ref={(el) => { if (el) el.srcObject = participant.stream; }} autoPlay playsInline /> )} <p>{participant.name}</p> </div> ))} {/* Controls */} <button onClick={() => sdk?.toggleAudio()}>Toggle Audio</button> <button onClick={() => sdk?.toggleVideo()}>Toggle Video</button> <button onClick={() => sdk?.leaveRoom()}>Leave Room</button> </div> ); } ``` ## Error Handling The SDK provides comprehensive error handling through the `error` event: ```typescript sdk.on('error', (errorData) => { switch (errorData.type) { case 'connection': console.error('Connection error:', errorData.error); break; case 'media': console.error('Media access error:', errorData.error); break; case 'socket': console.error('Socket error:', errorData.error); break; case 'screenshare': console.error('Screen share error:', errorData.error); break; default: console.error('Unknown error:', errorData.error); } }); ``` ## Browser Support - Chrome 70+ - Firefox 70+ - Safari 14+ - Edge 80+ ## Requirements - Node.js 16+ - Modern browser with WebRTC support - HTTPS (required for media access) ## Getting Your API Key 1. Visit the [TalkLynk Client Portal](https://client.talklynk.com) 2. Create an account or sign in 3. Navigate to API Keys section 4. Generate a new API key for your application ## Support - šŸ“§ Email: support@talklynk.com - šŸ“– Documentation: https://docs.talklynk.com - šŸ› Issues: https://github.com/talklynk/sdk/issues ## License MIT License - see LICENSE file for details.