def delete(self, id: int):
     property_db = Property.query.filter_by(
         id=id).first_or_404("Property not found")
     # delete folder with image from storage
     MagicImage.delete_folder(name_folder=property_db.slug,
                              path_delete='properties/')
     property_db.delete_from_db()
     return {"message": "Success delete property."}, 200
 def post(self):
     _image_schema = AddImageCategorySchema()
     file = _image_schema.load(request.files)
     data = _category_schema.load(request.form)
     # save image
     magic_image = MagicImage(file=file['image'],width=260,height=260,path_upload='categories/')
     magic_image.save_image()
     category = Category(name=data['name'],image=magic_image.FILE_NAME)
     category.save_to_db()
     return {"message":"Success add category."}, 201
Example #3
0
    def post(self):
        _image_schema = AddImageActivitySchema()
        files = _image_schema.load(request.files)
        data = _activity_schema.load(request.form)
        if Activity.query.filter_by(name=data['name']).first():
            raise ValidationError({'name':['The name has already been taken.']})

        magic_image = MagicImage(file=files,resize=550,path_upload='activities/')
        magic_image.save_image()
        files_name = magic_image.FILE_NAME

        args = {**files_name,**data}
        activity = Activity(**args)
        activity.save_to_db()
        return {"message":"Success add activity."}, 201
Example #4
0
 def delete(self,id: int):
     activity = Activity.query.filter_by(id=id).first_or_404('Activity not found')
     files = [activity.image,activity.image2,activity.image3,activity.image4]
     # delete all image in storage
     [MagicImage.delete_image(file=file,path_delete='activities/') for file in files]
     activity.delete_from_db()
     return {"message":"Success delete activity."}, 200
    def post(self):
        _image_schema = AddImageRegionSchema()
        file = _image_schema.load(request.files)
        data = _region_schema.load(request.form)
        if Region.query.filter_by(name=data['name']).first():
            raise ValidationError(
                {'name': ['The name has already been taken.']})

        magic_image = MagicImage(file=file['image'],
                                 width=2000,
                                 height=3000,
                                 path_upload='regions/',
                                 square=False)
        magic_image.save_image()
        region = Region(image=magic_image.FILE_NAME, **data)
        region.save_to_db()
        return {"message": "Success add region."}, 201
    def put(self, id: int):
        region = Region.query.filter_by(id=id).first_or_404('Region not found')
        _image_schema = UpdateImageRegionSchema()
        file = _image_schema.load(request.files)
        data = _region_schema.load(request.form)
        if region.name != data['name'] and Region.query.filter_by(
                name=data['name']).first():
            raise ValidationError(
                {'name': ['The name has already been taken.']})

        file_name = None
        if file:
            MagicImage.delete_image(file=region.image, path_delete='regions/')
            # save image
            magic_image = MagicImage(file=file['image'],
                                     width=2000,
                                     height=3000,
                                     path_upload='regions/',
                                     square=False)
            magic_image.save_image()
            file_name = magic_image.FILE_NAME

        region.update_data_in_db(image=file_name, **data)
        region.save_to_db()
        return {"message": "Success update region."}, 200
    def post(self):
        _image_schema = AddImageNewsletterSchema()
        file = _image_schema.load(request.files)
        data = _newsletter_schema.load(request.form)
        if Newsletter.query.filter_by(title=data['title']).first():
            raise ValidationError({'title':['The title has already been taken.']})

        slug = slugify(data['title'],lowercase=False)
        image = MagicImage(file=file['image'],width=3003,height=1287,path_upload='newsletters/',
            dir_name=slug,square=False)
        image.save_image()

        thumbnail = MagicImage(file=file['image'],width=1024,height=686,path_upload='newsletters/',
            dir_name=slug,square=False)
        thumbnail.save_image()

        newsletter = Newsletter(slug=slug,image=image.FILE_NAME,thumbnail=thumbnail.FILE_NAME,**data)
        newsletter.save_to_db()
        # send email notification to subscriber
        access_token = create_access_token(identity=get_jwt_identity())
        title_email = newsletter.title[:25] + '...' if len(newsletter.title) > 25 else newsletter.title
        with current_app.test_client() as client:
            client.post(
                '/send-email/subscriber',
                headers={'Authorization':f"Bearer {access_token}"},
                json={
                    'subscribe_type':'newsletter',
                    'subject': f"Newsletter: {title_email}",
                    'html':'email/EmailNewsletter.html',
                    'content': {
                        'image': f"{os.getenv('BACKEND_URL')}/static/newsletters/{newsletter.slug}/{newsletter.thumbnail}",
                        'link': f"{os.getenv('APP_URL')}/news/{newsletter.slug}",
                        'title': newsletter.title,
                        'description': newsletter.description,
                        'created_at': newsletter.created_at.strftime("%d %B %Y"),
                        'unsubscribe': f"{os.getenv('APP_URL')}?unsubscribe=email"
                    }
                }
            )
        # revoke token after send notification email
        ACCESS_EXPIRES = int(os.getenv("ACCESS_TOKEN_EXPIRES"))
        access_jti = get_jti(encoded_token=access_token)
        conn_redis.set(access_jti, 'true', ACCESS_EXPIRES)

        return {"message":"Success add newsletter."}, 201
Example #8
0
    def put(self):
        _update_avatar_schema = UpdateAvatarSchema()
        args = _update_avatar_schema.load(request.files)
        user = User.query.get(get_jwt_identity())
        if user.avatar != 'default.png':
            MagicImage.delete_image(file=user.avatar,path_delete='avatars/')

        magic_image = MagicImage(file=args['avatar'],width=260,height=260,path_upload='avatars/')
        magic_image.save_image()

        user.avatar = magic_image.FILE_NAME
        user.change_update_time()
        user.save_to_db()
        return {"message":"Image profile has updated."}, 200
    def put(self,id: int):
        category = Category.query.filter_by(id=id).first_or_404('Category not found')
        _image_schema = UpdateImageCategorySchema()
        file = _image_schema.load(request.files)
        data = _category_schema.load(request.form)
        if file:
            MagicImage.delete_image(file=category.image,path_delete='categories/')
            # save image
            magic_image = MagicImage(file=file['image'],width=260,height=260,path_upload='categories/')
            magic_image.save_image()
            category.image = magic_image.FILE_NAME

        category.name = data['name']
        category.change_update_time()
        category.save_to_db()
        return {"message":"Success update category."}, 200
Example #10
0
 def post(self):
     _image_schema = AddImageVoucherSchema()
     file = _image_schema.load(request.files)
     data = _voucher_schema.load(request.form)
     # save image voucher
     magic_image = MagicImage(file=file['image'],
                              width=2000,
                              height=300,
                              path_upload='vouchers/',
                              square=False)
     magic_image.save_image()
     image = magic_image.FILE_NAME
     # crop image voucher to make thumbnail
     magic_image = MagicImage(file=file['image'],
                              width=650,
                              height=300,
                              path_upload='vouchers/thumbnail/',
                              square=False)
     magic_image.save_image()
     thumbnail = magic_image.FILE_NAME
     # save to db
     voucher = Voucher(**data, image=image, thumbnail=thumbnail)
     voucher.save_to_db()
     return {"message": "Success add voucher."}, 201
    def post(self, id: int):
        property_db = Property.query.filter_by(
            id=id).first_or_404("Property not found")
        _delete_property_schema = DeleteImagePropertySchema()
        data = request.get_json()
        args = _delete_property_schema.load(data)
        # check image still 5
        images = [x.split('/')[-1] for x in args['images']]
        delete_image = property_db.images.split(',')
        [delete_image.remove(x) for x in images]
        if len(delete_image) < 5:
            raise ValidationError(
                {'images': ['Minimum 5 images to be upload']})

        # delete image from storage
        [
            MagicImage.delete_image(file=file,
                                    path_delete='properties/{}'.format(
                                        property_db.slug)) for file in images
        ]
        # update image to db
        property_db.images = ','.join(delete_image)
        property_db.save_to_db()
        return {"message": "Success delete image."}, 200
    def put(self,id: int):
        newsletter = Newsletter.query.filter_by(id=id).first_or_404('Newsletter not found')
        _image_schema = UpdateImageNewsletterSchema()
        file = _image_schema.load(request.files)
        data = _newsletter_schema.load(request.form)

        if newsletter.title != data['title'] and Newsletter.query.filter_by(title=data['title']).first():
            raise ValidationError({'title':['The title has already been taken.']})

        slug = slugify(data['title'],lowercase=False)
        # change folder name if name in db not same with data
        if newsletter.title != data['title']:
            MagicImage.rename_folder(old_name=newsletter.slug,new_name=slug,path_update='newsletters/')

        image_name = None
        thumbnail_name = None
        if file:
            # delete image and thumbnail
            MagicImage.delete_image(file=newsletter.image,path_delete='newsletters/{}'.format(slug))
            MagicImage.delete_image(file=newsletter.thumbnail,path_delete='newsletters/{}'.format(slug))
            # save image
            image = MagicImage(file=file['image'],width=3003,height=1287,path_upload='newsletters/',
                dir_name=slug,square=False)
            image.save_image()
            image_name = image.FILE_NAME

            thumbnail = MagicImage(file=file['image'],width=1024,height=686,path_upload='newsletters/',
                dir_name=slug,square=False)
            thumbnail.save_image()
            thumbnail_name = thumbnail.FILE_NAME

        newsletter.update_data_in_db(slug=slug,image=image_name,thumbnail=thumbnail_name,**data)
        newsletter.change_update_time()
        newsletter.save_to_db()
        return {"message":"Success update newsletter."}, 200
 def delete(self,id: int):
     newsletter = Newsletter.query.filter_by(id=id).first_or_404('Newsletter not found')
     # delete folder with image from storage
     MagicImage.delete_folder(name_folder=newsletter.slug,path_delete='newsletters/')
     newsletter.delete_from_db()
     return {"message":"Success delete newsletter."}, 200
Example #14
0
 def delete(self, id: int):
     category = Category.query.filter_by(
         id=id).first_or_404('Category not found')
     MagicImage.delete_image(file=category.image, path_delete='categories/')
     category.delete_from_db()
     return {"message": "Success delete category."}, 200
    def put(self, id: int):
        activity = Activity.query.filter_by(
            id=id).first_or_404('Activity not found')
        _image_schema = UpdateImageActivitySchema()
        files = _image_schema.load(request.files)
        data = _activity_schema.load(request.form)
        if activity.name != data['name'] and Activity.query.filter_by(
                name=data['name']).first():
            raise ValidationError(
                {'name': ['The name has already been taken.']})

        files_name = dict()
        if files:
            # delete image if exists
            for index in files.keys():
                if index == 'image':
                    MagicImage.delete_image(file=activity.image,
                                            path_delete='activities/')
                if index == 'image2':
                    MagicImage.delete_image(file=activity.image2,
                                            path_delete='activities/')
                if index == 'image3':
                    MagicImage.delete_image(file=activity.image3,
                                            path_delete='activities/')
                if index == 'image4':
                    MagicImage.delete_image(file=activity.image4,
                                            path_delete='activities/')
            # save image
            magic_image = MagicImage(file=files,
                                     width=550,
                                     height=550,
                                     path_upload='activities/')
            magic_image.save_image()
            files_name = magic_image.FILE_NAME

        # update data in database
        args = {**files_name, **data}
        activity.update_data_in_db(**args)
        activity.change_update_time()
        activity.save_to_db()
        return {"message": "Success update activity."}, 200
 def delete(self, id: int):
     region = Region.query.filter_by(id=id).first_or_404('Region not found')
     MagicImage.delete_image(file=region.image, path_delete='regions/')
     region.delete_from_db()
     return {"message": "Success delete region."}, 200
    def post(self):
        _image_schema = AddImagePropertySchema()
        files = _image_schema.load(request.files)
        data = _property_schema.load(request.form)
        # delete data unnecessarily before validate
        ValidateProperty.delete_data_unnecessarily(data)

        if len(files['images']) < 5:
            raise ValidationError(
                {'images': ['Minimum 5 images to be upload']})
        # check name exists in db
        if Property.query.filter_by(name=data['name']).first():
            raise ValidationError(
                {'name': ['The name has already been taken.']})

        if 'facility' in data:
            ValidateProperty.check_facility(data['facility'])
        # save images
        slug = slugify(data['name'], lowercase=False)
        magic_image = MagicImage(file=files['images'],
                                 width=1200,
                                 height=800,
                                 path_upload='properties/',
                                 square=False,
                                 dir_name=slug,
                                 watermark='center')
        magic_image.save_image()
        images = ','.join(magic_image.FILE_NAME.values())
        # save data to db
        property_db = Property(**data, slug=slug, images=images)
        property_db.save_to_db()
        # save price to db
        property_price = PropertyPrice(**data, property_id=property_db.id)
        property_price.save_to_db()
        if 'facility' in data:
            # many to many between property and facility
            [
                property_db.facilities.append(Facility.query.get(
                    int(facility))) for facility in data['facility'].split(',')
            ]
            property_db.save_to_db()

        # send email notification to subscriber
        access_token = create_access_token(identity=get_jwt_identity())
        first_image = property_db.images.split(',')[0]
        title_email = property_db.name[:25] + '...' if len(
            property_db.name) > 25 else property_db.name
        with current_app.test_client() as client:
            client.post(
                '/send-email/subscriber',
                headers={'Authorization': f"Bearer {access_token}"},
                json={
                    'subscribe_type': 'property',
                    'subject': f"Property: {title_email}",
                    'html': 'email/EmailProperty.html',
                    'content': {
                        'image':
                        f"{os.getenv('BACKEND_URL')}/static/properties/{property_db.slug}/{first_image}",
                        'link':
                        f"{os.getenv('APP_URL')}/property/{property_db.slug}",
                        'name': property_db.name,
                        'description': property_db.description,
                        'created_at':
                        property_db.created_at.strftime("%d %B %Y"),
                        'unsubscribe':
                        f"{os.getenv('APP_URL')}?unsubscribe=email"
                    }
                })
        # revoke token after send notification email
        ACCESS_EXPIRES = int(os.getenv("ACCESS_TOKEN_EXPIRES"))
        access_jti = get_jti(encoded_token=access_token)
        conn_redis.set(access_jti, 'true', ACCESS_EXPIRES)

        return {"message": "Success add property."}, 201
    def put(self, id: int):
        property_db = Property.query.filter_by(
            id=id).first_or_404("Property not found")
        _image_schema = UpdateImagePropertySchema()
        files = _image_schema.load(request.files)
        data = _property_schema.load(request.form)
        # delete data unnecessarily before validate
        ValidateProperty.delete_data_unnecessarily(data)
        # check name exists in db
        if property_db.name != data['name'] and Property.query.filter_by(
                name=data['name']).first():
            raise ValidationError(
                {'name': ['The name has already been taken.']})

        if 'facility' in data:
            ValidateProperty.check_facility(data['facility'])

        slug = slugify(data['name'], lowercase=False)
        # change folder name if name in db not same with data
        if property_db.name != data['name']:
            MagicImage.rename_folder(old_name=property_db.slug,
                                     new_name=slug,
                                     path_update='properties/')

        # clear data in db before update
        property_db.property_for = None
        property_db.period = None
        property_db.status = None
        property_db.bedroom = None
        property_db.bathroom = None
        property_db.building_size = None

        if files:
            # save to storage
            magic_image = MagicImage(file=files['images'],
                                     width=1200,
                                     height=800,
                                     path_upload='properties/',
                                     square=False,
                                     dir_name=slug,
                                     watermark='center')
            magic_image.save_image()
            images = ','.join(magic_image.FILE_NAME.values())
            # save to db
            property_db.update_data_in_db(**data, slug=slug, images=images)
            property_db.save_to_db()
        else:
            property_db.update_data_in_db(**data, slug=slug)
            property_db.save_to_db()

        # clear data in db before update
        property_db.price.freehold_price = None
        property_db.price.leasehold_price = None
        property_db.price.leasehold_period = None
        property_db.price.daily_price = None
        property_db.price.weekly_price = None
        property_db.price.monthly_price = None
        property_db.price.annually_price = None
        # save to db
        property_db.price.update_data_in_db(**data)
        property_db.price.save_to_db()

        # delete all relationship from facilities
        property_db.delete_facilities()
        if 'facility' in data:
            # many to many between property and facility
            [
                property_db.facilities.append(Facility.query.get(
                    int(facility))) for facility in data['facility'].split(',')
            ]
            property_db.save_to_db()
        # change update time in db
        property_db.change_update_time()
        property_db.save_to_db()
        return {"message": "Success update property."}, 200