send.py 1.47 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 9
class SendSchema(Schema):
    client_id = fields.Str(required=True)
    secret = fields.Str(required=True)
    body = fields.Str(required=True)
    topic = fields.Str(required=True)
10 11

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

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

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

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
        messages = []
        allow = False
        body = request.args.get("body")
        topic = request.args.get("topic")
        client_id = request.args.get("client_id")
        outbox_queue = client_id + "-outbox"
        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)
            message = {
                'topic': topic,
                'message': body,
            }
            channel.basic_publish(exchange="", routing_key=notify_queue, body=message)
            deliver_connection.close()