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