task_info.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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. event_graph::gen_id,
  29. util::{
  30. file::{load_json_file, save_json_file},
  31. time::Timestamp,
  32. },
  33. Error,
  34. };
  35. use crate::{
  36. error::{TaudError, TaudResult},
  37. month_tasks::MonthTasks,
  38. util::find_free_id,
  39. };
  40. pub enum State {
  41. Open,
  42. Start,
  43. Pause,
  44. Stop,
  45. }
  46. impl State {
  47. pub const fn is_start(&self) -> bool {
  48. matches!(*self, Self::Start)
  49. }
  50. pub const fn is_pause(&self) -> bool {
  51. matches!(*self, Self::Pause)
  52. }
  53. pub const fn is_stop(&self) -> bool {
  54. matches!(*self, Self::Stop)
  55. }
  56. }
  57. impl fmt::Display for State {
  58. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  59. match self {
  60. State::Open => write!(f, "open"),
  61. State::Start => write!(f, "start"),
  62. State::Stop => write!(f, "stop"),
  63. State::Pause => write!(f, "pause"),
  64. }
  65. }
  66. }
  67. impl FromStr for State {
  68. type Err = Error;
  69. fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
  70. let result = match s.to_lowercase().as_str() {
  71. "open" => State::Open,
  72. "stop" => State::Stop,
  73. "start" => State::Start,
  74. "pause" => State::Pause,
  75. _ => return Err(Error::ParseFailed("unable to parse state")),
  76. };
  77. Ok(result)
  78. }
  79. }
  80. #[derive(Clone, Debug, SerialEncodable, SerialDecodable, PartialEq, Eq)]
  81. pub struct TaskEvent {
  82. pub action: String,
  83. pub author: String,
  84. pub content: String,
  85. pub timestamp: Timestamp,
  86. }
  87. impl std::fmt::Display for TaskEvent {
  88. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  89. write!(f, "action: {}, timestamp: {}", self.action, self.timestamp)
  90. }
  91. }
  92. impl Default for TaskEvent {
  93. fn default() -> Self {
  94. Self {
  95. action: State::Open.to_string(),
  96. author: "".to_string(),
  97. content: "".to_string(),
  98. timestamp: Timestamp::current_time(),
  99. }
  100. }
  101. }
  102. impl TaskEvent {
  103. pub fn new(action: String, author: String, content: String) -> Self {
  104. Self { action, author, content, timestamp: Timestamp::current_time() }
  105. }
  106. }
  107. impl From<TaskEvent> for JsonValue {
  108. fn from(task_event: TaskEvent) -> JsonValue {
  109. JsonValue::Object(HashMap::from([
  110. ("action".to_string(), JsonValue::String(task_event.action.clone())),
  111. ("author".to_string(), JsonValue::String(task_event.author.clone())),
  112. ("content".to_string(), JsonValue::String(task_event.content.clone())),
  113. ("timestamp".to_string(), JsonValue::String(task_event.timestamp.0.to_string())),
  114. ]))
  115. }
  116. }
  117. impl From<&JsonValue> for TaskEvent {
  118. fn from(value: &JsonValue) -> TaskEvent {
  119. let map = value.get::<HashMap<String, JsonValue>>().unwrap();
  120. TaskEvent {
  121. action: map["action"].get::<String>().unwrap().clone(),
  122. author: map["author"].get::<String>().unwrap().clone(),
  123. content: map["content"].get::<String>().unwrap().clone(),
  124. timestamp: Timestamp(map["timestamp"].get::<String>().unwrap().parse::<u64>().unwrap()),
  125. }
  126. }
  127. }
  128. #[derive(Clone, Debug, SerialDecodable, SerialEncodable, PartialEq, Eq)]
  129. pub struct Comment {
  130. content: String,
  131. author: String,
  132. timestamp: Timestamp,
  133. }
  134. impl std::fmt::Display for Comment {
  135. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  136. write!(f, "{} author: {}, content: {} ", self.timestamp, self.author, self.content)
  137. }
  138. }
  139. impl From<Comment> for JsonValue {
  140. fn from(comment: Comment) -> JsonValue {
  141. JsonValue::Object(HashMap::from([
  142. ("content".to_string(), JsonValue::String(comment.content.clone())),
  143. ("author".to_string(), JsonValue::String(comment.author.clone())),
  144. ("timestamp".to_string(), JsonValue::String(comment.timestamp.0.to_string())),
  145. ]))
  146. }
  147. }
  148. impl From<JsonValue> for Comment {
  149. fn from(value: JsonValue) -> Comment {
  150. let map = value.get::<HashMap<String, JsonValue>>().unwrap();
  151. Comment {
  152. content: map["content"].get::<String>().unwrap().clone(),
  153. author: map["author"].get::<String>().unwrap().clone(),
  154. timestamp: Timestamp(map["timestamp"].get::<String>().unwrap().parse::<u64>().unwrap()),
  155. }
  156. }
  157. }
  158. impl Comment {
  159. pub fn new(content: &str, author: &str) -> Self {
  160. Self {
  161. content: content.into(),
  162. author: author.into(),
  163. timestamp: Timestamp::current_time(),
  164. }
  165. }
  166. }
  167. #[derive(Clone, Debug, SerialEncodable, SerialDecodable, PartialEq)]
  168. pub struct TaskInfo {
  169. pub ref_id: String,
  170. pub workspace: String,
  171. pub id: u32,
  172. pub title: String,
  173. pub tags: Vec<String>,
  174. pub desc: String,
  175. pub owner: String,
  176. pub assign: Vec<String>,
  177. pub project: Vec<String>,
  178. pub due: Option<Timestamp>,
  179. pub rank: Option<f32>,
  180. pub created_at: Timestamp,
  181. pub state: String,
  182. pub events: Vec<TaskEvent>,
  183. pub comments: Vec<Comment>,
  184. }
  185. impl From<&TaskInfo> for JsonValue {
  186. fn from(task: &TaskInfo) -> JsonValue {
  187. let ref_id = JsonValue::String(task.ref_id.clone());
  188. let workspace = JsonValue::String(task.workspace.clone());
  189. let id = JsonValue::Number(task.id.into());
  190. let title = JsonValue::String(task.title.clone());
  191. let tags: Vec<JsonValue> = task.tags.iter().map(|x| JsonValue::String(x.clone())).collect();
  192. let desc = JsonValue::String(task.desc.clone());
  193. let owner = JsonValue::String(task.owner.clone());
  194. let assign: Vec<JsonValue> =
  195. task.assign.iter().map(|x| JsonValue::String(x.clone())).collect();
  196. let project: Vec<JsonValue> =
  197. task.project.iter().map(|x| JsonValue::String(x.clone())).collect();
  198. let due = if let Some(ts) = task.due {
  199. JsonValue::String(ts.0.to_string())
  200. } else {
  201. JsonValue::Null
  202. };
  203. let rank = if let Some(rank) = task.rank {
  204. JsonValue::Number(rank.into())
  205. } else {
  206. JsonValue::Null
  207. };
  208. let created_at = JsonValue::String(task.created_at.0.to_string());
  209. let state = JsonValue::String(task.state.clone());
  210. let events: Vec<JsonValue> = task.events.iter().map(|x| x.clone().into()).collect();
  211. let comments: Vec<JsonValue> = task.comments.iter().map(|x| x.clone().into()).collect();
  212. JsonValue::Object(HashMap::from([
  213. ("ref_id".to_string(), ref_id),
  214. ("workspace".to_string(), workspace),
  215. ("id".to_string(), id),
  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(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(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. id: *value["id"].get::<f64>().unwrap() as u32,
  263. title: value["title"].get::<String>().unwrap().clone(),
  264. tags: tags.iter().map(|x| x.get::<String>().unwrap().clone()).collect(),
  265. desc: value["desc"].get::<String>().unwrap().clone(),
  266. owner: value["owner"].get::<String>().unwrap().clone(),
  267. assign: assign.iter().map(|x| x.get::<String>().unwrap().clone()).collect(),
  268. project: project.iter().map(|x| x.get::<String>().unwrap().clone()).collect(),
  269. due,
  270. rank,
  271. created_at,
  272. state: value["state"].get::<String>().unwrap().clone(),
  273. events,
  274. comments,
  275. }
  276. }
  277. }
  278. impl TaskInfo {
  279. pub fn new(
  280. workspace: String,
  281. title: &str,
  282. desc: &str,
  283. owner: &str,
  284. due: Option<Timestamp>,
  285. rank: Option<f32>,
  286. dataset_path: &Path,
  287. ) -> TaudResult<Self> {
  288. // generate ref_id
  289. let ref_id = gen_id(30);
  290. let created_at = Timestamp::current_time();
  291. let task_ids: Vec<u32> =
  292. MonthTasks::load_current_tasks(dataset_path, workspace.clone(), false)?
  293. .into_iter()
  294. .map(|t| t.id)
  295. .collect();
  296. let id: u32 = find_free_id(&task_ids);
  297. if let Some(d) = &due {
  298. if *d < Timestamp::current_time() {
  299. return Err(TaudError::InvalidDueTime)
  300. }
  301. }
  302. Ok(Self {
  303. ref_id,
  304. workspace,
  305. id,
  306. title: title.into(),
  307. desc: desc.into(),
  308. owner: owner.into(),
  309. tags: vec![],
  310. assign: vec![],
  311. project: vec![],
  312. due,
  313. rank,
  314. created_at,
  315. state: "open".into(),
  316. comments: vec![],
  317. events: vec![],
  318. })
  319. }
  320. pub fn load(ref_id: &str, dataset_path: &Path) -> TaudResult<Self> {
  321. debug!(target: "tau", "TaskInfo::load()");
  322. let task = load_json_file(&Self::get_path(ref_id, dataset_path))?;
  323. Ok(task.into())
  324. }
  325. pub fn save(&self, dataset_path: &Path) -> TaudResult<()> {
  326. debug!(target: "tau", "TaskInfo::save()");
  327. save_json_file(&Self::get_path(&self.ref_id, dataset_path), &self.into(), true)
  328. .map_err(TaudError::Darkfi)?;
  329. if self.get_state() == "stop" {
  330. self.deactivate(dataset_path)?;
  331. } else {
  332. self.activate(dataset_path)?;
  333. }
  334. Ok(())
  335. }
  336. pub fn activate(&self, path: &Path) -> TaudResult<()> {
  337. debug!(target: "tau", "TaskInfo::activate()");
  338. let mut mt = MonthTasks::load_or_create(Some(&self.created_at), path)?;
  339. mt.add(&self.ref_id);
  340. mt.save(path)
  341. }
  342. pub fn deactivate(&self, path: &Path) -> TaudResult<()> {
  343. debug!(target: "tau", "TaskInfo::deactivate()");
  344. let mut mt = MonthTasks::load_or_create(Some(&self.created_at), path)?;
  345. mt.remove(&self.ref_id);
  346. mt.save(path)
  347. }
  348. pub fn get_state(&self) -> String {
  349. debug!(target: "tau", "TaskInfo::get_state()");
  350. self.state.clone()
  351. }
  352. pub fn get_path(ref_id: &str, dataset_path: &Path) -> PathBuf {
  353. debug!(target: "tau", "TaskInfo::get_path()");
  354. dataset_path.join("task").join(ref_id)
  355. }
  356. pub fn get_id(&self) -> u32 {
  357. debug!(target: "tau", "TaskInfo::get_id()");
  358. self.id
  359. }
  360. pub fn set_title(&mut self, title: &str) {
  361. debug!(target: "tau", "TaskInfo::set_title()");
  362. self.title = title.into();
  363. }
  364. pub fn set_desc(&mut self, desc: &str) {
  365. debug!(target: "tau", "TaskInfo::set_desc()");
  366. self.desc = desc.into();
  367. }
  368. pub fn set_tags(&mut self, tags: &[String]) {
  369. debug!(target: "tau", "TaskInfo::set_tags()");
  370. for tag in tags.iter() {
  371. if tag.starts_with('+') && !self.tags.contains(tag) {
  372. self.tags.push(tag.to_string());
  373. }
  374. if tag.starts_with('-') {
  375. let t = tag.replace('-', "+");
  376. self.tags.retain(|tag| tag != &t);
  377. }
  378. }
  379. }
  380. pub fn set_assign(&mut self, assigns: &[String]) {
  381. debug!(target: "tau", "TaskInfo::set_assign()");
  382. self.assign = assigns.to_owned();
  383. }
  384. pub fn set_project(&mut self, projects: &[String]) {
  385. debug!(target: "tau", "TaskInfo::set_project()");
  386. self.project = projects.to_owned();
  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. }