dango-core 0.1.1

A music backend that manages storage, querying, and playback of remote and local songs.
Documentation
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use file_format::{FileFormat, Kind};
use serde::Deserialize;
use lofty::{Accessor, AudioFile, Probe, TaggedFileExt, ItemKey, ItemValue, TagType};
use rusqlite::{params, Connection};
use cue::{cd_text::PTI, cd::CD};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
use time::Date;
use walkdir::WalkDir;

use crate::music_controller::config::Config;

#[derive(Debug)]
pub struct Song {
    pub path: Box<Path>,
    pub title:  Option<String>,
    pub album:  Option<String>,
    tracknum: Option<usize>,
    pub artist: Option<String>,
    date:   Option<Date>,
    genre:  Option<String>,
    plays:  Option<usize>,
    favorited: Option<bool>,
    format: Option<FileFormat>, // TODO: Make this a proper FileFormat eventually
    duration: Option<Duration>,
    pub custom_tags: Option<Vec<Tag>>,
}
#[derive(Clone)]
pub enum URI{
    Local(String),
    Remote(Service, String),
}

#[derive(Clone, Copy)]
pub enum Service {
    InternetRadio,
    Spotify,
    Youtube,
}

#[derive(Debug)]
pub struct Playlist {
    title: String,
    cover_art: Box<Path>,
}

pub fn create_db() -> Result<(), rusqlite::Error> {
    let path = "./music_database.db3";
    let db_connection = Connection::open(path)?;

    db_connection.pragma_update(None, "synchronous", "0")?;
    db_connection.pragma_update(None, "journal_mode", "WAL")?;

    // Create the important tables
    db_connection.execute(
        "CREATE TABLE music_collection (
            song_path TEXT PRIMARY KEY,
            title   TEXT,
            album   TEXT,
            tracknum INTEGER,
            artist  TEXT,
            date    INTEGER,
            genre   TEXT,
            plays   INTEGER,
            favorited BLOB,
            format  TEXT,
            duration INTEGER
        )",
        (), // empty list of parameters.
    )?;

    db_connection.execute(
        "CREATE TABLE playlists (
            playlist_name TEXT NOT NULL,
            song_path   TEXT NOT NULL,
            FOREIGN KEY(song_path) REFERENCES music_collection(song_path)
        )",
        (), // empty list of parameters.
    )?;

    db_connection.execute(
        "CREATE TABLE custom_tags (
            song_path TEXT NOT NULL,
            tag TEXT NOT NULL,
            tag_value TEXT,
            FOREIGN KEY(song_path) REFERENCES music_collection(song_path)
        )",
        (), // empty list of parameters.
    )?;

    Ok(())
}

fn path_in_db(query_path: &Path, connection: &Connection) -> bool {
    let query_string = format!("SELECT EXISTS(SELECT 1 FROM music_collection WHERE song_path='{}')", query_path.to_string_lossy());

    let mut query_statement = connection.prepare(&query_string).unwrap();
    let mut rows = query_statement.query([]).unwrap();

    match rows.next().unwrap() {
        Some(value) => value.get::<usize, bool>(0).unwrap(),
        None => false
    }
}

/// Parse a cuesheet given a path and a directory it is located in,
/// returning a Vec of Song objects
fn parse_cuesheet(
    cuesheet_path: &Path,
    current_dir: &PathBuf
) -> Result<Vec<Song>, Box<dyn std::error::Error>>{
    let cuesheet = CD::parse_file(cuesheet_path.to_path_buf())?;

    let album = cuesheet.get_cdtext().read(PTI::Title);

    let mut song_list:Vec<Song> = vec![];

    for (index, track) in cuesheet.tracks().iter().enumerate() {
        let track_string_path = format!("{}/{}", current_dir.to_string_lossy(), track.get_filename());
        let track_path = Path::new(&track_string_path);

        if !track_path.exists() {continue};

        // Get the format as a string
        let short_format = match FileFormat::from_file(track_path) {
            Ok(fmt) => Some(fmt),
            Err(_) => None
        };

        let duration = Duration::from_secs(track.get_length().unwrap_or(-1) as u64);

        let custom_index_start = Tag::Custom{
            tag: String::from("dango_cue_index_start"),
            tag_value: track.get_index(0).unwrap_or(-1).to_string()
        };
        let custom_index_end = Tag::Custom{
            tag: String::from("dango_cue_index_end"),
            tag_value: track.get_index(0).unwrap_or(-1).to_string()
        };

        let custom_tags: Vec<Tag> = vec![custom_index_start, custom_index_end];

        let tags = track.get_cdtext();
        let cue_song = Song {
            path: track_path.into(),
            title: tags.read(PTI::Title),
            album: album.clone(),
            tracknum: Some(index + 1),
            artist: tags.read(PTI::Performer),
            date: None,
            genre: tags.read(PTI::Genre),
            plays: Some(0),
            favorited: Some(false),
            format: short_format,
            duration: Some(duration),
            custom_tags: Some(custom_tags)
        };

        song_list.push(cue_song);
    }

    Ok(song_list)
}

pub fn find_all_music(
    config: &Config,
    target_path: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let db_connection = Connection::open(&*config.db_path)?;

    db_connection.pragma_update(None, "synchronous", "0")?;
    db_connection.pragma_update(None, "journal_mode", "WAL")?;

    let mut current_dir = PathBuf::new();
    for entry in WalkDir::new(target_path).follow_links(true).into_iter().filter_map(|e| e.ok()) {
        let target_file = entry;
        let is_file = fs::metadata(target_file.path())?.is_file();

        // Ensure the target is a file and not a directory, if it isn't, skip this loop
        if !is_file {
            current_dir = target_file.into_path();
            continue;
        }

        let format = FileFormat::from_file(target_file.path())?;
        let extension = target_file
            .path()
            .extension()
            .expect("Could not find file extension");

        // If it's a normal file, add it to the database
        // if it's a cuesheet, do a bunch of fancy stuff
        if format.kind() == Kind::Audio {
            add_file_to_db(target_file.path(), &db_connection)
        } else if extension.to_ascii_lowercase() == "cue" {
            // TODO: implement cuesheet support
            parse_cuesheet(target_file.path(), &current_dir);
        }
    }

    // create the indexes after all the data is inserted
    db_connection.execute(
        "CREATE INDEX path_index ON music_collection (song_path)", ()
    )?;

    db_connection.execute(
        "CREATE INDEX custom_tags_index ON custom_tags (song_path)", ()
    )?;

    Ok(())
}

pub fn add_file_to_db(target_file: &Path, connection: &Connection) {
    // TODO: Fix error handling here
    let tagged_file = match lofty::read_from_path(target_file) {
        Ok(tagged_file) => tagged_file,

        Err(_) => match Probe::open(target_file)
            .expect("ERROR: Bad path provided!")
            .read() {
                Ok(tagged_file) => tagged_file,

                Err(_) => return
            }
    };

    // Ensure the tags exist, if not, insert blank data
    let blank_tag = &lofty::Tag::new(TagType::Id3v2);
    let tag = match tagged_file.primary_tag() {
        Some(primary_tag) => primary_tag,

        None => match tagged_file.first_tag() {
            Some(first_tag) => first_tag,
            None => blank_tag
        },
    };

    let mut custom_insert = String::new();
    let mut loops = 0;
    for item in tag.items() {
        let mut custom_key = String::new();
        match item.key() {
            ItemKey::TrackArtist |
            ItemKey::TrackTitle  |
            ItemKey::AlbumTitle  |
            ItemKey::Genre       |
            ItemKey::TrackNumber |
            ItemKey::Year        |
            ItemKey::RecordingDate  => continue,
            ItemKey::Unknown(unknown) => custom_key.push_str(&unknown),
            custom => custom_key.push_str(&format!("{:?}", custom))
            // TODO: This is kind of cursed, maybe fix?
        };

        let custom_value = match item.value() {
            ItemValue::Text(value) => value,
            ItemValue::Locator(value) => value,
            ItemValue::Binary(_) => ""
        };

        if loops > 0 {
            custom_insert.push_str(", ");
        }

        custom_insert.push_str(&format!(" (?1, '{}', '{}')", custom_key.replace("\'", "''"), custom_value.replace("\'", "''")));

        loops += 1;
    }
    
    // Get the format as a string
    let short_format: Option<String> = match FileFormat::from_file(target_file) {
        Ok(fmt) => Some(fmt.to_string()),
        Err(_) => None
    };

    println!("{}", short_format.as_ref().unwrap());
    
    let duration = tagged_file.properties().duration().as_secs().to_string();
    
    // TODO: Fix error handling
    let binding = fs::canonicalize(target_file).unwrap();
    let abs_path = binding.to_str().unwrap();

    // Add all the info into the music_collection table
    connection.execute(
        "INSERT INTO music_collection (
            song_path,
            title,
            album,
            tracknum,
            artist,
            date,
            genre,
            plays,
            favorited,
            format,
            duration
        ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
        params![abs_path, tag.title(), tag.album(), tag.track(), tag.artist(), tag.year(), tag.genre(), 0, false, short_format, duration],
    ).unwrap();

    //TODO: Fix this, it's horrible
    if custom_insert != "" {
        connection.execute(
            &format!("INSERT INTO custom_tags ('song_path', 'tag', 'tag_value') VALUES {}", &custom_insert),
            params![
                abs_path,
            ]
        ).unwrap();
    }
}

#[derive(Debug, Deserialize)]
pub enum Tag {
    SongPath,
    Title,
    Album,
    TrackNum,
    Artist,
    Date,
    Genre,
    Plays,
    Favorited,
    Format,
    Duration,
    Custom{tag: String, tag_value: String},
}

impl Tag {
    fn as_str(&self) -> &str {
        match self {
            Tag::SongPath => "song_path",
            Tag::Title  => "title",
            Tag::Album  => "album",
            Tag::TrackNum => "tracknum",
            Tag::Artist => "artist",
            Tag::Date   => "date",
            Tag::Genre  => "genre",
            Tag::Plays  => "plays",
            Tag::Favorited => "favorited",
            Tag::Format => "format",
            Tag::Duration => "duration",
            Tag::Custom{tag, ..} => tag,
        }
    }
}

#[derive(Debug)]
pub enum MusicObject {
    Song(Song),
    Album(Playlist),
    Playlist(Playlist),
}

impl MusicObject {
    pub fn as_song(&self) -> Option<&Song> {
        match self {
            MusicObject::Song(data) => Some(data),
            _ => None
        }
    }
}

/// Query the database, returning a list of items
pub fn query(
    config: &Config,
    text_input: &String,
    queried_tags: &Vec<&Tag>,
    order_by_tags: &Vec<&Tag>,
) -> Option<Vec<MusicObject>> {
    let db_connection = Connection::open(&*config.db_path).unwrap();

    // Set up some database settings
    db_connection.pragma_update(None, "synchronous", "0").unwrap();
    db_connection.pragma_update(None, "journal_mode", "WAL").unwrap();

    // Build the "WHERE" part of the SQLite query
    let mut where_string = String::new();
    let mut loops = 0;
    for tag in queried_tags {
        if loops > 0 {
            where_string.push_str("OR ");
        }

        match tag {
            Tag::Custom{tag, ..} => where_string.push_str(&format!("custom_tags.tag = '{tag}' AND custom_tags.tag_value LIKE '{text_input}' ")),
            Tag::SongPath => where_string.push_str(&format!("music_collection.{} LIKE '{text_input}' ", tag.as_str())),
            _ => where_string.push_str(&format!("{} LIKE '{text_input}' ", tag.as_str()))
        }

        loops += 1;
    }

    // Build the "ORDER BY" part of the SQLite query
    let mut order_by_string = String::new();
    let mut loops = 0;
    for tag in order_by_tags {
        match tag {
            Tag::Custom{..} => continue,
            _ => ()
        }

        if loops > 0 {
            order_by_string.push_str(", ");
        }

        order_by_string.push_str(tag.as_str());

        loops += 1;
    }

    // Build the final query string
    let query_string = format!("
        SELECT music_collection.*, JSON_GROUP_ARRAY(JSON_OBJECT('Custom',JSON_OBJECT('tag', custom_tags.tag, 'tag_value', custom_tags.tag_value))) AS custom_tags
        FROM music_collection
        LEFT JOIN custom_tags ON music_collection.song_path = custom_tags.song_path
        WHERE {where_string}
        GROUP BY music_collection.song_path
        ORDER BY {order_by_string}
    ");
    
    let mut query_statement = db_connection.prepare(&query_string).unwrap();
    let mut rows = query_statement.query([]).unwrap();

    let mut final_result:Vec<MusicObject> = vec![];

    while let Some(row) = rows.next().unwrap() {
        let custom_tags: Vec<Tag> = match row.get::<usize, String>(11) {
            Ok(result) => serde_json::from_str(&result).unwrap_or(vec![]),
            Err(_) => vec![]
        };

        let file_format: FileFormat = FileFormat::from(row.get::<usize, String>(9).unwrap().as_bytes());

        let new_song = Song {
            // TODO: Implement proper errors here
            path:   Path::new(&row.get::<usize, String>(0).unwrap_or("".to_owned())).into(),
            title:  row.get::<usize, String>(1).ok(),
            album:  row.get::<usize, String>(2).ok(),
            tracknum: row.get::<usize, usize>(3).ok(),
            artist: row.get::<usize, String>(4).ok(),
            date:   Date::from_calendar_date(row.get::<usize, i32>(5).unwrap_or(0), time::Month::January, 1).ok(), // TODO: Fix this to get the actual date
            genre:  row.get::<usize, String>(6).ok(),
            plays:  row.get::<usize, usize>(7).ok(),
            favorited: row.get::<usize, bool>(8).ok(),
            format: Some(file_format),
            duration: Some(Duration::from_secs(row.get::<usize, u64>(10).unwrap_or(0))),
            custom_tags: Some(custom_tags),
        };

        final_result.push(MusicObject::Song(new_song));
    };

    Some(final_result)
}