jsonrpc.rs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 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 async_trait::async_trait;
  19. use log::error;
  20. use serde_json::{json, Value};
  21. use darkfi::{
  22. rpc::{
  23. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  24. server::RequestHandler,
  25. },
  26. Error,
  27. };
  28. use crate::Patch;
  29. pub struct JsonRpcInterface {
  30. sender: smol::channel::Sender<(String, bool, Vec<String>)>,
  31. receiver: smol::channel::Receiver<Vec<Vec<Patch>>>,
  32. }
  33. #[async_trait]
  34. impl RequestHandler for JsonRpcInterface {
  35. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  36. if !req.params.is_array() {
  37. return JsonError::new(ErrorCode::InvalidParams, None, req.id).into()
  38. }
  39. let params = req.params.as_array().unwrap();
  40. let rep = match req.method.as_str() {
  41. Some("update") => self.update(req.id, params).await,
  42. Some("restore") => self.restore(req.id, params).await,
  43. Some("log") => self.log(req.id, params).await,
  44. Some(_) | None => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  45. };
  46. rep
  47. }
  48. }
  49. fn patch_to_tuple(p: &Patch, colorize: bool) -> (String, String, String) {
  50. (p.path.to_owned(), p.workspace.to_owned(), if colorize { p.colorize() } else { p.to_string() })
  51. }
  52. fn printable_patches(
  53. patches: Vec<Vec<Patch>>,
  54. colorize: bool,
  55. ) -> Vec<Vec<(String, String, String)>> {
  56. let mut response = vec![];
  57. for ps in patches {
  58. response.push(ps.iter().map(|p| patch_to_tuple(p, colorize)).collect())
  59. }
  60. response
  61. }
  62. impl JsonRpcInterface {
  63. pub fn new(
  64. sender: smol::channel::Sender<(String, bool, Vec<String>)>,
  65. receiver: smol::channel::Receiver<Vec<Vec<Patch>>>,
  66. ) -> Self {
  67. Self { sender, receiver }
  68. }
  69. // RPCAPI:
  70. // Update files
  71. // --> {"jsonrpc": "2.0", "method": "update", "params": [], "id": 1}
  72. // <-- {"jsonrpc": "2.0", "result": [[(String, String)]], "id": 1}
  73. async fn update(&self, id: Value, params: &[Value]) -> JsonResult {
  74. let dry = params[0].as_bool().unwrap();
  75. let files: Vec<String> =
  76. params[1].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
  77. let res = self.sender.send(("update".into(), dry, files)).await.map_err(Error::from);
  78. if let Err(e) = res {
  79. error!("Failed to update: {}", e);
  80. return JsonError::new(ErrorCode::InternalError, None, id).into()
  81. }
  82. let response = self.receiver.recv().await.unwrap();
  83. let response = printable_patches(response, true);
  84. JsonResponse::new(json!(response), id).into()
  85. }
  86. // RPCAPI:
  87. // Undo the local changes
  88. // --> {"jsonrpc": "2.0", "method": "restore", "params": [dry, files], "id": 1}
  89. // <-- {"jsonrpc": "2.0", "result": [String, ..], "id": 1}
  90. async fn restore(&self, id: Value, params: &[Value]) -> JsonResult {
  91. let dry = params[0].as_bool().unwrap();
  92. let files: Vec<String> =
  93. params[1].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
  94. let res = self.sender.send(("restore".into(), dry, files)).await.map_err(Error::from);
  95. if let Err(e) = res {
  96. error!("Failed to restore: {}", e);
  97. return JsonError::new(ErrorCode::InternalError, None, id).into()
  98. }
  99. let response = self.receiver.recv().await.unwrap();
  100. let response = printable_patches(response, false);
  101. JsonResponse::new(json!(response), id).into()
  102. }
  103. // RPCAPI:
  104. // Show all patches
  105. // --> {"jsonrpc": "2.0", "method": "log", "params": [dry, files], "id": 1}
  106. // <-- {"jsonrpc": "2.0", "result": [[(String, String)]], "id": 1}
  107. async fn log(&self, id: Value, _params: &[Value]) -> JsonResult {
  108. JsonResponse::new(json!(true), id).into()
  109. }
  110. }