summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 78081a49eacf1689caf434936488bf8bf24b57a9 (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
use std::{env, fs::{self, File}, path::Path, io::{Error, BufReader, Read}, fmt::format, os::fd::IntoRawFd};

use lofty::{Probe, TaggedFileExt, LoftyError, TagExt, Tag, Picture, Accessor, PictureType};

use clap::Parser;

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
    /// Path to your music folder
    #[arg(short, long)]
    path: Option<String>,

    /// Print more logs while running TODO
    #[arg(short, long, default_value_t = false)]
    verbose: bool,
}

/*
    Title
    Artist - Title
    Artist - Album - Title
    Artist - Album - Nr - Title
    Artist - Album - Nr - Max Nr - Title
 */

struct InnerTag {
    title: String,
    artist: Option<String>,
    album: Option<String>,
    track: Option<u32>,
}

impl InnerTag {
    pub fn empty() -> InnerTag {
        InnerTag {title: "".into(), artist: None, album: None, track: None}
    }

    pub fn from(name: &str) -> Result<InnerTag, Error>{
        let mut inner_tag: InnerTag = InnerTag::empty();

        let mut tags: Vec<String> = Vec::new();

        { // TODO make it faster and cleaner
            let mut text: String = "".into();
            let mut connected = false;

            for s in name.split("-") {
                if text == "" {
                    text = s.into();
                } else {
                    if s == "" {
                        connected = true;
                        text += "-";
                    } else if connected {
                        text += s;
                        connected = false;
                    } else {
                        tags.push(text);
                        text = s.into();
                    }
                }
            }

            tags.push(text);
        }

        match tags.len() {
            1 => {
                inner_tag.title = tags.remove(0);
            },
            2 => {
                inner_tag.artist = Some(tags.remove(0));
                inner_tag.title = tags.remove(0);
            },
            3 => {
                inner_tag.artist = Some(tags.remove(0));
                inner_tag.album = Some(tags.remove(0));
                inner_tag.title = tags.remove(0);
            },
            4 => {
                inner_tag.artist = Some(tags.remove(0));
                inner_tag.album = Some(tags.remove(0));
                inner_tag.track = Some(tags.remove(0).parse().unwrap());
                inner_tag.title = tags.remove(0);
            },
            5 => {
                inner_tag.artist = Some(tags.remove(0));
                inner_tag.album = Some(tags.remove(0));
                inner_tag.track = Some(tags.remove(0).parse().unwrap());
                inner_tag.title = tags.remove(1);
            },
            _ => panic!("🔥 To many tags in {}", name)
        }

        return Ok(inner_tag);
    }
}

fn truncate(s: &str, min_chars: usize, max_chars: usize) -> &str {
    let e = match s.char_indices().nth(min_chars) {
        None => s,
        Some((idx, _)) => &s[idx..],
    };

    if max_chars < min_chars {
        return "";
    }

    return match e.char_indices().nth(max_chars - min_chars) {
        None => e,
        Some((idx, _)) => &e[..idx],
    }
}

fn tag_ogg_file(path: &Path) -> Result<(), LoftyError> {
	let mut tagged_file = Probe::open(path)
		.expect("ERROR: Bad path provided!")
		.read()?;

	let tag = match tagged_file.primary_tag_mut() {
		Some(primary_tag) => primary_tag,
		None => {
			if let Some(first_tag) = tagged_file.first_tag_mut() {
				first_tag
			} else {
				let tag_type = tagged_file.primary_tag_type();

				eprintln!("👻 No tags found, creating a new tag of type `{tag_type:?}`");
				tagged_file.insert_tag(Tag::new(tag_type));

				tagged_file.primary_tag_mut().unwrap()
			}
		},
	};

    let path_without_ext = path.with_extension("");
    let name = path_without_ext.file_name().unwrap().to_str().unwrap();
    let inner_tag = InnerTag::from(name).unwrap();

    tag.clear();
    tag.set_title(inner_tag.title);
    tag.set_artist(inner_tag.artist.unwrap_or("".into()));
    tag.set_album(inner_tag.album.unwrap_or("".into()));
    if let Some(track) = inner_tag.track {
        tag.set_track(track);
    }

    if let Some(album) = tag.album() {
        if album != "" {
            let image_path = path.parent().unwrap().join(format!(".cover/{}/{}.jpg", tag.artist().unwrap(), album));

            if image_path.exists() {
                let image_file = &mut File::open(image_path.clone()).unwrap();

                let mut picture = Picture::from_reader(image_file).unwrap();
                picture.set_pic_type(PictureType::CoverFront);

                tag.set_picture(0, picture)
            } else {
                eprintln!("👻 Can't found image {}", image_path.to_str().unwrap());
            }
        }
    }


    tag.save_to_path(path).expect("ERROR: Can't save ogg file");

    println!("✅  {}", name);

    return Ok(());
}

fn main() {
    let args = Args::parse();

    let music_path: String;

    if let Some(path) = args.path {
        music_path = path;
    } else if let Ok(home) = env::var("HOME") {
        println!("💡 Trying to find the music folder automatically");
        music_path = home + "/Music"
    } else {
        eprintln!("🔥 Couldn't find a music folder automatically");
        std::process::exit(1);
    }

    let music_dir: fs::ReadDir;

    if let Ok(dir) = fs::read_dir(music_path.as_str()) {
        music_dir = dir;
    } else {
        eprintln!("🔥 Dir \"{}\" doesn't exits", music_path.as_str());
        std::process::exit(1);
    }

    println!("💡 Start scanning \"{}\" dir for ogg file", music_path.as_str());

    for path in music_dir {
        // println!("Name: {}", path.unwrap().file_name().to_str().unwrap())
        if path.as_ref().unwrap().file_type().unwrap().is_file() {
            tag_ogg_file(path.unwrap().path().as_path());
        }
    }

    println!("💡 Ended successfully");
}
Software created with 💖