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

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

/*
    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!("FUCK to many tags {}", tags.len())
        }

        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!("WARN: 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 {
                println!("⚠️  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 music_dir = fs::read_dir("/home/jp3/Music").unwrap();

    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());
        }
    }
}
Software created with 💖