Something went wrong. Try again.
Teal.fm scrobbler for Plex
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138use 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<Utc>, pub expires_at: DateTime<Utc>, pub auth_token: String,}
async fn authenticate_pin(http_client: &Client, client_id: &str, pin: &str) -> Result<String> { // 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::<AuthResponse>(&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<String>,}
async fn get_user_info( http_client: &Client, app_config: &AppConfig, auth_token: &str,) -> Result<UserInfo> { 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<Client>, State(user_storage): State<Arc<dyn UserSessionStorage>>, State(webhook_storage): State<Arc<dyn WebhookStorage>>, State(plex_storage): State<Arc<dyn PlexStorage>>, State(app_config): State<Arc<AppConfig>>, 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()}