예제 #1
0
def inbound_handler():
    """
    The inbound request handler for consuming HTTP wrapped SMS content from
    Flowroute's messaging service.
    """
    # We'll take this time to clear out any expired sessions and release
    # TNs back to the pool if possible
    ProxySession.clean_expired()
    body = request.json
    try:
        virtual_tn = body['to']
        assert len(virtual_tn) <= 18
        tx_participant = body['from']
        assert len(tx_participant) <= 18
        message = body['body']
    except (TypeError, KeyError, AssertionError) as e:
        msg = ("Malformed inbound message: {}".format(body))
        log.error({"message": msg, "status": "failed", "exc": str(e)})
        return Response('There was an issue parsing your request.', status=400)
    rcv_participant, session_id = ProxySession.get_other_participant(
        virtual_tn, tx_participant)
    if rcv_participant is not None:
        recipients = [rcv_participant]
        send_message(recipients, virtual_tn, message, session_id)
    else:
        recipients = [tx_participant]
        send_message(recipients,
                     virtual_tn,
                     NO_SESSION_MSG,
                     None,
                     is_system_msg=True)
        msg = ("ProxySession not found, or {} is not authorized "
               "to participate".format(tx_participant))
        log.info({"message": msg, "status": "succeeded"})
    return Response(status=200)
예제 #2
0
파일: api.py 프로젝트: tuxpowered/sms-proxy
def inbound_handler():
    """
    The inbound request handler for consuming HTTP wrapped SMS content from
    Flowroute's messaging service.
    """
    # We'll take this time to clear out any expired sessions and release
    # TNs back to the pool if possible
    ProxySession.clean_expired()
    body = request.json
    try:
        virtual_tn = body["to"]
        assert len(virtual_tn) <= 18
        tx_participant = body["from"]
        assert len(tx_participant) <= 18
        message = body["body"]
    except (TypeError, KeyError, AssertionError) as e:
        msg = "Malformed inbound message: {}".format(body)
        log.error({"message": msg, "status": "failed", "exc": str(e)})
        return Response("There was an issue parsing your request.", status=400)
    rcv_participant, session_id = ProxySession.get_other_participant(virtual_tn, tx_participant)
    if rcv_participant is not None:
        recipients = [rcv_participant]
        send_message(recipients, virtual_tn, message, session_id)
    else:
        recipients = [tx_participant]
        send_message(recipients, virtual_tn, NO_SESSION_MSG, None, is_system_msg=True)
        msg = "ProxySession not found, or {} is not authorized " "to participate".format(tx_participant)
        log.info({"message": msg, "status": "succeeded"})
    return Response(status=200)
예제 #3
0
def add_proxy_session():
    """
    The ProxySession resource endpoint for adding a new ProxySession
    to the pool.
    """
    body = request.json
    try:
        participant_a = body['participant_a']
        participant_b = body['participant_b']
        assert len(participant_a) <= 18
        assert len(participant_b) <= 18
    except (AssertionError, KeyError):
        raise InvalidAPIUsage(
            ("Required argument: 'participant_a' (str, length <= 18)"
             ", 'participant_b' (str, length <= 18)"),
            payload={'reason': 'invalidAPIUsage'})
    if 'expiry_window' in body:
        expiry_window = body['expiry_window']
    else:
        expiry_window = None
    # Release any VirtualTNs from expired ProxySessions back to the pool
    ProxySession.clean_expired()
    virtual_tn = VirtualTN.get_next_available()
    if virtual_tn is None:
        msg = "Could not create a new session -- No virtual TNs available."
        log.critical({"message": msg, "status": "failed"})
        return Response(json.dumps({
            "message": msg,
            "status": "failed"
        }),
                        content_type="application/json",
                        status=400)
    else:
        session = ProxySession(virtual_tn.value, participant_a, participant_b,
                               expiry_window)
        try:
            virtual_tn.session_id = session.id
            db_session.add(session)
            db_session.add(virtual_tn)
            db_session.commit()
        except IntegrityError:
            db_session.rollback()
            msg = "There were two sessions attempting to reserve the same virtual tn. Please retry."
            log.error({"message": msg, "status": "failed"})
            return Response(json.dumps({
                "message": msg,
                "status": "failed"
            }),
                            content_type="application/json",
                            status=500)
        expiry_date = session.expiry_date.strftime(
            '%Y-%m-%d %H:%M:%S') if session.expiry_date else None
        recipients = [participant_a, participant_b]
        try:
            send_message(recipients,
                         virtual_tn.value,
                         SESSION_START_MSG,
                         session.id,
                         is_system_msg=True)
        except InternalSMSDispatcherError as e:
            db_session.delete(session)
            virtual_tn.session_id = None
            db_session.add(virtual_tn)
            db_session.commit()
            raise e
        msg = "ProxySession {} started with participants {} and {}".format(
            session.id, participant_a, participant_b)
        log.info({"message": msg, "status": "succeeded"})
        return Response(json.dumps({
            "message": "Created new session",
            "status": "succeeded",
            "session_id": session.id,
            "expiry_date": expiry_date,
            "virtual_tn": virtual_tn.value,
            "participant_a": participant_a,
            "participant_b": participant_b
        }),
                        content_type="application/json")
예제 #4
0
파일: api.py 프로젝트: tuxpowered/sms-proxy
def add_proxy_session():
    """
    The ProxySession resource endpoint for adding a new ProxySession
    to the pool.
    """
    body = request.json
    try:
        participant_a = body["participant_a"]
        participant_b = body["participant_b"]
        assert len(participant_a) <= 18
        assert len(participant_b) <= 18
    except (AssertionError, KeyError):
        raise InvalidAPIUsage(
            ("Required argument: 'participant_a' (str, length <= 18)" ", 'participant_b' (str, length <= 18)"),
            payload={"reason": "invalidAPIUsage"},
        )
    if "expiry_window" in body:
        expiry_window = body["expiry_window"]
    else:
        expiry_window = None
    # Release any VirtualTNs from expired ProxySessions back to the pool
    ProxySession.clean_expired()
    virtual_tn = VirtualTN.get_next_available()
    if virtual_tn is None:
        msg = "Could not create a new session -- No virtual TNs available."
        log.critical({"message": msg, "status": "failed"})
        return Response(json.dumps({"message": msg, "status": "failed"}), content_type="application/json", status=400)
    else:
        session = ProxySession(virtual_tn.value, participant_a, participant_b, expiry_window)
        try:
            virtual_tn.session_id = session.id
            db_session.add(session)
            db_session.add(virtual_tn)
            db_session.commit()
        except IntegrityError:
            db_session.rollback()
            msg = "There were two sessions attempting to reserve the same virtual tn. Please retry."
            log.error({"message": msg, "status": "failed"})
            return Response(
                json.dumps({"message": msg, "status": "failed"}), content_type="application/json", status=500
            )
        expiry_date = session.expiry_date.strftime("%Y-%m-%d %H:%M:%S") if session.expiry_date else None
        recipients = [participant_a, participant_b]
        try:
            send_message(recipients, virtual_tn.value, SESSION_START_MSG, session.id, is_system_msg=True)
        except InternalSMSDispatcherError as e:
            db_session.delete(session)
            virtual_tn.session_id = None
            db_session.add(virtual_tn)
            db_session.commit()
            raise e
        msg = "ProxySession {} started with participants {} and {}".format(session.id, participant_a, participant_b)
        log.info({"message": msg, "status": "succeeded"})
        return Response(
            json.dumps(
                {
                    "message": "Created new session",
                    "status": "succeeded",
                    "session_id": session.id,
                    "expiry_date": expiry_date,
                    "virtual_tn": virtual_tn.value,
                    "participant_a": participant_a,
                    "participant_b": participant_b,
                }
            ),
            content_type="application/json",
        )