jetbrains_toolbox_updater/
lib.rs1use dirs::home_dir;
2use json::{JsonError, JsonValue};
3use std::fs::File;
4use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
5use std::path::PathBuf;
6use std::process::{Child, Command};
7use std::thread::sleep;
8use std::time::{Duration, Instant};
9use std::{fs, io};
10use sysinfo::{Process, System};
11
12#[derive(Debug, Clone)]
13pub struct JetBrainsToolboxInstallation {
14 binary: PathBuf,
15 channels: PathBuf, log: PathBuf,
17}
18
19#[derive(Debug)]
20#[non_exhaustive]
21pub enum UpdateError {
22 Io(io::Error),
23 Json(JsonError),
24 InvalidChannel,
25 CouldNotTerminate(String),
26 PrematureExit,
27 DoubleToolboxSelfUpdate,
28 StartupFusAssistantTimeout,
29 DoubleStartupFusAssistant,
30}
31
32impl From<io::Error> for UpdateError {
33 fn from(err: io::Error) -> UpdateError {
34 UpdateError::Io(err)
35 }
36}
37
38impl From<JsonError> for UpdateError {
39 fn from(err: JsonError) -> UpdateError {
40 UpdateError::Json(err)
41 }
42}
43
44impl JetBrainsToolboxInstallation {
45 fn update_all_channels<F>(&self, mut operation: F) -> Result<(), UpdateError>
46 where
47 F: FnMut(&PathBuf, &mut JsonValue) -> Result<(), UpdateError>,
48 {
49 for file in fs::read_dir(&self.channels)? {
50 let file = file?;
51 self.update_channel(file.path(), &mut operation)?;
52 }
53 Ok(())
54 }
55
56 fn update_channel<F>(&self, path: PathBuf, operation: &mut F) -> Result<(), UpdateError>
57 where
58 F: FnMut(&PathBuf, &mut JsonValue) -> Result<(), UpdateError>,
59 {
60 let mut file = File::options().read(true).write(true).open(&path)?;
61 let mut buf = String::new();
62 file.read_to_string(&mut buf)?;
63 let mut data = json::parse(&buf)?;
64 operation(&path, &mut data)?;
65 file.seek(SeekFrom::Start(0))?; buf = data.dump();
68 file.write_all(buf.as_bytes())?; let current_position = file.stream_position()?;
70 file.set_len(current_position)?; Ok(())
73 }
74
75 fn start_minimized(&self) -> io::Result<Child> {
76 Command::new(&self.binary).arg("--minimize").spawn()
77 }
78}
79
80#[derive(Debug, Clone)]
81#[non_exhaustive]
82pub enum FindError {
83 NotFound,
84 InvalidInstallation,
85 NoHomeDir,
86 UnsupportedOS(String),
87}
88
89#[cfg(target_os = "linux")]
90pub fn find_jetbrains_toolbox() -> Result<JetBrainsToolboxInstallation, FindError> {
91 let home_dir = home_dir().ok_or(FindError::NoHomeDir)?;
92 let dir = home_dir.join(".local/share/JetBrains/Toolbox");
93 if !dir.exists() {
94 return Err(FindError::NotFound);
95 } else if !dir.is_dir() {
96 return Err(FindError::InvalidInstallation);
98 }
99 let binary = dir.join("bin/jetbrains-toolbox");
100 if !binary.exists() {
101 return Err(FindError::InvalidInstallation);
102 }
103 let channels = dir.join("channels");
104 if !channels.is_dir() {
105 return Err(FindError::InvalidInstallation);
106 }
107 let logs_dir = dir.join("logs");
108 if !logs_dir.is_dir() {
109 return Err(FindError::InvalidInstallation);
110 }
111 let log = logs_dir.join("toolbox.latest.log"); Ok(JetBrainsToolboxInstallation {
114 binary,
115 channels,
116 log,
117 })
118}
119
120#[cfg(target_os = "windows")]
121pub fn find_jetbrains_toolbox() -> Result<JetBrainsToolboxInstallation, FindError> {
122 Err(FindError::UnsupportedOS("Windows".to_string())) }
124
125#[cfg(target_os = "macos")]
126pub fn find_jetbrains_toolbox() -> Result<JetBrainsToolboxInstallation, FindError> {
127 Err(FindError::UnsupportedOS("MacOS".to_string())) }
129
130#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
131pub fn find_jetbrains_toolbox() -> Result<JetBrainsToolboxInstallation, FindError> {
132 Err(FindError::UnsupportedOS(std::env::consts::OS.to_string()))
134}
135
136fn kill_all() -> Result<bool, UpdateError> {
138 let mut sys = System::new_all();
139 sys.refresh_all();
140 let processes = sys
142 .processes()
143 .values()
144 .filter_map(|p| {
145 let exe = p.exe()?; let name = p.name();
147 match exe.file_name().ok_or(UpdateError::CouldNotTerminate(
148 "Error getting file_name".to_string(),
149 )) {
150 Ok(file_name)
158 if file_name == "jetbrains-toolbox"
159 && name.to_str()?.starts_with("jetbrains") =>
160 {
161 Some(Ok(p))
162 }
163 Ok(_) => None, Err(e) => Some(Err(e)), }
166 })
167 .collect::<Result<Vec<&Process>, UpdateError>>()?;
168 Ok(match processes.len() {
169 0 => false, _ => {
171 for process in processes {
172 process.kill();
173 process.wait();
174 }
175 true }
177 })
178}
179
180pub fn update_jetbrains_toolbox(
181 installation: JetBrainsToolboxInstallation,
182) -> Result<(), UpdateError> {
183 _update_jetbrains_toolbox::<false>(installation)
184}
185
186fn _update_jetbrains_toolbox<const IS_RECURSIVE: bool>(
187 installation: JetBrainsToolboxInstallation,
188) -> Result<(), UpdateError> {
189 let toolbox_was_open = kill_all()?;
191
192 let skipped_channels = change_config(&installation)?;
194
195 let redo = match actual_update(&installation) {
196 Err(e) => {
197 println!("Unexpected error encountered, resetting configuration to previous state");
198 reset_config(&installation, skipped_channels)?;
199 return Err(e);
200 }
201 Ok(redo) => redo,
202 };
203
204 reset_config(&installation, skipped_channels)?;
206
207 if toolbox_was_open {
209 installation.start_minimized()?;
210 }
211
212 if redo {
213 if IS_RECURSIVE {
219 return Err(UpdateError::DoubleToolboxSelfUpdate);
221 }
222
223 _update_jetbrains_toolbox::<true>(installation)
224 } else {
225 Ok(())
226 }
227}
228
229fn actual_update(installation: &JetBrainsToolboxInstallation) -> Result<bool, UpdateError> {
231 let mut redo = false;
232
233 installation.start_minimized()?;
235
236 let mut updates: u32 = 0;
238 let mut correct_checksums_expected: u32 = 0;
239 let start_time = Instant::now();
240 let mut startup_time = None;
241
242 let file = File::open(&installation.log)?;
243 let mut file = BufReader::new(file);
244 file.seek(SeekFrom::End(0))?;
245 loop {
246 if startup_time.is_none() && start_time + Duration::from_secs(60) < Instant::now() {
249 return Err(UpdateError::StartupFusAssistantTimeout);
250 }
251
252 if let Some(startup_time) = startup_time {
253 if updates == 0 && startup_time + Duration::from_secs(10) < Instant::now() {
255 println!("No updates found.");
256 break;
257 }
258 }
259
260 let curr_position = file.stream_position()?;
261
262 let mut line = String::new();
264 file.read_line(&mut line)?;
265
266 if line.is_empty() {
267 file.seek(SeekFrom::Start(curr_position))?;
270 sleep(Duration::from_millis(100));
271 } else {
272 if line.contains("Correct checksum for") || line.contains("Downloading from") {
278 if line.contains("Correct checksum for") && correct_checksums_expected > 0 {
279 correct_checksums_expected -= 1;
280 continue;
281 }
282 println!("Found an update, waiting until it finishes...");
284 updates += 1;
285 if line.contains("Downloading from") {
286 correct_checksums_expected += 1;
288 }
289 } else if line.contains("Show notification") {
290 updates -= 1;
292 if updates == 0 {
293 println!("Update finished, exiting...");
294 sleep(Duration::from_secs(2)); break;
296 } else {
297 println!("Update finished, waiting for other update(s) to finish")
298 }
299 } else if line.contains(
300 "Shutting down. Reason: The updated app is starting, closing the current process",
301 ) {
302 redo = true;
305 println!("Toolbox (self-)update finished.");
306 sleep(Duration::from_secs(2)); break;
308 } else if line.contains("Downloaded fus-assistant.xml") {
309 if startup_time.is_some() {
310 return Err(UpdateError::DoubleStartupFusAssistant);
312 }
313 startup_time = Some(Instant::now())
314 }
315 }
316 }
317
318 if !kill_all()? {
320 return Err(UpdateError::PrematureExit);
322 }
323
324 Ok(redo)
325}
326
327fn change_config(installation: &JetBrainsToolboxInstallation) -> Result<Vec<PathBuf>, UpdateError> {
328 let mut skipped_channels = vec![];
329 installation.update_all_channels(|channel, d| {
330 if !d.has_key("channel") {
331 return Err(UpdateError::InvalidChannel);
332 }
333 if d["channel"].has_key("autoUpdate") {
334 if d["channel"]["autoUpdate"] == true {
335 skipped_channels.push(channel.clone());
337 return Ok(());
338 } else {
339 return Err(UpdateError::InvalidChannel);
341 }
342 }
343
344 d["channel"]["autoUpdate"] = true.into();
345 Ok(())
346 })?;
347 Ok(skipped_channels)
348}
349
350fn reset_config(
351 installation: &JetBrainsToolboxInstallation,
352 skipped_channels: Vec<PathBuf>,
353) -> Result<(), UpdateError> {
354 installation.update_all_channels(|channel, d| {
355 if !d.has_key("channel") {
356 return Err(UpdateError::InvalidChannel);
357 }
358 if skipped_channels.contains(channel) {
359 return Ok(());
361 }
362 d["channel"].remove("autoUpdate");
363 Ok(())
364 })?;
365 Ok(())
366}