Skip to content

Commit

Permalink
🚑 'guess_type' does not always return a result so an 'IncorrectPaddin…
Browse files Browse the repository at this point in the history
…g' error occurs
  • Loading branch information
Rafis Bikbov committed Dec 12, 2018
1 parent 4c73308 commit 4ba7d5a
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
2 changes: 1 addition & 1 deletion ir_attachment_url/__manifest__.py
Expand Up @@ -4,7 +4,7 @@
"summary": """Use attachment URL and upload data to external storage""",
"category": "Tools",
"images": [],
"version": "10.0.1.1.6",
"version": "10.0.1.1.7",
"application": False,

"author": "IT-Projects LLC, Ildar Nasyrov",
Expand Down
5 changes: 5 additions & 0 deletions ir_attachment_url/doc/changelog.rst
@@ -1,3 +1,8 @@
`1.1.7`
-------

- **Fix** When a link to a picture that does not have an extension is written in a binary field, its mimetype is not determined, which leads to an "binascii.Error: decoding with base64 codec failed (Error: Incorrect padding)"

`1.1.6`
-------

Expand Down
31 changes: 29 additions & 2 deletions ir_attachment_url/models/binary_fields.py
@@ -1,9 +1,30 @@
# -*- coding: utf-8 -*-
from odoo import fields
import mimetypes
import requests

from odoo import fields
from odoo.tools.mimetypes import guess_mimetype
from . import image


def get_mimetype_by_url(url):
mimetype = mimetypes.guess_type(url)[0]

# head request for content-type header getting
if not mimetype:
with requests.head(url) as r:
mimetype = getattr(r, 'headers', {}).get('Content-Type')

# download picture for reading content
if not mimetype:
with requests.get(url) as r:
content = getattr(r, 'content')
if content:
mimetype = guess_mimetype(content)

return mimetype


class Binary(fields.Binary):

def write(self, records, value):
Expand All @@ -21,13 +42,17 @@ def write(self, records, value):
if value and image.is_url(value):
with records.env.norecompute():
if value:
mimetype = get_mimetype_by_url(value)
index_content = mimetype.split('/')[0]
# update the existing attachments
atts.write({
'url': value,
'mimetype': mimetypes.guess_type(value)[0],
'mimetype': mimetype,
'datas': None,
'type': 'url',
'index_content': index_content,
})

# create the missing attachments
for record in (records - records.browse(atts.mapped('res_id'))):
atts.create({
Expand All @@ -37,6 +62,8 @@ def write(self, records, value):
'res_id': record.id,
'type': 'url',
'url': value,
'mimetype': mimetype,
'index_content': index_content,
})
else:
atts.unlink()
Expand Down

0 comments on commit 4ba7d5a

Please sign in to comment.