module.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. use crate::{
  2. errors::DocError,
  3. services::{
  4. doc::{doc_controller::DocController, ClientEditDoc},
  5. server::construct_doc_server,
  6. ws::WsDocumentManager,
  7. },
  8. };
  9. use backend_service::config::ServerConfig;
  10. use flowy_database::ConnectionPool;
  11. use flowy_document_infra::entities::doc::{DocDelta, DocIdentifier};
  12. use std::sync::Arc;
  13. pub trait DocumentUser: Send + Sync {
  14. fn user_dir(&self) -> Result<String, DocError>;
  15. fn user_id(&self) -> Result<String, DocError>;
  16. fn token(&self) -> Result<String, DocError>;
  17. fn db_pool(&self) -> Result<Arc<ConnectionPool>, DocError>;
  18. }
  19. pub struct FlowyDocument {
  20. doc_ctrl: Arc<DocController>,
  21. user: Arc<dyn DocumentUser>,
  22. }
  23. impl FlowyDocument {
  24. pub fn new(
  25. user: Arc<dyn DocumentUser>,
  26. ws_manager: Arc<WsDocumentManager>,
  27. server_config: &ServerConfig,
  28. ) -> FlowyDocument {
  29. let server = construct_doc_server(server_config);
  30. let doc_ctrl = Arc::new(DocController::new(server.clone(), user.clone(), ws_manager.clone()));
  31. Self { doc_ctrl, user }
  32. }
  33. pub fn init(&self) -> Result<(), DocError> {
  34. let _ = self.doc_ctrl.init()?;
  35. Ok(())
  36. }
  37. pub fn delete(&self, params: DocIdentifier) -> Result<(), DocError> {
  38. let _ = self.doc_ctrl.delete(params)?;
  39. Ok(())
  40. }
  41. pub async fn open(&self, params: DocIdentifier) -> Result<Arc<ClientEditDoc>, DocError> {
  42. let edit_context = self.doc_ctrl.open(params, self.user.db_pool()?).await?;
  43. Ok(edit_context)
  44. }
  45. pub async fn close(&self, params: DocIdentifier) -> Result<(), DocError> {
  46. let _ = self.doc_ctrl.close(&params.doc_id)?;
  47. Ok(())
  48. }
  49. pub async fn read_document_data(
  50. &self,
  51. params: DocIdentifier,
  52. pool: Arc<ConnectionPool>,
  53. ) -> Result<DocDelta, DocError> {
  54. let edit_context = self.doc_ctrl.open(params, pool).await?;
  55. let delta = edit_context.delta().await?;
  56. Ok(delta)
  57. }
  58. pub async fn apply_doc_delta(&self, params: DocDelta) -> Result<DocDelta, DocError> {
  59. // workaround: compare the rust's delta with flutter's delta. Will be removed
  60. // very soon
  61. let doc = self
  62. .doc_ctrl
  63. .apply_local_delta(params.clone(), self.user.db_pool()?)
  64. .await?;
  65. Ok(doc)
  66. }
  67. }