Skip to content

Commit af2b94d

Browse files
author
janligudzinski
committed
add dedicated RealtimeSIP client
1 parent 17da42c commit af2b94d

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/realtime/api.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ use tokio_tungstenite::{
77
MaybeTlsStream, WebSocketStream,
88
};
99

10+
pub mod sip;
11+
1012
const WSS_URL: &str = "wss://api.openai.com/v1/realtime";
1113

1214
pub struct RealtimeClient {

src/realtime/api/sip.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
use super::*;
2+
3+
/// Intended for connecting to an already existing Realtime session spawned by accepting an incoming SIP call from e.g. Twilio.
4+
pub struct RealtimeSipClient {
5+
pub wss_url: String,
6+
pub api_key: String,
7+
pub call_id: String,
8+
}
9+
10+
impl RealtimeSipClient {
11+
pub fn new(api_key: String, call_id: String) -> Self {
12+
let wss_url = std::env::var("WSS_URL").unwrap_or_else(|_| WSS_URL.to_owned());
13+
Self::new_with_endpoint(wss_url, api_key, call_id)
14+
}
15+
16+
pub fn new_with_endpoint(wss_url: String, api_key: String, call_id: String) -> Self {
17+
Self {
18+
wss_url,
19+
api_key,
20+
call_id,
21+
}
22+
}
23+
24+
pub async fn connect(
25+
&self,
26+
) -> Result<
27+
(
28+
SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>,
29+
SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>,
30+
),
31+
Box<dyn std::error::Error>,
32+
> {
33+
let url = format!("{}?callId={}", self.wss_url, self.call_id);
34+
let mut request = url.into_client_request()?;
35+
let api_key = self.api_key.clone();
36+
request
37+
.headers_mut()
38+
.insert("Authorization", format!("Bearer {api_key}").parse()?);
39+
let (ws_stream, _) = connect_async(request).await?;
40+
let (write, read) = ws_stream.split();
41+
Ok((write, read))
42+
}
43+
}

0 commit comments

Comments
 (0)