view.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. import urwid
  18. import logging
  19. import asyncio
  20. import datetime as dt
  21. from scroll import ScrollBar, Scrollable
  22. from 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 len(self.i) == 1:
  51. self.addr = addr[0]
  52. self.id = addr[1]
  53. txt = urwid.Text(f" {self.i}: {self.addr}")
  54. else:
  55. self.addr = addr
  56. txt = urwid.Text(f" {self.addr}")
  57. super().update(txt)
  58. class View():
  59. palette = [
  60. ('body','light gray','default', 'standout'),
  61. ('line','dark cyan','default','standout'),
  62. ]
  63. def __init__(self, model):
  64. self.model = model
  65. info_text = urwid.Text("")
  66. self.pile = urwid.Pile([info_text])
  67. scroll = ScrollBar(Scrollable(self.pile))
  68. rightbox = urwid.LineBox(scroll)
  69. self.listbox_content = []
  70. self.listwalker = urwid.SimpleListWalker(self.listbox_content)
  71. self.list = urwid.ListBox(self.listwalker)
  72. leftbox = urwid.LineBox(self.list)
  73. columns = urwid.Columns([leftbox, rightbox], focus_column=0)
  74. self.ui = urwid.Frame(urwid.AttrWrap( columns, 'body' ))
  75. #-----------------------------------------------------------------
  76. # Render get_info()
  77. #-----------------------------------------------------------------
  78. def draw_info(self, node_name, info):
  79. node = Node(node_name, "node")
  80. node.set_txt(False)
  81. self.listwalker.contents.append(node)
  82. if 'outbound' in info and info['outbound']:
  83. session = Session(node_name, "outbound")
  84. session.set_txt()
  85. self.listwalker.contents.append(session)
  86. for i, addr in info['outbound'].items():
  87. slot = Slot(node_name, "outbound-slot")
  88. slot.set_txt(i, addr)
  89. self.listwalker.contents.append(slot)
  90. if 'inbound' in info and info['inbound']:
  91. if any(info['inbound'].values()):
  92. session = Session(node_name, "inbound")
  93. session.set_txt()
  94. self.listwalker.contents.append(session)
  95. for i, addr in info['inbound'].items():
  96. if bool(addr):
  97. slot = Slot(node_name, "inbound-slot")
  98. slot.set_txt(i, addr)
  99. self.listwalker.contents.append(slot)
  100. if 'manual' in info and info['manual']:
  101. session = Session(node_name, "manual")
  102. session.set_txt()
  103. self.listwalker.contents.append(session)
  104. for i, addr in info['manual'].items():
  105. slot = Slot(node_name, "manual-slot")
  106. slot.set_txt(i, addr)
  107. self.listwalker.contents.append(slot)
  108. if 'seed' in info and info['seed']:
  109. session = Session(node_name, "seed")
  110. session.set_txt()
  111. self.listwalker.contents.append(session)
  112. for i, info in info['seed'].items():
  113. slot = Slot(node_name, "seed-slot")
  114. slot.set_txt(i, addr)
  115. self.listwalker.contents.append(slot)
  116. def draw_empty(self, node_name, info):
  117. node = Node(node_name, "node")
  118. node.set_txt(True)
  119. self.listwalker.contents.append(node)
  120. #-----------------------------------------------------------------
  121. # Render subscribe_events() (left menu)
  122. #-----------------------------------------------------------------
  123. def fill_left_box(self):
  124. live_inbound = []
  125. new_inbound= {}
  126. for index, item in enumerate(self.listwalker.contents):
  127. # Update outbound slot info
  128. if item.session == "outbound-slot":
  129. key = (f"{item.node_name}", f"{item.i}")
  130. if key in self.model.nodes[item.node_name]['event']:
  131. info = self.model.nodes[item.node_name]['event'].get(key)
  132. slot = Slot(item.node_name, item.session)
  133. slot.set_txt(item.i, info)
  134. self.listwalker.contents[index] = slot
  135. #-----------------------------------------------------------------
  136. # Render subscribe_events() (right menu)
  137. #-----------------------------------------------------------------
  138. def fill_right_box(self):
  139. self.pile.contents.clear()
  140. focus_w = self.list.get_focus()
  141. if focus_w[0] is None:
  142. return
  143. session = focus_w[0].session
  144. if session == "outbound":
  145. key = (focus_w[0].node_name, "outbound")
  146. info = self.model.nodes.get(focus_w[0].node_name)
  147. if key in info['event']:
  148. ev = info['event'].get(key)
  149. self.pile.contents.append((
  150. urwid.Text(f" {ev}"),
  151. self.pile.options()))
  152. if (session == "outbound-slot" or session == "inbound-slot"
  153. or session == "manual-slot" or session == "seed-slot"):
  154. addr = focus_w[0].addr
  155. node_name = focus_w[0].node_name
  156. info = self.model.nodes.get(node_name)
  157. if addr in info['msgs']:
  158. msg = info['msgs'].get(addr)
  159. for m in msg:
  160. time = m[0]
  161. event = m[1]
  162. msg = m[2]
  163. self.pile.contents.append((urwid.Text(
  164. f"{time}: {event}: {msg}"),
  165. self.pile.options()))
  166. async def update_view(self, evloop: asyncio.AbstractEventLoop,
  167. loop: urwid.MainLoop):
  168. live_nodes = []
  169. dead_nodes = []
  170. known_nodes = []
  171. known_inbound = []
  172. known_outbound = []
  173. refresh = False
  174. while True:
  175. await asyncio.sleep(0.1)
  176. nodes = self.model.nodes.items()
  177. listw = self.listwalker.contents
  178. evloop.call_soon(loop.draw_screen)
  179. for index, item in enumerate(listw):
  180. # Keep track of known nodes.
  181. if item.node_name not in known_nodes:
  182. known_nodes.append(item.node_name)
  183. # Keep track of known inbounds.
  184. if (item.session == "inbound-slot"
  185. and item.i not in known_inbound):
  186. known_inbound.append(item.i)
  187. # Keep track of known outbounds.
  188. if (item.session == "outbound-slot"
  189. and item.id not in known_outbound
  190. and not item.id == 0):
  191. known_outbound.append(item.id)
  192. for name, info in nodes:
  193. # 1. Sort nodes into lists.
  194. if bool(info) and name not in live_nodes:
  195. live_nodes.append(name)
  196. if not bool(info) and name not in dead_nodes:
  197. dead_nodes.append(name)
  198. if bool(info) and name in dead_nodes:
  199. logging.debug("Refresh: dead node online.")
  200. refresh = True
  201. if not bool(info) and name in live_nodes:
  202. logging.debug("Refresh: online node offline.")
  203. refresh = True
  204. # 2. Display nodes according to list.
  205. if name in live_nodes and name not in known_nodes:
  206. self.draw_info(name, info)
  207. if name in dead_nodes and name not in known_nodes:
  208. self.draw_empty(name, info)
  209. if refresh:
  210. logging.debug("Refresh initiated.")
  211. await asyncio.sleep(0.1)
  212. known_outbound.clear()
  213. known_inbound.clear()
  214. known_nodes.clear()
  215. live_nodes.clear()
  216. dead_nodes.clear()
  217. refresh = False
  218. listw.clear()
  219. logging.debug("Refresh complete.")
  220. # 3. Handle events on nodes we know.
  221. if bool(info) and name in known_nodes:
  222. self.fill_left_box()
  223. self.fill_right_box()
  224. if 'inbound' in info:
  225. for key in info['inbound'].keys():
  226. # New inbound online.
  227. if key not in known_inbound:
  228. addr = info['inbound'].get(key)
  229. if bool(addr):
  230. logging.debug(f"Refresh: inbound {key} online")
  231. refresh = True
  232. # Known inbound offline.
  233. for key in known_inbound:
  234. addr = info['inbound'].get(key)
  235. if bool(addr):
  236. continue
  237. logging.debug(f"Refresh: inbound {key} offline")
  238. refresh = True
  239. # New outbound online.
  240. if 'outbound' in info:
  241. for i, info in info['outbound'].items():
  242. addr = info[0]
  243. id = info[1]
  244. if id == 0:
  245. continue
  246. if id in known_outbound:
  247. continue
  248. logging.debug(f"Outbound {i}, {addr} came online.")
  249. refresh = True