Exemplo n.º 1
0
 def post(self, id_, *args, **kwargs):
     """
     @apiVersion 0.1.0
     @api {post} /notes/{id}/favor/ Favor a note.
     @apiName FavorNote
     @apiGroup Notes
     @apiUse TokenRequired
     @apiDescription Favor a note.
     @apiUse BadRequest
     @apiSuccess 200 Success-Response:
     @apiUse NoSuchUserError
     @apiSuccessExample Success-Response
       HTTP/1.1 200 OK
       {
         "message": "added note {note_name} to your favorites"
       }
     """
     user_id = kwargs.get('user')['user_id']
     user = user_model.User.query.get(user_id)
     note = note_model.Note.query.get(id_)
     if not user or not note:
         return response.simple_response('no such user or note', status=404)
     success = user.add_favorite(note)
     if not success:
         return response.simple_response(
             'you dont need to favor this note again :-)', status=401)
     db.session.commit()
     return response.simple_response(
         'added note {0} to your favorites'.format(note.name))
Exemplo n.º 2
0
 def delete(self, *args, **kwargs):
     """
     @apiVersion 0.1.0
     @api {delete} /users/images/ Delete a profile pic
     @apiName DeleteProfilcePicture
     @apiGroup Users
     @apiUse TokenRequired
     @apiDescription Upload a profile pic.a
     @apiUse BadRequest
     @apiUse SuccessfullyDeleted
     @apiUse NoSuchUserError
     """
     user_id = kwargs.get('user')['user_id']
     user = model.User.query.get(user_id)
     if not user:
         return response.simple_response('no such user', status=404)
     profile_img_path = user.profile_img_path
     print profile_img_path
     if not profile_img_path:
         return response.simple_response('no profile image uploaded yet',
                                         status=404)
     APP_ROOT = config.Config().PROJECT_ROOT
     os.remove(os.path.join(APP_ROOT, profile_img_path))
     user.profile_img_path = None
     db.session.commit()
     return response.simple_response('deleted profile image')
Exemplo n.º 3
0
 def post(self, *args, **kwargs):
     """
     @apiVersion 0.1.0
     @api {post} /users/images/ Add a profile pic
     @apiName AddProfilePic
     @apiGroup Users
     @apiUse TokenRequired
     @apiDescription Upload a profile pic.
     @apiUse BadRequest
     @apiUse NoSuchUserError
     """
     if 'file' not in request.files:
         return response.simple('You have to provide a file', 404)
     user_id = kwargs.get('user')['user_id']
     user = model.User.query.get(user_id)
     if not user:
         return response.simple_response('no such user', status=404)
     file = request.files['file']
     if file.filename == '':
         return request.simple('Empty file', 404)
     if not self.allowed_file(file.filename):
         return response.simple_response('this kind of data is not allowed',
                                         400)
     if not file:
         response.simple_response('no file', 404)
     filename = secure_filename(file.filename)
     filename, file_extension = os.path.splitext(filename)
     new_filename = user.username + file_extension
     path_ = os.path.join(config.Config().UPLOAD_FOLDER_USER_PROFILE_IMAGES,
                          new_filename)
     path = os.path.join(config.Config().PROJECT_ROOT, path_)
     file.save(path)
     user.profile_img_path = path
     db.session.commit()
     return response.simple_response('saved image')
Exemplo n.º 4
0
 def delete(self, id_, *args, **kwargs):
     """
     @apiVersion 0.1.0
     @api {delete} /notes/{id}/favor/ Unfavor a note.
     @apiName UnfavorNote
     @apiGroup Notes
     @apiUse TokenRequired
     @apiDescription Unfavor a note.
     @apiUse BadRequest
     @apiSuccess 200 Success-Response:
     @apiUse NoSuchUserError
     @apiSuccessExample Success-Response
       HTTP/1.1 200 OK
       {
         "message": "removed note from your favorites"
       }
     """
     user_id = kwargs.get('user')['user_id']
     user = user_model.User.query.get(user_id)
     note = note_model.Note.query.get(id_)
     if not user or not note:
         return response.simple_response('no such user or note', status=404)
     if not note in user.favorite_notes:
         return response.simple_response('you did not favor this note',
                                         status=400)
     user.favorite_notes.remove(note)
     db.session.commit()
     return response.simple_response(
         'removed note {0} from your favorites'.format(note.name),
         status=200)
Exemplo n.º 5
0
 def put(self, id_, *args, **kwargs):
     """
     @apiVersion 0.1.0
     @api {put} /notes/{note_id}/ Modify a note.
     @apiName ModifyNote
     @apiGroup Notes
     @apiUse TokenRequired
     @apiDescription Modify a note.
     @apiUse BadRequest
     @apiParam {String} name The notes name.
     @apiParam {String} topic The notes topic.
     @apiParam {String} content The notes content.
     @apiUse NoSuchResourceError
     @apiUse SuccessfullyModified
     """
     parser = self.put_parser()
     args = parser.parse_args()
     user_id = kwargs.get('user')['user_id']
     user = user_model.User.query.get(user_id)
     note_to_modify = model.Note.query.get(id_)
     if not user or not note_to_modify:
         return response.simple_response('no such note or user', status=404)
     if note_to_modify in user.notes:
         message = u""
         for key, value in args.items():
             if key and value:
                 value = unicode(value)
                 setattr(note_to_modify, key, value)
                 message += u'{key} set to {value} | '.format(key=key,
                                                              value=value)
         db.session.commit()
         return response.simple_response(message)
     return response.simple_response(
         'you must be the creator of this note in order to modify it',
         status=401)
Exemplo n.º 6
0
 def delete(self, id_, *args, **kwargs):
     """
     @apiVersion 0.1.0
     @api {delete} /notes/{note_id}/ Delete a note.
     @apiName DeleteNote
     @apiGroup Notes
     @apiUse TokenRequired
     @apiDescription Delete a note.
     @apiUse BadRequest
     @apiSuccess 200 Success-Response:
     @apiUse NoSuchResourceError
     @apiUse SuccessfullyDeleted
     """
     user_id = kwargs.get('user')['user_id']
     user = user_model.User.query.get(user_id)
     note_to_delete = model.Note.query.get(id_)
     if not user or not note_to_delete:
         return response.simple_response('no such note or user', status=404)
     if note_to_delete in user.notes:
         if note_to_delete.image_path:
             APP_ROOT = config.Config().PROJECT_ROOT
             upload.delete_if_exists(
                 os.path.join(APP_ROOT, note_to_delete.image_path))
         db.session.delete(note_to_delete)
         db.session.commit()
         return response.simple_response('note deleted')
     return response.simple_response(
         'you must be the creator of this note in order to delete it',
         status=401)
Exemplo n.º 7
0
    def get(self, *args, **kwargs):
        """
        @apiVersion 0.1.0
        @api {get} /users/notes?favorites={true/false} Get a users (favorite) notes.
        @apiName UsersNotes
        @apiGroup Notes
        @apiUse TokenRequired
        @apiDescription Get a users note. If onlyFavorites is provided, this will return the users favorite notes.
        @apiUse BadRequest
        @apiSuccess 200 Success-Response:
        @apiUse NoSuchUserError
        @apiSuccessExample Success-Response
          HTTP/1.1 200 OK
        [
          {
            "content": "Der B-Baum ist so schoen! ",
            "group": {
              "topic_area": "Machine Learning",
              "protected": true,
              "id": 9,
              "name": "The Royals"
            },
            "name": "B-Baum",
            "creator": {
              "username": "******"
            },
            "topic": "Algorithmen",
            "id": 1
          }, .....
        ]
        """
        def with_count(notes):
            UM = user_model.User
            all_notes = notes
            marshalled = marshal(all_notes, note_model.Note.fields)
            for note in marshalled:
                count = UM.query.filter(
                    UM.favorite_notes.any(
                        model.Note.id == note['id'])).count()
                note.update({'favorite_count': count})
            return jsonify(marshalled)

        user_id = kwargs.get('user')['user_id']
        user = user_model.User.query.get(user_id)
        if not user:
            response.simple_response('no such user')
        favorites = request.args.get('favorites')
        if favorites:
            if favorites.lower() == 'true':
                return with_count(user.favorite_notes.all())
            if favorites.lower() not in ['true', 'false']:
                return response.simple_response(
                    'expected ?favorites=[true|false], got {0}'.format(
                        favorites))
        return with_count(user.notes.all())
Exemplo n.º 8
0
    def get(self, university, *args, **kwargs):
        """
        @apiVersion 0.1.0
        @api {get} /groups/{university}?isMember={true/false} Get all groups at a university.
        @apiName GetGroupsAtUniversity
        @apiDescription Returns a list of all groups at the specified university or, if you provide the parameter isMember
        you will receive a list of groups you are (not) a member of.
        @apiGroup Groups
        @apiUse TokenRequired
        @apiUse BadRequest
        @apiSuccess 200 message Success message.
        @apiSuccessExample Success-Response:
          HTTP/1.1 200 OK
          {
            'id': the groups id,
            'name': the groups name,
            'topic_area': the groups area of topic
            }

        @apiError NoSuchResourceError

        """
        user_id = kwargs.get('user')['user_id']
        user = user_model.User.query.get(user_id)
        uni = university_model.University.query.filter_by(
            name=university).first()
        if not uni:
            return response.simple_response('no such university')
        all_groups = uni.groups
        is_member = request.args.get('isMember')
        if is_member:
            if is_member.lower() == 'true':
                return jsonify(
                    marshal(user.groups,
                            model.Group.fields['only_id_and_name']))
            elif is_member.lower() == 'false':
                #user not in uni.groups
                g = all_groups.filter(~group_model.Group.members.any(
                    user_model.User.id == user_id)).order_by(
                        model.Group.id.desc()).all()
                return jsonify(
                    marshal(g, model.Group.fields['only_id_and_name']))
            else:
                return response.simple_response(
                    'expected is_member to be true or false, got {0}'.format(
                        is_member),
                    status=400)
        all_groups = all_groups.all()
        return jsonify(marshal(all_groups, model.Group.fields['only_id_and_name']))\
            if user and all_groups else response.simple('no such group or user', status=404)
Exemplo n.º 9
0
    def get(self, id, *args, **kwargs):
        """
        @apiVersion 0.1.0
        @api {get} /groups/{id}/ Get group at id.
        @apiName GetGroupAtId
        @apiGroup Groups
        @apiUse TokenRequired
        @apiUse BadRequest
        @apiSuccess 200 message Success message for group creation.
        @apiSuccessExample Success-Response:
          HTTP/1.1 200 OK
          {
            'id': the groups id,
            'name': the groups name,
            'topic_area': the groups area of topic,
            'description': the groups description,
             'protected':  true/false if the group is password protected,
            'members': [{name: users who are members of the group}]
            }

        @apiUse NoSuchResourceError

        """
        user_id = kwargs.get('user')['user_id']
        user = user_model.User.query.get(user_id)
        group = group_model.Group.query.get(id)
        if user and group:
            cpy = group_model.Group.fields['with_members'].copy()
            cpy.update({
                'im_a_member':
                fields.Boolean(attribute=lambda x: True
                               if user in group.members else False)
            })
            return jsonify(marshal(group, cpy))
        return response.simple_response('no such group or user', status=404)
Exemplo n.º 10
0
    def get(self, group_id, *args, **kwargs):
        """
        @apiVersion 0.1.0
        @api {get} /groups/{group_id}/notes/ Get a groups notes.
        @apiName GetGroupNotes
        @apiGroup Notes
        @apiUse TokenRequired
        @apiDescription Get a groups notes.
        @apiUse BadRequest
        @apiSuccess 200 Success-Response:
        @apiSuccessExample Success-Response
          HTTP/1.1 200 OK
          {
            [
            {
            'id': the notes id,
            'creator': the creators name,
            'group': the groups name the note was posted in,
            'name': the groups name,
            'topic': the groups topic,
            'content': the groups content
            'has_image': true/false
            }, ...]
            }

        """
        user_id = kwargs.get('user')['user_id']
        user = user_model.User.query.get(user_id)
        group = group_model.Group.query.get(group_id)
        if user and group:
            if user.is_member_of(group):
                # explicitly load because of lazy relationship
                notes = group.notes.all()
                marshalled = marshal(notes, model.Note.fields)
                UM = user_model.User
                for note_marshalled in marshalled:
                    count = UM.query.filter(
                        UM.favorite_notes.any(
                            model.Note.id == note_marshalled['id'])).count()
                    note_marshalled.update({'favorite_count': count})
                return jsonify(marshalled)
            else:
                return response.simple_response(
                    'no you are not a member of this group', status=404)
        return response.simple_response('no notes found', status=404)
Exemplo n.º 11
0
    def post(self, group_id, *args, **kwargs):
        """
        @apiVersion 0.1.0
        @api {post} /groups/{group_id}/notes/ Create a note.
        @apiName CreateNote
        @apiGroup Notes
        @apiDescription Create a new Note.
        @apiUse TokenRequired
        @apiUse BadRequest
        @apiUse SuccessfullyCreated
        @apiParam {String} name The notes name.
        @apiParam {String} topic The notes topic.
        @apiParam {String} [content] The notes content.
        @apiParam {image} [file] An optional image.
        @apiUse NoSuchUserError
        @apiUse CouldNotBeSavedError
        """

        user_id = kwargs.get('user')['user_id']
        parser = self.post_parser()
        args = parser.parse_args()
        post_in_group = group_model.Group.query.get(group_id)
        parent_user = user_model.User.query.get(user_id)
        if not parent_user or not post_in_group:
            return response.simple_response('no such user or group',
                                            status=404)
        if not parent_user.is_member_of(post_in_group):
            return response.simple_response(
                'you must be a member of this group', status=401)
        new_note = model.Note(args['name'], args['topic'], args['content'])
        if 'file' in request.files:
            path_ = upload.get_uploaded_image_and_save(
                save_to=config.Config().UPLOAD_FOLDER_NOTES_IMAGES)
            new_note.image_path = path_
        new_note.creator = parent_user
        new_note.group = post_in_group
        db.session.add(new_note)
        db.session.commit()
        return response.simple_response('note created ' + str(new_note.id),
                                        status=201)
Exemplo n.º 12
0
    def get(self, *args, **kwargs):
        """
        @apiVersion 0.1.0
        @api {get} /users/images/ Get a profile pic
        @apiName GetProfilePic
        @apiGroup Users
        @apiUse TokenRequired
        @apiDescription Upload a profile pic.
        @apiUse BadRequest
        @apiUse NoSuchUserError
        """
        user_id = kwargs.get('user')['user_id']
        user = model.User.query.get(user_id)
        if not user:
            return response.simple_response('no such user', status=404)
        profile_img_path = user.profile_img_path
        print profile_img_path
        if not profile_img_path:
            return response.simple_response('no profile image uploaded yet',
                                            status=404)

        return send_file(
            os.path.join(config.Config().PROJECT_ROOT, profile_img_path))
Exemplo n.º 13
0
 def get(self, id_, *args, **kwargs):
     """
     @apiVersion 0.1.0
     @api {get} /notes/{id}?image=[true|false] Get a note by id
     @apiName NoteById
     @apiGroup Notes
     @apiUse TokenRequired
     @apiDescription  Get a note by id.
     @apiUse BadRequest
     @apiSuccess 200 Success-Response:
     @apiUse NoSuchUserError
     @apiUse NoSuchResourceError
     @apiSuccessExample Success-Response
       HTTP/1.1 200 OK
     [
       {
         "content": "Der B-Baum ist so schoen! ",
         "group": {
           "topic_area": "Machine Learning",
           "protected": true,
           "id": 9,
           "name": "The Royals"
         },
         "name": "B-Baum",
         "creator": {
           "username": "******"
         },
         "topic": "Algorithmen",
         "id": 1,
         "has_image": true/false,
         "is_creator": true,
         "if_favorite": false,
         "favorite_count": 42
       }
     ]
     """
     user_id = kwargs.get('user')['user_id']
     user = user_model.User.query.get(user_id)
     note_to_return = model.Note.query.get(id_)
     if not user or not note_to_return:
         return response.simple_response('no such note or user', status=404)
     image = request.args.get('image')
     users_note_check = note_to_return.group_id in [
         group.id for group in user.groups
     ]
     if not users_note_check:
         return response.simple_response('this is not your note',
                                         status=401)
     if image:
         if not note_to_return.image_path:
             return response.simple_response('this note has no image', 404)
         if image.lower() == 'true':
             APP_ROOT = config.Config().PROJECT_ROOT
             return send_file(
                 os.path.join(APP_ROOT, note_to_return.image_path))
         if image.lower() not in ['true', 'false']:
             return response.simple_response(
                 'expected ?image=[true|false], got {0}'.format(image))
     additional_info = {
         'is_favorite':
         True if note_to_return in user.favorite_notes else False,
         'is_creator': True if note_to_return in user.notes else False
     }
     UM = user_model.User
     count = UM.query.filter(
         UM.favorite_notes.any(model.Note.id == note_to_return.id)).count()
     marshalled = marshal(note_to_return, note_model.Note.fields)
     marshalled_ = marshalled.copy()
     marshalled_.update(additional_info)
     marshalled_.update({'favorite_count': count})
     return jsonify(marshalled_)