summaryrefslogblamecommitdiff
path: root/src/commands/io.rs
blob: c9691c459236a19dd1849df8a976512b5d5a8ee5 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
                                            
                                    

                        
 

                



                                                                         
                               
                                                                  
  


                                        
                           


                                        

                      
              


                    
                                                                     
                 
                                                                            
                                                                    




                                        

                   
                                 





                                    

                                                                           

                                 
                     
                                                   
          
 
                                                          

                                  
                                                                     
         
 

                        
                     



                                                 


     

            
                                                              
                                              



                                                                             
 
                                           
                       
                                              
            






                                                                 
     
 

                                            
                                                          
                                                      
                                                              
     

                                                   
 
                                  
                                                    



                              
 

                                           
                                     
                                                                   


          
 
            




                          
                                         



                                                   
                                    



                                                              


                                                           

                     




                                  
           


                                       



                                                      
         
                                                               


          
use indicatif::{ProgressBar, ProgressStyle};
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::prelude::*;

use crate::{
    config::Cfg,
    db::{
        lists_get, lists_get_all_ids, lists_insert, userlist_get_all_ids,
        userlist_get_current_version, userlist_get_set_version,
    },
    error::{EType, MLErr, MLE},
    mod_add, AddMod, IDSelector, List, Modloader, STYLE_OPERATION,
};

#[derive(Debug, Serialize, Deserialize)]
struct Export {
    lists: Vec<ExportList>,
}

#[derive(Debug, Serialize, Deserialize)]
struct ExportVersion {
    version: String,
    set: bool,
}

impl ExportVersion {
    fn from(config: &Cfg, list_id: &str, mod_id: &str) -> MLE<Self> {
        Ok(Self {
            version: userlist_get_current_version(config, list_id, mod_id)?,
            set: userlist_get_set_version(config, list_id, mod_id)?,
        })
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct ExportList {
    id: String,
    versions: Vec<ExportVersion>,
    launcher: String,
    mc_version: String,
    download_folder: Option<String>,
}

impl ExportList {
    pub fn from(config: &Cfg, list_id: &str, download: bool) -> MLE<Self> {
        let list = lists_get(config, list_id)?;

        let mut dl_folder = None;
        if download {
            dl_folder = Some(list.download_folder);
        };

        let mods = userlist_get_all_ids(config, list_id)?;
        let mut versions = vec![];
        for m in mods {
            versions.push(ExportVersion::from(config, list_id, &m)?);
        }

        Ok(Self {
            id: list.id,
            versions,
            launcher: list.modloader.to_string(),
            mc_version: list.mc_version,
            download_folder: dl_folder,
        })
    }
}

/// # Errors
/// # Panics
pub fn export(config: &Cfg, list: Option<String>) -> MLE<()> {
    let progress = ProgressBar::new_spinner();
    progress.set_style(
        ProgressStyle::with_template(STYLE_OPERATION)
            .map_err(|_| MLErr::new(EType::LibIndicatif, "template error"))?,
    );

    let mut list_ids: Vec<String> = vec![];
    if list.is_none() {
        list_ids = lists_get_all_ids(config)?;
    } else {
        list_ids.push(
            lists_get(
                config,
                &list.ok_or(MLErr::new(EType::Other, "nolist"))?,
            )?
            .id,
        );
    }

    let mut lists: Vec<ExportList> = vec![];
    for list_id in list_ids {
        progress.set_message(format!("Export {list_id}"));
        //TODO download option/ new download on import
        lists.push(ExportList::from(config, &list_id, true)?);
    }

    let toml = toml::to_string(&Export { lists })?;

    let filestr = dirs::home_dir()
        .ok_or(MLErr::new(EType::Other, "no home"))?
        .join("mlexport.toml")
        .into_os_string()
        .into_string()
        .unwrap();

    progress.set_message("Create file");
    let mut file = File::create(&filestr)?;
    file.write_all(toml.as_bytes())?;
    progress.finish_with_message(format!("Exported to {filestr}"));

    Ok(())
}

/// # Errors
pub async fn import(
    config: &Cfg,
    file_str: &str,
    direct_download: bool,
) -> MLE<()> {
    let mut file = File::open(file_str)?;
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    let export: Export = toml::from_str(&content)?;

    for exportlist in export.lists {
        let list = List {
            id: exportlist.id,
            mc_version: exportlist.mc_version,
            modloader: Modloader::from(&exportlist.launcher)?,
            download_folder: exportlist
                .download_folder
                .ok_or(MLErr::new(EType::Other, "NO_DL"))?,
        };
        lists_insert(
            config,
            &list.id,
            &list.mc_version,
            &list.modloader,
            &list.download_folder,
        )?;

        let mut ver_ids = vec![];
        for id in exportlist.versions {
            ver_ids.push(AddMod {
                id: IDSelector::VersionID(id.version),
                set_version: id.set,
            });
        }
        mod_add(config, ver_ids, list, direct_download).await?;
    }
    Ok(())
}