main.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 asyncio, json, random, sys, time
  18. # TODO: this cli is currently unimplemented
  19. class JsonRpc:
  20. async def start(self, server, port):
  21. reader, writer = await asyncio.open_connection(server, port)
  22. self.reader = reader
  23. self.writer = writer
  24. async def stop(self):
  25. self.writer.close()
  26. await self.writer.wait_closed()
  27. async def _make_request(self, method, params):
  28. ident = random.randint(0, 2**16)
  29. print(ident)
  30. request = {
  31. "jsonrpc": "2.0",
  32. "method": method,
  33. "params": params,
  34. "id": ident,
  35. }
  36. message = json.dumps(request) + "\n"
  37. self.writer.write(message.encode())
  38. await self.writer.drain()
  39. data = await self.reader.readline()
  40. message = data.decode().strip()
  41. response = json.loads(message)
  42. print(response)
  43. return response
  44. async def _subscribe(self, method, params):
  45. ident = random.randint(0, 2**16)
  46. request = {
  47. "jsonrpc": "2.0",
  48. "method": method,
  49. "params": params,
  50. "id": ident,
  51. }
  52. message = json.dumps(request) + "\n"
  53. self.writer.write(message.encode())
  54. await self.writer.drain()
  55. print("Subscribed")
  56. async def ping(self):
  57. return await self._make_request("ping", [])
  58. async def dnet_switch(self, state):
  59. return await self._make_request("dnet.switch", [state])
  60. async def dnet_subscribe_events(self):
  61. return await self._subscribe("dnet.subscribe_events", [])
  62. async def main(argv):
  63. # TODO: Rpc port should be command line flag
  64. # e.g. dchat 1066
  65. rpc = JsonRpc()
  66. while True:
  67. try:
  68. await rpc.start("localhost", 26660)
  69. break
  70. except OSError:
  71. pass
  72. await rpc.stop()
  73. asyncio.run(main(sys.argv))