summaryrefslogblamecommitdiff
path: root/src/commands/modification.rs
blob: ab424683c2542486cdb2d5023498ffe3f7bad8c2 (plain) (tree)
1
2
3
4
5
6
7
                                           
 



                                                                                       
                                                                                      





                                                                                                
 





                         


                                      
                      
 
 







                                         
                          

 
                                

                     
                      

                          
              

                                        
 

                                                      

                                                                                              



                                                                                  

         
 
                                                       









                                                                                            
 


                                                     




                                                                        
 
                                











                                                                       
                                
           

                                                                                                









                                                       
           






                            
                       





                                                                              


                             


                                                                


                                 
                        


                                                                              


          










                                                                                                        


                                                       


                                                                 


                               

                                           





                                          


                                                                 


                                                                                  
                                                               
 






                                                 


                                       


                          





                                                                        
                     
 

                                                    
             
 
                                          
                                                  




                                                            
                                                                      
              
                
                                                                                          
                                   

                                                              
                                          
                                                  




                                                            
                                                                      
              
         
     
 

                   
 









                                                                                           
                                                       
 
                                           
                                                                            


                                                
     






                                                                          







                                      
                                              




                                                                 
                                                                  

          
                   

 






                                                                 
                                                
 
                                                                                              
                                                                                   
 


                                                                
                                                        














                                                                                          
 


                                                                
                                                      
 
                                                      

                             
                                                                    








                                                                     




                                   
 


                                     
                     

          
 
use std::{io::Write, collections::HashMap};

use crate::{
    config::Cfg,
    db::{
        lists_get_all_ids, mods_get_id, mods_insert, mods_remove, userlist_get_all_ids,
        userlist_get_current_version, userlist_insert, userlist_remove, mods_get_info,
    },
    error::{ErrorType, MLError, MLE},
    files::{delete_version, download_versions},
    modrinth::{extract_current_version, get_raw_versions, project, projects, versions, Version},
    List,
};

#[derive(Debug, Clone)]
pub struct AddMod {
    pub id: IDSelector,
    pub set_version: bool
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IDSelector {
    ModificationID(String),
    VersionID(String),
}

#[derive(Debug, Clone)]
pub struct ProjectInfo {
    pub mod_id: String,
    pub slug: String,
    pub title: String,
    pub current_version: Option<Version>,
    pub applicable_versions: Vec<String>,
    pub download_link: String,
    pub set_version: bool,
}

//TODO fix setversion to per mod
pub async fn mod_add(
    config: Cfg,
    mods: Vec<AddMod>,
    list: List,
    direct_download: bool,
) -> MLE<()> {
    println!("Add mods to {}", list.id);
    println!("  └Add mods:");

    let mut mod_ids: Vec<(String, bool)> = Vec::new();
    let mut ver_ids: Vec<(String, bool)> = Vec::new();

    //"Sort" project ids from version ids to be able to handle them differently but in a batch
    for m in mods {
        match m.id {
            IDSelector::ModificationID(pid) => mod_ids.push((pid, m.set_version)),
            IDSelector::VersionID(vid) => ver_ids.push((vid, m.set_version)),
        }
    }

    let mut projectinfo: Vec<ProjectInfo> = Vec::new();
    if !mod_ids.is_empty() {
        projectinfo.append(&mut get_mod_infos(config.clone(), mod_ids, list.clone()).await?)
    };
    if !ver_ids.is_empty() {
        projectinfo.append(&mut get_ver_info(config.clone(), ver_ids).await?)
    };

    if projectinfo.is_empty() {
        return Err(MLError::new(ErrorType::ArgumentError, "NO_IDS?"));
    };

    let mut downloadstack: Vec<Version> = Vec::new();

    //Adding each mod to the lists and downloadstack
    if projectinfo.len() == 1 {
        println!("  └Insert mod in list {} and save infos", list.id);
    } else {
        println!("  └Insert mods in list {} and save infos", list.id);
    }

    for project in projectinfo {
        let current_version_id = if project.current_version.is_none() {
            String::from("NONE")
        } else {
            project.current_version.clone().unwrap().id
        };
        match userlist_insert(
            config.clone(),
            &list.id,
            &project.mod_id,
            &current_version_id,
            project.clone().applicable_versions,
            &project.download_link,
            project.set_version,
        ) {
            Err(e) => {
                let expected_err = format!("SQL: UNIQUE constraint failed: {}.mod_id", list.id);
                if e.to_string() == expected_err {
                    Err(MLError::new(
                        ErrorType::ModError,
                        "MOD_ALREADY_ON_SELECTED_LIST",
                    ))
                } else {
                    Err(e)
                }
            }
            Ok(..) => Ok(..),
        }?;

        match mods_insert(
            config.clone(),
            &project.mod_id,
            &project.slug,
            &project.title,
        ) {
            Err(e) => {
                if e.to_string() == "SQL: UNIQUE constraint failed: mods.id" {
                    Ok(..)
                } else {
                    Err(e)
                }
            }
            Ok(..) => Ok(..),
        }?;

        if project.current_version.is_some() {
            downloadstack.push(project.current_version.unwrap())
        };
    }

    //Download all the added mods
    if direct_download {
        download_versions(list.clone(), config.clone(), downloadstack).await?;
    };

    Ok(())
}

async fn get_mod_infos(config: Cfg, mod_ids: Vec<(String, bool)>, list: List) -> MLE<Vec<ProjectInfo>> {

    let mut setmap: HashMap<String, bool> = HashMap::new();

    let mut ids = vec![];

    for id in mod_ids {
        setmap.insert(id.0.to_string(), id.1);
        ids.push(id.0);
    }

    let mut projectinfo: Vec<ProjectInfo> = Vec::new();

    //Get required information from mod_ids
    let m_projects = match ids.len() {
        1 => vec![project(&config.apis.modrinth, &ids[0]).await],
        2.. => projects(&config.apis.modrinth, ids).await,
        _ => panic!("PANIC"),
    };
    for project in m_projects {
        println!("\t└{}", project.title);
        println!("\t  └Get versions");
        let available_versions = versions(
            &config.apis.modrinth,
            String::from(&project.id),
            list.clone(),
        )
        .await;

        let mut available_versions_vec: Vec<String> = Vec::new();
        let current_version: Option<Version>;
        let file: String;
        if !available_versions.is_empty() {
            let current_id = extract_current_version(available_versions.clone())?;
            println!("\t  └Current version: {}", current_id);

            current_version = Some(
                available_versions
                    .clone()
                    .into_iter()
                    .find(|v| v.id == current_id)
                    .unwrap(),
            );
            
            // match primary, if none?
            let files = current_version
                .clone()
                .ok_or("")
                .unwrap()
                .files;

            file = match files.clone().into_iter().find(|f| f.primary) {
                    Some(f) => f,
                    None => { files[0].clone() }
                }
                .url;

            for ver in available_versions {
                available_versions_vec.push(ver.id);
            }

            projectinfo.push(ProjectInfo {
                mod_id: String::from(&project.id),
                slug: project.slug,
                title: project.title,
                current_version,
                applicable_versions: available_versions_vec,
                download_link: file,
                set_version: setmap.get(&project.id).unwrap().clone(),
            })
        } else {
            println!("\t  └There's currently no mod version for your specified target");
            current_version = None;
            file = String::from("NONE");
            available_versions_vec.push(String::from("NONE"));
            projectinfo.push(ProjectInfo {
                mod_id: String::from(&project.id),
                slug: project.slug,
                title: project.title,
                current_version,
                applicable_versions: available_versions_vec,
                download_link: file,
                set_version: setmap.get(&project.id).unwrap().clone(),
            })
        }
    }

    Ok(projectinfo)
}

async fn get_ver_info(config: Cfg, ver_ids: Vec<(String, bool)>) -> MLE<Vec<ProjectInfo>> {

    let mut setmap: HashMap<String, bool> = HashMap::new();

    let mut ids = vec![];

    for id in ver_ids {
        setmap.insert(id.0.to_string(), id.1);
        ids.push(id.0);
    }
    let mut projectinfo: Vec<ProjectInfo> = Vec::new();

    //Get required information from ver_ids
    let mut v_versions = get_raw_versions(&config.apis.modrinth, ids).await;
    let mut v_mod_ids: Vec<String> = Vec::new();
    for ver in v_versions.clone() {
        v_mod_ids.push(ver.project_id);
    }
    let mut v_projects = projects(&config.apis.modrinth, v_mod_ids).await;
    v_versions.sort_by(|a, b| a.project_id.cmp(&b.project_id));
    v_projects.sort_by(|a, b| a.id.cmp(&b.id));

    for (i, project) in v_projects.into_iter().enumerate() {
        let version = &v_versions[i];
        println!("\t└{}({})", project.title, version.id);
        let file = version
            .clone()
            .files
            .into_iter()
            .find(|f| f.primary)
            .unwrap()
            .url;
        projectinfo.push(ProjectInfo {
            mod_id: String::from(&project.id),
            slug: project.slug,
            title: project.title,
            current_version: Some(version.clone()),
            applicable_versions: vec![String::from(&version.id)],
            download_link: file,
            set_version: setmap.get(&project.id).unwrap().clone(),
        })
    }
    Ok(projectinfo)
}

/// Remove mod from a list
/// # Arguments
///
/// * `config` - config struct
/// * `id` - name, slug or id of the mod
/// * `list` - List struct
pub fn mod_remove(config: Cfg, id: &str, list: List) -> MLE<()> {
    let mod_id = mods_get_id(&config.data, id)?;

    println!("Remove mod {} from {}", mods_get_info(config.clone(), &mod_id)?.title, list.id);
    let version = userlist_get_current_version(config.clone(), &list.id, &mod_id)?;

    print!("  └Remove from list");
    //Force flush of stdout, else print! doesn't print instantly
    std::io::stdout().flush()?;
    userlist_remove(config.clone(), &list.id, &mod_id)?;
    println!(" ✓");

    print!("  └Delete file");
    //Force flush of stdout, else print! doesn't print instantly
    std::io::stdout().flush()?;
    match delete_version(list, version) {
        Ok(_) => (),
        Err(err) => {
            if err.to_string() !=  "User input not accepted: VERSION_NOT_FOUND_IN_FILES" {
                return Err(err);
            };
            ()
        },
    };
    println!(" ✓");

    print!("  └Clean main db table");
    //Force flush of stdout, else print! doesn't print instantly
    std::io::stdout().flush()?;
    let list_ids = lists_get_all_ids(config.clone())?;

    // Remove mod from main list if not used elsewhere
    let mut mod_used = false;
    for id in list_ids {
        let mods = match userlist_get_all_ids(config.clone(), &id) {
            Ok(m) => m,
            Err(err) => {
                if err.to_string() ==  "Database: NO_MODS_USERLIST" {
                    println!(" ✓");
                    return Ok(());
                };
                return Err(err)
            }
        };
        if mods.contains(&mod_id) {
            mod_used = true;
            break;
        };
    }

    if !mod_used {
        mods_remove(config, mod_id)?;
    };
    println!(" ✓");

    Ok(())
}