cell_data_operation.rs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. use crate::entities::FieldType;
  2. use crate::services::field::*;
  3. use bytes::Bytes;
  4. use flowy_error::{internal_error, ErrorCode, FlowyError, FlowyResult};
  5. use flowy_grid_data_model::revision::{CellRevision, FieldRevision};
  6. use serde::{Deserialize, Serialize};
  7. use std::fmt::Formatter;
  8. use std::str::FromStr;
  9. pub trait CellDataOperation<D, F> {
  10. fn decode_cell_data<T>(
  11. &self,
  12. encoded_data: T,
  13. decoded_field_type: &FieldType,
  14. field_rev: &FieldRevision,
  15. ) -> FlowyResult<DecodedCellData>
  16. where
  17. T: Into<D>;
  18. fn apply_filter<T>(&self, encoded_data: T, filter: &F) -> bool
  19. where
  20. T: Into<D>;
  21. fn apply_changeset<C: Into<CellContentChangeset>>(
  22. &self,
  23. changeset: C,
  24. cell_rev: Option<CellRevision>,
  25. ) -> FlowyResult<String>;
  26. }
  27. #[derive(Debug)]
  28. pub struct CellContentChangeset(pub String);
  29. impl std::fmt::Display for CellContentChangeset {
  30. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  31. write!(f, "{}", &self.0)
  32. }
  33. }
  34. impl<T: AsRef<str>> std::convert::From<T> for CellContentChangeset {
  35. fn from(s: T) -> Self {
  36. let s = s.as_ref().to_owned();
  37. CellContentChangeset(s)
  38. }
  39. }
  40. impl std::ops::Deref for CellContentChangeset {
  41. type Target = str;
  42. fn deref(&self) -> &Self::Target {
  43. &self.0
  44. }
  45. }
  46. #[derive(Debug, Serialize, Deserialize)]
  47. pub struct TypeOptionCellData {
  48. pub data: String,
  49. pub field_type: FieldType,
  50. }
  51. impl std::str::FromStr for TypeOptionCellData {
  52. type Err = FlowyError;
  53. fn from_str(s: &str) -> Result<Self, Self::Err> {
  54. let type_option_cell_data: TypeOptionCellData = serde_json::from_str(s)?;
  55. Ok(type_option_cell_data)
  56. }
  57. }
  58. impl std::convert::TryInto<TypeOptionCellData> for String {
  59. type Error = FlowyError;
  60. fn try_into(self) -> Result<TypeOptionCellData, Self::Error> {
  61. TypeOptionCellData::from_str(&self)
  62. }
  63. }
  64. impl std::convert::TryFrom<&CellRevision> for TypeOptionCellData {
  65. type Error = FlowyError;
  66. fn try_from(value: &CellRevision) -> Result<Self, Self::Error> {
  67. Self::from_str(&value.data)
  68. }
  69. }
  70. impl TypeOptionCellData {
  71. pub fn new<T: ToString>(data: T, field_type: FieldType) -> Self {
  72. TypeOptionCellData {
  73. data: data.to_string(),
  74. field_type,
  75. }
  76. }
  77. pub fn json(&self) -> String {
  78. serde_json::to_string(self).unwrap_or_else(|_| "".to_owned())
  79. }
  80. pub fn is_number(&self) -> bool {
  81. self.field_type == FieldType::Number
  82. }
  83. pub fn is_text(&self) -> bool {
  84. self.field_type == FieldType::RichText
  85. }
  86. pub fn is_checkbox(&self) -> bool {
  87. self.field_type == FieldType::Checkbox
  88. }
  89. pub fn is_date(&self) -> bool {
  90. self.field_type == FieldType::DateTime
  91. }
  92. pub fn is_single_select(&self) -> bool {
  93. self.field_type == FieldType::SingleSelect
  94. }
  95. pub fn is_multi_select(&self) -> bool {
  96. self.field_type == FieldType::MultiSelect
  97. }
  98. pub fn is_select_option(&self) -> bool {
  99. self.field_type == FieldType::MultiSelect || self.field_type == FieldType::SingleSelect
  100. }
  101. }
  102. /// The changeset will be deserialized into specific data base on the FieldType.
  103. /// For example, it's String on FieldType::RichText, and SelectOptionChangeset on FieldType::SingleSelect
  104. pub fn apply_cell_data_changeset<C: Into<CellContentChangeset>, T: AsRef<FieldRevision>>(
  105. changeset: C,
  106. cell_rev: Option<CellRevision>,
  107. field_rev: T,
  108. ) -> Result<String, FlowyError> {
  109. let field_rev = field_rev.as_ref();
  110. let field_type = field_rev.field_type_rev.into();
  111. let s = match field_type {
  112. FieldType::RichText => RichTextTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  113. FieldType::Number => NumberTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  114. FieldType::DateTime => DateTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  115. FieldType::SingleSelect => SingleSelectTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  116. FieldType::MultiSelect => MultiSelectTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  117. FieldType::Checkbox => CheckboxTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  118. FieldType::URL => URLTypeOption::from(field_rev).apply_changeset(changeset, cell_rev),
  119. }?;
  120. Ok(TypeOptionCellData::new(s, field_type).json())
  121. }
  122. pub fn decode_cell_data<T: TryInto<TypeOptionCellData>>(data: T, field_rev: &FieldRevision) -> DecodedCellData {
  123. if let Ok(type_option_cell_data) = data.try_into() {
  124. let TypeOptionCellData { data, field_type } = type_option_cell_data;
  125. let to_field_type = field_rev.field_type_rev.into();
  126. match try_decode_cell_data(data, field_rev, &field_type, &to_field_type) {
  127. Ok(cell_data) => cell_data,
  128. Err(e) => {
  129. tracing::error!("Decode cell data failed, {:?}", e);
  130. DecodedCellData::default()
  131. }
  132. }
  133. } else {
  134. tracing::error!("Decode type option data failed");
  135. DecodedCellData::default()
  136. }
  137. }
  138. pub fn try_decode_cell_data(
  139. encoded_data: String,
  140. field_rev: &FieldRevision,
  141. s_field_type: &FieldType,
  142. t_field_type: &FieldType,
  143. ) -> FlowyResult<DecodedCellData> {
  144. let get_cell_data = || {
  145. let data = match t_field_type {
  146. FieldType::RichText => field_rev
  147. .get_type_option_entry::<RichTextTypeOption, _>(t_field_type)?
  148. .decode_cell_data(encoded_data, s_field_type, field_rev),
  149. FieldType::Number => field_rev
  150. .get_type_option_entry::<NumberTypeOption, _>(t_field_type)?
  151. .decode_cell_data(encoded_data, s_field_type, field_rev),
  152. FieldType::DateTime => field_rev
  153. .get_type_option_entry::<DateTypeOption, _>(t_field_type)?
  154. .decode_cell_data(encoded_data, s_field_type, field_rev),
  155. FieldType::SingleSelect => field_rev
  156. .get_type_option_entry::<SingleSelectTypeOption, _>(t_field_type)?
  157. .decode_cell_data(encoded_data, s_field_type, field_rev),
  158. FieldType::MultiSelect => field_rev
  159. .get_type_option_entry::<MultiSelectTypeOption, _>(t_field_type)?
  160. .decode_cell_data(encoded_data, s_field_type, field_rev),
  161. FieldType::Checkbox => field_rev
  162. .get_type_option_entry::<CheckboxTypeOption, _>(t_field_type)?
  163. .decode_cell_data(encoded_data, s_field_type, field_rev),
  164. FieldType::URL => field_rev
  165. .get_type_option_entry::<URLTypeOption, _>(t_field_type)?
  166. .decode_cell_data(encoded_data, s_field_type, field_rev),
  167. };
  168. Some(data)
  169. };
  170. match get_cell_data() {
  171. Some(Ok(data)) => Ok(data),
  172. Some(Err(err)) => {
  173. tracing::error!("{:?}", err);
  174. Ok(DecodedCellData::default())
  175. }
  176. None => Ok(DecodedCellData::default()),
  177. }
  178. }
  179. pub(crate) struct EncodedCellData<T>(pub Option<T>);
  180. impl<T> EncodedCellData<T> {
  181. pub fn try_into_inner(self) -> FlowyResult<T> {
  182. match self.0 {
  183. None => Err(ErrorCode::InvalidData.into()),
  184. Some(data) => Ok(data),
  185. }
  186. }
  187. }
  188. impl<T> std::convert::From<String> for EncodedCellData<T>
  189. where
  190. T: FromStr<Err = FlowyError>,
  191. {
  192. fn from(s: String) -> Self {
  193. match T::from_str(&s) {
  194. Ok(inner) => EncodedCellData(Some(inner)),
  195. Err(e) => {
  196. tracing::error!("Deserialize Cell Data failed: {}", e);
  197. EncodedCellData(None)
  198. }
  199. }
  200. }
  201. }
  202. /// The data is encoded by protobuf or utf8. You should choose the corresponding decode struct to parse it.
  203. ///
  204. /// For example:
  205. ///
  206. /// * Use DateCellData to parse the data when the FieldType is Date.
  207. /// * Use URLCellData to parse the data when the FieldType is URL.
  208. /// * Use String to parse the data when the FieldType is RichText, Number, or Checkbox.
  209. /// * Check out the implementation of CellDataOperation trait for more information.
  210. #[derive(Default)]
  211. pub struct DecodedCellData {
  212. pub data: Vec<u8>,
  213. }
  214. impl DecodedCellData {
  215. pub fn new<T: AsRef<[u8]>>(data: T) -> Self {
  216. Self {
  217. data: data.as_ref().to_vec(),
  218. }
  219. }
  220. pub fn try_from_bytes<T: TryInto<Bytes>>(bytes: T) -> FlowyResult<Self>
  221. where
  222. <T as TryInto<Bytes>>::Error: std::fmt::Debug,
  223. {
  224. let bytes = bytes.try_into().map_err(internal_error)?;
  225. Ok(Self { data: bytes.to_vec() })
  226. }
  227. pub fn parse<'a, T: TryFrom<&'a [u8]>>(&'a self) -> FlowyResult<T>
  228. where
  229. <T as TryFrom<&'a [u8]>>::Error: std::fmt::Debug,
  230. {
  231. T::try_from(self.data.as_ref()).map_err(internal_error)
  232. }
  233. }
  234. impl ToString for DecodedCellData {
  235. fn to_string(&self) -> String {
  236. match String::from_utf8(self.data.clone()) {
  237. Ok(s) => s,
  238. Err(e) => {
  239. tracing::error!("DecodedCellData to string failed: {:?}", e);
  240. "".to_string()
  241. }
  242. }
  243. }
  244. }