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