notifier.rs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. use flowy_user_data_model::entities::UserProfile;
  2. use tokio::sync::{broadcast, mpsc};
  3. #[derive(Clone)]
  4. pub enum UserStatus {
  5. Login {
  6. token: String,
  7. user_id: String,
  8. },
  9. Logout {
  10. token: String,
  11. },
  12. Expired {
  13. token: String,
  14. },
  15. SignUp {
  16. profile: UserProfile,
  17. ret: mpsc::Sender<()>,
  18. },
  19. }
  20. pub struct UserNotifier {
  21. user_status_notifier: broadcast::Sender<UserStatus>,
  22. }
  23. impl std::default::Default for UserNotifier {
  24. fn default() -> Self {
  25. let (user_status_notifier, _) = broadcast::channel(10);
  26. UserNotifier { user_status_notifier }
  27. }
  28. }
  29. impl UserNotifier {
  30. pub(crate) fn new() -> Self {
  31. UserNotifier::default()
  32. }
  33. pub(crate) fn notify_login(&self, token: &str, user_id: &str) {
  34. let _ = self.user_status_notifier.send(UserStatus::Login {
  35. token: token.to_owned(),
  36. user_id: user_id.to_owned(),
  37. });
  38. }
  39. pub(crate) fn notify_sign_up(&self, ret: mpsc::Sender<()>, user_profile: &UserProfile) {
  40. let _ = self.user_status_notifier.send(UserStatus::SignUp {
  41. profile: user_profile.clone(),
  42. ret,
  43. });
  44. }
  45. pub(crate) fn notify_logout(&self, token: &str) {
  46. let _ = self.user_status_notifier.send(UserStatus::Logout {
  47. token: token.to_owned(),
  48. });
  49. }
  50. pub fn subscribe_user_status(&self) -> broadcast::Receiver<UserStatus> {
  51. self.user_status_notifier.subscribe()
  52. }
  53. }