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

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

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

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

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

26
        allow = False
27
        body = args.get("body")
28 29 30 31
        message = {
            'topic': 'broadcast',
            'message': body,
        }
32
        client_id = args.get("client_id")
33
        notify_queue = client_id + "-broadcast"
34 35
        if client_id in self.clients:
            client = self.clients.get(client_id)
36
            if args.get("secret") == client.get("secret"):
37 38 39 40 41 42
                allow = True

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