~kf5jwc/sms-printer

06b4d3c377ad2e3228fae392851475978b99efaf — Kyle Jones 2 years ago 5be96bf
Add Bandwidth v1/v2 API discriminating
1 files changed, 47 insertions(+), 10 deletions(-)

M sms_printer/application.py
M sms_printer/application.py => sms_printer/application.py +47 -10
@@ 19,19 19,56 @@ def main():

@APP.route("/sms-printer", methods=['POST'])
def sms_printer():
    for sms in request.get_json(force=True):
        if ALLOWED_SENDERS and sms['message']['from'] not in ALLOWED_SENDERS:
            return Response(status=401)
    def sms_main():
        user_agent = (request.user_agent.platform, request.user_agent.version)
        if user_agent is ("BandwidthAPI", "v2"):
            return bandwidth_v2()

        # Default, since they report no UA
        return bandwidth_v1()

    def allowed_sender(sender):
        return ALLOWED_SENDERS and sender not in ALLOWED_SENDERS

    def archive_request(sms_id, data):
        with open(os.path.join(ARCHIVE, sms_id), 'w+') as archive_file:
            json.dump(data, archive_file)

        with open(os.path.join(ARCHIVE, sms['message']['id']), 'w+') as f:
            json.dump(sms, f)
    def print_message(message):
        with NamedTemporaryFile(mode='w+') as tmp_file:
            print("{}".format(message), file=tmp_file)
            tmp_file.flush()

        with NamedTemporaryFile(mode='w+') as f:
            print("{}".format(sms['message']['text']), file=f)
            f.flush()
            try:
                run(['lp', f.name], check=True, timeout=10)
                run(['lp', tmp_file.name], check=True, timeout=10)

            except CalledProcessError:
                return False

        return True

    def bandwidth_v1():
        sms = request.get_json(force=True)
        archive_request(sms['messageId'], sms)

        if not allowed_sender(sms['from']):
            return Response(status=401)

        if not print_message(sms['text']):
            return Response(status=500)

        return Response(status=200)

    def bandwidth_v2():
        for sms in request.get_json(force=True):
            archive_request(sms['message']['id'], sms)

            if not allowed_sender(sms['message']['from']):
                return Response(status=401)

            if not print_message(sms['message']['text']):
                return Response(status=500)

    return Response(status=200)
        return Response(status=200)

    sms_main()