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