use std::{fs::{File, read_dir, remove_file, rename}, io::Write, collections::HashMap}; use futures_util::StreamExt; use reqwest::Client; use crate::{List, modrinth::Version, db::userlist_add_disabled_versions, config::Cfg}; pub async fn download_versions(current_list: List, versions: Vec) -> Result> { let dl_path = String::from(¤t_list.download_folder); for ver in versions { let primary_file = ver.files.into_iter().find(|file| file.primary).unwrap(); let mut splitname: Vec<&str> = primary_file.filename.split('.').collect(); let extension = splitname.pop().ok_or("NO_FILE_EXTENSION")?; let filename = format!("{}.mr.{}.{}.{}", splitname.join("."), ver.project_id, ver.id, extension); download_file(primary_file.url, current_list.clone().download_folder, filename).await?; } Ok(dl_path) } async fn download_file(url: String, path: String, name: String) -> Result<(), Box> { println!("Downloading {}", url); let dl_path_file = format!("{}/{}", path, name); let res = Client::new() .get(String::from(&url)) .send() .await?; // download chunks let mut file = File::create(&dl_path_file)?; let mut stream = res.bytes_stream(); while let Some(item) = stream.next().await { let chunk = item?; file.write_all(&chunk)?; } Ok(()) } pub fn disable_version(config: Cfg, current_list: List, versionid: String, mod_id: String) -> Result<(), Box> { println!("Disabling version {} for mod {}", versionid, mod_id); let file = get_file_path(current_list.clone(), String::from(&versionid))?; let disabled = format!("{}.disabled", file); rename(file, disabled)?; userlist_add_disabled_versions(config, current_list.id, versionid, mod_id)?; Ok(()) } pub fn delete_version(list: List, version: String) -> Result<(), Box> { let file = get_file_path(list, version)?; remove_file(file)?; Ok(()) } pub fn get_file_path(list: List, versionid: String) -> Result> { let mut names: HashMap = HashMap::new(); for file in read_dir(list.download_folder)? { let path = file?.path(); if path.is_file() { let pathstr = path.to_str().ok_or("BAH")?; let namesplit: Vec<&str> = pathstr.split('.').collect(); let ver_id = namesplit[namesplit.len() - 2]; names.insert(String::from(ver_id), String::from(pathstr)); } }; let filename = names.get(&versionid).ok_or("VERSION_NOT_FOUND_IN_FILES")?; Ok(filename.to_owned()) } pub fn get_downloaded_versions(list: List) -> Result, Box> { let mut versions: HashMap = HashMap::new(); for file in read_dir(&list.download_folder)? { let path = file?.path(); if path.is_file() && path.extension().ok_or("BAH")? == "jar" { let pathstr = path.to_str().ok_or("BAH")?; let namesplit: Vec<&str> = pathstr.split('.').collect(); versions.insert(String::from(namesplit[namesplit.len() - 3]), String::from(namesplit[namesplit.len() - 2])); } } Ok(versions) }