Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
547 changes: 546 additions & 1 deletion Cargo.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ block2 = "0.6.2"
crossbeam-channel = "0.5.15"
emojis = "0.8.0"
global-hotkey = "0.7.0"
hex = "0.4.3"
iced = { version = "0.14.0", features = ["image", "tokio"] }
icns = "0.3.1"
image = { version = "0.25.9", features = ["tiff"] }
Expand All @@ -31,8 +32,11 @@ rayon = "1.11.0"
rfd = "0.17.2"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.149"
sha2 = "0.11.0"
tempfile = "3.27.0"
tokio = { version = "1.48.0", features = ["full"] }
toml = "0.9.8"
tracing-subscriber = { version = "0.3.22", features = ["env-filter"] }
tray-icon = "0.21.3"
url = { version = "2.5.8", default-features = false }
zip = "8.5.1"
1 change: 1 addition & 0 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ pub enum SetConfigFields {
PlaceHolder(String),
SearchUrl(String),
ClipboardHistory(bool),
SetAutoUpdate(bool),
HapticFeedback(bool),
ShowMenubarIcon(bool),
SetPage(MainPage),
Expand Down
14 changes: 14 additions & 0 deletions src/app/pages/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,19 @@ pub fn settings_page(config: Config) -> Element<'static, Message> {
notice_item(theme.clone(), "If you want rustcast to start on login"),
]);

let theme_clone = theme.clone();
let auto_update = settings_item_row([
settings_hint_text(theme.clone(), "Auto update"),
checkbox(config.clone().auto_update)
.style(move |_, _| settings_checkbox_style(&theme_clone))
.on_toggle(move |input| Message::SetConfig(SetConfigFields::SetAutoUpdate(input)))
.into(),
notice_item(
theme.clone(),
"If rustcast should automatically update itself",
),
]);

let theme_clone = theme.clone();
let haptic = Row::from_iter([
settings_hint_text(theme.clone(), "Haptic feedback"),
Expand Down Expand Up @@ -422,6 +435,7 @@ pub fn settings_page(config: Config) -> Element<'static, Message> {
search.into(),
debounce.into(),
start_at_login.into(),
auto_update.into(),
haptic.into(),
tray_icon.into(),
clipboard_history.into(),
Expand Down
43 changes: 3 additions & 40 deletions src/app/tile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod update;

use crate::app::apps::App;
use crate::app::{ArrowKey, Message, Move, Page};
use crate::autoupdate::new_version_available;
use crate::clipboard::ClipBoardContentType;
use crate::config::{Config, Shelly};
use crate::debounce::Debouncer;
Expand Down Expand Up @@ -32,7 +33,6 @@ use tray_icon::TrayIcon;

use std::collections::HashMap;
use std::fmt::Debug;
use std::str::FromStr;
use std::time::Duration;

/// This is a wrapper around the sender to disable dropping
Expand Down Expand Up @@ -597,46 +597,9 @@ fn handle_recipient() -> impl futures::Stream<Item = Message> {

fn handle_version_and_rankings() -> impl futures::Stream<Item = Message> {
stream::channel(100, async |mut output| {
let current_version = format!("\"{}\"", option_env!("APP_VERSION").unwrap_or(""));

if current_version.is_empty() {
println!("empty version");
return;
}

let req = minreq::Request::new(
minreq::Method::Get,
"https://api.github.com/repos/RustCastLabs/rustcast/releases/latest",
)
.with_header("User-Agent", "rustcast-update-checker")
.with_header("Accept", "application/vnd.github+json")
.with_header("X-GitHub-Api-Version", "2022-11-28");

loop {
let resp = req
.clone()
.send()
.and_then(|x| x.as_str().map(serde_json::Value::from_str));

info!("Made a req for latest version");

if let Ok(Ok(val)) = resp {
let new_ver = val
.get("name")
.map(|x| x.to_string())
.unwrap_or("".to_string());

// new_ver is in the format "\"v0.0.0\""
// note that it is encapsulated in double quotes
if new_ver.trim() != current_version
&& !new_ver.is_empty()
&& new_ver.starts_with("\"v")
{
info!("new version available: {new_ver}");
output.send(Message::UpdateAvailable).await.ok();
}
} else {
warn!("Error getting resp");
if new_version_available().is_some() {
output.send(Message::UpdateAvailable).await.ok();
}
tokio::time::sleep(Duration::from_secs(30)).await;
output.send(Message::SaveRanking).await.ok();
Expand Down
12 changes: 12 additions & 0 deletions src/app/tile/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ use crate::app::menubar::menu_builder;
use crate::app::menubar::menu_icon;
use crate::app::tile::AppIndex;
use crate::app::{Message, Page, tile::Tile};
use crate::autoupdate::download_latest_app;
use crate::autoupdate::relaunch_app;
use crate::calculator::Expr;
use crate::commands::Function;
use crate::config::Config;
Expand Down Expand Up @@ -96,6 +98,13 @@ pub fn handle_update(tile: &mut Tile, message: Message) -> Task<Message> {

Message::UpdateAvailable => {
tile.update_available = true;

if tile.config.auto_update {
thread::spawn(|| {
download_latest_app().ok();
relaunch_app();
});
}
Task::done(Message::ReloadConfig)
}

Expand Down Expand Up @@ -796,6 +805,9 @@ pub fn handle_update(tile: &mut Tile, message: Message) -> Task<Message> {
SetConfigFields::HapticFeedback(haptic_feedback) => {
final_config.haptic_feedback = haptic_feedback
}
SetConfigFields::SetAutoUpdate(au) => {
final_config.auto_update = au;
}
SetConfigFields::ShowMenubarIcon(show) => final_config.show_trayicon = show,
SetConfigFields::SetThemeFields(SetConfigThemeFields::Font(fnt)) => {
final_config.theme.font = Some(fnt)
Expand Down
222 changes: 222 additions & 0 deletions src/autoupdate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
use std::str::FromStr;

use log::{error, info};
use sha2::{Digest, Sha256};

pub struct ReleaseInfo {
pub version: String,
pub zip_url: String,
pub sha256: String,
}

pub fn get_latest_release() -> Option<ReleaseInfo> {
let req = minreq::Request::new(
minreq::Method::Get,
"https://api.github.com/repos/RustCastLabs/rustcast/releases/latest",
)
.with_header("User-Agent", "rustcast-update-checker")
.with_header("Accept", "application/vnd.github+json")
.with_header("X-GitHub-Api-Version", "2022-11-28");

let resp = req
.send()
.and_then(|x| x.as_str().map(serde_json::Value::from_str));

if let Ok(Ok(val)) = resp {
let version = val.get("name")?.as_str()?.to_string();

let assets = val.get("assets")?.as_array()?;

let mut zip_url = None;
let mut sha256 = None;

for asset in assets {
let name = asset.get("name")?.as_str()?;
let url = asset.get("browser_download_url")?.as_str()?.to_string();

if name == "Rustcast-universal-macos.app.zip" {
zip_url = Some(url);

sha256 = asset
.get("digest")
.and_then(|d| d.as_str())
.and_then(|d| d.strip_prefix("sha256:"))
.map(|d| d.to_string());
}
}

Some(ReleaseInfo {
version,
zip_url: zip_url?,
sha256: sha256?,
})
} else {
None
}
}

pub fn new_version_available() -> Option<ReleaseInfo> {
info!("Checking for new version");
let info = get_latest_release()?;
info!("Got latest info");
let current = option_env!("APP_VERSION").unwrap_or("");

if info.version != current {
Some(info)
} else {
None
}
}

pub fn verify_sha256(file_path: &std::path::Path, expected_hex: &str) -> std::io::Result<bool> {
let bytes = std::fs::read(file_path)?;
let digest = Sha256::digest(&bytes);
let actual_hex = hex::encode(digest);
Ok(actual_hex == expected_hex)
}

pub fn download_latest_app() -> Result<std::path::PathBuf, ()> {
let info = get_latest_release().ok_or_else(|| {
error!("Could not get latest release info");
})?;

info!("got latest release");

let tmp = tempfile::tempdir().map_err(|e| {
error!("Could not create temporary directory: {e}");
})?;

info!("created temp dir");

let zip_path = tmp.path().join("Rustcast-universal-macos.app.zip");

info!("zip path: {:?}", zip_path);
let resp = minreq::get(&info.zip_url)
.with_header("User-Agent", "rustcast-update-checker")
.send()
.map_err(|e| {
error!("Could not download update: {e}");
})?;

info!("downloaded zip");

std::fs::write(&zip_path, resp.as_bytes()).map_err(|e| {
error!("Could not write zip to disk: {e}");
})?;

info!("wrote zip to disk");

let ok = verify_sha256(&zip_path, &info.sha256).map_err(|e| {
error!("Could not verify sha256: {e}");
})?;

info!("verified sha256");

if !ok {
error!("SHA256 mismatch — aborting update");
return Err(());
}

let zip_file = std::fs::File::open(&zip_path).map_err(|e| {
error!("Could not open zip: {e}");
})?;

info!("opened zip");

let mut archive = zip::ZipArchive::new(zip_file).map_err(|e| {
error!("Could not read zip archive: {e}");
})?;

info!("read zip archive. contents:");

archive.extract(tmp.path()).map_err(|e| {
error!("Could not extract zip: {e}");
})?;

if let Ok(entries) = std::fs::read_dir(tmp.path()) {
for entry in entries.flatten() {
info!(" extracted entry: {:?}", entry.file_name());
}
}

let extracted_app = tmp.path().join("target/release/macos/Rustcast.app");

info!("found extracted app at: {:?}", extracted_app);

let dest = get_app_path().ok_or_else(|| {
error!("Could not determine current app path");
})?;

info!("Installing update over {:?}", dest);

if dest.exists() {
std::fs::remove_dir_all(&dest).map_err(|e| {
error!("Could not remove existing app: {e}");
})?;
}

move_or_copy(&extracted_app, &dest).map_err(|e| {
error!("Could not move app into place: {e}");
})?;

info!("Successful update");

Ok(dest)
}

fn move_or_copy(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
match std::fs::rename(src, dst) {
Ok(()) => Ok(()),
Err(_) => {
copy_dir_recursive(src, dst)?;
std::fs::remove_dir_all(src)
}
}
}

fn copy_dir_recursive(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
std::fs::create_dir_all(dst)?;
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let dst_path = dst.join(entry.file_name());
if entry.file_type()?.is_dir() {
copy_dir_recursive(&entry.path(), &dst_path)?;
} else {
std::fs::copy(entry.path(), dst_path)?;
}
}
Ok(())
}

pub fn relaunch_app() {
let app_path = match get_app_path() {
Some(p) => p,
None => {
error!("Could not determine current app path for relaunch");
return;
}
};

match std::process::Command::new("open").arg(&app_path).spawn() {
Ok(_) => {
info!("Relaunching app at {:?}", app_path);
std::thread::sleep(std::time::Duration::from_millis(500));
std::process::exit(0);
}
Err(e) => {
error!("Could not relaunch app: {e}");
}
}
}

pub fn get_app_path() -> Option<std::path::PathBuf> {
let exe = std::env::current_exe().ok()?;

let mut path = exe.as_path();
loop {
if path.extension().and_then(|e| e.to_str()) == Some("app") {
return Some(path.to_path_buf());
}
path = path.parent()?;
}
}
2 changes: 2 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub struct Config {
pub search_dirs: Vec<String>,
pub log_path: String,
pub debounce_delay: u64,
pub auto_update: bool,
}

impl Default for Config {
Expand All @@ -49,6 +50,7 @@ impl Default for Config {
search_url: "https://duckduckgo.com/search?q=%s".to_string(),
cbhist: true,
haptic_feedback: false,
auto_update: true,
show_trayicon: true,
main_page: MainPage::default(),
search_dirs: vec!["~".to_string()],
Expand Down
Loading
Loading