### Complete Example: Agent Worker Setup Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/agent-utilities.md A full example demonstrating agent worker setup, including deployment validation and token generation. The agent is configured with specific permissions and metadata. ```go package main import ( "context" "log" "github.com/livekit/protocol/agent" "github.com/livekit/protocol/livekit" ) func main() { // Validate deployment before creating token deployment := "agent-v2.1" if err := agent.ValidateDeployment(deployment); err != nil { log.Fatal("Invalid deployment:", err) } // Generate token for agent permissions := &livekit.ParticipantPermission{ CanSubscribe: true, CanPublish: true, CanPublishData: true, Hidden: true, // Agent is hidden from participant lists } token, err := agent.BuildAgentToken( "my-api-key", "my-api-secret", "my-room", "agent-"+deployment, "LiveKit Assistant", `{"deployment":"agent-v2.1","version":"2.1"}`, map[string]string{ "deployment": deployment, "region": "us-west-2", }, permissions, ) if err != nil { log.Fatal("Token generation failed:", err) } log.Println("Agent token generated successfully") log.Printf("Token: %s", token) // Token can now be used in SDK to connect // livekit.ConnectOptions{ // AutoSubscribe: true, // Token: token, // } } ``` -------------------------------- ### Complete Webhook Notifier Example Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/webhook-notifier.md Demonstrates how to set up and use the webhook notifier to send a room started event. Includes custom key provider implementation and webhook processing callback. ```go package main import ( "context" "log" "github.com/livekit/protocol/auth" "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/webhook" ) type KeyProvider struct { secrets map[string]string } func (p *KeyProvider) GetSecret(key string) string { return p.secrets[key] } func (p *KeyProvider) NumKeys() int { return len(p.secrets) } func main() { kp := &KeyProvider{ secrets: map[string]string{ "my-api-key": "my-api-secret", }, } config := webhook.WebHookConfig{ URLs: []string{"https://myapp.example.com/livekit-webhooks"}, APIKey: "my-api-key", } notifier, err := webhook.NewDefaultNotifier(config, kp) if err != nil { log.Fatal(err) } defer notifier.Stop(false) // Register callback to log delivered webhooks notifier.RegisterProcessedHook(func(ctx context.Context, whi *livekit.WebhookInfo) { log.Printf("Webhook delivered: %s", whi.Url) }) // Send a room started event event := &livekit.WebhookEvent{ Event: webhook.EventRoomStarted, Room: &livekit.Room{ Sid: "room-123", Name: "my-room", }, CreatedAt: 1234567890, } err = notifier.QueueNotify(context.Background(), event) if err != nil { log.Println("Queue error:", err) } } ``` -------------------------------- ### Install LiveKit Protocol (JavaScript/TypeScript) Source: https://github.com/livekit/protocol/blob/main/_autodocs/quick-start.md Install the protocol package using npm. ```bash npm install @livekit/protocol ``` -------------------------------- ### List Rooms Request Example Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/room-service.md Example of listing all active rooms on the server. This operation requires the `roomList` grant. ```go // response, err := client.ListRooms(ctx, &livekit.ListRoomsRequest{}) // All rooms returned as Room objects ``` -------------------------------- ### Get Participant Request Example Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/room-service.md Example of retrieving detailed information about a specific participant within a room. Requires the `roomAdmin` grant for the room. ```go req := &livekit.RoomParticipantIdentity{ Room: "conference-room-1", Identity: "user-123", } // response, err := client.GetParticipant(ctx, req) // response contains full participant details including tracks ``` -------------------------------- ### List Participants Request Example Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/room-service.md Example of listing all participants currently in a specific room. Requires the `roomAdmin` grant for the target room. ```go req := &livekit.ListParticipantsRequest{ Room: "conference-room-1", } // response, err := client.ListParticipants(ctx, req) // response.Participants contains all active participants ``` -------------------------------- ### Install LiveKit Protocol (Go) Source: https://github.com/livekit/protocol/blob/main/_autodocs/quick-start.md Add the protocol dependency to your go.mod file. ```bash go get github.com/livekit/protocol ``` -------------------------------- ### Ingress Setup Source: https://github.com/livekit/protocol/blob/main/_autodocs/GENERATION_SUMMARY.txt Configure and manage ingress streams for ingesting media into LiveKit rooms. ```APIDOC ## Ingress Setup ### Description Configures and manages the ingestion of media streams into LiveKit rooms from external sources. ### Method POST ### Endpoint `/ingress/start` ### Request Body - **type** (string) - Required - Type of ingress (e.g., `rtmp`, `webrtc`). - **room_name** (string) - Optional - The name of the room to join. If not provided, a new room will be created. - **url** (string) - Required if type is `rtmp` - The RTMP ingest URL. - **participant_name** (string) - Optional - Name for the participant joining the room. ### Request Example ```json { "type": "rtmp", "room_name": "my-meeting-room", "url": "rtmp://localhost/live/stream1" } ``` ### Response #### Success Response (200) - **ingress_id** (string) - Unique identifier for the ingress operation. - **url** (string) - The ingest URL provided to the source. #### Response Example ```json { "ingress_id": "ingressABC", "url": "rtmp://ingress.livekit.io/app/ingressABC?token=..." } ``` ``` -------------------------------- ### Create Room Request Example Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/room-service.md Example of creating a room with specified configurations like name, empty timeout, and maximum participants. Requires an API client with a JWT token. ```go req := &livekit.CreateRoomRequest{ Name: "conference-room-1", EmptyTimeout: 600, MaxParticipants: 50, Metadata: `{"topic":"Q1-planning"}`, } // Requires API client with JWT token // response, err := client.CreateRoom(ctx, req) ``` -------------------------------- ### Example: Validate Deployment Identifier Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/agent-utilities.md Shows examples of validating deployment identifiers, including valid cases (short strings, empty string) and invalid cases (exceeding length, containing underscores). ```go // Valid err := agent.ValidateDeployment("prod-v2.1") // err == nil // Invalid: contains underscore err = agent.ValidateDeployment("prod_v2") // err != nil: "deployment contains reserved character '_'" // Invalid: exceeds length longName := strings.Repeat("a", 65) er r= agent.ValidateDeployment(longName) // err != nil: "deployment exceeds 64 bytes" // Valid: empty is allowed er r= agent.ValidateDeployment("") // err == nil ``` -------------------------------- ### Example: Build Agent Token Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/agent-utilities.md Demonstrates how to construct an agent token with specified permissions, metadata, and attributes. Ensure the token is used within an hour of generation. ```go permissions := &livekit.ParticipantPermission{ CanSubscribe: true, CanPublish: true, CanPublishData: true, } token, err := agent.BuildAgentToken( "my-api-key", "my-api-secret", "my-room", "agent-worker-1", "AI Agent", `{"version":"1.0"}`, map[string]string{"deployment": "prod"}, permissions, ) if err != nil { log.Fatal(err) } // token can now be used to connect to LiveKit ``` -------------------------------- ### Start Recording (Egress) Source: https://github.com/livekit/protocol/blob/main/_autodocs/quick-start.md Begin recording a room using the Egress.StartEgress RPC. This requires a token with roomRecord permission. ```APIDOC ## Start Recording (Egress) Begin recording a room. ### Method POST ### Endpoint (Endpoint not explicitly provided, but implied to be an Egress RPC) ### Request Body - **room_name** (string) - Required - The name of the room to record. - **preset** (livekit.EncodingOptionsPreset) - Required - The encoding preset for the recording (e.g., H264_720P_30). - **outputs** (Array of livekit.Output) - Required - Configuration for the recording output. - **output.file** (livekit.DirectFileOutput) - Configuration for direct file output. - **file.filepath** (string) - Required - The path where the recording file will be saved. ### Request Example ```json { "room_name": "my-room", "preset": "H264_720P_30", "outputs": [ { "file": { "filepath": "/recordings/room-recording.mp4" } } ] } ``` ### Authentication A token with `roomRecord` permission is required. ### Response (Response schema not provided in source) ``` -------------------------------- ### Handle Agent Deployment Validation Error Go Example Source: https://github.com/livekit/protocol/blob/main/_autodocs/errors.md Example of how to use the ValidateDeployment function and handle potential errors. It checks for validation errors and logs a fatal message if the deployment is invalid. ```go deployment := "my-agent-v1" if err := agent.ValidateDeployment(deployment); err != nil { log.Fatal("Invalid deployment:", err) } ``` -------------------------------- ### Complete Room Management Example Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/room-service.md Demonstrates a complete room management workflow using the Room Service client, including creating a room, listing participants, updating participant permissions, and sending data. ```go package main import ( "context" "log" "github.com/livekit/protocol/livekit" // Import your gRPC/Twirp client ) func manageRoom(client livekit.RoomService, ctx context.Context) error { // Create room createResp, err := client.CreateRoom(ctx, &livekit.CreateRoomRequest{ Name: "meeting-1", MaxParticipants: 100, }) if err != nil { return err } log.Printf("Room created: %s", createResp.Sid) // List participants listResp, err := client.ListParticipants(ctx, &livekit.ListParticipantsRequest{ Room: "meeting-1", }) if err != nil { return err } log.Printf("Participants: %d", len(listResp.Participants)) // Update participant permission if len(listResp.Participants) > 0 { p := listResp.Participants[0] _, err := client.UpdateParticipant(ctx, &livekit.UpdateParticipantRequest{ Room: "meeting-1", Identity: p.Identity, Permission: &livekit.ParticipantPermission{ CanPublish: false, }, }) if err != nil { return err } log.Printf("Muted participant %s", p.Identity) } // Send broadcast message err = client.SendData(ctx, &livekit.SendDataRequest{ Room: "meeting-1", Data: []byte("Meeting will end in 5 minutes"), Kind: livekit.DataPacketKind_RELIABLE, }) if err != nil { return err } return nil } ``` -------------------------------- ### Usage Example: Creating a SIP Participant Token Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/sip-grant.md Demonstrates how to create a LiveKit AccessToken for a SIP participant, including setting SIP-specific grants. ```APIDOC ## Complete Example: SIP Participant Token ```go package main import ( "log" "time" "github.com/livekit/protocol/auth" "github.com/livekit/protocol/livekit" ) func CreateSIPToken(apiKey, apiSecret, sipNumber string) (string, error) { grant := &auth.SIPGrant{ Admin: true, Inbound: true, Outbound: true, CallGroup: "main-office", } token := auth.NewAccessToken(apiKey, apiSecret). SetIdentity(sipNumber). SetName("SIP Trunk: " + sipNumber). SetKind(livekit.ParticipantInfo_SIP). SetSIPGrant(grant). SetValidFor(24 * time.Hour) return token.ToJWT() } func main() { jwtToken, err := CreateSIPToken("api-key", "api-secret", "+1234567890") if err != nil { log.Fatal(err) } log.Println("SIP token:", jwtToken) } ``` ``` -------------------------------- ### Example Protobuf Service Definition Source: https://github.com/livekit/protocol/blob/main/protobufs/roomrpc/README.md Illustrates the naming convention for versioned services and messages in protobuf files. Use this pattern for defining new RPC services. ```protobuf service MyServiceV1 { rpc DoSomething(DoSomethingV1Request) returns (DoSomethingV1Response); } message DoSomethingV1Request {} message DoSomethingV1Response {} ``` -------------------------------- ### Basic SIPGrant Usage Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/sip-grant.md Example of creating a SIPGrant and embedding it within an access token for a SIP participant. ```go grant := &auth.SIPGrant{ Inbound: true, Outbound: true, CallGroup: "support-team", } token := auth.NewAccessToken(apiKey, apiSecret). SetIdentity("sip-endpoint-1"). SetKind(livekit.ParticipantInfo_SIP). SetSIPGrant(grant) jwtString, _ := token.ToJWT() ``` -------------------------------- ### Basic Webhook Configuration Source: https://github.com/livekit/protocol/blob/main/_autodocs/configuration.md Configure webhook notifications with URLs and an API key. This setup is for basic webhook integration. ```go config := webhook.WebHookConfig{ URLs: []string{ "https://myapp.example.com/webhooks", }, APIKey: "my-api-key", } notifier, err := webhook.NewDefaultNotifier(config, keyProvider) ``` -------------------------------- ### Basic Room Join with VideoGrant Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/video-grant.md Example of creating an access token for a basic room join. Sets the RoomJoin flag and specifies the room name. ```go grant := &auth.VideoGrant{ RoomJoin: true, Room: "my-room", } token := auth.NewAccessToken(apiKey, apiSecret). SetIdentity("user-1"). SetVideoGrant(grant) jwtString, _ := token.ToJWT() ``` -------------------------------- ### Delete Room Request Example Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/room-service.md Example of deleting a room by its name or SID. This action disconnects all participants in the room and requires the `roomCreate` grant. ```go req := &livekit.DeleteRoomRequest{ Room: "conference-room-1", } // client.DeleteRoom(ctx, req) ``` -------------------------------- ### Room Setup with Automatic Egress Source: https://github.com/livekit/protocol/blob/main/_autodocs/configuration.md Configure a room with automatic egress options, specifying layout and file output format (e.g., MP4 to S3). ```go roomConfig := &livekit.RoomConfiguration{ Egress: &livekit.EgressOptions{ Room: &livekit.RoomCompositeEgressRequest{ Layout: "speaker-light", FileOutput: &livekit.EncodedFileOutput{ FileType: livekit.EncodedFileOutput_MP4, S3: &livekit.S3Upload{ AccessKey: "key", Secret: "secret", Bucket: "recordings", Region: "us-west-2", }, }, }, }, } token := auth.NewAccessToken(apiKey, apiSecret). SetIdentity("user"). SetRoomConfig(roomConfig). SetAllowSensitiveCredentials(true) // Server-side only! ``` -------------------------------- ### Webhook Notification Source: https://github.com/livekit/protocol/blob/main/_autodocs/INDEX.md Guides on setting up and using the webhook notifier for event notifications. ```APIDOC ## Webhook Notification ### Description Utilities for sending event notifications via webhooks. ### Methods #### `NewDefaultNotifier(config, kp)` - **Description**: Creates a new default webhook notifier. - **Parameters**: - `config` (WebhookConfig) - Required - Configuration for the notifier. - `kp` (KeyProvider) - Required - Key provider for authentication. - **Returns**: A QueuedNotifier instance. #### `QueueNotify(ctx, event)` - **Description**: Queues a webhook event for delivery. - **Parameters**: - `ctx` (context.Context) - Required - The context for the operation. - `event` (WebhookEvent) - Required - The webhook event payload. ### Related Types - **QueuedNotifier**: The interface for queuing notifications. - **WebhookEvent**: Represents the structure of a webhook payload. ### Example Usage ```go // Assuming WebhookConfig and KeyProvider are defined elsewhere // and 'ctx' is a valid context.Context // config := webhook.WebhookConfig{ ... } // kp := webhook.NewStaticKeyProvider("SECRET") // Example KeyProvider // notifier := webhook.NewDefaultNotifier(config, kp) // Example WebhookEvent (replace with actual event construction) // event := webhook.WebhookEvent{ ... } // err := notifier.QueueNotify(ctx, event) // if err != nil { // // Handle error // } // fmt.Println("Webhook event queued.") ``` ``` -------------------------------- ### StartEgress Source: https://github.com/livekit/protocol/blob/main/_autodocs/endpoints.md Starts a new recording or stream using the Egress service. This method allows for various source types, encoding options, output configurations, and webhook settings. ```APIDOC ## POST /twirp/livekit.Egress/StartEgress ### Description Starts a new recording or stream. ### Method POST ### Endpoint /twirp/livekit.Egress/StartEgress ### Request Body - **room_name** (string) - Required - The name of the room to egress. - **source** (oneof) - Required - Specifies the source of the egress. - **template** (TemplateSource) - Use a predefined template. - **web** (WebSource) - Use a web source. - **media** (MediaSource) - Use a media source. - **encoding** (oneof) - Required - Specifies the encoding options. - **preset** (EncodingOptionsPreset) - Use a predefined encoding preset. - **advanced** (EncodingOptions) - Use advanced custom encoding options. - **outputs** (repeated Output) - Required - The list of output destinations. - **storage** (StorageConfig) - Optional - Configuration for storing the egressed data. - **webhooks** (repeated WebhookConfig) - Optional - Configuration for webhooks to notify about egress events. ### Permissions Required `roomRecord` grant ``` -------------------------------- ### Create New AccessToken Instance (Go) Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/access-token.md Instantiate a new AccessToken builder using your API key and secret. This is the starting point for creating a token. ```go token := auth.NewAccessToken(apiKey, apiSecret) ``` -------------------------------- ### Complete Token Verification Example Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/token-verifier.md This Go snippet shows how to parse, verify, and inspect grants from a JWT token. It includes a simple key provider implementation for looking up API secrets. Use this when you need to validate incoming tokens on your server. ```go package main import ( "fmt" "log" "github.com/livekit/protocol/auth" ) type SimpleKeyProvider struct { secrets map[string]string } func (p *SimpleKeyProvider) GetSecret(key string) string { return p.secrets[key] } func (p *SimpleKeyProvider) NumKeys() int { return len(p.secrets) } func main() { // Token received from client jwtString := "eyJ..." // JWT from client // Parse token to get API key verifier, err := auth.ParseAPIToken(jwtString) if err != nil { log.Fatal("Parse failed:", err) } apiKey := verifier.APIKey() identity := verifier.Identity() fmt.Printf("Token issued by key: %s, identity: %s\n", apiKey, identity) // Look up secret and verify kp := &SimpleKeyProvider{ secrets: map[string]string{ "my-api-key": "my-api-secret", }, } secret := kp.GetSecret(apiKey) _, grants, err := verifier.Verify(secret) if err != nil { log.Fatal("Token verification failed:", err) } // Token is valid, check grants if !grants.Video.RoomJoin { log.Fatal("Token does not have room join permission") } if grants.Video.Room != "" { fmt.Printf("Participant restricted to room: %s\n", grants.Video.Room) } if grants.Video.GetCanPublish() { fmt.Println("Participant can publish tracks") } fmt.Println("Token verified successfully!") } ``` -------------------------------- ### Handle Missing Authorization Header in Webhook Source: https://github.com/livekit/protocol/blob/main/_autodocs/errors.md Example of how to check for and handle a missing Authorization header in an incoming webhook request. ```go // When receiving a webhook request auth := r.Header.Get("Authorization") if auth == "" { log.Println("Webhook missing authorization header") http.Error(w, "Unauthorized", http.StatusUnauthorized) return } ``` -------------------------------- ### Get VideoGrant CanPublish Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/video-grant.md Returns whether publishing is allowed. Defaults to true if not explicitly set. ```go func (v *VideoGrant) GetCanPublish() bool ``` -------------------------------- ### Basic Video Participant Grants Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/claim-grants.md Example of creating ClaimGrants for a standard video participant. Requires setting identity, name, kind, and specific video grant options like room join, publish, and subscribe permissions. ```go grants := &auth.ClaimGrants{ Identity: "user-1", Name: "Alice", Kind: "STANDARD", Video: &auth.VideoGrant{ RoomJoin: true, CanPublish: &canPublish, CanSubscribe: &canSubscribe, }, } ``` -------------------------------- ### Multi-Grant Participant Grants Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/claim-grants.md Example demonstrating how to combine multiple grant types within a single ClaimGrants object. This includes video, observability, metadata, and custom attributes for a power user. ```go grants := &auth.ClaimGrants{ Identity: "power-user", Name: "Admin User", Kind: "STANDARD", Video: &auth.VideoGrant{ RoomJoin: true, RoomAdmin: true, RoomCreate: true, RoomList: true, CanPublish: &yes, CanSubscribe: &yes, }, Observability: &auth.ObservabilityGrant{ Admin: true, }, Metadata: `{"role":"administrator"}`, Attributes: map[string]string{ "org": "acme", "level": "10", }, } ``` -------------------------------- ### DefaultWebHookConfig Source: https://github.com/livekit/protocol/blob/main/_autodocs/configuration.md Provides the default empty webhook configuration, pre-populated with default URL notifier settings. Useful for starting with a baseline configuration. ```go var DefaultWebHookConfig = WebHookConfig{ URLNotifier: DefaultURLNotifierConfig, ResourceURLNotifier: DefaultResourceURLNotifierConfig, FilterParams: FilterParams{}, } ``` -------------------------------- ### Handle Unknown API Key in Webhook Signature Source: https://github.com/livekit/protocol/blob/main/_autodocs/errors.md Example of how to handle the ErrSecretNotFound error when verifying a webhook signature. ```go // In webhook receiver kp := &KeyProvider{...} err := verifyWebhookSignature(request, kp) if err == webhook.ErrSecretNotFound { log.Println("Unknown API key in webhook signature") http.Error(w, "Unauthorized", http.StatusUnauthorized) return } ``` -------------------------------- ### Wrap Error for Token Generation Context Go Example Source: https://github.com/livekit/protocol/blob/main/_autodocs/errors.md Shows how to wrap an error when generating a JWT token to provide additional context. This is useful for debugging by indicating the operation that failed. ```go token, err := auth.NewAccessToken(key, secret). SetIdentity("user"). SetVideoGrant(grant). ToJWT() if err != nil { return fmt.Errorf("failed to generate token: %w", err) } ``` -------------------------------- ### Set Room Configuration in Access Token Source: https://github.com/livekit/protocol/blob/main/_autodocs/configuration.md Apply room configuration, such as dispatching agents, when generating an access token. This allows participants to influence room setup upon joining. ```go config := &livekit.RoomConfiguration{ Agents: []*livekit.RoomAgentDispatch{ { Multicast: &livekit.MulticastAgentDispatch{ Topic: "my-agent-topic", }, }, }, } token := auth.NewAccessToken(apiKey, apiSecret). SetIdentity("user"). SetRoomConfig(config) ``` -------------------------------- ### SIP Participant Grants Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/claim-grants.md Example of creating ClaimGrants for a SIP participant. This involves setting the kind to SIP and configuring SIP-specific grants for inbound/outbound calls and call groups. ```go grants := &auth.ClaimGrants{ Identity: "+1234567890", Name: "SIP Trunk", Kind: "SIP", SIP: &auth.SIPGrant{ Inbound: true, Outbound: true, CallGroup: "support", }, } ``` -------------------------------- ### Get VideoGrant CanPublishSources Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/video-grant.md Returns the list of allowed TrackSources. Returns nil if all sources are allowed. ```go func (v *VideoGrant) GetCanPublishSources() []livekit.TrackSource ``` -------------------------------- ### Get VideoGrant CanSubscribe Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/video-grant.md Returns whether subscribing is allowed. Defaults to true if not explicitly set. ```go func (v *VideoGrant) GetCanSubscribe() bool ``` -------------------------------- ### Create Room Programmatically in Go Source: https://github.com/livekit/protocol/blob/main/_autodocs/quick-start.md This Go snippet demonstrates how to construct a request to create a room programmatically. It also shows how to generate a token with the necessary `roomCreate` permission. ```go package main import ( "context" "log" "github.com/livekit/protocol/auth" "github.com/livekit/protocol/livekit" ) // You would use a gRPC client to call the API // This shows the structure func main() { // Create room request createReq := &livekit.CreateRoomRequest{ Name: "my-room", EmptyTimeout: 300, // 5 minutes MaxParticipants: 100, Metadata: `{"topic":"conference"}`, } // Token with roomCreate permission token := auth.NewAccessToken("api-key", "api-secret"). SetIdentity("admin"). SetVideoGrant(&auth.VideoGrant{ RoomCreate: true, }) jwtString, _ := token.ToJWT() println("Token with roomCreate:", jwtString) // Use this token to call RoomService.CreateRoom via gRPC/HTTP } ``` -------------------------------- ### Get Participant Identity Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/token-verifier.md Retrieves the participant identity, which is stored in the 'sub' claim of the parsed token. ```go identity := verifier.Identity() fmt.Println(identity) // "user-123" ``` -------------------------------- ### Handle Invalid Webhook Signature Source: https://github.com/livekit/protocol/blob/main/_autodocs/errors.md Example of how to handle the ErrInvalidChecksum error when webhook signature verification fails. ```go err := verifyWebhookSignature(request, keyProvider) if err == webhook.ErrInvalidChecksum { log.Println("Webhook signature invalid - rejecting") http.Error(w, "Unauthorized", http.StatusUnauthorized) return } ``` -------------------------------- ### Import SIP Grant Package Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/sip-grant.md Import the necessary package to use SIPGrant. ```go import "github.com/livekit/protocol/auth" ``` -------------------------------- ### Get VideoGrant CanPublishSource Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/video-grant.md Checks if a specific TrackSource can be published. Use this to verify individual source permissions. ```go func (v *VideoGrant) GetCanPublishSource(source livekit.TrackSource) bool ``` ```go if grant.GetCanPublishSource(livekit.TrackSource_SCREEN_SHARE) { fmt.Println("Can share screen") } ``` -------------------------------- ### AccessToken Creation and Usage Source: https://github.com/livekit/protocol/blob/main/_autodocs/INDEX.md Demonstrates how to create and configure an AccessToken for authentication, including setting grants and generating the JWT. ```APIDOC ## AccessToken ### Description Used to build and sign JWT tokens for authentication with LiveKit. ### Methods #### `NewAccessToken(key, secret)` - **Description**: Creates a new AccessToken builder. - **Parameters**: - `key` (string) - Required - API key. - `secret` (string) - Required - API secret. - **Returns**: An AccessToken builder. #### `SetIdentity(id)` - **Description**: Sets the identity of the participant. - **Parameters**: - `id` (string) - Required - The unique identifier for the participant. #### `SetVideoGrant(grant)` - **Description**: Sets the video room permissions for the token. - **Parameters**: - `grant` (VideoGrant) - Required - The VideoGrant object specifying room permissions. #### `ToJWT()` - **Description**: Generates the JWT string representation of the token. - **Returns**: A JWT string. ### Related Types - **VideoGrant**: Defines permissions for video rooms. - **ClaimGrants**: Represents the claims within a JWT. ### Example Usage ```go // Assuming VideoGrant is defined elsewhere key := "API_KEY" secret := "API_SECRET" token := auth.NewAccessToken(key, secret) token.SetIdentity("user-id") // Example VideoGrant (replace with actual VideoGrant construction) videoGrant := &livekit.VideoGrant{ Room: "my-room", CanPublish: true, CanSubscribe: true, } token.SetVideoGrant(videoGrant) jwt, err := token.ToJWT() if err != nil { // Handle error } fmt.Println("Generated JWT:", jwt) ``` ``` -------------------------------- ### Get VideoGrant CanPublishData Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/video-grant.md Returns whether data publishing is allowed. Inherits from GetCanPublish() if not explicitly set. ```go func (v *VideoGrant) GetCanPublishData() bool ``` -------------------------------- ### Set Video Permissions Grant (Go) Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/access-token.md Configure permissions for video-related actions within a room, including joining, publishing, and subscribing. This requires a VideoGrant object. ```go grant := &auth.VideoGrant{ RoomJoin: true, CanPublish: &canPublish, CanSubscribe: &canSubscribe, Room: "my-room", } token.SetVideoGrant(grant) ``` -------------------------------- ### Get VideoGrant CanSubscribeMetrics Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/video-grant.md Returns whether metric subscription is allowed. Use this to check if metric subscriptions are permitted. ```go func (v *VideoGrant) GetCanSubscribeMetrics() bool ``` -------------------------------- ### Get VideoGrant CanUpdateOwnMetadata Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/video-grant.md Returns whether metadata updates are allowed. Use this to check if a participant can update their own metadata. ```go func (v *VideoGrant) GetCanUpdateOwnMetadata() bool ``` -------------------------------- ### Generate Access Token (Go) Source: https://github.com/livekit/protocol/blob/main/_autodocs/quick-start.md Create a JWT token for a participant to join a LiveKit room. Ensure you have the 'time' package imported for SetValidFor. ```go package main import ( "log" "time" "github.com/livekit/protocol/auth" ) func main() { // Generate token for video participant token := auth.NewAccessToken("api-key", "api-secret"). SetIdentity("user-123"). SetName("Alice"). SetVideoGrant(&auth.VideoGrant{ RoomJoin: true, Room: "my-room", CanPublish: &yes, CanSubscribe: &yes, }). SetValidFor(1 * time.Hour) jwtString, err := token.ToJWT() if err != nil { log.Fatal(err) } println("Token:", jwtString) // Send to client for connection } ``` -------------------------------- ### Get VideoGrant CanManageAgentSession Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/video-grant.md Returns whether agent session management is allowed. Use this to check if agent session management is permitted. ```go func (v *VideoGrant) GetCanManageAgentSession() bool ``` -------------------------------- ### Build and Verify ClaimGrants Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/claim-grants.md Demonstrates creating a ClaimGrants object, cloning it for backup, modifying the original, and verifying that the clone remains unchanged. This is useful for managing grant states and ensuring data integrity. ```go package main import ( "log" "github.com/livekit/protocol/auth" ) func main() { // Create grants can := true grants := &auth.ClaimGrants{ Identity: "user-123", Name: "Alice", Video: &auth.VideoGrant{ RoomJoin: true, CanPublish: &can, CanSubscribe: &can, Room: "my-room", }, Metadata: `{"department":"engineering"}`, } // Clone for backup backup := grants.Clone() // Modify original grants.Metadata = `{"department":"management"}` // Verify clone is unchanged log.Println("Original metadata:", grants.Metadata) log.Println("Backup metadata:", backup.Metadata) // Use in token token := auth.NewAccessToken("api-key", "api-secret") token.grant = *grants jwtString, err := token.ToJWT() if err != nil { log.Fatal(err) } log.Println("Token:", jwtString) } ``` -------------------------------- ### Configure Webhook Notifier in Go Source: https://github.com/livekit/protocol/blob/main/_autodocs/quick-start.md Set up a webhook notifier to send events to a specified URL. Requires a KeyProvider for authentication. Ensure the notifier is stopped when no longer needed. ```go package main import ( "context" "log" "github.com/livekit/protocol/webhook" "github.com/livekit/protocol/auth" ) type KeyProvider struct { secrets map[string]string } func (p *KeyProvider) GetSecret(key string) string { return p.secrets[key] } func (p *KeyProvider) NumKeys() int { return len(p.secrets) } func main() { kp := &KeyProvider{ secrets: map[string]string{ "api-key": "api-secret", }, } // Create notifier notifier, err := webhook.NewDefaultNotifier(webhook.WebHookConfig{ URLs: []string{"https://myapp.example.com/webhooks"}, APIKey: "api-key", }, kp) if err != nil { log.Fatal(err) } defer notifier.Stop(false) // Register callback for processed webhooks notifier.RegisterProcessedHook(func(ctx context.Context, whi *livekit.WebhookInfo) { log.Printf("Webhook delivered to %s", whi.Url) }) // In your application, send events: // notifier.QueueNotify(ctx, event) } ``` -------------------------------- ### Get API Key Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/token-verifier.md Retrieves the API key, which is stored in the 'iss' claim of the parsed token. This key can be used to look up the corresponding secret. ```go apiKey := verifier.APIKey() // Use this to look up the corresponding secret secret := keyProvider.GetSecret(apiKey) ``` -------------------------------- ### StartEgressRequest Structure Source: https://github.com/livekit/protocol/blob/main/_autodocs/configuration.md Defines the parameters required to initiate an egress process, such as the room name, source type, encoding options, output destinations, and storage configuration. ```protobuf message StartEgressRequest { string room_name = 1; oneof source { TemplateSource template = 2; WebSource web = 3; MediaSource media = 4; } oneof encoding { EncodingOptionsPreset preset = 5; EncodingOptions advanced = 6; } repeated Output outputs = 7; StorageConfig storage = 8; repeated WebhookConfig webhooks = 9; } ``` -------------------------------- ### CreateRoom Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/room-service.md Creates a new room with optional pre-configuration settings. Requires the `roomCreate` grant. ```APIDOC ## POST /twirp/livekit.RoomService/CreateRoom ### Description Creates a room with optional pre-configuration. ### Method POST ### Endpoint /twirp/livekit.RoomService/CreateRoom ### Authentication Requires `roomCreate` grant in video token ### Parameters #### Request Body - **Name** (string) - Required - Unique room identifier - **RoomPreset** (string) - Optional - Named configuration preset - **EmptyTimeout** (uint32) - Optional - Seconds before auto-close if empty (default: 300) - **DepartureTimeout** (uint32) - Optional - Seconds before auto-close after all leave - **MaxParticipants** (uint32) - Optional - Maximum concurrent participants (0 = unlimited) - **NodeId** (string) - Optional - Override node placement (debug only) - **Metadata** (string) - Optional - Room metadata (max size depends on server) - **Tags** (map) - Optional - Key-value search tags ### Response #### Success Response (200) - **Sid** (string) - Room SID - **Name** (string) - Room name - **CreationTimeMs** (int64) - Room creation time in milliseconds - **EmptyTimeout** (uint32) - Timeout in seconds before auto-close if empty - **DepartureTimeout** (uint32) - Timeout in seconds before auto-close after all leave - **MaxParticipants** (uint32) - Maximum concurrent participants - **Metadata** (string) - Room metadata - **NumParticipants** (uint32) - Current number of participants - **NumPublishers** (uint32) - Current number of publishers - **ActiveRecording** (bool) - Indicates if recording is active - **EnabledCodecs** ([]Codec) - List of enabled codecs ### Request Example ```go req := &livekit.CreateRoomRequest{ Name: "conference-room-1", EmptyTimeout: 600, MaxParticipants: 50, Metadata: `{\"topic\":\"Q1-planning\"}`, } // Requires API client with JWT token // response, err := client.CreateRoom(ctx, req) ``` ``` -------------------------------- ### Import Webhook Package Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/webhook-notifier.md Imports the necessary webhook package for using the notification system. ```go import "github.com/livekit/protocol/webhook" ``` -------------------------------- ### Get Current Grants from Access Token Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/access-token.md Retrieves the current grant claims associated with the access token. This allows for inspection or modification of existing grants. ```go grants := token.GetGrants() fmt.Println(grants.Identity) ``` -------------------------------- ### Encoding Options Presets Source: https://github.com/livekit/protocol/blob/main/_autodocs/configuration.md Provides a list of predefined encoding quality and codec options for egress. Use these presets for common video resolutions and frame rates. ```protobuf enum EncodingOptionsPreset { H264_720P_30 = 0; // 1280×720, 30fps, H.264 H264_1080P_30 = 1; // 1920×1080, 30fps, H.264 H264_540P_25 = 2; // 960×540, 25fps, H.264 VP8_720P_30 = 3; // VP8 codec VP8_1080P_30 = 4; // VP8 codec PORTRAIT_H264_720P_30 = 5; PORTRAIT_H264_1080P_30 = 6; } ``` -------------------------------- ### Create a New Default Notifier Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/webhook-notifier.md Initializes a new webhook notifier with specified configuration and authentication. Use this to set up the webhook sending mechanism. ```go func NewDefaultNotifier(config WebHookConfig, kp auth.KeyProvider) (QueuedNotifier, error) ``` ```go kp := &SimpleKeyProvider{...} notifier, err := webhook.NewDefaultNotifier(webhook.WebHookConfig{ URLs: []string{"https://example.com/webhooks"}, APIKey: "my-api-key", }, kp) if err != nil { log.Fatal(err) } defer notifier.Stop(false) ``` -------------------------------- ### Handle Incoming Webhooks in Go Source: https://github.com/livekit/protocol/blob/main/_autodocs/quick-start.md Create an HTTP handler to receive and process incoming webhook events. This includes verifying the signature, reading the request body, and parsing the event data. ```go package main import ( "io" "net/http" "github.com/livekit/protocol/webhook" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/types/known/structpb" "github.com/livekit/protocol/livekit" ) func webhookHandler(w http.ResponseWriter, r *http.Request) { // Verify signature auth := r.Header.Get("Authorization") if auth == "" { http.Error(w, "Missing Authorization header", http.StatusUnauthorized) return } // Read body body, _ := io.ReadAll(r.Body) defer r.Body.Close() // Parse event event := &livekit.WebhookEvent{} _ = protojson.Unmarshal(body, event) // Handle event switch event.Event { case webhook.EventRoomStarted: println("Room started:", event.Room.Name) case webhook.EventParticipantJoined: println("Participant joined:", event.Participant.Identity) case webhook.EventTrackPublished: println("Track published:", event.Track.Name) } w.WriteHeader(http.StatusOK) } ``` -------------------------------- ### Manage Rooms (Go) Source: https://github.com/livekit/protocol/blob/main/_autodocs/README.md Perform room management operations such as creation and listing participants. Requires a RoomService client. ```go client.CreateRoom(ctx, &CreateRoomRequest{Name: "my-room"}) client.ListParticipants(ctx, &ListParticipantsRequest{Room: "my-room"}) ``` -------------------------------- ### Go Imports for LiveKit Protocol Source: https://github.com/livekit/protocol/blob/main/_autodocs/overview.md Import necessary packages for authentication and webhooks in Go applications using the LiveKit protocol. ```Go import "github.com/livekit/protocol/auth" import "github.com/livekit/protocol/webhook" import "github.com/livekit/protocol/livekit" ``` -------------------------------- ### AudioConfig Configuration Source: https://github.com/livekit/protocol/blob/main/_autodocs/configuration.md Configures audio capture and routing for egress. It allows capturing all audio or selectively routing tracks based on participant identity or kind. ```protobuf message AudioConfig { bool capture_all = 1; // Capture all audio to both channels repeated AudioRoute routes = 2; // Selective routing } enum AudioChannel { AUDIO_CHANNEL_BOTH = 0; AUDIO_CHANNEL_LEFT = 1; AUDIO_CHANNEL_RIGHT = 2; } message AudioRoute { oneof match { string track_id = 1; string participant_identity = 2; ParticipantInfo.Kind participant_kind = 3; } AudioChannel channel = 4; } ``` -------------------------------- ### IngressAudioOptions Configuration Source: https://github.com/livekit/protocol/blob/main/_autodocs/configuration.md Configures audio encoding for ingress. Supports predefined presets or custom encoding options including codec, bitrate, DTX, and channels. ```protobuf message IngressAudioOptions { string name = 1; TrackSource source = 2; oneof encoding_options { IngressAudioEncodingPreset preset = 3; IngressAudioEncodingOptions options = 4; } } ``` ```protobuf enum IngressAudioEncodingPreset { OPUS_STEREO_96KBPS = 0; OPUS_MONO_64KBS = 1; } ``` ```protobuf message IngressAudioEncodingOptions { AudioCodec audio_codec = 1; uint32 bitrate = 2; bool disable_dtx = 3; uint32 channels = 4; } ``` -------------------------------- ### Agent Participant Grants Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/claim-grants.md Example of creating ClaimGrants for an agent participant. This includes setting the kind to AGENT and specifying agent-specific grants for worker and job functionalities, along with video grants. ```go grants := &auth.ClaimGrants{ Identity: "agent-worker-1", Name: "AI Assistant", Kind: "AGENT", Agent: &auth.AgentGrant{ Worker: true, Job: true, }, Video: &auth.VideoGrant{ RoomJoin: true, Agent: true, }, } ``` -------------------------------- ### ParticipantPermission Structure Source: https://github.com/livekit/protocol/blob/main/_autodocs/types.md Defines the runtime permissions for a participant in a LiveKit room. Specifies capabilities such as subscribing, publishing audio/video or data, track source restrictions, visibility, metadata updates, metrics subscription, and agent session management. ```protobuf message ParticipantPermission { bool can_subscribe = 1; bool can_publish = 2; bool can_publish_data = 3; repeated TrackSource can_publish_sources = 9; bool hidden = 7; bool can_update_metadata = 10; bool can_subscribe_metrics = 12; bool can_manage_agent_session = 13; } ``` -------------------------------- ### JWT Validation Error Type Assertion Go Example Source: https://github.com/livekit/protocol/blob/main/_autodocs/errors.md Demonstrates how to perform a type assertion to check for specific JWT validation errors using errors.As. This allows for targeted handling of JWT-related issues. ```go import "github.com/golang-jwt/jwt/v5" var ve *jwt.ValidationError if errors.As(err, &ve) { // Handle specific JWT validation error } ``` -------------------------------- ### Set Agent Framework Permissions Grant (Go) Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/access-token.md Configure permissions for using the agent framework with an AgentGrant object. ```go token.SetAgentGrant(grant) ``` -------------------------------- ### Create Agent Token (Go) Source: https://github.com/livekit/protocol/blob/main/_autodocs/README.md Build a JWT token specifically for LiveKit agents. This requires various parameters including API credentials and agent details. ```go agent.BuildAgentToken(apiKey, secret, room, identity, name, metadata, attrs, permissions) ``` -------------------------------- ### Room Creation Source: https://github.com/livekit/protocol/blob/main/_autodocs/GENERATION_SUMMARY.txt API for creating new rooms with predefined presets and managing participant lifecycles within rooms. ```APIDOC ## Room Creation ### Description Creates a new room with optional presets for configuration. Manages participant lifecycle within the room. ### Method POST ### Endpoint `/rooms` ### Request Body - **name** (string) - Optional - The name of the room. - **emptyTimeout** (number) - Optional - Timeout in seconds before an empty room is deleted. - **maxParticipants** (number) - Optional - Maximum number of participants allowed. - **creationToken** (string) - Optional - Token to use for room creation. - **preset** (string) - Optional - Predefined room configuration preset. ### Request Example ```json { "name": "my-meeting-room", "maxParticipants": 50, "preset": "default" } ``` ### Response #### Success Response (200) - **room** (object) - Details of the created room. - **sid** (string) - The unique identifier for the room. - **name** (string) - The name of the room. - **createdAt** (number) - Timestamp of room creation. #### Response Example ```json { "room": { "sid": "room123", "name": "my-meeting-room", "createdAt": 1678886400 } } ``` ``` -------------------------------- ### Define RoomConfiguration for Token Source: https://github.com/livekit/protocol/blob/main/_autodocs/configuration.md Use this struct to define configuration options that a participant can apply when creating a room via their token. It includes settings for egress and agents. ```go type RoomConfiguration struct { Egress *livekit.EgressOptions Agents []*livekit.RoomAgentDispatch } ``` -------------------------------- ### Set SIP Permissions Grant (Go) Source: https://github.com/livekit/protocol/blob/main/_autodocs/api-reference/access-token.md Configure permissions specifically for SIP participants using a SIPGrant object. ```go token.SetSIPGrant(grant) ``` -------------------------------- ### CreateRoomRequest Protocol Buffer Definition Source: https://github.com/livekit/protocol/blob/main/_autodocs/configuration.md Defines the parameters available when creating a room via the API. Includes settings for room name, presets, timeouts, participant limits, and metadata. ```protobuf message CreateRoomRequest { string name = 1; string room_preset = 12; uint32 empty_timeout = 2; uint32 departure_timeout = 10; uint32 max_participants = 3; string node_id = 4; string metadata = 5; map tags = 15; } ```