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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
|
use std::collections::HashMap;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use crate::{
config::Cfg,
db::{
lists_get_all_ids, mods_get_id, mods_get_info, mods_insert,
mods_remove, userlist_get_all_ids, userlist_get_current_version,
userlist_insert, userlist_remove,
},
error::{EType, MLErr, MLE},
files::{delete_version, download_versions},
modrinth::{
extract_current_version, get_raw_versions, project, projects, versions,
Version,
},
List, PROGRESS_CHARS, STYLE_BAR_POS, STYLE_OPERATION,
};
#[derive(Debug)]
pub struct AddMod {
pub id: IDSelector,
pub set_version: bool,
}
#[derive(Debug, 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,
}
/// # Errors
pub async fn mod_add(
config: &Cfg,
mods: Vec<AddMod>,
list: List,
direct_download: bool,
) -> MLE<()> {
let mp = MultiProgress::new();
let mut mod_ids: Vec<(String, bool)> = Vec::new();
let mut ver_ids: Vec<(String, bool)> = Vec::new();
let add_p = mp.add(ProgressBar::new(
mods.len()
.try_into()
.map_err(|_| MLErr::new(EType::Other, "MODSLENTRY"))?,
));
add_p.set_style(
ProgressStyle::with_template(STYLE_BAR_POS)
.map_err(|_| MLErr::new(EType::LibIndicatif, "template error"))?
.progress_chars(PROGRESS_CHARS),
);
add_p.set_message("Sort ids");
//"Sort" project ids from version ids to be able to handle them differently but in a batch
for m in mods {
add_p.inc(1);
match m.id {
IDSelector::ModificationID(pid) => {
mod_ids.push((pid, m.set_version));
}
IDSelector::VersionID(vid) => ver_ids.push((vid, m.set_version)),
}
}
add_p.set_message("Get infos");
let mut projectinfo: Vec<ProjectInfo> = Vec::new();
if !mod_ids.is_empty() {
projectinfo
.append(&mut get_mod_infos(config, mod_ids, list.clone()).await?);
};
if !ver_ids.is_empty() {
projectinfo.append(&mut get_ver_info(config, ver_ids).await?);
};
if projectinfo.is_empty() {
return Err(MLErr::new(EType::ArgumentError, "NO_IDS?"));
};
add_p.set_message("Add mods to database");
let mut downloadstack: Vec<Version> = Vec::new();
//Adding each mod to the lists and downloadstack
let project_p = mp.insert_before(
&add_p,
ProgressBar::new(
projectinfo
.len()
.try_into()
.map_err(|_| MLErr::new(EType::Other, "infolen"))?,
),
);
project_p.set_style(
ProgressStyle::with_template(STYLE_BAR_POS)
.map_err(|_| MLErr::new(EType::LibIndicatif, "template error"))?
.progress_chars(PROGRESS_CHARS),
);
for project in projectinfo {
add_project(config, &project_p, &project, &list)?;
if project.current_version.is_some() {
downloadstack.push(
project
.current_version
.ok_or(MLErr::new(EType::Other, "cur_ver"))?,
);
};
}
project_p.finish_with_message("Added all mods to the database");
//Download all the added mods
if direct_download {
add_p.set_message("Download mods");
download_versions(
list.clone(),
config.clone(),
downloadstack,
&mp,
&add_p,
)
.await?;
};
add_p.finish_with_message("Added all mods");
Ok(())
}
fn add_project(
config: &Cfg,
project_p: &ProgressBar,
project: &ProjectInfo,
list: &List,
) -> MLE<()> {
project_p.set_message(format!("Add {}", project.title));
let current_version_id = if project.current_version.is_none() {
String::from("NONE")
} else {
project
.current_version
.clone()
.ok_or(MLErr::new(EType::Other, "cur_ver"))?
.id
};
match userlist_insert(
config,
&list.id,
&project.mod_id,
¤t_version_id,
&project.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(MLErr::new(EType::ModError, "MOD_ALREADY_ON_SELECTED_LIST"))
} else {
Err(e)
}
}
Ok(..) => Ok(..),
}?;
match mods_insert(config, &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(..),
}?;
project_p.inc(1);
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 {
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() {
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)
.ok_or(MLErr::new(EType::Other, "not in setmap"))?,
});
} else {
let current_id =
extract_current_version(available_versions.clone())?;
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.clone(),
title: project.title,
current_version,
applicable_versions: available_versions_vec,
download_link: file,
set_version: *setmap.get(&project.slug).unwrap(),
});
}
}
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];
let files = version.clone().files;
let file = match files.clone().into_iter().find(|f| f.primary) {
Some(f) => f,
None => files[0].clone(),
}
.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(&version.id).unwrap(),
});
}
Ok(projectinfo)
}
/// Remove mod from a list
/// # Arguments
///
/// * `config` - config struct
/// * `id` - name, slug or id of the mod
/// * `list` - List struct
///
/// # Errors
pub fn mod_remove(config: &Cfg, id: &str, list: &List) -> MLE<()> {
let progress = ProgressBar::new_spinner();
progress.set_style(
ProgressStyle::with_template(STYLE_OPERATION)
.map_err(|_| MLErr::new(EType::LibIndicatif, "template error"))?,
);
let mod_id = mods_get_id(&config.data, id)?;
let info = mods_get_info(config, &mod_id)?;
progress.set_message(format!("Remove {} from {}", info.title, list.id));
let version = userlist_get_current_version(config, &list.id, &mod_id)?;
userlist_remove(config, &list.id, &mod_id)?;
progress.set_message("Delete file");
match delete_version(list, &version) {
Ok(()) => (),
Err(err) => {
if err.to_string()
!= "User input not accepted: VERSION_NOT_FOUND_IN_FILES"
{
return Err(err);
};
}
};
progress.set_message("Check main list");
let list_ids = lists_get_all_ids(config)?;
// 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, &id) {
Ok(m) => m,
Err(err) => {
if err.to_string() == "Database: NO_MODS_USERLIST" {
return Ok(());
};
return Err(err);
}
};
if mods.contains(&mod_id) {
mod_used = true;
break;
};
}
if !mod_used {
progress.set_message("Remove from main list");
mods_remove(config, &mod_id)?;
};
progress.finish_with_message(format!(
"Removed {} from {}",
info.title, list.id
));
Ok(())
}
|