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
149 if let Some(release_channel) = cx.try_global::<ReleaseChannel>() {
150 let channel = match release_channel {
151 ReleaseChannel::Preview => "preview",
152 ReleaseChannel::Stable => "stable",
153 _ => return,
154 };
155 cx.open_url(&format!(
156 "{server_url}/releases/{channel}/{current_version}"
157 ))
158 }
159 }
160}
161
162pub fn notify_of_any_new_update(cx: &mut ViewContext<Workspace>) -> Option<()> {
163 let updater = AutoUpdater::get(cx)?;
164 let version = updater.read(cx).current_version;
165 let should_show_notification = updater.read(cx).should_show_update_notification(cx);
166
167 cx.spawn(|workspace, mut cx| async move {
168 let should_show_notification = should_show_notification.await?;
169 if should_show_notification {
170 workspace.update(&mut cx, |workspace, cx| {
171 workspace.show_notification(0, cx, |cx| {
172 cx.new_view(|_| UpdateNotification::new(version))
173 });
174 updater
175 .read(cx)
176 .set_should_show_update_notification(false, cx)
177 .detach_and_log_err(cx);
178 })?;
179 }
180 anyhow::Ok(())
181 })
182 .detach();
183
184 None
185}
186
187impl AutoUpdater {
188 pub fn get(cx: &mut AppContext) -> Option<Model<Self>> {
189 cx.default_global::<Option<Model<Self>>>().clone()
190 }
191
192 fn new(
193 current_version: SemanticVersion,
194 http_client: Arc<dyn HttpClient>,
195 server_url: String,
196 ) -> Self {
197 Self {
198 status: AutoUpdateStatus::Idle,
199 current_version,
200 http_client,
201 server_url,
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, server_url, current_version) = this.read_with(&cx, |this, _| {
248 (
249 this.http_client.clone(),
250 this.server_url.clone(),
251 this.current_version,
252 )
253 })?;
254
255 let mut url_string = format!(
256 "{server_url}/api/releases/latest?token={ZED_SECRET_CLIENT_TOKEN}&asset=Zed.dmg"
257 );
258 cx.update(|cx| {
259 if let Some(param) = cx
260 .try_global::<ReleaseChannel>()
261 .map(|release_channel| release_channel.release_query_param())
262 .flatten()
263 {
264 url_string += "&";
265 url_string += param;
266 }
267 })?;
268
269 let mut response = client.get(&url_string, Default::default(), true).await?;
270
271 let mut body = Vec::new();
272 response
273 .body_mut()
274 .read_to_end(&mut body)
275 .await
276 .context("error reading release")?;
277 let release: JsonRelease =
278 serde_json::from_slice(body.as_slice()).context("error deserializing release")?;
279
280 let should_download = match *RELEASE_CHANNEL {
281 ReleaseChannel::Nightly => cx
282 .try_read_global::<AppCommitSha, _>(|sha, _| release.version != sha.0)
283 .unwrap_or(true),
284 _ => release.version.parse::<SemanticVersion>()? > current_version,
285 };
286
287 if !should_download {
288 this.update(&mut cx, |this, cx| {
289 this.status = AutoUpdateStatus::Idle;
290 cx.notify();
291 })?;
292 return Ok(());
293 }
294
295 this.update(&mut cx, |this, cx| {
296 this.status = AutoUpdateStatus::Downloading;
297 cx.notify();
298 })?;
299
300 let temp_dir = tempdir::TempDir::new("zed-auto-update")?;
301 let dmg_path = temp_dir.path().join("Zed.dmg");
302 let mount_path = temp_dir.path().join("Zed");
303 let running_app_path = ZED_APP_PATH
304 .clone()
305 .map_or_else(|| cx.update(|cx| cx.app_path())?, Ok)?;
306 let running_app_filename = running_app_path
307 .file_name()
308 .ok_or_else(|| anyhow!("invalid running app path"))?;
309 let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
310 mounted_app_path.push("/");
311
312 let mut dmg_file = File::create(&dmg_path).await?;
313
314 let (installation_id, release_channel, telemetry) = cx.update(|cx| {
315 let installation_id = cx.global::<Arc<Client>>().telemetry().installation_id();
316 let release_channel = cx
317 .try_global::<ReleaseChannel>()
318 .map(|release_channel| release_channel.display_name());
319 let telemetry = TelemetrySettings::get_global(cx).metrics;
320
321 (installation_id, release_channel, telemetry)
322 })?;
323
324 let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
325 installation_id,
326 release_channel,
327 telemetry,
328 })?);
329
330 let mut response = client.get(&release.url, request_body, true).await?;
331 smol::io::copy(response.body_mut(), &mut dmg_file).await?;
332 log::info!("downloaded update. path:{:?}", dmg_path);
333
334 this.update(&mut cx, |this, cx| {
335 this.status = AutoUpdateStatus::Installing;
336 cx.notify();
337 })?;
338
339 let output = Command::new("hdiutil")
340 .args(&["attach", "-nobrowse"])
341 .arg(&dmg_path)
342 .arg("-mountroot")
343 .arg(&temp_dir.path())
344 .output()
345 .await?;
346 if !output.status.success() {
347 Err(anyhow!(
348 "failed to mount: {:?}",
349 String::from_utf8_lossy(&output.stderr)
350 ))?;
351 }
352
353 let output = Command::new("rsync")
354 .args(&["-av", "--delete"])
355 .arg(&mounted_app_path)
356 .arg(&running_app_path)
357 .output()
358 .await?;
359 if !output.status.success() {
360 Err(anyhow!(
361 "failed to copy app: {:?}",
362 String::from_utf8_lossy(&output.stderr)
363 ))?;
364 }
365
366 let output = Command::new("hdiutil")
367 .args(&["detach"])
368 .arg(&mount_path)
369 .output()
370 .await?;
371 if !output.status.success() {
372 Err(anyhow!(
373 "failed to unmount: {:?}",
374 String::from_utf8_lossy(&output.stderr)
375 ))?;
376 }
377
378 this.update(&mut cx, |this, cx| {
379 this.set_should_show_update_notification(true, cx)
380 .detach_and_log_err(cx);
381 this.status = AutoUpdateStatus::Updated;
382 cx.notify();
383 })?;
384 Ok(())
385 }
386
387 fn set_should_show_update_notification(
388 &self,
389 should_show: bool,
390 cx: &AppContext,
391 ) -> Task<Result<()>> {
392 cx.background_executor().spawn(async move {
393 if should_show {
394 KEY_VALUE_STORE
395 .write_kvp(
396 SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
397 "".to_string(),
398 )
399 .await?;
400 } else {
401 KEY_VALUE_STORE
402 .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
403 .await?;
404 }
405 Ok(())
406 })
407 }
408
409 fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
410 cx.background_executor().spawn(async move {
411 Ok(KEY_VALUE_STORE
412 .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
413 .is_some())
414 })
415 }
416}