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 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        // @nate - code to trigger update notification on launch
101        // todo!("remove this when Nate is done")
102        // workspace.show_notification(0, _cx, |cx| {
103        //     cx.build_view(|_| UpdateNotification::new(SemanticVersion::from_str("1.1.1").unwrap()))
104        // });
105    })
106    .detach();
107
108    if let Some(version) = ZED_APP_VERSION.or_else(|| cx.app_metadata().app_version) {
109        let auto_updater = cx.new_model(|cx| {
110            let updater = AutoUpdater::new(version, http_client, server_url);
111
112            let mut update_subscription = AutoUpdateSetting::get_global(cx)
113                .0
114                .then(|| updater.start_polling(cx));
115
116            cx.observe_global::<SettingsStore>(move |updater, cx| {
117                if AutoUpdateSetting::get_global(cx).0 {
118                    if update_subscription.is_none() {
119                        update_subscription = Some(updater.start_polling(cx))
120                    }
121                } else {
122                    update_subscription.take();
123                }
124            })
125            .detach();
126
127            updater
128        });
129        cx.set_global(Some(auto_updater));
130    }
131}
132
133pub fn check(_: &Check, cx: &mut WindowContext) {
134    if let Some(updater) = AutoUpdater::get(cx) {
135        updater.update(cx, |updater, cx| updater.poll(cx));
136    } else {
137        drop(cx.prompt(
138            gpui::PromptLevel::Info,
139            "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?token={ZED_SECRET_CLIENT_TOKEN}&asset=Zed.dmg"
259        );
260        cx.update(|cx| {
261            if let Some(param) = cx
262                .try_global::<ReleaseChannel>()
263                .map(|release_channel| release_channel.release_query_param())
264                .flatten()
265            {
266                url_string += "&";
267                url_string += param;
268            }
269        })?;
270
271        let mut response = client.get(&url_string, Default::default(), true).await?;
272
273        let mut body = Vec::new();
274        response
275            .body_mut()
276            .read_to_end(&mut body)
277            .await
278            .context("error reading release")?;
279        let release: JsonRelease =
280            serde_json::from_slice(body.as_slice()).context("error deserializing release")?;
281
282        let should_download = match *RELEASE_CHANNEL {
283            ReleaseChannel::Nightly => cx
284                .try_read_global::<AppCommitSha, _>(|sha, _| release.version != sha.0)
285                .unwrap_or(true),
286            _ => release.version.parse::<SemanticVersion>()? > current_version,
287        };
288
289        if !should_download {
290            this.update(&mut cx, |this, cx| {
291                this.status = AutoUpdateStatus::Idle;
292                cx.notify();
293            })?;
294            return Ok(());
295        }
296
297        this.update(&mut cx, |this, cx| {
298            this.status = AutoUpdateStatus::Downloading;
299            cx.notify();
300        })?;
301
302        let temp_dir = tempdir::TempDir::new("zed-auto-update")?;
303        let dmg_path = temp_dir.path().join("Zed.dmg");
304        let mount_path = temp_dir.path().join("Zed");
305        let running_app_path = ZED_APP_PATH
306            .clone()
307            .map_or_else(|| cx.update(|cx| cx.app_path())?, Ok)?;
308        let running_app_filename = running_app_path
309            .file_name()
310            .ok_or_else(|| anyhow!("invalid running app path"))?;
311        let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
312        mounted_app_path.push("/");
313
314        let mut dmg_file = File::create(&dmg_path).await?;
315
316        let (installation_id, release_channel, telemetry) = cx.update(|cx| {
317            let installation_id = cx.global::<Arc<Client>>().telemetry().installation_id();
318            let release_channel = cx
319                .try_global::<ReleaseChannel>()
320                .map(|release_channel| release_channel.display_name());
321            let telemetry = TelemetrySettings::get_global(cx).metrics;
322
323            (installation_id, release_channel, telemetry)
324        })?;
325
326        let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
327            installation_id,
328            release_channel,
329            telemetry,
330        })?);
331
332        let mut response = client.get(&release.url, request_body, true).await?;
333        smol::io::copy(response.body_mut(), &mut dmg_file).await?;
334        log::info!("downloaded update. path:{:?}", dmg_path);
335
336        this.update(&mut cx, |this, cx| {
337            this.status = AutoUpdateStatus::Installing;
338            cx.notify();
339        })?;
340
341        let output = Command::new("hdiutil")
342            .args(&["attach", "-nobrowse"])
343            .arg(&dmg_path)
344            .arg("-mountroot")
345            .arg(&temp_dir.path())
346            .output()
347            .await?;
348        if !output.status.success() {
349            Err(anyhow!(
350                "failed to mount: {:?}",
351                String::from_utf8_lossy(&output.stderr)
352            ))?;
353        }
354
355        let output = Command::new("rsync")
356            .args(&["-av", "--delete"])
357            .arg(&mounted_app_path)
358            .arg(&running_app_path)
359            .output()
360            .await?;
361        if !output.status.success() {
362            Err(anyhow!(
363                "failed to copy app: {:?}",
364                String::from_utf8_lossy(&output.stderr)
365            ))?;
366        }
367
368        let output = Command::new("hdiutil")
369            .args(&["detach"])
370            .arg(&mount_path)
371            .output()
372            .await?;
373        if !output.status.success() {
374            Err(anyhow!(
375                "failed to unmount: {:?}",
376                String::from_utf8_lossy(&output.stderr)
377            ))?;
378        }
379
380        this.update(&mut cx, |this, cx| {
381            this.set_should_show_update_notification(true, cx)
382                .detach_and_log_err(cx);
383            this.status = AutoUpdateStatus::Updated;
384            cx.notify();
385        })?;
386        Ok(())
387    }
388
389    fn set_should_show_update_notification(
390        &self,
391        should_show: bool,
392        cx: &AppContext,
393    ) -> Task<Result<()>> {
394        cx.background_executor().spawn(async move {
395            if should_show {
396                KEY_VALUE_STORE
397                    .write_kvp(
398                        SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
399                        "".to_string(),
400                    )
401                    .await?;
402            } else {
403                KEY_VALUE_STORE
404                    .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
405                    .await?;
406            }
407            Ok(())
408        })
409    }
410
411    fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
412        cx.background_executor().spawn(async move {
413            Ok(KEY_VALUE_STORE
414                .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
415                .is_some())
416        })
417    }
418}