1use anyhow::{Context, Result};
2use channel::{ChannelMessage, ChannelMessageId, ChannelStore};
3use client::{ChannelId, Client, UserStore};
4use collections::HashMap;
5use db::smol::stream::StreamExt;
6use gpui::{
7 AppContext, AsyncAppContext, Context as _, EventEmitter, Global, Model, ModelContext, Task,
8};
9use rpc::{proto, Notification, TypedEnvelope};
10use std::{ops::Range, sync::Arc};
11use sum_tree::{Bias, SumTree};
12use time::OffsetDateTime;
13use util::ResultExt;
14
15pub fn init(client: Arc<Client>, user_store: Model<UserStore>, cx: &mut AppContext) {
16 let notification_store = cx.new_model(|cx| NotificationStore::new(client, user_store, cx));
17 cx.set_global(GlobalNotificationStore(notification_store));
18}
19
20struct GlobalNotificationStore(Model<NotificationStore>);
21
22impl Global for GlobalNotificationStore {}
23
24pub struct NotificationStore {
25 client: Arc<Client>,
26 user_store: Model<UserStore>,
27 channel_messages: HashMap<u64, ChannelMessage>,
28 channel_store: Model<ChannelStore>,
29 notifications: SumTree<NotificationEntry>,
30 loaded_all_notifications: bool,
31 _watch_connection_status: Task<Option<()>>,
32 _subscriptions: Vec<client::Subscription>,
33}
34
35#[derive(Clone, PartialEq, Eq, Debug)]
36pub enum NotificationEvent {
37 NotificationsUpdated {
38 old_range: Range<usize>,
39 new_count: usize,
40 },
41 NewNotification {
42 entry: NotificationEntry,
43 },
44 NotificationRemoved {
45 entry: NotificationEntry,
46 },
47 NotificationRead {
48 entry: NotificationEntry,
49 },
50}
51
52#[derive(Debug, PartialEq, Eq, Clone)]
53pub struct NotificationEntry {
54 pub id: u64,
55 pub notification: Notification,
56 pub timestamp: OffsetDateTime,
57 pub is_read: bool,
58 pub response: Option<bool>,
59}
60
61#[derive(Clone, Debug, Default)]
62pub struct NotificationSummary {
63 max_id: u64,
64 count: usize,
65 unread_count: usize,
66}
67
68#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
69struct Count(usize);
70
71#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
72struct UnreadCount(usize);
73
74#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
75struct NotificationId(u64);
76
77impl NotificationStore {
78 pub fn global(cx: &AppContext) -> Model<Self> {
79 cx.global::<GlobalNotificationStore>().0.clone()
80 }
81
82 pub fn new(
83 client: Arc<Client>,
84 user_store: Model<UserStore>,
85 cx: &mut ModelContext<Self>,
86 ) -> Self {
87 let mut connection_status = client.status();
88 let watch_connection_status = cx.spawn(|this, mut cx| async move {
89 while let Some(status) = connection_status.next().await {
90 let this = this.upgrade()?;
91 match status {
92 client::Status::Connected { .. } => {
93 if let Some(task) = this
94 .update(&mut cx, |this, cx| this.handle_connect(cx))
95 .log_err()?
96 {
97 task.await.log_err()?;
98 }
99 }
100 _ => this
101 .update(&mut cx, |this, cx| this.handle_disconnect(cx))
102 .log_err()?,
103 }
104 }
105 Some(())
106 });
107
108 Self {
109 channel_store: ChannelStore::global(cx),
110 notifications: Default::default(),
111 loaded_all_notifications: false,
112 channel_messages: Default::default(),
113 _watch_connection_status: watch_connection_status,
114 _subscriptions: vec![
115 client.add_message_handler(cx.weak_model(), Self::handle_new_notification),
116 client.add_message_handler(cx.weak_model(), Self::handle_delete_notification),
117 client.add_message_handler(cx.weak_model(), Self::handle_update_notification),
118 ],
119 user_store,
120 client,
121 }
122 }
123
124 pub fn notification_count(&self) -> usize {
125 self.notifications.summary().count
126 }
127
128 pub fn unread_notification_count(&self) -> usize {
129 self.notifications.summary().unread_count
130 }
131
132 pub fn channel_message_for_id(&self, id: u64) -> Option<&ChannelMessage> {
133 self.channel_messages.get(&id)
134 }
135
136 // Get the nth newest notification.
137 pub fn notification_at(&self, ix: usize) -> Option<&NotificationEntry> {
138 let count = self.notifications.summary().count;
139 if ix >= count {
140 return None;
141 }
142 let ix = count - 1 - ix;
143 let mut cursor = self.notifications.cursor::<Count>();
144 cursor.seek(&Count(ix), Bias::Right, &());
145 cursor.item()
146 }
147
148 pub fn notification_for_id(&self, id: u64) -> Option<&NotificationEntry> {
149 let mut cursor = self.notifications.cursor::<NotificationId>();
150 cursor.seek(&NotificationId(id), Bias::Left, &());
151 if let Some(item) = cursor.item() {
152 if item.id == id {
153 return Some(item);
154 }
155 }
156 None
157 }
158
159 pub fn load_more_notifications(
160 &self,
161 clear_old: bool,
162 cx: &mut ModelContext<Self>,
163 ) -> Option<Task<Result<()>>> {
164 if self.loaded_all_notifications && !clear_old {
165 return None;
166 }
167
168 let before_id = if clear_old {
169 None
170 } else {
171 self.notifications.first().map(|entry| entry.id)
172 };
173 let request = self.client.request(proto::GetNotifications { before_id });
174 Some(cx.spawn(|this, mut cx| async move {
175 let this = this
176 .upgrade()
177 .context("Notification store was dropped while loading notifications")?;
178
179 let response = request.await?;
180 this.update(&mut cx, |this, _| {
181 this.loaded_all_notifications = response.done
182 })?;
183 Self::add_notifications(
184 this,
185 response.notifications,
186 AddNotificationsOptions {
187 is_new: false,
188 clear_old,
189 includes_first: response.done,
190 },
191 cx,
192 )
193 .await?;
194 Ok(())
195 }))
196 }
197
198 fn handle_connect(&mut self, cx: &mut ModelContext<Self>) -> Option<Task<Result<()>>> {
199 self.notifications = Default::default();
200 self.channel_messages = Default::default();
201 cx.notify();
202 self.load_more_notifications(true, cx)
203 }
204
205 fn handle_disconnect(&mut self, cx: &mut ModelContext<Self>) {
206 cx.notify()
207 }
208
209 async fn handle_new_notification(
210 this: Model<Self>,
211 envelope: TypedEnvelope<proto::AddNotification>,
212 cx: AsyncAppContext,
213 ) -> Result<()> {
214 Self::add_notifications(
215 this,
216 envelope.payload.notification.into_iter().collect(),
217 AddNotificationsOptions {
218 is_new: true,
219 clear_old: false,
220 includes_first: false,
221 },
222 cx,
223 )
224 .await
225 }
226
227 async fn handle_delete_notification(
228 this: Model<Self>,
229 envelope: TypedEnvelope<proto::DeleteNotification>,
230 mut cx: AsyncAppContext,
231 ) -> Result<()> {
232 this.update(&mut cx, |this, cx| {
233 this.splice_notifications([(envelope.payload.notification_id, None)], false, cx);
234 Ok(())
235 })?
236 }
237
238 async fn handle_update_notification(
239 this: Model<Self>,
240 envelope: TypedEnvelope<proto::UpdateNotification>,
241 mut cx: AsyncAppContext,
242 ) -> Result<()> {
243 this.update(&mut cx, |this, cx| {
244 if let Some(notification) = envelope.payload.notification {
245 if let Some(rpc::Notification::ChannelMessageMention {
246 message_id,
247 sender_id: _,
248 channel_id: _,
249 }) = Notification::from_proto(¬ification)
250 {
251 let fetch_message_task = this.channel_store.update(cx, |this, cx| {
252 this.fetch_channel_messages(vec![message_id], cx)
253 });
254
255 cx.spawn(|this, mut cx| async move {
256 let messages = fetch_message_task.await?;
257 this.update(&mut cx, move |this, cx| {
258 for message in messages {
259 this.channel_messages.insert(message_id, message);
260 }
261 cx.notify();
262 })
263 })
264 .detach_and_log_err(cx)
265 }
266 }
267 Ok(())
268 })?
269 }
270
271 async fn add_notifications(
272 this: Model<Self>,
273 notifications: Vec<proto::Notification>,
274 options: AddNotificationsOptions,
275 mut cx: AsyncAppContext,
276 ) -> Result<()> {
277 let mut user_ids = Vec::new();
278 let mut message_ids = Vec::new();
279
280 let notifications = notifications
281 .into_iter()
282 .filter_map(|message| {
283 Some(NotificationEntry {
284 id: message.id,
285 is_read: message.is_read,
286 timestamp: OffsetDateTime::from_unix_timestamp(message.timestamp as i64)
287 .ok()?,
288 notification: Notification::from_proto(&message)?,
289 response: message.response,
290 })
291 })
292 .collect::<Vec<_>>();
293 if notifications.is_empty() {
294 return Ok(());
295 }
296
297 for entry in ¬ifications {
298 match entry.notification {
299 Notification::ChannelInvitation { inviter_id, .. } => {
300 user_ids.push(inviter_id);
301 }
302 Notification::ContactRequest {
303 sender_id: requester_id,
304 } => {
305 user_ids.push(requester_id);
306 }
307 Notification::ContactRequestAccepted {
308 responder_id: contact_id,
309 } => {
310 user_ids.push(contact_id);
311 }
312 Notification::ChannelMessageMention {
313 sender_id,
314 message_id,
315 ..
316 } => {
317 user_ids.push(sender_id);
318 message_ids.push(message_id);
319 }
320 }
321 }
322
323 let (user_store, channel_store) = this.read_with(&cx, |this, _| {
324 (this.user_store.clone(), this.channel_store.clone())
325 })?;
326
327 user_store
328 .update(&mut cx, |store, cx| store.get_users(user_ids, cx))?
329 .await?;
330 let messages = channel_store
331 .update(&mut cx, |store, cx| {
332 store.fetch_channel_messages(message_ids, cx)
333 })?
334 .await?;
335 this.update(&mut cx, |this, cx| {
336 if options.clear_old {
337 cx.emit(NotificationEvent::NotificationsUpdated {
338 old_range: 0..this.notifications.summary().count,
339 new_count: 0,
340 });
341 this.notifications = SumTree::default();
342 this.channel_messages.clear();
343 this.loaded_all_notifications = false;
344 }
345
346 if options.includes_first {
347 this.loaded_all_notifications = true;
348 }
349
350 this.channel_messages
351 .extend(messages.into_iter().filter_map(|message| {
352 if let ChannelMessageId::Saved(id) = message.id {
353 Some((id, message))
354 } else {
355 None
356 }
357 }));
358
359 this.splice_notifications(
360 notifications
361 .into_iter()
362 .map(|notification| (notification.id, Some(notification))),
363 options.is_new,
364 cx,
365 );
366 })
367 .log_err();
368
369 Ok(())
370 }
371
372 fn splice_notifications(
373 &mut self,
374 notifications: impl IntoIterator<Item = (u64, Option<NotificationEntry>)>,
375 is_new: bool,
376 cx: &mut ModelContext<'_, NotificationStore>,
377 ) {
378 let mut cursor = self.notifications.cursor::<(NotificationId, Count)>();
379 let mut new_notifications = SumTree::new();
380 let mut old_range = 0..0;
381
382 for (i, (id, new_notification)) in notifications.into_iter().enumerate() {
383 new_notifications.append(cursor.slice(&NotificationId(id), Bias::Left, &()), &());
384
385 if i == 0 {
386 old_range.start = cursor.start().1 .0;
387 }
388
389 let old_notification = cursor.item();
390 if let Some(old_notification) = old_notification {
391 if old_notification.id == id {
392 cursor.next(&());
393
394 if let Some(new_notification) = &new_notification {
395 if new_notification.is_read {
396 cx.emit(NotificationEvent::NotificationRead {
397 entry: new_notification.clone(),
398 });
399 }
400 } else {
401 cx.emit(NotificationEvent::NotificationRemoved {
402 entry: old_notification.clone(),
403 });
404 }
405 }
406 } else if let Some(new_notification) = &new_notification {
407 if is_new {
408 cx.emit(NotificationEvent::NewNotification {
409 entry: new_notification.clone(),
410 });
411 }
412 }
413
414 if let Some(notification) = new_notification {
415 new_notifications.push(notification, &());
416 }
417 }
418
419 old_range.end = cursor.start().1 .0;
420 let new_count = new_notifications.summary().count - old_range.start;
421 new_notifications.append(cursor.suffix(&()), &());
422 drop(cursor);
423
424 self.notifications = new_notifications;
425 cx.emit(NotificationEvent::NotificationsUpdated {
426 old_range,
427 new_count,
428 });
429 }
430
431 pub fn respond_to_notification(
432 &mut self,
433 notification: Notification,
434 response: bool,
435 cx: &mut ModelContext<Self>,
436 ) {
437 match notification {
438 Notification::ContactRequest { sender_id } => {
439 self.user_store
440 .update(cx, |store, cx| {
441 store.respond_to_contact_request(sender_id, response, cx)
442 })
443 .detach();
444 }
445 Notification::ChannelInvitation { channel_id, .. } => {
446 self.channel_store
447 .update(cx, |store, cx| {
448 store.respond_to_channel_invite(ChannelId(channel_id), response, cx)
449 })
450 .detach();
451 }
452 _ => {}
453 }
454 }
455}
456
457impl EventEmitter<NotificationEvent> for NotificationStore {}
458
459impl sum_tree::Item for NotificationEntry {
460 type Summary = NotificationSummary;
461
462 fn summary(&self) -> Self::Summary {
463 NotificationSummary {
464 max_id: self.id,
465 count: 1,
466 unread_count: if self.is_read { 0 } else { 1 },
467 }
468 }
469}
470
471impl sum_tree::Summary for NotificationSummary {
472 type Context = ();
473
474 fn add_summary(&mut self, summary: &Self, _: &()) {
475 self.max_id = self.max_id.max(summary.max_id);
476 self.count += summary.count;
477 self.unread_count += summary.unread_count;
478 }
479}
480
481impl<'a> sum_tree::Dimension<'a, NotificationSummary> for NotificationId {
482 fn add_summary(&mut self, summary: &NotificationSummary, _: &()) {
483 debug_assert!(summary.max_id > self.0);
484 self.0 = summary.max_id;
485 }
486}
487
488impl<'a> sum_tree::Dimension<'a, NotificationSummary> for Count {
489 fn add_summary(&mut self, summary: &NotificationSummary, _: &()) {
490 self.0 += summary.count;
491 }
492}
493
494impl<'a> sum_tree::Dimension<'a, NotificationSummary> for UnreadCount {
495 fn add_summary(&mut self, summary: &NotificationSummary, _: &()) {
496 self.0 += summary.unread_count;
497 }
498}
499
500struct AddNotificationsOptions {
501 is_new: bool,
502 clear_old: bool,
503 includes_first: bool,
504}