15881
|
1 |
use crate::core::types::Replay;
|
|
2 |
//use super::demo::load;
|
|
3 |
use std::fs;
|
|
4 |
use std::path::PathBuf;
|
|
5 |
|
|
6 |
pub struct ReplayStorage {
|
|
7 |
borrowed_replays: Vec<ReplayId>,
|
|
8 |
}
|
|
9 |
|
|
10 |
#[derive(Clone, PartialEq)]
|
|
11 |
pub struct ReplayId {
|
|
12 |
path: PathBuf,
|
|
13 |
}
|
|
14 |
|
|
15 |
impl ReplayStorage {
|
|
16 |
pub fn new() -> Self {
|
|
17 |
ReplayStorage {
|
|
18 |
borrowed_replays: vec![],
|
|
19 |
}
|
|
20 |
}
|
|
21 |
|
|
22 |
pub fn pick_replay(&mut self, protocol: u16) -> Option<(ReplayId, Replay)> {
|
|
23 |
let protocol_suffix = format!(".{}", protocol);
|
|
24 |
let result = fs::read_dir("replays")
|
|
25 |
.ok()?
|
|
26 |
.flat_map(|f| Some(f.ok()?.path()))
|
15883
|
27 |
.find(|f| {
|
15881
|
28 |
f.ends_with(&protocol_suffix) && !self.borrowed_replays.iter().any(|e| &e.path == f)
|
|
29 |
})
|
|
30 |
.and_then(|f| {
|
|
31 |
Some((
|
|
32 |
ReplayId { path: f.clone() },
|
|
33 |
Replay::load(f.to_str()?).ok()?,
|
|
34 |
))
|
|
35 |
});
|
|
36 |
|
|
37 |
if let Some((ref replay_id, _)) = result {
|
|
38 |
self.borrowed_replays.push((*replay_id).clone());
|
|
39 |
}
|
|
40 |
|
|
41 |
result
|
|
42 |
}
|
|
43 |
|
|
44 |
pub fn move_failed_replay(&mut self, id: &ReplayId) -> std::io::Result<()> {
|
|
45 |
self.unborrow(id);
|
|
46 |
self.move_file("failed", id)
|
|
47 |
}
|
|
48 |
|
|
49 |
pub fn move_checked_replay(&mut self, id: &ReplayId) -> std::io::Result<()> {
|
|
50 |
self.unborrow(id);
|
|
51 |
self.move_file("checked", id)
|
|
52 |
}
|
|
53 |
|
|
54 |
pub fn requeue_replay(&mut self, id: &ReplayId) {
|
|
55 |
self.unborrow(id)
|
|
56 |
}
|
|
57 |
|
|
58 |
fn unborrow(&mut self, id: &ReplayId) {
|
|
59 |
self.borrowed_replays.retain(|i| i != id)
|
|
60 |
}
|
|
61 |
|
|
62 |
fn move_file(&self, dir: &str, id: &ReplayId) -> std::io::Result<()> {
|
|
63 |
let new_name = format!(
|
|
64 |
"{}/{}",
|
|
65 |
dir,
|
|
66 |
id.path
|
|
67 |
.file_name()
|
|
68 |
.and_then(|f| f.to_str())
|
|
69 |
.expect("What's up with your file name?")
|
|
70 |
);
|
|
71 |
|
|
72 |
fs::rename(&id.path, new_name)
|
|
73 |
}
|
|
74 |
}
|