summaryrefslogtreecommitdiff
path: root/src/db.rs
blob: 742c0031adef7aa07f5ff9aec4e5e31bdd53917f (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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
use anyhow::{Result, anyhow};
use directories::BaseDirs;
use futures_util::Stream;
use libsql::{Builder, Connection, params};
use std::{
    path::Path,
    time::{Duration, UNIX_EPOCH},
};

use crate::flac::{CURRENT_VENDOR, get_vendor};

const TABLE_CREATE: &str = "CREATE TABLE IF NOT EXISTS flacs (path TEXT PRIMARY KEY, toencode BOOLEAN NOT NULL, modtime INTEGER)";
const ADD_NEW_ITEM: &str = "INSERT INTO flacs (path, toencode, modtime) VALUES (?1, ?2, ?3)";
const REPLACE_ITEM: &str = "REPLACE INTO flacs (path, toencode, modtime) VALUES (?1, ?2, ?3)";
const TOENCODE_QUERY: &str = "SELECT path FROM flacs WHERE toencode";
const CHECK_FILE: &str = "SELECT exists(SELECT 1 FROM flacs WHERE path = ?1)";
const FETCH_MODTIME: &str = "SELECT modtime FROM flacs WHERE path = ?1";
const FETCH_FILES: &str = "SELECT path FROM flacs";
const REMOVE_FILE: &str = "DELETE FROM flacs WHERE path = ?1";
const DEDUPE_DB: &str =
    "DELETE FROM flacs WHERE rowid NOT IN (SELECT MAX(rowid) FROM flacs GROUP BY path)";

#[derive(Debug, Clone)]
pub struct Database(pub Connection);

impl Database {
    pub async fn new(path: impl AsRef<Path>) -> Result<Self> {
        let conn = Builder::new_local(path).build().await?.connect()?;
        conn.execute(TABLE_CREATE, ()).await?;

        Ok(Database(conn))
    }

    pub async fn insert_file(&self, filename: impl AsRef<Path>) -> Result<()> {
        let abs_filename = filename.as_ref().canonicalize()?;
        let toencode = !matches!(get_vendor(&abs_filename)?.as_str(), CURRENT_VENDOR);

        let modtime = abs_filename
            .metadata()?
            .modified()?
            .duration_since(UNIX_EPOCH)?
            .as_secs();

        self.0
            .execute(
                ADD_NEW_ITEM,
                params![abs_filename.to_str().unwrap(), toencode, modtime],
            )
            .await?;

        Ok(())
    }

    pub async fn update_file(&self, filename: impl AsRef<Path>) -> Result<()> {
        let abs_filename = filename.as_ref().canonicalize()?;

        let modtime = abs_filename
            .metadata()?
            .modified()?
            .duration_since(UNIX_EPOCH)?
            .as_secs();

        self.0
            .execute(
                REPLACE_ITEM,
                params![abs_filename.to_str().unwrap(), false, modtime],
            )
            .await?;

        Ok(())
    }

    pub async fn check_file(&self, filename: impl AsRef<Path>) -> Result<bool> {
        let abs_filename = filename.as_ref().canonicalize()?;

        if let Some(row) = self
            .0
            .query(CHECK_FILE, params!(abs_filename.to_str().unwrap()))
            .await?
            .next()
            .await?
        {
            Ok(matches!(row.get_value(0)?, libsql::Value::Integer(1)))
        } else {
            Err(anyhow!("database error"))
        }
    }

    pub async fn get_modtime(&self, filename: impl AsRef<Path>) -> Result<u64> {
        let abs_filename = filename.as_ref().canonicalize()?;

        if let Some(row) = self
            .0
            .query(FETCH_MODTIME, params!(abs_filename.to_str().unwrap()))
            .await?
            .next()
            .await?
        {
            if let Some(sec) = row.get_value(0)?.as_integer() {
                Ok(Duration::from_secs(*sec as u64).as_secs())
            } else {
                Ok(Duration::from_secs(0).as_secs())
            }
        } else {
            Err(anyhow!("database error"))
        }
    }

    pub async fn clean_files(&self) -> Result<()> {
        let mut tasks = tokio::task::JoinSet::new();
        self.0.execute(DEDUPE_DB, ()).await?;
        let mut query_res = self.0.query(FETCH_FILES, ()).await?;
        while let Ok(Some(row)) = query_res.next().await {
            let path = Path::new(row.get_str(0)?).canonicalize()?;
            let conn = self.0.clone();
            tasks.spawn(async move {
                if !path.exists() {
                    let _ = conn
                        .execute(REMOVE_FILE, params!(path.to_str().unwrap()))
                        .await;
                }
            });
        }

        tasks.join_all().await;

        self.0.execute("VACUUM;", ()).await?;

        Ok(())
    }

    pub async fn get_toencode_stream(
        &self,
    ) -> Result<impl Stream<Item = libsql::Result<libsql::Row>>> {
        Ok(self.0.query(TOENCODE_QUERY, ()).await?.into_stream())
    }
}

pub async fn open_default_db() -> Result<Database> {
    if let Some(base_dir) = BaseDirs::new() {
        let db_name = Path::new(base_dir.data_dir()).join("reencoder.db");
        Ok(Database::new(db_name).await?)
    } else {
        Err(anyhow!("Failed to locate data directory"))
    }
}

#[cfg(test)]
mod tests {
    use futures_util::StreamExt;

    use super::*;

    #[tokio::test]
    async fn check_localfiles() {
        let dbname = String::from("temp1.db");
        let filenames = ["16bit.flac", "24bit.flac", "32bit.flac"];
        let conn = Database::new(&dbname).await.unwrap();
        for file in filenames {
            let _ = conn.insert_file(&file.to_string()).await;
        }
        let returned = conn
            .0
            .query(TOENCODE_QUERY, ())
            .await
            .unwrap()
            .into_stream();
        pin_utils::pin_mut!(returned);

        let mut counter = 0;

        while let Some(Ok(_)) = returned.next().await {
            counter += 1
        }

        std::fs::remove_file(dbname).unwrap();
        assert!(counter == 0)
    }

    #[tokio::test]
    async fn check_update() {
        let dbname = String::from("temp2.db");
        let filenames = ["16bit.flac", "24bit.flac", "32bit.flac"];
        let conn = Database::new(&dbname).await.unwrap();
        for file in filenames {
            let _ = conn.insert_file(&file.to_string()).await;
        }

        let _ = conn
            .0
            .execute(
                REPLACE_ITEM,
                params![
                    Path::new("16bit.flac")
                        .canonicalize()
                        .unwrap()
                        .to_str()
                        .unwrap(),
                    true,
                    ""
                ],
            )
            .await;

        conn.update_file(&"16bit.flac".to_string()).await.unwrap();

        let returned = conn
            .0
            .query(TOENCODE_QUERY, ())
            .await
            .unwrap()
            .into_stream();
        pin_utils::pin_mut!(returned);
        let mut counter = 0;
        while let Some(Ok(_)) = returned.next().await {
            counter += 1
        }
        std::fs::remove_file(dbname).unwrap();
        assert!(counter == 0)
    }
}