month_tasks.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. fs, io,
  21. path::{Path, PathBuf},
  22. };
  23. use chrono::{TimeZone, Utc};
  24. use log::debug;
  25. use tinyjson::JsonValue;
  26. use darkfi::util::{
  27. file::{load_json_file, save_json_file},
  28. time::Timestamp,
  29. };
  30. use crate::{
  31. error::{TaudError, TaudResult},
  32. task_info::TaskInfo,
  33. };
  34. #[derive(Clone, Debug, PartialEq, Eq)]
  35. pub struct MonthTasks {
  36. created_at: Timestamp,
  37. active_tks: Vec<String>,
  38. deactive_tks: Vec<String>,
  39. }
  40. impl From<MonthTasks> for JsonValue {
  41. fn from(mt: MonthTasks) -> JsonValue {
  42. let active_tks: Vec<JsonValue> =
  43. mt.active_tks.iter().map(|x| JsonValue::String(x.clone())).collect();
  44. let deactive_tks: Vec<JsonValue> =
  45. mt.deactive_tks.iter().map(|x| JsonValue::String(x.clone())).collect();
  46. JsonValue::Object(HashMap::from([
  47. ("created_at".to_string(), JsonValue::String(mt.created_at.0.to_string())),
  48. ("active_tks".to_string(), JsonValue::Array(active_tks)),
  49. ("deactive_tks".to_string(), JsonValue::Array(deactive_tks)),
  50. ]))
  51. }
  52. }
  53. impl From<JsonValue> for MonthTasks {
  54. fn from(value: JsonValue) -> MonthTasks {
  55. let created_at = {
  56. let u64_str = value["created_at"].get::<String>().unwrap();
  57. Timestamp(u64_str.parse::<u64>().unwrap())
  58. };
  59. let active_tks: Vec<String> = value["active_tks"]
  60. .get::<Vec<JsonValue>>()
  61. .unwrap()
  62. .iter()
  63. .map(|x| x.get::<String>().unwrap().clone())
  64. .collect();
  65. let deactive_tks: Vec<String> = value["deactive_tks"]
  66. .get::<Vec<JsonValue>>()
  67. .unwrap()
  68. .iter()
  69. .map(|x| x.get::<String>().unwrap().clone())
  70. .collect();
  71. MonthTasks { created_at, active_tks, deactive_tks }
  72. }
  73. }
  74. impl MonthTasks {
  75. pub fn new(active_tks: &[String], deactive_tks: &[String]) -> Self {
  76. Self {
  77. created_at: Timestamp::current_time(),
  78. active_tks: active_tks.to_owned(),
  79. deactive_tks: deactive_tks.to_owned(),
  80. }
  81. }
  82. pub fn add(&mut self, ref_id: &str) {
  83. debug!(target: "tau", "MonthTasks::add()");
  84. if !self.active_tks.contains(&ref_id.into()) {
  85. self.active_tks.push(ref_id.into());
  86. }
  87. }
  88. pub fn objects(&self, dataset_path: &Path) -> TaudResult<Vec<TaskInfo>> {
  89. debug!(target: "tau", "MonthTasks::objects()");
  90. let mut tks: Vec<TaskInfo> = vec![];
  91. for ref_id in self.active_tks.iter() {
  92. tks.push(TaskInfo::load(ref_id, dataset_path)?);
  93. }
  94. for ref_id in self.deactive_tks.iter() {
  95. tks.push(TaskInfo::load(ref_id, dataset_path)?);
  96. }
  97. Ok(tks)
  98. }
  99. pub fn remove(&mut self, ref_id: &str) {
  100. debug!(target: "tau", "MonthTasks::remove()");
  101. if self.active_tks.contains(&ref_id.to_string()) {
  102. if let Some(index) = self.active_tks.iter().position(|t| *t == ref_id) {
  103. self.deactive_tks.push(self.active_tks.remove(index));
  104. }
  105. } else {
  106. self.deactive_tks.push(ref_id.to_owned());
  107. }
  108. }
  109. pub fn set_date(&mut self, date: &Timestamp) {
  110. debug!(target: "tau", "MonthTasks::set_date()");
  111. self.created_at = *date;
  112. }
  113. fn get_path(date: &Timestamp, dataset_path: &Path) -> PathBuf {
  114. debug!(target: "tau", "MonthTasks::get_path()");
  115. dataset_path.join("month").join(
  116. Utc.timestamp_opt(date.0.try_into().unwrap(), 0).unwrap().format("%m%y").to_string(),
  117. )
  118. }
  119. pub fn save(&self, dataset_path: &Path) -> TaudResult<()> {
  120. debug!(target: "tau", "MonthTasks::save()");
  121. let mt: JsonValue = self.clone().into();
  122. save_json_file(&Self::get_path(&self.created_at, dataset_path), &mt, true)
  123. .map_err(TaudError::Darkfi)
  124. }
  125. fn get_all(dataset_path: &Path) -> io::Result<Vec<PathBuf>> {
  126. debug!(target: "tau", "MonthTasks::get_all()");
  127. let mut entries = fs::read_dir(dataset_path.join("month"))?
  128. .map(|res| res.map(|e| e.path()))
  129. .collect::<Result<Vec<_>, io::Error>>()?;
  130. entries.sort();
  131. Ok(entries)
  132. }
  133. fn create(date: &Timestamp, dataset_path: &Path) -> TaudResult<Self> {
  134. debug!(target: "tau", "MonthTasks::create()");
  135. let mut mt = Self::new(&[], &[]);
  136. mt.set_date(date);
  137. mt.save(dataset_path)?;
  138. Ok(mt)
  139. }
  140. pub fn load_or_create(date: Option<&Timestamp>, dataset_path: &Path) -> TaudResult<Self> {
  141. debug!(target: "tau", "MonthTasks::load_or_create()");
  142. // if a date is given we load that date's month tasks
  143. // if not, we load tasks from all months
  144. match date {
  145. Some(date) => match load_json_file(&Self::get_path(date, dataset_path)) {
  146. Ok(mt) => Ok(mt.into()),
  147. Err(_) => Self::create(date, dataset_path),
  148. },
  149. None => {
  150. let path_all = match Self::get_all(dataset_path) {
  151. Ok(t) => t,
  152. Err(_) => vec![],
  153. };
  154. let mut loaded_mt = Self::new(&[], &[]);
  155. for path in path_all {
  156. let mt = load_json_file(&path)?;
  157. let mt: MonthTasks = mt.into();
  158. loaded_mt.created_at = mt.created_at;
  159. for tks in mt.active_tks {
  160. if !loaded_mt.active_tks.contains(&tks) {
  161. loaded_mt.active_tks.push(tks)
  162. }
  163. }
  164. for dtks in mt.deactive_tks {
  165. if !loaded_mt.deactive_tks.contains(&dtks) {
  166. loaded_mt.deactive_tks.push(dtks)
  167. }
  168. }
  169. }
  170. Ok(loaded_mt)
  171. }
  172. }
  173. }
  174. pub fn load_current_tasks(
  175. dataset_path: &Path,
  176. ws: String,
  177. all: bool,
  178. ) -> TaudResult<Vec<TaskInfo>> {
  179. let mt = Self::load_or_create(None, dataset_path)?;
  180. if all {
  181. Ok(mt.objects(dataset_path)?.into_iter().filter(|t| t.workspace == ws).collect())
  182. } else {
  183. Ok(mt
  184. .objects(dataset_path)?
  185. .into_iter()
  186. .filter(|t| t.get_state() != "stop" && t.workspace == ws)
  187. .collect())
  188. }
  189. }
  190. pub fn load_stop_tasks(
  191. dataset_path: &Path,
  192. ws: String,
  193. date: Option<&Timestamp>,
  194. ) -> TaudResult<Vec<TaskInfo>> {
  195. let mt = Self::load_or_create(date, dataset_path)?;
  196. Ok(mt
  197. .objects(dataset_path)?
  198. .into_iter()
  199. .filter(|t| t.get_state() == "stop" && t.workspace == ws)
  200. .collect())
  201. }
  202. }
  203. #[cfg(test)]
  204. mod tests {
  205. use std::{
  206. fs::{create_dir_all, remove_dir_all},
  207. path::PathBuf,
  208. };
  209. use super::*;
  210. use darkfi::Result;
  211. const TEST_DATA_PATH: &str = "/tmp/test_tau_data";
  212. fn get_path() -> Result<PathBuf> {
  213. remove_dir_all(TEST_DATA_PATH).ok();
  214. let path = PathBuf::from(TEST_DATA_PATH);
  215. // mkdir dataset_path if not exists
  216. create_dir_all(path.join("month"))?;
  217. create_dir_all(path.join("task"))?;
  218. Ok(path)
  219. }
  220. #[test]
  221. fn load_and_save_tasks() -> TaudResult<()> {
  222. let dataset_path = get_path()?;
  223. // load and save TaskInfo
  224. ///////////////////////
  225. let mut task = TaskInfo::new(
  226. "darkfi".to_string(),
  227. "test_title",
  228. "test_desc",
  229. "NICKNAME",
  230. None,
  231. Some(0.0),
  232. Timestamp::current_time(),
  233. )?;
  234. task.save(&dataset_path)?;
  235. let t_load = TaskInfo::load(&task.ref_id, &dataset_path)?;
  236. assert_eq!(task, t_load);
  237. task.set_title("test_title_2");
  238. task.save(&dataset_path)?;
  239. let t_load = TaskInfo::load(&task.ref_id, &dataset_path)?;
  240. assert_eq!(task, t_load);
  241. // load and save MonthTasks
  242. ///////////////////////
  243. let task_tks = vec![];
  244. let mut mt = MonthTasks::new(&task_tks, &[]);
  245. mt.save(&dataset_path)?;
  246. let mt_load = MonthTasks::load_or_create(Some(&Timestamp::current_time()), &dataset_path)?;
  247. assert_eq!(mt, mt_load);
  248. mt.add(&task.ref_id);
  249. mt.save(&dataset_path)?;
  250. let mt_load = MonthTasks::load_or_create(Some(&Timestamp::current_time()), &dataset_path)?;
  251. assert_eq!(mt, mt_load);
  252. // activate task
  253. ///////////////////////
  254. let task = TaskInfo::new(
  255. "darkfi".to_string(),
  256. "test_title_3",
  257. "test_desc",
  258. "NICKNAME",
  259. None,
  260. Some(0.0),
  261. Timestamp::current_time(),
  262. )?;
  263. task.save(&dataset_path)?;
  264. let mt_load = MonthTasks::load_or_create(Some(&Timestamp::current_time()), &dataset_path)?;
  265. assert!(mt_load.active_tks.contains(&task.ref_id));
  266. remove_dir_all(TEST_DATA_PATH).ok();
  267. Ok(())
  268. }
  269. }