jsonrpc.rs 16 KB

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