Пример #1
0
    def patch(self, conntype, id):
        if conntype not in CONNECTION_TYPE_MAPPING:
            return ('TYPE', 400, [])
        conn_dict = CONNECTION_TYPE_MAPPING[conntype]
        conn_class = conn_dict['class']

        conn = self._get_instance(conntype, id)
        if not isinstance(conn, conn_class):
            # error
            return conn

        logged_user = get_logged_user()

        if conntype == 'friendships':
            type_status = request.json.get('type_status')
            if type_status:
                # pending status can be changed only by the other counterpart
                # (to be improved yet)
                if (conn.type_status['current'] == 'pending' and
                        conn.user_from_id == logged_user.id):
                    return ('UNAUTHORIZED', 405, [])
                try:
                    make_transition(conn, 'type_status', type_status)
                except StateValueError:
                    return (jsonify(build_error_dict([
                        'Invalid "type_status" value.'])), 400, [])
                except StateTransitionError:
                    return (jsonify(build_error_dict([
                        'Invalid "type_status" transition.'])), 400, [])

        return jsonify(conn.serializer_func(logged_user))
Пример #2
0
    def patch(self, direction, msgtype, id):
        user = get_logged_user()
        request_json = json_loads(request.data)

        if msgtype not in MESSAGE_TYPE_MAPPING:
            return ('TYPE', 400, [])
        msg_dict = MESSAGE_TYPE_MAPPING[msgtype]
        msg_notification_class = msg_dict['notification_class']

        if direction == 'out':  # PATCH op is allowed only for incoming msgs
            return ('FORBIDDEN', 403, [])
        elif direction != 'in':  # Invalid direction value
            return ('DIRECTION', 400, [])

        msg_list = filter_by_direction(
            msgtype, 'in', user, additional_filters={'id': id})
        if not msg_list:
            return ('NOT FOUND', 404, [])

        msg = msg_list[0]

        added_flags, removed_flags = (
            request_json.get('flags_in'),
            request_json.get('flags_out'))

        msg.change_flags(added_flags, removed_flags)

        msg_notification = msg.get_notification(user)
        errors = []

        try:
            msg_notification.change_status(request_json.get('message_status'))
        except ValueError:  # Invalid transition
            errors.append('Invalid "message_status" value.')

        if msgtype == 'hospitality_request':
            request_status = request_json.get('request_status')
            if (request_status and
                ((direction == 'out' and request_status == 'canceled')
                 or direction == 'in' and msg.status != 'canceled')):
                try:
                    msg.change_status(request_status)
                except ValueError:  # Invalid transition
                    errors.append('Invalid "request_status" value.')

        if errors:  # Errors found, returns error structure
            return (jsonify(build_error_dict(errors)), 400, [])

        # in case of success, returns the updated message serialization
        msg.save()
        msg_notification.save(commit=True)
        return jsonify(msg.serialized_func(user))
Пример #3
0
    def post(self):
        """
        Creates a new account.
        """
        # TODO: improved password handling?
        params = dict(
            first_name=request.json.get('first_name'),
            last_name=request.json.get('last_name'),
            birth_date=request.json.get('birth_date'),
            email=request.json.get('email'),
            gender=request.json.get('gender'),
            username=request.json.get('username'),
            password=request.json.get('password'))

        optional_params = dict(
            city_id=request.json.get('city_id'))

        missing_fields = [k for (k, v) in params.iteritems() if not v]
        if missing_fields:
            return (jsonify(build_error_dict([
                'No value specified for "%s".' % field
                for field in missing_fields])), 400, [])

        params.update(optional_params)
        user = User(**params)
        user.save(commit=True)
        return UserByIDHandler._get(user)
Пример #4
0
    def post(self, conntype):
        logged_user = get_logged_user()
        if conntype not in CONNECTION_TYPE_MAPPING:
            return ('TYPE', '400', [])
        conn_dict = CONNECTION_TYPE_MAPPING[conntype]

        conn_class, conn_validator = (
            conn_dict['class'],
            getattr(self, conn_dict['validator']))

        success, param_dict = getattr(
            self, conn_dict['validator'])(logged_user)
        if not success:
            return (jsonify(**param_dict), 400, [])
        conn = conn_class(**param_dict)
        conn.save(commit=True)
        return jsonify(conn.serializer_func(logged_user))
Пример #5
0
 def get(self):
     # TODO - search to be defined
     filter_args = get_filter_dict(
         request.args, ('city_id', 'parent_group_id'))
     query = Group.query.filter_by(is_active=True)
     if filter_args:
         query = query.filter_by(**filter_args)
     resp = [o.serialized for o in query]
     return jsonify(resp)
Пример #6
0
 def _get(cls, user):
     expand_rels = request.args.get('expand')
     if expand_rels:
         expand_rels = filter(lambda o: o.lower().strip(),
                              expand_rels.split(','))
         user.force_serialize(expand_rels)
     resp = user.serialized
     resp['token'] = get_request_token()
     return jsonify(resp)
Пример #7
0
    def _get(cls, conntype, conn):
        logged_user = get_logged_user()
        if not conn:
            return ('NOT FOUND', 404, [])

        this_conn = cls._get_instance(conntype, conn)
        if isinstance(this_conn, tuple):
            return this_conn

        return jsonify(this_conn.serializer_func(logged_user))
Пример #8
0
    def post(self):
        """
        Create new group.

        {
            "title": str,
            "description": str,
            ^"city_id": int,
            ^"minorlocality_id": int,
            ^"parent_group_id": int}
        """
        user = get_logged_user()
        params = dict(
            title=request.json.get('title'),
            creator_id=user.id)

        optional_params = dict(
            description=request.json.get('description'),
            city_id=request.json.get('city_id'),
            minorlocality_id=request.json.get('minorlocality_id'),
            parent_group_id=request.json.get('parent_group_id'))

        if not all([v not in (None, '') for v in params.itervalues()]):
            return (jsonify(error=True), 400, [])

        if (optional_params['city_id'] is None and
                optional_params['minorlocality_id'] is not None):
            return (jsonify(error=True), 400, [])

        if (optional_params['parent_group_id'] is not None):
            parent_group = Group.query.filter_by(
                id=optional_params['parent_group_id']).first()
            if not parent_group:
                return (jsonify(error=True), 400, [])
            elif parent_group.city_id != optional_params['city_id']:
                return (jsonify(error=True), 400, [])

        params.update(optional_params)

        group = Group(**params)
        group.save(commit=True)
        return GroupByIDHandler._get(group)
Пример #9
0
    def post(self):
        logged_user = get_logged_user()
        success, params = self.validate(logged_user)

        if not success:
            return (jsonify(params), 400, [])

        activity = Activity(**params)
        activity.save(commit=True)
        activity.set_user_rsvp(logged_user, "yes")
        return ActivityByIDHandler._get(activity)
Пример #10
0
    def get(self, direction, msgtype):
        user = get_logged_user()
        if msgtype not in MESSAGE_TYPE_MAPPING:
            return ('TYPE', 400, [])

        try:
            msg_list = filter_by_direction(msgtype, direction, user)
        except ValueError:
            return ('DIRECTION', 400, [])

        resp = [msg.serialized_func(user) for msg in msg_list]
        return jsonify(resp)
Пример #11
0
    def post(self, direction, msgtype):
        user = get_logged_user()
        if direction != 'out':
            return ('NOT ALLOWED', 403, [])

        logged_user = get_logged_user()
        if msgtype not in MESSAGE_TYPE_MAPPING:
            return ('TYPE', 400, [])
        msg_dict = MESSAGE_TYPE_MAPPING[msgtype]

        msg_class, msg_validator = (
            msg_dict['class'],
            getattr(self, msg_dict['validator']))

        success, param_dict = getattr(
            self, msg_dict['validator'])(logged_user)
        if not success:
            return (jsonify(param_dict), 400, [])

        msg = msg_class(**param_dict)
        msg.send_to(*msg.recipient_list)
        return jsonify(msg.serialized_func(user))
Пример #12
0
    def get(self, conntype):
        user = get_logged_user()
        if conntype not in CONNECTION_TYPE_MAPPING:
            return ('TYPE', '400', [])
        conn_dict = CONNECTION_TYPE_MAPPING[conntype]

        conn_class = conn_dict['class']

        conn_list = conn_class.query.filter(or_(
            conn_class.user_from_id == user.id,
            conn_class.user_to_id == user.id)).all()
        resp = [conn.serializer_func(user) for conn in conn_list]
        return jsonify(resp)
Пример #13
0
    def get(self, direction, msgtype, id):
        user = get_logged_user()
        if msgtype not in MESSAGE_TYPE_MAPPING:
            return ('TYPE', 400, [])
        try:
            msg_list = filter_by_direction(
                msgtype, direction, user, additional_filters={'id': id})
        except ValueError:
            return ('DIRECTION', 400, [])
        if not msg_list:
            return ('NOT FOUND', 404, [])
        msg = msg_list[0]

        return jsonify(msg.serialized_func(user))
Пример #14
0
    def _patch(cls, user):
        params = dict(
            first_name=request.json.get('first_name'),
            last_name=request.json.get('last_name'),
            birth_date=request.json.get('birth_date'),
            email=request.json.get('email'),
            gender=request.json.get('gender'),
            city_id=request.json.get('city_id'))

        # password handling
        password = request.json.get('password')
        if password:
            user.set_and_encrypt_password(password)

        # "normal" param handling
        for (key, val) in params.iteritems():
            if val is None:
                continue

            curval = getattr(user, key, None)
            if curval != val:
                setattr(user, key, val)

        # profile details are stored in a different table
        profile_details = request.json.get('details')
        if profile_details:
            detail_object = user.details
            for (key, val) in profile_details.iteritems():
                if key not in ('websites', 'profile_details', 'sections'):
                    continue

                if val and not detail_object:
                    # detail entry not present, must be created
                    detail_object = UserProfileDetails(user_id=user.id)
                    setattr(detail_object, key, val)
                else:
                    if not detail_object:
                        continue  # no need to create a new entry for now

                    # update existing entry if needed
                    curval = getattr(detail_object, key, None)
                    if curval != val:
                        setattr(detail_object, key, val)

            if detail_object:
                # save details here (commit comes later)
                detail_object.save()

        user.save(commit=True)
        return jsonify(user.serialized)
Пример #15
0
 def get(self):
     """
     Currently not implemented.
     """
     ALLOWED_FILTERS = frozenset([
         'city_id', 'gender', 'age',
         'n_refs', 'n_friends', 'has_details',
         'can_host', 'keywords'])
     search_dict = parse_search_fields()
     if search_dict.get('fields'):
         # only some filters are allowed
         search_dict['fields'] = dict(
             (k, v) for k, v in search_dict['fields'].iteritems()
             if k in ALLOWED_FILTERS)
     resp = query(User, **search_dict)
     return jsonify([obj.serialized for _, obj in resp] if resp else [])
Пример #16
0
 def get(self, loctype):
     logged_user = get_logged_user()
     if loctype not in LOCATION_TYPE_MAPPING:
         return ('TYPE', '400', [])
     location_class = LOCATION_TYPE_MAPPING[loctype]
     #loc_query = location_class.query
     #if logged_user:
     #    make_point = lambda c: func.ST_SetSRID(
     #        func.ST_Point(c.x, c.y), 4326)
     #    loc_query = loc_query.filter(
     #        func.ST_Distance_Sphere(
     #            make_point(location_class.coordinates),
     #            make_point(logged_user.city.coordinates)) < 100000)
     fields = parse_search_fields()
     fields['query_field'] = 'name'
     resp = search.query(location_class, **fields)
     return jsonify([obj.serialized for _, obj in resp])
Пример #17
0
    def post(self, loctype):
        if loctype not in LOCATION_TYPE_MAPPING:
            return ('TYPE', '400', [])
        location_class = LOCATION_TYPE_MAPPING[loctype]

        params = dict(
            name=request.json.get('name'),
            country_id=request.json.get('country_id'),
            latitude=request.json.get('latitude'),
            longitude=request.json.get('longitude'))

        optional_params = dict(
            rating=request.json.get('rating'),
            timezone=request.json.get('timezone'),
            slug=request.json.get('slug'),
            wikiname=request.json.get('wikiname'))

        missing_vals = [(k, v) for (k, v) in params.iteritems()
                        if v in (None, '')]
        if missing_vals:
            error_dict = build_error_dict([
                '"%s" not specified' % k for (k, _) in missing_vals])
            return (jsonify(error_dict), 400, [])

        params.update(optional_params)

        params['coordinates'] = WKTSpatialElement(
            'POINT(%s %s)' % (
                params.get('latitude'),
                params.get('longitude')))
        del params['latitude']
        del params['longitude']

        location = location_class(**params)
        location.save(commit=True)
        return LocationByIDHandler._get(loctype, location)
Пример #18
0
 def _get(cls, group):
     resp = group.serialized
     return jsonify(resp)
Пример #19
0
 def delete(self):
     logout()
     return jsonify(success=True)
Пример #20
0
 def _get(cls, loctype, location):
     resp = location.serialized
     resp['type'] = loctype
     return jsonify(resp)
Пример #21
0
 def get(self):
     # TODO - TO BE IMPROVED
     return jsonify([o.serialized for o in Activity.query.all()])
Пример #22
0
 def _get(cls, activity):
     return jsonify(activity.serialized)