auto_update.rs

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