month_tasks.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. 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.inner().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::from_u64(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.inner().try_into().unwrap(), 0)
  117. .unwrap()
  118. .format("%m%y")
  119. .to_string(),
  120. )
  121. }
  122. pub fn save(&self, dataset_path: &Path) -> TaudResult<()> {
  123. debug!(target: "tau", "MonthTasks::save()");
  124. let mt: JsonValue = self.clone().into();
  125. save_json_file(&Self::get_path(&self.created_at, dataset_path), &mt, true)
  126. .map_err(TaudError::Darkfi)
  127. }
  128. fn get_all(dataset_path: &Path) -> io::Result<Vec<PathBuf>> {
  129. debug!(target: "tau", "MonthTasks::get_all()");
  130. let mut entries = fs::read_dir(dataset_path.join("month"))?
  131. .map(|res| res.map(|e| e.path()))
  132. .collect::<Result<Vec<_>, io::Error>>()?;
  133. entries.sort();
  134. Ok(entries)
  135. }
  136. fn create(date: &Timestamp, dataset_path: &Path) -> TaudResult<Self> {
  137. debug!(target: "tau", "MonthTasks::create()");
  138. let mut mt = Self::new(&[], &[]);
  139. mt.set_date(date);
  140. mt.save(dataset_path)?;
  141. Ok(mt)
  142. }
  143. pub fn load_or_create(date: Option<&Timestamp>, dataset_path: &Path) -> TaudResult<Self> {
  144. debug!(target: "tau", "MonthTasks::load_or_create()");
  145. // if a date is given we load that date's month tasks
  146. // if not, we load tasks from all months
  147. match date {
  148. Some(date) => match load_json_file(&Self::get_path(date, dataset_path)) {
  149. Ok(mt) => Ok(mt.into()),
  150. Err(_) => Self::create(date, dataset_path),
  151. },
  152. None => {
  153. let path_all = match Self::get_all(dataset_path) {
  154. Ok(t) => t,
  155. Err(_) => vec![],
  156. };
  157. let mut loaded_mt = Self::new(&[], &[]);
  158. for path in path_all {
  159. let mt = load_json_file(&path)?;
  160. let mt: MonthTasks = mt.into();
  161. loaded_mt.created_at = mt.created_at;
  162. for tks in mt.active_tks {
  163. if !loaded_mt.active_tks.contains(&tks) {
  164. loaded_mt.active_tks.push(tks)
  165. }
  166. }
  167. for dtks in mt.deactive_tks {
  168. if !loaded_mt.deactive_tks.contains(&dtks) {
  169. loaded_mt.deactive_tks.push(dtks)
  170. }
  171. }
  172. }
  173. Ok(loaded_mt)
  174. }
  175. }
  176. }
  177. pub fn load_current_tasks(
  178. dataset_path: &Path,
  179. ws: String,
  180. all: bool,
  181. ) -> TaudResult<Vec<TaskInfo>> {
  182. let mt = Self::load_or_create(None, dataset_path)?;
  183. if all {
  184. Ok(mt.objects(dataset_path)?.into_iter().filter(|t| t.workspace == ws).collect())
  185. } else {
  186. Ok(mt
  187. .objects(dataset_path)?
  188. .into_iter()
  189. .filter(|t| t.get_state() != "stop" && t.workspace == ws)
  190. .collect())
  191. }
  192. }
  193. pub fn load_stop_tasks(
  194. dataset_path: &Path,
  195. ws: String,
  196. date: Option<&Timestamp>,
  197. ) -> TaudResult<Vec<TaskInfo>> {
  198. let mt = Self::load_or_create(date, dataset_path)?;
  199. Ok(mt
  200. .objects(dataset_path)?
  201. .into_iter()
  202. .filter(|t| t.get_state() == "stop" && t.workspace == ws)
  203. .collect())
  204. }
  205. }
  206. #[cfg(test)]
  207. mod tests {
  208. use std::fs::{create_dir_all, remove_dir_all};
  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. }