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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
|
use askama::Template;
use axum::{
Form, Router,
body::Body,
extract::{Path, State},
http::Request,
response::{Html, Redirect},
routing::{get, post},
};
use rusqlite::params;
use std::io::{Cursor, Read};
use crate::auth::CurrentUser;
use crate::mods;
use crate::routes::AppState;
use crate::sanitize;
#[derive(Template)]
#[template(path = "mods/list.html")]
struct ModListTemplate {
username: String,
is_superuser: bool,
password_change_required: bool,
instance_name: String,
instance_id: i64,
mods: Vec<ModRow>,
flash: Option<FlashMessage>,
}
#[derive(Debug)]
struct ModRow {
id: i64,
filename: String,
display_name: Option<String>,
side: String,
accepted: bool,
enabled: bool,
rejection_reason: Option<String>,
created_at: String,
}
struct FlashMessage {
kind: String,
text: String,
}
/// Helper: extract all `mod_id` values from raw form key-value pairs.
fn parse_mod_ids(pairs: &[(String, String)]) -> Vec<i64> {
pairs
.iter()
.filter(|(k, _)| k == "mod_id")
.filter_map(|(_, v)| v.parse().ok())
.collect()
}
pub fn router() -> Router<AppState> {
Router::new()
.route("/instances/{id}/mods", get(list_mods).post(upload_mod))
.route("/instances/{id}/mods/{mod_id}/delete", post(delete_mod))
.route("/instances/{id}/mods/{mod_id}/toggle", post(toggle_mod))
.route("/instances/{id}/mods/batch-disable", post(batch_disable))
.route("/instances/{id}/mods/batch-delete", post(batch_delete))
.route("/instances/{id}/mods/batch-toggle", post(batch_toggle))
.route("/instances/{id}/mods/rescan", post(rescan_mods))
}
async fn list_mods(
State(state): State<AppState>,
Path(instance_id): Path<i64>,
CurrentUser(account): CurrentUser,
) -> Result<Html<String>, axum::response::Redirect> {
let conn = state.db.conn();
let instance_name: String = conn
.query_row(
"SELECT name FROM instances WHERE id = ?1",
params![instance_id],
|row| row.get(0),
)
.map_err(|_| Redirect::to("/instances"))?;
let mut stmt = conn
.prepare(
"SELECT id, filename, display_name, side, accepted, enabled, rejection_reason, created_at
FROM mods WHERE instance_id = ?1 ORDER BY created_at DESC",
)
.map_err(|_| Redirect::to("/instances"))?;
let mods: Vec<ModRow> = stmt
.query_map(params![instance_id], |row| {
Ok(ModRow {
id: row.get(0)?,
filename: row.get(1)?,
display_name: row.get(2)?,
side: row.get(3)?,
accepted: row.get::<_, i32>(4)? != 0,
enabled: row.get::<_, i32>(5)? != 0,
rejection_reason: row.get(6)?,
created_at: row.get(7)?,
})
})
.map_err(|_| Redirect::to("/instances"))?
.filter_map(|r| r.ok())
.collect();
drop(stmt);
drop(conn);
let template = ModListTemplate {
username: account.username.clone(),
is_superuser: account.is_superuser,
password_change_required: account.password_change_required,
instance_name,
instance_id,
mods,
flash: None,
};
match template.render() {
Ok(html) => Ok(Html(html)),
Err(e) => {
tracing::error!("Failed to render mods template: {e}");
Err(Redirect::to("/instances"))
}
}
}
// ── Single-mod actions ───────────────────────────────────────────────
async fn upload_mod(
State(state): State<AppState>,
Path(instance_id): Path<i64>,
CurrentUser(_user): CurrentUser,
req: Request<Body>,
) -> Result<Redirect, axum::response::Redirect> {
tracing::info!("Upload mod request for instance {instance_id}");
let instance_name = match get_instance_name(&state, instance_id) {
Some(n) => n,
None => return Err(Redirect::to("/instances")),
};
let safe_name = match sanitize::sanitize_instance_name(&instance_name) {
Some(n) => n,
None => return Err(Redirect::to("/instances")),
};
let mods_dir = state
.config
.server_directory
.join("instances")
.join(&safe_name)
.join("data")
.join("mods");
let _ = std::fs::create_dir_all(&mods_dir);
// Build multer multipart parser
let (parts, body) = req.into_parts();
let content_type = parts
.headers
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let boundary = content_type
.split(';')
.find_map(|part| {
let part = part.trim();
part.strip_prefix("boundary=").map(|b| b.trim_matches('"').to_string())
})
.unwrap_or_default();
if boundary.is_empty() {
tracing::error!("No boundary found in Content-Type");
return Err(Redirect::to(&format!("/instances/{instance_id}/mods")));
}
let constraints = multer::Constraints::new()
.size_limit(multer::SizeLimit::new()
.whole_stream(500 * 1024 * 1024)
.per_field(500 * 1024 * 1024));
let stream = body.into_data_stream();
let mut multipart = multer::Multipart::with_constraints(stream, boundary, constraints);
let mut processed = 0u32;
loop {
match multipart.next_field().await {
Ok(Some(field)) => {
let file_name = field
.file_name()
.map(|s| s.to_string())
.unwrap_or_else(|| "mod.jar".to_string());
let buf = match field.bytes().await {
Ok(b) => b.to_vec(),
Err(e) => {
tracing::error!("Failed to read field bytes: {e}");
continue;
}
};
if buf.is_empty() {
continue;
}
let lower = file_name.to_lowercase();
if lower.ends_with(".zip") {
process_zip_upload(&state, instance_id, &buf, &file_name, &mods_dir);
} else if lower.ends_with(".jar") {
process_jar_upload(&state, instance_id, &buf, &file_name, &mods_dir);
}
processed += 1;
}
Ok(None) => break,
Err(e) => {
tracing::error!("Multer error: {e}");
break;
}
}
}
tracing::info!("Upload done, processed {processed} files");
Ok(Redirect::to(&format!("/instances/{instance_id}/mods")))
}
/// Toggle a mod between enabled and disabled.
/// Disabled = `.jar` renamed to `.jar.disabled` on disk so the server skips it.
async fn toggle_mod(
State(state): State<AppState>,
Path((instance_id, mod_id)): Path<(i64, i64)>,
CurrentUser(_user): CurrentUser,
) -> Result<Redirect, axum::response::Redirect> {
let conn = state.db.conn();
let (filename, instance_name, currently_enabled): (String, String, bool) = conn
.query_row(
"SELECT m.filename, i.name, m.enabled FROM mods m
JOIN instances i ON i.id = m.instance_id
WHERE m.id = ?1 AND m.instance_id = ?2",
params![mod_id, instance_id],
|row| Ok((row.get(0)?, row.get(1)?, row.get::<_, i32>(2)? != 0)),
)
.map_err(|_| Redirect::to(&format!("/instances/{instance_id}/mods")))?;
drop(conn);
let safe_name = sanitize::sanitize_instance_name(&instance_name)
.ok_or_else(|| Redirect::to(&format!("/instances/{instance_id}/mods")))?;
let safe_filename = sanitize::sanitize_backup_filename(&filename)
.ok_or_else(|| Redirect::to(&format!("/instances/{instance_id}/mods")))?;
let mods_dir = state
.config
.server_directory
.join("instances")
.join(&safe_name)
.join("data")
.join("mods");
let base_path = mods_dir.join(&safe_filename);
if currently_enabled {
// Disable: rename .jar → .jar.disabled
let disabled_path = mods_dir.join(format!("{safe_filename}.disabled"));
if base_path.exists() {
let _ = std::fs::rename(&base_path, &disabled_path);
}
} else {
// Enable: rename .jar.disabled → .jar
let disabled_path = mods_dir.join(format!("{safe_filename}.disabled"));
if disabled_path.exists() {
let _ = std::fs::rename(&disabled_path, &base_path);
} else if !base_path.exists() {
// Neither exists — file may have been deleted out of band; just toggle the DB
tracing::warn!("Mod file not found on disk: {safe_filename}");
}
}
let conn = state.db.conn();
let _ = conn.execute(
"UPDATE mods SET enabled = NOT enabled WHERE id = ?1",
params![mod_id],
);
drop(conn);
Ok(Redirect::to(&format!("/instances/{instance_id}/mods")))
}
/// Permanently delete a single mod (file + DB record).
async fn delete_mod(
State(state): State<AppState>,
Path((instance_id, mod_id)): Path<(i64, i64)>,
CurrentUser(_user): CurrentUser,
) -> Result<Redirect, axum::response::Redirect> {
let conn = state.db.conn();
let (filename, instance_name): (String, String) = conn
.query_row(
"SELECT m.filename, i.name FROM mods m
JOIN instances i ON i.id = m.instance_id
WHERE m.id = ?1 AND m.instance_id = ?2",
params![mod_id, instance_id],
|row| Ok((row.get(0)?, row.get(1)?)),
)
.map_err(|_| Redirect::to(&format!("/instances/{instance_id}/mods")))?;
let safe_name = sanitize::sanitize_instance_name(&instance_name)
.ok_or_else(|| Redirect::to(&format!("/instances/{instance_id}/mods")))?;
let safe_filename = sanitize::sanitize_backup_filename(&filename)
.ok_or_else(|| Redirect::to(&format!("/instances/{instance_id}/mods")))?;
let mods_dir = state
.config
.server_directory
.join("instances")
.join(&safe_name)
.join("data")
.join("mods");
// Try deleting both the .jar and the .jar.disabled variant
let jar_path = mods_dir.join(&safe_filename);
let disabled_path = mods_dir.join(format!("{safe_filename}.disabled"));
let _ = std::fs::remove_file(&jar_path);
let _ = std::fs::remove_file(&disabled_path);
// Remove from DB
conn.execute("DELETE FROM mods WHERE id = ?1", params![mod_id])
.ok();
let remaining: i64 = conn
.query_row(
"SELECT COUNT(*) FROM mods WHERE instance_id = ?1 AND accepted = 1",
params![instance_id],
|row| row.get(0),
)
.unwrap_or(0);
if remaining == 0 {
conn.execute(
"UPDATE instances SET has_modpack = 0 WHERE id = ?1",
params![instance_id],
)
.ok();
}
drop(conn);
Ok(Redirect::to(&format!("/instances/{instance_id}/mods")))
}
// ── Batch actions ─────────────────────────────────────────────────────
/// Disable all checked mods at once.
async fn batch_disable(
State(state): State<AppState>,
Path(instance_id): Path<i64>,
CurrentUser(_user): CurrentUser,
Form(form): Form<Vec<(String, String)>>,
) -> Result<Redirect, axum::response::Redirect> {
let mod_ids = parse_mod_ids(&form);
for mod_id in &mod_ids {
let conn = state.db.conn();
let (filename, instance_name): (String, String) = match conn.query_row(
"SELECT m.filename, i.name FROM mods m
JOIN instances i ON i.id = m.instance_id
WHERE m.id = ?1 AND m.instance_id = ?2",
params![mod_id, instance_id],
|row| Ok((row.get(0)?, row.get(1)?)),
) {
Ok(v) => v,
Err(_) => continue,
};
drop(conn);
let safe_name = match sanitize::sanitize_instance_name(&instance_name) {
Some(n) => n,
None => continue,
};
let safe_filename = match sanitize::sanitize_backup_filename(&filename) {
Some(f) => f,
None => continue,
};
let mods_dir = state
.config
.server_directory
.join("instances")
.join(&safe_name)
.join("data")
.join("mods");
let jar = mods_dir.join(&safe_filename);
let disabled = mods_dir.join(format!("{safe_filename}.disabled"));
if jar.exists() {
let _ = std::fs::rename(&jar, &disabled);
}
let conn = state.db.conn();
let _ = conn.execute(
"UPDATE mods SET enabled = 0 WHERE id = ?1",
params![mod_id],
);
drop(conn);
}
Ok(Redirect::to(&format!("/instances/{instance_id}/mods")))
}
/// Permanently delete all checked mods at once.
async fn batch_delete(
State(state): State<AppState>,
Path(instance_id): Path<i64>,
CurrentUser(_user): CurrentUser,
Form(form): Form<Vec<(String, String)>>,
) -> Result<Redirect, axum::response::Redirect> {
let mod_ids = parse_mod_ids(&form);
for mod_id in &mod_ids {
let conn = state.db.conn();
let (filename, instance_name): (String, String) = match conn.query_row(
"SELECT m.filename, i.name FROM mods m
JOIN instances i ON i.id = m.instance_id
WHERE m.id = ?1 AND m.instance_id = ?2",
params![mod_id, instance_id],
|row| Ok((row.get(0)?, row.get(1)?)),
) {
Ok(v) => v,
Err(_) => continue,
};
drop(conn);
let safe_name = match sanitize::sanitize_instance_name(&instance_name) {
Some(n) => n,
None => continue,
};
let safe_filename = match sanitize::sanitize_backup_filename(&filename) {
Some(f) => f,
None => continue,
};
let mods_dir = state
.config
.server_directory
.join("instances")
.join(&safe_name)
.join("data")
.join("mods");
let _ = std::fs::remove_file(mods_dir.join(&safe_filename));
let _ = std::fs::remove_file(mods_dir.join(format!("{safe_filename}.disabled")));
let conn = state.db.conn();
conn.execute("DELETE FROM mods WHERE id = ?1", params![mod_id])
.ok();
drop(conn);
}
// Update has_modpack flag
let conn = state.db.conn();
let remaining: i64 = conn
.query_row(
"SELECT COUNT(*) FROM mods WHERE instance_id = ?1 AND accepted = 1",
params![instance_id],
|row| row.get(0),
)
.unwrap_or(0);
if remaining == 0 {
let _ = conn.execute(
"UPDATE instances SET has_modpack = 0 WHERE id = ?1",
params![instance_id],
);
}
drop(conn);
Ok(Redirect::to(&format!("/instances/{instance_id}/mods")))
}
/// Toggle (enable/disable) all checked mods at once — each flips its state.
async fn batch_toggle(
State(state): State<AppState>,
Path(instance_id): Path<i64>,
CurrentUser(_user): CurrentUser,
Form(form): Form<Vec<(String, String)>>,
) -> Result<Redirect, axum::response::Redirect> {
let mod_ids = parse_mod_ids(&form);
for mod_id in &mod_ids {
let conn = state.db.conn();
let (filename, instance_name, currently_enabled): (String, String, bool) =
match conn.query_row(
"SELECT m.filename, i.name, m.enabled FROM mods m
JOIN instances i ON i.id = m.instance_id
WHERE m.id = ?1 AND m.instance_id = ?2",
params![mod_id, instance_id],
|row| Ok((row.get(0)?, row.get(1)?, row.get::<_, i32>(2)? != 0)),
) {
Ok(v) => v,
Err(_) => continue,
};
drop(conn);
let safe_name = match sanitize::sanitize_instance_name(&instance_name) {
Some(n) => n,
None => continue,
};
let safe_filename = match sanitize::sanitize_backup_filename(&filename) {
Some(f) => f,
None => continue,
};
let mods_dir = state
.config
.server_directory
.join("instances")
.join(&safe_name)
.join("data")
.join("mods");
let jar = mods_dir.join(&safe_filename);
let disabled = mods_dir.join(format!("{safe_filename}.disabled"));
if currently_enabled {
// Was enabled → now disable
if jar.exists() {
let _ = std::fs::rename(&jar, &disabled);
}
} else {
// Was disabled → now enable
if disabled.exists() {
let _ = std::fs::rename(&disabled, &jar);
}
}
let conn = state.db.conn();
let _ = conn.execute(
"UPDATE mods SET enabled = NOT enabled WHERE id = ?1",
params![mod_id],
);
drop(conn);
}
Ok(Redirect::to(&format!("/instances/{instance_id}/mods")))
}
// ── Helpers ───────────────────────────────────────────────────────────
fn get_instance_name(state: &AppState, id: i64) -> Option<String> {
let conn = state.db.conn();
let result = conn
.query_row(
"SELECT name FROM instances WHERE id = ?1",
params![id],
|row| row.get::<_, String>(0),
)
.ok();
drop(conn);
result
}
fn process_jar_upload(
state: &AppState,
instance_id: i64,
bytes: &[u8],
filename: &str,
mods_dir: &std::path::Path,
) {
let safe_name = std::path::Path::new(filename)
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| filename.to_string());
tracing::info!("Validating {safe_name}");
let result = mods::validate_mod(bytes, &safe_name);
let conn = state.db.conn();
if let Err(e) = conn.execute(
"INSERT INTO mods (instance_id, filename, display_name, side, accepted, rejection_reason, enabled)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 1)",
params![
instance_id,
safe_name,
result.display_name,
result.side.to_string(),
result.accepted,
result.rejection_reason,
],
) {
tracing::error!("DB insert failed: {e}");
drop(conn);
return;
}
drop(conn);
if result.accepted {
let dest = mods_dir.join(&safe_name);
if std::fs::write(&dest, bytes).is_ok() {
tracing::info!("Written to disk: {}", dest.display());
} else {
tracing::error!("Failed to write {}", dest.display());
}
let conn = state.db.conn();
let _ = conn.execute(
"UPDATE instances SET has_modpack = 1 WHERE id = ?1",
params![instance_id],
);
drop(conn);
}
}
fn process_zip_upload(
state: &AppState,
instance_id: i64,
bytes: &[u8],
filename: &str,
mods_dir: &std::path::Path,
) {
tracing::info!("Extracting ZIP archive {filename}");
let cursor = Cursor::new(bytes);
let mut archive = match zip::ZipArchive::new(cursor) {
Ok(a) => a,
Err(e) => {
tracing::error!("Failed to read ZIP {filename}: {e}");
return;
}
};
for i in 0..archive.len().min(500) {
let mut entry = match archive.by_index(i) {
Ok(e) => e,
Err(_) => continue,
};
let entry_name = entry.name().to_string();
let lower = entry_name.to_lowercase();
if !lower.ends_with(".jar") {
continue;
}
let base_name = std::path::Path::new(&entry_name)
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| entry_name.clone());
let mut jar_bytes = Vec::new();
if entry.read_to_end(&mut jar_bytes).is_err() {
continue;
}
process_jar_upload(state, instance_id, &jar_bytes, &base_name, mods_dir);
}
}
async fn rescan_mods(
State(state): State<AppState>,
Path(instance_id): Path<i64>,
CurrentUser(_user): CurrentUser,
) -> Result<Redirect, axum::response::Redirect> {
let instance_name = match get_instance_name(&state, instance_id) {
Some(n) => n,
None => return Err(Redirect::to("/instances")),
};
let safe_name = match sanitize::sanitize_instance_name(&instance_name) {
Some(n) => n,
None => return Err(Redirect::to("/instances")),
};
let mods_dir = state
.config
.server_directory
.join("instances")
.join(&safe_name)
.join("data")
.join("mods");
if let Ok(entries) = std::fs::read_dir(&mods_dir) {
for entry in entries.flatten() {
let path = entry.path();
if !path.is_file() {
continue;
}
let filename = path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
// Skip disabled mods (intentionally deactivated) and non-jar files
if !filename.ends_with(".jar") || filename.ends_with(".jar.disabled") {
continue;
}
let data = match std::fs::read(&path) {
Ok(d) => d,
Err(_) => continue,
};
tracing::info!("Rescanning existing mod: {filename}");
process_jar_upload(&state, instance_id, &data, &filename, &mods_dir);
}
}
Ok(Redirect::to(&format!("/instances/{instance_id}/mods")))
}
|