jsonrpc.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. use async_std::sync::{Arc, Mutex};
  2. use std::{fs::create_dir_all, path::PathBuf};
  3. use async_trait::async_trait;
  4. use fxhash::FxHashMap;
  5. use log::{debug, warn};
  6. use serde::{Deserialize, Serialize};
  7. use serde_json::{json, Value};
  8. use darkfi::{
  9. rpc::{
  10. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResult},
  11. server::RequestHandler,
  12. },
  13. util::{expand_path, Timestamp},
  14. Error,
  15. };
  16. use crate::{
  17. error::{to_json_result, TaudError, TaudResult},
  18. month_tasks::MonthTasks,
  19. task_info::{Comment, TaskInfo},
  20. util::Workspace,
  21. };
  22. pub struct JsonRpcInterface {
  23. dataset_path: PathBuf,
  24. notify_queue_sender: async_channel::Sender<TaskInfo>,
  25. nickname: String,
  26. workspace: Arc<Mutex<String>>,
  27. configured_ws: FxHashMap<String, Workspace>,
  28. }
  29. #[derive(Clone, Debug, Serialize, Deserialize)]
  30. struct BaseTaskInfo {
  31. title: String,
  32. desc: String,
  33. assign: Vec<String>,
  34. project: Vec<String>,
  35. due: Option<Timestamp>,
  36. rank: Option<f32>,
  37. }
  38. #[async_trait]
  39. impl RequestHandler for JsonRpcInterface {
  40. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  41. if !req.params.is_array() {
  42. return JsonError::new(ErrorCode::InvalidParams, None, req.id).into()
  43. }
  44. let params = req.params.as_array().unwrap();
  45. let rep = match req.method.as_str() {
  46. Some("add") => self.add(params).await,
  47. Some("get_ids") => self.get_ids(params).await,
  48. Some("update") => self.update(params).await,
  49. Some("set_state") => self.set_state(params).await,
  50. Some("set_comment") => self.set_comment(params).await,
  51. Some("get_task_by_id") => self.get_task_by_id(params).await,
  52. Some("switch_ws") => self.switch_ws(params).await,
  53. Some("export") => self.export_to(params).await,
  54. Some("import") => self.import_from(params).await,
  55. Some(_) | None => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  56. };
  57. to_json_result(rep, req.id)
  58. }
  59. }
  60. impl JsonRpcInterface {
  61. pub fn new(
  62. dataset_path: PathBuf,
  63. notify_queue_sender: async_channel::Sender<TaskInfo>,
  64. nickname: String,
  65. workspace: Arc<Mutex<String>>,
  66. configured_ws: FxHashMap<String, Workspace>,
  67. ) -> Self {
  68. Self { dataset_path, nickname, workspace, configured_ws, notify_queue_sender }
  69. }
  70. // RPCAPI:
  71. // Add new task and returns `true` upon success.
  72. // --> {"jsonrpc": "2.0", "method": "add",
  73. // "params":
  74. // [{
  75. // "title": "..",
  76. // "desc": "..",
  77. // assign: [..],
  78. // project: [..],
  79. // "due": ..,
  80. // "rank": ..
  81. // }],
  82. // "id": 1
  83. // }
  84. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  85. async fn add(&self, params: &[Value]) -> TaudResult<Value> {
  86. debug!(target: "tau", "JsonRpc::add() params {:?}", params);
  87. let task: BaseTaskInfo = serde_json::from_value(params[0].clone())?;
  88. let ws = self.workspace.lock().await.clone();
  89. let mut new_task: TaskInfo = TaskInfo::new(
  90. ws,
  91. &task.title,
  92. &task.desc,
  93. &self.nickname,
  94. task.due,
  95. task.rank.unwrap_or(0.0),
  96. &self.dataset_path,
  97. )?;
  98. new_task.set_project(&task.project);
  99. new_task.set_assign(&task.assign);
  100. self.notify_queue_sender.send(new_task).await.map_err(Error::from)?;
  101. Ok(json!(true))
  102. }
  103. // RPCAPI:
  104. // List tasks
  105. // --> {"jsonrpc": "2.0", "method": "get_ids", "params": [], "id": 1}
  106. // <-- {"jsonrpc": "2.0", "result": [task_id, ...], "id": 1}
  107. async fn get_ids(&self, params: &[Value]) -> TaudResult<Value> {
  108. debug!(target: "tau", "JsonRpc::get_ids() params {:?}", params);
  109. let ws = self.workspace.lock().await.clone();
  110. let tasks = MonthTasks::load_current_open_tasks(&self.dataset_path, ws)?;
  111. let task_ids: Vec<u32> = tasks.iter().map(|task| task.get_id()).collect();
  112. Ok(json!(task_ids))
  113. }
  114. // RPCAPI:
  115. // Update task and returns `true` upon success.
  116. // --> {"jsonrpc": "2.0", "method": "update", "params": [task_id, {"title": "new title"} ], "id": 1}
  117. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  118. async fn update(&self, params: &[Value]) -> TaudResult<Value> {
  119. debug!(target: "tau", "JsonRpc::update() params {:?}", params);
  120. if params.len() != 2 {
  121. return Err(TaudError::InvalidData("len of params should be 2".into()))
  122. }
  123. let ws = self.workspace.lock().await.clone();
  124. let task = self.check_params_for_update(&params[0], &params[1], ws)?;
  125. self.notify_queue_sender.send(task).await.map_err(Error::from)?;
  126. Ok(json!(true))
  127. }
  128. // RPCAPI:
  129. // Set state for a task and returns `true` upon success.
  130. // --> {"jsonrpc": "2.0", "method": "set_state", "params": [task_id, state], "id": 1}
  131. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  132. async fn set_state(&self, params: &[Value]) -> TaudResult<Value> {
  133. // Allowed states for a task
  134. let states = ["stop", "start", "open", "pause"];
  135. debug!(target: "tau", "JsonRpc::set_state() params {:?}", params);
  136. if params.len() != 2 {
  137. return Err(TaudError::InvalidData("len of params should be 2".into()))
  138. }
  139. let state: String = serde_json::from_value(params[1].clone())?;
  140. let ws = self.workspace.lock().await.clone();
  141. let mut task: TaskInfo = self.load_task_by_id(&params[0], ws)?;
  142. if states.contains(&state.as_str()) {
  143. task.set_state(&state);
  144. }
  145. self.notify_queue_sender.send(task).await.map_err(Error::from)?;
  146. Ok(json!(true))
  147. }
  148. // RPCAPI:
  149. // Set comment for a task and returns `true` upon success.
  150. // --> {"jsonrpc": "2.0", "method": "set_comment", "params": [task_id, comment_content], "id": 1}
  151. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  152. async fn set_comment(&self, params: &[Value]) -> TaudResult<Value> {
  153. debug!(target: "tau", "JsonRpc::set_comment() params {:?}", params);
  154. if params.len() != 2 {
  155. return Err(TaudError::InvalidData("len of params should be 3".into()))
  156. }
  157. let comment_content: String = serde_json::from_value(params[1].clone())?;
  158. let ws = self.workspace.lock().await.clone();
  159. let mut task: TaskInfo = self.load_task_by_id(&params[0], ws)?;
  160. task.set_comment(Comment::new(&comment_content, &self.nickname));
  161. self.notify_queue_sender.send(task).await.map_err(Error::from)?;
  162. Ok(json!(true))
  163. }
  164. // RPCAPI:
  165. // Get a task by id.
  166. // --> {"jsonrpc": "2.0", "method": "get_task_by_id", "params": [task_id], "id": 1}
  167. // <-- {"jsonrpc": "2.0", "result": "task", "id": 1}
  168. async fn get_task_by_id(&self, params: &[Value]) -> TaudResult<Value> {
  169. debug!(target: "tau", "JsonRpc::get_task_by_id() params {:?}", params);
  170. if params.len() != 1 {
  171. return Err(TaudError::InvalidData("len of params should be 1".into()))
  172. }
  173. let ws = self.workspace.lock().await.clone();
  174. let task: TaskInfo = self.load_task_by_id(&params[0], ws)?;
  175. Ok(json!(task))
  176. }
  177. // RPCAPI:
  178. // Switch tasks workspace.
  179. // --> {"jsonrpc": "2.0", "method": "switch_ws", "params": [workspace], "id": 1}
  180. // <-- {"jsonrpc": "2.0", "result": "true", "id": 1}
  181. async fn switch_ws(&self, params: &[Value]) -> TaudResult<Value> {
  182. debug!(target: "tau", "JsonRpc::switch_ws() params {:?}", params);
  183. if params.len() != 1 {
  184. return Err(TaudError::InvalidData("len of params should be 1".into()))
  185. }
  186. if !params[0].is_string() {
  187. return Err(TaudError::InvalidData("Invalid workspace".into()))
  188. }
  189. let ws = params[0].as_str().unwrap().to_string();
  190. let mut s = self.workspace.lock().await;
  191. if self.configured_ws.contains_key(&ws) {
  192. *s = ws
  193. } else {
  194. warn!("Workspace \"{}\" is not configured", ws);
  195. }
  196. Ok(json!(true))
  197. }
  198. // RPCAPI:
  199. // Export tasks.
  200. // --> {"jsonrpc": "2.0", "method": "export_to", "params": [path], "id": 1}
  201. // <-- {"jsonrpc": "2.0", "result": "true", "id": 1}
  202. async fn export_to(&self, params: &[Value]) -> TaudResult<Value> {
  203. debug!(target: "tau", "JsonRpc::export_to() params {:?}", params);
  204. if params.len() != 1 {
  205. return Err(TaudError::InvalidData("len of params should be 1".into()))
  206. }
  207. if !params[0].is_string() {
  208. return Err(TaudError::InvalidData("Invalid path".into()))
  209. }
  210. let path = expand_path(params[0].as_str().unwrap())?.join("exported_tasks");
  211. // mkdir datastore_path if not exists
  212. create_dir_all(path.join("month")).map_err(Error::from)?;
  213. create_dir_all(path.join("task")).map_err(Error::from)?;
  214. let mt = MonthTasks::load_or_create(None, &self.dataset_path)?;
  215. let tasks = mt.objects(&self.dataset_path)?;
  216. for task in tasks {
  217. task.save(&path)?;
  218. }
  219. Ok(json!(true))
  220. }
  221. // RPCAPI:
  222. // Import tasks.
  223. // --> {"jsonrpc": "2.0", "method": "import_from", "params": [path], "id": 1}
  224. // <-- {"jsonrpc": "2.0", "result": "true", "id": 1}
  225. async fn import_from(&self, params: &[Value]) -> TaudResult<Value> {
  226. debug!(target: "tau", "JsonRpc::import_from() params {:?}", params);
  227. if params.len() != 1 {
  228. return Err(TaudError::InvalidData("len of params should be 1".into()))
  229. }
  230. if !params[0].is_string() {
  231. return Err(TaudError::InvalidData("Invalid path".into()))
  232. }
  233. let path = expand_path(params[0].as_str().unwrap())?.join("exported_tasks");
  234. let mt = MonthTasks::load_or_create(None, &path)?;
  235. let tasks = mt.objects(&path)?;
  236. for task in tasks {
  237. self.notify_queue_sender.send(task).await.map_err(Error::from)?;
  238. }
  239. Ok(json!(true))
  240. }
  241. fn load_task_by_id(&self, task_id: &Value, ws: String) -> TaudResult<TaskInfo> {
  242. let task_id: u64 = serde_json::from_value(task_id.clone())?;
  243. let tasks = MonthTasks::load_current_open_tasks(&self.dataset_path, ws)?;
  244. let task = tasks.into_iter().find(|t| (t.get_id() as u64) == task_id);
  245. task.ok_or(TaudError::InvalidId)
  246. }
  247. fn check_params_for_update(
  248. &self,
  249. task_id: &Value,
  250. fields: &Value,
  251. ws: String,
  252. ) -> TaudResult<TaskInfo> {
  253. let mut task: TaskInfo = self.load_task_by_id(task_id, ws)?;
  254. if !fields.is_object() {
  255. return Err(TaudError::InvalidData("Invalid task's data".into()))
  256. }
  257. let fields = fields.as_object().unwrap();
  258. if fields.contains_key("title") {
  259. let title = fields.get("title").unwrap().clone();
  260. let title: String = serde_json::from_value(title)?;
  261. if !title.is_empty() {
  262. task.set_title(&title);
  263. }
  264. }
  265. if fields.contains_key("desc") {
  266. let description = fields.get("description");
  267. if let Some(description) = description {
  268. let description: String = serde_json::from_value(description.clone())?;
  269. task.set_desc(&description);
  270. }
  271. }
  272. if fields.contains_key("rank") {
  273. let rank_opt = fields.get("rank");
  274. if let Some(rank) = rank_opt {
  275. let rank: Option<f32> = serde_json::from_value(rank.clone())?;
  276. if let Some(r) = rank {
  277. task.set_rank(r);
  278. }
  279. }
  280. }
  281. if fields.contains_key("due") {
  282. let due = fields.get("due").unwrap().clone();
  283. let due: Option<Option<Timestamp>> = serde_json::from_value(due)?;
  284. if let Some(d) = due {
  285. task.set_due(d);
  286. }
  287. }
  288. if fields.contains_key("assign") {
  289. let assign = fields.get("assign").unwrap().clone();
  290. let assign: Vec<String> = serde_json::from_value(assign)?;
  291. if !assign.is_empty() {
  292. task.set_assign(&assign);
  293. }
  294. }
  295. if fields.contains_key("project") {
  296. let project = fields.get("project").unwrap().clone();
  297. let project: Vec<String> = serde_json::from_value(project)?;
  298. if !project.is_empty() {
  299. task.set_project(&project);
  300. }
  301. }
  302. Ok(task)
  303. }
  304. }