Comment out the code to format player list
[minecraft_web.git] / backend / src / minecraft_controller.rs
1 use sysinfo::{ ProcessExt, SystemExt };
2
3 use std::{ fs, time::SystemTime };
4
5 use chrono::{ DateTime, offset::Local };
6
7 #[derive(Clone, Debug)]
8 pub struct MinecraftExe {
9 memory: u64, // [kB].
10 load_average_5min: f64, // [%].
11 uptime: u64, // [s].
12 world_size: u64, // [B].
13 active_players: Vec<String>,
14 last_backup: Option<SystemTime>,
15 }
16
17 impl MinecraftExe {
18 pub fn format_memory(&self) -> String {
19 format_byte_size(self.memory * 1024, 2)
20 }
21
22 pub fn format_load_average(&self) -> String {
23 format!("{:.2} %", self.load_average_5min)
24 }
25
26 pub fn format_uptime(&self) -> String {
27 let mins = self.uptime / 60;
28 let hours = mins / 60;
29 let days = hours / 24;
30 format!("{}d {}h {}min", days, hours - 24 * days, mins - 60 * hours)
31 }
32
33 pub fn format_world_size(&self) -> String {
34 format_byte_size(self.world_size, 2)
35 }
36
37 pub fn format_active_players(&self) -> String {
38 if self.active_players.len() == 0 {
39 String::from("<none>")
40 } else {
41 self.active_players.join(", ")
42 }
43 }
44
45 pub fn format_last_backup(&self) -> String {
46 match self.last_backup {
47 Some(t) => {
48 let datetime: DateTime<Local> = t.into();
49 datetime.format("%d/%m/%Y %T").to_string()
50 },
51 None => String::from("?")
52 }
53 }
54 }
55
56 const BINARY_PREFIXES: [&str; 8] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB"];
57
58 fn format_byte_size(bytes: u64, precision: usize) -> String {
59 for i in 0 .. 8 {
60 let mut size: u64 = 1;
61 size *= 1024u64.pow(i as u32);
62
63 if bytes < 1024 {
64 return format!("{} {}", std::cmp::max(0u64, bytes), BINARY_PREFIXES[i]);
65 }
66 else if bytes < 1024 * size {
67 return format!("{:.prec$} {}", bytes as f64 / size as f64, BINARY_PREFIXES[i], prec = precision);
68 }
69 }
70
71 String::from("")
72 }
73
74 const MINECRAFT_PROCESS_NAME: &str = "java";
75
76 // It doesn't work for the moment, it only scan the connection event and do not treat disconnections.
77 fn get_active_players(rcon_password: &str) -> Vec<String> {
78 let mut client = minecraft_client_rs::Client::new("127.0.0.1:25575".to_string()).unwrap();
79
80 let players =
81 match client.authenticate(rcon_password.to_string()) {
82 Ok(_) => {
83 match client.send_command("list".to_string()) {
84 Ok(resp) => {
85 resp.body
86 .split('\n')
87 .skip(1)
88 .filter(|n| !n.is_empty())
89 .map(|n| n.to_string())
90 .collect()
91 },
92 Err(_e) => {
93 println!("Error from 'list' command");
94 Vec::new()
95 },
96 }
97 },
98 Err(_e) => {
99 println!("Authentication error");
100 Vec::new()
101 },
102 };
103
104 client.close().unwrap();
105
106 players
107 }
108
109 fn get_last_backup_datetime(backup_path: &str) -> Option<SystemTime> {
110 let mut times =
111 fs::read_dir(backup_path).ok()?.filter_map(
112 |e| {
113 let dir = e.ok()?;
114 if dir.path().is_file() { Some(dir.metadata().ok()?.modified().ok()?) } else { None }
115 }
116 )
117 .collect::<Vec<SystemTime>>();
118
119 times.sort();
120
121 Some(times.last()?.clone())
122 }
123
124 pub fn get_minecraft_executable_information(world_path: &str, backup_path: &str, rcon_password: &str) -> Option<MinecraftExe> {
125 let mut system = sysinfo::System::new_all();
126 system.refresh_system();
127 let processes = system.get_process_by_name(MINECRAFT_PROCESS_NAME);
128
129 // TODO: find the correct process by checking the correct jar name in parameters.
130 if processes.len() >= 1 {
131 let process = processes.first().unwrap();
132
133 let world_size = match std::fs::metadata(world_path) { Ok(f) => f.len(), Err(_) => 0u64 };
134
135 Some(
136 MinecraftExe {
137 memory: process.memory(),
138 load_average_5min: system.get_load_average().five / system.get_processors().len() as f64 * 100.,
139 uptime: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() - process.start_time(),
140 world_size,
141 active_players: get_active_players(rcon_password),
142 last_backup: get_last_backup_datetime(backup_path)
143 }
144 )
145 } else {
146 None
147 }
148 }