main.rs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. use darkfi::{
  2. error::{Error, Result},
  3. rpc::{jsonrpc, jsonrpc::JsonResult},
  4. util::async_util,
  5. };
  6. use async_std::sync::{Arc, Mutex};
  7. use easy_parallel::Parallel;
  8. use log::debug;
  9. use serde_json::{json, Value};
  10. use smol::Executor;
  11. use std::{io, io::Read};
  12. use termion::{async_stdin, event::Key, input::TermRead, raw::IntoRawMode};
  13. use tui::{
  14. backend::{Backend, TermionBackend},
  15. Terminal,
  16. };
  17. use map::{
  18. model::{IdList, InfoList, NodeInfo},
  19. ui,
  20. view::{IdListView, InfoListView},
  21. Model, View,
  22. };
  23. struct Map {
  24. url: String,
  25. }
  26. impl Map {
  27. pub fn new(url: String) -> Self {
  28. Self { url }
  29. }
  30. async fn request(&self, r: jsonrpc::JsonRequest) -> Result<Value> {
  31. let reply: JsonResult = match jsonrpc::send_request(&self.url, json!(r)).await {
  32. Ok(v) => v,
  33. Err(e) => return Err(e),
  34. };
  35. match reply {
  36. JsonResult::Resp(r) => {
  37. debug!(target: "RPC", "<-- {}", serde_json::to_string(&r)?);
  38. Ok(r.result)
  39. }
  40. JsonResult::Err(e) => {
  41. debug!(target: "RPC", "<-- {}", serde_json::to_string(&e)?);
  42. Err(Error::JsonRpcError(e.error.message.to_string()))
  43. }
  44. JsonResult::Notif(n) => {
  45. debug!(target: "RPC", "<-- {}", serde_json::to_string(&n)?);
  46. Err(Error::JsonRpcError("Unexpected reply".to_string()))
  47. }
  48. }
  49. }
  50. // --> {"jsonrpc": "2.0", "method": "say_hello", "params": [], "id": 42}
  51. // <-- {"jsonrpc": "2.0", "result": "hello world", "id": 42}
  52. async fn _say_hello(&self) -> Result<Value> {
  53. let req = jsonrpc::request(json!("say_hello"), json!([]));
  54. Ok(self.request(req).await?)
  55. }
  56. //--> {"jsonrpc": "2.0", "method": "poll", "params": [], "id": 42}
  57. // <-- {"jsonrpc": "2.0", "result": {"nodeID": [], "nodeinfo" [], "id": 42}
  58. async fn get_info(&self) -> Result<Value> {
  59. let req = jsonrpc::request(json!("get_info"), json!([]));
  60. Ok(self.request(req).await?)
  61. }
  62. }
  63. #[async_std::main]
  64. async fn main() -> Result<()> {
  65. let stdout = io::stdout().into_raw_mode()?;
  66. let backend = TermionBackend::new(stdout);
  67. let mut terminal = Terminal::new(backend)?;
  68. terminal.clear()?;
  69. let infos = vec![NodeInfo::new()];
  70. //let infos = vec![
  71. // NodeInfo {
  72. // id: "0385048034sodisofjhosd1111q3434".to_string(),
  73. // connections: 10,
  74. // is_active: true,
  75. // last_message: "hey how are you?".to_string(),
  76. // },
  77. // NodeInfo {
  78. // id: "09w30we9wsnfksdfkdjflsjkdfjdfsd".to_string(),
  79. // connections: 5,
  80. // is_active: false,
  81. // last_message: "lmao".to_string(),
  82. // },
  83. // NodeInfo {
  84. // id: "038043325alsdlasjfrsdfsdfsdjsdf".to_string(),
  85. // connections: 7,
  86. // is_active: true,
  87. // last_message: "gm".to_string(),
  88. // },
  89. // NodeInfo {
  90. // id: "04985034953ldflsdjflsdjflsdjfii".to_string(),
  91. // connections: 2,
  92. // is_active: true,
  93. // last_message: "hihi".to_string(),
  94. // },
  95. // NodeInfo {
  96. // id: "09850249352asdjapsdikalskasdkas".to_string(),
  97. // connections: 10,
  98. // is_active: true,
  99. // last_message: "wtf".to_string(),
  100. // },
  101. //];
  102. let info_list = InfoList::new(infos.clone());
  103. let ids = vec![String::new()];
  104. let id_list = IdList::new(ids);
  105. let model = Arc::new(Model::new(id_list, info_list));
  106. //let model = Model::new(id_list, info_list);
  107. let nthreads = num_cpus::get();
  108. let (signal, shutdown) = async_channel::unbounded::<()>();
  109. let ex = Arc::new(Executor::new());
  110. let ex2 = ex.clone();
  111. let (_, result) = Parallel::new()
  112. .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  113. // Run the main future on the current thread.
  114. .finish(|| {
  115. smol::future::block_on(async move {
  116. run_rpc(ex2.clone(), model.clone()).await?;
  117. render(&mut terminal, model.clone()).await?;
  118. drop(signal);
  119. Ok::<(), darkfi::Error>(())
  120. })
  121. });
  122. result
  123. }
  124. async fn run_rpc(ex: Arc<Executor<'_>>, model: Arc<Model>) -> Result<()> {
  125. let client = Map::new("tcp://127.0.0.1:8000".to_string());
  126. ex.spawn(poll(client, model)).detach();
  127. Ok(())
  128. }
  129. async fn poll(client: Map, model: Arc<Model>) -> Result<()> {
  130. loop {
  131. let reply = client.get_info().await?;
  132. if reply.as_object().is_some() && !reply.as_object().unwrap().is_empty() {
  133. let nodes = reply.as_object().unwrap().get("nodes").unwrap();
  134. // todo: generalize this
  135. let node1 = &nodes[0];
  136. //let node2 = &nodes[1];
  137. //let node3 = &nodes[2];
  138. // TODO: error handling
  139. let infos = vec![NodeInfo {
  140. id: node1["id"].to_string(),
  141. connections: node1["connections"].as_u64().unwrap() as usize,
  142. is_active: node1["is_active"].as_bool().unwrap(),
  143. last_message: node1["message"].to_string(),
  144. }];
  145. //model.update(infos).await;
  146. for node in infos {
  147. model.id_list.node_id.lock().await.push(node.id);
  148. //self.info_list.infos.lock().await.push(node.info);
  149. //self.id_list.
  150. }
  151. } else {
  152. // TODO: error handling
  153. println!("Reply is an error");
  154. }
  155. async_util::sleep(1).await;
  156. }
  157. }
  158. async fn render<B: Backend>(terminal: &mut Terminal<B>, model: Arc<Model>) -> io::Result<()> {
  159. let mut asi = async_stdin();
  160. terminal.clear()?;
  161. let mut info_vec = Vec::new();
  162. for info in model.info_list.infos.lock().await.clone() {
  163. info_vec.push(info)
  164. }
  165. let mut id_vec = Vec::new();
  166. for id in model.id_list.node_id.lock().await.clone() {
  167. id_vec.push(id)
  168. }
  169. let id_list = IdListView::new(id_vec);
  170. let info_list = InfoListView::new(info_vec);
  171. let mut view = View::new(id_list, info_list);
  172. view.id_list.state.select(Some(0));
  173. view.info_list.index = 0;
  174. loop {
  175. terminal.draw(|f| {
  176. ui::ui(f, view.clone());
  177. })?;
  178. for k in asi.by_ref().keys() {
  179. match k.unwrap() {
  180. Key::Char('q') => {
  181. terminal.clear()?;
  182. return Ok(())
  183. }
  184. Key::Char('j') => {
  185. view.id_list.next();
  186. view.info_list.next().await;
  187. }
  188. Key::Char('k') => {
  189. view.id_list.previous();
  190. view.info_list.previous().await;
  191. }
  192. _ => (),
  193. }
  194. }
  195. }
  196. }