| 1 | use serde_json::{Value, json}; |
| 2 | |
| 3 | use crate::app::App; |
| 4 | use crate::error::{Error, Result}; |
| 5 | use crate::events::{TabControl, TabEvents}; |
| 6 | use crate::request::Outcome; |
| 7 | use crate::scope::Scope; |
| 8 | use crate::session::{FETCH_SCRIPT, NOT_GRANTED_PREFIX, Session}; |
| 9 | |
| 10 | const TOKEN_MARKER: &str = "if (!token) return {noToken: true, refreshError};"; |
| 11 | |
| 12 | impl 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 | } |