summaryrefslogtreecommitdiff
path: root/odoo/addons/base
diff options
context:
space:
mode:
authorThanhDodeurOdoo <tso@odoo.com>2018-11-07 14:52:33 +0000
committerThanhDodeurOdoo <tso@odoo.com>2018-12-06 19:09:33 +0000
commit89f20d2c297d99d4eb0ded8be78fbf86b8ec45d3 (patch)
treec86e3d9085425ef7aa9ddf4dcdd453b766a0b90f /odoo/addons/base
parent72905feee0b5393f8872e51b33a10e4ec7978085 (diff)
[REF] base, mail: splits the documents feature from ir attachment
Moved the field 'active', 'res_model_name' and 'thumbnail' from ir.attachment to enterprise's documents.document. Moved the pdf split feature to enterprise's Documents module. task: #1908896
Diffstat (limited to 'odoo/addons/base')
-rw-r--r--odoo/addons/base/models/ir_attachment.py112
-rw-r--r--odoo/addons/base/models/ir_http.py14
2 files changed, 11 insertions, 115 deletions
diff --git a/odoo/addons/base/models/ir_attachment.py b/odoo/addons/base/models/ir_attachment.py
index 535605d9fe7..967f93a33e2 100644
--- a/odoo/addons/base/models/ir_attachment.py
+++ b/odoo/addons/base/models/ir_attachment.py
@@ -6,17 +6,14 @@ import itertools
import logging
import mimetypes
import os
-import io
import re
from collections import defaultdict
import uuid
-from odoo import api, fields, models, tools, SUPERUSER_ID, exceptions, _
+from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo.exceptions import AccessError, ValidationError
from odoo.tools import config, human_size, ustr, html_escape
from odoo.tools.mimetypes import guess_mimetype
-from odoo.tools import crop_image, image_resize_image
-from PyPDF2 import PdfFileWriter, PdfFileReader
_logger = logging.getLogger(__name__)
@@ -46,14 +43,6 @@ class IrAttachment(models.Model):
record = self.env[attachment.res_model].browse(attachment.res_id)
attachment.res_name = record.display_name
- @api.depends('res_model')
- def _compute_res_model_name(self):
- for record in self:
- if record.res_model:
- model = self.env['ir.model'].search([('model', '=', record.res_model)], limit=1)
- if model:
- record.res_model_name = model[0].name
-
@api.model
def _storage(self):
return self.env['ir.config_parameter'].sudo().get_param('ir_attachment.location', 'file')
@@ -290,7 +279,6 @@ class IrAttachment(models.Model):
description = fields.Text('Description')
res_name = fields.Char('Resource Name', compute='_compute_res_name', store=True)
res_model = fields.Char('Resource Model', readonly=True, help="The database object this attachment will be attached to.")
- res_model_name = fields.Char(compute='_compute_res_model_name', store=True, index=True)
res_field = fields.Char('Resource Field', readonly=True)
res_id = fields.Integer('Resource ID', readonly=True, help="The record id this is attached to.")
company_id = fields.Many2one('res.company', string='Company', change_default=True,
@@ -312,8 +300,6 @@ class IrAttachment(models.Model):
checksum = fields.Char("Checksum/SHA1", size=40, index=True, readonly=True)
mimetype = fields.Char('Mime Type', readonly=True)
index_content = fields.Text('Indexed Content', readonly=True, prefetch=False)
- active = fields.Boolean(default=True, string="Active", oldname='archived')
- thumbnail = fields.Binary(readonly=1, attachment=True)
@api.model_cr_context
def _auto_init(self):
@@ -449,18 +435,6 @@ class IrAttachment(models.Model):
self.check('read')
return super(IrAttachment, self).read(fields, load=load)
- def _make_thumbnail(self, vals):
- if vals.get('datas') and not vals.get('res_field'):
- vals['thumbnail'] = False
- if vals.get('mimetype') and re.match('image.*(gif|jpeg|jpg|png)', vals['mimetype']):
- try:
- temp_image = crop_image(vals['datas'], type='center', size=(80, 80), ratio=(1, 1))
- vals['thumbnail'] = image_resize_image(base64_source=temp_image, size=(80, 80),
- encoding='base64')
- except Exception:
- pass
- return vals
-
@api.multi
def write(self, vals):
self.check('write', values=vals)
@@ -469,8 +443,6 @@ class IrAttachment(models.Model):
vals.pop(field, False)
if 'mimetype' in vals or 'datas' in vals:
vals = self._check_contents(vals)
- if all([not attachment.res_field for attachment in self]):
- vals = self._make_thumbnail(vals)
return super(IrAttachment, self).write(vals)
@api.multi
@@ -502,7 +474,6 @@ class IrAttachment(models.Model):
for field in ('file_size', 'checksum'):
values.pop(field, False)
values = self._check_contents(values)
- values = self._make_thumbnail(values)
self.browse().check('write', values=values)
return super(IrAttachment, self).create(vals_list)
@@ -518,87 +489,6 @@ class IrAttachment(models.Model):
def action_get(self):
return self.env['ir.actions.act_window'].for_xml_id('base', 'action_attachment')
- def _make_pdf(self, output, name_ext):
- """
- :param output: PdfFileWriter object.
- :param name_ext: the additional name of the new attachment (page count).
- :return: the id of the attachment.
- """
- self.ensure_one()
- try:
- stream = io.BytesIO()
- output.write(stream)
- return self.copy({
- 'name': self.name+'-'+name_ext,
- 'datas_fname': os.path.splitext(self.datas_fname or self.name)[0]+'-'+name_ext+".pdf",
- 'datas': base64.b64encode(stream.getvalue()),
- })
- except Exception:
- raise Exception
-
- def _split_pdf_groups(self, pdf_groups=None, remainder=False):
- """
- calls _make_pdf to create the a new attachment for each page section.
- :param pdf_groups: a list of lists representing the pages to split: pages = [[1,1], [4,5], [7,7]]
- :returns the list of the ID's of the new PDF attachments.
-
- """
- self.ensure_one()
- with io.BytesIO(base64.b64decode(self.datas)) as stream:
- try:
- input_pdf = PdfFileReader(stream)
- except Exception:
- raise exceptions.ValidationError(_("ERROR: Invalid PDF file!"))
- max_page = input_pdf.getNumPages()
- remainder_set = set(range(0, max_page))
- new_pdf_ids = []
- if not pdf_groups:
- pdf_groups = []
- for pages in pdf_groups:
- pages[1] = min(max_page, pages[1])
- pages[0] = min(max_page, pages[0])
- if pages[0] == pages[1]:
- name_ext = "%s" % (pages[0],)
- else:
- name_ext = "%s-%s" % (pages[0], pages[1])
- output = PdfFileWriter()
- for i in range(pages[0]-1, pages[1]):
- output.addPage(input_pdf.getPage(i))
- new_pdf_id = self._make_pdf(output, name_ext)
- new_pdf_ids.append(new_pdf_id)
- remainder_set = remainder_set.difference(set(range(pages[0] - 1, pages[1])))
- if remainder:
- for i in remainder_set:
- output_page = PdfFileWriter()
- name_ext = "%s" % (i + 1,)
- output_page.addPage(input_pdf.getPage(i))
- new_pdf_id = self._make_pdf(output_page, name_ext)
- new_pdf_ids.append(new_pdf_id)
- self.write({'active': False})
- elif not len(remainder_set):
- self.write({'active': False})
- return new_pdf_ids
-
- def split_pdf(self, indices=None, remainder=False):
- """
- called by the Document Viewer's Split PDF button.
- evaluates the input string and turns it into a list of lists to be processed by _split_pdf_groups
-
- :param indices: the formatted string of pdf split (e.g. 1,5-10, 8-22, 29-34) o_page_number_input
- :param remainder: bool, if true splits the non specified pages, one by one. form checkbox o_remainder_input
- :returns the list of the ID's of the newly created pdf attachments.
- """
- self.ensure_one()
- if 'pdf' not in self.mimetype:
- raise exceptions.ValidationError(_("ERROR: the file must be a PDF"))
- if indices:
- try:
- pages = [[int(x) for x in x.split('-')] for x in indices.split(',')]
- except ValueError:
- raise exceptions.ValidationError(_("ERROR: Invalid list of pages to split. Example: 1,5-9,10"))
- return self._split_pdf_groups(pdf_groups=[[min(x), max(x)] for x in pages], remainder=remainder)
- return self._split_pdf_groups(remainder=remainder)
-
@api.model
def get_serve_attachment(self, url, extra_domain=None, extra_fields=None, order=None):
domain = [('type', '=', 'binary'), ('url', '=', url)] + (extra_domain or [])
diff --git a/odoo/addons/base/models/ir_http.py b/odoo/addons/base/models/ir_http.py
index 63d12137d7a..5d6e84a59b3 100644
--- a/odoo/addons/base/models/ir_http.py
+++ b/odoo/addons/base/models/ir_http.py
@@ -3,7 +3,6 @@
# ir_http modular http routing
#----------------------------------------------------------
import base64
-import datetime
import hashlib
import logging
import mimetypes
@@ -23,7 +22,6 @@ from odoo.exceptions import AccessDenied, AccessError
from odoo.http import request, STATIC_CACHE, content_disposition
from odoo.tools import pycompat, consteq
from odoo.tools.mimetypes import guess_mimetype
-from ast import literal_eval
from odoo.modules.module import get_resource_path, get_module_path
_logger = logging.getLogger(__name__)
@@ -260,6 +258,13 @@ class IrHttp(models.AbstractModel):
"""
return False
+ @classmethod
+ def _get_special_models(cls):
+ """
+ :return: the set of models that have to pass through several specific fields checks:
+ used for the 'url' and the 'access_token' fields.
+ """
+ return {'ir.attachment'}
@classmethod
def binary_content(cls, xmlid=None, model='ir.attachment', id=None, field='datas',
@@ -290,6 +295,7 @@ class IrHttp(models.AbstractModel):
:returns: (status, headers, content)
"""
env = env or request.env
+ attachment_models = cls._get_special_models()
# get object and content
obj = None
if xmlid:
@@ -301,7 +307,7 @@ class IrHttp(models.AbstractModel):
return (404, [], None)
# access token grant access
- if model == 'ir.attachment' and access_token:
+ if model in attachment_models and access_token:
obj = obj.sudo()
if access_mode:
if not cls._check_access_mode(env, id, access_mode, model, access_token=access_token,
@@ -320,7 +326,7 @@ class IrHttp(models.AbstractModel):
# attachment by url check
module_resource_path = None
- if model == 'ir.attachment' and obj.type == 'url' and obj.url:
+ if model in attachment_models and obj.type == 'url' and obj.url:
url_match = re.match("^/(\w+)/(.+)$", obj.url)
if url_match:
module = url_match.group(1)