jsonrpc.rs 16 KB

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