1mod update_notification;
2
3use anyhow::{anyhow, Context, Result};
4use client::{http::HttpClient, ZED_SECRET_CLIENT_TOKEN};
5use db::kvp::KEY_VALUE_STORE;
6use gpui::{
7 actions, platform::AppVersion, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
8 MutableAppContext, Task, WeakViewHandle,
9};
10use lazy_static::lazy_static;
11use serde::Deserialize;
12use smol::{fs::File, io::AsyncReadExt, process::Command};
13use std::{env, ffi::OsString, path::PathBuf, sync::Arc, time::Duration};
14use update_notification::UpdateNotification;
15use util::channel::ReleaseChannel;
16use workspace::Workspace;
17
18const SHOULD_SHOW_UPDATE_NOTIFICATION_KEY: &str = "auto-updater-should-show-updated-notification";
19const POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
20
21lazy_static! {
22 pub static ref ZED_APP_VERSION: Option<AppVersion> = env::var("ZED_APP_VERSION")
23 .ok()
24 .and_then(|v| v.parse().ok());
25 pub static ref ZED_APP_PATH: Option<PathBuf> = env::var("ZED_APP_PATH").ok().map(PathBuf::from);
26}
27
28actions!(auto_update, [Check, DismissErrorMessage, ViewReleaseNotes]);
29
30#[derive(Clone, Copy, PartialEq, Eq)]
31pub enum AutoUpdateStatus {
32 Idle,
33 Checking,
34 Downloading,
35 Installing,
36 Updated,
37 Errored,
38}
39
40pub struct AutoUpdater {
41 status: AutoUpdateStatus,
42 current_version: AppVersion,
43 http_client: Arc<dyn HttpClient>,
44 pending_poll: Option<Task<()>>,
45 server_url: String,
46}
47
48#[derive(Deserialize)]
49struct JsonRelease {
50 version: String,
51 url: String,
52}
53
54impl Entity for AutoUpdater {
55 type Event = ();
56}
57
58pub fn init(http_client: Arc<dyn HttpClient>, server_url: String, cx: &mut MutableAppContext) {
59 if let Some(version) = (*ZED_APP_VERSION).or_else(|| cx.platform().app_version().ok()) {
60 let server_url = server_url;
61 let auto_updater = cx.add_model(|cx| {
62 let updater = AutoUpdater::new(version, http_client, server_url.clone());
63 updater.start_polling(cx).detach();
64 updater
65 });
66 cx.set_global(Some(auto_updater));
67 cx.add_global_action(|_: &Check, cx| {
68 if let Some(updater) = AutoUpdater::get(cx) {
69 updater.update(cx, |updater, cx| updater.poll(cx));
70 }
71 });
72 cx.add_global_action(move |_: &ViewReleaseNotes, cx| {
73 let latest_release_url = if cx.has_global::<ReleaseChannel>()
74 && *cx.global::<ReleaseChannel>() == ReleaseChannel::Preview
75 {
76 format!("{server_url}/releases/preview/latest")
77 } else {
78 format!("{server_url}/releases/latest")
79 };
80 cx.platform().open_url(&latest_release_url);
81 });
82 cx.add_action(UpdateNotification::dismiss);
83 }
84}
85
86pub fn notify_of_any_new_update(
87 workspace: WeakViewHandle<Workspace>,
88 cx: &mut MutableAppContext,
89) -> Option<()> {
90 let updater = AutoUpdater::get(cx)?;
91 let version = updater.read(cx).current_version;
92 let should_show_notification = updater.read(cx).should_show_update_notification(cx);
93
94 cx.spawn(|mut cx| async move {
95 let should_show_notification = should_show_notification.await?;
96 if should_show_notification {
97 if let Some(workspace) = workspace.upgrade(&cx) {
98 workspace.update(&mut cx, |workspace, cx| {
99 workspace.show_notification(0, cx, |cx| {
100 cx.add_view(|_| UpdateNotification::new(version))
101 });
102 updater
103 .read(cx)
104 .set_should_show_update_notification(false, cx)
105 .detach_and_log_err(cx);
106 });
107 }
108 }
109 anyhow::Ok(())
110 })
111 .detach();
112
113 None
114}
115
116impl AutoUpdater {
117 pub fn get(cx: &mut MutableAppContext) -> Option<ModelHandle<Self>> {
118 cx.default_global::<Option<ModelHandle<Self>>>().clone()
119 }
120
121 fn new(
122 current_version: AppVersion,
123 http_client: Arc<dyn HttpClient>,
124 server_url: String,
125 ) -> Self {
126 Self {
127 status: AutoUpdateStatus::Idle,
128 current_version,
129 http_client,
130 server_url,
131 pending_poll: None,
132 }
133 }
134
135 pub fn start_polling(&self, cx: &mut ModelContext<Self>) -> Task<()> {
136 cx.spawn(|this, mut cx| async move {
137 loop {
138 this.update(&mut cx, |this, cx| this.poll(cx));
139 cx.background().timer(POLL_INTERVAL).await;
140 }
141 })
142 }
143
144 pub fn poll(&mut self, cx: &mut ModelContext<Self>) {
145 if self.pending_poll.is_some() || self.status == AutoUpdateStatus::Updated {
146 return;
147 }
148
149 self.status = AutoUpdateStatus::Checking;
150 cx.notify();
151
152 self.pending_poll = Some(cx.spawn(|this, mut cx| async move {
153 let result = Self::update(this.clone(), cx.clone()).await;
154 this.update(&mut cx, |this, cx| {
155 this.pending_poll = None;
156 if let Err(error) = result {
157 log::error!("auto-update failed: error:{:?}", error);
158 this.status = AutoUpdateStatus::Errored;
159 cx.notify();
160 }
161 });
162 }));
163 }
164
165 pub fn status(&self) -> AutoUpdateStatus {
166 self.status
167 }
168
169 pub fn dismiss_error(&mut self, cx: &mut ModelContext<Self>) {
170 self.status = AutoUpdateStatus::Idle;
171 cx.notify();
172 }
173
174 async fn update(this: ModelHandle<Self>, mut cx: AsyncAppContext) -> Result<()> {
175 let (client, server_url, current_version) = this.read_with(&cx, |this, _| {
176 (
177 this.http_client.clone(),
178 this.server_url.clone(),
179 this.current_version,
180 )
181 });
182
183 let preview_param = cx.read(|cx| {
184 if cx.has_global::<ReleaseChannel>() {
185 if *cx.global::<ReleaseChannel>() == ReleaseChannel::Preview {
186 return "&preview=1";
187 }
188 }
189 ""
190 });
191
192 let mut response = client
193 .get(
194 &format!("{server_url}/api/releases/latest?token={ZED_SECRET_CLIENT_TOKEN}&asset=Zed.dmg{preview_param}"),
195 Default::default(),
196 true,
197 )
198 .await?;
199
200 let mut body = Vec::new();
201 response
202 .body_mut()
203 .read_to_end(&mut body)
204 .await
205 .context("error reading release")?;
206 let release: JsonRelease =
207 serde_json::from_slice(body.as_slice()).context("error deserializing release")?;
208
209 let latest_version = release.version.parse::<AppVersion>()?;
210 if latest_version <= current_version {
211 this.update(&mut cx, |this, cx| {
212 this.status = AutoUpdateStatus::Idle;
213 cx.notify();
214 });
215 return Ok(());
216 }
217
218 this.update(&mut cx, |this, cx| {
219 this.status = AutoUpdateStatus::Downloading;
220 cx.notify();
221 });
222
223 let temp_dir = tempdir::TempDir::new("zed-auto-update")?;
224 let dmg_path = temp_dir.path().join("Zed.dmg");
225 let mount_path = temp_dir.path().join("Zed");
226 let running_app_path = ZED_APP_PATH
227 .clone()
228 .map_or_else(|| cx.platform().app_path(), Ok)?;
229 let running_app_filename = running_app_path
230 .file_name()
231 .ok_or_else(|| anyhow!("invalid running app path"))?;
232 let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
233 mounted_app_path.push("/");
234
235 let mut dmg_file = File::create(&dmg_path).await?;
236 let mut response = client.get(&release.url, Default::default(), true).await?;
237 smol::io::copy(response.body_mut(), &mut dmg_file).await?;
238 log::info!("downloaded update. path:{:?}", dmg_path);
239
240 this.update(&mut cx, |this, cx| {
241 this.status = AutoUpdateStatus::Installing;
242 cx.notify();
243 });
244
245 let output = Command::new("hdiutil")
246 .args(&["attach", "-nobrowse"])
247 .arg(&dmg_path)
248 .arg("-mountroot")
249 .arg(&temp_dir.path())
250 .output()
251 .await?;
252 if !output.status.success() {
253 Err(anyhow!(
254 "failed to mount: {:?}",
255 String::from_utf8_lossy(&output.stderr)
256 ))?;
257 }
258
259 let output = Command::new("rsync")
260 .args(&["-av", "--delete"])
261 .arg(&mounted_app_path)
262 .arg(&running_app_path)
263 .output()
264 .await?;
265 if !output.status.success() {
266 Err(anyhow!(
267 "failed to copy app: {:?}",
268 String::from_utf8_lossy(&output.stderr)
269 ))?;
270 }
271
272 let output = Command::new("hdiutil")
273 .args(&["detach"])
274 .arg(&mount_path)
275 .output()
276 .await?;
277 if !output.status.success() {
278 Err(anyhow!(
279 "failed to unmount: {:?}",
280 String::from_utf8_lossy(&output.stderr)
281 ))?;
282 }
283
284 this.update(&mut cx, |this, cx| {
285 this.set_should_show_update_notification(true, cx)
286 .detach_and_log_err(cx);
287 this.status = AutoUpdateStatus::Updated;
288 cx.notify();
289 });
290 Ok(())
291 }
292
293 fn set_should_show_update_notification(
294 &self,
295 should_show: bool,
296 cx: &AppContext,
297 ) -> Task<Result<()>> {
298 cx.background().spawn(async move {
299 if should_show {
300 KEY_VALUE_STORE
301 .write_kvp(
302 SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
303 "".to_string(),
304 )
305 .await?;
306 } else {
307 KEY_VALUE_STORE
308 .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
309 .await?;
310 }
311 Ok(())
312 })
313 }
314
315 fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
316 cx.background().spawn(async move {
317 Ok(KEY_VALUE_STORE
318 .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
319 .is_some())
320 })
321 }
322}