Display '<none>' if there is no active player.
[valheim_web.git] / backend / src / valheim_controller.rs
1 use sysinfo::{ ProcessExt, SystemExt };
2
3 use std::{ fs, time::SystemTime };
4
5 use chrono::{ DateTime, offset::Local };
6
7 #[cfg(target_os = "linux")]
8 use systemd::journal;
9
10 #[derive(Clone, Debug)]
11 pub struct ValheimExe {
12 memory: u64, // [kB].
13 load_average_5min: f64, // [%].
14 uptime: u64, // [s].
15 world_size: u64, // [B].
16 active_players: Vec<String>,
17 last_backup: Option<SystemTime>,
18 }
19
20 impl ValheimExe {
21 pub fn format_memory(&self) -> String {
22 format_byte_size(self.memory * 1024, 2)
23 }
24
25 pub fn format_load_average(&self) -> String {
26 format!("{:.2} %", self.load_average_5min)
27 }
28
29 pub fn format_uptime(&self) -> String {
30 let mins = self.uptime / 60;
31 let hours = mins / 60;
32 let days = hours / 24;
33 format!("{}d {}h {}min", days, hours - 24 * days, mins - 60 * hours)
34 }
35
36 pub fn format_world_size(&self) -> String {
37 format_byte_size(self.world_size, 2)
38 }
39
40 pub fn format_active_players(&self) -> String {
41 if self.active_players.len() == 0 {
42 String::from("<none>")
43 } else {
44 self.active_players.join(", ")
45 }
46 }
47
48 pub fn format_last_backup(&self) -> String {
49 match self.last_backup {
50 Some(t) => {
51 let datetime: DateTime<Local> = t.into();
52 datetime.format("%d/%m/%Y %T").to_string()
53 },
54 None => String::from("?")
55 }
56 }
57 }
58
59 const BINARY_PREFIXES: [&str; 8] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB"];
60
61 fn format_byte_size(bytes: u64, precision: usize) -> String {
62 for i in 0 .. 8 {
63 let mut size: u64 = 1;
64 size *= 1024u64.pow(i as u32);
65
66 if bytes < 1024 {
67 return format!("{} {}", std::cmp::max(0u64, bytes), BINARY_PREFIXES[i]);
68 }
69 else if bytes < 1024 * size {
70 return format!("{:.prec$} {}", bytes as f64 / size as f64, BINARY_PREFIXES[i], prec = precision);
71 }
72 }
73
74 String::from("")
75 }
76
77 const VALHEIM_PROCESS_NAME: &str = "valheim_server";
78
79 #[cfg(target_os = "linux")]
80 fn get_active_players() -> Vec<String> {
81 let mut journal =
82 journal::OpenOptions::default().current_user(true).open().unwrap();
83
84 journal.seek_tail().unwrap();
85
86 let mut number_of_connections = 0;
87 let mut players : Vec<String> = Vec::new();
88
89 loop {
90 match journal.previous_entry() {
91 Ok(Some(entry)) => {
92 if let (Some(unit), Some(mess)) = (entry.get("_SYSTEMD_UNIT"), entry.get("MESSAGE")) {
93 if unit == "valheim.service" {
94 //"Got character ZDOID from {}"
95 if let Some(pos) = mess.find("Got character ZDOID from") {
96 let character_str = mess.get(pos+25..).unwrap();
97 if let Some(pos_end) = character_str.find(" : ") {
98 let player_name = String::from(character_str.get(0..pos_end).unwrap());
99 if !players.contains(&player_name) {
100 players.push(player_name);
101 if players.len() == number_of_connections {
102 return players;
103 }
104 }
105 }
106 }
107 else if let Some(pos) = mess.find("Connections") {
108 let nb_of_connections_str = mess.get(pos+12..).unwrap();
109 if let Some(pos_end) = nb_of_connections_str.find(' ') {
110 if let Ok(n) = nb_of_connections_str.get(0..pos_end).unwrap().parse() {
111 number_of_connections = n;
112 if players.len() >= number_of_connections {
113 return players;
114 }
115 }
116 }
117 }
118 }
119 }
120 },
121 _ => return players
122 }
123 }
124 }
125
126 #[cfg(target_os = "windows")]
127 fn get_active_players() -> Vec<String> {
128 Vec::new()
129 }
130
131 fn get_last_backup_datetime(backup_path: &str) -> Option<SystemTime> {
132 let mut times =
133 fs::read_dir(backup_path).ok()?.filter_map(
134 |e| {
135 let dir = e.ok()?;
136 if dir.path().is_file() { Some(dir.metadata().ok()?.modified().ok()?) } else { None }
137 }
138 )
139 .collect::<Vec<SystemTime>>();
140
141 times.sort();
142
143 Some(times.last()?.clone())
144 }
145
146 pub fn get_valheim_executable_information(world_path: &str, backup_path: &str) -> Option<ValheimExe> {
147 let mut system = sysinfo::System::new_all();
148 system.refresh_system();
149 let processes = system.get_process_by_name(VALHEIM_PROCESS_NAME);
150
151 if processes.len() >= 1 {
152 let process = processes.first().unwrap();
153
154 let world_size = match std::fs::metadata(world_path) { Ok(f) => f.len(), Err(_) => 0u64 };
155
156 Some(
157 ValheimExe {
158 memory: process.memory(),
159 load_average_5min: system.get_load_average().five / system.get_processors().len() as f64 * 100.,
160 uptime: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() - process.start_time(),
161 world_size,
162 active_players: get_active_players(),
163 last_backup: get_last_backup_datetime(backup_path)
164 }
165 )
166 } else {
167 None
168 }
169 }