예제 #1
0
def update_user(username, body):
    fields = [
        'email', 'username', 'full_name', 'password', 'device_token',
        'show_notifications'
    ]

    result, code = db.get_one(User, username)

    if code == 404:
        return result, code

    user = get_row_dict(result)

    params = get_params_by_body(fields, body)

    errors = validate_update_user(body, params)
    if errors:
        return errors, 400

    if 'password' in params:
        params['password'] = BCRYPT.generate_password_hash(
            params['password']).decode('utf-8')

    result, code = db.update(User, username, params)

    if code == 200:  # if successful, returns the data
        if 'device_token' in body:
            send_notification_on_signin(user, username, body)
        user = get_row_dict(result)  # converts row to dict
        return user, code
    return result, code  # else, returns database error and error code
def get_all_neighborhoods(city=None, state=None):
    filter_ = {} if state or city else None
    if city:
        filter_.update({'city': [city]})
    if state:
        filter_.update({'state': [state]})
    result, code = db.get_all(Neighborhood, filter_)
    if result:
        if code == 200:
            neighborhoods = [get_row_dict(u) for u in result]
            # getting statistics
            for index, _ in enumerate(neighborhoods):
                filter_ = {
                          "id_neighborhood": [
                                neighborhoods[index]['id_neighborhood']
                          ]
                         }
                ratings, status = db.get_all(Rating, filter_)
                if status != 200:
                    return ratings, status
                ratings = [r.to_dict() for r in ratings]
                if ratings:
                    statistics = get_neighborhood_statistics(ratings)
                    neighborhoods[index].update({'statistics': statistics})

            return neighborhoods, code
        return result, code
    return [], 200
def get_favorite_places(username):
    result, code = db.get_all(FavoritePlace, {'user': [username]})

    if result:
        if code == 200:  # if successful, returns the data
            # converts rows to dict
            favorite_places = [get_row_dict(place) for place in result]
            return favorite_places, code
    return [], 200
def delete_favorite_place(username, id_place):
    result, code = db.get_one(FavoritePlace, id_place)

    if code == 200:
        favorite_place = get_row_dict(result)

        if favorite_place['user'] != username:
            return "O usuário não tem permissão para deletar esse local favorito", 401

        result, code = db.delete(FavoritePlace, id_place)

    return result, code
def send_notifications_near_occcurrences(occurrence, username):
    result, code = get_all(FavoritePlace)

    favorite_places = [get_row_dict(u) for u in result]

    near_favorite_places = set()

    for favorite_place in favorite_places:
        if haversine(favorite_place, occurrence) != None:
            user = get_row_dict(get_one(User, favorite_place['user'])[0])

            if user['show_notifications'] and user['username'] != username:
                near_favorite_places.add(user['device_token'])

    message = {
        'to': [token for token in near_favorite_places],
        'sound': 'default',
        'title': 'Atenção!',
        'body':
        f'Uma ocorrência foi reportada perto de um de seus locais favoritos!',
        'data': {
            'data': occurrence
        },
    }

    headers = {
        "Accept": "*/*",
        'Accept-encoding': 'gzip, deflate',
        "Content-Type": "application/json"
    }

    response = requests.post('https://exp.host/--/api/v2/push/send',
                             data=json.dumps(message),
                             headers=headers)

    return occurrence, 200
def get_auth_response(user, auth):
    user = get_row_dict(user)
    if BCRYPT.check_password_hash(user['password'], auth['password']):
        token = jwt.encode(
            {
                'username': user['username'],
            },
            SECRET_KEY,
            algorithm='HS256'
        )
        return {
            'msg': 'Login bem sucedido',
            'token': token.decode('utf-8'),
        }, 200
    return 'Senha inválida', 401
def get_one_neighborhood(neighborhood_id):
    result, code = db.get_one(Neighborhood, neighborhood_id)

    if code == 200:
        # formating filter
        filter_ = {"id_neighborhood": [neighborhood_id]}
        ratings, status = db.get_all(Rating, filter_)
        if status != 200:
            return ratings, status
        ratings = [r.to_dict() for r in ratings]

        neighborhood = get_row_dict(result)
        if ratings:
            statistics = get_neighborhood_statistics(ratings)
            neighborhood.update({'statistics': statistics})
        return neighborhood, 200
    return result, code
    def to_dict(self, del_null_attr=True):
        # getting the details
        details = {}
        for field in self.details._fields:
            value = self.details.__getattribute__(field)
            if del_null_attr:
                if value is not None:
                    details.update({field: value})
            else:
                details.update({field: value})

        rating = {
            'details': details,
            'id_rating': self.id_rating,
            'user': self.user,
            'rating_neighborhood': self.rating_neighborhood,
            'neighborhood': get_row_dict(self.neighborhood)
        }

        return rating