manager.rs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  1. use std::collections::HashSet;
  2. use std::ops::Deref;
  3. use std::sync::{Arc, Weak};
  4. use appflowy_integrate::collab_builder::AppFlowyCollabBuilder;
  5. use appflowy_integrate::{CollabPersistenceConfig, RocksCollabDB, YrsDocAction};
  6. use collab::core::collab::{CollabRawData, MutexCollab};
  7. use collab::core::collab_state::SyncState;
  8. use collab_define::CollabType;
  9. use collab_folder::core::{
  10. FavoritesInfo, Folder, FolderData, FolderNotify, TrashChange, TrashChangeReceiver, TrashInfo,
  11. View, ViewChange, ViewChangeReceiver, ViewLayout, ViewUpdate, Workspace,
  12. };
  13. use parking_lot::{Mutex, RwLock};
  14. use tokio_stream::wrappers::WatchStream;
  15. use tokio_stream::StreamExt;
  16. use tracing::{event, Level};
  17. use flowy_error::{ErrorCode, FlowyError, FlowyResult};
  18. use flowy_folder_deps::cloud::{gen_view_id, FolderCloudService};
  19. use crate::entities::icon::UpdateViewIconParams;
  20. use crate::entities::{
  21. view_pb_with_child_views, view_pb_without_child_views, ChildViewUpdatePB, CreateViewParams,
  22. CreateWorkspaceParams, DeletedViewPB, FolderSnapshotPB, FolderSnapshotStatePB, FolderSyncStatePB,
  23. RepeatedTrashPB, RepeatedViewPB, RepeatedWorkspacePB, UpdateViewParams, UserFolderPB, ViewPB,
  24. WorkspacePB,
  25. };
  26. use crate::notification::{
  27. send_notification, send_workspace_notification, send_workspace_setting_notification,
  28. FolderNotification,
  29. };
  30. use crate::share::ImportParams;
  31. use crate::user_default::DefaultFolderBuilder;
  32. use crate::view_operation::{create_view, FolderOperationHandler, FolderOperationHandlers};
  33. /// [FolderUser] represents the user for folder.
  34. pub trait FolderUser: Send + Sync {
  35. fn user_id(&self) -> Result<i64, FlowyError>;
  36. fn token(&self) -> Result<Option<String>, FlowyError>;
  37. fn collab_db(&self, uid: i64) -> Result<Weak<RocksCollabDB>, FlowyError>;
  38. }
  39. pub struct FolderManager {
  40. workspace_id: RwLock<Option<String>>,
  41. mutex_folder: Arc<MutexFolder>,
  42. collab_builder: Arc<AppFlowyCollabBuilder>,
  43. user: Arc<dyn FolderUser>,
  44. operation_handlers: FolderOperationHandlers,
  45. cloud_service: Arc<dyn FolderCloudService>,
  46. }
  47. unsafe impl Send for FolderManager {}
  48. unsafe impl Sync for FolderManager {}
  49. impl FolderManager {
  50. pub async fn new(
  51. user: Arc<dyn FolderUser>,
  52. collab_builder: Arc<AppFlowyCollabBuilder>,
  53. operation_handlers: FolderOperationHandlers,
  54. cloud_service: Arc<dyn FolderCloudService>,
  55. ) -> FlowyResult<Self> {
  56. let mutex_folder = Arc::new(MutexFolder::default());
  57. let manager = Self {
  58. user,
  59. mutex_folder,
  60. collab_builder,
  61. operation_handlers,
  62. cloud_service,
  63. workspace_id: Default::default(),
  64. };
  65. Ok(manager)
  66. }
  67. pub async fn get_current_workspace(&self) -> FlowyResult<WorkspacePB> {
  68. self.with_folder(
  69. || {
  70. let uid = self.user.user_id()?;
  71. let workspace_id = self.workspace_id.read().as_ref().cloned().ok_or(
  72. FlowyError::from(ErrorCode::WorkspaceIdInvalid)
  73. .with_context("Unexpected empty workspace id"),
  74. )?;
  75. Err(workspace_data_not_sync_error(uid, &workspace_id))
  76. },
  77. |folder| {
  78. let workspace_pb_from_workspace = |workspace: Workspace, folder: &Folder| {
  79. let views = get_workspace_view_pbs(&workspace.id, folder);
  80. let workspace: WorkspacePB = (workspace, views).into();
  81. Ok::<WorkspacePB, FlowyError>(workspace)
  82. };
  83. match folder.get_current_workspace() {
  84. None => {
  85. // The current workspace should always exist. If not, try to find the first workspace.
  86. // from the folder. Otherwise, return an error.
  87. let mut workspaces = folder.workspaces.get_all_workspaces();
  88. if workspaces.is_empty() {
  89. Err(FlowyError::record_not_found().with_context("Can not find the workspace"))
  90. } else {
  91. tracing::error!("Can't find the current workspace, use the first workspace");
  92. let workspace = workspaces.remove(0);
  93. folder.set_current_workspace(&workspace.id);
  94. workspace_pb_from_workspace(workspace, folder)
  95. }
  96. },
  97. Some(workspace) => workspace_pb_from_workspace(workspace, folder),
  98. }
  99. },
  100. )
  101. }
  102. /// Return a list of views of the current workspace.
  103. /// Only the first level of child views are included.
  104. pub async fn get_current_workspace_views(&self) -> FlowyResult<Vec<ViewPB>> {
  105. let workspace_id = self
  106. .mutex_folder
  107. .lock()
  108. .as_ref()
  109. .map(|folder| folder.get_current_workspace_id());
  110. if let Some(Some(workspace_id)) = workspace_id {
  111. self.get_workspace_views(&workspace_id).await
  112. } else {
  113. tracing::warn!("Can't get current workspace views");
  114. Ok(vec![])
  115. }
  116. }
  117. pub async fn get_workspace_views(&self, workspace_id: &str) -> FlowyResult<Vec<ViewPB>> {
  118. let views = self.with_folder(std::vec::Vec::new, |folder| {
  119. get_workspace_view_pbs(workspace_id, folder)
  120. });
  121. Ok(views)
  122. }
  123. /// Called immediately after the application launched fi the user already sign in/sign up.
  124. #[tracing::instrument(level = "info", skip(self, initial_data), err)]
  125. pub async fn initialize(
  126. &self,
  127. uid: i64,
  128. workspace_id: &str,
  129. initial_data: FolderInitializeDataSource,
  130. ) -> FlowyResult<()> {
  131. *self.workspace_id.write() = Some(workspace_id.to_string());
  132. let workspace_id = workspace_id.to_string();
  133. if let Ok(collab_db) = self.user.collab_db(uid) {
  134. let (view_tx, view_rx) = tokio::sync::broadcast::channel(100);
  135. let (trash_tx, trash_rx) = tokio::sync::broadcast::channel(100);
  136. let folder_notifier = FolderNotify {
  137. view_change_tx: view_tx,
  138. trash_change_tx: trash_tx,
  139. };
  140. let folder = match initial_data {
  141. FolderInitializeDataSource::LocalDisk {
  142. create_if_not_exist,
  143. } => {
  144. let is_exist = is_exist_in_local_disk(&self.user, &workspace_id).unwrap_or(false);
  145. if is_exist {
  146. let collab = self.collab_for_folder(uid, &workspace_id, collab_db, vec![])?;
  147. Folder::open(collab, Some(folder_notifier))
  148. } else if create_if_not_exist {
  149. let folder_data =
  150. DefaultFolderBuilder::build(uid, workspace_id.to_string(), &self.operation_handlers)
  151. .await;
  152. let collab = self.collab_for_folder(uid, &workspace_id, collab_db, vec![])?;
  153. Folder::create(collab, Some(folder_notifier), Some(folder_data))
  154. } else {
  155. return Err(FlowyError::new(
  156. ErrorCode::RecordNotFound,
  157. "Can't find any workspace data",
  158. ));
  159. }
  160. },
  161. FolderInitializeDataSource::Cloud(raw_data) => {
  162. if raw_data.is_empty() {
  163. return Err(workspace_data_not_sync_error(uid, &workspace_id));
  164. }
  165. let collab = self.collab_for_folder(uid, &workspace_id, collab_db, raw_data)?;
  166. Folder::open(collab, Some(folder_notifier))
  167. },
  168. FolderInitializeDataSource::FolderData(folder_data) => {
  169. let collab = self.collab_for_folder(uid, &workspace_id, collab_db, vec![])?;
  170. Folder::create(collab, Some(folder_notifier), Some(folder_data))
  171. },
  172. };
  173. tracing::debug!("Current workspace_id: {}", workspace_id);
  174. let folder_state_rx = folder.subscribe_sync_state();
  175. *self.mutex_folder.lock() = Some(folder);
  176. let weak_mutex_folder = Arc::downgrade(&self.mutex_folder);
  177. subscribe_folder_sync_state_changed(
  178. workspace_id.clone(),
  179. folder_state_rx,
  180. &weak_mutex_folder,
  181. );
  182. subscribe_folder_snapshot_state_changed(workspace_id, &weak_mutex_folder);
  183. subscribe_folder_trash_changed(trash_rx, &weak_mutex_folder);
  184. subscribe_folder_view_changed(view_rx, &weak_mutex_folder);
  185. }
  186. Ok(())
  187. }
  188. fn collab_for_folder(
  189. &self,
  190. uid: i64,
  191. workspace_id: &str,
  192. collab_db: Weak<RocksCollabDB>,
  193. raw_data: CollabRawData,
  194. ) -> Result<Arc<MutexCollab>, FlowyError> {
  195. let collab = self.collab_builder.build_with_config(
  196. uid,
  197. workspace_id,
  198. CollabType::Folder,
  199. collab_db,
  200. raw_data,
  201. &CollabPersistenceConfig::new().enable_snapshot(true),
  202. )?;
  203. Ok(collab)
  204. }
  205. /// Initialize the folder with the given workspace id.
  206. /// Fetch the folder updates from the cloud service and initialize the folder.
  207. #[tracing::instrument(level = "debug", skip(self, user_id), err)]
  208. pub async fn initialize_with_workspace_id(
  209. &self,
  210. user_id: i64,
  211. workspace_id: &str,
  212. ) -> FlowyResult<()> {
  213. let folder_updates = self
  214. .cloud_service
  215. .get_folder_updates(workspace_id, user_id)
  216. .await?;
  217. tracing::info!(
  218. "Get folder updates via {}, number of updates: {}",
  219. self.cloud_service.service_name(),
  220. folder_updates.len()
  221. );
  222. self
  223. .initialize(
  224. user_id,
  225. workspace_id,
  226. FolderInitializeDataSource::Cloud(folder_updates),
  227. )
  228. .await?;
  229. Ok(())
  230. }
  231. /// Initialize the folder for the new user.
  232. /// Using the [DefaultFolderBuilder] to create the default workspace for the new user.
  233. pub async fn initialize_with_new_user(
  234. &self,
  235. user_id: i64,
  236. _token: &str,
  237. is_new: bool,
  238. data_source: FolderInitializeDataSource,
  239. workspace_id: &str,
  240. ) -> FlowyResult<()> {
  241. // Create the default workspace if the user is new
  242. tracing::info!("initialize_when_sign_up: is_new: {}", is_new);
  243. if is_new {
  244. self.initialize(user_id, workspace_id, data_source).await?;
  245. } else {
  246. // The folder updates should not be empty, as the folder data is stored
  247. // when the user signs up for the first time.
  248. let folder_updates = self
  249. .cloud_service
  250. .get_folder_updates(workspace_id, user_id)
  251. .await?;
  252. tracing::info!(
  253. "Get folder updates via {}, number of updates: {}",
  254. self.cloud_service.service_name(),
  255. folder_updates.len()
  256. );
  257. self
  258. .initialize(
  259. user_id,
  260. workspace_id,
  261. FolderInitializeDataSource::Cloud(folder_updates),
  262. )
  263. .await?;
  264. }
  265. Ok(())
  266. }
  267. /// Called when the current user logout
  268. ///
  269. pub async fn clear(&self, _user_id: i64) {}
  270. #[tracing::instrument(level = "info", skip_all, err)]
  271. pub async fn create_workspace(&self, params: CreateWorkspaceParams) -> FlowyResult<Workspace> {
  272. let workspace = self
  273. .cloud_service
  274. .create_workspace(self.user.user_id()?, &params.name)
  275. .await?;
  276. self.with_folder(
  277. || (),
  278. |folder| {
  279. folder.workspaces.create_workspace(workspace.clone());
  280. folder.set_current_workspace(&workspace.id);
  281. },
  282. );
  283. let repeated_workspace = RepeatedWorkspacePB {
  284. items: vec![workspace.clone().into()],
  285. };
  286. send_workspace_notification(FolderNotification::DidCreateWorkspace, repeated_workspace);
  287. Ok(workspace)
  288. }
  289. #[tracing::instrument(level = "info", skip_all, err)]
  290. pub async fn open_workspace(&self, workspace_id: &str) -> FlowyResult<Workspace> {
  291. self.with_folder(
  292. || Err(FlowyError::internal()),
  293. |folder| {
  294. let workspace = folder
  295. .workspaces
  296. .get_workspace(workspace_id)
  297. .ok_or_else(|| {
  298. FlowyError::record_not_found().with_context("Can't open not existing workspace")
  299. })?;
  300. folder.set_current_workspace(&workspace.id);
  301. Ok::<Workspace, FlowyError>(workspace)
  302. },
  303. )
  304. }
  305. pub async fn get_workspace(&self, workspace_id: &str) -> Option<Workspace> {
  306. self.with_folder(
  307. || None,
  308. |folder| folder.workspaces.get_workspace(workspace_id),
  309. )
  310. }
  311. async fn get_current_workspace_id(&self) -> FlowyResult<String> {
  312. self
  313. .mutex_folder
  314. .lock()
  315. .as_ref()
  316. .and_then(|folder| folder.get_current_workspace_id())
  317. .ok_or(FlowyError::internal().with_context("Unexpected empty workspace id"))
  318. }
  319. /// This function acquires a lock on the `mutex_folder` and checks its state.
  320. /// If the folder is `None`, it invokes the `none_callback`, otherwise, it passes the folder to the `f2` callback.
  321. ///
  322. /// # Parameters
  323. ///
  324. /// * `none_callback`: A callback function that is invoked when `mutex_folder` contains `None`.
  325. /// * `f2`: A callback function that is invoked when `mutex_folder` contains a `Some` value. The contained folder is passed as an argument to this callback.
  326. fn with_folder<F1, F2, Output>(&self, none_callback: F1, f2: F2) -> Output
  327. where
  328. F1: FnOnce() -> Output,
  329. F2: FnOnce(&Folder) -> Output,
  330. {
  331. let folder = self.mutex_folder.lock();
  332. match &*folder {
  333. None => none_callback(),
  334. Some(folder) => f2(folder),
  335. }
  336. }
  337. pub async fn get_all_workspaces(&self) -> Vec<Workspace> {
  338. self.with_folder(std::vec::Vec::new, |folder| {
  339. folder.workspaces.get_all_workspaces()
  340. })
  341. }
  342. pub async fn create_view_with_params(&self, params: CreateViewParams) -> FlowyResult<View> {
  343. let view_layout: ViewLayout = params.layout.clone().into();
  344. let _workspace_id = self.get_current_workspace_id().await?;
  345. let handler = self.get_handler(&view_layout)?;
  346. let user_id = self.user.user_id()?;
  347. let meta = params.meta.clone();
  348. if meta.is_empty() && params.initial_data.is_empty() {
  349. tracing::trace!("Create view with build-in data");
  350. handler
  351. .create_built_in_view(user_id, &params.view_id, &params.name, view_layout.clone())
  352. .await?;
  353. } else {
  354. tracing::trace!("Create view with view data");
  355. handler
  356. .create_view_with_view_data(
  357. user_id,
  358. &params.view_id,
  359. &params.name,
  360. params.initial_data.clone(),
  361. view_layout.clone(),
  362. meta,
  363. )
  364. .await?;
  365. }
  366. let index = params.index;
  367. let view = create_view(params, view_layout);
  368. self.with_folder(
  369. || (),
  370. |folder| {
  371. folder.insert_view(view.clone(), index);
  372. },
  373. );
  374. Ok(view)
  375. }
  376. /// The orphan view is meant to be a view that is not attached to any parent view. By default, this
  377. /// view will not be shown in the view list unless it is attached to a parent view that is shown in
  378. /// the view list.
  379. pub async fn create_orphan_view_with_params(
  380. &self,
  381. params: CreateViewParams,
  382. ) -> FlowyResult<View> {
  383. let view_layout: ViewLayout = params.layout.clone().into();
  384. let handler = self.get_handler(&view_layout)?;
  385. let user_id = self.user.user_id()?;
  386. handler
  387. .create_built_in_view(user_id, &params.view_id, &params.name, view_layout.clone())
  388. .await?;
  389. let view = create_view(params, view_layout);
  390. self.with_folder(
  391. || (),
  392. |folder| {
  393. folder.insert_view(view.clone(), None);
  394. },
  395. );
  396. Ok(view)
  397. }
  398. #[tracing::instrument(level = "debug", skip(self), err)]
  399. pub(crate) async fn close_view(&self, view_id: &str) -> Result<(), FlowyError> {
  400. if let Some(view) = self.with_folder(|| None, |folder| folder.views.get_view(view_id)) {
  401. let handler = self.get_handler(&view.layout)?;
  402. handler.close_view(view_id).await?;
  403. }
  404. Ok(())
  405. }
  406. /// Returns the view with the given view id.
  407. /// The child views of the view will only access the first. So if you want to get the child view's
  408. /// child view, you need to call this method again.
  409. #[tracing::instrument(level = "debug", skip(self, view_id), err)]
  410. pub async fn get_view(&self, view_id: &str) -> FlowyResult<ViewPB> {
  411. let view_id = view_id.to_string();
  412. let folder = self.mutex_folder.lock();
  413. let folder = folder.as_ref().ok_or_else(folder_not_init_error)?;
  414. let trash_ids = folder
  415. .get_all_trash()
  416. .into_iter()
  417. .map(|trash| trash.id)
  418. .collect::<Vec<String>>();
  419. if trash_ids.contains(&view_id) {
  420. return Err(FlowyError::record_not_found());
  421. }
  422. match folder.views.get_view(&view_id) {
  423. None => Err(FlowyError::record_not_found()),
  424. Some(view) => {
  425. let child_views = folder
  426. .views
  427. .get_views_belong_to(&view.id)
  428. .into_iter()
  429. .filter(|view| !trash_ids.contains(&view.id))
  430. .collect::<Vec<_>>();
  431. let view_pb = view_pb_with_child_views(view, child_views);
  432. Ok(view_pb)
  433. },
  434. }
  435. }
  436. /// Move the view to trash. If the view is the current view, then set the current view to empty.
  437. /// When the view is moved to trash, all the child views will be moved to trash as well.
  438. /// All the favorite views being trashed will be unfavorited first to remove it from favorites list as well. The process of unfavoriting concerned view is handled by `unfavorite_view_and_decendants()`
  439. #[tracing::instrument(level = "debug", skip(self), err)]
  440. pub async fn move_view_to_trash(&self, view_id: &str) -> FlowyResult<()> {
  441. self.with_folder(
  442. || (),
  443. |folder| {
  444. if let Some(view) = folder.views.get_view(view_id) {
  445. self.unfavorite_view_and_decendants(view.clone(), folder);
  446. folder.add_trash(vec![view_id.to_string()]);
  447. // notify the parent view that the view is moved to trash
  448. send_notification(view_id, FolderNotification::DidMoveViewToTrash)
  449. .payload(DeletedViewPB {
  450. view_id: view_id.to_string(),
  451. index: None,
  452. })
  453. .send();
  454. notify_child_views_changed(
  455. view_pb_without_child_views(view),
  456. ChildViewChangeReason::DidDeleteView,
  457. );
  458. }
  459. },
  460. );
  461. Ok(())
  462. }
  463. fn unfavorite_view_and_decendants(&self, view: Arc<View>, folder: &Folder) {
  464. let mut all_descendant_views: Vec<Arc<View>> = vec![view.clone()];
  465. all_descendant_views.extend(folder.views.get_views_belong_to(&view.id));
  466. let favorite_descendant_views: Vec<ViewPB> = all_descendant_views
  467. .iter()
  468. .filter(|view| view.is_favorite)
  469. .map(|view| view_pb_without_child_views(view.clone()))
  470. .collect();
  471. if !favorite_descendant_views.is_empty() {
  472. folder.delete_favorites(
  473. favorite_descendant_views
  474. .iter()
  475. .map(|v| v.id.clone())
  476. .collect(),
  477. );
  478. send_notification("favorite", FolderNotification::DidUnfavoriteView)
  479. .payload(RepeatedViewPB {
  480. items: favorite_descendant_views,
  481. })
  482. .send();
  483. }
  484. }
  485. /// Moves a nested view to a new location in the hierarchy.
  486. ///
  487. /// This function takes the `view_id` of the view to be moved,
  488. /// `new_parent_id` of the view under which the `view_id` should be moved,
  489. /// and an optional `prev_view_id` to position the `view_id` right after
  490. /// this specific view.
  491. ///
  492. /// If `prev_view_id` is provided, the moved view will be placed right after
  493. /// the view corresponding to `prev_view_id` under the `new_parent_id`.
  494. /// If `prev_view_id` is `None`, the moved view will become the first child of the new parent.
  495. ///
  496. /// # Arguments
  497. ///
  498. /// * `view_id` - A string slice that holds the id of the view to be moved.
  499. /// * `new_parent_id` - A string slice that holds the id of the new parent view.
  500. /// * `prev_view_id` - An `Option<String>` that holds the id of the view after which the `view_id` should be positioned.
  501. ///
  502. #[tracing::instrument(level = "trace", skip(self), err)]
  503. pub async fn move_nested_view(
  504. &self,
  505. view_id: String,
  506. new_parent_id: String,
  507. prev_view_id: Option<String>,
  508. ) -> FlowyResult<()> {
  509. let view = self.get_view(&view_id).await?;
  510. let old_parent_id = view.parent_view_id;
  511. self.with_folder(
  512. || (),
  513. |folder| {
  514. folder.move_nested_view(&view_id, &new_parent_id, prev_view_id);
  515. },
  516. );
  517. notify_parent_view_did_change(
  518. self.mutex_folder.clone(),
  519. vec![new_parent_id, old_parent_id],
  520. );
  521. Ok(())
  522. }
  523. /// Move the view with given id from one position to another position.
  524. /// The view will be moved to the new position in the same parent view.
  525. /// The passed in index is the index of the view that displayed in the UI.
  526. /// We need to convert the index to the real index of the view in the parent view.
  527. #[tracing::instrument(level = "trace", skip(self), err)]
  528. pub async fn move_view(&self, view_id: &str, from: usize, to: usize) -> FlowyResult<()> {
  529. if let Some((is_workspace, parent_view_id, child_views)) = self.get_view_relation(view_id).await
  530. {
  531. // The display parent view is the view that is displayed in the UI
  532. let display_views = if is_workspace {
  533. self
  534. .get_current_workspace()
  535. .await?
  536. .views
  537. .into_iter()
  538. .map(|view| view.id)
  539. .collect::<Vec<_>>()
  540. } else {
  541. self
  542. .get_view(&parent_view_id)
  543. .await?
  544. .child_views
  545. .into_iter()
  546. .map(|view| view.id)
  547. .collect::<Vec<_>>()
  548. };
  549. if display_views.len() > to {
  550. let to_view_id = display_views[to].clone();
  551. // Find the actual index of the view in the parent view
  552. let actual_from_index = child_views.iter().position(|id| id == view_id);
  553. let actual_to_index = child_views.iter().position(|id| id == &to_view_id);
  554. if let (Some(actual_from_index), Some(actual_to_index)) =
  555. (actual_from_index, actual_to_index)
  556. {
  557. self.with_folder(
  558. || (),
  559. |folder| {
  560. folder.move_view(view_id, actual_from_index as u32, actual_to_index as u32);
  561. },
  562. );
  563. notify_parent_view_did_change(self.mutex_folder.clone(), vec![parent_view_id]);
  564. }
  565. }
  566. }
  567. Ok(())
  568. }
  569. /// Return a list of views that belong to the given parent view id.
  570. #[tracing::instrument(level = "debug", skip(self, parent_view_id), err)]
  571. pub async fn get_views_belong_to(&self, parent_view_id: &str) -> FlowyResult<Vec<Arc<View>>> {
  572. let views = self.with_folder(std::vec::Vec::new, |folder| {
  573. folder.views.get_views_belong_to(parent_view_id)
  574. });
  575. Ok(views)
  576. }
  577. /// Update the view with the given params.
  578. #[tracing::instrument(level = "trace", skip(self), err)]
  579. pub async fn update_view_with_params(&self, params: UpdateViewParams) -> FlowyResult<()> {
  580. self
  581. .update_view(&params.view_id, |update| {
  582. update
  583. .set_name_if_not_none(params.name)
  584. .set_desc_if_not_none(params.desc)
  585. .set_layout_if_not_none(params.layout)
  586. .set_favorite_if_not_none(params.is_favorite)
  587. .done()
  588. })
  589. .await
  590. }
  591. /// Update the icon of the view with the given params.
  592. #[tracing::instrument(level = "trace", skip(self), err)]
  593. pub async fn update_view_icon_with_params(
  594. &self,
  595. params: UpdateViewIconParams,
  596. ) -> FlowyResult<()> {
  597. self
  598. .update_view(&params.view_id, |update| {
  599. update.set_icon(params.icon).done()
  600. })
  601. .await
  602. }
  603. /// Duplicate the view with the given view id.
  604. #[tracing::instrument(level = "debug", skip(self), err)]
  605. pub(crate) async fn duplicate_view(&self, view_id: &str) -> Result<(), FlowyError> {
  606. let view = self
  607. .with_folder(|| None, |folder| folder.views.get_view(view_id))
  608. .ok_or_else(|| FlowyError::record_not_found().with_context("Can't duplicate the view"))?;
  609. let handler = self.get_handler(&view.layout)?;
  610. let view_data = handler.duplicate_view(&view.id).await?;
  611. // get the current view index in the parent view, because we need to insert the duplicated view below the current view.
  612. let index = if let Some((_, __, views)) = self.get_view_relation(&view.parent_view_id).await {
  613. views.iter().position(|id| id == view_id).map(|i| i as u32)
  614. } else {
  615. None
  616. };
  617. let duplicate_params = CreateViewParams {
  618. parent_view_id: view.parent_view_id.clone(),
  619. name: format!("{} (copy)", &view.name),
  620. desc: view.desc.clone(),
  621. layout: view.layout.clone().into(),
  622. initial_data: view_data.to_vec(),
  623. view_id: gen_view_id().to_string(),
  624. meta: Default::default(),
  625. set_as_current: true,
  626. index,
  627. };
  628. self.create_view_with_params(duplicate_params).await?;
  629. Ok(())
  630. }
  631. #[tracing::instrument(level = "trace", skip(self), err)]
  632. pub(crate) async fn set_current_view(&self, view_id: &str) -> Result<(), FlowyError> {
  633. let folder = self.mutex_folder.lock();
  634. let folder = folder.as_ref().ok_or_else(folder_not_init_error)?;
  635. folder.set_current_view(view_id);
  636. let workspace = folder.get_current_workspace();
  637. let view = folder
  638. .get_current_view()
  639. .and_then(|view_id| folder.views.get_view(&view_id));
  640. send_workspace_setting_notification(workspace, view);
  641. Ok(())
  642. }
  643. #[tracing::instrument(level = "trace", skip(self))]
  644. pub(crate) async fn get_current_view(&self) -> Option<ViewPB> {
  645. let view_id = self.with_folder(|| None, |folder| folder.get_current_view())?;
  646. self.get_view(&view_id).await.ok()
  647. }
  648. /// Toggles the favorite status of a view identified by `view_id`If the view is not a favorite, it will be added to the favorites list; otherwise, it will be removed from the list.
  649. #[tracing::instrument(level = "debug", skip(self), err)]
  650. pub async fn toggle_favorites(&self, view_id: &str) -> FlowyResult<()> {
  651. self.with_folder(
  652. || (),
  653. |folder| {
  654. if let Some(old_view) = folder.views.get_view(view_id) {
  655. if old_view.is_favorite {
  656. folder.delete_favorites(vec![view_id.to_string()]);
  657. } else {
  658. folder.add_favorites(vec![view_id.to_string()]);
  659. }
  660. }
  661. },
  662. );
  663. self.send_toggle_favorite_notification(view_id).await;
  664. Ok(())
  665. }
  666. // Used by toggle_favorites to send notification to frontend, after the favorite status of view has been changed.It sends two distinct notifications: one to correctly update the concerned view's is_favorite status, and another to update the list of favorites that is to be displayed.
  667. async fn send_toggle_favorite_notification(&self, view_id: &str) {
  668. if let Ok(view) = self.get_view(view_id).await {
  669. let notification_type = if view.is_favorite {
  670. FolderNotification::DidFavoriteView
  671. } else {
  672. FolderNotification::DidUnfavoriteView
  673. };
  674. send_notification("favorite", notification_type)
  675. .payload(RepeatedViewPB {
  676. items: vec![view.clone()],
  677. })
  678. .send();
  679. send_notification(&view.id, FolderNotification::DidUpdateView)
  680. .payload(view)
  681. .send()
  682. }
  683. }
  684. #[tracing::instrument(level = "trace", skip(self))]
  685. pub(crate) async fn get_all_favorites(&self) -> Vec<FavoritesInfo> {
  686. self.with_folder(std::vec::Vec::new, |folder| {
  687. let trash_ids = folder
  688. .get_all_trash()
  689. .into_iter()
  690. .map(|trash| trash.id)
  691. .collect::<Vec<String>>();
  692. let mut views = folder.get_all_favorites();
  693. views.retain(|view| !trash_ids.contains(&view.id));
  694. views
  695. })
  696. }
  697. #[tracing::instrument(level = "trace", skip(self))]
  698. pub(crate) async fn get_all_trash(&self) -> Vec<TrashInfo> {
  699. self.with_folder(std::vec::Vec::new, |folder| folder.get_all_trash())
  700. }
  701. #[tracing::instrument(level = "trace", skip(self))]
  702. pub(crate) async fn restore_all_trash(&self) {
  703. self.with_folder(
  704. || (),
  705. |folder| {
  706. folder.remote_all_trash();
  707. },
  708. );
  709. send_notification("trash", FolderNotification::DidUpdateTrash)
  710. .payload(RepeatedTrashPB { items: vec![] })
  711. .send();
  712. }
  713. #[tracing::instrument(level = "trace", skip(self))]
  714. pub(crate) async fn restore_trash(&self, trash_id: &str) {
  715. self.with_folder(
  716. || (),
  717. |folder| {
  718. folder.delete_trash(vec![trash_id.to_string()]);
  719. },
  720. );
  721. }
  722. /// Delete all the trash permanently.
  723. #[tracing::instrument(level = "trace", skip(self))]
  724. pub(crate) async fn delete_all_trash(&self) {
  725. let deleted_trash = self.with_folder(std::vec::Vec::new, |folder| folder.get_all_trash());
  726. for trash in deleted_trash {
  727. let _ = self.delete_trash(&trash.id).await;
  728. }
  729. send_notification("trash", FolderNotification::DidUpdateTrash)
  730. .payload(RepeatedTrashPB { items: vec![] })
  731. .send();
  732. }
  733. /// Delete the trash permanently.
  734. /// Delete the view will delete all the resources that the view holds. For example, if the view
  735. /// is a database view. Then the database will be deleted as well.
  736. #[tracing::instrument(level = "debug", skip(self, view_id), err)]
  737. pub async fn delete_trash(&self, view_id: &str) -> FlowyResult<()> {
  738. let view = self.with_folder(|| None, |folder| folder.views.get_view(view_id));
  739. self.with_folder(
  740. || (),
  741. |folder| {
  742. folder.delete_trash(vec![view_id.to_string()]);
  743. folder.views.delete_views(vec![view_id]);
  744. },
  745. );
  746. if let Some(view) = view {
  747. if let Ok(handler) = self.get_handler(&view.layout) {
  748. handler.delete_view(view_id).await?;
  749. }
  750. }
  751. Ok(())
  752. }
  753. pub(crate) async fn import(&self, import_data: ImportParams) -> FlowyResult<View> {
  754. if import_data.data.is_none() && import_data.file_path.is_none() {
  755. return Err(FlowyError::new(
  756. ErrorCode::InvalidParams,
  757. "data or file_path is required",
  758. ));
  759. }
  760. let handler = self.get_handler(&import_data.view_layout)?;
  761. let view_id = gen_view_id().to_string();
  762. let uid = self.user.user_id()?;
  763. if let Some(data) = import_data.data {
  764. handler
  765. .import_from_bytes(
  766. uid,
  767. &view_id,
  768. &import_data.name,
  769. import_data.import_type,
  770. data,
  771. )
  772. .await?;
  773. }
  774. if let Some(file_path) = import_data.file_path {
  775. handler
  776. .import_from_file_path(&view_id, &import_data.name, file_path)
  777. .await?;
  778. }
  779. let params = CreateViewParams {
  780. parent_view_id: import_data.parent_view_id,
  781. name: import_data.name,
  782. desc: "".to_string(),
  783. layout: import_data.view_layout.clone().into(),
  784. initial_data: vec![],
  785. view_id,
  786. meta: Default::default(),
  787. set_as_current: false,
  788. index: None,
  789. };
  790. let view = create_view(params, import_data.view_layout);
  791. self.with_folder(
  792. || (),
  793. |folder| {
  794. folder.insert_view(view.clone(), None);
  795. },
  796. );
  797. notify_parent_view_did_change(self.mutex_folder.clone(), vec![view.parent_view_id.clone()]);
  798. Ok(view)
  799. }
  800. /// Update the view with the provided view_id using the specified function.
  801. async fn update_view<F>(&self, view_id: &str, f: F) -> FlowyResult<()>
  802. where
  803. F: FnOnce(ViewUpdate) -> Option<View>,
  804. {
  805. let value = self.with_folder(
  806. || None,
  807. |folder| {
  808. let old_view = folder.views.get_view(view_id);
  809. let new_view = folder.views.update_view(view_id, f);
  810. Some((old_view, new_view))
  811. },
  812. );
  813. if let Some((Some(old_view), Some(new_view))) = value {
  814. if let Ok(handler) = self.get_handler(&old_view.layout) {
  815. handler.did_update_view(&old_view, &new_view).await?;
  816. }
  817. }
  818. if let Ok(view_pb) = self.get_view(view_id).await {
  819. send_notification(&view_pb.id, FolderNotification::DidUpdateView)
  820. .payload(view_pb)
  821. .send();
  822. }
  823. Ok(())
  824. }
  825. /// Returns a handler that implements the [FolderOperationHandler] trait
  826. fn get_handler(
  827. &self,
  828. view_layout: &ViewLayout,
  829. ) -> FlowyResult<Arc<dyn FolderOperationHandler + Send + Sync>> {
  830. match self.operation_handlers.get(view_layout) {
  831. None => Err(FlowyError::internal().with_context(format!(
  832. "Get data processor failed. Unknown layout type: {:?}",
  833. view_layout
  834. ))),
  835. Some(processor) => Ok(processor.clone()),
  836. }
  837. }
  838. /// Returns the relation of the view. The relation is a tuple of (is_workspace, parent_view_id,
  839. /// child_view_ids). If the view is a workspace, then the parent_view_id is the workspace id.
  840. /// Otherwise, the parent_view_id is the parent view id of the view. The child_view_ids is the
  841. /// child view ids of the view.
  842. async fn get_view_relation(&self, view_id: &str) -> Option<(bool, String, Vec<String>)> {
  843. self.with_folder(
  844. || None,
  845. |folder| {
  846. let view = folder.views.get_view(view_id)?;
  847. match folder.views.get_view(&view.parent_view_id) {
  848. None => folder.get_current_workspace().map(|workspace| {
  849. (
  850. true,
  851. workspace.id,
  852. workspace
  853. .child_views
  854. .items
  855. .into_iter()
  856. .map(|view| view.id)
  857. .collect::<Vec<String>>(),
  858. )
  859. }),
  860. Some(parent_view) => Some((
  861. false,
  862. parent_view.id.clone(),
  863. parent_view
  864. .children
  865. .items
  866. .clone()
  867. .into_iter()
  868. .map(|view| view.id)
  869. .collect::<Vec<String>>(),
  870. )),
  871. }
  872. },
  873. )
  874. }
  875. pub async fn get_folder_snapshots(
  876. &self,
  877. workspace_id: &str,
  878. limit: usize,
  879. ) -> FlowyResult<Vec<FolderSnapshotPB>> {
  880. let snapshots = self
  881. .cloud_service
  882. .get_folder_snapshots(workspace_id, limit)
  883. .await?
  884. .into_iter()
  885. .map(|snapshot| FolderSnapshotPB {
  886. snapshot_id: snapshot.snapshot_id,
  887. snapshot_desc: "".to_string(),
  888. created_at: snapshot.created_at,
  889. data: snapshot.data,
  890. })
  891. .collect::<Vec<_>>();
  892. Ok(snapshots)
  893. }
  894. /// Only expose this method for testing
  895. #[cfg(debug_assertions)]
  896. pub fn get_mutex_folder(&self) -> &Arc<MutexFolder> {
  897. &self.mutex_folder
  898. }
  899. /// Only expose this method for testing
  900. #[cfg(debug_assertions)]
  901. pub fn get_cloud_service(&self) -> &Arc<dyn FolderCloudService> {
  902. &self.cloud_service
  903. }
  904. }
  905. /// Listen on the [ViewChange] after create/delete/update events happened
  906. fn subscribe_folder_view_changed(
  907. mut rx: ViewChangeReceiver,
  908. weak_mutex_folder: &Weak<MutexFolder>,
  909. ) {
  910. let weak_mutex_folder = weak_mutex_folder.clone();
  911. tokio::spawn(async move {
  912. while let Ok(value) = rx.recv().await {
  913. if let Some(folder) = weak_mutex_folder.upgrade() {
  914. tracing::trace!("Did receive view change: {:?}", value);
  915. match value {
  916. ViewChange::DidCreateView { view } => {
  917. notify_child_views_changed(
  918. view_pb_without_child_views(Arc::new(view.clone())),
  919. ChildViewChangeReason::DidCreateView,
  920. );
  921. notify_parent_view_did_change(folder.clone(), vec![view.parent_view_id]);
  922. },
  923. ViewChange::DidDeleteView { views } => {
  924. for view in views {
  925. notify_child_views_changed(
  926. view_pb_without_child_views(view),
  927. ChildViewChangeReason::DidDeleteView,
  928. );
  929. }
  930. },
  931. ViewChange::DidUpdate { view } => {
  932. notify_child_views_changed(
  933. view_pb_without_child_views(Arc::new(view.clone())),
  934. ChildViewChangeReason::DidUpdateView,
  935. );
  936. notify_parent_view_did_change(folder.clone(), vec![view.parent_view_id]);
  937. },
  938. };
  939. }
  940. }
  941. });
  942. }
  943. fn subscribe_folder_snapshot_state_changed(
  944. workspace_id: String,
  945. weak_mutex_folder: &Weak<MutexFolder>,
  946. ) {
  947. let weak_mutex_folder = weak_mutex_folder.clone();
  948. tokio::spawn(async move {
  949. if let Some(mutex_folder) = weak_mutex_folder.upgrade() {
  950. let stream = mutex_folder
  951. .lock()
  952. .as_ref()
  953. .map(|folder| folder.subscribe_snapshot_state());
  954. if let Some(mut state_stream) = stream {
  955. while let Some(snapshot_state) = state_stream.next().await {
  956. if let Some(new_snapshot_id) = snapshot_state.snapshot_id() {
  957. tracing::debug!("Did create folder remote snapshot: {}", new_snapshot_id);
  958. send_notification(
  959. &workspace_id,
  960. FolderNotification::DidUpdateFolderSnapshotState,
  961. )
  962. .payload(FolderSnapshotStatePB { new_snapshot_id })
  963. .send();
  964. }
  965. }
  966. }
  967. }
  968. });
  969. }
  970. fn subscribe_folder_sync_state_changed(
  971. workspace_id: String,
  972. mut folder_sync_state_rx: WatchStream<SyncState>,
  973. _weak_mutex_folder: &Weak<MutexFolder>,
  974. ) {
  975. tokio::spawn(async move {
  976. while let Some(state) = folder_sync_state_rx.next().await {
  977. send_notification(&workspace_id, FolderNotification::DidUpdateFolderSyncUpdate)
  978. .payload(FolderSyncStatePB::from(state))
  979. .send();
  980. }
  981. });
  982. }
  983. /// Listen on the [TrashChange]s and notify the frontend some views were changed.
  984. fn subscribe_folder_trash_changed(
  985. mut rx: TrashChangeReceiver,
  986. weak_mutex_folder: &Weak<MutexFolder>,
  987. ) {
  988. let weak_mutex_folder = weak_mutex_folder.clone();
  989. tokio::spawn(async move {
  990. while let Ok(value) = rx.recv().await {
  991. if let Some(folder) = weak_mutex_folder.upgrade() {
  992. let mut unique_ids = HashSet::new();
  993. tracing::trace!("Did receive trash change: {:?}", value);
  994. let ids = match value {
  995. TrashChange::DidCreateTrash { ids } => ids,
  996. TrashChange::DidDeleteTrash { ids } => ids,
  997. };
  998. if let Some(folder) = folder.lock().as_ref() {
  999. let views = folder.views.get_views(&ids);
  1000. for view in views {
  1001. unique_ids.insert(view.parent_view_id.clone());
  1002. }
  1003. let repeated_trash: RepeatedTrashPB = folder.get_all_trash().into();
  1004. send_notification("trash", FolderNotification::DidUpdateTrash)
  1005. .payload(repeated_trash)
  1006. .send();
  1007. }
  1008. let parent_view_ids = unique_ids.into_iter().collect();
  1009. notify_parent_view_did_change(folder.clone(), parent_view_ids);
  1010. }
  1011. }
  1012. });
  1013. }
  1014. /// Return the views that belong to the workspace. The views are filtered by the trash.
  1015. fn get_workspace_view_pbs(workspace_id: &str, folder: &Folder) -> Vec<ViewPB> {
  1016. let trash_ids = folder
  1017. .get_all_trash()
  1018. .into_iter()
  1019. .map(|trash| trash.id)
  1020. .collect::<Vec<String>>();
  1021. let mut views = folder.get_workspace_views(workspace_id);
  1022. views.retain(|view| !trash_ids.contains(&view.id));
  1023. views
  1024. .into_iter()
  1025. .map(|view| {
  1026. // Get child views
  1027. let child_views = folder
  1028. .views
  1029. .get_views_belong_to(&view.id)
  1030. .into_iter()
  1031. .collect();
  1032. view_pb_with_child_views(view, child_views)
  1033. })
  1034. .collect()
  1035. }
  1036. fn notify_did_update_workspace(workspace_id: &str, folder: &Folder) {
  1037. let repeated_view: RepeatedViewPB = get_workspace_view_pbs(workspace_id, folder).into();
  1038. tracing::trace!("Did update workspace views: {:?}", repeated_view);
  1039. send_notification(workspace_id, FolderNotification::DidUpdateWorkspaceViews)
  1040. .payload(repeated_view)
  1041. .send();
  1042. }
  1043. /// Notify the the list of parent view ids that its child views were changed.
  1044. #[tracing::instrument(level = "debug", skip(folder, parent_view_ids))]
  1045. fn notify_parent_view_did_change<T: AsRef<str>>(
  1046. folder: Arc<MutexFolder>,
  1047. parent_view_ids: Vec<T>,
  1048. ) -> Option<()> {
  1049. let folder = folder.lock();
  1050. let folder = folder.as_ref()?;
  1051. let workspace_id = folder.get_current_workspace_id()?;
  1052. let trash_ids = folder
  1053. .get_all_trash()
  1054. .into_iter()
  1055. .map(|trash| trash.id)
  1056. .collect::<Vec<String>>();
  1057. for parent_view_id in parent_view_ids {
  1058. let parent_view_id = parent_view_id.as_ref();
  1059. // if the view's parent id equal to workspace id. Then it will fetch the current
  1060. // workspace views. Because the the workspace is not a view stored in the views map.
  1061. if parent_view_id == workspace_id {
  1062. notify_did_update_workspace(&workspace_id, folder)
  1063. } else {
  1064. // Parent view can contain a list of child views. Currently, only get the first level
  1065. // child views.
  1066. let parent_view = folder.views.get_view(parent_view_id)?;
  1067. let mut child_views = folder.views.get_views_belong_to(parent_view_id);
  1068. child_views.retain(|view| !trash_ids.contains(&view.id));
  1069. event!(Level::DEBUG, child_views_count = child_views.len());
  1070. // Post the notification
  1071. let parent_view_pb = view_pb_with_child_views(parent_view, child_views);
  1072. send_notification(parent_view_id, FolderNotification::DidUpdateView)
  1073. .payload(parent_view_pb)
  1074. .send();
  1075. }
  1076. }
  1077. None
  1078. }
  1079. pub enum ChildViewChangeReason {
  1080. DidCreateView,
  1081. DidDeleteView,
  1082. DidUpdateView,
  1083. }
  1084. /// Notify the the list of parent view ids that its child views were changed.
  1085. #[tracing::instrument(level = "debug", skip_all)]
  1086. fn notify_child_views_changed(view_pb: ViewPB, reason: ChildViewChangeReason) {
  1087. let parent_view_id = view_pb.parent_view_id.clone();
  1088. let mut payload = ChildViewUpdatePB {
  1089. parent_view_id: view_pb.parent_view_id.clone(),
  1090. ..Default::default()
  1091. };
  1092. match reason {
  1093. ChildViewChangeReason::DidCreateView => {
  1094. payload.create_child_views.push(view_pb);
  1095. },
  1096. ChildViewChangeReason::DidDeleteView => {
  1097. payload.delete_child_views.push(view_pb.id);
  1098. },
  1099. ChildViewChangeReason::DidUpdateView => {
  1100. payload.update_child_views.push(view_pb);
  1101. },
  1102. }
  1103. send_notification(&parent_view_id, FolderNotification::DidUpdateChildViews)
  1104. .payload(payload)
  1105. .send();
  1106. }
  1107. fn folder_not_init_error() -> FlowyError {
  1108. FlowyError::internal().with_context("Folder not initialized")
  1109. }
  1110. #[derive(Clone, Default)]
  1111. pub struct MutexFolder(Arc<Mutex<Option<Folder>>>);
  1112. impl Deref for MutexFolder {
  1113. type Target = Arc<Mutex<Option<Folder>>>;
  1114. fn deref(&self) -> &Self::Target {
  1115. &self.0
  1116. }
  1117. }
  1118. unsafe impl Sync for MutexFolder {}
  1119. unsafe impl Send for MutexFolder {}
  1120. pub enum FolderInitializeDataSource {
  1121. /// It means using the data stored on local disk to initialize the folder
  1122. LocalDisk { create_if_not_exist: bool },
  1123. /// If there is no data stored on local disk, we will use the data from the server to initialize the folder
  1124. Cloud(CollabRawData),
  1125. /// If the user is new, we use the [DefaultFolderBuilder] to create the default folder.
  1126. FolderData(FolderData),
  1127. }
  1128. fn is_exist_in_local_disk(user: &Arc<dyn FolderUser>, doc_id: &str) -> FlowyResult<bool> {
  1129. let uid = user.user_id()?;
  1130. if let Some(collab_db) = user.collab_db(uid)?.upgrade() {
  1131. let read_txn = collab_db.read_txn();
  1132. Ok(read_txn.is_exist(uid, doc_id))
  1133. } else {
  1134. Ok(false)
  1135. }
  1136. }
  1137. fn workspace_data_not_sync_error(uid: i64, workspace_id: &str) -> FlowyError {
  1138. FlowyError::from(ErrorCode::WorkspaceDataNotSync).with_payload(UserFolderPB {
  1139. uid,
  1140. workspace_id: workspace_id.to_string(),
  1141. })
  1142. }