-
Notifications
You must be signed in to change notification settings - Fork 0
/
gateway.py
75 lines (59 loc) · 2.51 KB
/
gateway.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import gateway_helper as gwh
import logging
import os
import traceback
from dotenv import load_dotenv
from flask import Flask, request, abort, jsonify
from pathlib import Path
from xmpp_client import MUCBot
env_path = Path('.') / '.pyenv'
load_dotenv(dotenv_path=env_path)
logging.basicConfig(level=logging.getLevelName(os.environ['XMPP_LOG_LEVEL'].upper()))
app = Flask(__name__)
for err_code in [400, 404, 415, 500]:
app.register_error_handler(*gwh.error_handler(err_code))
known_rooms = gwh.parse_known_rooms(os.environ['KNOWN_ROOMS'])
@app.route('/post/<string:token>', methods=['POST'])
def push_send(token):
"""
Forwarding the received JSON object to the given notification channel (identified by the token)
Returns a JSON response along with a proper HTTP status
:see: XMPP API docs: https://github.com/caronc/apprise/wiki/Notify_xmpp
:see: XMPP implementation: https://github.com/caronc/apprise/blob/master/apprise/plugins/NotifyXMPP.py
:param: token string
:return: string, int
"""
app.logger.info('New message received')
app.logger.debug(request.headers)
app.logger.debug(request.form)
app.logger.debug(request.json)
if token not in known_rooms.keys():
abort(404, description='Token mismatch')
try:
if request.json:
message = gwh.format_message(os.environ['MESSAGE_FORMAT'], request.json)
else:
message = gwh.format_message(os.environ['MESSAGE_FORMAT'], dict(request.form))
except:
abort(415, description='Gateway configured with unknown message format')
try:
xmpp = MUCBot(os.environ['JID_FROM_USER'], os.environ['JID_FROM_PASS'],
known_rooms[token]['room'], known_rooms[token]['nick'], message)
xmpp.connect()
xmpp.process(forever=False)
app.logger.info('Forwarded the received message as %s to %s',
known_rooms[token]['nick'], known_rooms[token]['room'])
except:
app.logger.error('Unexpected error during message processing')
app.logger.error(traceback.format_exc())
app.logger.error('Could not forward the message')
app.logger.info(request.json)
abort(500, description='Unexpected error during message processing')
return {'success': True}, 200
if __name__ == '__main__':
app.logger.setLevel(1)
app.run(host='0.0.0.0')
else:
gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)