Ejemplo n.º 1
0
def test_delete_tn():
    """
    Creates a new virtual tn attached to a session, and requests to
    delete that number which is an illegal operation. The VirtualTN is then
    released, and the request is made again - this time succeeding.
    """
    client = app.test_client()
    test_num = '12223334444'
    session = ProxySession(test_num, '12223334444', '12223335555',
                           expiry_window=None)
    vnum = VirtualTN(test_num)
    vnum.session_id = 'fake_session_id'
    db_session.add(session)
    db_session.add(vnum)
    db_session.commit()
    resp = client.delete('/tn',
                         data=json.dumps({'value': test_num}),
                         content_type='application/json')
    data = json.loads(resp.data)
    assert data['status'] == 'failed'
    assert "Cannot delete the number." in data['message']
    assert session.id in data['message']
    assert resp.status_code == 400
    db_session.delete(session)
    vnum.session_id = None
    db_session.add(vnum)
    db_session.commit()
    resp = client.delete('/tn',
                         data=json.dumps({'value': test_num}),
                         content_type='application/json')
    data = json.loads(resp.data)
    assert 'Successfully removed TN from pool' in data['message']
    assert resp.status_code == 200
Ejemplo n.º 2
0
def test_delete_tn():
    """
    Creates a new virtual tn attached to a session, and requests to
    delete that number which is an illegal operation. The VirtualTN is then
    released, and the request is made again - this time succeeding.
    """
    client = app.test_client()
    test_num = '12223334444'
    session = ProxySession(test_num,
                           '12223334444',
                           '12223335555',
                           expiry_window=None)
    vnum = VirtualTN(test_num)
    vnum.session_id = 'fake_session_id'
    db_session.add(session)
    db_session.add(vnum)
    db_session.commit()
    resp = client.delete('/tn',
                         data=json.dumps({'value': test_num}),
                         content_type='application/json')
    data = json.loads(resp.data)
    assert data['status'] == 'failed'
    assert "Cannot delete the number." in data['message']
    assert session.id in data['message']
    assert resp.status_code == 400
    db_session.delete(session)
    vnum.session_id = None
    db_session.add(vnum)
    db_session.commit()
    resp = client.delete('/tn',
                         data=json.dumps({'value': test_num}),
                         content_type='application/json')
    data = json.loads(resp.data)
    assert 'Successfully removed TN from pool' in data['message']
    assert resp.status_code == 200
Ejemplo n.º 3
0
 def terminate(cls, session_id):
     """
     Ends a given session, and releases the virtual TN back into the pool
     """
     session = cls.query.filter_by(id=session_id).one()
     participant_a = session.participant_a
     participant_b = session.participant_b
     virtual_tn = VirtualTN.query.filter_by(session_id=session_id).one()
     virtual_tn.session_id = None
     db_session.commit()
     db_session.delete(session)
     db_session.commit()
     return participant_a, participant_b, virtual_tn
Ejemplo n.º 4
0
 def terminate(cls, session_id):
     """
     Ends a given session, and releases the virtual TN back into the pool
     """
     session = cls.query.filter_by(id=session_id).one()
     participant_a = session.participant_a
     participant_b = session.participant_b
     virtual_tn = VirtualTN.query.filter_by(session_id=session_id).one()
     virtual_tn.session_id = None
     db_session.commit()
     db_session.delete(session)
     db_session.commit()
     return participant_a, participant_b, virtual_tn
Ejemplo n.º 5
0
def remove_virtual_tn():
    """
    The VirtualTN resource endpoint for removing VirtualTN's from the pool.
    """
    body = request.json
    try:
        value = str(body['value'])
    except (AssertionError, KeyError):
        raise InvalidAPIUsage("Required argument: 'value' (str, length <= 18)",
                              payload={'reason': 'invalidAPIUsage'})
    try:
        virtualTN = VirtualTN.query.filter_by(value=value).one()
    except NoResultFound:
        msg = ("Could not delete virtual TN ({})"
               " because it does not exist").format(value)
        log.info({"message": msg, "status": "failed"})
        raise InvalidAPIUsage(
            "Virtual TN could not be deleted because it does not exist",
            status_code=404,
            payload={'reason': 'virtual TN not found'})
    else:
        # Release any VirtualTNs from expired ProxySessions
        ProxySession.clean_expired()
        try:
            active_session = ProxySession.query.filter_by(
                virtual_TN=virtualTN.value).one()
        except NoResultFound:
            db_session.delete(virtualTN)
            db_session.commit()
        else:
            msg = ("Cannot delete the number. There is an active "
                   "ProxySession {} using that VirtualTN.".format(
                       active_session.id))
            return Response(json.dumps({
                "message": msg,
                "status": "failed",
            }),
                            content_type="application/json",
                            status=400)
    return Response(json.dumps({
        "message": "Successfully removed TN from pool",
        "value": value,
        "status": "succeeded"
    }),
                    content_type="application/json")
Ejemplo n.º 6
0
def remove_virtual_tn():
    """
    The VirtualTN resource endpoint for removing VirtualTN's from the pool.
    """
    body = request.json
    try:
        value = str(body["value"])
    except (AssertionError, KeyError):
        raise InvalidAPIUsage("Required argument: 'value' (str, length <= 18)", payload={"reason": "invalidAPIUsage"})
    try:
        virtualTN = VirtualTN.query.filter_by(value=value).one()
    except NoResultFound:
        msg = ("Could not delete virtual TN ({})" " because it does not exist").format(value)
        log.info({"message": msg, "status": "failed"})
        raise InvalidAPIUsage(
            "Virtual TN could not be deleted because it does not exist",
            status_code=404,
            payload={"reason": "virtual TN not found"},
        )
    else:
        # Release any VirtualTNs from expired ProxySessions
        ProxySession.clean_expired()
        try:
            active_session = ProxySession.query.filter_by(virtual_TN=virtualTN.value).one()
        except NoResultFound:
            db_session.delete(virtualTN)
            db_session.commit()
        else:
            msg = "Cannot delete the number. There is an active " "ProxySession {} using that VirtualTN.".format(
                active_session.id
            )
            return Response(
                json.dumps({"message": msg, "status": "failed"}), content_type="application/json", status=400
            )
    return Response(
        json.dumps({"message": "Successfully removed TN from pool", "value": value, "status": "succeeded"}),
        content_type="application/json",
    )
Ejemplo n.º 7
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")
Ejemplo n.º 8
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",
        )