auto_update.rs

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