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 connector;
26pub mod egress;
27pub mod ingress;
28pub mod room;
29pub mod sip;
30
31mod twirp_client;
32
33pub const LIVEKIT_PACKAGE: &str = "livekit";
34
35#[derive(Debug, Error)]
36pub enum ServiceError {
37    #[error("invalid environment: {0}")]
38    Env(#[from] std::env::VarError),
39    #[error("invalid access token: {0}")]
40    AccessToken(#[from] AccessTokenError),
41    #[error("twirp error: {0}")]
42    Twirp(#[from] TwirpError),
43}
44
45pub type ServiceResult<T> = Result<T, ServiceError>;
46
47struct ServiceBase {
48    api_key: String,
49    api_secret: String,
50}
51
52impl Debug for ServiceBase {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.debug_struct("ServiceBase").field("api_key", &self.api_key).finish()
55    }
56}
57
58impl ServiceBase {
59    pub fn with_api_key(api_key: &str, api_secret: &str) -> Self {
60        Self { api_key: api_key.to_owned(), api_secret: api_secret.to_owned() }
61    }
62
63    pub fn auth_header(
64        &self,
65        grants: VideoGrants,
66        sip: Option<SIPGrants>,
67    ) -> Result<HeaderMap, AccessTokenError> {
68        let mut tok =
69            AccessToken::with_api_key(&self.api_key, &self.api_secret).with_grants(grants);
70        if sip.is_some() {
71            tok = tok.with_sip_grants(sip.unwrap())
72        }
73        let token = tok.to_jwt()?;
74
75        let mut headers = HeaderMap::new();
76        headers.insert(AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {}", token)).unwrap());
77        Ok(headers)
78    }
79}