use std::sync::Arc; use axum::{ extract::State, response::{IntoResponse, Redirect, Response}, }; use axum_extra::extract::CookieJar; use chrono::{DateTime, Utc}; use reqwest::Client; use serde::{Deserialize, Serialize}; use crate::{ plex::plex_storage::{PlexCredentials, PlexStorage}, session::user_storage::UserSessionStorage, web_context::AppConfig, webhooks::storage::WebhookStorage, }; use anyhow::{Context, Result}; #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] struct AuthResponse { pub id: usize, pub code: String, pub product: String, pub expires_in: usize, pub created_at: DateTime, pub expires_at: DateTime, pub auth_token: String, } async fn authenticate_pin(http_client: &Client, client_id: &str, pin: &str) -> Result { // Let token settle tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; let response_text = http_client .get(format!("https://plex.tv/api/v2/pins/{}", pin)) .header("Accept", "application/json") .header("X-Plex-Client-Identifier", client_id) .send() .await? .text() .await?; println!("{:#?}", response_text); let decoded = serde_json::from_str::(&response_text)?; Ok(decoded.auth_token) } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct UserInfo { pub id: usize, pub uuid: String, pub username: String, pub title: String, pub email: String, pub friendly_name: String, pub roles: Vec, } async fn get_user_info( http_client: &Client, app_config: &AppConfig, auth_token: &str, ) -> Result { http_client .get("https://plex.tv/api/v2/user") .header("Accept", "application/json") .header("X-Plex-Client-Identifier", &app_config.plex_client_id) .header("X-Plex-Product", &app_config.plex_product_name) .header("X-Plex-Token", auth_token) .send() .await? .json() .await .with_context(|| "Error parsing json") } pub async fn handle_callback( State(http_client): State, State(user_storage): State>, State(webhook_storage): State>, State(plex_storage): State>, State(app_config): State>, cookie_jar: CookieJar, ) -> Response { if let Some(session_cookie) = cookie_jar.get("session_id") && let session_id = session_cookie.value() && let Ok(Some(session)) = user_storage.get_session_by_id(session_id).await && let Ok(Some(_)) = webhook_storage.get_webhook_by_did(&session.did).await && let Ok(Some(plex_oauth_request)) = plex_storage.get_oauth_request_by_did(&session.did).await { let auth_result = authenticate_pin( &http_client, &app_config.plex_client_id, &plex_oauth_request.oauth_pin, ) .await; if auth_result.is_err() { return format!("{:#?}", auth_result).into_response(); } let auth_token = auth_result.unwrap(); let user_info_result = get_user_info(&http_client, &app_config, &auth_token).await; if user_info_result.is_err() { return format!("{:#?}", user_info_result).into_response(); } let user_info = user_info_result.unwrap(); let user_id = user_info.id.to_string(); let credentials_res = plex_storage .insert_credentials(&PlexCredentials { user_id: user_id.clone(), user_name: user_info.username, did: session.did.clone(), created_at: Utc::now(), }) .await; if credentials_res.is_err() { println!("Error inserting plex info: {:#?}", credentials_res) }; let link_res = webhook_storage.link_plex_id(&session.did, &user_id).await; if link_res.is_err() { println!("Error linking plex id: {:#?}", link_res); } } Redirect::to("/").into_response() }