Skip to main content

lazyanki_common/
lib.rs

1use anyhow::Ok;
2use directories::BaseDirs;
3use lazyanki_anki::AnkiClient;
4use reqwest::{
5    Client,
6    header::{ACCEPT_LANGUAGE, HeaderMap, HeaderValue},
7};
8use serde::{Deserialize, Serialize};
9use std::fs;
10
11#[derive(Debug, Serialize, Deserialize)]
12pub struct Config {
13    pub languages: Languages,
14}
15
16#[derive(Debug, Serialize, Deserialize)]
17pub struct Languages {
18    pub native_lang_tag: String,
19    pub target_lang_tag: String,
20}
21
22pub fn create_config(native_lang_tag: String, target_lang_tag: String) -> anyhow::Result<()> {
23    let base_dirs = BaseDirs::new().expect("cannot found base_dirs");
24
25    let path = base_dirs.config_dir().join("lazyanki");
26    let config = Config {
27        languages: Languages {
28            native_lang_tag,
29            target_lang_tag,
30        },
31    };
32
33    if !path.exists() {
34        fs::create_dir_all(&path)?;
35        fs::write(path.join("config.toml"), toml::to_string(&config)?)?;
36        println!("✅ Config has been created successfully");
37    }
38
39    Ok(())
40}
41
42pub fn load_config() -> Option<Config> {
43    let base_dirs = BaseDirs::new().expect("cannot found base_dirs");
44    let path = base_dirs.config_dir().join("lazyanki").join("config.toml");
45
46    if !path.exists() {
47        return None;
48    }
49
50    let s = fs::read_to_string(path).unwrap();
51    let cfg: Config = toml::from_str(&s).unwrap();
52
53    Some(cfg)
54}
55
56pub async fn get_client() -> anyhow::Result<Client> {
57    let mut headers = HeaderMap::new();
58    let config = load_config().expect("config not found");
59
60    headers.insert(
61        ACCEPT_LANGUAGE,
62        HeaderValue::from_str(&config.languages.native_lang_tag)?,
63    );
64    let client = reqwest::Client::builder()
65        .default_headers(headers)
66        .build()?;
67
68    Ok(client)
69}
70
71pub async fn get_anki_client() -> anyhow::Result<AnkiClient> {
72    let client = get_client().await?;
73
74    let anki_client = AnkiClient {
75        client,
76        url: "http://localhost:8765".to_string(),
77    };
78
79    Ok(anki_client)
80}