123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- #!/usr/bin/env python3
- import logging
- from http.server import BaseHTTPRequestHandler, HTTPServer
- import configparser
- import slixmpp
- config = configparser.ConfigParser()
- config.read("config.ini") # <--- Read configfile in dictionary
- def getRcpt(token): # <--- lookup recipient for token in config
- if token in config['RECIPIENT']:
- rcpt = config['RECIPIENT'][token]
- return rcpt
- else:
- return "" # <--- empty string / FALSE when no token was found
- class S(BaseHTTPRequestHandler):
- def _set_response(code):
- self.send_header('Content-type', 'text/plain')
- self.send_response(code)
- self.end_headers()
- def do_POST(self):
- token = self.headers['Authorization'][-64:]
- if token.isalnum():
- logging.info('Valid token received.')
- content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
- post_data = self.rfile.read(content_length) # <--- Gets the data itself
- msg = post_data.decode('utf-8')
- rcpt = getRcpt(token) # <--- lookup recipient for token in config
- if rcpt:
- sendMsg(rcpt, msg)
- self._set_response(202) # <--- HTTP Accepted, message sent + posibly received
- else:
- self._set_response(401) # <--- HTTP Unauthorized, no token found
- else:
- self._set_response(400) # <--- HTTP Bad Request, token contains special characters
- class SendMsgBot(slixmpp.ClientXMPP):
- def __init__(self, jid, password, recipient, message):
- slixmpp.ClientXMPP.__init__(self, jid, password)
- self.recipient = recipient
- self.msg = message
- # Event session_start event is triggered when connection is ready
- self.add_event_handler("session_start", self.start)
- async def start(self, event):
- self.send_message(mto=self.recipient, mbody=self.msg, mtype='chat')
- self.disconnect()
- def sendMsg(rcpt, msg):
- jid = config['ACCOUNT']['jid']
- password = config['ACCOUNT']['password']
- logging.info('Sending message.')
- xmpp = SendMsgBot(jid, password, rcpt, msg)
- xmpp.connect()
- xmpp.process(forever=False)
- del xmpp
-
- def run(server_class=HTTPServer, handler_class=S, port=8080):
- server_address = ('', port)
- httpd = server_class(server_address, handler_class)
- logging.info('Starting server...')
- try:
- httpd.serve_forever()
- except KeyboardInterrupt:
- pass
- httpd.server_close()
- run()
|