jsonrpc.rs 15 KB

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