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_tags::tags::{get_pic_bytes, get_pic_type};
use image::imageops::FilterType;
use image::io::Reader as ImageReader;
use lofty::file::{TaggedFile, TaggedFileExt};
use lofty::tag::{Accessor, ItemKey};
#[allow(unused_imports)]
use log::info;
use log::warn;
use std::io::Cursor;

pub fn regenerate_all_album_art() -> Result<String, CustomError> {
    //get all tracks
    //group by mb_release_id

    todo!()
}

pub fn generate_full_album_art_group(tag: &TaggedFile) -> Result<String, CustomError> {
    gen_album_art_group_by_resize(tag.primary_tag().unwrap(), None, "album_art_group_full")
}

pub fn generate_album_art_group(tag: &TaggedFile) -> Result<String, CustomError> {
    gen_album_art_group_by_resize(tag.primary_tag().unwrap(), Some(300), "album_art_group")
}

pub fn generate_full_album_art(tag: &TaggedFile) -> Result<String, CustomError> {
    gen_album_art_by_resize(tag.primary_tag().unwrap(), None, "album_art_full")
}

pub fn generate_album_art_by_size(tag: &TaggedFile, size: u32) -> Result<String, CustomError> {
    gen_album_art_by_resize(tag.primary_tag().unwrap(), Some(size), "album_art_full")
}

pub fn generate_album_art(tag: &TaggedFile) -> Result<String, CustomError> {
    gen_album_art_by_resize(tag.primary_tag().unwrap(), Some(300), "album_art")
}

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() {
            "image/jpeg" => "jpg",
            "image/png" => "png",
            _ => {
                return Err(TagErr(TagError {
                    tag_name: "Cover not supported".to_string(),
                }))
            }
        },
        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);
    }

    let key_to_get: ItemKey;
    //We use album id as unique filename
    if art_subdir.contains("group") {
        key_to_get = ItemKey::MusicBrainzReleaseGroupId;
    } else {
        key_to_get = ItemKey::MusicBrainzReleaseId;
    }

    let album_id = match tag.get_string(&key_to_get) {
        Some(x) => x.to_string(),
        None => {
            return Err(TagErr(TagError {
                tag_name: "Cover".to_string(),
            }));
        }
    };
    warn!(
        "gen_album_art_by_resize - {art_subdir} - {:?} - {album_id}",
        key_to_get
    );

    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())
}