librmo 0.4.4

A library to manage media files and play them
Documentation
use crate::app::settings::{read_config, Settings};
use crate::error::error::{CustomError, CustomError::TagErr, TagError};
use crate::media_checker::generate_album_art;
use crate::media_checker::track::{get_path_from_track, get_tracks_by_release_id};
use crate::media_tags::tags::{get_pic_bytes, get_pic_type, get_tags_from_path};
use image::imageops::FilterType;
use image::io::Reader as ImageReader;
use lofty::tag::{Accessor, ItemKey};
use std::io::Cursor;
use std::path::Path;

pub struct MusicPlayer {}

impl MusicPlayer {
    pub fn new() -> Self {
        Self {}
    }

    pub async fn generate_album_art_group_full(
        release_group_id: String,
        force: bool,
    ) -> Result<String, CustomError> {
        todo!()
    }

    pub async fn generate_album_art_group(
        release_group_id: String,
        force: bool,
    ) -> Result<String, CustomError> {
        todo!()
    }

    pub async fn generate_album_art_full(
        release_id: String,
        force: bool,
    ) -> Result<String, CustomError> {
        todo!()
    }

    /// Generates the thumbnail image for an album, uses the MusicBrainz Release
    /// Id to find the album. Stores result in `$HOME/.cache/librmo/album_art`
    /// with the filename as the release id.
    ///
    /// # Panics
    ///
    /// Panics if .
    ///
    /// # Errors
    ///
    /// This function will return an error if .
    pub async fn generate_album_art(
        release_id: String,
        force: bool,
    ) -> Result<String, CustomError> {
        // Get all tracks for this album
        let tracks = get_tracks_by_release_id(release_id.clone()).await?;
        // build the path and check if the file already exists
        let art_path =
            MusicPlayer::generate_album_art_path(release_id.clone(), String::from("album_art"));
        if Path::new(&String::from(format!("{}", art_path))).exists() && force == false {
            return Ok("Ok".to_string());
        }

        for t in tracks.iter() {
            let path = get_path_from_track(t.clone()).await?;
            let tag = get_tags_from_path(path, false).unwrap();
            match generate_album_art(&tag) {
                Ok(_) => return Ok("Ok".to_string()),
                Err(_) => continue,
            }
        }

        Err(CustomError::TagErr(TagError {
            tag_name: String::from("Cover"),
        }))
    }

    fn generate_album_art_path(release_id: String, art_subdir: String) -> String {
        let config = read_config().expect("Failed to set up application settings");
        let settings = config.try_deserialize::<Settings>().unwrap();

        String::from(format!(
            "{}/{}/{}.{}",
            settings.cache_dir, art_subdir, release_id, "jpg"
        ))
    }

    fn gen_album_art_group_by_resize(
        tag: &lofty::tag::Tag,
        size: Option<u32>,
        art_subdir: &str,
    ) -> Result<String, CustomError> {
        let config = read_config().expect("Failed to set up application settings");
        let settings = config.try_deserialize::<Settings>().unwrap();

        //Read tags from music file and get bytes
        let bytes = get_pic_bytes(tag.pictures())?;
        let file_extension = match get_pic_type(tag.pictures()) {
            Ok(x) => match x.as_str() {
                _ => "jpg",
            },
            Err(_) => {
                return Err(TagErr(TagError {
                    tag_name: "Cover".to_string(),
                }))
            }
        };

        //Create image object
        let mut img2 = ImageReader::new(Cursor::new(bytes))
            .with_guessed_format()?
            .decode()?;

        //Use resize feature if provided
        if size.is_some() {
            img2 = img2.resize(size.unwrap(), size.unwrap(), FilterType::Lanczos3);
        }

        //We use album id as unique filename
        let album_id = match tag.get_string(&ItemKey::MusicBrainzReleaseGroupId) {
            Some(x) => x.to_string(),
            None => {
                return Err(TagErr(TagError {
                    tag_name: "Cover".to_string(),
                }));
            }
        };

        img2.save(format!(
            "{}/{}/{}.{}",
            settings.cache_dir, art_subdir, album_id, file_extension
        ))
        .expect(
            String::from(format!(
                "Fault generating artwork thumb {}",
                tag.title().unwrap()
            ))
            .as_str(),
        );

        Ok("Ok".to_string())
    }

    fn gen_album_art_by_resize(
        tag: &lofty::tag::Tag,
        size: Option<u32>,
        art_subdir: &str,
    ) -> Result<String, CustomError> {
        let config = read_config().expect("Failed to set up application settings");
        let settings = config.try_deserialize::<Settings>().unwrap();

        //Read tags from music file and get bytes
        let bytes = get_pic_bytes(tag.pictures())?;
        let file_extension = match get_pic_type(tag.pictures()) {
            Ok(x) => match x.as_str() {
                _ => "jpg",
            },
            Err(_) => {
                return Err(TagErr(TagError {
                    tag_name: "Cover".to_string(),
                }))
            }
        };

        //Create image object
        let mut img2 = ImageReader::new(Cursor::new(bytes))
            .with_guessed_format()?
            .decode()?;

        //Use resize feature if provided
        if size.is_some() {
            img2 = img2.resize(size.unwrap(), size.unwrap(), FilterType::Lanczos3);
        }

        //We use album id as unique filename
        let album_id = match tag.get_string(&ItemKey::MusicBrainzReleaseGroupId) {
            Some(x) => x.to_string(),
            None => {
                return Err(TagErr(TagError {
                    tag_name: "Cover".to_string(),
                }));
            }
        };

        img2.save(format!(
            "{}/{}/{}.{}",
            settings.cache_dir, art_subdir, album_id, file_extension
        ))
        .expect(
            String::from(format!(
                "Fault generating artwork thumb {}",
                tag.title().unwrap()
            ))
            .as_str(),
        );

        Ok("Ok".to_string())
    }
}