Bring projects, wikis, and teams together with AI. AppFlowy is the AI collaborative workspace where you achieve more without losing control of your data. The leading open source Notion alternative.
Dart blogconfluence-alternativecontent-managementcontent-servicesdocumentationflutternote-takingnotion-alternativeproject-managementtask-managementteam-collaborationwiki
chore: auth type
Nathan6dac45172e2e
diff --git a/frontend/appflowy_flutter/lib/mobile/presentation/home/mobile_home_page_header.dart b/frontend/appflowy_flutter/lib/mobile/presentation/home/mobile_home_page_header.dartindex 97cc243c9e..4a1df63740 100644--- a/frontend/appflowy_flutter/lib/mobile/presentation/home/mobile_home_page_header.dart+++ b/frontend/appflowy_flutter/lib/mobile/presentation/home/mobile_home_page_header.dart@@ -194,6 +194,7 @@ class _MobileWorkspace extends StatelessWidget {context.read<UserWorkspaceBloc>().add(UserWorkspaceEvent.openWorkspace(workspace.workspaceId,+ workspace.authType,),);},diff --git a/frontend/appflowy_flutter/lib/user/application/user_service.dart b/frontend/appflowy_flutter/lib/user/application/user_service.dartindex 18f89ebc14..5e163b4e62 100644--- a/frontend/appflowy_flutter/lib/user/application/user_service.dart+++ b/frontend/appflowy_flutter/lib/user/application/user_service.dart@@ -121,8 +121,13 @@ class UserBackendService implements IUserBackendService {});}- Future<FlowyResult<void, FlowyError>> openWorkspace(String workspaceId) {- final payload = UserWorkspaceIdPB.create()..workspaceId = workspaceId;+ Future<FlowyResult<void, FlowyError>> openWorkspace(+ String workspaceId,+ AuthTypePB authType,+ ) {+ final payload = OpenUserWorkspacePB()+ ..workspaceId = workspaceId+ ..authType = authType;return UserEventOpenWorkspace(payload).send();}diff --git a/frontend/appflowy_flutter/lib/workspace/application/user/user_workspace_bloc.dart b/frontend/appflowy_flutter/lib/workspace/application/user/user_workspace_bloc.dartindex e6a8c4d921..7e341f4f1f 100644--- a/frontend/appflowy_flutter/lib/workspace/application/user/user_workspace_bloc.dart+++ b/frontend/appflowy_flutter/lib/workspace/application/user/user_workspace_bloc.dart@@ -52,7 +52,10 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {);if (currentWorkspace != null && result.$3 == true) {Log.info('init open workspace: ${currentWorkspace.workspaceId}');- await _userService.openWorkspace(currentWorkspace.workspaceId);+ await _userService.openWorkspace(+ currentWorkspace.workspaceId,+ currentWorkspace.authType,+ );}emit(@@ -86,7 +89,12 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {Log.info('fetch workspaces: try to open workspace: ${currentWorkspace.workspaceId}',);- add(OpenWorkspace(currentWorkspace.workspaceId));+ add(+ OpenWorkspace(+ currentWorkspace.workspaceId,+ currentWorkspace.authType,+ ),+ );}},createWorkspace: (name) async {@@ -118,7 +126,12 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {result..onSuccess((s) {Log.info('create workspace success: $s');- add(OpenWorkspace(s.workspaceId));+ add(+ OpenWorkspace(+ s.workspaceId,+ s.authType,+ ),+ );})..onFailure((f) {Log.error('create workspace error: $f');@@ -171,7 +184,12 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {Log.info('delete workspace success: $workspaceId');// if the current workspace is deleted, open the first workspaceif (state.currentWorkspace?.workspaceId == workspaceId) {- add(OpenWorkspace(workspaces.first.workspaceId));+ add(+ OpenWorkspace(+ workspaces.first.workspaceId,+ workspaces.first.authType,+ ),+ );}})..onFailure((f) {@@ -179,7 +197,12 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {// if the workspace is deleted but return an error, we need to// open the first workspaceif (!containsDeletedWorkspace) {- add(OpenWorkspace(workspaces.first.workspaceId));+ add(+ OpenWorkspace(+ workspaces.first.workspaceId,+ workspaces.first.authType,+ ),+ );}});emit(@@ -193,7 +216,7 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {),);},- openWorkspace: (workspaceId) async {+ openWorkspace: (workspaceId, authType) async {emit(state.copyWith(actionResult: const UserWorkspaceActionResult(@@ -203,7 +226,10 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {),),);- final result = await _userService.openWorkspace(workspaceId);+ final result = await _userService.openWorkspace(+ workspaceId,+ authType,+ );final currentWorkspace = result.fold((s) => state.workspaces.firstWhereOrNull((e) => e.workspaceId == workspaceId,@@ -337,7 +363,12 @@ class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {Log.info('leave workspace success: $workspaceId');// if leaving the current workspace, open the first workspaceif (state.currentWorkspace?.workspaceId == workspaceId) {- add(OpenWorkspace(workspaces.first.workspaceId));+ add(+ OpenWorkspace(+ workspaces.first.workspaceId,+ workspaces.first.authType,+ ),+ );}})..onFailure((f) {@@ -445,8 +476,10 @@ class UserWorkspaceEvent with _$UserWorkspaceEvent {CreateWorkspace;const factory UserWorkspaceEvent.deleteWorkspace(String workspaceId) =DeleteWorkspace;- const factory UserWorkspaceEvent.openWorkspace(String workspaceId) =- OpenWorkspace;+ const factory UserWorkspaceEvent.openWorkspace(+ String workspaceId,+ AuthTypePB authType,+ ) = OpenWorkspace;const factory UserWorkspaceEvent.renameWorkspace(String workspaceId,String name,diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dart b/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dartindex ff393a8305..daf332cc15 100644--- a/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dart+++ b/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dart@@ -306,9 +306,12 @@ class _WorkspaceInfo extends StatelessWidget {// Persist and close other tabs when switching workspace, restore tabs for new workspacegetIt<TabsBloc>().add(TabsEvent.switchWorkspace(workspace.workspaceId));- context- .read<UserWorkspaceBloc>()- .add(UserWorkspaceEvent.openWorkspace(workspace.workspaceId));+ context.read<UserWorkspaceBloc>().add(+ UserWorkspaceEvent.openWorkspace(+ workspace.workspaceId,+ workspace.authType,+ ),+ );PopoverContainer.of(context).closeAll();}diff --git a/frontend/appflowy_flutter/macos/Podfile.lock b/frontend/appflowy_flutter/macos/Podfile.lockindex 30ee626f09..b4a1a3d20d 100644--- a/frontend/appflowy_flutter/macos/Podfile.lock+++ b/frontend/appflowy_flutter/macos/Podfile.lock@@ -144,34 +144,34 @@ EXTERNAL SOURCES::path: Flutter/ephemeral/.symlinks/plugins/window_manager/macosSPEC CHECKSUMS:- app_links: 9028728e32c83a0831d9db8cf91c526d16cc5468- appflowy_backend: 464aeb3e5c6966a41641a2111e5ead72ce2695f7- auto_updater_macos: 3a42f1a06be6981f1a18be37e6e7bf86aa732118- bitsdojo_window_macos: 7959fb0ca65a3ccda30095c181ecb856fae48ea9- connectivity_plus: e74b9f74717d2d99d45751750e266e55912baeb5- desktop_drop: e0b672a7d84c0a6cbc378595e82cdb15f2970a43- device_info_plus: a56e6e74dbbd2bb92f2da12c64ddd4f67a749041- file_selector_macos: 6280b52b459ae6c590af5d78fc35c7267a3c4b31- flowy_infra_ui: 8760ff42a789de40bf5007a5f176b454722a341e+ app_links: 10e0a0ab602ffaf34d142cd4862f29d34b303b2a+ appflowy_backend: 865496343de667fc8c600e04b9fd05234e130cf9+ auto_updater_macos: 3e3462c418fe4e731917eacd8d28eef7af84086d+ bitsdojo_window_macos: 44e3b8fe3dd463820e0321f6256c5b1c16bb6a00+ connectivity_plus: 18d3c32514c886e046de60e9c13895109866c747+ desktop_drop: 69eeff437544aa619c8db7f4481b3a65f7696898+ device_info_plus: ce1b7762849d3ec103d0e0517299f2db7ad60720+ file_selector_macos: cc3858c981fe6889f364731200d6232dac1d812d+ flowy_infra_ui: 03301a39ad118771adbf051a664265c61c507f38FlutterMacOS: 8f6f14fa908a6fb3fba0cd85dbd81ec4b251fb24HotKey: 400beb7caa29054ea8d864c96f5ba7e5b4852277- hotkey_manager: b443f35f4d772162937aa73fd8995e579f8ac4e2- irondash_engine_context: 893c7d96d20ce361d7e996f39d360c4c2f9869ba- local_notifier: ebf072651e35ae5e47280ad52e2707375cb2ae4e- package_info_plus: f0052d280d17aa382b932f399edf32507174e870- path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564+ hotkey_manager: c32bf0bfe8f934b7bc17ab4ad5c4c142960b023c+ irondash_engine_context: da62996ee25616d2f01bbeb85dc115d813359478+ local_notifier: e9506bc66fc70311e8bc7291fb70f743c081e4ff+ package_info_plus: 12f1c5c2cfe8727ca46cbd0b26677728972d9a5b+ path_provider_foundation: 2b6b4c569c0fb62ec74538f866245ac84301af46ReachabilitySwift: 32793e867593cfc1177f5d16491e3a197d2fccda- screen_retriever_macos: 452e51764a9e1cdb74b3c541238795849f21557f+ screen_retriever_macos: 776e0fa5d42c6163d2bf772d22478df4b302b161Sentry: 1fe34e9c2cbba1e347623610d26db121dcb569f1- sentry_flutter: e24b397f9a61fa5bbefd8279c3b2242ca86faa90- share_plus: 510bf0af1a42cd602274b4629920c9649c52f4cc- shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7+ sentry_flutter: a39c2a2d67d5e5b9cb0b94a4985c76dd5b3fc737+ share_plus: 1fa619de8392a4398bfaf176d441853922614e89+ shared_preferences_foundation: fcdcbc04712aee1108ac7fda236f363274528f78Sparkle: 5f8960a7a119aa7d45dacc0d5837017170bc5675- sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0- super_native_extensions: c2795d6d9aedf4a79fae25cb6160b71b50549189- url_launcher_macos: 0fba8ddabfc33ce0a9afe7c5fef5aab3d8d2d673- webview_flutter_wkwebview: 44d4dee7d7056d5ad185d25b38404436d56c547c- window_manager: 1d01fa7ac65a6e6f83b965471b1a7fdd3f06166c+ sqflite_darwin: 5a7236e3b501866c1c9befc6771dfd73ffb8702d+ super_native_extensions: 85efee3a7495b46b04befcfc86ed12069264ebf3+ url_launcher_macos: c82c93949963e55b228a30115bd219499a6fe404+ webview_flutter_wkwebview: 0982481e3d9c78fd5c6f62a002fcd24fc791f1e4+ window_manager: 3a1844359a6295ab1e47659b1a777e36773cd6e8PODFILE CHECKSUM: 0532f3f001ca3110b8be345d6491fff690e95823diff --git a/frontend/rust-lib/event-integration-test/src/folder_event.rs b/frontend/rust-lib/event-integration-test/src/folder_event.rsindex 2e1b1cc417..345c1e58e0 100644--- a/frontend/rust-lib/event-integration-test/src/folder_event.rs+++ b/frontend/rust-lib/event-integration-test/src/folder_event.rs@@ -11,8 +11,8 @@ use flowy_folder_pub::entities::PublishPayload;use flowy_search::services::manager::{SearchHandler, SearchType};use flowy_user::entities::{AcceptWorkspaceInvitationPB, QueryWorkspacePB, RemoveWorkspaceMemberPB,- RepeatedWorkspaceInvitationPB, RepeatedWorkspaceMemberPB, WorkspaceMemberInvitationPB,- WorkspaceMemberPB,+ RepeatedWorkspaceInvitationPB, RepeatedWorkspaceMemberPB, UserWorkspaceIdPB, UserWorkspacePB,+ WorkspaceMemberInvitationPB, WorkspaceMemberPB,};use flowy_user::errors::FlowyError;use flowy_user::event_map::UserEvent;@@ -112,6 +112,18 @@ impl EventIntegrationTest {.parse::<WorkspacePB>()}+ pub async fn get_user_workspace(&self, workspace_id: &str) -> UserWorkspacePB {+ let payload = UserWorkspaceIdPB {+ workspace_id: workspace_id.to_string(),+ };+ EventBuilder::new(self.clone())+ .event(UserEvent::GetUserWorkspace)+ .payload(payload)+ .async_send()+ .await+ .parse::<UserWorkspacePB>()+ }+pub fn get_folder_search_handler(&self) -> &Arc<dyn SearchHandler> {self.appflowy_corediff --git a/frontend/rust-lib/event-integration-test/src/user_event.rs b/frontend/rust-lib/event-integration-test/src/user_event.rsindex 2ec74bafa6..5c9be65660 100644--- a/frontend/rust-lib/event-integration-test/src/user_event.rs+++ b/frontend/rust-lib/event-integration-test/src/user_event.rs@@ -17,10 +17,10 @@ use flowy_server::af_cloud::define::{USER_DEVICE_ID, USER_EMAIL, USER_SIGN_IN_URuse flowy_server_pub::af_cloud_config::AFCloudConfiguration;use flowy_server_pub::AuthenticatorType;use flowy_user::entities::{- AuthenticatorPB, ChangeWorkspaceIconPB, CloudSettingPB, CreateWorkspacePB, ImportAppFlowyDataPB,- OauthSignInPB, RenameWorkspacePB, RepeatedUserWorkspacePB, SignInUrlPB, SignInUrlPayloadPB,- SignUpPayloadPB, UpdateCloudConfigPB, UpdateUserProfilePayloadPB, UserProfilePB,- UserWorkspaceIdPB, UserWorkspacePB,+ AuthTypePB, AuthenticatorPB, ChangeWorkspaceIconPB, CloudSettingPB, CreateWorkspacePB,+ ImportAppFlowyDataPB, OauthSignInPB, OpenUserWorkspacePB, RenameWorkspacePB,+ RepeatedUserWorkspacePB, SignInUrlPB, SignInUrlPayloadPB, SignUpPayloadPB, UpdateCloudConfigPB,+ UpdateUserProfilePayloadPB, UserProfilePB, UserWorkspaceIdPB, UserWorkspacePB,};use flowy_user::errors::{FlowyError, FlowyResult};use flowy_user::event_map::UserEvent;@@ -280,9 +280,10 @@ impl EventIntegrationTest {.await;}- pub async fn open_workspace(&self, workspace_id: &str) {- let payload = UserWorkspaceIdPB {+ pub async fn open_workspace(&self, workspace_id: &str, auth_type: AuthTypePB) {+ let payload = OpenUserWorkspacePB {workspace_id: workspace_id.to_string(),+ auth_type,};EventBuilder::new(self.clone()).event(UserEvent::OpenWorkspace)diff --git a/frontend/rust-lib/event-integration-test/tests/user/af_cloud_test/workspace_test.rs b/frontend/rust-lib/event-integration-test/tests/user/af_cloud_test/workspace_test.rsindex 366e43c157..ea04d922fc 100644--- a/frontend/rust-lib/event-integration-test/tests/user/af_cloud_test/workspace_test.rs+++ b/frontend/rust-lib/event-integration-test/tests/user/af_cloud_test/workspace_test.rs@@ -89,7 +89,9 @@ async fn af_cloud_create_workspace_test() {}{// after opening new workspace- test.open_workspace(&created_workspace.workspace_id).await;+ test+ .open_workspace(&created_workspace.workspace_id, created_workspace.auth_type)+ .await;let folder_ws = test.folder_read_current_workspace().await;assert_eq!(folder_ws.id, created_workspace.workspace_id);let views = test.folder_read_current_workspace_views().await;@@ -110,6 +112,7 @@ async fn af_cloud_open_workspace_test() {test.create_document("A").await;test.create_document("B").await;let first_workspace = test.get_current_workspace().await;+ let first_workspace = test.get_user_workspace(&first_workspace.id).await;let views = test.get_all_workspace_views().await;assert_eq!(views.len(), 4);assert_eq!(views[0].name, default_document_name);@@ -120,8 +123,11 @@ async fn af_cloud_open_workspace_test() {let user_workspace = test.create_workspace("second workspace", AuthType::AppFlowyCloud).await;- test.open_workspace(&user_workspace.workspace_id).await;+ test+ .open_workspace(&user_workspace.workspace_id, user_workspace.auth_type)+ .await;let second_workspace = test.get_current_workspace().await;+ let second_workspace = test.get_user_workspace(&second_workspace.id).await;test.create_document("C").await;test.create_document("D").await;@@ -135,13 +141,23 @@ async fn af_cloud_open_workspace_test() {// simulate open workspace and check if the views are correctfor i in 0..10 {if i % 2 == 0 {- test.open_workspace(&first_workspace.id).await;+ test+ .open_workspace(+ &first_workspace.workspace_id,+ first_workspace.auth_type.clone(),+ )+ .await;sleep(Duration::from_millis(300)).await;test.create_document(&uuid::Uuid::new_v4().to_string()).await;} else {- test.open_workspace(&second_workspace.id).await;+ test+ .open_workspace(+ &second_workspace.workspace_id,+ second_workspace.auth_type.clone(),+ )+ .await;sleep(Duration::from_millis(200)).await;test.create_document(&uuid::Uuid::new_v4().to_string())@@ -149,14 +165,24 @@ async fn af_cloud_open_workspace_test() {}}- test.open_workspace(&first_workspace.id).await;+ test+ .open_workspace(+ &first_workspace.workspace_id,+ first_workspace.auth_type.clone(),+ )+ .await;let views_1 = test.get_all_workspace_views().await;assert_eq!(views_1[0].name, default_document_name);assert_eq!(views_1[1].name, "Shared");assert_eq!(views_1[2].name, "A");assert_eq!(views_1[3].name, "B");- test.open_workspace(&second_workspace.id).await;+ test+ .open_workspace(+ &second_workspace.workspace_id,+ second_workspace.auth_type.clone(),+ )+ .await;let views_2 = test.get_all_workspace_views().await;assert_eq!(views_2[0].name, default_document_name);assert_eq!(views_2[1].name, "Shared");@@ -212,7 +238,9 @@ async fn af_cloud_different_open_same_workspace_test() {for i in 0..30 {let index = i % 2;let iter_workspace_id = &all_workspaces[index].workspace_id;- client.open_workspace(iter_workspace_id).await;+ client+ .open_workspace(iter_workspace_id, all_workspaces[index].auth_type.clone())+ .await;if iter_workspace_id == &cloned_shared_workspace_id {let views = client.get_all_workspace_views().await;assert_eq!(views.len(), 2);diff --git a/frontend/rust-lib/flowy-core/src/user_state_callback.rs b/frontend/rust-lib/flowy-core/src/user_state_callback.rsindex ff1c6b6699..6002746603 100644--- a/frontend/rust-lib/flowy-core/src/user_state_callback.rs+++ b/frontend/rust-lib/flowy-core/src/user_state_callback.rs@@ -49,11 +49,10 @@ impl UserStatusCallback for UserStatusCallbackImpl {async fn did_init(&self,user_id: i64,- auth_type: &AuthType,cloud_config: &Option<UserCloudConfig>,user_workspace: &UserWorkspace,_device_id: &str,- authenticator: &AuthType,+ auth_type: &AuthType,) -> FlowyResult<()> {let workspace_id = user_workspace.workspace_id()?;self.server_provider.set_auth_type(*auth_type);@@ -81,7 +80,7 @@ impl UserStatusCallback for UserStatusCallbackImpl {.await?;self.database_manager- .initialize(user_id, authenticator == &AuthType::Local)+ .initialize(user_id, auth_type == &AuthType::Local).await?;self.document_manager.initialize(user_id).await?;@@ -95,7 +94,7 @@ impl UserStatusCallback for UserStatusCallbackImpl {user_id: i64,user_workspace: &UserWorkspace,device_id: &str,- authenticator: &AuthType,+ auth_type: &AuthType,) -> FlowyResult<()> {event!(tracing::Level::TRACE,@@ -103,6 +102,7 @@ impl UserStatusCallback for UserStatusCallbackImpl {user_workspace,device_id);+ self.server_provider.set_auth_type(*auth_type);self.folder_manager@@ -110,7 +110,7 @@ impl UserStatusCallback for UserStatusCallbackImpl {.await?;self.database_manager- .initialize(user_id, authenticator.is_local())+ .initialize(user_id, auth_type.is_local()).await?;self.document_manager.initialize(user_id).await?;@@ -207,15 +207,16 @@ impl UserStatusCallback for UserStatusCallbackImpl {&self,user_id: i64,user_workspace: &UserWorkspace,- authenticator: &AuthType,+ auth_type: &AuthType,) -> FlowyResult<()> {+ self.server_provider.set_auth_type(*auth_type);self.folder_manager.initialize_with_workspace_id(user_id).await?;self.database_manager- .initialize(user_id, authenticator.is_local())+ .initialize(user_id, auth_type.is_local()).await?;self.document_manager.initialize(user_id).await?;self.ai_manager.initialize(&user_workspace.id).await?;diff --git a/frontend/rust-lib/flowy-user/src/entities/user_profile.rs b/frontend/rust-lib/flowy-user/src/entities/user_profile.rsindex 54cb41db1e..f7a78a8f7d 100644--- a/frontend/rust-lib/flowy-user/src/entities/user_profile.rs+++ b/frontend/rust-lib/flowy-user/src/entities/user_profile.rs@@ -1,15 +1,14 @@+use super::AFRolePB;+use crate::entities::parser::{UserEmail, UserIcon, UserName};+use crate::entities::{AuthTypePB, AuthenticatorPB};+use crate::errors::ErrorCode;+use crate::services::sqlite_sql::workspace_sql::UserWorkspaceTable;use flowy_derive::{ProtoBuf, ProtoBuf_Enum};use flowy_user_pub::entities::*;use lib_infra::validator_fn::required_not_empty_str;use std::convert::TryInto;use validator::Validate;-use crate::entities::parser::{UserEmail, UserIcon, UserName};-use crate::entities::AuthenticatorPB;-use crate::errors::ErrorCode;--use super::AFRolePB;-#[derive(Default, ProtoBuf)]pub struct UserTokenPB {#[pb(index = 1)]@@ -153,10 +152,14 @@ pub struct RepeatedUserWorkspacePB {pub items: Vec<UserWorkspacePB>,}-impl From<Vec<UserWorkspace>> for RepeatedUserWorkspacePB {- fn from(workspaces: Vec<UserWorkspace>) -> Self {+impl From<(AuthType, Vec<UserWorkspace>)> for RepeatedUserWorkspacePB {+ fn from(value: (AuthType, Vec<UserWorkspace>)) -> Self {+ let (auth_type, workspaces) = value;Self {- items: workspaces.into_iter().map(UserWorkspacePB::from).collect(),+ items: workspaces+ .into_iter()+ .map(|w| UserWorkspacePB::from((auth_type, w)))+ .collect(),}}}@@ -181,17 +184,35 @@ pub struct UserWorkspacePB {#[pb(index = 6, one_of)]pub role: Option<AFRolePB>,++ #[pb(index = 7)]+ pub auth_type: AuthTypePB,+}++impl From<(AuthType, UserWorkspace)> for UserWorkspacePB {+ fn from(value: (AuthType, UserWorkspace)) -> Self {+ Self {+ workspace_id: value.1.id,+ name: value.1.name,+ created_at_timestamp: value.1.created_at.timestamp(),+ icon: value.1.icon,+ member_count: value.1.member_count,+ role: value.1.role.map(AFRolePB::from),+ auth_type: AuthTypePB::from(value.0),+ }+ }}-impl From<UserWorkspace> for UserWorkspacePB {- fn from(value: UserWorkspace) -> Self {+impl From<UserWorkspaceTable> for UserWorkspacePB {+ fn from(value: UserWorkspaceTable) -> Self {Self {workspace_id: value.id,name: value.name,- created_at_timestamp: value.created_at.timestamp(),+ created_at_timestamp: value.created_at,icon: value.icon,member_count: value.member_count,role: value.role.map(AFRolePB::from),+ auth_type: AuthTypePB::from(value.auth_type),}}}diff --git a/frontend/rust-lib/flowy-user/src/entities/workspace.rs b/frontend/rust-lib/flowy-user/src/entities/workspace.rsindex 26f848f3f5..d277fb4614 100644--- a/frontend/rust-lib/flowy-user/src/entities/workspace.rs+++ b/frontend/rust-lib/flowy-user/src/entities/workspace.rs@@ -155,6 +155,17 @@ pub enum AFRolePB {Guest = 2,}+impl From<i32> for AFRolePB {+ fn from(value: i32) -> Self {+ match value {+ 0 => AFRolePB::Owner,+ 1 => AFRolePB::Member,+ 2 => AFRolePB::Guest,+ _ => AFRolePB::Guest,+ }+ }+}+impl From<AFRolePB> for Role {fn from(value: AFRolePB) -> Self {match value {@@ -182,6 +193,16 @@ pub struct UserWorkspaceIdPB {pub workspace_id: String,}+#[derive(ProtoBuf, Default, Clone, Validate)]+pub struct OpenUserWorkspacePB {+ #[pb(index = 1)]+ #[validate(custom(function = "required_not_empty_str"))]+ pub workspace_id: String,++ #[pb(index = 2)]+ pub auth_type: AuthTypePB,+}+#[derive(ProtoBuf, Default, Clone, Validate)]pub struct CancelWorkspaceSubscriptionPB {#[pb(index = 1)]@@ -221,12 +242,21 @@ pub struct CreateWorkspacePB {pub auth_type: AuthTypePB,}-#[derive(ProtoBuf_Enum, Default, Clone)]+#[derive(ProtoBuf_Enum, Default, Debug, Clone)]pub enum AuthTypePB {LocalAuthType = 0,#[default]CloudAuthType = 1,}+impl From<i32> for AuthTypePB {+ fn from(value: i32) -> Self {+ match value {+ 0 => AuthTypePB::LocalAuthType,+ 1 => AuthTypePB::CloudAuthType,+ _ => AuthTypePB::CloudAuthType,+ }+ }+}impl From<AuthType> for AuthTypePB {fn from(value: AuthType) -> Self {diff --git a/frontend/rust-lib/flowy-user/src/event_handler.rs b/frontend/rust-lib/flowy-user/src/event_handler.rsindex bb2a0b2c30..4cd49649ce 100644--- a/frontend/rust-lib/flowy-user/src/event_handler.rs+++ b/frontend/rust-lib/flowy-user/src/event_handler.rs@@ -440,21 +440,42 @@ pub async fn get_all_workspace_handler(let user_workspaces = manager.get_all_user_workspaces(profile.uid, profile.auth_type).await?;- data_result_ok(user_workspaces.into())++ data_result_ok(RepeatedUserWorkspacePB::from((+ profile.auth_type,+ user_workspaces,+ )))}#[tracing::instrument(level = "info", skip(data, manager), err)]pub async fn open_workspace_handler(- data: AFPluginData<UserWorkspaceIdPB>,+ data: AFPluginData<OpenUserWorkspacePB>,manager: AFPluginState<Weak<UserManager>>,) -> Result<(), FlowyError> {let manager = upgrade_manager(manager)?;let params = data.try_into_inner()?;let workspace_id = Uuid::from_str(¶ms.workspace_id)?;- manager.open_workspace(&workspace_id).await?;+ manager+ .open_workspace(&workspace_id, AuthType::from(params.auth_type))+ .await?;Ok(())}+#[tracing::instrument(level = "info", skip(data, manager), err)]+pub async fn get_user_workspace_handler(+ data: AFPluginData<UserWorkspaceIdPB>,+ manager: AFPluginState<Weak<UserManager>>,+) -> DataResult<UserWorkspacePB, FlowyError> {+ let manager = upgrade_manager(manager)?;+ let params = data.try_into_inner()?;+ let workspace_id = Uuid::from_str(¶ms.workspace_id)?;+ let uid = manager.user_id()?;+ let user_workspace = manager+ .get_user_workspace_from_db(uid, &workspace_id)+ .ok_or_else(FlowyError::record_not_found)?;+ data_result_ok(UserWorkspacePB::from(user_workspace))+}+#[tracing::instrument(level = "debug", skip(data, manager), err)]pub async fn update_network_state_handler(data: AFPluginData<NetworkStatePB>,@@ -610,7 +631,7 @@ pub async fn create_workspace_handler(let auth_type = AuthType::from(data.auth_type);let manager = upgrade_manager(manager)?;let new_workspace = manager.create_workspace(&data.name, auth_type).await?;- data_result_ok(new_workspace.into())+ data_result_ok(UserWorkspacePB::from((auth_type, new_workspace)))}#[tracing::instrument(level = "debug", skip_all, err)]diff --git a/frontend/rust-lib/flowy-user/src/event_map.rs b/frontend/rust-lib/flowy-user/src/event_map.rsindex 03660ad0ff..1ae414afa7 100644--- a/frontend/rust-lib/flowy-user/src/event_map.rs+++ b/frontend/rust-lib/flowy-user/src/event_map.rs@@ -39,6 +39,7 @@ pub fn init(user_manager: Weak<UserManager>) -> AFPlugin {.event(UserEvent::GenerateSignInURL, gen_sign_in_url_handler).event(UserEvent::GetOauthURLWithProvider, sign_in_with_provider_handler).event(UserEvent::OpenWorkspace, open_workspace_handler)+ .event(UserEvent::GetUserWorkspace, get_user_workspace_handler).event(UserEvent::UpdateNetworkState, update_network_state_handler).event(UserEvent::OpenAnonUser, open_anon_user_handler).event(UserEvent::GetAnonUser, get_anon_user_handler)@@ -144,9 +145,12 @@ pub enum UserEvent {#[event(output = "RepeatedUserWorkspacePB")]GetAllWorkspace = 17,- #[event(input = "UserWorkspaceIdPB")]+ #[event(input = "OpenUserWorkspacePB")]OpenWorkspace = 21,+ #[event(input = "UserWorkspaceIdPB", output = "UserWorkspacePB")]+ GetUserWorkspace = 22,+#[event(input = "NetworkStatePB")]UpdateNetworkState = 24,@@ -281,11 +285,10 @@ pub trait UserStatusCallback: Send + Sync + 'static {async fn did_init(&self,_user_id: i64,- _user_authenticator: &AuthType,_cloud_config: &Option<UserCloudConfig>,_user_workspace: &UserWorkspace,_device_id: &str,- _authenticator: &AuthType,+ _auth_type: &AuthType,) -> FlowyResult<()> {Ok(())}@@ -295,7 +298,7 @@ pub trait UserStatusCallback: Send + Sync + 'static {_user_id: i64,_user_workspace: &UserWorkspace,_device_id: &str,- _authenticator: &AuthType,+ _auth_type: &AuthType,) -> FlowyResult<()> {Ok(())}@@ -318,7 +321,7 @@ pub trait UserStatusCallback: Send + Sync + 'static {&self,_user_id: i64,_user_workspace: &UserWorkspace,- _authenticator: &AuthType,+ _auth_type: &AuthType,) -> FlowyResult<()> {Ok(())}diff --git a/frontend/rust-lib/flowy-user/src/services/sqlite_sql/workspace_sql.rs b/frontend/rust-lib/flowy-user/src/services/sqlite_sql/workspace_sql.rsindex f197ca9738..7fc3b00157 100644--- a/frontend/rust-lib/flowy-user/src/services/sqlite_sql/workspace_sql.rs+++ b/frontend/rust-lib/flowy-user/src/services/sqlite_sql/workspace_sql.rs@@ -1,5 +1,5 @@use chrono::{TimeZone, Utc};-use diesel::{RunQueryDsl, SqliteConnection};+use diesel::RunQueryDsl;use flowy_error::FlowyError;use flowy_sqlite::schema::user_workspace_table;use flowy_sqlite::DBConnection;@@ -55,12 +55,14 @@ impl UserWorkspaceTable {}}-pub fn select_user_workspace(workspace_id: &str, mut conn: DBConnection) -> Option<UserWorkspace> {+pub fn select_user_workspace(+ workspace_id: &str,+ mut conn: DBConnection,+) -> Option<UserWorkspaceTable> {user_workspace_table::dsl::user_workspace_table.filter(user_workspace_table::id.eq(workspace_id)).first::<UserWorkspaceTable>(&mut *conn).ok()- .map(UserWorkspace::from)}pub fn select_all_user_workspace(@@ -89,7 +91,7 @@ pub fn upsert_user_workspace(uid: i64,auth_type: AuthType,user_workspace: UserWorkspace,- conn: &mut SqliteConnection,+ conn: &mut DBConnection,) -> Result<(), FlowyError> {let new_record = UserWorkspaceTable::from_workspace(uid, &user_workspace, auth_type)?;diff --git a/frontend/rust-lib/flowy-user/src/user_manager/manager.rs b/frontend/rust-lib/flowy-user/src/user_manager/manager.rsindex d7d7c8b68d..14aaebe86c 100644--- a/frontend/rust-lib/flowy-user/src/user_manager/manager.rs+++ b/frontend/rust-lib/flowy-user/src/user_manager/manager.rs@@ -273,7 +273,6 @@ impl UserManager {user_status_callback.did_init(user.uid,- &user.auth_type,&cloud_config,&session.user_workspace,&self.authenticate_user.user_config.device_id,diff --git a/frontend/rust-lib/flowy-user/src/user_manager/manager_user_workspace.rs b/frontend/rust-lib/flowy-user/src/user_manager/manager_user_workspace.rsindex ac15324c00..b24764cc6b 100644--- a/frontend/rust-lib/flowy-user/src/user_manager/manager_user_workspace.rs+++ b/frontend/rust-lib/flowy-user/src/user_manager/manager_user_workspace.rs@@ -32,7 +32,7 @@ use flowy_error::{ErrorCode, FlowyError, FlowyResult};use flowy_folder_pub::entities::{ImportFrom, ImportedCollabData, ImportedFolderData};use flowy_sqlite::schema::user_workspace_table;use flowy_sqlite::{query_dsl::*, ConnectionPool, DBConnection, ExpressionMethods};-use flowy_user_pub::cloud::UserCloudServiceProvider;+use flowy_user_pub::cloud::{UserCloudService, UserCloudServiceProvider};use flowy_user_pub::entities::{AuthType, Role, UserWorkspace, WorkspaceInvitation, WorkspaceInvitationStatus, WorkspaceMember,};@@ -162,13 +162,32 @@ impl UserManager {}#[instrument(skip(self), err)]- pub async fn open_workspace(&self, workspace_id: &Uuid) -> FlowyResult<()> {- info!("open workspace: {}", workspace_id);- let user_workspace = self- .cloud_service- .get_user_service()?- .open_workspace(workspace_id)- .await?;+ pub async fn open_workspace(&self, workspace_id: &Uuid, auth_type: AuthType) -> FlowyResult<()> {+ info!("open workspace: {}, auth_type:{}", workspace_id, auth_type);+ let uid = self.user_id()?;+ let conn = self.db_connection(self.user_id()?)?;+ let user_workspace = match select_user_workspace(&workspace_id.to_string(), conn) {+ None => {+ sync_workspace(+ workspace_id,+ self.cloud_service.get_user_service()?,+ uid,+ auth_type,+ self.db_pool(uid)?,+ )+ .await?+ },+ Some(row) => {+ let user_workspace = UserWorkspace::from(row);+ let workspace_id = *workspace_id;+ let user_service = self.cloud_service.get_user_service()?;+ let pool = self.db_pool(uid)?;+ tokio::spawn(async move {+ let _ = sync_workspace(&workspace_id, user_service, uid, auth_type, pool).await;+ });+ user_workspace+ },+ };self.authenticate_user@@ -176,6 +195,15 @@ impl UserManager {let uid = self.user_id()?;let user_profile = self.get_user_profile_from_disk(uid).await?;+ if let Err(err) = self+ .user_status_callback+ .read()+ .await+ .open_workspace(uid, &user_workspace, &user_profile.auth_type)+ .await+ {+ error!("Open workspace failed: {:?}", err);+ }if let Err(err) = self.initial_user_awareness(self.get_session()?.as_ref(), &user_profile.auth_type)@@ -187,16 +215,6 @@ impl UserManager {);}- if let Err(err) = self- .user_status_callback- .read()- .await- .open_workspace(uid, &user_workspace, &user_profile.auth_type)- .await- {- error!("Open workspace failed: {:?}", err);- }-Ok(())}@@ -240,10 +258,11 @@ impl UserManager {let conn = self.db_connection(uid)?;update_user_workspace(conn, changeset)?;- let user_workspace = self- .get_user_workspace(uid, workspace_id)+ let row = self+ .get_user_workspace_from_db(uid, workspace_id).ok_or_else(FlowyError::record_not_found)?;- let payload: UserWorkspacePB = user_workspace.clone().into();++ let payload = UserWorkspacePB::from(row);send_notification(&uid.to_string(), UserNotification::DidUpdateUserWorkspace).payload(payload).send();@@ -376,7 +395,11 @@ impl UserManager {Ok(())}- pub fn get_user_workspace(&self, uid: i64, workspace_id: &Uuid) -> Option<UserWorkspace> {+ pub fn get_user_workspace_from_db(+ &self,+ uid: i64,+ workspace_id: &Uuid,+ ) -> Option<UserWorkspaceTable> {let conn = self.db_connection(uid).ok()?;select_user_workspace(workspace_id.to_string().as_str(), conn)}@@ -395,7 +418,8 @@ impl UserManager {if let Ok(new_user_workspaces) = service.get_all_workspace(uid).await {if let Ok(conn) = pool.get() {let _ = save_all_user_workspaces(uid, conn, auth_type, &new_user_workspaces);- let repeated_workspace_pbs = RepeatedUserWorkspacePB::from(new_user_workspaces);+ let repeated_workspace_pbs =+ RepeatedUserWorkspacePB::from((auth_type, new_user_workspaces));send_notification(&uid.to_string(), UserNotification::DidUpdateUserWorkspaces).payload(repeated_workspace_pbs).send();@@ -783,3 +807,17 @@ async fn sync_workspace_settings(}Ok(())}++async fn sync_workspace(+ workspace_id: &Uuid,+ user_service: Arc<dyn UserCloudService>,+ uid: i64,+ auth_type: AuthType,+ pool: Arc<ConnectionPool>,+) -> FlowyResult<UserWorkspace> {+ let user_workspace = user_service.open_workspace(workspace_id).await?;+ if let Ok(mut conn) = pool.get() {+ upsert_user_workspace(uid, auth_type, user_workspace.clone(), &mut conn)?;+ }+ Ok(user_workspace)+}