user_session.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. use std::sync::{Arc, Weak};
  2. use appflowy_integrate::RocksCollabDB;
  3. use collab_folder::core::FolderData;
  4. use serde::{Deserialize, Serialize};
  5. use tokio::sync::RwLock;
  6. use uuid::Uuid;
  7. use flowy_error::{internal_error, ErrorCode, FlowyResult};
  8. use flowy_server_config::supabase_config::SupabaseConfiguration;
  9. use flowy_sqlite::schema::{user_table, user_workspace_table};
  10. use flowy_sqlite::ConnectionPool;
  11. use flowy_sqlite::{kv::KV, query_dsl::*, DBConnection, ExpressionMethods};
  12. use flowy_user_deps::entities::*;
  13. use lib_infra::box_any::BoxAny;
  14. use lib_infra::util::timestamp;
  15. use crate::entities::{AuthTypePB, RepeatedUserWorkspacePB};
  16. use crate::entities::{UserProfilePB, UserSettingPB};
  17. use crate::event_map::{
  18. DefaultUserStatusCallback, SignUpContext, UserCloudServiceProvider, UserStatusCallback,
  19. };
  20. use crate::migrations::historical_document::HistoricalEmptyDocumentMigration;
  21. use crate::migrations::local_user_to_cloud::migration_user_to_cloud;
  22. use crate::migrations::migration::UserLocalDataMigration;
  23. use crate::migrations::UserMigrationContext;
  24. use crate::services::database::UserDB;
  25. use crate::services::session_serde::Session;
  26. use crate::services::user_sql::{UserTable, UserTableChangeset};
  27. use crate::services::user_workspace_sql::UserWorkspaceTable;
  28. use crate::{errors::FlowyError, notification::*};
  29. const HISTORICAL_USER: &str = "af_historical_users";
  30. const SUPABASE_CONFIG_CACHE_KEY: &str = "af_supabase_config";
  31. pub struct UserSessionConfig {
  32. root_dir: String,
  33. /// Used as the key of `Session` when saving session information to KV.
  34. session_cache_key: String,
  35. }
  36. impl UserSessionConfig {
  37. /// The `root_dir` represents as the root of the user folders. It must be unique for each
  38. /// users.
  39. pub fn new(name: &str, root_dir: &str) -> Self {
  40. let session_cache_key = format!("{}_session_cache", name);
  41. Self {
  42. root_dir: root_dir.to_owned(),
  43. session_cache_key,
  44. }
  45. }
  46. }
  47. pub struct UserSession {
  48. database: UserDB,
  49. session_config: UserSessionConfig,
  50. cloud_services: Arc<dyn UserCloudServiceProvider>,
  51. pub(crate) user_status_callback: RwLock<Arc<dyn UserStatusCallback>>,
  52. }
  53. impl UserSession {
  54. pub fn new(
  55. session_config: UserSessionConfig,
  56. cloud_services: Arc<dyn UserCloudServiceProvider>,
  57. ) -> Self {
  58. let database = UserDB::new(&session_config.root_dir);
  59. let user_status_callback: RwLock<Arc<dyn UserStatusCallback>> =
  60. RwLock::new(Arc::new(DefaultUserStatusCallback));
  61. Self {
  62. database,
  63. session_config,
  64. cloud_services,
  65. user_status_callback,
  66. }
  67. }
  68. pub async fn init<C: UserStatusCallback + 'static>(&self, user_status_callback: C) {
  69. if let Ok(session) = self.get_session() {
  70. match (
  71. self.database.get_collab_db(session.user_id),
  72. self.database.get_pool(session.user_id),
  73. ) {
  74. (Ok(collab_db), Ok(sqlite_pool)) => {
  75. match UserLocalDataMigration::new(session.clone(), collab_db, sqlite_pool)
  76. .run(vec![Box::new(HistoricalEmptyDocumentMigration)])
  77. {
  78. Ok(applied_migrations) => {
  79. if applied_migrations.len() > 0 {
  80. tracing::info!("Did apply migrations: {:?}", applied_migrations);
  81. }
  82. },
  83. Err(e) => tracing::error!("User data migration failed: {:?}", e),
  84. }
  85. },
  86. _ => tracing::error!("Failed to get collab db or sqlite pool"),
  87. }
  88. if let Err(e) = user_status_callback
  89. .did_init(session.user_id, &session.user_workspace)
  90. .await
  91. {
  92. tracing::error!("Failed to call did_sign_in callback: {:?}", e);
  93. }
  94. }
  95. *self.user_status_callback.write().await = Arc::new(user_status_callback);
  96. }
  97. pub fn db_connection(&self, uid: i64) -> Result<DBConnection, FlowyError> {
  98. self.database.get_connection(uid)
  99. }
  100. // The caller will be not 'Sync' before of the return value,
  101. // PooledConnection<ConnectionManager> is not sync. You can use
  102. // db_connection_pool function to require the ConnectionPool that is 'Sync'.
  103. //
  104. // let pool = self.db_connection_pool()?;
  105. // let conn: PooledConnection<ConnectionManager> = pool.get()?;
  106. pub fn db_pool(&self, uid: i64) -> Result<Arc<ConnectionPool>, FlowyError> {
  107. self.database.get_pool(uid)
  108. }
  109. pub fn get_collab_db(&self, uid: i64) -> Result<Weak<RocksCollabDB>, FlowyError> {
  110. self
  111. .database
  112. .get_collab_db(uid)
  113. .map(|collab_db| Arc::downgrade(&collab_db))
  114. }
  115. async fn migrate_local_user_to_cloud(
  116. &self,
  117. old_user: &UserMigrationContext,
  118. new_user: &UserMigrationContext,
  119. ) -> Result<Option<FolderData>, FlowyError> {
  120. let old_collab_db = self.database.get_collab_db(old_user.session.user_id)?;
  121. let new_collab_db = self.database.get_collab_db(new_user.session.user_id)?;
  122. let folder_data = migration_user_to_cloud(old_user, &old_collab_db, new_user, &new_collab_db)?;
  123. Ok(folder_data)
  124. }
  125. #[tracing::instrument(level = "debug", skip(self, params))]
  126. pub async fn sign_in(
  127. &self,
  128. params: BoxAny,
  129. auth_type: AuthType,
  130. ) -> Result<UserProfile, FlowyError> {
  131. let resp: SignInResponse = self
  132. .cloud_services
  133. .get_user_service()?
  134. .sign_in(params)
  135. .await?;
  136. let session: Session = resp.clone().into();
  137. let uid = session.user_id;
  138. self.set_session(Some(session))?;
  139. self.log_user(uid, self.user_dir(uid));
  140. let user_workspace = resp.latest_workspace.clone();
  141. save_user_workspaces(
  142. self.db_pool(uid)?,
  143. resp
  144. .user_workspaces
  145. .iter()
  146. .map(|user_workspace| UserWorkspaceTable::from((uid, user_workspace)))
  147. .collect(),
  148. )?;
  149. let user_profile: UserProfile = self.save_user(uid, (resp, auth_type).into()).await?.into();
  150. if let Err(e) = self
  151. .user_status_callback
  152. .read()
  153. .await
  154. .did_sign_in(user_profile.id, &user_workspace)
  155. .await
  156. {
  157. tracing::error!("Failed to call did_sign_in callback: {:?}", e);
  158. }
  159. send_sign_in_notification()
  160. .payload::<UserProfilePB>(user_profile.clone().into())
  161. .send();
  162. Ok(user_profile)
  163. }
  164. pub async fn update_auth_type(&self, auth_type: &AuthType) {
  165. self
  166. .user_status_callback
  167. .read()
  168. .await
  169. .auth_type_did_changed(auth_type.clone());
  170. self.cloud_services.set_auth_type(auth_type.clone());
  171. }
  172. #[tracing::instrument(level = "debug", skip(self, params))]
  173. pub async fn sign_up(
  174. &self,
  175. auth_type: AuthType,
  176. params: BoxAny,
  177. ) -> Result<UserProfile, FlowyError> {
  178. let old_user = {
  179. if let Ok(old_session) = self.get_session() {
  180. self
  181. .get_user_profile(old_session.user_id, false)
  182. .await
  183. .ok()
  184. .map(|user_profile| UserMigrationContext {
  185. user_profile,
  186. session: old_session,
  187. })
  188. } else {
  189. None
  190. }
  191. };
  192. let auth_service = self.cloud_services.get_user_service()?;
  193. let response: SignUpResponse = auth_service.sign_up(params).await?;
  194. let mut sign_up_context = SignUpContext {
  195. is_new: response.is_new,
  196. local_folder: None,
  197. };
  198. let new_session = Session {
  199. user_id: response.user_id,
  200. user_workspace: response.latest_workspace.clone(),
  201. };
  202. let uid = new_session.user_id;
  203. self.set_session(Some(new_session.clone()))?;
  204. self.log_user(uid, self.user_dir(uid));
  205. save_user_workspaces(
  206. self.db_pool(uid)?,
  207. response
  208. .user_workspaces
  209. .iter()
  210. .map(|user_workspace| UserWorkspaceTable::from((uid, user_workspace)))
  211. .collect(),
  212. )?;
  213. let user_table = self
  214. .save_user(uid, (response, auth_type.clone()).into())
  215. .await?;
  216. let new_user_profile: UserProfile = user_table.into();
  217. // Only migrate the data if the user is login in as a guest and sign up as a new user if the current
  218. // auth type is not [AuthType::Local].
  219. if sign_up_context.is_new {
  220. if let Some(old_user) = old_user {
  221. if old_user.user_profile.auth_type == AuthType::Local && !auth_type.is_local() {
  222. let new_user = UserMigrationContext {
  223. user_profile: new_user_profile.clone(),
  224. session: new_session.clone(),
  225. };
  226. tracing::info!(
  227. "Migrate old user data from {:?} to {:?}",
  228. old_user.user_profile.id,
  229. new_user.user_profile.id
  230. );
  231. match self.migrate_local_user_to_cloud(&old_user, &new_user).await {
  232. Ok(folder_data) => sign_up_context.local_folder = folder_data,
  233. Err(e) => tracing::error!("{:?}", e),
  234. }
  235. // close the old user db
  236. let _ = self.database.close(old_user.session.user_id);
  237. }
  238. }
  239. }
  240. let _ = self
  241. .user_status_callback
  242. .read()
  243. .await
  244. .did_sign_up(
  245. sign_up_context,
  246. &new_user_profile,
  247. &new_session.user_workspace,
  248. )
  249. .await;
  250. Ok(new_user_profile)
  251. }
  252. #[tracing::instrument(level = "info", skip(self))]
  253. pub async fn sign_out(&self) -> Result<(), FlowyError> {
  254. let session = self.get_session()?;
  255. self.database.close(session.user_id)?;
  256. self.set_session(None)?;
  257. let server = self.cloud_services.get_user_service()?;
  258. tokio::spawn(async move {
  259. match server.sign_out(None).await {
  260. Ok(_) => {},
  261. Err(e) => tracing::error!("Sign out failed: {:?}", e),
  262. }
  263. });
  264. Ok(())
  265. }
  266. #[tracing::instrument(level = "debug", skip(self))]
  267. pub async fn update_user_profile(
  268. &self,
  269. params: UpdateUserProfileParams,
  270. ) -> Result<(), FlowyError> {
  271. let auth_type = params.auth_type.clone();
  272. let session = self.get_session()?;
  273. let changeset = UserTableChangeset::new(params.clone());
  274. diesel_update_table!(
  275. user_table,
  276. changeset,
  277. &*self.db_connection(session.user_id)?
  278. );
  279. let session = self.get_session()?;
  280. let user_profile = self.get_user_profile(session.user_id, false).await?;
  281. let profile_pb: UserProfilePB = user_profile.into();
  282. send_notification(
  283. &session.user_id.to_string(),
  284. UserNotification::DidUpdateUserProfile,
  285. )
  286. .payload(profile_pb)
  287. .send();
  288. self
  289. .update_user(&auth_type, session.user_id, None, params)
  290. .await?;
  291. Ok(())
  292. }
  293. pub async fn init_user(&self) -> Result<(), FlowyError> {
  294. Ok(())
  295. }
  296. pub async fn check_user(&self) -> Result<(), FlowyError> {
  297. let user_id = self.get_session()?.user_id;
  298. let credential = UserCredentials::from_uid(user_id);
  299. let auth_service = self.cloud_services.get_user_service()?;
  300. auth_service.check_user(credential).await?;
  301. Ok(())
  302. }
  303. pub async fn check_user_with_uuid(&self, uuid: &Uuid) -> Result<(), FlowyError> {
  304. let credential = UserCredentials::from_uuid(uuid.to_string());
  305. let auth_service = self.cloud_services.get_user_service()?;
  306. auth_service.check_user(credential).await?;
  307. Ok(())
  308. }
  309. pub async fn open_workspace(&self, workspace_id: &str) -> FlowyResult<()> {
  310. let uid = self.user_id()?;
  311. if let Some(user_workspace) = self.get_user_workspace(uid, workspace_id) {
  312. if let Err(err) = self
  313. .user_status_callback
  314. .read()
  315. .await
  316. .open_workspace(uid, &user_workspace)
  317. .await
  318. {
  319. tracing::error!("Open workspace failed: {:?}", err);
  320. }
  321. }
  322. Ok(())
  323. }
  324. pub async fn add_user_to_workspace(
  325. &self,
  326. user_email: String,
  327. to_workspace_id: String,
  328. ) -> FlowyResult<()> {
  329. self
  330. .cloud_services
  331. .get_user_service()?
  332. .add_workspace_member(user_email, to_workspace_id)
  333. .await?;
  334. Ok(())
  335. }
  336. pub async fn remove_user_to_workspace(
  337. &self,
  338. user_email: String,
  339. from_workspace_id: String,
  340. ) -> FlowyResult<()> {
  341. self
  342. .cloud_services
  343. .get_user_service()?
  344. .remove_workspace_member(user_email, from_workspace_id)
  345. .await?;
  346. Ok(())
  347. }
  348. /// Get the user profile from the database
  349. /// If the refresh is true, it will try to get the user profile from the server
  350. pub async fn get_user_profile(&self, uid: i64, refresh: bool) -> Result<UserProfile, FlowyError> {
  351. let user_id = uid.to_string();
  352. let user = user_table::dsl::user_table
  353. .filter(user_table::id.eq(&user_id))
  354. .first::<UserTable>(&*(self.db_connection(uid)?))?;
  355. if refresh {
  356. let weak_auth_service = Arc::downgrade(&self.cloud_services.get_user_service()?);
  357. let weak_pool = Arc::downgrade(&self.database.get_pool(uid)?);
  358. tokio::spawn(async move {
  359. if let (Some(auth_service), Some(pool)) = (weak_auth_service.upgrade(), weak_pool.upgrade())
  360. {
  361. if let Ok(Some(user_profile)) = auth_service
  362. .get_user_profile(UserCredentials::from_uid(uid))
  363. .await
  364. {
  365. let changeset = UserTableChangeset::from_user_profile(user_profile.clone());
  366. if let Ok(conn) = pool.get() {
  367. let filter =
  368. user_table::dsl::user_table.filter(user_table::dsl::id.eq(changeset.id.clone()));
  369. let _ = diesel::update(filter).set(changeset).execute(&*conn);
  370. // Send notification to the client
  371. let user_profile_pb: UserProfilePB = user_profile.into();
  372. send_notification(&uid.to_string(), UserNotification::DidUpdateUserProfile)
  373. .payload(user_profile_pb)
  374. .send();
  375. }
  376. }
  377. }
  378. });
  379. }
  380. Ok(user.into())
  381. }
  382. pub fn user_dir(&self, uid: i64) -> String {
  383. format!("{}/{}", self.session_config.root_dir, uid)
  384. }
  385. pub fn user_setting(&self) -> Result<UserSettingPB, FlowyError> {
  386. let session = self.get_session()?;
  387. let user_setting = UserSettingPB {
  388. user_folder: self.user_dir(session.user_id),
  389. };
  390. Ok(user_setting)
  391. }
  392. pub fn user_id(&self) -> Result<i64, FlowyError> {
  393. Ok(self.get_session()?.user_id)
  394. }
  395. pub fn token(&self) -> Result<Option<String>, FlowyError> {
  396. Ok(None)
  397. }
  398. pub fn save_supabase_config(&self, config: SupabaseConfiguration) {
  399. self.cloud_services.update_supabase_config(&config);
  400. let _ = KV::set_object(SUPABASE_CONFIG_CACHE_KEY, config);
  401. }
  402. async fn update_user(
  403. &self,
  404. _auth_type: &AuthType,
  405. uid: i64,
  406. token: Option<String>,
  407. params: UpdateUserProfileParams,
  408. ) -> Result<(), FlowyError> {
  409. let server = self.cloud_services.get_user_service()?;
  410. let token = token.to_owned();
  411. tokio::spawn(async move {
  412. let credentials = UserCredentials::new(token, Some(uid), None);
  413. server.update_user(credentials, params).await
  414. })
  415. .await
  416. .map_err(internal_error)??;
  417. Ok(())
  418. }
  419. async fn save_user(&self, uid: i64, user: UserTable) -> Result<UserTable, FlowyError> {
  420. let conn = self.db_connection(uid)?;
  421. conn.immediate_transaction(|| {
  422. // delete old user if exists
  423. diesel::delete(user_table::dsl::user_table.filter(user_table::dsl::id.eq(&user.id)))
  424. .execute(&*conn)?;
  425. let _ = diesel::insert_into(user_table::table)
  426. .values(user.clone())
  427. .execute(&*conn)?;
  428. Ok::<(), FlowyError>(())
  429. })?;
  430. Ok(user)
  431. }
  432. pub fn get_user_workspace(&self, uid: i64, workspace_id: &str) -> Option<UserWorkspace> {
  433. let conn = self.db_connection(uid).ok()?;
  434. let row = user_workspace_table::dsl::user_workspace_table
  435. .filter(user_workspace_table::id.eq(workspace_id))
  436. .first::<UserWorkspaceTable>(&*conn)
  437. .ok()?;
  438. Some(UserWorkspace::from(row))
  439. }
  440. pub fn get_all_user_workspaces(&self, uid: i64) -> FlowyResult<Vec<UserWorkspace>> {
  441. let conn = self.db_connection(uid)?;
  442. let rows = user_workspace_table::dsl::user_workspace_table
  443. .filter(user_workspace_table::uid.eq(uid))
  444. .load::<UserWorkspaceTable>(&*conn)?;
  445. if let Ok(service) = self.cloud_services.get_user_service() {
  446. if let Ok(pool) = self.db_pool(uid) {
  447. tokio::spawn(async move {
  448. if let Ok(new_user_workspaces) = service.get_user_workspaces(uid).await {
  449. let _ = save_user_workspaces(
  450. pool,
  451. new_user_workspaces
  452. .iter()
  453. .map(|user_workspace| UserWorkspaceTable::from((uid, user_workspace)))
  454. .collect(),
  455. );
  456. let repeated_workspace_pbs = RepeatedUserWorkspacePB::from(new_user_workspaces);
  457. send_notification(&uid.to_string(), UserNotification::DidUpdateUserWorkspaces)
  458. .payload(repeated_workspace_pbs)
  459. .send();
  460. }
  461. });
  462. }
  463. }
  464. Ok(rows.into_iter().map(UserWorkspace::from).collect())
  465. }
  466. pub async fn save_user_workspaces(
  467. &self,
  468. uid: i64,
  469. user_workspaces: Vec<UserWorkspaceTable>,
  470. ) -> FlowyResult<()> {
  471. let conn = self.db_connection(uid)?;
  472. conn.immediate_transaction(|| {
  473. for user_workspace in user_workspaces {
  474. if let Err(err) = diesel::update(
  475. user_workspace_table::dsl::user_workspace_table
  476. .filter(user_workspace_table::id.eq(user_workspace.id.clone())),
  477. )
  478. .set((
  479. user_workspace_table::name.eq(&user_workspace.name),
  480. user_workspace_table::created_at.eq(&user_workspace.created_at),
  481. user_workspace_table::database_storage_id.eq(&user_workspace.database_storage_id),
  482. ))
  483. .execute(&*conn)
  484. .and_then(|rows| {
  485. if rows == 0 {
  486. let _ = diesel::insert_into(user_workspace_table::table)
  487. .values(user_workspace)
  488. .execute(&*conn)?;
  489. }
  490. Ok(())
  491. }) {
  492. tracing::error!("Error saving user workspace: {:?}", err);
  493. }
  494. }
  495. Ok::<(), FlowyError>(())
  496. })
  497. }
  498. fn set_session(&self, session: Option<Session>) -> Result<(), FlowyError> {
  499. tracing::debug!("Set user session: {:?}", session);
  500. match &session {
  501. None => KV::remove(&self.session_config.session_cache_key),
  502. Some(session) => {
  503. KV::set_object(&self.session_config.session_cache_key, session.clone())
  504. .map_err(internal_error)?;
  505. },
  506. }
  507. Ok(())
  508. }
  509. fn log_user(&self, uid: i64, storage_path: String) {
  510. let mut logger_users = KV::get_object::<HistoricalUsers>(HISTORICAL_USER).unwrap_or_default();
  511. logger_users.add_user(HistoricalUser {
  512. user_id: uid,
  513. sign_in_timestamp: timestamp(),
  514. storage_path,
  515. });
  516. let _ = KV::set_object(HISTORICAL_USER, logger_users);
  517. }
  518. pub fn get_historical_users(&self) -> Vec<HistoricalUser> {
  519. KV::get_object::<HistoricalUsers>(HISTORICAL_USER)
  520. .unwrap_or_default()
  521. .users
  522. }
  523. /// Returns the current user session.
  524. pub fn get_session(&self) -> Result<Session, FlowyError> {
  525. match KV::get_object::<Session>(&self.session_config.session_cache_key) {
  526. None => Err(FlowyError::new(
  527. ErrorCode::RecordNotFound,
  528. "User is not logged in".to_string(),
  529. )),
  530. Some(session) => Ok(session),
  531. }
  532. }
  533. }
  534. pub fn get_supabase_config() -> Option<SupabaseConfiguration> {
  535. KV::get_str(SUPABASE_CONFIG_CACHE_KEY)
  536. .and_then(|s| serde_json::from_str(&s).ok())
  537. .unwrap_or_else(|| SupabaseConfiguration::from_env().ok())
  538. }
  539. pub fn save_user_workspaces(
  540. pool: Arc<ConnectionPool>,
  541. user_workspaces: Vec<UserWorkspaceTable>,
  542. ) -> FlowyResult<()> {
  543. let conn = pool.get()?;
  544. conn.immediate_transaction(|| {
  545. for user_workspace in user_workspaces {
  546. if let Err(err) = diesel::update(
  547. user_workspace_table::dsl::user_workspace_table
  548. .filter(user_workspace_table::id.eq(user_workspace.id.clone())),
  549. )
  550. .set((
  551. user_workspace_table::name.eq(&user_workspace.name),
  552. user_workspace_table::created_at.eq(&user_workspace.created_at),
  553. user_workspace_table::database_storage_id.eq(&user_workspace.database_storage_id),
  554. ))
  555. .execute(&*conn)
  556. .and_then(|rows| {
  557. if rows == 0 {
  558. let _ = diesel::insert_into(user_workspace_table::table)
  559. .values(user_workspace)
  560. .execute(&*conn)?;
  561. }
  562. Ok(())
  563. }) {
  564. tracing::error!("Error saving user workspace: {:?}", err);
  565. }
  566. }
  567. Ok::<(), FlowyError>(())
  568. })
  569. }
  570. impl From<AuthTypePB> for AuthType {
  571. fn from(pb: AuthTypePB) -> Self {
  572. match pb {
  573. AuthTypePB::Supabase => AuthType::Supabase,
  574. AuthTypePB::Local => AuthType::Local,
  575. AuthTypePB::SelfHosted => AuthType::SelfHosted,
  576. }
  577. }
  578. }
  579. impl From<AuthType> for AuthTypePB {
  580. fn from(auth_type: AuthType) -> Self {
  581. match auth_type {
  582. AuthType::Supabase => AuthTypePB::Supabase,
  583. AuthType::Local => AuthTypePB::Local,
  584. AuthType::SelfHosted => AuthTypePB::SelfHosted,
  585. }
  586. }
  587. }
  588. #[derive(Debug, Clone, Default, Serialize, Deserialize)]
  589. pub struct HistoricalUsers {
  590. pub(crate) users: Vec<HistoricalUser>,
  591. }
  592. impl HistoricalUsers {
  593. pub fn add_user(&mut self, new_user: HistoricalUser) {
  594. self.users.retain(|user| user.user_id != new_user.user_id);
  595. self.users.push(new_user);
  596. }
  597. }
  598. #[derive(Debug, Clone, Default, Serialize, Deserialize)]
  599. pub struct HistoricalUser {
  600. pub user_id: i64,
  601. pub sign_in_timestamp: i64,
  602. pub storage_path: String,
  603. }