month_tasks.rs 8.3 KB

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