Use config file to store sessions

This commit is contained in:
bytedream 2023-07-13 13:51:02 +02:00
parent 9ad27102fc
commit 850aa7a969
8 changed files with 177 additions and 47 deletions

View file

@ -1,11 +1,9 @@
use crate::utils::config::Auth;
use crate::utils::context::Context;
use crate::Execute;
use anyhow::bail;
use anyhow::Result;
use clap::Parser;
use crunchyroll_rs::crunchyroll::SessionToken;
use std::fs;
use std::path::PathBuf;
#[derive(Debug, clap::Parser)]
#[clap(about = "Save your login credentials persistent on disk")]
@ -19,23 +17,14 @@ pub struct Login {
#[async_trait::async_trait(?Send)]
impl Execute for Login {
async fn execute(self, ctx: Context) -> Result<()> {
if let Some(login_file_path) = session_file_path() {
fs::create_dir_all(login_file_path.parent().unwrap())?;
match ctx.crunchy.session_token().await {
SessionToken::RefreshToken(refresh_token) => Ok(fs::write(
login_file_path,
format!("refresh_token:{}", refresh_token),
)?),
SessionToken::EtpRt(etp_rt) => {
Ok(fs::write(login_file_path, format!("etp_rt:{}", etp_rt))?)
}
SessionToken::Anonymous => bail!("Anonymous login cannot be saved"),
}
} else {
bail!("Cannot find config path")
}
async fn execute(self, mut ctx: Context) -> Result<()> {
let auth = match ctx.crunchy.session_token().await {
SessionToken::RefreshToken(token) => Auth::RefreshToken { token },
SessionToken::EtpRt(token) => Auth::EtpRt { token },
SessionToken::Anonymous => Auth::Anonymous,
};
ctx.config.auth = Some(auth);
Ok(ctx.config.write()?)
}
}
@ -56,7 +45,3 @@ pub struct LoginMethod {
#[arg(long, default_value_t = false)]
pub anonymous: bool,
}
pub fn session_file_path() -> Option<PathBuf> {
dirs::config_dir().map(|config_dir| config_dir.join("crunchy-cli").join("session"))
}