auto_update.rs

  1mod update_notification;
  2
  3use anyhow::{anyhow, Context, Result};
  4use client::{ZED_APP_PATH, ZED_APP_VERSION, ZED_SECRET_CLIENT_TOKEN};
  5use db::kvp::KEY_VALUE_STORE;
  6use gpui::{
  7    actions, platform::AppVersion, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
  8    MutableAppContext, Task, WeakViewHandle,
  9};
 10use serde::Deserialize;
 11use settings::Settings;
 12use smol::{fs::File, io::AsyncReadExt, process::Command};
 13use std::{ffi::OsString, sync::Arc, time::Duration};
 14use update_notification::UpdateNotification;
 15use util::channel::ReleaseChannel;
 16use util::http::HttpClient;
 17use workspace::Workspace;
 18
 19const SHOULD_SHOW_UPDATE_NOTIFICATION_KEY: &str = "auto-updater-should-show-updated-notification";
 20const POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
 21
 22actions!(auto_update, [Check, DismissErrorMessage, ViewReleaseNotes]);
 23
 24#[derive(Clone, Copy, PartialEq, Eq)]
 25pub enum AutoUpdateStatus {
 26    Idle,
 27    Checking,
 28    Downloading,
 29    Installing,
 30    Updated,
 31    Errored,
 32}
 33
 34pub struct AutoUpdater {
 35    status: AutoUpdateStatus,
 36    current_version: AppVersion,
 37    http_client: Arc<dyn HttpClient>,
 38    pending_poll: Option<Task<()>>,
 39    server_url: String,
 40}
 41
 42#[derive(Deserialize)]
 43struct JsonRelease {
 44    version: String,
 45    url: String,
 46}
 47
 48impl Entity for AutoUpdater {
 49    type Event = ();
 50}
 51
 52pub fn init(http_client: Arc<dyn HttpClient>, server_url: String, cx: &mut MutableAppContext) {
 53    if let Some(version) = (*ZED_APP_VERSION).or_else(|| cx.platform().app_version().ok()) {
 54        let server_url = server_url;
 55        let auto_updater = cx.add_model(|cx| {
 56            let updater = AutoUpdater::new(version, http_client, server_url.clone());
 57
 58            let mut update_subscription = cx
 59                .global::<Settings>()
 60                .auto_update
 61                .then(|| updater.start_polling(cx));
 62
 63            cx.observe_global::<Settings, _>(move |updater, cx| {
 64                if cx.global::<Settings>().auto_update {
 65                    if update_subscription.is_none() {
 66                        *(&mut update_subscription) = Some(updater.start_polling(cx))
 67                    }
 68                } else {
 69                    (&mut update_subscription).take();
 70                }
 71            })
 72            .detach();
 73
 74            updater
 75        });
 76        cx.set_global(Some(auto_updater));
 77        cx.add_global_action(|_: &Check, cx| {
 78            if let Some(updater) = AutoUpdater::get(cx) {
 79                updater.update(cx, |updater, cx| updater.poll(cx));
 80            }
 81        });
 82        cx.add_global_action(move |_: &ViewReleaseNotes, cx| {
 83            let latest_release_url = if cx.has_global::<ReleaseChannel>()
 84                && *cx.global::<ReleaseChannel>() == ReleaseChannel::Preview
 85            {
 86                format!("{server_url}/releases/preview/latest")
 87            } else {
 88                format!("{server_url}/releases/latest")
 89            };
 90            cx.platform().open_url(&latest_release_url);
 91        });
 92        cx.add_action(UpdateNotification::dismiss);
 93    }
 94}
 95
 96pub fn notify_of_any_new_update(
 97    workspace: WeakViewHandle<Workspace>,
 98    cx: &mut MutableAppContext,
 99) -> Option<()> {
100    let updater = AutoUpdater::get(cx)?;
101    let version = updater.read(cx).current_version;
102    let should_show_notification = updater.read(cx).should_show_update_notification(cx);
103
104    cx.spawn(|mut cx| async move {
105        let should_show_notification = should_show_notification.await?;
106        if should_show_notification {
107            if let Some(workspace) = workspace.upgrade(&cx) {
108                workspace.update(&mut cx, |workspace, cx| {
109                    workspace.show_notification(0, cx, |cx| {
110                        cx.add_view(|_| UpdateNotification::new(version))
111                    });
112                    updater
113                        .read(cx)
114                        .set_should_show_update_notification(false, cx)
115                        .detach_and_log_err(cx);
116                });
117            }
118        }
119        anyhow::Ok(())
120    })
121    .detach();
122
123    None
124}
125
126impl AutoUpdater {
127    pub fn get(cx: &mut MutableAppContext) -> Option<ModelHandle<Self>> {
128        cx.default_global::<Option<ModelHandle<Self>>>().clone()
129    }
130
131    fn new(
132        current_version: AppVersion,
133        http_client: Arc<dyn HttpClient>,
134        server_url: String,
135    ) -> Self {
136        Self {
137            status: AutoUpdateStatus::Idle,
138            current_version,
139            http_client,
140            server_url,
141            pending_poll: None,
142        }
143    }
144
145    pub fn start_polling(&self, cx: &mut ModelContext<Self>) -> Task<()> {
146        cx.spawn(|this, mut cx| async move {
147            loop {
148                this.update(&mut cx, |this, cx| this.poll(cx));
149                cx.background().timer(POLL_INTERVAL).await;
150            }
151        })
152    }
153
154    pub fn poll(&mut self, cx: &mut ModelContext<Self>) {
155        if self.pending_poll.is_some() || self.status == AutoUpdateStatus::Updated {
156            return;
157        }
158
159        self.status = AutoUpdateStatus::Checking;
160        cx.notify();
161
162        self.pending_poll = Some(cx.spawn(|this, mut cx| async move {
163            let result = Self::update(this.clone(), cx.clone()).await;
164            this.update(&mut cx, |this, cx| {
165                this.pending_poll = None;
166                if let Err(error) = result {
167                    log::error!("auto-update failed: error:{:?}", error);
168                    this.status = AutoUpdateStatus::Errored;
169                    cx.notify();
170                }
171            });
172        }));
173    }
174
175    pub fn status(&self) -> AutoUpdateStatus {
176        self.status
177    }
178
179    pub fn dismiss_error(&mut self, cx: &mut ModelContext<Self>) {
180        self.status = AutoUpdateStatus::Idle;
181        cx.notify();
182    }
183
184    async fn update(this: ModelHandle<Self>, mut cx: AsyncAppContext) -> Result<()> {
185        let (client, server_url, current_version) = this.read_with(&cx, |this, _| {
186            (
187                this.http_client.clone(),
188                this.server_url.clone(),
189                this.current_version,
190            )
191        });
192
193        let preview_param = cx.read(|cx| {
194            if cx.has_global::<ReleaseChannel>() {
195                if *cx.global::<ReleaseChannel>() == ReleaseChannel::Preview {
196                    return "&preview=1";
197                }
198            }
199            ""
200        });
201
202        let mut response = client
203            .get(
204                &format!("{server_url}/api/releases/latest?token={ZED_SECRET_CLIENT_TOKEN}&asset=Zed.dmg{preview_param}"),
205                Default::default(),
206                true,
207            )
208            .await?;
209
210        let mut body = Vec::new();
211        response
212            .body_mut()
213            .read_to_end(&mut body)
214            .await
215            .context("error reading release")?;
216        let release: JsonRelease =
217            serde_json::from_slice(body.as_slice()).context("error deserializing release")?;
218
219        let latest_version = release.version.parse::<AppVersion>()?;
220        if latest_version <= current_version {
221            this.update(&mut cx, |this, cx| {
222                this.status = AutoUpdateStatus::Idle;
223                cx.notify();
224            });
225            return Ok(());
226        }
227
228        this.update(&mut cx, |this, cx| {
229            this.status = AutoUpdateStatus::Downloading;
230            cx.notify();
231        });
232
233        let temp_dir = tempdir::TempDir::new("zed-auto-update")?;
234        let dmg_path = temp_dir.path().join("Zed.dmg");
235        let mount_path = temp_dir.path().join("Zed");
236        let running_app_path = ZED_APP_PATH
237            .clone()
238            .map_or_else(|| cx.platform().app_path(), Ok)?;
239        let running_app_filename = running_app_path
240            .file_name()
241            .ok_or_else(|| anyhow!("invalid running app path"))?;
242        let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
243        mounted_app_path.push("/");
244
245        let mut dmg_file = File::create(&dmg_path).await?;
246        let mut response = client.get(&release.url, Default::default(), true).await?;
247        smol::io::copy(response.body_mut(), &mut dmg_file).await?;
248        log::info!("downloaded update. path:{:?}", dmg_path);
249
250        this.update(&mut cx, |this, cx| {
251            this.status = AutoUpdateStatus::Installing;
252            cx.notify();
253        });
254
255        let output = Command::new("hdiutil")
256            .args(&["attach", "-nobrowse"])
257            .arg(&dmg_path)
258            .arg("-mountroot")
259            .arg(&temp_dir.path())
260            .output()
261            .await?;
262        if !output.status.success() {
263            Err(anyhow!(
264                "failed to mount: {:?}",
265                String::from_utf8_lossy(&output.stderr)
266            ))?;
267        }
268
269        let output = Command::new("rsync")
270            .args(&["-av", "--delete"])
271            .arg(&mounted_app_path)
272            .arg(&running_app_path)
273            .output()
274            .await?;
275        if !output.status.success() {
276            Err(anyhow!(
277                "failed to copy app: {:?}",
278                String::from_utf8_lossy(&output.stderr)
279            ))?;
280        }
281
282        let output = Command::new("hdiutil")
283            .args(&["detach"])
284            .arg(&mount_path)
285            .output()
286            .await?;
287        if !output.status.success() {
288            Err(anyhow!(
289                "failed to unmount: {:?}",
290                String::from_utf8_lossy(&output.stderr)
291            ))?;
292        }
293
294        this.update(&mut cx, |this, cx| {
295            this.set_should_show_update_notification(true, cx)
296                .detach_and_log_err(cx);
297            this.status = AutoUpdateStatus::Updated;
298            cx.notify();
299        });
300        Ok(())
301    }
302
303    fn set_should_show_update_notification(
304        &self,
305        should_show: bool,
306        cx: &AppContext,
307    ) -> Task<Result<()>> {
308        cx.background().spawn(async move {
309            if should_show {
310                KEY_VALUE_STORE
311                    .write_kvp(
312                        SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
313                        "".to_string(),
314                    )
315                    .await?;
316            } else {
317                KEY_VALUE_STORE
318                    .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
319                    .await?;
320            }
321            Ok(())
322        })
323    }
324
325    fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
326        cx.background().spawn(async move {
327            Ok(KEY_VALUE_STORE
328                .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
329                .is_some())
330        })
331    }
332}