BlueGit

ict rusty-teams

Files

rusty-teams / crates / session / src / transport.rs

transport.rs

transport.rs 3.1 KiB Download Raw
1use std::future::Future;
2use std::pin::Pin;
3
4use serde_json::json;
5
6use crate::app::{App, find_app_tab, has_login_tab};
7use crate::error::Result;
8use crate::events::{TabControl, TabEvents, open};
9use crate::http::list_targets;
10
11pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
12pub type OpenedTab = (TabControl, Option<TabEvents>);
13
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
15pub struct Diagnosis {
16 pub login_pending: bool,
17 pub app_tab_open: bool,
18}
19
20/// Where the signed-in Teams web app lives: a debug port or an embedded webview.
21pub trait Transport: Send + Sync {
22 fn check(&self) -> BoxFuture<'_, Result<()>>;
23
24 /// `None` when the app has no tab. Without `with_events` the tab's protocol events are dropped.
25 fn open(&self, app: App, with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>>;
26
27 /// Reloads the app so it fetches tokens again.
28 fn wake(&self, app: App) -> BoxFuture<'_, Result<()>>;
29
30 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>>;
31
32 /// While held the host must not navigate the app on its own (no parking).
33 fn hold(&self, _app: App, _held: bool) {}
34}
35
36pub struct CdpTransport {
37 endpoint: String,
38}
39
40impl CdpTransport {
41 pub fn new(endpoint: &str) -> Self {
42 CdpTransport {
43 endpoint: endpoint.trim_end_matches('/').to_owned(),
44 }
45 }
46}
47
48impl Transport for CdpTransport {
49 fn check(&self) -> BoxFuture<'_, Result<()>> {
50 Box::pin(async move { list_targets(&self.endpoint).await.map(drop) })
51 }
52
53 fn open(&self, app: App, with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>> {
54 Box::pin(async move {
55 let targets = list_targets(&self.endpoint).await?;
56 let Some(websocket_url) =
57 find_app_tab(&targets, app).and_then(|target| target.websocket_url.clone())
58 else {
59 return Ok(None);
60 };
61 open(&websocket_url, with_events).await.map(Some)
62 })
63 }
64
65 fn wake(&self, app: App) -> BoxFuture<'_, Result<()>> {
66 Box::pin(async move {
67 let targets = list_targets(&self.endpoint).await?;
68 let Some(target) = find_app_tab(&targets, app) else {
69 return Ok(());
70 };
71 let parked = app.is_park_url(&target.url);
72 let (control, _) =
73 open(target.websocket_url.as_deref().unwrap_or_default(), false).await?;
74 if parked {
75 control
76 .call("Page.navigate", json!({"url": app.start_url()}))
77 .await?;
78 } else {
79 control
80 .call("Page.reload", json!({"ignoreCache": false}))
81 .await?;
82 }
83 Ok(())
84 })
85 }
86
87 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {
88 Box::pin(async move {
89 let targets = list_targets(&self.endpoint).await?;
90 Ok(Diagnosis {
91 login_pending: has_login_tab(&targets),
92 app_tab_open: App::ALL
93 .iter()
94 .any(|&app| find_app_tab(&targets, app).is_some()),
95 })
96 })
97 }
98}