task_info.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. collections::HashMap,
  20. fmt,
  21. path::{Path, PathBuf},
  22. str::FromStr,
  23. };
  24. use darkfi_serial::{async_trait, SerialDecodable, SerialEncodable};
  25. use log::debug;
  26. use tinyjson::JsonValue;
  27. use darkfi::{
  28. util::{
  29. file::{load_json_file, save_json_file},
  30. time::Timestamp,
  31. },
  32. Error,
  33. };
  34. use crate::{
  35. error::{TaudError, TaudResult},
  36. month_tasks::MonthTasks,
  37. util::gen_id,
  38. };
  39. pub enum State {
  40. Open,
  41. Start,
  42. Pause,
  43. Stop,
  44. }
  45. impl State {
  46. pub const fn is_start(&self) -> bool {
  47. matches!(*self, Self::Start)
  48. }
  49. pub const fn is_pause(&self) -> bool {
  50. matches!(*self, Self::Pause)
  51. }
  52. pub const fn is_stop(&self) -> bool {
  53. matches!(*self, Self::Stop)
  54. }
  55. }
  56. impl fmt::Display for State {
  57. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  58. match self {
  59. State::Open => write!(f, "open"),
  60. State::Start => write!(f, "start"),
  61. State::Stop => write!(f, "stop"),
  62. State::Pause => write!(f, "pause"),
  63. }
  64. }
  65. }
  66. impl FromStr for State {
  67. type Err = Error;
  68. fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
  69. let result = match s.to_lowercase().as_str() {
  70. "open" => State::Open,
  71. "stop" => State::Stop,
  72. "start" => State::Start,
  73. "pause" => State::Pause,
  74. _ => return Err(Error::ParseFailed("unable to parse state")),
  75. };
  76. Ok(result)
  77. }
  78. }
  79. #[derive(Clone, Debug, SerialEncodable, SerialDecodable, PartialEq, Eq)]
  80. pub struct TaskEvent {
  81. pub action: String,
  82. pub author: String,
  83. pub content: String,
  84. pub timestamp: Timestamp,
  85. }
  86. impl std::fmt::Display for TaskEvent {
  87. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  88. write!(f, "action: {}, timestamp: {}", self.action, self.timestamp)
  89. }
  90. }
  91. impl Default for TaskEvent {
  92. fn default() -> Self {
  93. Self {
  94. action: State::Open.to_string(),
  95. author: "".to_string(),
  96. content: "".to_string(),
  97. timestamp: Timestamp::current_time(),
  98. }
  99. }
  100. }
  101. impl TaskEvent {
  102. pub fn new(action: String, author: String, content: String) -> Self {
  103. Self { action, author, content, timestamp: Timestamp::current_time() }
  104. }
  105. }
  106. impl From<TaskEvent> for JsonValue {
  107. fn from(task_event: TaskEvent) -> JsonValue {
  108. JsonValue::Object(HashMap::from([
  109. ("action".to_string(), JsonValue::String(task_event.action.clone())),
  110. ("author".to_string(), JsonValue::String(task_event.author.clone())),
  111. ("content".to_string(), JsonValue::String(task_event.content.clone())),
  112. ("timestamp".to_string(), JsonValue::String(task_event.timestamp.inner().to_string())),
  113. ]))
  114. }
  115. }
  116. impl From<&JsonValue> for TaskEvent {
  117. fn from(value: &JsonValue) -> TaskEvent {
  118. let map = value.get::<HashMap<String, JsonValue>>().unwrap();
  119. TaskEvent {
  120. action: map["action"].get::<String>().unwrap().clone(),
  121. author: map["author"].get::<String>().unwrap().clone(),
  122. content: map["content"].get::<String>().unwrap().clone(),
  123. timestamp: Timestamp::from_u64(
  124. map["timestamp"].get::<String>().unwrap().parse::<u64>().unwrap(),
  125. ),
  126. }
  127. }
  128. }
  129. #[derive(Clone, Debug, SerialDecodable, SerialEncodable, PartialEq, Eq)]
  130. pub struct Comment {
  131. content: String,
  132. author: String,
  133. timestamp: Timestamp,
  134. }
  135. impl std::fmt::Display for Comment {
  136. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  137. write!(f, "{} author: {}, content: {} ", self.timestamp, self.author, self.content)
  138. }
  139. }
  140. impl From<Comment> for JsonValue {
  141. fn from(comment: Comment) -> JsonValue {
  142. JsonValue::Object(HashMap::from([
  143. ("content".to_string(), JsonValue::String(comment.content.clone())),
  144. ("author".to_string(), JsonValue::String(comment.author.clone())),
  145. ("timestamp".to_string(), JsonValue::String(comment.timestamp.inner().to_string())),
  146. ]))
  147. }
  148. }
  149. impl From<JsonValue> for Comment {
  150. fn from(value: JsonValue) -> Comment {
  151. let map = value.get::<HashMap<String, JsonValue>>().unwrap();
  152. Comment {
  153. content: map["content"].get::<String>().unwrap().clone(),
  154. author: map["author"].get::<String>().unwrap().clone(),
  155. timestamp: Timestamp::from_u64(
  156. map["timestamp"].get::<String>().unwrap().parse::<u64>().unwrap(),
  157. ),
  158. }
  159. }
  160. }
  161. impl Comment {
  162. pub fn new(content: &str, author: &str) -> Self {
  163. Self {
  164. content: content.into(),
  165. author: author.into(),
  166. timestamp: Timestamp::current_time(),
  167. }
  168. }
  169. }
  170. #[derive(Clone, Debug, SerialEncodable, SerialDecodable, PartialEq)]
  171. pub struct TaskInfo {
  172. pub ref_id: String,
  173. pub workspace: String,
  174. pub title: String,
  175. pub tags: Vec<String>,
  176. pub desc: String,
  177. pub owner: String,
  178. pub assign: Vec<String>,
  179. pub project: Vec<String>,
  180. pub due: Option<Timestamp>,
  181. pub rank: Option<f32>,
  182. pub created_at: Timestamp,
  183. pub state: String,
  184. pub events: Vec<TaskEvent>,
  185. pub comments: Vec<Comment>,
  186. }
  187. impl From<&TaskInfo> for JsonValue {
  188. fn from(task: &TaskInfo) -> JsonValue {
  189. let ref_id = JsonValue::String(task.ref_id.clone());
  190. let workspace = JsonValue::String(task.workspace.clone());
  191. let title = JsonValue::String(task.title.clone());
  192. let tags: Vec<JsonValue> = task.tags.iter().map(|x| JsonValue::String(x.clone())).collect();
  193. let desc = JsonValue::String(task.desc.clone());
  194. let owner = JsonValue::String(task.owner.clone());
  195. let assign: Vec<JsonValue> =
  196. task.assign.iter().map(|x| JsonValue::String(x.clone())).collect();
  197. let project: Vec<JsonValue> =
  198. task.project.iter().map(|x| JsonValue::String(x.clone())).collect();
  199. let due = if let Some(ts) = task.due {
  200. JsonValue::String(ts.inner().to_string())
  201. } else {
  202. JsonValue::Null
  203. };
  204. let rank = if let Some(rank) = task.rank {
  205. JsonValue::Number(rank.into())
  206. } else {
  207. JsonValue::Null
  208. };
  209. let created_at = JsonValue::String(task.created_at.inner().to_string());
  210. let state = JsonValue::String(task.state.clone());
  211. let events: Vec<JsonValue> = task.events.iter().map(|x| x.clone().into()).collect();
  212. let comments: Vec<JsonValue> = task.comments.iter().map(|x| x.clone().into()).collect();
  213. JsonValue::Object(HashMap::from([
  214. ("ref_id".to_string(), ref_id),
  215. ("workspace".to_string(), workspace),
  216. ("title".to_string(), title),
  217. ("tags".to_string(), JsonValue::Array(tags)),
  218. ("desc".to_string(), desc),
  219. ("owner".to_string(), owner),
  220. ("assign".to_string(), JsonValue::Array(assign)),
  221. ("project".to_string(), JsonValue::Array(project)),
  222. ("due".to_string(), due),
  223. ("rank".to_string(), rank),
  224. ("created_at".to_string(), created_at),
  225. ("state".to_string(), state),
  226. ("events".to_string(), JsonValue::Array(events)),
  227. ("comments".to_string(), JsonValue::Array(comments)),
  228. ]))
  229. }
  230. }
  231. impl From<JsonValue> for TaskInfo {
  232. fn from(value: JsonValue) -> TaskInfo {
  233. let tags = value["tags"].get::<Vec<JsonValue>>().unwrap();
  234. let assign = value["assign"].get::<Vec<JsonValue>>().unwrap();
  235. let project = value["project"].get::<Vec<JsonValue>>().unwrap();
  236. let events = value["events"].get::<Vec<JsonValue>>().unwrap();
  237. let comments = value["comments"].get::<Vec<JsonValue>>().unwrap();
  238. let due = {
  239. if value["due"].is_null() {
  240. None
  241. } else {
  242. let u64_str = value["due"].get::<String>().unwrap();
  243. Some(Timestamp::from_u64(u64_str.parse::<u64>().unwrap()))
  244. }
  245. };
  246. let rank = {
  247. if value["rank"].is_null() {
  248. None
  249. } else {
  250. Some(*value["rank"].get::<f64>().unwrap() as f32)
  251. }
  252. };
  253. let created_at = {
  254. let u64_str = value["created_at"].get::<String>().unwrap();
  255. Timestamp::from_u64(u64_str.parse::<u64>().unwrap())
  256. };
  257. let events: Vec<TaskEvent> = events.iter().map(|x| x.into()).collect();
  258. let comments: Vec<Comment> = comments.iter().map(|x| (*x).clone().into()).collect();
  259. TaskInfo {
  260. ref_id: value["ref_id"].get::<String>().unwrap().clone(),
  261. workspace: value["workspace"].get::<String>().unwrap().clone(),
  262. title: value["title"].get::<String>().unwrap().clone(),
  263. tags: tags.iter().map(|x| x.get::<String>().unwrap().clone()).collect(),
  264. desc: value["desc"].get::<String>().unwrap().clone(),
  265. owner: value["owner"].get::<String>().unwrap().clone(),
  266. assign: assign.iter().map(|x| x.get::<String>().unwrap().clone()).collect(),
  267. project: project.iter().map(|x| x.get::<String>().unwrap().clone()).collect(),
  268. due,
  269. rank,
  270. created_at,
  271. state: value["state"].get::<String>().unwrap().clone(),
  272. events,
  273. comments,
  274. }
  275. }
  276. }
  277. impl TaskInfo {
  278. pub fn new(
  279. workspace: String,
  280. title: &str,
  281. desc: &str,
  282. owner: &str,
  283. due: Option<Timestamp>,
  284. rank: Option<f32>,
  285. created_at: Timestamp,
  286. ) -> TaudResult<Self> {
  287. // generate ref_id
  288. let ref_id = gen_id(30);
  289. if let Some(d) = &due {
  290. if *d < Timestamp::current_time() {
  291. return Err(TaudError::InvalidDueTime)
  292. }
  293. }
  294. Ok(Self {
  295. ref_id,
  296. workspace,
  297. title: title.into(),
  298. desc: desc.into(),
  299. owner: owner.into(),
  300. tags: vec![],
  301. assign: vec![],
  302. project: vec![],
  303. due,
  304. rank,
  305. created_at,
  306. state: "open".into(),
  307. comments: vec![],
  308. events: vec![],
  309. })
  310. }
  311. pub fn load(ref_id: &str, dataset_path: &Path) -> TaudResult<Self> {
  312. debug!(target: "tau", "TaskInfo::load()");
  313. let task = load_json_file(&Self::get_path(ref_id, dataset_path))?;
  314. Ok(task.into())
  315. }
  316. pub fn save(&self, dataset_path: &Path) -> TaudResult<()> {
  317. debug!(target: "tau", "TaskInfo::save()");
  318. save_json_file(&Self::get_path(&self.ref_id, dataset_path), &self.into(), true)
  319. .map_err(TaudError::Darkfi)?;
  320. if self.get_state() == "stop" {
  321. self.deactivate(dataset_path)?;
  322. } else {
  323. self.activate(dataset_path)?;
  324. }
  325. Ok(())
  326. }
  327. pub fn activate(&self, path: &Path) -> TaudResult<()> {
  328. debug!(target: "tau", "TaskInfo::activate()");
  329. let mut mt = MonthTasks::load_or_create(Some(&self.created_at), path)?;
  330. mt.add(&self.ref_id);
  331. mt.save(path)
  332. }
  333. pub fn deactivate(&self, path: &Path) -> TaudResult<()> {
  334. debug!(target: "tau", "TaskInfo::deactivate()");
  335. let mut mt = MonthTasks::load_or_create(Some(&self.created_at), path)?;
  336. mt.remove(&self.ref_id);
  337. mt.save(path)
  338. }
  339. pub fn get_state(&self) -> String {
  340. debug!(target: "tau", "TaskInfo::get_state()");
  341. self.state.clone()
  342. }
  343. pub fn get_path(ref_id: &str, dataset_path: &Path) -> PathBuf {
  344. debug!(target: "tau", "TaskInfo::get_path()");
  345. dataset_path.join("task").join(ref_id)
  346. }
  347. pub fn get_ref_id(&self) -> String {
  348. debug!(target: "tau", "TaskInfo::get_ref_id()");
  349. self.ref_id.clone()
  350. }
  351. pub fn set_title(&mut self, title: &str) {
  352. debug!(target: "tau", "TaskInfo::set_title()");
  353. self.title = title.into();
  354. }
  355. pub fn set_desc(&mut self, desc: &str) {
  356. debug!(target: "tau", "TaskInfo::set_desc()");
  357. self.desc = desc.into();
  358. }
  359. pub fn set_tags(&mut self, tags: &[String]) {
  360. debug!(target: "tau", "TaskInfo::set_tags()");
  361. for tag in tags.iter() {
  362. let stripped = &tag[1..];
  363. if tag.starts_with('+') && !self.tags.contains(&stripped.to_string()) {
  364. self.tags.push(stripped.to_string());
  365. }
  366. if tag.starts_with('-') {
  367. self.tags.retain(|tag| tag != stripped);
  368. }
  369. }
  370. }
  371. pub fn set_assign(&mut self, assigns: &[String]) {
  372. debug!(target: "tau", "TaskInfo::set_assign()");
  373. // self.assign = assigns.to_owned();
  374. for assign in assigns.iter() {
  375. let stripped = assign.split('@').collect::<Vec<&str>>()[1];
  376. if assign.starts_with('@') && !self.assign.contains(&stripped.to_string()) {
  377. self.assign.push(stripped.to_string());
  378. }
  379. if assign.starts_with("-@") {
  380. self.assign.retain(|assign| assign != stripped);
  381. }
  382. }
  383. }
  384. pub fn set_project(&mut self, projects: &[String]) {
  385. debug!(target: "tau", "TaskInfo::set_project()");
  386. projects.clone_into(&mut self.project);
  387. }
  388. pub fn set_comment(&mut self, c: Comment) {
  389. debug!(target: "tau", "TaskInfo::set_comment()");
  390. self.comments.push(c);
  391. }
  392. pub fn set_rank(&mut self, r: Option<f32>) {
  393. debug!(target: "tau", "TaskInfo::set_rank()");
  394. self.rank = r;
  395. }
  396. pub fn set_due(&mut self, d: Option<Timestamp>) {
  397. debug!(target: "tau", "TaskInfo::set_due()");
  398. self.due = d;
  399. }
  400. pub fn set_state(&mut self, state: &str) {
  401. debug!(target: "tau", "TaskInfo::set_state()");
  402. if self.get_state() == state {
  403. return
  404. }
  405. self.state = state.to_string();
  406. }
  407. }