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