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,
 10};
 11use isahc::AsyncBody;
 12use serde::Deserialize;
 13use serde_derive::Serialize;
 14use smol::io::AsyncReadExt;
 15
 16use settings::{Settings, SettingsStore};
 17use smol::{fs::File, process::Command};
 18use std::{ffi::OsString, sync::Arc, time::Duration};
 19use update_notification::UpdateNotification;
 20use util::channel::{AppCommitSha, ReleaseChannel};
 21use util::http::HttpClient;
 22use workspace::Workspace;
 23
 24const SHOULD_SHOW_UPDATE_NOTIFICATION_KEY: &str = "auto-updater-should-show-updated-notification";
 25const POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
 26
 27//todo!(remove CheckThatAutoUpdaterWorks)
 28actions!(
 29    Check,
 30    DismissErrorMessage,
 31    ViewReleaseNotes,
 32    CheckThatAutoUpdaterWorks
 33);
 34
 35#[derive(Serialize)]
 36struct UpdateRequestBody {
 37    installation_id: Option<Arc<str>>,
 38    release_channel: Option<&'static str>,
 39    telemetry: bool,
 40}
 41
 42#[derive(Clone, Copy, PartialEq, Eq)]
 43pub enum AutoUpdateStatus {
 44    Idle,
 45    Checking,
 46    Downloading,
 47    Installing,
 48    Updated,
 49    Errored,
 50}
 51
 52pub struct AutoUpdater {
 53    status: AutoUpdateStatus,
 54    current_version: SemanticVersion,
 55    http_client: Arc<dyn HttpClient>,
 56    pending_poll: Option<Task<Option<()>>>,
 57    server_url: String,
 58}
 59
 60#[derive(Deserialize)]
 61struct JsonRelease {
 62    version: String,
 63    url: String,
 64}
 65
 66struct AutoUpdateSetting(bool);
 67
 68impl Settings for AutoUpdateSetting {
 69    const KEY: Option<&'static str> = Some("auto_update");
 70
 71    type FileContent = Option<bool>;
 72
 73    fn load(
 74        default_value: &Option<bool>,
 75        user_values: &[&Option<bool>],
 76        _: &mut AppContext,
 77    ) -> Result<Self> {
 78        Ok(Self(
 79            Self::json_merge(default_value, user_values)?.ok_or_else(Self::missing_default)?,
 80        ))
 81    }
 82}
 83
 84pub fn init(http_client: Arc<dyn HttpClient>, server_url: String, cx: &mut AppContext) {
 85    AutoUpdateSetting::register(cx);
 86
 87    cx.observe_new_views(|workspace: &mut Workspace, _cx| {
 88        workspace
 89            .register_action(|_, action: &Check, cx| check(action, cx))
 90            .register_action(|_, _action: &CheckThatAutoUpdaterWorks, cx| {
 91                let prompt = cx.prompt(gpui::PromptLevel::Info, "It does!", &["Ok"]);
 92                cx.spawn(|_, _cx| async move {
 93                    prompt.await.ok();
 94                })
 95                .detach();
 96            });
 97
 98        // @nate - code to trigger update notification on launch
 99        // workspace.show_notification(0, _cx, |cx| {
100        //     cx.build_view(|_| UpdateNotification::new(SemanticVersion::from_str("1.1.1").unwrap()))
101        // });
102    })
103    .detach();
104
105    if let Some(version) = *ZED_APP_VERSION {
106        let auto_updater = cx.build_model(|cx| {
107            let updater = AutoUpdater::new(version, http_client, server_url);
108
109            let mut update_subscription = AutoUpdateSetting::get_global(cx)
110                .0
111                .then(|| updater.start_polling(cx));
112
113            cx.observe_global::<SettingsStore>(move |updater, cx| {
114                if AutoUpdateSetting::get_global(cx).0 {
115                    if update_subscription.is_none() {
116                        update_subscription = Some(updater.start_polling(cx))
117                    }
118                } else {
119                    update_subscription.take();
120                }
121            })
122            .detach();
123
124            updater
125        });
126        cx.set_global(Some(auto_updater));
127        //todo!(action)
128        // cx.add_global_action(view_release_notes);
129        // cx.add_action(UpdateNotification::dismiss);
130    }
131}
132
133pub fn check(_: &Check, cx: &mut AppContext) {
134    if let Some(updater) = AutoUpdater::get(cx) {
135        updater.update(cx, |updater, cx| updater.poll(cx));
136    }
137}
138
139pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut AppContext) {
140    if let Some(auto_updater) = AutoUpdater::get(cx) {
141        let auto_updater = auto_updater.read(cx);
142        let server_url = &auto_updater.server_url;
143        let current_version = auto_updater.current_version;
144        if cx.has_global::<ReleaseChannel>() {
145            match cx.global::<ReleaseChannel>() {
146                ReleaseChannel::Dev => {}
147                ReleaseChannel::Nightly => {}
148                ReleaseChannel::Preview => {
149                    cx.open_url(&format!("{server_url}/releases/preview/{current_version}"))
150                }
151                ReleaseChannel::Stable => {
152                    cx.open_url(&format!("{server_url}/releases/stable/{current_version}"))
153                }
154            }
155        }
156    }
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.build_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!(
253            "{server_url}/api/releases/latest?token={ZED_SECRET_CLIENT_TOKEN}&asset=Zed.dmg"
254        );
255        cx.update(|cx| {
256            if cx.has_global::<ReleaseChannel>() {
257                if let Some(param) = cx.global::<ReleaseChannel>().release_query_param() {
258                    url_string += "&";
259                    url_string += param;
260                }
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 = tempdir::TempDir::new("zed-auto-update")?;
296        let dmg_path = temp_dir.path().join("Zed.dmg");
297        let mount_path = temp_dir.path().join("Zed");
298        let running_app_path = ZED_APP_PATH
299            .clone()
300            .map_or_else(|| cx.update(|cx| cx.app_path())?, Ok)?;
301        let running_app_filename = running_app_path
302            .file_name()
303            .ok_or_else(|| anyhow!("invalid running app path"))?;
304        let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
305        mounted_app_path.push("/");
306
307        let mut dmg_file = File::create(&dmg_path).await?;
308
309        let (installation_id, release_channel, telemetry) = cx.update(|cx| {
310            let installation_id = cx.global::<Arc<Client>>().telemetry().installation_id();
311            let release_channel = cx
312                .has_global::<ReleaseChannel>()
313                .then(|| cx.global::<ReleaseChannel>().display_name());
314            let telemetry = TelemetrySettings::get_global(cx).metrics;
315
316            (installation_id, release_channel, telemetry)
317        })?;
318
319        let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
320            installation_id,
321            release_channel,
322            telemetry,
323        })?);
324
325        let mut response = client.get(&release.url, request_body, true).await?;
326        smol::io::copy(response.body_mut(), &mut dmg_file).await?;
327        log::info!("downloaded update. path:{:?}", dmg_path);
328
329        this.update(&mut cx, |this, cx| {
330            this.status = AutoUpdateStatus::Installing;
331            cx.notify();
332        })?;
333
334        let output = Command::new("hdiutil")
335            .args(&["attach", "-nobrowse"])
336            .arg(&dmg_path)
337            .arg("-mountroot")
338            .arg(&temp_dir.path())
339            .output()
340            .await?;
341        if !output.status.success() {
342            Err(anyhow!(
343                "failed to mount: {:?}",
344                String::from_utf8_lossy(&output.stderr)
345            ))?;
346        }
347
348        let output = Command::new("rsync")
349            .args(&["-av", "--delete"])
350            .arg(&mounted_app_path)
351            .arg(&running_app_path)
352            .output()
353            .await?;
354        if !output.status.success() {
355            Err(anyhow!(
356                "failed to copy app: {:?}",
357                String::from_utf8_lossy(&output.stderr)
358            ))?;
359        }
360
361        let output = Command::new("hdiutil")
362            .args(&["detach"])
363            .arg(&mount_path)
364            .output()
365            .await?;
366        if !output.status.success() {
367            Err(anyhow!(
368                "failed to unmount: {:?}",
369                String::from_utf8_lossy(&output.stderr)
370            ))?;
371        }
372
373        this.update(&mut cx, |this, cx| {
374            this.set_should_show_update_notification(true, cx)
375                .detach_and_log_err(cx);
376            this.status = AutoUpdateStatus::Updated;
377            cx.notify();
378        })?;
379        Ok(())
380    }
381
382    fn set_should_show_update_notification(
383        &self,
384        should_show: bool,
385        cx: &AppContext,
386    ) -> Task<Result<()>> {
387        cx.background_executor().spawn(async move {
388            if should_show {
389                KEY_VALUE_STORE
390                    .write_kvp(
391                        SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
392                        "".to_string(),
393                    )
394                    .await?;
395            } else {
396                KEY_VALUE_STORE
397                    .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
398                    .await?;
399            }
400            Ok(())
401        })
402    }
403
404    fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
405        cx.background_executor().spawn(async move {
406            Ok(KEY_VALUE_STORE
407                .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
408                .is_some())
409        })
410    }
411}