auto_update.rs

  1use anyhow::{anyhow, Result};
  2use client::http::{self, HttpClient};
  3use gpui::{
  4    actions,
  5    elements::{Empty, MouseEventHandler, Text},
  6    platform::AppVersion,
  7    AsyncAppContext, Element, Entity, ModelContext, ModelHandle, MutableAppContext, Task, View,
  8    ViewContext,
  9};
 10use lazy_static::lazy_static;
 11use serde::Deserialize;
 12use settings::Settings;
 13use smol::{fs::File, io::AsyncReadExt, process::Command};
 14use std::{env, ffi::OsString, path::PathBuf, sync::Arc, time::Duration};
 15use surf::Request;
 16use workspace::{ItemHandle, StatusItemView};
 17
 18const POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
 19const ACCESS_TOKEN: &'static str = "618033988749894";
 20
 21lazy_static! {
 22    pub static ref ZED_APP_VERSION: Option<AppVersion> = env::var("ZED_APP_VERSION")
 23        .ok()
 24        .and_then(|v| v.parse().ok());
 25    pub static ref ZED_APP_PATH: Option<PathBuf> = env::var("ZED_APP_PATH").ok().map(PathBuf::from);
 26}
 27
 28actions!(auto_update, [Check, DismissErrorMessage]);
 29
 30#[derive(Clone, PartialEq, Eq)]
 31pub enum AutoUpdateStatus {
 32    Idle,
 33    Checking,
 34    Downloading,
 35    Installing,
 36    Updated,
 37    Errored,
 38}
 39
 40pub struct AutoUpdater {
 41    status: AutoUpdateStatus,
 42    current_version: AppVersion,
 43    http_client: Arc<dyn HttpClient>,
 44    pending_poll: Option<Task<()>>,
 45    server_url: String,
 46}
 47
 48pub struct AutoUpdateIndicator {
 49    updater: Option<ModelHandle<AutoUpdater>>,
 50}
 51
 52#[derive(Deserialize)]
 53struct JsonRelease {
 54    version: String,
 55    url: http::Url,
 56}
 57
 58impl Entity for AutoUpdater {
 59    type Event = ();
 60}
 61
 62pub fn init(http_client: Arc<dyn HttpClient>, server_url: String, cx: &mut MutableAppContext) {
 63    if let Some(version) = ZED_APP_VERSION.clone().or(cx.platform().app_version().ok()) {
 64        let auto_updater = cx.add_model(|cx| {
 65            let updater = AutoUpdater::new(version, http_client, server_url);
 66            updater.start_polling(cx).detach();
 67            updater
 68        });
 69        cx.set_global(Some(auto_updater));
 70        cx.add_global_action(|_: &Check, cx| {
 71            if let Some(updater) = AutoUpdater::get(cx) {
 72                updater.update(cx, |updater, cx| updater.poll(cx));
 73            }
 74        });
 75        cx.add_action(AutoUpdateIndicator::dismiss_error_message);
 76    }
 77}
 78
 79impl AutoUpdater {
 80    fn get(cx: &mut MutableAppContext) -> Option<ModelHandle<Self>> {
 81        cx.default_global::<Option<ModelHandle<Self>>>().clone()
 82    }
 83
 84    fn new(
 85        current_version: AppVersion,
 86        http_client: Arc<dyn HttpClient>,
 87        server_url: String,
 88    ) -> Self {
 89        Self {
 90            status: AutoUpdateStatus::Idle,
 91            current_version,
 92            http_client,
 93            server_url,
 94            pending_poll: None,
 95        }
 96    }
 97
 98    pub fn start_polling(&self, cx: &mut ModelContext<Self>) -> Task<()> {
 99        cx.spawn(|this, mut cx| async move {
100            loop {
101                this.update(&mut cx, |this, cx| this.poll(cx));
102                cx.background().timer(POLL_INTERVAL).await;
103            }
104        })
105    }
106
107    pub fn poll(&mut self, cx: &mut ModelContext<Self>) {
108        if self.pending_poll.is_some() || self.status == AutoUpdateStatus::Updated {
109            return;
110        }
111
112        self.status = AutoUpdateStatus::Checking;
113        cx.notify();
114
115        self.pending_poll = Some(cx.spawn(|this, mut cx| async move {
116            let result = Self::update(this.clone(), cx.clone()).await;
117            this.update(&mut cx, |this, cx| {
118                this.pending_poll = None;
119                if let Err(error) = result {
120                    log::error!("auto-update failed: error:{:?}", error);
121                    this.status = AutoUpdateStatus::Errored;
122                    cx.notify();
123                }
124            });
125        }));
126    }
127
128    async fn update(this: ModelHandle<Self>, mut cx: AsyncAppContext) -> Result<()> {
129        let (client, server_url, current_version) = this.read_with(&cx, |this, _| {
130            (
131                this.http_client.clone(),
132                this.server_url.clone(),
133                this.current_version,
134            )
135        });
136        let mut response = client
137            .send(Request::new(
138                http::Method::Get,
139                http::Url::parse(&format!(
140                    "{server_url}/api/releases/latest?token={ACCESS_TOKEN}&asset=Zed.dmg"
141                ))?,
142            ))
143            .await?;
144        let release = response
145            .body_json::<JsonRelease>()
146            .await
147            .map_err(|err| anyhow!("error deserializing release {:?}", err))?;
148        let latest_version = release.version.parse::<AppVersion>()?;
149        if latest_version <= current_version {
150            this.update(&mut cx, |this, cx| {
151                this.status = AutoUpdateStatus::Idle;
152                cx.notify();
153            });
154            return Ok(());
155        }
156
157        this.update(&mut cx, |this, cx| {
158            this.status = AutoUpdateStatus::Downloading;
159            cx.notify();
160        });
161
162        let temp_dir = tempdir::TempDir::new("zed-auto-update")?;
163        let dmg_path = temp_dir.path().join("Zed.dmg");
164        let mount_path = temp_dir.path().join("Zed");
165        let mut mounted_app_path: OsString = mount_path.join("Zed.app").into();
166        mounted_app_path.push("/");
167        let running_app_path = ZED_APP_PATH
168            .clone()
169            .map_or_else(|| cx.platform().app_path(), Ok)?;
170
171        let mut dmg_file = File::create(&dmg_path).await?;
172        let response = client
173            .send(Request::new(http::Method::Get, release.url))
174            .await?;
175        smol::io::copy(response.bytes(), &mut dmg_file).await?;
176        log::info!("downloaded update. path:{:?}", dmg_path);
177
178        this.update(&mut cx, |this, cx| {
179            this.status = AutoUpdateStatus::Installing;
180            cx.notify();
181        });
182
183        let output = Command::new("hdiutil")
184            .args(&["attach", "-nobrowse"])
185            .arg(&dmg_path)
186            .arg("-mountroot")
187            .arg(&temp_dir.path())
188            .output()
189            .await?;
190        if !output.status.success() {
191            Err(anyhow!(
192                "failed to mount: {:?}",
193                String::from_utf8_lossy(&output.stderr)
194            ))?;
195        }
196
197        let output = Command::new("rsync")
198            .args(&["-av", "--delete"])
199            .arg(&mounted_app_path)
200            .arg(&running_app_path)
201            .output()
202            .await?;
203        if !output.status.success() {
204            Err(anyhow!(
205                "failed to copy app: {:?}",
206                String::from_utf8_lossy(&output.stderr)
207            ))?;
208        }
209
210        let output = Command::new("hdiutil")
211            .args(&["detach"])
212            .arg(&mount_path)
213            .output()
214            .await?;
215        if !output.status.success() {
216            Err(anyhow!(
217                "failed to unmount: {:?}",
218                String::from_utf8_lossy(&output.stderr)
219            ))?;
220        }
221
222        this.update(&mut cx, |this, cx| {
223            this.status = AutoUpdateStatus::Updated;
224            cx.notify();
225        });
226        Ok(())
227    }
228}
229
230impl Entity for AutoUpdateIndicator {
231    type Event = ();
232}
233
234impl View for AutoUpdateIndicator {
235    fn ui_name() -> &'static str {
236        "AutoUpdateIndicator"
237    }
238
239    fn render(&mut self, cx: &mut gpui::RenderContext<'_, Self>) -> gpui::ElementBox {
240        if let Some(updater) = &self.updater {
241            let theme = &cx.global::<Settings>().theme.workspace.status_bar;
242            match &updater.read(cx).status {
243                AutoUpdateStatus::Checking => Text::new(
244                    "Checking for updates…".to_string(),
245                    theme.auto_update_progress_message.clone(),
246                )
247                .boxed(),
248                AutoUpdateStatus::Downloading => Text::new(
249                    "Downloading update…".to_string(),
250                    theme.auto_update_progress_message.clone(),
251                )
252                .boxed(),
253                AutoUpdateStatus::Installing => Text::new(
254                    "Installing update…".to_string(),
255                    theme.auto_update_progress_message.clone(),
256                )
257                .boxed(),
258                AutoUpdateStatus::Updated => Text::new(
259                    "Restart to update Zed".to_string(),
260                    theme.auto_update_done_message.clone(),
261                )
262                .boxed(),
263                AutoUpdateStatus::Errored => {
264                    MouseEventHandler::new::<Self, _, _>(0, cx, |_, cx| {
265                        let theme = &cx.global::<Settings>().theme.workspace.status_bar;
266                        Text::new(
267                            "Auto update failed".to_string(),
268                            theme.auto_update_done_message.clone(),
269                        )
270                        .boxed()
271                    })
272                    .on_click(|cx| cx.dispatch_action(DismissErrorMessage))
273                    .boxed()
274                }
275                AutoUpdateStatus::Idle => Empty::new().boxed(),
276            }
277        } else {
278            Empty::new().boxed()
279        }
280    }
281}
282
283impl StatusItemView for AutoUpdateIndicator {
284    fn set_active_pane_item(&mut self, _: Option<&dyn ItemHandle>, _: &mut ViewContext<Self>) {}
285}
286
287impl AutoUpdateIndicator {
288    pub fn new(cx: &mut ViewContext<Self>) -> Self {
289        let updater = AutoUpdater::get(cx);
290        if let Some(updater) = &updater {
291            cx.observe(updater, |_, _, cx| cx.notify()).detach();
292        }
293        Self { updater }
294    }
295
296    fn dismiss_error_message(&mut self, _: &DismissErrorMessage, cx: &mut ViewContext<Self>) {
297        if let Some(updater) = &self.updater {
298            updater.update(cx, |updater, cx| {
299                updater.status = AutoUpdateStatus::Idle;
300                cx.notify();
301            });
302        }
303    }
304}