Show player names (WIP)
[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 self.active_players.join(", ")
42 }
43
44 pub fn format_last_backup(&self) -> String {
45 match self.last_backup {
46 Some(t) => {
47 let datetime: DateTime<Local> = t.into();
48 datetime.format("%d/%m/%Y %T").to_string()
49 },
50 None => String::from("?")
51 }
52 }
53 }
54
55 const BINARY_PREFIXES: [&str; 8] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB"];
56
57 fn format_byte_size(bytes: u64, precision: usize) -> String {
58 for i in 0 .. 8 {
59 let mut size: u64 = 1;
60 size *= 1024u64.pow(i as u32);
61
62 if bytes < 1024 {
63 return format!("{} {}", std::cmp::max(0u64, bytes), BINARY_PREFIXES[i]);
64 }
65 else if bytes < 1024 * size {
66 return format!("{:.prec$} {}", bytes as f64 / size as f64, BINARY_PREFIXES[i], prec = precision);
67 }
68 }
69
70 String::from("")
71 }
72
73 const VALHEIM_PROCESS_NAME: &str = "valheim_server";
74
75 #[cfg(target_os = "linux")]
76 fn get_active_players() -> Vec<String> {
77 let mut journal =
78 journal::OpenOptions::default().current_user(true).open().unwrap();
79
80 journal.seek_tail().unwrap();
81
82 let mut number_of_connections = -1;
83 let mut players : Vec<String> = Vec::new();
84
85 loop {
86 match journal.previous_entry() {
87 Ok(Some(entry)) => {
88 if let (Some(unit), Some(mess)) = (entry.get("_SYSTEMD_UNIT"), entry.get("MESSAGE")) {
89 if unit == "valheim.service" {
90 //"Got character ZDOID from {}"
91 if let Some(pos) = mess.find("Got character ZDOID from") {
92 let character_str = mess.get(pos+25..).unwrap();
93 if let Some(pos_end) = character_str.find(" : ") {
94 let player_name = String::from(character_str.get(0..pos_end));
95 if !players.contains(player_name) {
96 players.push(player_name);
97 if players.len() == number_of_connections {
98 return players;
99 }
100 }
101 }
102 }
103 else if let Some(pos) = mess.find("Connections") {
104 let nb_of_connections_str = mess.get(pos+12..).unwrap();
105 if let Some(pos_end) = nb_of_connections_str.find(' ') {
106 if let Ok(n) = nb_of_connections_str.get(0..pos_end).unwrap().parse() {
107 number_of_connections = n;
108 if players.len() >= number_of_connections {
109 return players;
110 }
111 }
112 }
113 }
114 }
115 }
116 },
117 _ => return players
118 }
119 }
120 }
121
122 #[cfg(target_os = "windows")]
123 fn get_active_players() -> Vec<String> {
124 Vec::new()
125 }
126
127 fn get_last_backup_datetime(backup_path: &str) -> Option<SystemTime> {
128 let mut times =
129 fs::read_dir(backup_path).ok()?.filter_map(
130 |e| {
131 let dir = e.ok()?;
132 if dir.path().is_file() { Some(dir.metadata().ok()?.modified().ok()?) } else { None }
133 }
134 )
135 .collect::<Vec<SystemTime>>();
136
137 times.sort();
138
139 Some(times.last()?.clone())
140 }
141
142 pub fn get_valheim_executable_information(world_path: &str, backup_path: &str) -> Option<ValheimExe> {
143 let mut system = sysinfo::System::new_all();
144 system.refresh_system();
145 let processes = system.get_process_by_name(VALHEIM_PROCESS_NAME);
146
147 if processes.len() >= 1 {
148 let process = processes.first().unwrap();
149
150 let world_size = match std::fs::metadata(world_path) { Ok(f) => f.len(), Err(_) => 0u64 };
151
152 Some(
153 ValheimExe {
154 memory: process.memory(),
155 load_average_5min: system.get_load_average().five / system.get_processors().len() as f64 * 100.,
156 uptime: std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() - process.start_time(),
157 world_size,
158 active_players: get_active_players(),
159 last_backup: get_last_backup_datetime(backup_path)
160 }
161 )
162 } else {
163 None
164 }
165 }