auto_update.rs

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