event_map.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. use std::sync::{Arc, Weak};
  2. use collab_database::database::WatchStream;
  3. use collab_folder::core::FolderData;
  4. use strum_macros::Display;
  5. use flowy_derive::{Flowy_Event, ProtoBuf_Enum};
  6. use flowy_error::FlowyResult;
  7. use flowy_user_deps::cloud::{UserCloudConfig, UserCloudService};
  8. use flowy_user_deps::entities::*;
  9. use lib_dispatch::prelude::*;
  10. use lib_infra::future::{to_fut, Fut};
  11. use crate::errors::FlowyError;
  12. use crate::event_handler::*;
  13. use crate::manager::UserManager;
  14. pub fn init(user_session: Weak<UserManager>) -> AFPlugin {
  15. let store_preferences = user_session
  16. .upgrade()
  17. .map(|session| session.get_store_preferences())
  18. .unwrap();
  19. AFPlugin::new()
  20. .name("Flowy-User")
  21. .state(user_session)
  22. .state(store_preferences)
  23. .event(UserEvent::SignIn, sign_in)
  24. .event(UserEvent::SignUp, sign_up)
  25. .event(UserEvent::InitUser, init_user_handler)
  26. .event(UserEvent::GetUserProfile, get_user_profile_handler)
  27. .event(UserEvent::SignOut, sign_out)
  28. .event(UserEvent::UpdateUserProfile, update_user_profile_handler)
  29. .event(UserEvent::CheckUser, check_user_handler)
  30. .event(UserEvent::SetAppearanceSetting, set_appearance_setting)
  31. .event(UserEvent::GetAppearanceSetting, get_appearance_setting)
  32. .event(UserEvent::GetUserSetting, get_user_setting)
  33. .event(UserEvent::SetCloudConfig, set_cloud_config_handler)
  34. .event(UserEvent::GetCloudConfig, get_cloud_config_handler)
  35. .event(UserEvent::SetEncryptionSecret, set_encrypt_secret_handler)
  36. .event(UserEvent::CheckEncryptionSign, check_encrypt_secret_handler)
  37. .event(UserEvent::OauthSignIn, oauth_handler)
  38. .event(UserEvent::GetSignInURL, get_sign_in_url_handler)
  39. .event(
  40. UserEvent::GetOauthURLWithProvider,
  41. sign_in_with_provider_handler,
  42. )
  43. .event(
  44. UserEvent::GetAllUserWorkspaces,
  45. get_all_user_workspace_handler,
  46. )
  47. .event(UserEvent::OpenWorkspace, open_workspace_handler)
  48. .event(UserEvent::AddUserToWorkspace, add_user_to_workspace_handler)
  49. .event(
  50. UserEvent::RemoveUserToWorkspace,
  51. remove_user_from_workspace_handler,
  52. )
  53. .event(UserEvent::UpdateNetworkState, update_network_state_handler)
  54. .event(UserEvent::GetHistoricalUsers, get_historical_users_handler)
  55. .event(UserEvent::OpenHistoricalUser, open_historical_users_handler)
  56. .event(UserEvent::PushRealtimeEvent, push_realtime_event_handler)
  57. .event(UserEvent::CreateReminder, create_reminder_event_handler)
  58. .event(UserEvent::GetAllReminders, get_all_reminder_event_handler)
  59. .event(UserEvent::RemoveReminder, remove_reminder_event_handler)
  60. .event(UserEvent::UpdateReminder, update_reminder_event_handler)
  61. .event(UserEvent::ResetWorkspace, reset_workspace_handler)
  62. .event(UserEvent::SetDateTimeSettings, set_date_time_settings)
  63. .event(UserEvent::GetDateTimeSettings, get_date_time_settings)
  64. }
  65. pub struct SignUpContext {
  66. /// Indicate whether the user is new or not.
  67. pub is_new: bool,
  68. /// If the user is sign in as guest, and the is_new is true, then the folder data will be not
  69. /// None.
  70. pub local_folder: Option<FolderData>,
  71. }
  72. pub trait UserStatusCallback: Send + Sync + 'static {
  73. /// When the [AuthType] changed, this method will be called. Currently, the auth type
  74. /// will be changed when the user sign in or sign up.
  75. fn auth_type_did_changed(&self, _auth_type: AuthType) {}
  76. /// This will be called after the application launches if the user is already signed in.
  77. /// If the user is not signed in, this method will not be called
  78. fn did_init(
  79. &self,
  80. user_id: i64,
  81. cloud_config: &Option<UserCloudConfig>,
  82. user_workspace: &UserWorkspace,
  83. device_id: &str,
  84. ) -> Fut<FlowyResult<()>>;
  85. /// Will be called after the user signed in.
  86. fn did_sign_in(
  87. &self,
  88. user_id: i64,
  89. user_workspace: &UserWorkspace,
  90. device_id: &str,
  91. ) -> Fut<FlowyResult<()>>;
  92. /// Will be called after the user signed up.
  93. fn did_sign_up(
  94. &self,
  95. is_new_user: bool,
  96. user_profile: &UserProfile,
  97. user_workspace: &UserWorkspace,
  98. device_id: &str,
  99. ) -> Fut<FlowyResult<()>>;
  100. fn did_expired(&self, token: &str, user_id: i64) -> Fut<FlowyResult<()>>;
  101. fn open_workspace(&self, user_id: i64, user_workspace: &UserWorkspace) -> Fut<FlowyResult<()>>;
  102. fn did_update_network(&self, _reachable: bool) {}
  103. }
  104. /// The user cloud service provider.
  105. /// The provider can be supabase, firebase, aws, or any other cloud service.
  106. pub trait UserCloudServiceProvider: Send + Sync + 'static {
  107. fn set_token(&self, token: &str) -> Result<(), FlowyError>;
  108. fn subscribe_token_state(&self) -> Option<WatchStream<UserTokenState>> {
  109. None
  110. }
  111. fn set_enable_sync(&self, uid: i64, enable_sync: bool);
  112. fn set_encrypt_secret(&self, secret: String);
  113. fn set_auth_type(&self, auth_type: AuthType);
  114. fn set_device_id(&self, device_id: &str);
  115. fn get_user_service(&self) -> Result<Arc<dyn UserCloudService>, FlowyError>;
  116. fn service_name(&self) -> String;
  117. }
  118. impl<T> UserCloudServiceProvider for Arc<T>
  119. where
  120. T: UserCloudServiceProvider,
  121. {
  122. fn set_token(&self, token: &str) -> Result<(), FlowyError> {
  123. (**self).set_token(token)
  124. }
  125. fn set_enable_sync(&self, uid: i64, enable_sync: bool) {
  126. (**self).set_enable_sync(uid, enable_sync)
  127. }
  128. fn set_encrypt_secret(&self, secret: String) {
  129. (**self).set_encrypt_secret(secret)
  130. }
  131. fn set_auth_type(&self, auth_type: AuthType) {
  132. (**self).set_auth_type(auth_type)
  133. }
  134. fn set_device_id(&self, device_id: &str) {
  135. (**self).set_device_id(device_id)
  136. }
  137. fn get_user_service(&self) -> Result<Arc<dyn UserCloudService>, FlowyError> {
  138. (**self).get_user_service()
  139. }
  140. fn service_name(&self) -> String {
  141. (**self).service_name()
  142. }
  143. }
  144. /// Acts as a placeholder [UserStatusCallback] for the user session, but does not perform any function
  145. pub(crate) struct DefaultUserStatusCallback;
  146. impl UserStatusCallback for DefaultUserStatusCallback {
  147. fn did_init(
  148. &self,
  149. _user_id: i64,
  150. _cloud_config: &Option<UserCloudConfig>,
  151. _user_workspace: &UserWorkspace,
  152. _device_id: &str,
  153. ) -> Fut<FlowyResult<()>> {
  154. to_fut(async { Ok(()) })
  155. }
  156. fn did_sign_in(
  157. &self,
  158. _user_id: i64,
  159. _user_workspace: &UserWorkspace,
  160. _device_id: &str,
  161. ) -> Fut<FlowyResult<()>> {
  162. to_fut(async { Ok(()) })
  163. }
  164. fn did_sign_up(
  165. &self,
  166. _is_new_user: bool,
  167. _user_profile: &UserProfile,
  168. _user_workspace: &UserWorkspace,
  169. _device_id: &str,
  170. ) -> Fut<FlowyResult<()>> {
  171. to_fut(async { Ok(()) })
  172. }
  173. fn did_expired(&self, _token: &str, _user_id: i64) -> Fut<FlowyResult<()>> {
  174. to_fut(async { Ok(()) })
  175. }
  176. fn open_workspace(&self, _user_id: i64, _user_workspace: &UserWorkspace) -> Fut<FlowyResult<()>> {
  177. to_fut(async { Ok(()) })
  178. }
  179. }
  180. #[derive(Clone, Copy, PartialEq, Eq, Debug, Display, Hash, ProtoBuf_Enum, Flowy_Event)]
  181. #[event_err = "FlowyError"]
  182. pub enum UserEvent {
  183. /// Only use when the [AuthType] is Local or SelfHosted
  184. /// Logging into an account using a register email and password
  185. #[event(input = "SignInPayloadPB", output = "UserProfilePB")]
  186. SignIn = 0,
  187. /// Only use when the [AuthType] is Local or SelfHosted
  188. /// Creating a new account
  189. #[event(input = "SignUpPayloadPB", output = "UserProfilePB")]
  190. SignUp = 1,
  191. /// Logging out fo an account
  192. #[event()]
  193. SignOut = 2,
  194. /// Update the user information
  195. #[event(input = "UpdateUserProfilePayloadPB")]
  196. UpdateUserProfile = 3,
  197. /// Get the user information
  198. #[event(output = "UserProfilePB")]
  199. GetUserProfile = 4,
  200. /// Check the user current session is valid or not
  201. #[event(output = "UserProfilePB")]
  202. CheckUser = 5,
  203. /// Initialize resources for the current user after launching the application
  204. #[event()]
  205. InitUser = 6,
  206. /// Change the visual elements of the interface, such as theme, font and more
  207. #[event(input = "AppearanceSettingsPB")]
  208. SetAppearanceSetting = 7,
  209. /// Get the appearance setting
  210. #[event(output = "AppearanceSettingsPB")]
  211. GetAppearanceSetting = 8,
  212. /// Get the settings of the user, such as the user storage folder
  213. #[event(output = "UserSettingPB")]
  214. GetUserSetting = 9,
  215. #[event(input = "OauthSignInPB", output = "UserProfilePB")]
  216. OauthSignIn = 10,
  217. /// Get the OAuth callback url
  218. /// Only use when the [AuthType] is AFCloud
  219. #[event(input = "SignInUrlPayloadPB", output = "SignInUrlPB")]
  220. GetSignInURL = 11,
  221. #[event(input = "OauthProviderPB", output = "OauthProviderDataPB")]
  222. GetOauthURLWithProvider = 12,
  223. #[event(input = "UpdateCloudConfigPB")]
  224. SetCloudConfig = 13,
  225. #[event(output = "UserCloudConfigPB")]
  226. GetCloudConfig = 14,
  227. #[event(input = "UserSecretPB")]
  228. SetEncryptionSecret = 15,
  229. #[event(output = "UserEncryptionSecretCheckPB")]
  230. CheckEncryptionSign = 16,
  231. /// Return the all the workspaces of the user
  232. #[event()]
  233. GetAllUserWorkspaces = 20,
  234. #[event(input = "UserWorkspacePB")]
  235. OpenWorkspace = 21,
  236. #[event(input = "AddWorkspaceUserPB")]
  237. AddUserToWorkspace = 22,
  238. #[event(input = "RemoveWorkspaceUserPB")]
  239. RemoveUserToWorkspace = 23,
  240. #[event(input = "NetworkStatePB")]
  241. UpdateNetworkState = 24,
  242. #[event(output = "RepeatedHistoricalUserPB")]
  243. GetHistoricalUsers = 25,
  244. #[event(input = "HistoricalUserPB")]
  245. OpenHistoricalUser = 26,
  246. /// Push a realtime event to the user. Currently, the realtime event
  247. /// is only used when the auth type is: [AuthType::Supabase].
  248. ///
  249. #[event(input = "RealtimePayloadPB")]
  250. PushRealtimeEvent = 27,
  251. #[event(input = "ReminderPB")]
  252. CreateReminder = 28,
  253. #[event(output = "RepeatedReminderPB")]
  254. GetAllReminders = 29,
  255. #[event(input = "ReminderIdentifierPB")]
  256. RemoveReminder = 30,
  257. #[event(input = "ReminderPB")]
  258. UpdateReminder = 31,
  259. #[event(input = "ResetWorkspacePB")]
  260. ResetWorkspace = 32,
  261. /// Change the Date/Time formats globally
  262. #[event(input = "DateTimeSettingsPB")]
  263. SetDateTimeSettings = 33,
  264. /// Retrieve the Date/Time formats
  265. #[event(output = "DateTimeSettingsPB")]
  266. GetDateTimeSettings = 34,
  267. }