aboutsummaryrefslogtreecommitdiff
path: root/src/state.rs
blob: 425e5d716f63ae57e48f7ea6739f4575bf8e3416 (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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use std::{collections::HashSet, fmt, fs};
use directories::ProjectDirs;
use expanduser::expanduser;
use serde::{Deserialize, Serialize};
use walkdir::WalkDir;
use zstd;

use crate::{config::Config, learner::Learner, trajectory::Trajectory};

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

#[derive(Serialize, Deserialize, Default)]
pub struct State {
    trajectory: Trajectory,
    learner: Learner,
    albums: HashSet<String>,
}

impl State {
    pub fn next(&mut self, config: &Config) -> Option<(String, f32)> {
        let learning = self.trajectory.step(config.skip_window_secs);
        if let Some(ref learning) = learning {
            self.learner.learn(learning);
        }
        if let Some((new_album, prob)) = self.learner.sample(
            self.trajectory.slice(),
            &learning.as_ref().into(),
            &self.albums,
            config,
        ) {
            self.trajectory.log(&new_album);
            Some((new_album, prob))
        } else {
            None
        }
    }
}

pub struct UpdateResult {
    added: usize,
    removed: usize,
    new_total: usize,
}

impl fmt::Display for UpdateResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "+{}/-{}, total {}", self.added, self.removed, self.new_total)
    }
}

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| bincode::deserialize(&decompressed).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 =
            bincode::serialize(self).map_err(|e| format!("Failed to serialize state: {}", e))?;
        let compressed = zstd::encode_all(serialised.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(())
    }

    pub fn update_albums(&mut self, config: &Config) -> UpdateResult {
        let roots: Vec<_> = config
            .music_roots
            .iter()
            .filter_map(|x| expanduser(x).ok().filter(|p| p.is_dir()))
            .collect();

        let mut new_albums: HashSet<String> = HashSet::new();

        for root_path in &roots {
            for entry in WalkDir::new(&root_path) {
                let entry = match entry {
                    Ok(e) if e.path().is_dir() => e,
                    _ => continue,
                };

                if !Self::contains_audio(&entry, config) {
                    continue;
                }

                if let Some(rel_str) = entry
                    .path()
                    .strip_prefix(&root_path)
                    .ok()
                    .and_then(|p| p.to_str())
                {
                    new_albums.insert(rel_str.to_string());
                }
            }
        }

        let added = new_albums.difference(&self.albums).count();
        let removed = self.albums.difference(&new_albums).count();
        self.albums.clone_from(&new_albums);

        self.trajectory.prune(&self.albums);
        self.learner.prune(&self.albums);

        UpdateResult {
            added,
            removed,
            new_total: self.albums.len(),
        }
    }

    fn contains_audio(entry: &walkdir::DirEntry, config: &Config) -> bool {
        fs::read_dir(entry.path()).ok().is_some_and(|mut entries| {
            entries.any(|e| {
                e.as_ref()
                    .is_ok_and(|entry| Self::is_audio_file(&entry.path(), config))
            })
        })
    }

    fn is_audio_file(path: &std::path::Path, config: &Config) -> bool {
        !path.is_dir()
            && path
                .extension()
                .and_then(|ext| ext.to_str())
                .map(|s| s.to_lowercase())
                .is_some_and(|ext| config.audio_exts.contains(&format!(".{ext}")))
    }
}

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

    pub fn dump_learner(&self) -> Result<String, String> {
        serde_json::to_string_pretty(&self.learner).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())
    }
}