view.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. # This file is part of DarkFi (https://dark.fi)
  2. #
  3. # Copyright (C) 2020-2024 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. import urwid
  18. import logging
  19. import asyncio
  20. import datetime as dt
  21. from src.scroll import ScrollBar, Scrollable
  22. from src.model import Model
  23. class DnetWidget(urwid.WidgetWrap):
  24. def __init__(self, node_name, session):
  25. self.node_name = node_name
  26. self.session = session
  27. def selectable(self):
  28. return True
  29. def keypress(self, size, key):
  30. return key
  31. def update(self, txt):
  32. super().__init__(txt)
  33. self._w = urwid.AttrWrap(self._w, None)
  34. self._w.focus_attr = 'line'
  35. class Node(DnetWidget):
  36. def set_txt(self, is_empty: bool):
  37. if is_empty:
  38. txt = urwid.Text(f"{self.node_name} (offline)")
  39. super().update(txt)
  40. else:
  41. txt = urwid.Text(f"{self.node_name}")
  42. super().update(txt)
  43. class Session(DnetWidget):
  44. def set_txt(self):
  45. txt = urwid.Text(f" {self.session}")
  46. super().update(txt)
  47. class Slot(DnetWidget):
  48. def set_txt(self, i, addr):
  49. self.i = i
  50. if self.session == "outbound-slot":
  51. self.addr = addr[0]
  52. self.id = addr[1]
  53. txt = urwid.Text(f" {self.i}: {self.addr}")
  54. if self.session == "spawn-slot":
  55. self.id = addr
  56. txt = urwid.Text(f" {addr}")
  57. if (self.session == "manual-slot"
  58. or self.session == "seed-slot"
  59. or self.session == "inbound-slot"):
  60. self.addr = addr
  61. txt = urwid.Text(f" {self.addr}")
  62. super().update(txt)
  63. class View():
  64. palette = [
  65. ('body','light gray','default', 'standout'),
  66. ('line','dark cyan','default','standout'),
  67. ]
  68. def __init__(self, model):
  69. self.model = model
  70. info_text = urwid.Text("")
  71. self.pile = urwid.Pile([info_text])
  72. scroll = ScrollBar(Scrollable(self.pile))
  73. rightbox = urwid.LineBox(scroll)
  74. self.listbox_content = []
  75. self.listwalker = urwid.SimpleListWalker(self.listbox_content)
  76. self.listw = self.listwalker.contents
  77. self.list = urwid.ListBox(self.listwalker)
  78. leftbox = urwid.LineBox(self.list)
  79. columns = urwid.Columns([leftbox, rightbox], focus_column=0)
  80. self.ui = urwid.Frame(urwid.AttrWrap( columns, 'body' ))
  81. self.known_outbound = []
  82. self.known_inbound = []
  83. self.known_nodes = []
  84. self.live_nodes = []
  85. self.dead_nodes = []
  86. self.refresh = False
  87. #-----------------------------------------------------------------
  88. # Render dnet.get_info() RPC call
  89. #-----------------------------------------------------------------
  90. def draw_info(self, node_name, info):
  91. #logging.debug('draw_info() [START]')
  92. if 'spawns' in info:
  93. #logging.debug(f'drawing lilith name={node_name} info={info}')
  94. self.draw_lilith(node_name, info)
  95. else:
  96. #logging.debug(f'drawing node name={node_name} info={info}')
  97. node = Node(node_name, "node")
  98. node.set_txt(False)
  99. self.listw.append(node)
  100. if 'outbound' in info and info['outbound']:
  101. session = Session(node_name, "outbound")
  102. session.set_txt()
  103. self.listw.append(session)
  104. for i, addr in info['outbound'].items():
  105. slot = Slot(node_name, "outbound-slot")
  106. slot.set_txt(i, addr)
  107. self.listw.append(slot)
  108. if 'inbound' in info and info['inbound']:
  109. if any(info['inbound'].values()):
  110. session = Session(node_name, "inbound")
  111. session.set_txt()
  112. self.listw.append(session)
  113. for i, addr in info['inbound'].items():
  114. if bool(addr):
  115. slot = Slot(node_name, "inbound-slot")
  116. slot.set_txt(i, addr)
  117. self.listw.append(slot)
  118. if 'manual' in info and info['manual']:
  119. session = Session(node_name, "manual")
  120. session.set_txt()
  121. self.listw.append(session)
  122. for i, addr in info['manual'].items():
  123. slot = Slot(node_name, "manual-slot")
  124. slot.set_txt(i, addr)
  125. self.listw.append(slot)
  126. if 'seed' in info and info['seed']:
  127. session = Session(node_name, "seed")
  128. session.set_txt()
  129. self.listw.append(session)
  130. for i, info in info['seed'].items():
  131. slot = Slot(node_name, "seed-slot")
  132. slot.set_txt(i, addr)
  133. self.listw.append(slot)
  134. def draw_lilith(self, node_name, info):
  135. node = Node(node_name, "lilith-node")
  136. node.set_txt(False)
  137. self.listw.append(node)
  138. for (i, key) in enumerate(info['spawns'].keys()):
  139. slot = Slot(node_name, "spawn-slot")
  140. slot.set_txt(i, key)
  141. self.listw.append(slot)
  142. def draw_empty(self, node_name, info):
  143. node = Node(node_name, "node")
  144. node.set_txt(True)
  145. self.listw.append(node)
  146. #-----------------------------------------------------------------
  147. # Render dnet.subscribe_events() RPC call
  148. # Left hand panel only
  149. #-----------------------------------------------------------------
  150. def fill_left_box(self):
  151. live_inbound = []
  152. new_inbound= {}
  153. for index, item in enumerate(self.listw):
  154. # Update outbound slot info
  155. if item.session == "outbound-slot":
  156. key = (f"{item.node_name}", f"{item.i}")
  157. if key in self.model.nodes[item.node_name]['event']:
  158. info = self.model.nodes[item.node_name]['event'].get(key)
  159. slot = Slot(item.node_name, item.session)
  160. slot.set_txt(item.i, info)
  161. self.listw[index] = slot
  162. #-----------------------------------------------------------------
  163. # Render lilith.spawns() RPC call
  164. # Right hand panel only
  165. #-----------------------------------------------------------------
  166. def fill_lilith_right_box(self):
  167. self.pile.contents.clear()
  168. focus_w = self.list.get_focus()
  169. if focus_w[0] is None:
  170. return
  171. session = focus_w[0].session
  172. if session == "spawn-slot":
  173. node_name = focus_w[0].node_name
  174. spawn_name = focus_w[0].id
  175. lilith = self.model.liliths.get(node_name)
  176. spawns = lilith.get('spawns')
  177. info = spawns.get(spawn_name)
  178. if info['urls']:
  179. urls = info['urls']
  180. self.pile.contents.append((urwid.Text(
  181. f"Accept addrs:"),
  182. self.pile.options()))
  183. for url in urls:
  184. self.pile.contents.append((urwid.Text(
  185. f" {url}"),
  186. self.pile.options()))
  187. if info['whitelist']:
  188. whitelist = info['whitelist']
  189. self.pile.contents.append((urwid.Text(
  190. f"Whitelist:"),
  191. self.pile.options()))
  192. for host in whitelist:
  193. self.pile.contents.append((urwid.Text(
  194. f" {host}"),
  195. self.pile.options()))
  196. if info['greylist']:
  197. greylist = info['greylist']
  198. self.pile.contents.append((urwid.Text(
  199. f"Greylist:"),
  200. self.pile.options()))
  201. for host in greylist:
  202. self.pile.contents.append((urwid.Text(
  203. f" {host}"),
  204. self.pile.options()))
  205. if info['goldlist']:
  206. goldlist = info['goldlist']
  207. self.pile.contents.append((urwid.Text(
  208. f"Goldlist:"),
  209. self.pile.options()))
  210. for host in goldlist:
  211. self.pile.contents.append((urwid.Text(
  212. f" {host}"),
  213. self.pile.options()))
  214. #-----------------------------------------------------------------
  215. # Render dnet.subscribe_events() RPC call
  216. # Right hand menu only
  217. #-----------------------------------------------------------------
  218. def fill_right_box(self):
  219. self.pile.contents.clear()
  220. focus_w = self.list.get_focus()
  221. if focus_w[0] is None:
  222. return
  223. session = focus_w[0].session
  224. if session == "outbound":
  225. key = (focus_w[0].node_name, "outbound")
  226. info = self.model.nodes.get(focus_w[0].node_name)
  227. if key in info['event']:
  228. ev = info['event'].get(key)
  229. self.pile.contents.append((
  230. urwid.Text(f" {ev}"),
  231. self.pile.options()))
  232. if (session == "outbound-slot" or session == "inbound-slot"
  233. or session == "manual-slot" or session == "seed-slot"):
  234. addr = focus_w[0].addr
  235. node_name = focus_w[0].node_name
  236. info = self.model.nodes.get(node_name)
  237. if addr in info['msgs']:
  238. msg = info['msgs'].get(addr)
  239. for m in msg:
  240. time = m[0]
  241. event = m[1]
  242. msg = m[2]
  243. self.pile.contents.append((urwid.Text(
  244. f"{time}: {event}: {msg}"),
  245. self.pile.options()))
  246. if session == "spawn-slot":
  247. node_name = focus_w[0].node_name
  248. spawn_name = focus_w[0].id
  249. lilith = self.model.liliths.get(node_name)
  250. spawns = lilith.get('spawns')
  251. info = spawns.get(spawn_name)
  252. if info['urls']:
  253. urls = info['urls']
  254. self.pile.contents.append((urwid.Text(
  255. f"Accept addrs:"),
  256. self.pile.options()))
  257. for url in urls:
  258. self.pile.contents.append((urwid.Text(
  259. f" {url}"),
  260. self.pile.options()))
  261. if info['whitelist']:
  262. whitelist = info['whitelist']
  263. self.pile.contents.append((urwid.Text(
  264. f"Whitelist:"),
  265. self.pile.options()))
  266. for host in whitelist:
  267. self.pile.contents.append((urwid.Text(
  268. f" {host}"),
  269. self.pile.options()))
  270. if info['greylist']:
  271. greylist = info['greylist']
  272. self.pile.contents.append((urwid.Text(
  273. f"Greylist:"),
  274. self.pile.options()))
  275. for host in greylist:
  276. self.pile.contents.append((urwid.Text(
  277. f" {host}"),
  278. self.pile.options()))
  279. if info['goldlist']:
  280. goldlist = info['goldlist']
  281. self.pile.contents.append((urwid.Text(
  282. f"Goldlist:"),
  283. self.pile.options()))
  284. for host in goldlist:
  285. self.pile.contents.append((urwid.Text(
  286. f" {host}"),
  287. self.pile.options()))
  288. #-----------------------------------------------------------------
  289. # Sort through node info, checking whether we are already
  290. # tracking this node or if the node's state has changed.
  291. #-----------------------------------------------------------------
  292. def sort(self, nodes):
  293. for name, info in nodes:
  294. if bool(info) and name not in self.live_nodes:
  295. self.live_nodes.append(name)
  296. if not bool(info) and name not in self.dead_nodes:
  297. self.dead_nodes.append(name)
  298. if bool(info) and name in self.dead_nodes:
  299. logging.debug("Refresh: dead node online.")
  300. self.refresh = True
  301. if not bool(info) and name in self.live_nodes:
  302. logging.debug("Refresh: online node offline.")
  303. self.refresh = True
  304. #-----------------------------------------------------------------
  305. # Checks whether we are already displaying this node, and draw
  306. # it if not.
  307. #-----------------------------------------------------------------
  308. async def display(self, nodes):
  309. for name, info in nodes:
  310. if name in self.live_nodes and name not in self.known_nodes:
  311. self.draw_info(name, info)
  312. if name in self.dead_nodes and name not in self.known_nodes:
  313. self.draw_empty(name, info)
  314. if self.refresh:
  315. logging.debug("Refresh initiated.")
  316. await asyncio.sleep(0.1)
  317. self.known_outbound.clear()
  318. self.known_inbound.clear()
  319. self.known_nodes.clear()
  320. self.live_nodes.clear()
  321. self.dead_nodes.clear()
  322. self.refresh = False
  323. self.listw.clear()
  324. logging.debug("Refresh complete.")
  325. #-----------------------------------------------------------------
  326. # Handle events.
  327. #-----------------------------------------------------------------
  328. def draw_events(self, nodes):
  329. for name, info in nodes:
  330. if bool(info) and name in self.known_nodes:
  331. self.fill_left_box()
  332. self.fill_right_box()
  333. if 'inbound' in info:
  334. # New inbound online.
  335. for key in info['inbound'].keys():
  336. if key not in self.known_inbound:
  337. addr = info['inbound'].get(key)
  338. if not bool(addr) or not addr == None:
  339. continue
  340. logging.debug(f"Refresh: inbound {key} online")
  341. self.refresh = True
  342. # Known inbound offline.
  343. for key in self.known_inbound:
  344. addr = info['inbound'].get(key)
  345. if bool(addr) or addr == None:
  346. continue
  347. logging.debug(f"Refresh: inbound {key} offline")
  348. self.refresh = True
  349. # New outbound online.
  350. if 'outbound' in info:
  351. for i, info in info['outbound'].items():
  352. addr = info[0]
  353. id = info[1]
  354. if id == 0:
  355. continue
  356. if id in self.known_outbound:
  357. continue
  358. logging.debug(f"Outbound {i}, {addr} came online.")
  359. self.refresh = True
  360. async def update_view(self, evloop: asyncio.AbstractEventLoop,
  361. loop: urwid.MainLoop):
  362. while True:
  363. await asyncio.sleep(0.1)
  364. nodes = self.model.nodes.items()
  365. liliths = self.model.liliths.items()
  366. evloop.call_soon(loop.draw_screen)
  367. # We first ensure that we are keeping track
  368. # of all the displayed widgets.
  369. for index, item in enumerate(self.listw):
  370. # Keep track of known nodes.
  371. if item.node_name not in self.known_nodes:
  372. self.known_nodes.append(item.node_name)
  373. # Keep track of known inbounds.
  374. if (item.session == "inbound-slot"
  375. and item.i not in self.known_inbound):
  376. self.known_inbound.append(item.i)
  377. # Keep track of known outbounds.
  378. if (item.session == "outbound-slot"
  379. and item.id not in self.known_outbound
  380. and not item.id == 0):
  381. self.known_outbound.append(item.id)
  382. self.sort(nodes)
  383. self.sort(liliths)
  384. await self.display(nodes)
  385. await self.display(liliths)
  386. self.fill_lilith_right_box()
  387. self.draw_events(nodes)