1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
use std::{fs::{File, read_dir, remove_file}, io::Write, collections::HashMap};
use futures_util::StreamExt;
use reqwest::Client;
use crate::{List, modrinth::Version};
pub async fn download_versions(current_list: List, versions: Vec<Version>) -> Result<String, Box<dyn std::error::Error>> {
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.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<dyn std::error::Error>> {
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(String::from(&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 delete_version(list: List, version: String) -> Result<(), Box<dyn std::error::Error>> {
let file = get_file_path(list, version)?;
remove_file(file)?;
Ok(())
}
pub fn get_file_path(list: List, versionid: String) -> Result<String, Box<dyn std::error::Error>> {
let mut names: HashMap<String, String> = 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 api_versionid = format!("mr{}", versionid);
let filename = names.get(&api_versionid).ok_or("VERSION_NOT_FOUND_IN_FILES")?;
Ok(filename.to_owned())
}
pub fn get_downloaded_versions(list: List) -> Result<Vec<String>, Box<dyn std::error::Error>> {
let mut versions: Vec<String> = vec![];
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.push(String::from(namesplit[namesplit.len() - 2].split_at(2).1));
}
}
Ok(versions)
}
|