framesmith 0.1.0

A Rust library for controlling Samsung Frame TVs over the local network
Documentation
use std::path::{Path, PathBuf};

use crate::AuthTokenStore;

pub struct FileAuthTokenStore {
    path: PathBuf,
}

impl FileAuthTokenStore {
    pub fn new(path: &Path) -> Self {
        Self {
            path: path.to_path_buf(),
        }
    }
}

impl AuthTokenStore for FileAuthTokenStore {
    async fn load_token(&self) -> Result<Option<String>, Box<dyn std::error::Error + Send + Sync>> {
        match tokio::fs::read_to_string(&self.path).await {
            Ok(contents) => {
                let token = contents.trim().to_string();
                if token.is_empty() {
                    Ok(None)
                } else {
                    Ok(Some(token))
                }
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(e.into()),
        }
    }

    async fn save_token(
        &self,
        token: &str,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        if let Some(parent) = self.path.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }
        tokio::fs::write(&self.path, token).await?;
        Ok(())
    }
}