[MIG] : Migration to 13.0

This commit is contained in:
vancouver29 2022-08-01 14:22:11 +02:00
parent 82927b81b3
commit 229dd46f23
8 changed files with 116 additions and 115 deletions

View File

@ -3,22 +3,14 @@
{ {
"name": "Preview attachments", "name": "Preview attachments",
"version": "12.0.1.0.2", "version": "13.0.1.0.0",
"author": "Therp BV," "author": "Therp BV," "Onestein," "Odoo Community Association (OCA)",
"Onestein,"
"Odoo Community Association (OCA)",
"license": "AGPL-3", "license": "AGPL-3",
"summary": 'Preview attachments supported by Viewer.js', "summary": "Preview attachments supported by Viewer.js",
"category": "Knowledge Management", "category": "Knowledge Management",
"depends": [ "depends": ["web", "mail"],
'web', "data": ["templates/assets.xml"],
'mail' "qweb": ["static/src/xml/attachment_preview.xml"],
], "external_dependencies": {"python": ["magic"]},
"data": [
"templates/assets.xml",
],
"qweb": [
'static/src/xml/attachment_preview.xml',
],
"installable": True, "installable": True,
} }

View File

@ -1,12 +1,14 @@
# Translation of Odoo Server. # Translation of Odoo Server.
# This file contains the translation of the following modules: # This file contains the translation of the following modules:
# * attachment_preview # * attachment_preview
# #
msgid "" msgid ""
msgstr "" msgstr ""
"Project-Id-Version: Odoo Server 12.0\n" "Project-Id-Version: Odoo Server 13.0\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"Last-Translator: <>\n" "POT-Creation-Date: 2022-08-09 15:27+0000\n"
"PO-Revision-Date: 2022-08-09 15:27+0000\n"
"Last-Translator: \n"
"Language-Team: \n" "Language-Team: \n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n" "Content-Type: text/plain; charset=UTF-8\n"
@ -20,9 +22,8 @@ msgstr ""
#. module: attachment_preview #. module: attachment_preview
#. openerp-web #. openerp-web
#: code:addons/attachment_preview/static/src/js/attachment_preview.js:188 #: code:addons/attachment_preview/static/src/js/attachment_preview.js:0
#: code:addons/attachment_preview/static/src/js/attachment_preview.js:216 #: code:addons/attachment_preview/static/src/js/attachment_preview.js:0
#, python-format #, python-format
msgid "Preview %s" msgid "Preview %s"
msgstr "" msgstr ""

View File

@ -1,23 +1,19 @@
# Translation of Odoo Server. # Translation of Odoo Server.
# This file contains the translation of the following modules: # This file contains the translation of the following modules:
# * attachment_preview # * attachment_preview
# #
# Translators:
# Rudolf Schnapka <rs@techno-flex.de>, 2015
msgid "" msgid ""
msgstr "" msgstr ""
"Project-Id-Version: knowledge (8.0)\n" "Project-Id-Version: Odoo Server 13.0\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2015-12-08 08:32+0000\n" "POT-Creation-Date: 2022-08-09 15:30+0000\n"
"PO-Revision-Date: 2015-11-25 09:41+0000\n" "PO-Revision-Date: 2022-08-09 15:30+0000\n"
"Last-Translator: Rudolf Schnapka <rs@techno-flex.de>\n" "Last-Translator: \n"
"Language-Team: German (http://www.transifex.com/oca/OCA-knowledge-8-0/" "Language-Team: \n"
"language/de/)\n"
"Language: de\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n" "Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n" "Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n" "Plural-Forms: \n"
#. module: attachment_preview #. module: attachment_preview
#: model:ir.model,name:attachment_preview.model_ir_attachment #: model:ir.model,name:attachment_preview.model_ir_attachment
@ -26,8 +22,8 @@ msgstr ""
#. module: attachment_preview #. module: attachment_preview
#. openerp-web #. openerp-web
#: code:addons/attachment_preview/static/src/js/attachment_preview.js:188 #: code:addons/attachment_preview/static/src/js/attachment_preview.js:0
#: code:addons/attachment_preview/static/src/js/attachment_preview.js:216 #: code:addons/attachment_preview/static/src/js/attachment_preview.js:0
#, python-format #, python-format
msgid "Preview %s" msgid "Preview %s"
msgstr "Vorschau %s" msgstr "Vorschau %s"

View File

@ -12,64 +12,62 @@ _logger = logging.getLogger(__name__)
class IrAttachment(models.Model): class IrAttachment(models.Model):
_inherit = 'ir.attachment' _inherit = "ir.attachment"
@api.model @api.model
def get_binary_extension(self, model, ids, binary_field, def get_binary_extension(self, model, ids, binary_field, filename_field=None):
filename_field=None):
result = {} result = {}
ids_to_browse = ids if isinstance(ids, collections.Iterable) else [ids] ids_to_browse = ids if isinstance(ids, collections.Iterable) else [ids]
# First pass: load fields in bin_size mode to avoid loading big files # First pass: load fields in bin_size mode to avoid loading big files
# unnecessarily. # unnecessarily.
if filename_field: if filename_field:
for this in self.env[model].with_context( for this in (
bin_size=True).browse(ids_to_browse): self.env[model].with_context(bin_size=True).browse(ids_to_browse)
if not this.id: ):
result[this.id] = False # if not this.id:
continue # result[this.id] = False
extension = '' # continue
result[this.id] = False
extension = ""
if this[filename_field]: if this[filename_field]:
filename, extension = os.path.splitext( filename, extension = os.path.splitext(this[filename_field])
this[filename_field])
if this[binary_field] and extension: if this[binary_field] and extension:
result[this.id] = extension result[this.id] = extension
_logger.debug('Got extension %s from filename %s', _logger.debug(
extension, this[filename_field]) "Got extension %s from filename %s",
extension,
this[filename_field],
)
# Second pass for all attachments which have to be loaded fully # Second pass for all attachments which have to be loaded fully
# to get the extension from the content # to get the extension from the content
ids_to_browse = [_id for _id in ids_to_browse if _id not in result] ids_to_browse = [_id for _id in ids_to_browse if _id not in result]
for this in self.env[model].with_context( for this in self.env[model].with_context(bin_size=True).browse(ids_to_browse):
bin_size=True).browse(ids_to_browse): # if not this[binary_field]:
if not this[binary_field]: # result[this.id] = False
result[this.id] = False # continue
continue result[this.id] = False
try: try:
import magic import magic
if model == self._name and binary_field == 'datas'\
and this.store_fname: if model == self._name and binary_field == "datas" and this.store_fname:
mimetype = magic.from_file( mimetype = magic.from_file(
this._full_path(this.store_fname), mime=True) this._full_path(this.store_fname), mime=True
_logger.debug('Magic determined mimetype %s from file %s', )
mimetype, this.store_fname)
else: else:
mimetype = magic.from_buffer( mimetype = magic.from_buffer(this[binary_field], mime=True)
this[binary_field], mime=True) _logger.debug("Magic determined mimetype %s from buffer", mimetype)
_logger.debug('Magic determined mimetype %s from buffer',
mimetype)
except ImportError: except ImportError:
(mimetype, encoding) = mimetypes.guess_type( (mimetype, encoding) = mimetypes.guess_type(
'data:;base64,' + this[binary_field], strict=False) "data:;base64," + this[binary_field].decode("utf-8"), strict=False
_logger.debug('Mimetypes guessed type %s from buffer', )
mimetype) _logger.debug("Mimetypes guessed type %s from buffer", mimetype)
extension = mimetypes.guess_extension( extension = mimetypes.guess_extension(mimetype.split(";")[0], strict=False)
mimetype.split(';')[0], strict=False)
result[this.id] = extension result[this.id] = extension
for _id in result: for _id in result:
result[_id] = (result[_id] or '').lstrip('.').lower() result[_id] = (result[_id] or "").lstrip(".").lower()
return result if isinstance(ids, collections.Iterable) else result[ids] return result if isinstance(ids, collections.Iterable) else result[ids]
@api.model @api.model
def get_attachment_extension(self, ids): def get_attachment_extension(self, ids):
return self.get_binary_extension( return self.get_binary_extension(self._name, ids, "datas", "name")
self._name, ids, 'datas', 'datas_fname')

View File

@ -1,4 +1,4 @@
For filetype recognition, you'll get the best results by installing For filetype recognition, you'll get the best results by installing
``python-magic``: ``python3-magic``:
sudo apt-get install python-magic sudo apt-get install python3-magic

View File

@ -6,13 +6,15 @@ odoo.define("attachment_preview", function(require) {
var core = require("web.core"); var core = require("web.core");
var _t = core._t; var _t = core._t;
var qweb = core.qweb;
var Chatter = require("mail.Chatter"); var Chatter = require("mail.Chatter");
var basic_fields = require("web.basic_fields"); var basic_fields = require("web.basic_fields");
var FormRenderer = require("web.FormRenderer"); var FormRenderer = require("web.FormRenderer");
var FormController = require("web.FormController");
var Widget = require("web.Widget"); var Widget = require("web.Widget");
var active_attachment_id = 0;
var active_attachment_index = 0;
var first_click = true;
var AttachmentPreviewMixin = { var AttachmentPreviewMixin = {
canPreview: function(extension) { canPreview: function(extension) {
return ( return (
@ -81,13 +83,15 @@ odoo.define("attachment_preview", function(require) {
_openAttachmentBox: function() { _openAttachmentBox: function() {
var res = this._super.apply(this, arguments); var res = this._super.apply(this, arguments);
this.getPreviewableAttachments().done( setTimeout(() => {
function(atts) { this.getPreviewableAttachments().done(
this.previewableAttachments = atts; function(atts) {
this.updatePreviewButtons(atts); this.previewableAttachments = atts;
this.getParent().attachmentPreviewWidget.setAttachments(atts); this.updatePreviewButtons(atts);
}.bind(this) this.getParent().attachmentPreviewWidget.setAttachments(atts);
); }.bind(this)
);
}, 0);
return res; return res;
}, },
@ -96,7 +100,7 @@ odoo.define("attachment_preview", function(require) {
var res = this._super.apply(this, arguments); var res = this._super.apply(this, arguments);
var self = this; var self = this;
if (this.getParent().$el.hasClass("attachment_preview")) { if (this.getParent().$el.hasClass("attachment_preview")) {
this._fetchAttachments().done(function() { this._fetchAttachments().then(function() {
self._openAttachmentBox(); self._openAttachmentBox();
self.getPreviewableAttachments().done(function(atts) { self.getPreviewableAttachments().done(function(atts) {
self.updatePreviewButtons(self.previewableAttachments); self.updatePreviewButtons(self.previewableAttachments);
@ -118,6 +122,11 @@ odoo.define("attachment_preview", function(require) {
attachment_extension = $target.attr("data-extension"), attachment_extension = $target.attr("data-extension"),
attachment_title = $target.attr("data-original-title"); attachment_title = $target.attr("data-original-title");
if (attachment_id !== active_attachment_id) {
active_attachment_id = attachment_id;
first_click = true;
}
if (attachment_extension) { if (attachment_extension) {
this.showPreview( this.showPreview(
attachment_id, attachment_id,
@ -145,9 +154,10 @@ odoo.define("attachment_preview", function(require) {
getPreviewableAttachments: function() { getPreviewableAttachments: function() {
var self = this; var self = this;
var deferred = $.Deferred(); var deferred = $.Deferred();
var $items = this.$el.find(".o_attachment_preview"); var $items = self.$el.find(".o_attachment_preview");
var attachments = _.object( var attachments = _.object(
$items.map(function() { $items.map(function() {
return parseInt($(this).attr("data-id"), 10); return parseInt($(this).attr("data-id"), 10);
@ -173,7 +183,7 @@ odoo.define("attachment_preview", function(require) {
function(extensions) { function(extensions) {
var reviewableAttachments = _.map( var reviewableAttachments = _.map(
_.keys( _.keys(
_.pick(extensions, function(extension, id) { _.pick(extensions, function(extension) {
return self.canPreview(extension); return self.canPreview(extension);
}) })
), ),
@ -218,7 +228,7 @@ odoo.define("attachment_preview", function(require) {
basic_fields.FieldBinaryFile.include(AttachmentPreviewMixin); basic_fields.FieldBinaryFile.include(AttachmentPreviewMixin);
basic_fields.FieldBinaryFile.include({ basic_fields.FieldBinaryFile.include({
events: _.extend({}, basic_fields.FieldBinaryFile.prototype.events, { events: _.extend({}, basic_fields.FieldBinaryFile.prototype.events, {
"click .fa-search": "_onPreview", "click .fa-external-link": "_onPreview",
}), }),
_renderReadonly: function() { _renderReadonly: function() {
@ -226,7 +236,7 @@ odoo.define("attachment_preview", function(require) {
this._super.apply(this, arguments); this._super.apply(this, arguments);
if (this.recordData.id) { if (this.recordData.id) {
this._getBinaryExtension().done(function(extension) { this._getBinaryExtension().then(function(extension) {
if (self.canPreview(extension)) { if (self.canPreview(extension)) {
self._renderPreviewButton(extension); self._renderPreviewButton(extension);
} }
@ -236,7 +246,7 @@ odoo.define("attachment_preview", function(require) {
_renderPreviewButton: function(extension) { _renderPreviewButton: function(extension) {
this.$previewBtn = $("<a/>"); this.$previewBtn = $("<a/>");
this.$previewBtn.addClass("fa fa-search mr-2"); this.$previewBtn.addClass("fa fa-external-link mr-2");
this.$previewBtn.attr("href", "javascript:void(0)"); this.$previewBtn.attr("href", "javascript:void(0)");
this.$previewBtn.attr( this.$previewBtn.attr(
"title", "title",
@ -284,6 +294,7 @@ odoo.define("attachment_preview", function(require) {
}, },
start: function() { start: function() {
first_click = true;
var res = this._super.apply(this, arguments); var res = this._super.apply(this, arguments);
this.$overlay = this.$el.find(".attachment_preview_overlay"); this.$overlay = this.$el.find(".attachment_preview_overlay");
this.$iframe = this.$el.find(".attachment_preview_iframe"); this.$iframe = this.$el.find(".attachment_preview_iframe");
@ -337,6 +348,7 @@ odoo.define("attachment_preview", function(require) {
}, },
hide: function() { hide: function() {
first_click = true;
this.$el.addClass("d-none"); this.$el.addClass("d-none");
this.trigger("hidden"); this.trigger("hidden");
}, },
@ -356,7 +368,18 @@ odoo.define("attachment_preview", function(require) {
return; return;
} }
var att = this.attachments[this.activeIndex]; if (first_click) {
for (var i in this.attachments) {
if (this.attachments[i].id === active_attachment_id.toString()) {
active_attachment_index = i;
first_click = false;
}
}
} else {
active_attachment_index = this.activeIndex;
}
var att = this.attachments[active_attachment_index];
this.$iframe.attr("src", att.previewUrl); this.$iframe.attr("src", att.previewUrl);
}, },
@ -411,7 +434,7 @@ odoo.define("attachment_preview", function(require) {
return this._super.apply(this, arguments); return this._super.apply(this, arguments);
}, },
_onAttachmentPreview: function(event) { _onAttachmentPreview: function() {
this.showAttachmentPreviewWidget(); this.showAttachmentPreviewWidget();
}, },
}); });

View File

@ -4,6 +4,7 @@
// This file contains tweaks for viewerjs itself and is not meant to be run in // This file contains tweaks for viewerjs itself and is not meant to be run in
// OpenERP's context // OpenERP's context
(function(original_Viewer) { (function(original_Viewer) {
"use strict";
window.Viewer = function(plugin, parameters) { window.Viewer = function(plugin, parameters) {
if (!plugin) { if (!plugin) {
// eslint-disable-next-line no-alert // eslint-disable-next-line no-alert

View File

@ -8,40 +8,30 @@ from odoo.tests.common import TransactionCase
class TestAttachmentPreview(TransactionCase): class TestAttachmentPreview(TransactionCase):
def test_get_extension(self): def test_get_extension(self):
attachment = self.env['ir.attachment'].create({ attachment = self.env["ir.attachment"].create(
'datas': base64.b64encode(b'from this, to that.'), {"datas": base64.b64encode(b"from this, to that."), "name": "doc.txt"}
'name': 'doc.txt',
'datas_fname': 'doc.txt'
})
attachment2 = self.env['ir.attachment'].create({
'datas': base64.b64encode(b'Png'),
'name': 'image.png',
'datas_fname': 'image.png'
})
res = self.env['ir.attachment'].get_attachment_extension(
attachment.id
) )
self.assertEqual(res, 'txt') attachment2 = self.env["ir.attachment"].create(
{"datas": base64.b64encode(b"Png"), "name": "image.png"}
)
res = self.env["ir.attachment"].get_attachment_extension(attachment.id)
self.assertEqual(res, "txt")
res = self.env['ir.attachment'].get_attachment_extension( res = self.env["ir.attachment"].get_attachment_extension(
[attachment.id, attachment2.id] [attachment.id, attachment2.id]
) )
self.assertEqual(res[attachment.id], 'txt') self.assertEqual(res[attachment.id], "txt")
self.assertEqual(res[attachment2.id], 'png') self.assertEqual(res[attachment2.id], "png")
res2 = self.env['ir.attachment'].get_binary_extension( res2 = self.env["ir.attachment"].get_binary_extension(
'ir.attachment', "ir.attachment", attachment.id, "datas"
attachment.id,
'datas'
) )
self.assertTrue(res2) self.assertTrue(res2)
module = self.env['ir.module.module'].search([]).filtered( module = (
lambda m: m.icon_image self.env["ir.module.module"].search([]).filtered(lambda m: m.icon_image)[0]
)[0] )
res3 = self.env['ir.attachment'].get_binary_extension( res3 = self.env["ir.attachment"].get_binary_extension(
'ir.module.module', "ir.module.module", module.id, "icon_image"
module.id,
'icon_image'
) )
self.assertTrue(res3) self.assertTrue(res3)