Exemple #1
0
def uploadImage():
    try:
        data = request.get_json()['imgFile']
        image = data['imgFile']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    extension = data['extension']
    try:
        imageName = saveToImage(imageFile=image, extension=extension)
    except Exception:
        return ErrorResponse(ImageNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    uid = data['uid']
    fetch_user = User.getUser(user_id=uid)
    if fetch_user is None:
        return ErrorResponse(
            UserNotFound(uid).message, 422, {
                'Content-Type': 'application/json'
            }).respond()

    file_upload = File(filename=imageName,
                       filetype='image',
                       uploader=fetch_user)
    file_upload.save_to_db()
    return jsonify(ImageFileSchema().dump(file_upload).data)
Exemple #2
0
def upload_manual_data():
    try:
        data = request.get_json()['data']['attributes']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    if not data.get('manual_data'):
        return ErrorResponse(ManualDataNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    uid = data.get('uid')
    manual_data = data.get('manual_data')
    fetch_user = User.getUser(user_id=uid)
    if fetch_user is None:
        return ErrorResponse(
            UserNotFound(uid).message, 422, {
                'Content-Type': 'application/json'
            }).respond()

    try:
        csvName = saveAsCSV(csvData=manual_data)
    except Exception:
        return ErrorResponse(OperationNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    file_upload = File(filename=csvName, filetype='csv', uploader=fetch_user)
    file_upload.save_to_db()
    return jsonify(ManualFileSchema().dump(file_upload).data)
Exemple #3
0
def upload_default():
    try:
        data = request.get_json()['data']['attributes']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    uid = data.get('uid')
    image_name = data.get('defaultImage')
    image_data = None
    with open(
            os.path.join(app.config.get('BASE_DIR'), 'badge_backgrounds',
                         image_name), "rb") as image_file:
        image_data = base64.b64encode(image_file.read())

    try:
        imageName = saveToImage(imageFile=image_data.decode('utf-8'),
                                extension=".png")
    except Exception as e:
        print(e)
        return ErrorResponse(ImageNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    fetch_user = User.getUser(user_id=uid)
    file_upload = File(filename=imageName,
                       filetype='image',
                       uploader=fetch_user)
    file_upload.save_to_db()
    return jsonify(DefImageSchem().dump(file_upload).data)
Exemple #4
0
    def put(self, file_id):
        try:
            update_fields = {}
            parser = reqparse.RequestParser()

            parser.add_argument('name',
                                type=str,
                                help="New name for the file/folder")
            parser.add_argument('parent_id',
                                type=str,
                                help="New parent folder for the file/folder")

            args = parser.parse_args()

            name = args.get('name', None)
            parent_id = args.get('parent_id', None)

            if name is not None:
                update_fields['name'] = name

            if parent_id is not None and g.file['parent_id'] != parent_id:
                if parent_id != '0':
                    folder_access = Folder.filter({
                        'id': parent_id,
                        'creator': g.user_id
                    })
                    if not folder_access:
                        abort(
                            404,
                            message=
                            "You don't have access to the folder you're trying to move this object to"
                        )

                if g.file['is_folder']:
                    update_fields['tag'] = g.file[
                        'id'] if parent_id == '0' else "{0}#{1}".format(
                            folder_access['tag'], folder['last_index'])
                    Folder.move(g.file, folder_access)
                else:
                    File.move(g.file, folder_access)

                update_fields['parent_id'] = parent_id

            if g.file['is_folder']:
                Folder.update(file_id, update_fields)
            else:
                File.update(file_id, update_fields)

            return File.find(file_id)
        except Exception as e:
            abort(500,
                  message="There was an while processing your request --> {0}".
                  format(e))
Exemple #5
0
 def get(self):
     try:
         return File.filter({'creator': g.user_id})
     except Exception as e:
         abort(500,
               message=
               "There was an error while trying to get your files --> {0}".
               format(e))
Exemple #6
0
    def get_file_names(self, request, pk=None):
        serializer = self.serializer_class(data=request.data)

        if serializer.exists():
            user = User.objects.get(email=serializer.data['email'])
            id_file = File.id_file(user)
            selfie = File.selfie(user)

            return Response(
                {
                    'selfie': selfie.name if selfie else '',
                    'id_file': id_file.name if id_file else '',
                },
                status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Exemple #7
0
    def func(*args, **kwargs):
        file_id = kwargs.get('file_id')

        payload = _decode_jwt()
        g.user_id = payload['id']

        file = File.find(file_id, True)
        if not file or file['creator'] != g.user_id:
            abort(404, message="The file you are trying to access was not found")
        g.file = file
        return f(*args, **kwargs)
Exemple #8
0
    def post(self):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('image_data',
                                type=str,
                                help="Image Base, base64 format")
            parser.add_argument('name', type=str, help="Site Title")
            parser.add_argument('url', type=str, help="URL")

            args = parser.parse_args()

            image_data = args.get('image_data', None)
            name = args.get('name', None)
            url = args.get('url', False)

            parent = None

            _path = os.path.join(current_app.config['UPLOAD_FOLDER'],
                                 g.user_id)
            _dir = os.path.join(BASE_DIR, "{0}/".format(_path))

            if not os.path.isdir(_dir):
                os.mkdir(_dir)

            filename = secure_filename("{0}.png".format(rand_str(10)))
            to_path = os.path.join(_dir, filename)

            pattern = re.compile(r'^data:image/png;base64,', re.IGNORECASE)
            image_data = re.sub(pattern, '', image_data)

            img_bytes = base64.b64decode(image_data)
            with open(to_path, 'bw+') as f:
                f.write(img_bytes)

            print(to_path)

            fileuri = os.path.join("{0}/".format(_path), filename)
            filesize = os.path.getsize(to_path)

            return File.create(name=filename,
                               uri=fileuri,
                               size=filesize,
                               parent=parent,
                               creator=g.user_id,
                               siteName=name,
                               url=url)

        except Exception as e:
            abort(500,
                  message=
                  "There was an error while processing your request --> {0}".
                  format(e))
Exemple #9
0
def background_color():
    try:
        data = request.get_json()['data']['attributes']
        bg_color = data['bg_color']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    svg2png = SVG2PNG()

    bg_color = '#' + str(bg_color)
    user_defined_path = svg2png.do_svg2png(1, bg_color)
    with open(user_defined_path, "rb") as image_file:
        image_data = base64.b64encode(image_file.read())
        os.remove(user_defined_path)

    try:
        imageName = saveToImage(imageFile=image_data.decode('utf-8'),
                                extension=".png")
    except Exception:
        return ErrorResponse(ImageNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    uid = data['uid']
    fetch_user = User.getUser(user_id=uid)
    if fetch_user is None:
        return ErrorResponse(
            UserNotFound(uid).message, 422, {
                'Content-Type': 'application/json'
            }).respond()

    file_upload = File(filename=imageName,
                       filetype='image',
                       uploader=fetch_user)
    file_upload.save_to_db()
    return jsonify(ColorImageSchema().dump(file_upload).data)
Exemple #10
0
 def get(self, file_id):
     try:
         file_data = File.find(file_id)
         #print(file_data)
         parts = os.path.split(file_data['uri'])
         file_path = os.path.join(BASE_DIR, parts[0])
         #print(file_path)
         return send_from_directory(directory=file_path,
                                    filename=parts[1],
                                    as_attachment=True)
     except Exception as e:
         abort(500,
               message="There was an while processing your request --> {0}".
               format(e))
Exemple #11
0
 def get_basic(self, request, pk=None):
     serializer = self.serializer_class(data=request.data)
     if serializer.exists():
         user = User.objects.get(email=serializer.data['email'])
         return Response(
             {
                 'name': str(user),
                 'profile': File.selfie(user),
                 # Add level later when game-ifying
             },
             status=status.HTTP_200_OK)
     else:
         return Response(serializer.email_error,
                         status=status.HTTP_400_BAD_REQUEST)
Exemple #12
0
def fileUpload():
    try:
        data = request.json['csvFile']
        csv = data['csvFile']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    if 'extension' not in data.keys():
        return ErrorResponse(ExtensionNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    extension = data['extension']
    if extension != 'csv':
        return ErrorResponse(CSVNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()
    try:
        csvName = saveToCSV(csvFile=csv, extension='.csv')
    except Exception:
        return ErrorResponse(OperationNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    uid = data.get('uid')
    fetch_user = User.getUser(user_id=uid)
    if fetch_user is None:
        return ErrorResponse(
            UserNotFound(uid).message, 422, {
                'Content-Type': 'application/json'
            }).respond()

    file_upload = File(filename=csvName, filetype='csv', uploader=fetch_user)
    file_upload.save_to_db()
    return jsonify(CSVUploadSchema().dump(file_upload).data)
Exemple #13
0
 def delete(self, file_id):
     try:
         hard_delete = request.args.get('hard_delete', False)
         if not g.file['is_folder']:
             if hard_delete == 'true':
                 os.remove(g.file['uri'])
                 File.delete(file_id)
             else:
                 File.update(file_id, {'status': False})
         else:
             if hard_delete == 'true':
                 folders = Folder.filter(
                     lambda folder: folder['tag'].startswith(g.file['tag']))
                 for folder in folders:
                     files = File.filter({
                         'parent_id': folder['id'],
                         'is_folder': False
                     })
                     File.delete({
                         'parent_id': folder['id'],
                         'is_folder': False
                     })
                     for f in files:
                         os.remove(f['uri'])
             else:
                 File.update(file_id, {'status': False})
                 File.update({'parent_id': file_id}, {'status': False})
         return "File has been deleted successfully", 204
     except:
         abort(500,
               message=
               "There was an error while processing your request --> {0}".
               format(e))
Exemple #14
0
    def post(self):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('image_data',
                                type=str,
                                help="Image Base, base64 format")
            parser.add_argument('site_name', type=str, help="Site Title")
            parser.add_argument('url', type=str, help="URL")

            args = parser.parse_args()

            image_data = args.get('image_data', None)
            site_name = args.get('site_name', None)
            url = args.get('url', False)

            parent = None

            _path = os.path.join(current_app.config['UPLOAD_FOLDER'],
                                 g.user_id)
            _dir = os.path.join(BASE_DIR, "{0}/".format(_path))

            if not os.path.isdir(_dir):
                os.mkdir(_dir)

            filename = secure_filename("{0}.png".format(rand_str(10)))
            to_path = os.path.join(_dir, filename)

            pattern = re.compile(r'^data:image/png;base64,', re.IGNORECASE)
            image_data = re.sub(pattern, '', image_data)

            img_bytes = base64.b64decode(image_data)
            with open(to_path, 'bw+') as f:
                f.write(img_bytes)

            print(to_path)

            fileuri = os.path.join("{0}/".format(_path), filename)
            filesize = os.path.getsize(to_path)

            new_file = File.create(name=filename,
                                   uri=fileuri,
                                   size=filesize,
                                   parent=parent,
                                   creator=g.user_id,
                                   site_name=site_name,
                                   url=url)

            try:
                token = jwt.encode({'id': g.user_id},
                                   current_app.config['SECRET_KEY'],
                                   algorithm='HS256')
            except JWTError:
                raise ValidationError(
                    "There was a problem while trying to create a JWT token.")

            first_task_id = ocr_pipeline(token, new_file['id'])
            logger.warn('first_task_id')

            return new_file

        except Exception as e:
            abort(500,
                  message=
                  "There was an error while processing your request --> {0}".
                  format(e))
Exemple #15
0
    def post(self):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument(
                'name',
                type=str,
                help="This should be the folder name if creating a folder")
            parser.add_argument('parent_id',
                                type=str,
                                help='This should be the parent folder id')
            parser.add_argument(
                'is_folder',
                type=bool,
                help=
                "This indicates whether you are trying to create a folder or not"
            )

            args = parser.parse_args()

            name = args.get('name', None)
            parent_id = args.get('parent_id', None)
            is_folder = args.get('is_folder', False)

            parent = None

            # Are we adding this to a parent folder?
            if parent_id is not None:
                parent = File.find(parent_id)
                if parent is None:
                    raise Exception("This folder does not exist")
                if not parent['is_folder']:
                    raise Exception("Select a valid folder to upload to")
            # Are we creating a folder?

            if is_folder:
                if name is None:
                    raise Exception(
                        "You need to specify a name for this folder")

                return Folder.create(name=name,
                                     parent=parent,
                                     is_folder=is_folder,
                                     creator=g.user_id)

            else:
                files = request.files['file']

                if files:
                    if not is_allowed(files.filename):
                        raise Exception("File not allowed: {0}".format(
                            files.filename))

                    _path = os.path.join(current_app.config['UPLOAD_FOLDER'],
                                         g.user_id)
                    _dir = os.path.join(BASE_DIR, "{0}/".format(_path))

                    if not os.path.isdir(_dir):
                        os.mkdir(_dir)

                    filetitle, fileext = os.path.splitext(files.filename)
                    filename = secure_filename("{0}_{1}{2}".format(
                        filetitle, rand_str(10), fileext))
                    to_path = os.path.join(_dir, filename)
                    files.save(to_path)
                    fileuri = os.path.join("{0}/".format(_path), filename)
                    filesize = os.path.getsize(to_path)

                    return File.create(name=filename,
                                       uri=fileuri,
                                       size=filesize,
                                       parent=parent,
                                       creator=g.user_id)
                raise Exception(
                    "You did not supply a valid file in your request")

        except Exception as e:
            abort(500,
                  message=
                  "There was an error while processing your request --> {0}".
                  format(e))
Exemple #16
0
def get_file():
    input_data = request.args
    file = File().query.filter_by(filename=input_data.get('filename')).first()
    return jsonify(FileSchema().dump(file).data)