BlueGit

ict rusty-teams

Files

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

page_script.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
page_script.rs 2.6 KiB Download Raw
1use serde_json::{Value, json};
2
3use crate::app::App;
4use crate::error::{Error, Result};
5use crate::events::{TabControl, TabEvents};
6use crate::request::Outcome;
7use crate::scope::Scope;
8use crate::session::{FETCH_SCRIPT, NOT_GRANTED_PREFIX, Session};
9
10const TOKEN_MARKER: &str = "if (!token) return {noToken: true, refreshError};";
11
12impl Session {
13 /// Opens a dedicated CDP connection to the app tab. Events of the tab arrive on the stream.
14 pub async fn subscribe(&self, app: App) -> Result<(TabControl, TabEvents)> {
15 let (control, events) = self.transport.open(app, true).await?.ok_or(Error::NoAppTab)?;
16 Ok((control, events.expect("opened with events")))
17 }
18
19 /// Runs `body` inside the app tab after the token lookup of the fetch script.
20 /// `body` is an async function body that sees `token` and `args`; the token never leaves the page.
21 pub async fn run_with_token(
22 &self,
23 app: App,
24 scope: &Scope,
25 body: &str,
26 args: &Value,
27 force_refresh: bool,
28 ) -> Result<Value> {
29 let marker_at = FETCH_SCRIPT
30 .find(TOKEN_MARKER)
31 .expect("fetch.js contains the token marker");
32 let payload = json!({
33 "requests": [],
34 "resource": scope.resource,
35 "scope": scope.name,
36 "marginMs": self.config.refresh_margin.as_millis() as u64,
37 "concurrency": 1,
38 "maxBytes": 1,
39 "forceRefresh": force_refresh,
40 });
41 let script = format!(
42 "{head}{TOKEN_MARKER}\nconst args = {args};\n{body}\n}})",
43 head = &FETCH_SCRIPT[..marker_at]
44 );
45 let expression = format!("({script})({payload})");
46 let outcome = self
47 .evaluate_in(app, &expression)
48 .await?
49 .ok_or(Error::NoAppTab)?;
50 if outcome.get("noToken").and_then(Value::as_bool) == Some(true) {
51 let outcome: Outcome = serde_json::from_value(outcome)
52 .map_err(|error| Error::Cdp(format!("unexpected page answer: {error}")))?;
53 let reason = outcome.refresh_error.unwrap_or_default();
54 if reason.starts_with(NOT_GRANTED_PREFIX) {
55 return Err(Error::LoginRequired(format!("{app} app is not granted {scope}")));
56 }
57 let detail = if reason.is_empty() {
58 String::new()
59 } else {
60 format!(" (token refresh failed in {app}: {reason})")
61 };
62 return Err(Error::NoFreshToken {
63 scope: scope.to_string(),
64 detail,
65 });
66 }
67 Ok(outcome)
68 }
69}