postmsg.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env python3
  2. import logging
  3. from http.server import BaseHTTPRequestHandler, HTTPServer
  4. import configparser
  5. import slixmpp
  6. config = configparser.ConfigParser()
  7. config.read("config.ini") # <--- Read configfile in dictionary
  8. def getRcpt(token): # <--- lookup recipient for token in config
  9. if token in config['RECIPIENT']:
  10. rcpt = config['RECIPIENT'][token]
  11. return rcpt
  12. else:
  13. return "" # <--- empty string / FALSE when no token was found
  14. class S(BaseHTTPRequestHandler):
  15. def _set_response(code):
  16. self.send_header('Content-type', 'text/plain')
  17. self.send_response(code)
  18. self.end_headers()
  19. def do_POST(self):
  20. token = self.headers['Authorization'][-64:]
  21. if token.isalnum():
  22. logging.info('Valid token received.')
  23. content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
  24. post_data = self.rfile.read(content_length) # <--- Gets the data itself
  25. msg = post_data.decode('utf-8')
  26. rcpt = getRcpt(token) # <--- lookup recipient for token in config
  27. if rcpt:
  28. sendMsg(rcpt, msg)
  29. self._set_response(202) # <--- HTTP Accepted, message sent + posibly received
  30. else:
  31. self._set_response(401) # <--- HTTP Unauthorized, no token found
  32. else:
  33. self._set_response(400) # <--- HTTP Bad Request, token contains special characters
  34. class SendMsgBot(slixmpp.ClientXMPP):
  35. def __init__(self, jid, password, recipient, message):
  36. slixmpp.ClientXMPP.__init__(self, jid, password)
  37. self.recipient = recipient
  38. self.msg = message
  39. # Event session_start event is triggered when connection is ready
  40. self.add_event_handler("session_start", self.start)
  41. async def start(self, event):
  42. self.send_message(mto=self.recipient, mbody=self.msg, mtype='chat')
  43. self.disconnect()
  44. def sendMsg(rcpt, msg):
  45. jid = config['ACCOUNT']['jid']
  46. password = config['ACCOUNT']['password']
  47. logging.info('Sending message.')
  48. xmpp = SendMsgBot(jid, password, rcpt, msg)
  49. xmpp.connect()
  50. xmpp.process(forever=False)
  51. del xmpp
  52. def run(server_class=HTTPServer, handler_class=S, port=8080):
  53. server_address = ('', port)
  54. httpd = server_class(server_address, handler_class)
  55. logging.info('Starting server...')
  56. try:
  57. httpd.serve_forever()
  58. except KeyboardInterrupt:
  59. pass
  60. httpd.server_close()
  61. run()