summaryrefslogtreecommitdiff
path: root/src/files.rs
blob: 2b924d8d8d1124ed4b1f0e9c71e52275f16c54c3 (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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
use anyhow::{Result, anyhow};
#[cfg(not(test))]
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rayon::prelude::*;
use std::{
    error::Error,
    fmt::Display,
    path::{Path, PathBuf},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::UNIX_EPOCH,
};
use walkdir::WalkDir;

use crate::{db::Database, flac::handle_encode};

#[cfg(not(test))]
const BAR_TEMPLATE: &str = "{msg:<} [{wide_bar:.green/cyan}] Elapsed: {elapsed} {pos:>7}/{len:7}";
#[cfg(not(test))]
const SPINNER_TEMPLATE: &str = "Removed from db: {pos:.green}";

#[derive(Debug)]
pub struct FileError {
    file: PathBuf,
    error: anyhow::Error,
}

impl FileError {
    pub fn new(file: impl AsRef<Path>, error: anyhow::Error) -> Self {
        FileError {
            file: file.as_ref().to_path_buf(),
            error,
        }
    }
}

impl Display for FileError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "error: {}\ton file {}",
            self.error,
            self.file.to_string_lossy()
        )
    }
}

impl Error for FileError {}

fn handle_file(file: impl AsRef<Path>, conn: &Database) -> Result<()> {
    if conn.check_file(&file)? {
        let modtime = file
            .as_ref()
            .metadata()?
            .modified()?
            .duration_since(UNIX_EPOCH)?
            .as_secs();
        let db_modtime = conn.get_modtime(&file)?;
        if modtime != db_modtime {
            if let Err(error) = conn.update_file(&file) {
                return Err(FileError::new(&file, error).into());
            };
        }
        return Ok(());
    }

    if let Err(error) = conn.insert_file(&file) {
        return Err(FileError::new(file, error).into());
    }

    Ok(())
}

pub fn index_files_recursively(
    path: impl AsRef<Path>,
    pool: &Pool<SqliteConnectionManager>,
    handler: Arc<AtomicBool>,
) -> Result<()> {
    if !path.as_ref().is_dir() {
        return Err(anyhow!("Invalid root directory"));
    }
    let abspath = path.as_ref().canonicalize()?;

    #[cfg(not(test))]
    let bar = ProgressBar::with_draw_target(Some(0), ProgressDrawTarget::stdout_with_hz(60))
        .with_style(ProgressStyle::with_template(BAR_TEMPLATE)?.progress_chars("#>-"))
        .with_message("Indexing");

    for entry in WalkDir::new(&abspath) {
        if handler.load(Ordering::SeqCst) {
            let path = entry.unwrap().into_path();
            if !path.is_file() {
                continue;
            }
            if path.extension().is_some_and(|x| x == "flac") {
                #[cfg(not(test))]
                bar.inc_length(1);
            }
        } else {
            break;
        }
    }

    let conn = Database::new(pool.get()?);
    for entry in WalkDir::new(abspath) {
        if handler.load(Ordering::SeqCst) {
            let path = entry.unwrap().into_path();
            if !path.is_file() {
                continue;
            }
            if path.extension().is_some_and(|x| x == "flac") {
                if let Err(error) = handle_file(&path, &conn) {
                    eprintln!("{}", FileError::new(path, error));
                } else {
                    #[cfg(not(test))]
                    bar.inc(1);
                }
            }
        } else {
            break;
        }
    }

    #[cfg(not(test))]
    {
        if handler.load(Ordering::SeqCst) {
            bar.finish_with_message("Finished indexing");
        } else {
            bar.abandon_with_message("Indexing aborted");
        }
    }
    Ok(())
}

pub fn reencode_files(
    pool: &Pool<SqliteConnectionManager>,
    handler: Arc<AtomicBool>,
) -> Result<()> {
    let conn = Database::new(pool.get()?);
    #[cfg(not(test))]
    let bar = ProgressBar::with_draw_target(
        Some(conn.get_toencode_number()?),
        ProgressDrawTarget::stdout_with_hz(60),
    )
    .with_style(ProgressStyle::with_template(BAR_TEMPLATE)?.progress_chars("#>-"))
    .with_message("Reencoding");

    let files = conn.get_toencode_files()?;
    drop(conn);

    files.par_iter().for_each(|file| {
        if handler.load(Ordering::SeqCst) {
            let conn = match pool.get() {
                Ok(conn) => Database::new(conn),
                Err(error) => {
                    eprintln!("{}", FileError::new(file, error.into()));
                    return;
                }
            };

            if !file.exists() {
                let _ = conn.remove_file(file);
                return;
            }

            if let Err(error) = handle_encode(file) {
                eprintln!("{}", FileError::new(file, error));
            } else {
                if let Err(error) = conn.update_file(file) {
                    eprintln!("{}", FileError::new(file, error));
                }
                #[cfg(not(test))]
                bar.inc(1)
            }
        }
    });

    #[cfg(not(test))]
    {
        if handler.load(Ordering::SeqCst) {
            bar.finish_with_message("Finished reencoding");
        } else {
            bar.abandon_with_message("Reencoding aborted");
        }
    }
    Ok(())
}

pub fn clean_files(pool: &Pool<SqliteConnectionManager>, handler: Arc<AtomicBool>) -> Result<()> {
    let conn = Database::new(pool.get()?);
    let files = conn.init_clean_files()?;
    drop(conn);

    #[cfg(not(test))]
    let spinner = ProgressBar::with_draw_target(None, ProgressDrawTarget::stdout_with_hz(60))
        .with_style(ProgressStyle::with_template(SPINNER_TEMPLATE)?);

    files.par_iter().for_each(|file| {
        if handler.load(Ordering::SeqCst) && !file.exists() {
            let conn = match pool.get() {
                Ok(conn) => Database::new(conn),
                Err(error) => {
                    eprintln!("{}", FileError::new(file, error.into()));
                    return;
                }
            };
            if let Err(error) = conn.remove_file(file) {
                eprintln!("{}", FileError::new(file, error))
            };
            #[cfg(not(test))]
            spinner.inc(1);
        }
    });
    #[cfg(not(test))]
    spinner.finish();

    let conn = Database::new(pool.get()?);
    conn.vaccum()?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::*;

    #[test]
    fn test_index_lots_of_files() {
        let handler = Arc::new(AtomicBool::new(true));
        let pool = open_db(Some("temp3.db"), 10).unwrap();
        index_files_recursively(Path::new("./testfiles"), &pool, handler).unwrap();
        std::fs::remove_file("temp3.db").unwrap();
    }

    #[test]
    fn test_reencode_lots_of_files() {
        let handler = Arc::new(AtomicBool::new(true));
        let pool = open_db(Some("temp4.db"), 10).unwrap();
        let temp = handler.clone();
        index_files_recursively(Path::new("./testfiles"), &pool, temp).unwrap();
        let conn = Database::new(pool.get().unwrap());
        println!("\n{}", conn.get_toencode_number().unwrap());
        drop(conn);
        reencode_files(&pool, handler).unwrap();
        let conn = Database::new(pool.get().unwrap());
        println!("\n{}", conn.get_toencode_number().unwrap());
        std::fs::remove_file("temp4.db").unwrap();
    }
}