Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

13.3 KB
Raw Blame
//! Automatic updates, for a RustCord installed with RustCordSetup on Windows.
//!
//! A minute after it starts, and every six hours after that, RustCord asks
//! GitHub for its latest release. A newer version's installer is downloaded,
//! checked against the SHA-256 published beside it and run silently: the new
//! version is in place for the next start (the running program is moved
//! aside, as `rustcord.old`), and the title bar shows Discord's green
//! "Update Ready!" button, which restarts into it.
//!
//! Whether it does this is one registry value, `HKCU\Software\RustCord\
//! AutoUpdate` (0 = off, missing = on), set on the installer's last page and
//! in Settings → About. "Check for Updates" there works either way. Copies
//! that weren't installed (development builds, the Linux and macOS builds)
//! never check.

use std::path::{Path, PathBuf};
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// The latest published (not draft, not pre-release) release.
const LATEST: &str = "https://api.github.com/repos/VRonGitHub/RustCord/releases/latest";
/// Where installers are downloaded from (nothing else is run).
const DOWNLOADS: &str = "https://github.com/VRonGitHub/RustCord/releases/download/";
pub const RELEASES_PAGE: &str = "https://github.com/VRonGitHub/RustCord/releases";
const FIRST_CHECK: Duration = Duration::from_secs(60);
const EVERY: Duration = Duration::from_secs(6 * 3600);
const EXE: &str = "rustcord.exe";
const UNINSTALLER: &str = "rustcord-uninstall.exe";

#[derive(Clone, PartialEq)]
pub enum Status {
    /// Not checked yet.
    Idle,
    Checking,
    /// Nothing newer, as of then.
    UpToDate(chrono::DateTime<chrono::Local>),
    Downloading { version: String, done: u64, total: u64 },
    Installing(String),
    /// Installed: RustCord starts as this version from now on.
    Ready(String),
    Failed(String),
}

impl Status {
    /// Checking, downloading or installing.
    pub fn busy(&self) -> bool {
        matches!(self, Self::Checking | Self::Downloading { .. } | Self::Installing(_))
    }
}

pub struct Updater {
    status: Arc<Mutex<Status>>,
    enabled: bool,
    check_now: Sender<()>,
    dir: PathBuf,
}

impl Updater {
    /// Start checking in the background, if this copy was installed (the
    /// uninstaller sits beside it). None otherwise.
    pub fn start(ctx: &eframe::egui::Context) -> Option<Self> {
        if !cfg!(windows) {
            return None;
        }
        // Dev aid (`RUSTCORD_DEV_UPDATE_FROM=<version>`): a development build
        // acts as the installed copy at that version, checking right away,
        // so an update can be tried from start to end (it goes to the real
        // install, in %LOCALAPPDATA%\Programs\RustCord).
        let pretend = crate::diagnostics::dev_var("RUSTCORD_DEV_UPDATE_FROM").ok();
        let dir = if pretend.is_some() {
            PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("Programs").join("RustCord")
        } else {
            let exe = std::env::current_exe().ok()?;
            if !exe.file_name().is_some_and(|n| n.eq_ignore_ascii_case(EXE)) {
                return None;
            }
            exe.parent()?.to_path_buf()
        };
        if !dir.join(UNINSTALLER).exists() {
            return None;
        }
        let first = if pretend.is_some() { Duration::from_secs(5) } else { FIRST_CHECK };
        let version = pretend.unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string());
        let status = Arc::new(Mutex::new(Status::Idle));
        let (check_now, wake) = std::sync::mpsc::channel();
        let (shared, ctx, folder) = (status.clone(), ctx.clone(), dir.clone());
        std::thread::Builder::new().name("updater".into()).spawn(move || run(&shared, &wake, &ctx, &folder, version, first)).ok()?;
        Some(Self { status, enabled: enabled(), check_now, dir })
    }

    pub fn status(&self) -> Status {
        self.status.lock().map(|s| s.clone()).unwrap_or(Status::Idle)
    }

    pub fn enabled(&self) -> bool {
        self.enabled
    }

    /// Turn automatic updates on or off (turning them on checks right away).
    pub fn set_enabled(&mut self, on: bool) {
        self.enabled = on;
        set_enabled(on);
        log::info!("updater: automatic updates turned {}", if on { "on" } else { "off" });
        if on && !self.status().busy() {
            let _ = self.check_now.send(());
        }
    }

    /// "Check for Updates": also installs what it finds, when updates are off.
    pub fn check_now(&self) {
        if !self.status().busy() {
            let _ = self.check_now.send(());
        }
    }

    /// The title bar's button: Some(true) when an update is ready, Some(false)
    /// while one is being fetched.
    pub fn title_bar_button(&self) -> Option<bool> {
        match self.status() {
            Status::Ready(_) => Some(true),
            Status::Downloading { .. } | Status::Installing(_) => Some(false),
            _ => None,
        }
    }

    /// The installed program (the new version, once one is ready).
    pub fn exe(&self) -> PathBuf {
        self.dir.join(EXE)
    }
}

/// The background thread: `installed` is the running version, and the first
/// check comes after `first`.
fn run(status: &Mutex<Status>, wake: &Receiver<()>, ctx: &eframe::egui::Context, dir: &Path, mut installed: String, first: Duration) {
    let set = |s: Status| {
        if let Ok(mut current) = status.lock() {
            *current = s;
        }
        ctx.request_repaint();
    };
    let Ok(runtime) = tokio::runtime::Builder::new_current_thread().enable_all().build() else { return };
    let Ok(client) = reqwest::Client::builder().timeout(Duration::from_secs(60)).user_agent("RustCord").build() else { return };
    // The program the last update moved aside (it was running then).
    let _ = std::fs::remove_file(dir.join("rustcord.old"));
    let mut next = Instant::now() + first;
    loop {
        let asked = match wake.recv_timeout(next.saturating_duration_since(Instant::now())) {
            Ok(()) => true,
            Err(RecvTimeoutError::Timeout) => false,
            Err(RecvTimeoutError::Disconnected) => return,
        };
        if !asked {
            next = Instant::now() + EVERY;
            if !enabled() {
                continue;
            }
        }
        let ready = status.lock().ok().and_then(|s| if let Status::Ready(v) = &*s { Some(v.clone()) } else { None });
        set(Status::Checking);
        match runtime.block_on(update(&client, dir, &installed, &set)) {
            Ok(Some(version)) => {
                log::info!("updater: RustCord {version} is installed and starts next time");
                installed = version.clone();
                set(Status::Ready(version));
            }
            // (An update that is ready stays ready.)
            Ok(None) => set(ready.map_or_else(|| Status::UpToDate(chrono::Local::now()), Status::Ready)),
            Err(e) => {
                log::warn!("updater: {e}");
                set(ready.map_or(Status::Failed(e), Status::Ready));
            }
        }
    }
}

/// Install the latest release if it is newer than `installed`: its version
/// when it was.
async fn update(client: &reqwest::Client, dir: &Path, installed: &str, set: &impl Fn(Status)) -> Result<Option<String>, String> {
    let offline = |e: reqwest::Error| format!("Couldn't reach GitHub ({e})");
    let release: serde_json::Value = client
        .get(LATEST)
        .header("Accept", "application/vnd.github+json")
        .send()
        .await
        .and_then(|r| r.error_for_status())
        .map_err(offline)?
        .json()
        .await
        .map_err(offline)?;
    let version = release["tag_name"].as_str().map(|t| t.trim_start_matches('v').to_string()).ok_or("GitHub's answer had no version in it")?;
    if !newer(&version, installed) {
        return Ok(None);
    }
    let name = format!("RustCordSetup-{version}.exe");
    let asset = |file: &str| {
        release["assets"].as_array().into_iter().flatten().find(|a| a["name"] == file).and_then(|a| Some((a["browser_download_url"].as_str()?.to_string(), a["size"].as_u64().unwrap_or(0))))
    };
    let (Some((url, size)), Some((sum_url, _))) = (asset(&name), asset(&format!("{name}.sha256"))) else {
        return Err(format!("RustCord {version} has no Windows installer yet"));
    };
    if !url.starts_with(DOWNLOADS) || !sum_url.starts_with(DOWNLOADS) {
        return Err(format!("RustCord {version}'s installer isn't on RustCord's release page"));
    }
    let failed = |e: reqwest::Error| format!("Couldn't download RustCord {version} ({e})");
    let sums = client.get(&sum_url).send().await.and_then(|r| r.error_for_status()).map_err(failed)?.text().await.map_err(failed)?;
    let expected = sums.split_whitespace().next().filter(|h| h.len() == 64).ok_or(format!("RustCord {version}'s checksum file is unreadable"))?.to_ascii_lowercase();

    log::info!("updater: downloading RustCord {version}");
    let file = std::env::temp_dir().join(&name);
    let mut response = client.get(&url).timeout(Duration::from_secs(30 * 60)).send().await.and_then(|r| r.error_for_status()).map_err(failed)?;
    let total = response.content_length().unwrap_or(size);
    let downloaded = async {
        use sha2::Digest;
        use std::io::Write;
        let mut out = std::fs::File::create(&file).map_err(|e| format!("Couldn't save the download ({e})"))?;
        let mut hash = sha2::Sha256::new();
        let mut done = 0u64;
        let mut shown = u64::MAX;
        while let Some(chunk) = response.chunk().await.map_err(failed)? {
            out.write_all(&chunk).map_err(|e| format!("Couldn't save the download ({e})"))?;
            hash.update(&chunk);
            done += chunk.len() as u64;
            // (The page shows whole percents: no repaint for less.)
            let percent = done * 100 / total.max(1);
            if percent != shown {
                shown = percent;
                set(Status::Downloading { version: version.clone(), done, total });
            }
        }
        out.flush().map_err(|e| format!("Couldn't save the download ({e})"))?;
        let got: String = hash.finalize().iter().map(|b| format!("{b:02x}")).collect();
        if got == expected {
            Ok(())
        } else {
            Err(format!("RustCord {version}'s download was damaged (its checksum doesn't match)"))
        }
    }
    .await;
    if let Err(e) = downloaded {
        let _ = std::fs::remove_file(&file);
        return Err(e);
    }

    // The installer's silent mode: it keeps the shortcuts and the settings,
    // and moves the running program aside instead of closing it.
    set(Status::Installing(version.clone()));
    log::info!("updater: installing RustCord {version}");
    let mut setup = std::process::Command::new(&file);
    setup.arg("/S").arg("--dir").arg(dir);
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        setup.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
    }
    let result = setup.status();
    let _ = std::fs::remove_file(&file);
    match result {
        Ok(s) if s.success() => Ok(Some(version)),
        Ok(s) => Err(format!("RustCord {version}'s installer failed (exit code {})", s.code().unwrap_or(-1))),
        Err(e) => Err(format!("Couldn't start RustCord {version}'s installer ({e})")),
    }
}

/// Is version `a` newer than `b`? ("0.10.0" is newer than "0.9.2".)
fn newer(a: &str, b: &str) -> bool {
    let parts = |v: &str| v.split('.').map(|p| p.trim().parse::<u64>().unwrap_or(0)).collect::<Vec<_>>();
    let (mut a, mut b) = (parts(a), parts(b));
    let len = a.len().max(b.len());
    a.resize(len, 0);
    b.resize(len, 0);
    a > b
}

#[cfg(windows)]
fn registry_names() -> (Vec<u16>, Vec<u16>) {
    let wide = |s: &str| s.encode_utf16().chain(Some(0)).collect::<Vec<u16>>();
    (wide("Software\\RustCord"), wide("AutoUpdate"))
}

/// Automatic updates are on (the installer's choice, or Settings').
#[cfg(windows)]
fn enabled() -> bool {
    use windows_sys::Win32::System::Registry::{RegGetValueW, HKEY_CURRENT_USER, RRF_RT_REG_DWORD};
    let (key, name) = registry_names();
    let mut value = 1u32;
    let mut size = 4u32;
    // SAFETY: NUL-terminated names; a DWORD and its size in bytes.
    let read = unsafe { RegGetValueW(HKEY_CURRENT_USER, key.as_ptr(), name.as_ptr(), RRF_RT_REG_DWORD, std::ptr::null_mut(), (&mut value as *mut u32).cast(), &mut size) };
    read != 0 || value != 0
}

#[cfg(windows)]
fn set_enabled(on: bool) {
    use windows_sys::Win32::System::Registry::{RegSetKeyValueW, HKEY_CURRENT_USER, REG_DWORD};
    let (key, name) = registry_names();
    let value = u32::from(on);
    // SAFETY: NUL-terminated names; a DWORD and its size in bytes.
    let written = unsafe { RegSetKeyValueW(HKEY_CURRENT_USER, key.as_ptr(), name.as_ptr(), REG_DWORD, (&value as *const u32).cast(), 4) };
    if written != 0 {
        log::warn!("updater: couldn't save the setting (error {written})");
    }
}

#[cfg(not(windows))]
fn enabled() -> bool {
    false
}

#[cfg(not(windows))]
fn set_enabled(_on: bool) {}

#[cfg(test)]
mod tests {
    use super::newer;

    #[test]
    fn versions_compare_by_number() {
        assert!(newer("0.4.39", "0.4.38"));
        assert!(newer("0.10.0", "0.9.2"));
        assert!(newer("1.0", "0.99.99"));
        assert!(!newer("0.4.38", "0.4.38"));
        assert!(!newer("0.4.38", "0.4.39"));
        assert!(!newer("0.4", "0.4.0"));
    }
}