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
//! A blazingly fast media (audio/image/video) file finder
//! (almost as fast as walkdir).
//!
#![warn(missing_docs)]
#![allow(unused)]
use infer;
use std::io;
use std::path::PathBuf;
use std::sync::mpsc;
use std::sync::mpsc::Receiver;
use std::thread;
use walkdir::WalkDir;

const AUDIO: &str = "audio";
const IMAGE: &str = "image";
const VIDEO: &str = "video";

/// This struct contains the result for a single found file.
/// - `path`: The path of the found file.
/// - `mime`: The file's MIME type.
/// - `result`:
///   - _bool_:
///     - `true`: A file and a media type for it was found.
///     - `false`: A file was found, but no media
///         type could not be found for it.
///   - _io::Error_: Something went wrong while trying to figure out
///         the media type.
pub struct MediaWalkResult {
    /// The path of the found file.
    pub path: String,
    /// The file's MIME type.
    pub mime: String,
    /// - _bool_:
    ///   - `true`: A file and a media type for it was found.
    ///   - `false`: A file was found, but no media
    ///       type could not be found for it.
    /// - _io::Error_: Something went wrong while trying to figure out
    ///       the media type.
    pub result: Result<bool, io::Error>,
}

/// Start walkding through the given directory. Returns a channel of
/// MediaWalkResult structs.
///
/// # Examples
///
/// ```
/// use std::env;
/// use std::path::PathBuf;
/// use mediawalker::{start_walking, MediaWalkResult};
/// let mut resource_dir = PathBuf::new();
/// if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
///     resource_dir.push(manifest_dir);
/// }
/// let rx = start_walking(&resource_dir);
/// for received in rx {
///     match received.result {
///         Ok(result) => {
///             if result == true {
///                 println!("A good file: {}", received.path);
///             } else {
///                 println!("Unknown media type: {}", received.path);
///             }
///         }
///         Err(err) => {
///             println!("{}: {:?}", received.path, err);
///         }
///     }
/// }
pub fn start_walking(first_step: &PathBuf) -> Receiver<MediaWalkResult> {
    let (tx, rx) = mpsc::channel();

    let starter = first_step.clone();
    thread::spawn(move || {
        let walker = WalkDir::new(starter).follow_links(true).into_iter();
        for entry_result in walker {
            if let Ok(entry) = entry_result {
                if entry.file_type().is_file() {
                    if let Some(path) = entry.path().to_str() {
                        let mut walk_result = MediaWalkResult {
                            path: path.to_string(),
                            mime: "".to_string(),
                            result: Ok(true),
                        };
                        match infer::get_from_path(path.to_string()) {
                            Ok(Some(info)) => {
                                if info.mime_type().starts_with(AUDIO)
                                    || info.mime_type().starts_with(IMAGE)
                                    || info.mime_type().starts_with(VIDEO)
                                {
                                    walk_result.mime = info.mime_type().to_string();
                                    tx.send(walk_result).unwrap();
                                }
                            }
                            Ok(None) => {
                                // eprintln!("Unknown file type");
                                walk_result.result = Ok(false);
                                tx.send(walk_result).unwrap();
                            }
                            Err(e) => {
                                // eprintln!("Looks like something went wrong");
                                // eprintln!("{}", e);
                                walk_result.result = Err(e);
                                tx.send(walk_result).unwrap();
                            }
                        }
                    }
                }
            }
        }
    });
    return rx;
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;

    #[test]
    fn it_finds_the_expected_amount_of_files() {
        let mut resource_dir = PathBuf::new();
        if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
            resource_dir.push(manifest_dir);
        }
        resource_dir.push("resources");
        resource_dir.push("test");
        let mut items: Vec<String> = vec![];
        let rx = start_walking(&resource_dir);
        let mut invalid_count = 0;
        for received in rx {
            match received.result {
                Ok(result) => {
                    if result == true {
                        items.push(received.path);
                    } else {
                        println!("Unknown media type: {}", received.path);
                        invalid_count += 1;
                    }
                }
                Err(err) => {
                    println!("{}: {:?}", received.path, err);
                }
            }
        }
        // Real amount is 8 media files, but for now we accept the one Markdown file as well.
        assert_eq!(items.len(), 8);
        assert_eq!(invalid_count, 1);
    }
}