Esempio n. 1
0
 def wrapper(*args, **kwargs):
     cl = request.content_length
     if cl is not None and cl > max_length:
         Utilities.write_log_error(
             app,
             "The users sends a too large request data to the server")
         abort(413)
     return f(*args, **kwargs)
Esempio n. 2
0
 def wrapped(*args, **kwargs):
     user_role = AR_DATABASE.get_user_role(USER.id) or None
     if user_role not in roles:
         Utilities.write_log_error(
             app,
             "The uses doesn't have permissions to enter to this resource"
         )
         abort(403)
     return f(*args, **kwargs)
Esempio n. 3
0
def add_action(version=app.config['ACTUAL_API']):
    """
    Add a new LEA (Low Elementary Action) into database.
    
    The JSON structure must be in a defined format called Common Data format as:

    {
        "action": "eu:c4a:POI_EXIT",
        "user": "******",
        "pilot": "LCC",
        "location": "eu:c4a:Pharmacy:Vanilla123",
        "position": "38.976908 22.724375",
        "timestamp": "2015-05-20T07:08:41.013+03:00",
        "payload": {
            "instance_id": "1287"
        },
        "rating": 0.45,
        "data_source_type": [ "sensors", "external_dataset" ],
        "extra": {
            "pilot_specific_field": "some value"
        }
    }

    :param basestring version: Api version

    :return: Different kind of HTML codes explaining if the action was successful
    """

    if Utilities.check_connection(app, version):
        # We created a list of Python dict.
        data = _convert_to_dict(request.json)
        msg = Utilities.check_add_action_data(AR_DATABASE, data)
        # TODO review in the future
        if data and not msg and USER:
            # User and data are OK. save data into DB
            res_ar = AR_DATABASE.add_action(data)
            res_sr = SR_DATABASE.add_action(data)
            if res_ar and res_sr:
                logging.info(
                    "add_action: the username: %s adds new action into database"
                    % USER.username)
                return Response('Data stored in database OK\n'), 200
            else:
                logging.error(
                    "add_action: the username: %s failed to store data into database. 500"
                    % USER.username)
                return "There is an error in DB", 500
        else:
            logging.error("add_action: there is a problem with entered data")
            # Data is not valid, check the problem
            if msg and "duplicated" in msg:
                # Data sent is duplicated.
                return Response(msg), 409
            else:
                # Standard Error
                return Response(msg), 400
Esempio n. 4
0
def add_new_user(version=app.config['ACTUAL_API']):
    """
    Adds a new system user into the system. The idea is give to an user in the system, an system access.

    An example in JSON could be:

    {
        "username": "******",
        "password": "******",
        "valid_from": "2014-05-20T07:08:41.013+03:00", **# OPTIONAL
        "valid_to": "2018-05-20T07:08:41.013+03:00", **# OPTIONAL
        "user": "******", # OPTIONAL
        "roletype": "administrator",
        "pilot": "ath"
    }

    There are optional parameters that are used only if the administrator wants to add access credentials to ana ctive
    user in the system.

    :param basestring version: Api version

    :return: Response of the API
    """

    # TODO review if validation if the given role exist or not in DB

    if Utilities.check_connection(app, version):
        data = _convert_to_dict(request.json)
        # check the JSON data
        msg = Utilities.check_add_new_user_data(AR_DATABASE, data)
        if data and not msg and USER:
            # User and entered data are OK. save new user into DB
            res_ar = AR_DATABASE.add_new_user_in_system(data)
            res_sr = SR_DATABASE.add_new_user_in_system(data)
            if res_ar and res_sr:
                logging.info(
                    "add_new_user: the username: %s adds new user into database"
                    % USER.username)

                return Response(
                    'The user(s) are registered successfully in the system',
                    200)
            else:
                logging.error(
                    "add_new_user: %s failed to store data into database. 500"
                    % USER.username)
                return Response("There is an error in DB"), 500
        else:
            logging.error("add_new_user: there is a problem with entered data")
            # Data is not valid, check the problem
            if msg and "duplicated" in msg:
                # Data sent is duplicated.
                return Response(msg), 409
            else:
                # Standard Error
                return Response(msg), 400
Esempio n. 5
0
def add_measure(version=app.config['ACTUAL_API']):
    """
    Adds a new measure into the system. This endpoint is sensible to different combinations of GEF/GES


    An example in JSON could be:

    {
        "user": "******",
        "pilot": "SIN",
        "interval_start": "2014-01-20T00:00:00.000+08:00",
        "duration": "DAY",                                  # COULD BE INTERVAL_END INSTEAD OF THIS VALUE
        "payload": {
          "WALK_STEPS": { "value": 1728, "notice": "the user walks a lot in this day" },
          "SHOP_VISITS": { "value": 3, "data_source_type": ["sensors", "external_dataset"]},
          "PHONECALLS_PLACED_PERC": { "value": 21.23, "data_source_type": ["external_dataset"] }
        },
        "extra": {
          "pilot_specific_field": "some value"
        }
    }

    :param basestring version: Api version

    :return: Response of the request

    """

    if Utilities.check_connection(app, version):
        # We created a list of Python dict.
        data = _convert_to_dict(request.json)
        msg = Utilities.check_add_measure_data(SR_DATABASE, data)
        if data and not msg and USER:
            # User and data are OK. save data into DB
            res = SR_DATABASE.add_measure(data)
            if res:
                logging.info(
                    "add_measure: the username: %s adds new action into database"
                    % USER.username)
                return Response(
                    'add_measure: data stored in database OK\n'), 200
            else:
                logging.error(
                    "add_measure: the username: %s failed to store data into database. 500"
                    % USER.username)
                return "There is an error in DB", 500
        else:
            logging.error("add_measure: there is a problem with entered data")
            # Data is not valid, check the problem
            if msg and "duplicated" in msg:
                # Data sent is duplicated.
                return Response(msg), 409
            else:
                # Standard Error
                return Response(msg), 400
Esempio n. 6
0
def add_frailty_status(version=app.config['ACTUAL_API']):
    """
    This endpoint allows to geriatricians, add a ground truth of the status of each citizen, by selecting their status

    * Non-Frail
    * Pre-Frail
    * Frail

    An example of JSON could be

    {
          "user": "******",
          "interval_start": "2014-01-20T00:00:00.000+08:00",
          "duration": "MON",
          "condition": "frail",
          "notice": "Jon Doe is the best"
    }


    :param basestring version: Api version

    :return: Response of the request
    """

    if Utilities.check_connection(app, version):
        # We created a list of Python dict.
        data = _convert_to_dict(request.json)
        msg = Utilities.check_add_frailty_status(
            SR_DATABASE, data, USER.user_in_role[0].pilot_code or 'lcc')
        if data and not msg and USER:
            # Data entered ok, executing the needed method to insert data in DB
            res = SR_DATABASE.add_frailty_status(data, USER.id)
            if res:
                logging.info(
                    "add_frailty_status: the username: %s adds new Frailty_Status into database"
                    % USER.username)
                return Response(
                    'add_frailty_status: data stored in database OK\n'), 200
            else:
                logging.error(
                    "add_frailty_status: the username: %s failed to store data into database. 500"
                    % USER.username)
                return "There is an error in DB", 500
        else:
            logging.error(
                "add_frailty_status: there is a problem with entered data")
            # Data is not valid, check the problem
            if msg and "duplicated" in msg:
                # Data sent is duplicated.
                return Response(msg), 409
            else:
                # Standard Error
                return Response(msg), 400
Esempio n. 7
0
def add_eam(version=app.config['ACTUAL_API']):
    """
    This endpoint allows to pilots insert information about related EAMS from different type of activities.

    It allow to Expert Activity Model, have an input access to discover new activities based on user performed actions.


    An example in JSON could be:


    {
        "activity": "payingvisits",
        "locations": ["eu:c4a:seniorcenter", "eu:c4a:friendhome", "eu:c4a:familymemberhome"],
        "transformed_action": ["seniorcenter_enter", "seniorcenter_exit", "friendhome_enter"],
        "duration": 800,
        "start": [["10:00", "22:00"]]
    }


    :param basestring version: Api version

    :return: Response of the request
    """

    if Utilities.check_connection(app, version):
        # We created a list of Python dict.
        data = _convert_to_dict(request.json)
        msg = Utilities.check_add_eam_data(
            AR_DATABASE, data, USER.user_in_role[0].pilot_code or 'lcc')
        if data and not msg and USER:
            # The user data are correct. We proceed to insert it into DB
            # res = AR_DATABASE.add_eam(data, USER)
            res = AR_DATABASE.add_global_eam(data, USER)
            if res:
                logging.info(
                    "add_eam: the username: %s adds new EAM into database" %
                    USER.username)
                return Response('add_eam: data stored in database OK\n'), 200
            else:
                logging.error(
                    "add_eam: the username: %s failed to store data into database. 500"
                    % USER.username)
                return "There is an error in DB", 500
        else:
            logging.error("add_eam: there is a problem with entered data")
            # Data is not valid, check the problem
            if msg and "duplicated" in msg:
                # Data sent is duplicated.
                return Response(msg), 409
            else:
                # Standard Error
                return Response(msg), 400
Esempio n. 8
0
def add_care_receiver(version=app.config['ACTUAL_API']):
    """
    This method allow to the Pilots (roletype: developers) to add new users in the system with the role
    care_receivers
    
    An example in JSON could be:

    {
        "pilot_user_source_id": "xxXXX?????",
        "valid_from": "2014-05-20T07:08:41.013+03:00", ** OPTIONAL
        "valid_to": "2018-05-20T07:08:41.013+03:00", ** OPTIONAL
        "username": "******",
        "password": "******"
    }
    
    :param base version: Api version

    :return: Response of the request
    """
    if Utilities.check_connection(app, version):
        data = _convert_to_dict(request.json)
        # Checking if INPUT json is OK
        msg = Utilities.check_add_care_receiver_data(AR_DATABASE, data)
        if data and not msg and USER:
            # User and entered data are OK. save new user into DB
            res_ar = AR_DATABASE.add_new_care_receiver(data, USER.id)
            res_sr = SR_DATABASE.add_new_care_receiver(data, USER.id)
            if res_ar and res_sr:
                # We only return one value, because both database has the same IDS
                logging.info(
                    "add_care_receiver: the username: %s adds new user care receiver into database"
                    % USER.username)
                return jsonify(res_ar)
            else:
                logging.error(
                    "add_care_receiver: %s failed to store data into database. 500"
                    % USER.username)
                return Response("There is an error in DB"), 500
        else:
            logging.error(
                "add_care_receiver: there is a problem with entered data")
            # Data is not valid, check the problem
            if msg and "duplicated" in msg:
                # Data sent is duplicated.
                return Response(msg), 409
            else:
                # Standard Error
                return Response(msg), 400
Esempio n. 9
0
def api(version=app.config['ACTUAL_API']):
    """
    This is our main page.

    :param version: Api version
    :return:
    """
    if Utilities.check_version(app, version):
        return """

        <h1>Welcome to City4Age Rest API</h1>

        Here you have a list of available commands to use:

        This API is designed to be used with curl and JSON request.

        <ul>
            <li><b>login</b>: Obtain an identification user token.</li>
            <li><b>logout</b>: Remove the actual user token from the system.</li>
            <li><b>add_action</b>: Adds new Action into database.</li>
            <li><b>add_activity</b>: Adds new Activity into database.</li>
            <li><b>add_measure</b>: Adds a new Measure into database.</li>
            <li><b>add_eam</b>: Adds information about EAM's in the API related to an activity.</li>
            <li><b>add_care_receiver</b>: Allows to a Pilot add a new user 'care_receiver' in the API.</li>
            <li><b>add_new_user</b>: Adds a new registered user in the system (Administrator only).</li>
            <li><b>get_my_info</b>: Returns user information about the actual client.</li>
        </ul>

        """
    else:
        return "You have entered an invalid api version", 404
Esempio n. 10
0
def login(version=app.config['ACTUAL_API']):
    """
    Gives the ability to login into API. It returns an encrypted cookie with the token information and a JSON containing
    the string of the token to use in the validation process.

    :param version: Api version
    :return: A token with user ID information in two formats: 1) in a cookie encrypted; 2) in a JSON decoded.
    """
    if Utilities.check_version(app, version):
        # We relieve the actual logging user information
        if USER:
            token = AR_DATABASE.get_auth_token(USER, app, expiration=600)
            session['token'] = token
            return jsonify({'token': token.decode('ascii')})
    else:
        Utilities.write_log_error(
            app, "logout: User entered an invalid api version, 404")
        return "You have entered an invalid api version", 404
Esempio n. 11
0
def logout(version=app.config['ACTUAL_API']):
    """
    Logout from the system and removes session mark

    :param version: APi version
    :return:
    """
    if Utilities.check_version(app, version):
        global USER
        if USER:
            session.pop('token', None)
            USER = None
            Utilities.write_log_info(app, "logout: User logout successfully")
            flash('You were logged out')
            return redirect(url_for('api', version=app.config['ACTUAL_API']))
    else:
        Utilities.write_log_error(
            app, "logout: User entered an invalid api version, 404")
        return "You have entered an invalid api version", 404
Esempio n. 12
0
def add_new_activity(version=app.config['ACTUAL_API']):
    """
    Adds a new value into the codebook of activities. The activity must not exist previously in database

    {
        "activity": "LeaveHouse",
        "description": "User leave the house",      # OPTIONAL VALUE
        "instrumental": true
    }

    :param basestring version: Api version

    :return: Response of the API
    """
    if Utilities.check_connection(app, version):
        data = _convert_to_dict(request.json)
        msg = Utilities.check_add_new_activity_data(AR_DATABASE, data)
        if data and not msg and USER:
            # User and data are OK. save data into DB
            res_ar = AR_DATABASE.add_new_activity(data)
            res_sr = SR_DATABASE.add_new_activity(data)
            if res_ar and res_sr:
                logging.info(
                    "add_new_activity: the username: %s adds new activity into database"
                    % USER.username)
                return Response('Data stored in database OK\n'), 200
            else:
                logging.error(
                    "add_new_activity: the username: %s failed to store data into database. 500"
                    % USER.username)
                return Response("There is an error in DB"), 500
        else:
            logging.error(
                "add_new_activity: there is a problem with entered data")
            # Data is not valid, check the problem
            if msg and "duplicated" in msg:
                # Data sent is duplicated.
                return Response(msg), 409
            else:
                # Standard Error
                return Response(msg), 400
Esempio n. 13
0
def api(version=app.config['ACTUAL_API']):
    """
    This is our main page.

    :param basestring version: Api version

    :return: Render with the index page of the API
    """
    if Utilities.check_version(app, version):
        # Loading main page of the APi
        return render_template('index.html')
    else:
        return "You have entered an invalid api version", 404
Esempio n. 14
0
def verify_password(username_or_token, password):
    """
    This decorator is used by Flask-HTTPauth to stablish the user's password verification process.

    The method is defined to validate user when it sends either its username/password or token.

    :param username_or_token: The username or validation token
    :param password: The user password

    :return: True if the user credentials are ok
            False if the user credentials are ko

    """

    global USER
    if session and session.get('token', False):
        # Validating user using the encrypted cookie.
        user = AR_DATABASE.verify_auth_token(session['token'], app)
    else:
        # Validating user using the auth Token.
        user = AR_DATABASE.verify_auth_token(username_or_token, app)
    if not user:
        # Validating user with username/password.
        user = AR_DATABASE.verify_user_login(username_or_token, password, app)
        if not user:
            Utilities.write_log_error(
                app,
                "login: User entered an invalid username or password. 401")
            # If there are some user session, the system will clear all data to force user to make a successful login.
            session.pop('token', None)
            USER = None
            return False
    # Put the user id in a global stage
    USER = user
    # Writing the log
    Utilities.write_log_info(
        app, ("login: User login successfully with username or token: %s" %
              username_or_token))
    return True
Esempio n. 15
0
def add_new_user(version=app.config['ACTUAL_API']):
    """
    Adds a new system user into the system. The idea is give to an user in the system, an system access.

    An example in JSON could be:

    {
        "username": "******",
        "password": "******",
        "valid_from": "2014-05-20T07:08:41.013+03:00", **# OPTIONAL
        "valid_to": "2018-05-20T07:08:41.013+03:00", **# OPTIONAL
        "user": "******", # OPTIONAL
        "roletype": "administrator",
        "pilot": "ath"
    }
    
    
    There are optional parameters that are used only if the administrator wants to add access credentials to ana ctive
    user in the system.
    

    :param version: Api version
    :return:
    """
    if Utilities.check_connection(app, version):
        data = _convert_to_dict(request.json)
        # check the JSON data
        res, msg = Utilities.check_add_new_user_data(AR_DATABASE, data)
        if data and res and USER:
            # User and entered data are OK. save new user into DB
            res_ar = AR_DATABASE.add_new_user_in_system(data)
            res_sr = SR_DATABASE.add_new_user_in_system(data)
            if res_ar and res_sr:
                Utilities.write_log_info(app, (
                    "add_new_user: the username: %s adds new user into database"
                    % USER.username))

                return Response(
                    'The user(s) are registered successfully in the system',
                    200)
            else:
                Utilities.write_log_error(
                    app, ("add_new_user: the username: %s failed to store "
                          "data into database. 500" % USER.username))
                return Response("There is an error in DB"), 500
        else:
            return Response(msg), 400
Esempio n. 16
0
def add_action(version=app.config['ACTUAL_API']):
    """
    Add a new LEA (Low Elementary Action) into database.
    
    The JSON structure must be in a defined format called Common Data format as:

    {
            "action": "eu:c4a:POI_ENTER",
            "user": "******",
            "pilot": "ATH",
            "location": "eu:c4a:Shop:Ermou96",
            "position": "37.976908 23.724375",
            "timestamp": "2014-05-20T07:08:41.013+03:00",
            "payload": {
                "instance_id": "124"
            },
            "data_source_type": [ "sensors", "external_dataset" ],
            "extra": {
                "pilot_specific_field": "some value"
            }
    }
    
    :param version: Api version
    :return: Different kind of HTML codes explaining if the action was successful
    """

    if Utilities.check_connection(app, version):
        # We created a list of Python dict.
        data = _convert_to_dict(request.json)
        res, msg = Utilities.check_add_action_data(AR_DATABASE, data)
        if data and res and USER:
            # User and data are OK. save data into DB
            res_ar = AR_DATABASE.add_action(data)
            res_sr = SR_DATABASE.add_action(data)
            if res_ar and res_sr:
                Utilities.write_log_info(app, (
                    "add_action: the username: %s adds new action into database"
                    % USER.username))
                return Response('Data stored in database OK\n'), 200
            else:
                Utilities.write_log_error(app, (
                    "add_action: the username: %s failed to store data into database. 500"
                    % USER.username))
                return "There is an error in DB", 500
        else:
            return Response(msg), 400
Esempio n. 17
0
def add_measure(version=app.config['ACTUAL_API']):
    """
    Adds a new measure into the system. This endpoint is sensible to different combinations of GEF/GES


    An example in JSON could be:

    {
        "user": "******",
        "pilot": "SIN",
        "interval_start": "2014-01-20T00:00:00.000+08:00",
        "duration": "DAY",                                  # OPTIONALLY COULD BE INTERVAL_END
        "payload": {
          "WALK_STEPS": { "value": 1728 },
          "SHOP_VISITS": { "value": 3, "data_source_type": ["sensors", "external_dataset"]},
          "PHONECALLS_PLACED_PERC": { "value": 21.23, "data_source_type": ["external_dataset"] }
        },
        "extra": {
          "pilot_specific_field": “some value”
        }
    }

    :param version: Api version
    :return:

    """
    if Utilities.check_connection(app, version):
        # We created a list of Python dict.
        data = _convert_to_dict(request.json)
        res, msg = Utilities.check_add_measure_data(SR_DATABASE, data)
        if data and res and USER:
            # User and data are OK. save data into DB
            res = SR_DATABASE.add_measure(data)
            if res:
                Utilities.write_log_info(app, (
                    "add_measure: the username: %s adds new action into database"
                    % USER.username))
                return Response(
                    'add_measure: data stored in database OK\n'), 200
            else:
                Utilities.write_log_error(app, (
                    "add_measure: the username: %s failed to store data into database. 500"
                    % USER.username))
                return "There is an error in DB", 500
        else:
            return Response(msg), 400
Esempio n. 18
0
def add_care_receiver(version=app.config['ACTUAL_API']):
    """
    This method allow to the Pilots (roletype: developers) to add new users in the system with the role
    care_receivers
    
    An example in JSON could be:

    {
        "pilot_user_source_id": "xxXXX?????",
        "valid_from": "2014-05-20T07:08:41.013+03:00", ** OPTIONAL
        "valid_to": "2018-05-20T07:08:41.013+03:00", ** OPTIONAL
        "username": "******",
        "password": "******"
    }
    
    :param version: 
    :return: A urn with --> eu:c4a:user:{city4AgeId}
    """

    if Utilities.check_connection(app, version):
        data = _convert_to_dict(request.json)
        # Checking if INPUT json is OK
        res, msg = Utilities.check_add_care_receiver_data(AR_DATABASE, data)
        if data and res and USER and not msg:
            # User and entered data are OK. save new user into DB
            res_ar = AR_DATABASE.add_new_care_receiver(data, USER.id)
            res_sr = SR_DATABASE.add_new_care_receiver(data, USER.id)
            if res_ar and res_sr:
                Utilities.write_log_info(app, (
                    "add_care_receiver: the username: %s adds new care receiver "
                    "into database" % USER.username))
                # We only return one value, because both database has the same IDS
                return jsonify(res_ar)
            else:
                Utilities.write_log_error(
                    app,
                    ("add_care_receiver: the username: %s failed to store "
                     "data into database. 500" % USER.username))
                return Response("There is an error in DB"), 500
        else:
            # Data is not valid, check the problem

            # TODO maybe detect here the source of message???

            return Response(msg), 400
Esempio n. 19
0
def add_eam(version=app.config['ACTUAL_API']):
    """
    This endpoint allows to pilots insert information about related EAMS from different type of activities.

    It allow to Expert Activity Model, have an input access to discover new activities based on user performed actions.


    An example in JSON could be:

    {
        "activity_name": "AnsweringPhone",                      # This must exist previously
        "locations": ["Kitchen", "Office", "Bedroom"],
        "actions": ["KitchenPIR", "BedroomPIR"],
        "duration": 120,
        "start": [
            ["12:00", "12:05"],
            ["20:00", "20:10"]
        ]
    }


    :param version: Api version
    :return:
    """
    if Utilities.check_connection(app, version):
        # We created a list of Python dict.
        data = _convert_to_dict(request.json)
        res, msg = Utilities.check_add_eam_data(AR_DATABASE, data)
        if data and res and USER:
            # The user data are correct. We proceed to insert it into DB
            res = AR_DATABASE.add_eam(data)
            if res:
                Utilities.write_log_info(
                    app,
                    ("add_eam: the username: %s adds new EAM into database" %
                     USER.username))
                return Response('add_eam: data stored in database OK\n'), 200
            else:
                Utilities.write_log_error(app, (
                    "add_eam: the username: %s failed to store data into database. 500"
                    % USER.username))
                return "There is an error in DB", 500
        else:
            return Response(msg), 400
Esempio n. 20
0
def commit_measure(version=app.config['ACTUAL_API']):
    """
    This method executes and external program that makes the needed calculations in SR schema and
    updates some tables


    :param basestring version: API version

    :return: Response of the request
    """
    if Utilities.check_version(app=app, p_ver=version) and USER:
        # Calling to external java jar file to update database data
        res = SR_DATABASE.commit_measure(USER)
        if res:
            logging.info("commit_measure: data commit successfully")
            return Response(
                'Your measures are successfully saved and committed in database\n'
            ), 200
        else:
            logging.error(
                "commit_measure: failed to commit measures data in DB")
            return Response(
                'FAILED: the commit script was encountered an error. Contact with administrator'
            ), 500
Esempio n. 21
0
def add_activity(version=app.config['ACTUAL_API']):
    """
    Adds a new activity into the system


    # TODO Instrumental and Basic activities are present HERE!!!! There are two type of Activities
    # Copanion? YES NO boolean

    An example in JSON could be:

    {
        "activity_name": "LeaveHouse",
        "activity_description": "Some description of the activity",          # Optional
        "instrumental": True,                                               # Optional
        "house_number": 0,              # Optional
        "indoor": false,                # Optional
        "location":"eu:c4a:Bus:39",     # Optional
        "pilot": "LCC"                  # Optional
    }

    :param version: Api version
    :return:
    """
    if Utilities.check_connection(app, version):
        data = _convert_to_dict(request.json)
        res, msg = Utilities.check_add_activity_data(AR_DATABASE, data)
        if data and res and USER:
            # User and data are OK. save data into DB
            res_ar = AR_DATABASE.add_activity(data)
            res_sr = SR_DATABASE.add_activity(data)
            if res_ar and res_sr:
                Utilities.write_log_info(app, (
                    "add_activity: the username: %s adds new activity into database"
                    % USER.username))
                return Response('Data stored in database OK\n'), 200
            else:
                Utilities.write_log_error(
                    app, ("add_activity: the username: %s failed to store "
                          "data into database. 500" % USER.username))
                return Response("There is an error in DB"), 500
        else:
            return Response(msg), 400
Esempio n. 22
0
def search(version=app.config['ACTUAL_API']):
    """
    Return data based on specified search filters:

    Example of JSON search call:

    {
        'table': 'table_name',
        'criteria': {
            "col1": "value",
            "col2": "value"
        },
        ###### Optional parameters
        'limit': 2323,
        'offset': 2,
        'order_by': 'desc'
    }

    You only need to define a JSON with needed filters and you can optionally add some data to define limits, orders
    and offsets.

    :param basestring version: Api version

    :return: Response of the request
    """

    # TODO this endpoint will be different if the user is admin or pilot --> Using roles
    ########################################################3

    if Utilities.check_connection(app, version):
        # We created a list of Python dict.
        data = _convert_to_dict(request.json)
        if len(data) == 1:
            msg = Utilities.check_search_data(AR_DATABASE, SR_DATABASE, data)
            if data and not msg and USER:
                # User and data are OK. save data into DB
                # Finding the desired table in the proper schema
                is_ar_table = Utilities.validate_search_tables(
                    AR_DATABASE, data[0])
                is_sr_table = Utilities.validate_search_tables(
                    SR_DATABASE, data[0])
                # Defining default values to return data
                res_ar = None
                res_sr = None
                if is_ar_table and is_sr_table:
                    # The table is in both schema, making the search in AR only
                    res_ar = AR_DATABASE.search(data[0])
                elif is_ar_table and not is_sr_table:
                    # The table is only in AR schema, making the search in AR only
                    res_ar = AR_DATABASE.search(data[0])
                elif is_sr_table and not is_ar_table:
                    # The table is only in SR schema, making the search in SR only
                    res_sr = SR_DATABASE.search(data[0])
                else:
                    # General exception. Error in DB
                    logging.error(
                        'search: Internal error of the database when deciding the search schema criteria'
                    )
                    return Response(
                        "Database internal error, contact with administrator",
                        500)
                # Return the results of the performed search
                res = res_ar or res_sr
                if res.count() > 0:
                    # We have data to show
                    logging.info(
                        "search: the username: %s requests a search without size of %s elements"
                        % (USER.username, res.count()))
                    # Returning the results
                    # TODO find a solution to serialize datetimes
                    return jsonify(json_list=res.all())
                else:
                    logging.info(
                        "search: the username: %s requests a search without results"
                        % USER.username)
                    return Response(
                        "The search query doesn't return any result"), 200
            else:
                logging.error(
                    "add_action: there is a problem with entered data")
                # Data is not valid, check the problem
                if msg and "duplicated" in msg:
                    # Data sent is duplicated.
                    return Response(msg), 409
                else:
                    # Standard Error
                    return Response(msg), 400
        else:
            return Response("This method doesn't allow list of JSON", 400)
Esempio n. 23
0
def add_activity(version=app.config['ACTUAL_API']):
    """
    Adds a new activity into the system


    An example in JSON could be:


    {
        "activity": "LeaveHouse",
        "user": "******",
        "pilot": "LCC",
        "start_time": "2018-04-20T07:08:41.013+03:00",
        "end_time": "2018-05-20T07:08:41.013+03:00",
        "duration": 23232323,
        "payload": [{
            "action": "eu:c4a:POI_EXIT",
            "location": "eu:c4a:Pharmacy:Vanilla123",
            "timestamp": "2015-05-20T07:08:41.013+03:00",
            "position": "38.976908 22.724375"
        }, {
            "action": "eu:c4a:POI_ENTER",
            "location": "eu:c4a:Shop:Ermou96",
            "timestamp": "2014-05-20T07:08:41.013+03:00",
            "position": "37.976908 23.724375"
        }, {
            "action": "eu:c4a:APPLIANCE_ON",
            "location": "eu:c4a:Room:number23",
            "timestamp": "2012-05-20T07:08:41.013+03:00",
            "position": "42.986908 33.724375"
        }
                   ],
        "data_source_type": ["sensors", "external_dataset"]
    }

    :param basestring version: Api version

    :return: Response of the request
    """
    if Utilities.check_connection(app, version):
        data = _convert_to_dict(request.json)
        msg = Utilities.check_add_activity_data(AR_DATABASE, data)
        if data and not msg and USER:
            # User and data are OK. save data into DB
            res_ar = AR_DATABASE.add_activity(data)
            res_sr = SR_DATABASE.add_activity(data)
            if res_ar and res_sr:
                logging.info(
                    "add_activity: the username: %s adds new activity into database"
                    % USER.username)
                return Response('Data stored in database OK\n'), 200
            else:
                logging.error(
                    "add_activity: %s failed to store data into database. 500"
                    % USER.username)
                return Response("There is an error in DB"), 500
        else:
            logging.error("add_activity: there is a problem with entered data")
            # Data is not valid, check the problem
            if msg and "duplicated" in msg:
                # Data sent is duplicated.
                return Response(msg), 409
            else:
                # Standard Error
                return Response(msg), 400