main.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env python
  2. """
  3. wifi-with-matrix script.
  4. Bridge between https://code.ffdn.org/FFDN/wifi-with-me & a matrix room
  5. Needs the following environment variables:
  6. - MMW_BOT_MATRIX_URL: the url of the matrix homeserver
  7. - MMW_BOT_MATRIX_ID: the user id of the bot on this server
  8. - MMW_BOT_MATRIX_PW: the password for this user
  9. - MMW_BOT_ROOM_ID: the room on which send the notifications
  10. """
  11. import json
  12. import os
  13. from http.server import BaseHTTPRequestHandler, HTTPServer
  14. from matrix_client.client import MatrixClient
  15. SERVER_ADDRESS = ('', int(os.environ.get('MMW_BOT_PORT', 4785)))
  16. MATRIX_URL = os.environ.get('MMW_BOT_MATRIX_URL', 'https://matrix.org')
  17. MATRIX_ID = os.environ.get('MMW_BOT_MATRIX_ID', 'wwm')
  18. MATRIX_PW = os.environ['MMW_BOT_MATRIX_PW']
  19. ROOM_ID = os.environ['MMW_BOT_ROOM_ID']
  20. class WWMBotServer(HTTPServer):
  21. """
  22. an HTTPServer that also contain a matrix client
  23. """
  24. def __init__(self, *args, **kwargs):
  25. super().__init__(*args, **kwargs)
  26. self.matrix_client = MatrixClient(MATRIX_URL)
  27. self.matrix_token = self.matrix_client.login(username=MATRIX_ID, password=MATRIX_PW)
  28. self.matrix_room = self.matrix_client.get_rooms()[ROOM_ID]
  29. class WWMBotForwarder(BaseHTTPRequestHandler):
  30. """
  31. Class given to the server, st. it knows what to do with a request.
  32. This one handles the HTTP request, and forwards it to the matrix room.
  33. """
  34. def do_POST(self):
  35. """
  36. main method, get a json dict from wifi-with-me, send a message to a matrix room
  37. """
  38. length = int(self.headers.get('Content-Length'))
  39. data = json.loads(self.rfile.read(length).decode())
  40. name, url = data['name'], data['url']
  41. self.server.matrix_room.send_text(f'Nouvelle demande de {name}: {url}')
  42. self.ret_ok()
  43. def ret_ok(self):
  44. """
  45. return a success status
  46. """
  47. self.send_response(200)
  48. self.send_header('Content-Type', 'application/json')
  49. self.end_headers()
  50. self.wfile.write(b"{'status': 'OK'}")
  51. if __name__ == '__main__':
  52. WWMBotServer(SERVER_ADDRESS, WWMBotForwarder).serve_forever()