notify.py 1.29 KB
Newer Older
Dan Jones's avatar
Dan Jones committed
1 2
from flask_restful import Resource, reqparse, abort
from marshmallow import Schema, fields
3 4
import json

5 6 7 8
class NotifySchema(Schema):
    client_id = fields.Str(required=True)
    secret = fields.Str(required=True)
    body = fields.Str(required=True)
9 10

class Notify(Resource):
11 12
    clients = None
    schema = None
13

14 15 16 17
    def __init__(self):
        self.schema = ReceiveSchema()
        with open("clients.json", "r") as clients_file:
            self.clients = json.load(clients_file)
18

19 20 21 22
    def post(self):
        errors = self.schema.validate(request.args)
        if errors:
            abort(400, str(errors))
23

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
        messages = []
        allow = False
        body = request.args.get("body")
        client_id = request.args.get("client_id")
        notify_queue = client_id + "-notify"
        if client_id in self.clients:
            client = self.clients.get(client_id)
            if request.args.get("secret") == client.get("secret"):
                allow = True

        if allow:
            connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost"))
            channel = connection.channel()
            channel.queue_declare(queue=notify_queue, durable=True)
            channel.basic_publish(exchange="", routing_key=notify_queue, body=body)
            deliver_connection.close()