month_tasks.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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 tinyjson::JsonValue;
  25. use tracing::debug;
  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 = Self::get_all(dataset_path).unwrap_or_default();
  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::fs::{create_dir_all, remove_dir_all};
  206. use super::*;
  207. use darkfi::Result;
  208. const TEST_DATA_PATH: &str = "/tmp/test_tau_data";
  209. fn get_path() -> Result<PathBuf> {
  210. remove_dir_all(TEST_DATA_PATH).ok();
  211. let path = PathBuf::from(TEST_DATA_PATH);
  212. // mkdir dataset_path if not exists
  213. create_dir_all(path.join("month"))?;
  214. create_dir_all(path.join("task"))?;
  215. Ok(path)
  216. }
  217. #[test]
  218. fn load_and_save_tasks() -> TaudResult<()> {
  219. let dataset_path = get_path()?;
  220. // load and save TaskInfo
  221. ///////////////////////
  222. let mut task = TaskInfo::new(
  223. "darkfi".to_string(),
  224. "test_title",
  225. "test_desc",
  226. "NICKNAME",
  227. None,
  228. Some(0.0),
  229. Timestamp::current_time(),
  230. None,
  231. )?;
  232. task.save(&dataset_path)?;
  233. let t_load = TaskInfo::load(&task.ref_id, &dataset_path)?;
  234. assert_eq!(task, t_load);
  235. task.set_title("test_title_2");
  236. task.save(&dataset_path)?;
  237. let t_load = TaskInfo::load(&task.ref_id, &dataset_path)?;
  238. assert_eq!(task, t_load);
  239. // load and save MonthTasks
  240. ///////////////////////
  241. let task_tks = vec![];
  242. let mut mt = MonthTasks::new(&task_tks, &[]);
  243. mt.save(&dataset_path)?;
  244. let mt_load = MonthTasks::load_or_create(Some(&Timestamp::current_time()), &dataset_path)?;
  245. assert_eq!(mt, mt_load);
  246. mt.add(&task.ref_id);
  247. mt.save(&dataset_path)?;
  248. let mt_load = MonthTasks::load_or_create(Some(&Timestamp::current_time()), &dataset_path)?;
  249. assert_eq!(mt, mt_load);
  250. // activate task
  251. ///////////////////////
  252. let task = TaskInfo::new(
  253. "darkfi".to_string(),
  254. "test_title_3",
  255. "test_desc",
  256. "NICKNAME",
  257. None,
  258. Some(0.0),
  259. Timestamp::current_time(),
  260. None,
  261. )?;
  262. task.save(&dataset_path)?;
  263. let mt_load = MonthTasks::load_or_create(Some(&Timestamp::current_time()), &dataset_path)?;
  264. assert!(mt_load.active_tks.contains(&task.ref_id));
  265. remove_dir_all(TEST_DATA_PATH).ok();
  266. Ok(())
  267. }
  268. }