BlueGit

ict rusty-teams

Files

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

transport.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
transport.rs 2.9 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 and Outlook web apps live: 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
33pub struct CdpTransport {
34 endpoint: String,
35}
36
37impl CdpTransport {
38 pub fn new(endpoint: &str) -> Self {
39 CdpTransport {
40 endpoint: endpoint.trim_end_matches('/').to_owned(),
41 }
42 }
43}
44
45impl Transport for CdpTransport {
46 fn check(&self) -> BoxFuture<'_, Result<()>> {
47 Box::pin(async move { list_targets(&self.endpoint).await.map(drop) })
48 }
49
50 fn open(&self, app: App, with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>> {
51 Box::pin(async move {
52 let targets = list_targets(&self.endpoint).await?;
53 let Some(websocket_url) = find_app_tab(&targets, app).and_then(|target| target.websocket_url.clone()) else {
54 return Ok(None);
55 };
56 open(&websocket_url, with_events).await.map(Some)
57 })
58 }
59
60 fn wake(&self, app: App) -> BoxFuture<'_, Result<()>> {
61 Box::pin(async move {
62 let targets = list_targets(&self.endpoint).await?;
63 let Some(target) = find_app_tab(&targets, app) else {
64 return Ok(());
65 };
66 let parked = app.is_park_url(&target.url);
67 let (control, _) = open(target.websocket_url.as_deref().unwrap_or_default(), false).await?;
68 if parked {
69 control.call("Page.navigate", json!({"url": app.start_url()})).await?;
70 } else {
71 control.call("Page.reload", json!({"ignoreCache": false})).await?;
72 }
73 Ok(())
74 })
75 }
76
77 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {
78 Box::pin(async move {
79 let targets = list_targets(&self.endpoint).await?;
80 Ok(Diagnosis {
81 login_pending: has_login_tab(&targets),
82 app_tab_open: App::ALL.iter().any(|&app| find_app_tab(&targets, app).is_some()),
83 })
84 })
85 }
86}