livekit_api/services/
mod.rs

1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Debug;
16
17use http::header::{HeaderMap, HeaderValue, AUTHORIZATION};
18use thiserror::Error;
19
20use crate::access_token::{AccessToken, AccessTokenError, SIPGrants, VideoGrants};
21
22pub use twirp_client::{TwirpError, TwirpErrorCode, TwirpResult};
23
24pub mod agent_dispatch;
25pub mod egress;
26pub mod ingress;
27pub mod room;
28pub mod sip;
29
30mod twirp_client;
31
32pub const LIVEKIT_PACKAGE: &str = "livekit";
33
34#[derive(Debug, Error)]
35pub enum ServiceError {
36    #[error("invalid environment: {0}")]
37    Env(#[from] std::env::VarError),
38    #[error("invalid access token: {0}")]
39    AccessToken(#[from] AccessTokenError),
40    #[error("twirp error: {0}")]
41    Twirp(#[from] TwirpError),
42}
43
44pub type ServiceResult<T> = Result<T, ServiceError>;
45
46struct ServiceBase {
47    api_key: String,
48    api_secret: String,
49}
50
51impl Debug for ServiceBase {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        f.debug_struct("ServiceBase").field("api_key", &self.api_key).finish()
54    }
55}
56
57impl ServiceBase {
58    pub fn with_api_key(api_key: &str, api_secret: &str) -> Self {
59        Self { api_key: api_key.to_owned(), api_secret: api_secret.to_owned() }
60    }
61
62    pub fn auth_header(
63        &self,
64        grants: VideoGrants,
65        sip: Option<SIPGrants>,
66    ) -> Result<HeaderMap, AccessTokenError> {
67        let mut tok =
68            AccessToken::with_api_key(&self.api_key, &self.api_secret).with_grants(grants);
69        if sip.is_some() {
70            tok = tok.with_sip_grants(sip.unwrap())
71        }
72        let token = tok.to_jwt()?;
73
74        let mut headers = HeaderMap::new();
75        headers.insert(AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {}", token)).unwrap());
76        Ok(headers)
77    }
78}