task_info.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. };
  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.0.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(map["timestamp"].get::<String>().unwrap().parse::<u64>().unwrap()),
  124. }
  125. }
  126. }
  127. #[derive(Clone, Debug, SerialDecodable, SerialEncodable, PartialEq, Eq)]
  128. pub struct Comment {
  129. content: String,
  130. author: String,
  131. timestamp: Timestamp,
  132. }
  133. impl std::fmt::Display for Comment {
  134. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  135. write!(f, "{} author: {}, content: {} ", self.timestamp, self.author, self.content)
  136. }
  137. }
  138. impl From<Comment> for JsonValue {
  139. fn from(comment: Comment) -> JsonValue {
  140. JsonValue::Object(HashMap::from([
  141. ("content".to_string(), JsonValue::String(comment.content.clone())),
  142. ("author".to_string(), JsonValue::String(comment.author.clone())),
  143. ("timestamp".to_string(), JsonValue::String(comment.timestamp.0.to_string())),
  144. ]))
  145. }
  146. }
  147. impl From<JsonValue> for Comment {
  148. fn from(value: JsonValue) -> Comment {
  149. let map = value.get::<HashMap<String, JsonValue>>().unwrap();
  150. Comment {
  151. content: map["content"].get::<String>().unwrap().clone(),
  152. author: map["author"].get::<String>().unwrap().clone(),
  153. timestamp: Timestamp(map["timestamp"].get::<String>().unwrap().parse::<u64>().unwrap()),
  154. }
  155. }
  156. }
  157. impl Comment {
  158. pub fn new(content: &str, author: &str) -> Self {
  159. Self {
  160. content: content.into(),
  161. author: author.into(),
  162. timestamp: Timestamp::current_time(),
  163. }
  164. }
  165. }
  166. #[derive(Clone, Debug, SerialEncodable, SerialDecodable, PartialEq)]
  167. pub struct TaskInfo {
  168. pub ref_id: String,
  169. pub workspace: String,
  170. pub title: String,
  171. pub tags: Vec<String>,
  172. pub desc: String,
  173. pub owner: String,
  174. pub assign: Vec<String>,
  175. pub project: Vec<String>,
  176. pub due: Option<Timestamp>,
  177. pub rank: Option<f32>,
  178. pub created_at: Timestamp,
  179. pub state: String,
  180. pub events: Vec<TaskEvent>,
  181. pub comments: Vec<Comment>,
  182. }
  183. impl From<&TaskInfo> for JsonValue {
  184. fn from(task: &TaskInfo) -> JsonValue {
  185. let ref_id = JsonValue::String(task.ref_id.clone());
  186. let workspace = JsonValue::String(task.workspace.clone());
  187. let title = JsonValue::String(task.title.clone());
  188. let tags: Vec<JsonValue> = task.tags.iter().map(|x| JsonValue::String(x.clone())).collect();
  189. let desc = JsonValue::String(task.desc.clone());
  190. let owner = JsonValue::String(task.owner.clone());
  191. let assign: Vec<JsonValue> =
  192. task.assign.iter().map(|x| JsonValue::String(x.clone())).collect();
  193. let project: Vec<JsonValue> =
  194. task.project.iter().map(|x| JsonValue::String(x.clone())).collect();
  195. let due = if let Some(ts) = task.due {
  196. JsonValue::String(ts.0.to_string())
  197. } else {
  198. JsonValue::Null
  199. };
  200. let rank = if let Some(rank) = task.rank {
  201. JsonValue::Number(rank.into())
  202. } else {
  203. JsonValue::Null
  204. };
  205. let created_at = JsonValue::String(task.created_at.0.to_string());
  206. let state = JsonValue::String(task.state.clone());
  207. let events: Vec<JsonValue> = task.events.iter().map(|x| x.clone().into()).collect();
  208. let comments: Vec<JsonValue> = task.comments.iter().map(|x| x.clone().into()).collect();
  209. JsonValue::Object(HashMap::from([
  210. ("ref_id".to_string(), ref_id),
  211. ("workspace".to_string(), workspace),
  212. ("title".to_string(), title),
  213. ("tags".to_string(), JsonValue::Array(tags)),
  214. ("desc".to_string(), desc),
  215. ("owner".to_string(), owner),
  216. ("assign".to_string(), JsonValue::Array(assign)),
  217. ("project".to_string(), JsonValue::Array(project)),
  218. ("due".to_string(), due),
  219. ("rank".to_string(), rank),
  220. ("created_at".to_string(), created_at),
  221. ("state".to_string(), state),
  222. ("events".to_string(), JsonValue::Array(events)),
  223. ("comments".to_string(), JsonValue::Array(comments)),
  224. ]))
  225. }
  226. }
  227. impl From<JsonValue> for TaskInfo {
  228. fn from(value: JsonValue) -> TaskInfo {
  229. let tags = value["tags"].get::<Vec<JsonValue>>().unwrap();
  230. let assign = value["assign"].get::<Vec<JsonValue>>().unwrap();
  231. let project = value["project"].get::<Vec<JsonValue>>().unwrap();
  232. let events = value["events"].get::<Vec<JsonValue>>().unwrap();
  233. let comments = value["comments"].get::<Vec<JsonValue>>().unwrap();
  234. let due = {
  235. if value["due"].is_null() {
  236. None
  237. } else {
  238. let u64_str = value["due"].get::<String>().unwrap();
  239. Some(Timestamp(u64_str.parse::<u64>().unwrap()))
  240. }
  241. };
  242. let rank = {
  243. if value["rank"].is_null() {
  244. None
  245. } else {
  246. Some(*value["rank"].get::<f64>().unwrap() as f32)
  247. }
  248. };
  249. let created_at = {
  250. let u64_str = value["created_at"].get::<String>().unwrap();
  251. Timestamp(u64_str.parse::<u64>().unwrap())
  252. };
  253. let events: Vec<TaskEvent> = events.iter().map(|x| x.into()).collect();
  254. let comments: Vec<Comment> = comments.iter().map(|x| (*x).clone().into()).collect();
  255. TaskInfo {
  256. ref_id: value["ref_id"].get::<String>().unwrap().clone(),
  257. workspace: value["workspace"].get::<String>().unwrap().clone(),
  258. title: value["title"].get::<String>().unwrap().clone(),
  259. tags: tags.iter().map(|x| x.get::<String>().unwrap().clone()).collect(),
  260. desc: value["desc"].get::<String>().unwrap().clone(),
  261. owner: value["owner"].get::<String>().unwrap().clone(),
  262. assign: assign.iter().map(|x| x.get::<String>().unwrap().clone()).collect(),
  263. project: project.iter().map(|x| x.get::<String>().unwrap().clone()).collect(),
  264. due,
  265. rank,
  266. created_at,
  267. state: value["state"].get::<String>().unwrap().clone(),
  268. events,
  269. comments,
  270. }
  271. }
  272. }
  273. impl TaskInfo {
  274. pub fn new(
  275. workspace: String,
  276. title: &str,
  277. desc: &str,
  278. owner: &str,
  279. due: Option<Timestamp>,
  280. rank: Option<f32>,
  281. created_at: Timestamp,
  282. ) -> TaudResult<Self> {
  283. // generate ref_id
  284. let ref_id = gen_id(30);
  285. if let Some(d) = &due {
  286. if *d < Timestamp::current_time() {
  287. return Err(TaudError::InvalidDueTime)
  288. }
  289. }
  290. Ok(Self {
  291. ref_id,
  292. workspace,
  293. title: title.into(),
  294. desc: desc.into(),
  295. owner: owner.into(),
  296. tags: vec![],
  297. assign: vec![],
  298. project: vec![],
  299. due,
  300. rank,
  301. created_at,
  302. state: "open".into(),
  303. comments: vec![],
  304. events: vec![],
  305. })
  306. }
  307. pub fn load(ref_id: &str, dataset_path: &Path) -> TaudResult<Self> {
  308. debug!(target: "tau", "TaskInfo::load()");
  309. let task = load_json_file(&Self::get_path(ref_id, dataset_path))?;
  310. Ok(task.into())
  311. }
  312. pub fn save(&self, dataset_path: &Path) -> TaudResult<()> {
  313. debug!(target: "tau", "TaskInfo::save()");
  314. save_json_file(&Self::get_path(&self.ref_id, dataset_path), &self.into(), true)
  315. .map_err(TaudError::Darkfi)?;
  316. if self.get_state() == "stop" {
  317. self.deactivate(dataset_path)?;
  318. } else {
  319. self.activate(dataset_path)?;
  320. }
  321. Ok(())
  322. }
  323. pub fn activate(&self, path: &Path) -> TaudResult<()> {
  324. debug!(target: "tau", "TaskInfo::activate()");
  325. let mut mt = MonthTasks::load_or_create(Some(&self.created_at), path)?;
  326. mt.add(&self.ref_id);
  327. mt.save(path)
  328. }
  329. pub fn deactivate(&self, path: &Path) -> TaudResult<()> {
  330. debug!(target: "tau", "TaskInfo::deactivate()");
  331. let mut mt = MonthTasks::load_or_create(Some(&self.created_at), path)?;
  332. mt.remove(&self.ref_id);
  333. mt.save(path)
  334. }
  335. pub fn get_state(&self) -> String {
  336. debug!(target: "tau", "TaskInfo::get_state()");
  337. self.state.clone()
  338. }
  339. pub fn get_path(ref_id: &str, dataset_path: &Path) -> PathBuf {
  340. debug!(target: "tau", "TaskInfo::get_path()");
  341. dataset_path.join("task").join(ref_id)
  342. }
  343. pub fn get_ref_id(&self) -> String {
  344. debug!(target: "tau", "TaskInfo::get_ref_id()");
  345. self.ref_id.clone()
  346. }
  347. pub fn set_title(&mut self, title: &str) {
  348. debug!(target: "tau", "TaskInfo::set_title()");
  349. self.title = title.into();
  350. }
  351. pub fn set_desc(&mut self, desc: &str) {
  352. debug!(target: "tau", "TaskInfo::set_desc()");
  353. self.desc = desc.into();
  354. }
  355. pub fn set_tags(&mut self, tags: &[String]) {
  356. debug!(target: "tau", "TaskInfo::set_tags()");
  357. for tag in tags.iter() {
  358. let stripped = &tag[1..];
  359. if tag.starts_with('+') && !self.tags.contains(&stripped.to_string()) {
  360. self.tags.push(stripped.to_string());
  361. }
  362. if tag.starts_with('-') {
  363. self.tags.retain(|tag| tag != stripped);
  364. }
  365. }
  366. }
  367. pub fn set_assign(&mut self, assigns: &[String]) {
  368. debug!(target: "tau", "TaskInfo::set_assign()");
  369. // self.assign = assigns.to_owned();
  370. for assign in assigns.iter() {
  371. let stripped = assign.split('@').collect::<Vec<&str>>()[1];
  372. if assign.starts_with('@') && !self.assign.contains(&stripped.to_string()) {
  373. self.assign.push(stripped.to_string());
  374. }
  375. if assign.starts_with("-@") {
  376. self.assign.retain(|assign| assign != stripped);
  377. }
  378. }
  379. }
  380. pub fn set_project(&mut self, projects: &[String]) {
  381. debug!(target: "tau", "TaskInfo::set_project()");
  382. self.project = projects.to_owned();
  383. }
  384. pub fn set_comment(&mut self, c: Comment) {
  385. debug!(target: "tau", "TaskInfo::set_comment()");
  386. self.comments.push(c);
  387. }
  388. pub fn set_rank(&mut self, r: Option<f32>) {
  389. debug!(target: "tau", "TaskInfo::set_rank()");
  390. self.rank = r;
  391. }
  392. pub fn set_due(&mut self, d: Option<Timestamp>) {
  393. debug!(target: "tau", "TaskInfo::set_due()");
  394. self.due = d;
  395. }
  396. pub fn set_state(&mut self, state: &str) {
  397. debug!(target: "tau", "TaskInfo::set_state()");
  398. if self.get_state() == state {
  399. return
  400. }
  401. self.state = state.to_string();
  402. }
  403. }