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| view_release_notes(action, cx));
97
98 // @nate - code to trigger update notification on launch
99 // todo!("remove this when Nate is done")
100 // workspace.show_notification(0, _cx, |cx| {
101 // cx.build_view(|_| UpdateNotification::new(SemanticVersion::from_str("1.1.1").unwrap()))
102 // });
103 })
104 .detach();
105
106 if let Some(version) = ZED_APP_VERSION.or_else(|| cx.app_metadata().app_version) {
107 let auto_updater = cx.new_model(|cx| {
108 let updater = AutoUpdater::new(version, http_client, server_url);
109
110 let mut update_subscription = AutoUpdateSetting::get_global(cx)
111 .0
112 .then(|| updater.start_polling(cx));
113
114 cx.observe_global::<SettingsStore>(move |updater, cx| {
115 if AutoUpdateSetting::get_global(cx).0 {
116 if update_subscription.is_none() {
117 update_subscription = Some(updater.start_polling(cx))
118 }
119 } else {
120 update_subscription.take();
121 }
122 })
123 .detach();
124
125 updater
126 });
127 cx.set_global(Some(auto_updater));
128 }
129}
130
131pub fn check(_: &Check, cx: &mut WindowContext) {
132 if let Some(updater) = AutoUpdater::get(cx) {
133 updater.update(cx, |updater, cx| updater.poll(cx));
134 } else {
135 drop(cx.prompt(
136 gpui::PromptLevel::Info,
137 "Auto-updates disabled for non-bundled app.",
138 &["Ok"],
139 ));
140 }
141}
142
143pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut AppContext) {
144 if let Some(auto_updater) = AutoUpdater::get(cx) {
145 let auto_updater = auto_updater.read(cx);
146 let server_url = &auto_updater.server_url;
147 let current_version = auto_updater.current_version;
148 if cx.has_global::<ReleaseChannel>() {
149 match cx.global::<ReleaseChannel>() {
150 ReleaseChannel::Dev => {}
151 ReleaseChannel::Nightly => {}
152 ReleaseChannel::Preview => {
153 cx.open_url(&format!("{server_url}/releases/preview/{current_version}"))
154 }
155 ReleaseChannel::Stable => {
156 cx.open_url(&format!("{server_url}/releases/stable/{current_version}"))
157 }
158 }
159 }
160 }
161}
162
163pub fn notify_of_any_new_update(cx: &mut ViewContext<Workspace>) -> Option<()> {
164 let updater = AutoUpdater::get(cx)?;
165 let version = updater.read(cx).current_version;
166 let should_show_notification = updater.read(cx).should_show_update_notification(cx);
167
168 cx.spawn(|workspace, mut cx| async move {
169 let should_show_notification = should_show_notification.await?;
170 if should_show_notification {
171 workspace.update(&mut cx, |workspace, cx| {
172 workspace.show_notification(0, cx, |cx| {
173 cx.new_view(|_| UpdateNotification::new(version))
174 });
175 updater
176 .read(cx)
177 .set_should_show_update_notification(false, cx)
178 .detach_and_log_err(cx);
179 })?;
180 }
181 anyhow::Ok(())
182 })
183 .detach();
184
185 None
186}
187
188impl AutoUpdater {
189 pub fn get(cx: &mut AppContext) -> Option<Model<Self>> {
190 cx.default_global::<Option<Model<Self>>>().clone()
191 }
192
193 fn new(
194 current_version: SemanticVersion,
195 http_client: Arc<dyn HttpClient>,
196 server_url: String,
197 ) -> Self {
198 Self {
199 status: AutoUpdateStatus::Idle,
200 current_version,
201 http_client,
202 server_url,
203 pending_poll: None,
204 }
205 }
206
207 pub fn start_polling(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
208 cx.spawn(|this, mut cx| async move {
209 loop {
210 this.update(&mut cx, |this, cx| this.poll(cx))?;
211 cx.background_executor().timer(POLL_INTERVAL).await;
212 }
213 })
214 }
215
216 pub fn poll(&mut self, cx: &mut ModelContext<Self>) {
217 if self.pending_poll.is_some() || self.status == AutoUpdateStatus::Updated {
218 return;
219 }
220
221 self.status = AutoUpdateStatus::Checking;
222 cx.notify();
223
224 self.pending_poll = Some(cx.spawn(|this, mut cx| async move {
225 let result = Self::update(this.upgrade()?, cx.clone()).await;
226 this.update(&mut cx, |this, cx| {
227 this.pending_poll = None;
228 if let Err(error) = result {
229 log::error!("auto-update failed: error:{:?}", error);
230 this.status = AutoUpdateStatus::Errored;
231 cx.notify();
232 }
233 })
234 .ok()
235 }));
236 }
237
238 pub fn status(&self) -> AutoUpdateStatus {
239 self.status
240 }
241
242 pub fn dismiss_error(&mut self, cx: &mut ModelContext<Self>) {
243 self.status = AutoUpdateStatus::Idle;
244 cx.notify();
245 }
246
247 async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> Result<()> {
248 let (client, server_url, current_version) = this.read_with(&cx, |this, _| {
249 (
250 this.http_client.clone(),
251 this.server_url.clone(),
252 this.current_version,
253 )
254 })?;
255
256 let mut url_string = format!(
257 "{server_url}/api/releases/latest?token={ZED_SECRET_CLIENT_TOKEN}&asset=Zed.dmg"
258 );
259 cx.update(|cx| {
260 if cx.has_global::<ReleaseChannel>() {
261 if let Some(param) = cx.global::<ReleaseChannel>().release_query_param() {
262 url_string += "&";
263 url_string += param;
264 }
265 }
266 })?;
267
268 let mut response = client.get(&url_string, Default::default(), true).await?;
269
270 let mut body = Vec::new();
271 response
272 .body_mut()
273 .read_to_end(&mut body)
274 .await
275 .context("error reading release")?;
276 let release: JsonRelease =
277 serde_json::from_slice(body.as_slice()).context("error deserializing release")?;
278
279 let should_download = match *RELEASE_CHANNEL {
280 ReleaseChannel::Nightly => cx
281 .try_read_global::<AppCommitSha, _>(|sha, _| release.version != sha.0)
282 .unwrap_or(true),
283 _ => release.version.parse::<SemanticVersion>()? > current_version,
284 };
285
286 if !should_download {
287 this.update(&mut cx, |this, cx| {
288 this.status = AutoUpdateStatus::Idle;
289 cx.notify();
290 })?;
291 return Ok(());
292 }
293
294 this.update(&mut cx, |this, cx| {
295 this.status = AutoUpdateStatus::Downloading;
296 cx.notify();
297 })?;
298
299 let temp_dir = tempdir::TempDir::new("zed-auto-update")?;
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 .has_global::<ReleaseChannel>()
317 .then(|| cx.global::<ReleaseChannel>().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}