aboutsummaryrefslogtreecommitdiff
path: root/src/state.rs
blob: aae22b084d38f71da1f01dd74029f071a07ffd82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
use std::fs;

use directories::ProjectDirs;
use expanduser::expanduser;
use serde::{Deserialize, Serialize};

use crate::{albums, cli::VERSION, config::Config, intuition::Intuition, trajectory::Trajectory};

fn default_state_path() -> String {
    let name = "mood.json.zstd";
    ProjectDirs::from("qualifier", "organisation", "mood")
        .and_then(|pd| {
            pd.config_dir()
                .join(name)
                .to_str()
                .map(std::string::ToString::to_string)
        })
        .unwrap_or(format!("~/.config/mood/{name}"))
}

#[derive(Serialize, Deserialize)]
pub struct State {
    trajectory: Trajectory,
    intuition: Intuition,
    version: String,
}

impl Default for State {
    fn default() -> State {
        State {
            trajectory: Trajectory::default(),
            intuition: Intuition::default(),
            version: VERSION.to_string(),
        }
    }
}

impl State {
    pub fn next(&mut self, config: &Config) -> Option<(String, f32)> {
        let albums = albums::load(config);
        if albums.is_empty() {
            println!("Found no albums in {}", config.music_root);
            return None;
        }
        let l = albums.len();
        println!("Found {} album{}", l, if l > 1 { "s" } else { "" });

        let learning = self.trajectory.step(config.skip_window_secs);
        if let Some(ref learning) = learning {
            self.intuition.learn(learning);
        }
        if let Some((new_album, prob)) = self.intuition.sample(
            self.trajectory.slice(),
            &learning.as_ref().into(),
            &albums,
            config,
        ) {
            self.trajectory.log(&new_album);
            Some((new_album, prob))
        } else {
            None
        }
    }
}

impl State {
    pub fn try_load() -> Result<State, String> {
        expanduser(default_state_path())
            .map_err(|e| e.to_string())
            .and_then(|p| fs::read(p).map_err(|e| e.to_string()))
            .and_then(|contents| zstd::decode_all(&contents[..]).map_err(|e| e.to_string()))
            .and_then(|decompressed| {
                std::str::from_utf8(&decompressed)
                    .map(std::string::ToString::to_string)
                    .map_err(|e| e.to_string())
            })
            .and_then(|utf8| serde_json::from_str(&utf8).map_err(|e| e.to_string()))
    }

    pub fn try_save(&self) -> Result<(), String> {
        let str_path = default_state_path();
        let path = expanduser(&str_path).map_err(|e| e.to_string())?;
        _ = path.parent().map(std::fs::create_dir_all);
        let serialised = serde_json::to_string_pretty(self)
            .map_err(|e| format!("Failed to serialize state: {e}"))?;
        let compressed = zstd::encode_all(serialised.into_bytes().as_slice(), 3)
            .map_err(|e| format!("Failed to compress state: {e}"))?;
        fs::write(&path, compressed)
            .map_err(|e| format!("Failed to write state file at {str_path}: {e}"))?;
        Ok(())
    }
}

impl State {
    pub fn dump_intuition(&self) -> Result<String, String> {
        serde_json::to_string_pretty(&self.intuition).map_err(|e| e.to_string())
    }

    pub fn dump_trajectory(&self) -> Result<String, String> {
        serde_json::to_string_pretty(&self.trajectory).map_err(|e| e.to_string())
    }
}