Ejemplo n.º 1
0
    def attach(self,
               func,
               upload=None,
               url=None,
               disable_optimization=None,
               **kwargs):
        # the upload argument doesn't allow us to access the files if more than
        # one file is uploaded, as upload references the first file
        # therefore we have to recover the files from the request object
        Attachments = request.env[
            'ir.attachment']  # registry for the attachment table

        uploads = []
        message = None
        if not upload:  # no image provided, storing the link and the image name
            name = url.split("/").pop()  # recover filename
            attachment = Attachments.create({
                'name': name,
                'type': 'url',
                'url': url,
                'public': True,
                'res_model': 'ir.ui.view',
            })
            uploads += attachment.read(['name', 'mimetype', 'checksum', 'url'])
        else:  # images provided
            try:
                attachments = request.env['ir.attachment']
                for c_file in request.httprequest.files.getlist('upload'):
                    data = c_file.read()
                    try:
                        image = Image.open(cStringIO.StringIO(data))
                        w, h = image.size
                        if w * h > 42e6:  # Nokia Lumia 1020 photo resolution
                            raise ValueError(
                                u"Image size excessive, uploaded images must be smaller "
                                u"than 42 million pixel")
                        if not disable_optimization and image.format in (
                                'PNG', 'JPEG'):
                            data = tools.image_save_for_web(image)
                    except IOError, e:
                        pass

                    attachment = Attachments.create({
                        'name':
                        c_file.filename,
                        'datas':
                        data.encode('base64'),
                        'datas_fname':
                        c_file.filename,
                        'public':
                        True,
                        'res_model':
                        'ir.ui.view',
                    })
                    attachments += attachment
                uploads += attachments.read(
                    ['name', 'mimetype', 'checksum', 'url'])
            except Exception, e:
                logger.exception("Failed to upload image to attachment")
                message = unicode(e)
Ejemplo n.º 2
0
def compress_image(image):
    """
    Function to compress image accordingly.
    This function uses image_save_for_web-utility from tools.
    Max dimensions can be set on system parameters.
    Process of compressing image:
    - Calculate new image dimensions according to MAX_WIDTH and MAX_HEIGHT
    - Resize image with new dimensions
    - Compress using image_save_for_web -utility

    TODO: Fix MAX_WIDTH and MAX_HEIGHT to be fetched from ir.config_parameter

    :param image: Image data in binary
    :return: Compressed and resized image data in binary
    """
    MAX_WIDTH = 1080
    MAX_HEIGHT = 1080
    img = Image.open(BytesIO(image))
    (width, height) = img.size
    _logger.debug("Image starting size: (%s, %s)" % (width, height))
    if width > MAX_WIDTH or height > MAX_HEIGHT:
        if width > height:
            if width > MAX_WIDTH:
                new_height = int(round((MAX_WIDTH / float(width)) * height))
                new_width = MAX_WIDTH
        else:
            if height > MAX_HEIGHT:
                new_width = int(round((MAX_HEIGHT / float(height)) * width))
                new_height = MAX_HEIGHT
        img.thumbnail((new_width, new_height), Image.ANTIALIAS)
        _logger.debug("Compressed size: (%s, %s)" % (new_width, new_height))
    return image_save_for_web(img)
Ejemplo n.º 3
0
Archivo: main.py Proyecto: 10537/odoo
    def attach(self, upload=None, url=None, disable_optimization=None, filters=None, **kwargs):
        # the upload argument doesn't allow us to access the files if more than
        # one file is uploaded, as upload references the first file
        # therefore we have to recover the files from the request object
        Attachments = request.env['ir.attachment']  # registry for the attachment table

        uploads = []
        message = None
        if not upload: # no image provided, storing the link and the image name
            name = url.split("/").pop()                       # recover filename
            datas_fname = name
            if filters:
                datas_fname = filters + '_' + datas_fname
            attachment = Attachments.create({
                'name': name,
                'datas_fname': datas_fname,
                'type': 'url',
                'url': url,
                'public': True,
                'res_model': 'ir.ui.view',
            })
            uploads += attachment.read(['name', 'mimetype', 'checksum', 'url'])
        else:                                                  # images provided
            try:
                attachments = request.env['ir.attachment']
                for c_file in request.httprequest.files.getlist('upload'):
                    data = c_file.read()
                    try:
                        image = Image.open(io.BytesIO(data))
                        w, h = image.size
                        if w*h > 42e6: # Nokia Lumia 1020 photo resolution
                            raise ValueError(
                                u"Image size excessive, uploaded images must be smaller "
                                u"than 42 million pixel")
                        if not disable_optimization and image.format in ('PNG', 'JPEG'):
                            data = tools.image_save_for_web(image)
                    except IOError as e:
                        pass

                    name = c_file.filename
                    datas_fname = name
                    if filters:
                        datas_fname = filters + '_' + datas_fname
                    attachment = Attachments.create({
                        'name': name,
                        'datas': base64.b64encode(data),
                        'datas_fname': datas_fname,
                        'public': True,
                        'res_model': 'ir.ui.view',
                    })
                    attachments += attachment
                uploads += attachments.read(['name', 'mimetype', 'checksum', 'url'])
            except Exception as e:
                logger.exception("Failed to upload image to attachment")
                message = pycompat.text_type(e)

        return """<script type='text/javascript'>
            window.attachments = %s;
            window.error = %s;
        </script>""" % (json.dumps(uploads), json.dumps(message))
Ejemplo n.º 4
0
 def _image_to_attachment(self,
                          res_model,
                          res_id,
                          data,
                          name,
                          datas_fname,
                          disable_optimization=None):
     Attachments = request.env['ir.attachment']
     try:
         image = Image.open(io.BytesIO(data))
         w, h = image.size
         if w * h > 42e6:  # Nokia Lumia 1020 photo resolution
             raise ValueError(
                 u"Image size excessive, uploaded images must be smaller "
                 u"than 42 million pixel")
         if not disable_optimization and image.format in ('PNG', 'JPEG'):
             data = tools.image_save_for_web(image)
     except IOError:
         pass
     attachment = Attachments.create({
         'name': name,
         'datas_fname': datas_fname,
         'datas': base64.b64encode(data),
         'public': res_model == 'ir.ui.view',
         'res_id': res_id,
         'res_model': res_model,
     })
     attachment.generate_access_token()
     return attachment
Ejemplo n.º 5
0
 def _optimize_image(self, image_data, disable_optimization=False):
     try:
         image = Image.open(io.BytesIO(image_data))
         w, h = image.size
         if w * h >= 42e6:  # Nokia Lumia 1020 photo resolution
             raise ValueError(
                 _(u"Image size excessive, uploaded images "
                   u"must be smaller than 42 million pixel"))
         if not disable_optimization and image.format in ('PNG', 'JPEG'):
             image_data = tools.image_save_for_web(image)
     except IOError:  # pylint: disable=except-pass
         pass
     return image_data
Ejemplo n.º 6
0
    def attach(self, func, upload=None, url=None, disable_optimization=None, **kwargs):
        # the upload argument doesn't allow us to access the files if more than
        # one file is uploaded, as upload references the first file
        # therefore we have to recover the files from the request object
        Attachments = request.env['ir.attachment']  # registry for the attachment table

        uploads = []
        message = None
        if not upload: # no image provided, storing the link and the image name
            name = url.split("/").pop()                       # recover filename
            attachment = Attachments.create({
                'name': name,
                'type': 'url',
                'url': url,
                'public': True,
                'res_model': 'ir.ui.view',
            })
            uploads += attachment.read(['name', 'mimetype', 'checksum', 'url'])
        else:                                                  # images provided
            try:
                attachments = request.env['ir.attachment']
                for c_file in request.httprequest.files.getlist('upload'):
                    data = c_file.read()
                    try:
                        image = Image.open(cStringIO.StringIO(data))
                        w, h = image.size
                        if w*h > 42e6: # Nokia Lumia 1020 photo resolution
                            raise ValueError(
                                u"Image size excessive, uploaded images must be smaller "
                                u"than 42 million pixel")
                        if not disable_optimization and image.format in ('PNG', 'JPEG'):
                            data = tools.image_save_for_web(image)
                    except IOError, e:
                        pass

                    attachment = Attachments.create({
                        'name': c_file.filename,
                        'datas': data.encode('base64'),
                        'datas_fname': c_file.filename,
                        'public': True,
                        'res_model': 'ir.ui.view',
                    })
                    attachments += attachment
                uploads += attachments.read(['name', 'mimetype', 'checksum', 'url'])
            except Exception, e:
                logger.exception("Failed to upload image to attachment")
                message = unicode(e)
Ejemplo n.º 7
0
    def import_product_images(self,
                              product_images=None,
                              disable_optimization=None,
                              **kwargs):
        if not product_images:
            print("There're no images to load")
        else:
            try:
                images_per_product = 0
                for c_file in request.httprequest.files.getlist(
                        'product_images'):
                    image_data = c_file.read()
                    try:
                        image = Image.open(io.BytesIO(image_data))
                        w, h = image.size
                        if w * h > 42e6:
                            raise ValueError(
                                u"Image size excessive, uploaded images must be smaller "
                                u"than 42 million pixel")
                        if not disable_optimization and image.format in (
                                'PNG', 'JPEG', 'JPG', 'GIF'):
                            image_data = tools.image_save_for_web(image)
                    except IOError as e:
                        pass

                    # Search product by internal reference
                    default_code = c_file.filename.split(".")
                    file_name_product = default_code[0].strip()

                    product_obj = http.request.env['product.template'].sudo(
                    ).search([('default_code', '=', file_name_product)])

                    if product_obj:
                        images_per_product += 1
                        processed_image = base64.b64encode(image_data)
                        product_obj.sudo().write(
                            {'image_medium': processed_image})
                if images_per_product > 0:
                    return http.request.redirect(
                        '/page/import_product_images.images_success')
                else:
                    return http.request.redirect(
                        '/page/import_product_images.images_failed')
            except Exception as e:
                logger.exception("Failed to upload images")
Ejemplo n.º 8
0
 def _image_to_attachment(self, res_model, res_id, data, name, datas_fname, disable_optimization=None):
     Attachments = request.env['ir.attachment']
     try:
         image = Image.open(io.BytesIO(data))
         w, h = image.size
         if w*h > 42e6: # Nokia Lumia 1020 photo resolution
             raise ValueError(
                 u"Image size excessive, uploaded images must be smaller "
                 u"than 42 million pixel")
         if not disable_optimization and image.format in ('PNG', 'JPEG'):
             data = tools.image_save_for_web(image)
     except IOError:
         pass
     attachment = Attachments.create({
         'name': name,
         'datas_fname': datas_fname,
         'datas': base64.b64encode(data),
         'public': res_model == 'ir.ui.view',
         'res_id': res_id,
         'res_model': res_model,
     })
     attachment.generate_access_token()
     return attachment
Ejemplo n.º 9
0
    def save_unsplash_url(self, unsplashurls=None, **kwargs):
        """
            unsplashurls = {
                image_id1: {
                    url: image_url,
                    download_url: download_url,
                },
                image_id2: {
                    url: image_url,
                    download_url: download_url,
                },
                .....
            }
        """
        def slugify(s):
            ''' Keeps only alphanumeric characters, hyphens and spaces from a string.
                The string will also be truncated to 1024 characters max.
                :param s: the string to be filtered
                :return: the sanitized string
            '''
            return "".join([c for c in s if c.isalnum() or c in list("- ")])[:1024]

        if not unsplashurls:
            return []

        uploads = []
        Attachments = request.env['ir.attachment']

        query = kwargs.get('query', '')
        query = slugify(query)

        res_model = kwargs.get('res_model', 'ir.ui.view')
        if res_model != 'ir.ui.view' and kwargs.get('res_id'):
            res_id = int(kwargs['res_id'])
        else:
            res_id = None

        for key, value in unsplashurls.items():
            url = value.get('url')
            try:
                if not url.startswith('https://images.unsplash.com/'):
                    logger.exception("ERROR: Unknown Unsplash URL!: " + url)
                    raise Exception(_("ERROR: Unknown Unsplash URL!"))
                req = requests.get(url)
                if req.status_code != requests.codes.ok:
                    continue

                # get mime-type of image url because unsplash url dosn't contains mime-types in url
                mimetype = req.headers.get('Content-Type')
                datas = req.content
            except requests.exceptions.ConnectionError as e:
                logger.exception("Connection Error: " + str(e))
                continue
            except requests.exceptions.Timeout as e:
                logger.exception("Timeout: " + str(e))
                continue

            # optimized image before save
            if mimetype in ('image/jpeg', 'image/png'):
                image = Image.open(io.BytesIO(datas))
                if image.format in ('PNG', 'JPEG'):
                    datas = tools.image_save_for_web(image)
                    # append image extension in name
                    query += '.' + str.lower(image.format)

            # /unsplash/5gR788gfd/lion
            url_frags = ['unsplash', key, query]

            attachment = Attachments.create({
                'name': query,
                'url': '/' + '/'.join(url_frags),
                'datas_fname': '_'.join(url_frags),
                'mimetype': mimetype,
                'datas': base64.b64encode(datas),
                'public': res_model == 'ir.ui.view',
                'res_id': res_id,
                'res_model': res_model,
            })
            attachment.generate_access_token()
            uploads.extend(attachment.read(['name', 'mimetype', 'checksum', 'res_id', 'res_model', 'access_token', 'url']))

            # Notifies Unsplash from an image download. (API requirement)
            self._notify_download(value.get('download_url'))

        return uploads
Ejemplo n.º 10
0
    def attach(self,
               func,
               upload=None,
               url=None,
               disable_optimization=None,
               **kwargs):
        if kwargs.get("flag_store", "false") == "true":
            attachments = request.env[
                'ir.attachment']  # registry for the attachment table

            res_model = kwargs.get('res_model', 'ir.ui.view')
            res_id = res_model != 'ir.ui.view' and kwargs.get('res_id') or None

            uploads = []
            message = None
            try:
                store_path = tools.config['store_path']
                url_img = tools.config['url_img']
                am_obj = request.env['ir.attachment']
                for c_file in request.httprequest.files.getlist('upload'):
                    data = c_file.read()
                    current_date = datetime.now()
                    folder_flow_date = '%s/%s/%s' % (current_date.year,
                                                     current_date.month,
                                                     current_date.day)
                    store_path = '%s/%s' % (store_path, folder_flow_date)
                    pathlib.Path(store_path).mkdir(parents=True, exist_ok=True)
                    try:
                        image = Image.open(io.BytesIO(data))
                        w, h = image.size
                        if w * h > 42e6:  # Nokia Lumia 1020 photo resolution
                            raise ValueError(
                                u"Image size excessive, uploaded images must be smaller "
                                u"than 42 million pixel")
                        if not disable_optimization and image.format in (
                                'PNG', 'JPEG'):
                            data = tools.image_save_for_web(image)
                        with open("%s/%s" % (store_path, c_file.filename),
                                  "wb") as f:
                            f.write(data)
                    except IOError as e:
                        pass

                    pathlib.Path().mkdir(parents=True, exist_ok=True)
                    attachment = attachments.create({
                        'name':
                        c_file.filename,
                        'type':
                        'url',
                        'url':
                        "%s/%s/%s" %
                        (url_img, folder_flow_date, c_file.filename),
                        'public':
                        True,
                        'res_id':
                        res_id,
                        'res_model':
                        res_model,
                        'is_store':
                        True,
                    })
                    attachment.generate_access_token()
                    am_obj += attachment
                    uploads += attachment.read([
                        'name', 'mimetype', 'checksum', 'url', 'res_id',
                        'res_model', 'access_token'
                    ])
            except Exception as e:
                logger.exception(e)
                logger.exception("Failed to upload image to attachment")
            return """<script type='text/javascript'>
                          window.parent['%s'](%s, %s);
                      </script>""" % (func, json.dumps(uploads),
                                      json.dumps(message))
        res = super(WebEditor,
                    self).attach(func,
                                 upload=upload,
                                 url=url,
                                 disable_optimization=disable_optimization,
                                 **kwargs)
        return res
Ejemplo n.º 11
0
    def attach(self, func, upload=None, url=None, disable_optimization=None, **kwargs):
        # the upload argument doesn't allow us to access the files if more than
        # one file is uploaded, as upload references the first file
        # therefore we have to recover the files from the request object
        Attachments = request.env['ir.attachment']  # registry for the attachment table

        res_model = kwargs.get('res_model', 'ir.ui.view')
        if res_model != 'ir.ui.view' and kwargs.get('res_id'):
            res_id = int(kwargs['res_id'])
        else:
            res_id = None

        uploads = []
        message = None
        if not upload: # no image provided, storing the link and the image name
            name = url.split("/").pop()                       # recover filename
            attachment = Attachments.create({
                'name': name,
                'type': 'url',
                'url': url,
                'public': res_model == 'ir.ui.view',
                'res_id': res_id,
                'res_model': res_model,
            })
            attachment.generate_access_token()
            uploads += attachment.read(['name', 'mimetype', 'checksum', 'url', 'res_id', 'res_model', 'access_token'])
        else:                                                  # images provided
            try:
                attachments = request.env['ir.attachment']
                for c_file in request.httprequest.files.getlist('upload'):
                    data = c_file.read()
                    try:
                        image = Image.open(io.BytesIO(data))
                        w, h = image.size
                        if w*h > 42e6: # Nokia Lumia 1020 photo resolution
                            raise ValueError(
                                u"Image size excessive, uploaded images must be smaller "
                                u"than 42 million pixel")
                        if not disable_optimization and image.format in ('PNG', 'JPEG'):
                            data = tools.image_save_for_web(image)
                    except IOError as e:
                        pass

                    attachment = Attachments.create({
                        'name': c_file.filename,
                        'datas': base64.b64encode(data),
                        'datas_fname': c_file.filename,
                        'public': res_model == 'ir.ui.view',
                        'res_id': res_id,
                        'res_model': res_model,
                    })
                    attachment.generate_access_token()
                    attachments += attachment
                uploads += attachments.read(['name', 'mimetype', 'checksum', 'url', 'res_id', 'res_model', 'access_token'])
            except Exception as e:
                logger.exception("Failed to upload image to attachment")
                message = pycompat.text_type(e)

        return """<script type='text/javascript'>
            window.parent['%s'](%s, %s);
        </script>""" % (func, json.dumps(uploads), json.dumps(message))
Ejemplo n.º 12
0
    def save_unsplash_url(self, unsplashurls=None, **kwargs):
        """
            unsplashurls = {
                image_id1: image_url1,
                image_id2: image_url2,
                .....
            }
        """
        if not unsplashurls:
            return []

        uploads = []
        Attachments = request.env['ir.attachment']

        res_model = kwargs.get('res_model', 'ir.ui.view')
        if res_model != 'ir.ui.view' and kwargs.get('res_id'):
            res_id = int(kwargs['res_id'])
        else:
            res_id = None

        for key in unsplashurls:
            url = unsplashurls[key].get('url')
            try:
                req = requests.get(url)
                if req.status_code != requests.codes.ok:
                    continue

                # get mime-type of image url because unsplash url dosn't contains mime-types in url
                mimetype = req.headers.get('Content-Type')
                datas = req.content
            except requests.exceptions.ConnectionError as e:
                logger.exception("Connection Error: " + str(e))
                continue
            except requests.exceptions.Timeout as e:
                logger.exception("Timeout: " + str(e))
                continue

            image = Image.open(io.BytesIO(datas))
            image_format = image.format

            # optimized image before save
            if image_format and image_format in ('PNG', 'JPEG'):
                datas = tools.image_save_for_web(image)

            name = key
            # append image extension in name
            if image_format:
                name += '.' + image_format.lower()

            attachment = Attachments.create({
                'name': name,
                'datas_fname': name,
                'mimetype': mimetype,
                'datas': base64.b64encode(datas),
                'public': res_model == 'ir.ui.view',
                'res_id': res_id,
                'res_model': res_model,
            })
            attachment.generate_access_token()
            uploads.extend(
                attachment.read([
                    'name', 'mimetype', 'checksum', 'res_id', 'res_model',
                    'access_token'
                ]))

        return uploads
Ejemplo n.º 13
0
 def optimize_img(self, img):
     img = Image.open(BytesIO(img))
     img_optimized = tools.image_save_for_web(img)
     return img_optimized
Ejemplo n.º 14
0
Archivo: main.py Proyecto: Gorrice/odoo
    def save_unsplash_url(self, unsplashurls=None, **kwargs):
        """
            unsplashurls = {
                image_id1: image_url1,
                image_id2: image_url2,
                .....
            }
        """
        if not unsplashurls:
            return []

        uploads = []
        Attachments = request.env['ir.attachment']

        res_model = kwargs.get('res_model', 'ir.ui.view')
        if res_model != 'ir.ui.view' and kwargs.get('res_id'):
            res_id = int(kwargs['res_id'])
        else:
            res_id = None

        for key, value in unsplashurls.items():
            url = value.get('url')
            try:
                if not url.startswith('https://images.unsplash.com/'):
                    logger.exception("ERROR: Unknown Unsplash URL!: " + url)
                    raise Exception(_("ERROR: Unknown Unsplash URL!"))
                req = requests.get(url)
                if req.status_code != requests.codes.ok:
                    continue

                # get mime-type of image url because unsplash url dosn't contains mime-types in url
                mimetype = req.headers.get('Content-Type')
                datas = req.content
            except requests.exceptions.ConnectionError as e:
                logger.exception("Connection Error: " + str(e))
                continue
            except requests.exceptions.Timeout as e:
                logger.exception("Timeout: " + str(e))
                continue

            name = key

            # optimized image before save
            if mimetype in ('image/jpeg', 'image/png'):
                image = Image.open(io.BytesIO(datas))
                if image.format in ('PNG', 'JPEG'):
                    datas = tools.image_save_for_web(image)
                    # append image extension in name
                    name += '.' + image.format

            attachment = Attachments.create({
                'name': name,
                'url': '/unsplash/' + name,
                'datas_fname': name,
                'mimetype': mimetype,
                'datas': base64.b64encode(datas),
                'public': res_model == 'ir.ui.view',
                'res_id': res_id,
                'res_model': res_model,
            })
            attachment.generate_access_token()
            uploads.extend(attachment.read(['name', 'mimetype', 'checksum', 'res_id', 'res_model', 'access_token', 'url']))

        return uploads
Ejemplo n.º 15
0
    def save_unsplash_url(self, unsplashurls=None, **kwargs):
        """
            unsplashurls = {
                image_id1: {
                    url: image_url,
                    download_url: download_url,
                },
                image_id2: {
                    url: image_url,
                    download_url: download_url,
                },
                .....
            }
        """
        def slugify(s):
            ''' Keeps only alphanumeric characters, hyphens and spaces from a string.
                The string will also be truncated to 1024 characters max.
                :param s: the string to be filtered
                :return: the sanitized string
            '''
            return "".join([c for c in s
                            if c.isalnum() or c in list("- ")])[:1024]

        if not unsplashurls:
            return []

        uploads = []
        Attachments = request.env['ir.attachment']

        query = kwargs.get('query', '')
        query = slugify(query)

        res_model = kwargs.get('res_model', 'ir.ui.view')
        if res_model != 'ir.ui.view' and kwargs.get('res_id'):
            res_id = int(kwargs['res_id'])
        else:
            res_id = None

        for key, value in unsplashurls.items():
            url = value.get('url')
            try:
                if not url.startswith('https://images.unsplash.com/'):
                    logger.exception("ERROR: Unknown Unsplash URL!: " + url)
                    raise Exception(_("ERROR: Unknown Unsplash URL!"))
                req = requests.get(url)
                if req.status_code != requests.codes.ok:
                    continue

                # get mime-type of image url because unsplash url dosn't contains mime-types in url
                mimetype = req.headers.get('Content-Type')
                datas = req.content
            except requests.exceptions.ConnectionError as e:
                logger.exception("Connection Error: " + str(e))
                continue
            except requests.exceptions.Timeout as e:
                logger.exception("Timeout: " + str(e))
                continue

            # optimized image before save
            if mimetype in ('image/jpeg', 'image/png'):
                image = Image.open(io.BytesIO(datas))
                if image.format in ('PNG', 'JPEG'):
                    datas = tools.image_save_for_web(image)
                    # append image extension in name
                    query += '.' + str.lower(image.format)

            # /unsplash/5gR788gfd/lion
            url_frags = ['unsplash', key, query]

            attachment = Attachments.create({
                'name': query,
                'url': '/' + '/'.join(url_frags),
                'datas_fname': '_'.join(url_frags),
                'mimetype': mimetype,
                'datas': base64.b64encode(datas),
                'public': res_model == 'ir.ui.view',
                'res_id': res_id,
                'res_model': res_model,
            })
            attachment.generate_access_token()
            uploads.extend(
                attachment.read([
                    'name', 'mimetype', 'checksum', 'res_id', 'res_model',
                    'access_token', 'url'
                ]))

            # Notifies Unsplash from an image download. (API requirement)
            self._notify_download(value.get('download_url'))

        return uploads
Ejemplo n.º 16
0
    def save_unsplash_url(self, unsplashurls=None, **kwargs):
        """
            unsplashurls = {
                image_id1: image_url1,
                image_id2: image_url2,
                .....
            }
        """
        if not unsplashurls:
            return []

        uploads = []
        Attachments = request.env['ir.attachment']

        res_model = kwargs.get('res_model', 'ir.ui.view')
        if res_model != 'ir.ui.view' and kwargs.get('res_id'):
            res_id = int(kwargs['res_id'])
        else:
            res_id = None

        for key, value in unsplashurls.items():
            url = value.get('url')
            try:
                if not url.startswith('https://images.unsplash.com/'):
                    logger.exception("ERROR: Unknown Unsplash URL!: " + url)
                    raise Exception(_("ERROR: Unknown Unsplash URL!"))
                req = requests.get(url)
                if req.status_code != requests.codes.ok:
                    continue

                # get mime-type of image url because unsplash url dosn't contains mime-types in url
                mimetype = req.headers.get('Content-Type')
                datas = req.content
            except requests.exceptions.ConnectionError as e:
                logger.exception("Connection Error: " + str(e))
                continue
            except requests.exceptions.Timeout as e:
                logger.exception("Timeout: " + str(e))
                continue

            name = key

            # optimized image before save
            if mimetype in ('image/jpeg', 'image/png'):
                image = Image.open(io.BytesIO(datas))
                if image.format in ('PNG', 'JPEG'):
                    datas = tools.image_save_for_web(image)
                    # append image extension in name
                    name += '.' + image.format

            attachment = Attachments.create({
                'name': name,
                'url': '/unsplash/' + name,
                'datas_fname': name,
                'mimetype': mimetype,
                'datas': base64.b64encode(datas),
                'public': res_model == 'ir.ui.view',
                'res_id': res_id,
                'res_model': res_model,
            })
            attachment.generate_access_token()
            uploads.extend(
                attachment.read([
                    'name', 'mimetype', 'checksum', 'res_id', 'res_model',
                    'access_token', 'url'
                ]))

        return uploads
Ejemplo n.º 17
0
Archivo: main.py Proyecto: astirpe/odoo
    def save_unsplash_url(self, unsplashurls=None, **kwargs):
        """
            unsplashurls = {
                image_id1: image_url1,
                image_id2: image_url2,
                .....
            }
        """
        if not unsplashurls:
            return []

        uploads = []
        Attachments = request.env['ir.attachment']

        res_model = kwargs.get('res_model', 'ir.ui.view')
        if res_model != 'ir.ui.view' and kwargs.get('res_id'):
            res_id = int(kwargs['res_id'])
        else:
            res_id = None

        for key in unsplashurls:
            url = unsplashurls[key].get('url')
            try:
                req = requests.get(url)
                if req.status_code != requests.codes.ok:
                    continue

                # get mime-type of image url because unsplash url dosn't contains mime-types in url
                mimetype = req.headers.get('Content-Type')
                datas = req.content
            except requests.exceptions.ConnectionError as e:
                logger.exception("Connection Error: " + str(e))
                continue
            except requests.exceptions.Timeout as e:
                logger.exception("Timeout: " + str(e))
                continue

            image = Image.open(io.BytesIO(datas))
            image_format = image.format

            # optimized image before save
            if image_format and image_format in ('PNG', 'JPEG'):
                datas = tools.image_save_for_web(image)

            name = key
            # append image extension in name
            if image_format:
                name += '.' + image_format.lower()

            attachment = Attachments.create({
                'name': name,
                'datas_fname': name,
                'mimetype': mimetype,
                'datas': base64.b64encode(datas),
                'public': res_model == 'ir.ui.view',
                'res_id': res_id,
                'res_model': res_model,
            })
            attachment.generate_access_token()
            uploads.extend(attachment.read(['name', 'mimetype', 'checksum', 'res_id', 'res_model', 'access_token']))

        return uploads
Ejemplo n.º 18
0
    def attach(self, func, upload=None, url=None, disable_optimization=None, **kwargs):
        # the upload argument doesn't allow us to access the files if more than
        # one file is uploaded, as upload references the first file
        # therefore we have to recover the files from the request object
        Attachments = request.env['ir.attachment']  # registry for the attachment table
        print ("kwargs",kwargs)
        hidden_folder_id = kwargs.get('hidden_folder_id', False)
        uploads = []
        message = None
        if not upload: # no image provided, storing the link and the image name
            name = url.split("/").pop()# recover filename
            if '?' in name:
                name = name[:name.find('?')]
            attach_vals = {
                'name': name,
                'datas_fname': name,
                'type': 'binary',
                'url': '',
                'public': True,
                'res_model': 'hc.image.bank',
                'hc_image_bank_id' : hidden_folder_id,
            }
            try:
                import requests
                res = requests.get(url, params={'d': '404', 's': '128'}, timeout=5)
                datas = base64.b64encode(res.content)
                attach_vals.update({'datas': datas, 'type': 'binary',})
            except Exception as e:
                logger.info("Unable to store this Image in database - " + str(e))
            attachment = Attachments.create(attach_vals)

            if hidden_folder_id:
                hidden_folder_obj = request.env['hc.image.bank']
                hidden_folder_browse = hidden_folder_obj.browse(int(hidden_folder_id))
                hidden_folder_browse.write({'attachment_ids': [(4, attachment.id)]})

            uploads += attachment.read(['name', 'mimetype', 'checksum', 'url', 'hc_image_bank_id'])#, 'res_model'
        else:                                                  # images provided
            try:
                attachments = request.env['ir.attachment']
                for c_file in request.httprequest.files.getlist('upload'):
                    data = c_file.read()
                    try:
                        image = Image.open(io.BytesIO(data))
                        w, h = image.size
                        if w*h > 42e6: # Nokia Lumia 1020 photo resolution
                            raise ValueError(
                                u"Image size excessive, uploaded images must be smaller "
                                u"than 42 million pixel")
                        if not disable_optimization and image.format in ('PNG', 'JPEG'):
                            data = tools.image_save_for_web(image)
                    except IOError as e:
                        pass

                    attachment = Attachments.create({
                        'name': c_file.filename,
                        'datas': base64.b64encode(data),
                        'datas_fname': c_file.filename,
                        'public': True,
                        'res_model': 'hc.image.bank',
                        'hc_image_bank_id': hidden_folder_id
                    })
                    attachments += attachment
                    if hidden_folder_id:
                        hidden_folder_obj = request.env['hc.image.bank']
                        hidden_folder_browse = hidden_folder_obj.browse(int(hidden_folder_id))
                        hidden_folder_browse.write({'attachment_ids': [(4, attachment.id)]})
                uploads += attachments.read(['name', 'mimetype', 'checksum', 'url', 'hc_image_bank_id'])
            except Exception as e:
                logger.exception("Failed to upload image to attachment")
                message = pycompat.text_type(e)

        return """<script type='text/javascript'>
            window.parent['%s'](%s, %s);
        </script>""" % (func, json.dumps(uploads), json.dumps(message))