Просмотр исходного кода

script/dnet: create main.py and fix rpc to work with urwid async pattern

lunar-mining 2 лет назад
Родитель
Сommit
fa43710994
3 измененных файлов с 90 добавлено и 85 удалено
  1. 85 0
      script/dnet/main.py
  2. 4 66
      script/dnet/rpc.py
  3. 1 19
      script/dnet/view.py

+ 85 - 0
script/dnet/main.py

@@ -0,0 +1,85 @@
+# This file is part of DarkFi (https://dark.fi)
+#
+# Copyright (C) 2020-2023 Dyne.org foundation
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program.  If not, see <https://www.gnu.org/licenses/>.
+
+import sys
+import urwid
+import asyncio
+
+from rpc import JsonRpc
+from view import Dnetview
+
+async def get_info(rpc):
+    while True:
+        try:
+            await rpc.start("localhost", 26660)
+            break
+        except OSError:
+            pass
+
+    response = await rpc._make_request("p2p.get_info", [])
+    info = response["result"]
+    channels = info["channels"]
+    channel_lookup = {}
+    for channel in channels:
+        id = channel["id"]
+        channel_lookup[id] = channel
+
+    #print("inbound:")
+    for channel in channels:
+        if channel["session"] != "inbound":
+            continue
+        url = channel["url"]
+        #print(f"  {url}")
+
+    #print("outbound:")
+    for i, id in enumerate(info["outbound_slots"]):
+        if id == 0:
+            #print(f"  {i}: none")
+            continue
+
+        assert id in channel_lookup
+        url = channel_lookup[id]["url"]
+        #print(f"  {i}: {url}")
+
+    #print("seed:")
+    for channel in channels:
+        if channel["session"] != "seed":
+            continue
+        url = channel["url"]
+        #print(f"  {url}")
+
+    #print("manual:")
+    for channel in channels:
+        if channel["session"] != "manual":
+            continue
+        url = channel["url"]
+        #print(f"  {url}")
+
+    await rpc.stop()
+
+if __name__ == '__main__':
+    ev = asyncio.get_event_loop()
+
+    rpc = JsonRpc()
+    ev.create_task(get_info(rpc))
+
+    dnet = Dnetview()
+    ev.create_task(dnet.render_info())
+
+    loop = urwid.MainLoop(dnet.view, dnet.palette,
+        event_loop=urwid.AsyncioEventLoop(loop=ev))
+    loop.run()

+ 4 - 66
script/dnet/rpc.py

@@ -14,11 +14,10 @@
 #
 # You should have received a copy of the GNU Affero General Public License
 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
-import asyncio, json, random, sys, time
 
+import asyncio, json, random, time
 
 class JsonRpc:
-
     async def start(self, server, port):
         reader, writer = await asyncio.open_connection(server, port)
         self.reader = reader
@@ -30,7 +29,7 @@ class JsonRpc:
 
     async def _make_request(self, method, params):
         ident = random.randint(0, 2**16)
-        print(ident)
+        #print(ident)
         request = {
             "jsonrpc": "2.0",
             "method": method,
@@ -45,7 +44,7 @@ class JsonRpc:
         data = await self.reader.readline()
         message = data.decode().strip()
         response = json.loads(message)
-        print(response)
+        #print(response)
         return response
 
     async def _subscribe(self, method, params):
@@ -60,7 +59,7 @@ class JsonRpc:
         message = json.dumps(request) + "\n"
         self.writer.write(message.encode())
         await self.writer.drain()
-        print("Subscribed")
+        #print("Subscribed")
 
     async def ping(self):
         return await self._make_request("ping", [])
@@ -72,64 +71,3 @@ class JsonRpc:
         return await self._subscribe("dnet.subscribe_events", [])
 
 
-#async def main(argv):
-#    rpc = JsonRpc()
-#    while True:
-#        try:
-#            await rpc.start("localhost", 26660)
-#            break
-#        except OSError:
-#            pass
-#    await rpc.dnet_switch(True)
-#    await rpc.dnet_subscribe_events()
-#
-#    while True:
-#        data = await rpc.reader.readline()
-#        #with open("rpclog", "a") as f:
-#        #    f.write(data.decode())
-#        data = json.loads(data)
-#
-#        params = data["params"][0]
-#        ev = params["event"]
-#        if ev in ["send", "recv"]:
-#            continue
-#        info = params["info"]
-#
-#        t = time.localtime()
-#        current_time = time.strftime("%H:%M:%S", t)
-#
-#        match ev:
-#            case "inbound_connected":
-#                addr = info["addr"]
-#                print(f"{current_time}  inbound (connect):    {addr}")
-#            case "inbound_disconnected":
-#                addr = info["addr"]
-#                print(f"{current_time}  inbound (disconnect): {addr}")
-#            case "outbound_slot_sleeping":
-#                slot = info["slot"]
-#                print(f"{current_time}  slot {slot}: sleeping")
-#            case "outbound_slot_connecting":
-#                slot = info["slot"]
-#                addr = info["addr"]
-#                print(f"{current_time}  slot {slot}: connecting   addr={addr}")
-#            case "outbound_slot_connected":
-#                slot = info["slot"]
-#                addr = info["addr"]
-#                channel_id = info["channel_id"]
-#                print(f"{current_time}  slot {slot}: connected    addr={addr}")
-#            case "outbound_slot_disconnected":
-#                slot = info["slot"]
-#                err = info["err"]
-#                print(f"{current_time}  slot {slot}: disconnected err='{err}'")
-#            case "outbound_peer_discovery":
-#                attempt = info["attempt"]
-#                state = info["state"]
-#                print(f"{current_time}  peer_discovery: {state} (attempt {attempt})")
-#        #print(data)
-#
-#    await rpc.dnet_switch(False)
-#    await rpc.stop()
-#
-#
-#asyncio.run(main(sys.argv))
-

+ 1 - 19
script/dnet/view.py

@@ -17,7 +17,7 @@
 
 import urwid
 import asyncio
-import time
+
 from scroll import ScrollBar, Scrollable
 
 event_loop = asyncio.get_event_loop()
@@ -123,12 +123,6 @@ class Dnetview():
         columns = urwid.Columns([leftbox, rightbox], focus_column=0)
         self.view = urwid.Frame(urwid.AttrWrap( columns, 'body' ))
 
-    def main(self):
-        event_loop.create_task(self.render_info())
-        loop = urwid.MainLoop(self.view, self.palette,
-            event_loop=urwid.AsyncioEventLoop(loop=event_loop))
-        loop.run()
-
     async def render_info(self):
         while True:
             await asyncio.sleep(0.1)
@@ -141,15 +135,3 @@ class Dnetview():
                     self.pile.contents.append((urwid.Text("2"), self.pile.options()))
                 case "ConnectView":
                     self.pile.contents.append((urwid.Text("3"), self.pile.options()))
-    
-if __name__ == '__main__':
-    dnet = Dnetview()
-    dnet.main()
-
-
-
-
-
-
-
-