[IMP] attachment_preview: black, isort, prettier

This commit is contained in:
vancouver29 2022-08-23 11:35:25 +02:00 committed by anusrinps96
parent 57ef68f803
commit 1ee243d342
8 changed files with 280 additions and 202 deletions

View File

@ -4,21 +4,16 @@
{ {
"name": "Preview attachments", "name": "Preview attachments",
"version": "12.0.1.0.2", "version": "12.0.1.0.2",
"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',
'mail'
],
"data": [ "data": [
"templates/assets.xml", "templates/assets.xml",
], ],
"qweb": [ "qweb": [
'static/src/xml/attachment_preview.xml', "static/src/xml/attachment_preview.xml",
], ],
"installable": True, "installable": True,
} }

View File

@ -6,70 +6,71 @@ import logging
import mimetypes import mimetypes
import os.path import os.path
from odoo import models, api from odoo import api, models
_logger = logging.getLogger(__name__) _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: if not this.id:
result[this.id] = False result[this.id] = False
continue continue
extension = '' 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
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) _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], 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", "datas_fname")
self._name, ids, 'datas', 'datas_fname')

View File

@ -1,41 +1,69 @@
/* Copyright 2014 Therp BV (<http://therp.nl>) /* Copyright 2014 Therp BV (<http://therp.nl>)
* License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). */ * License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). */
odoo.define('attachment_preview', function (require) { odoo.define("attachment_preview", function (require) {
'use strict'; "use strict";
var core = require('web.core'); var core = require("web.core");
var _t = core._t; var _t = core._t;
var qweb = core.qweb; 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 FormController = require("web.FormController");
var Widget = require('web.Widget'); var Widget = require("web.Widget");
var AttachmentPreviewMixin = { var AttachmentPreviewMixin = {
canPreview: function (extension) { canPreview: function (extension) {
return $.inArray( return (
extension, $.inArray(extension, [
['odt', 'odp', 'ods', 'fodt', 'pdf', 'ott', 'fodp', 'otp', "odt",
'fods', 'ots', "odp",
]) > -1; "ods",
"fodt",
"pdf",
"ott",
"fodp",
"otp",
"fods",
"ots",
]) > -1
);
}, },
getUrl: function (attachment_id, attachment_url, attachment_extension, attachment_title) { getUrl: function (
var url = (window.location.origin || '') + attachment_id,
'/attachment_preview/static/lib/ViewerJS/index.html' + attachment_url,
'?type=' + encodeURIComponent(attachment_extension) + attachment_extension,
'&title=' + encodeURIComponent(attachment_title) + attachment_title
'#' + ) {
attachment_url.replace(window.location.origin, ''); var url =
(window.location.origin || "") +
"/attachment_preview/static/lib/ViewerJS/index.html" +
"?type=" +
encodeURIComponent(attachment_extension) +
"&title=" +
encodeURIComponent(attachment_title) +
"#" +
attachment_url.replace(window.location.origin, "");
return url; return url;
}, },
showPreview: function (attachment_id, attachment_url, attachment_extension, attachment_title, split_screen) { showPreview: function (
var url = this.getUrl(attachment_id, attachment_url, attachment_extension, attachment_title); attachment_id,
attachment_url,
attachment_extension,
attachment_title,
split_screen
) {
var url = this.getUrl(
attachment_id,
attachment_url,
attachment_extension,
attachment_title
);
if (split_screen) { if (split_screen) {
this.trigger_up('onAttachmentPreview', {url: url}); this.trigger_up("onAttachmentPreview", {url: url});
} else { } else {
window.open(url); window.open(url);
} }
@ -45,7 +73,7 @@ odoo.define('attachment_preview', function (require) {
Chatter.include(AttachmentPreviewMixin); Chatter.include(AttachmentPreviewMixin);
Chatter.include({ Chatter.include({
events: _.extend({}, Chatter.prototype.events, { events: _.extend({}, Chatter.prototype.events, {
'click .o_attachment_preview': '_onPreviewAttachment', "click .o_attachment_preview": "_onPreviewAttachment",
}), }),
previewableAttachments: null, previewableAttachments: null,
@ -53,11 +81,13 @@ 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(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)
);
return res; return res;
}, },
@ -65,7 +95,7 @@ odoo.define('attachment_preview', function (require) {
update: function () { update: function () {
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().done(function () {
self._openAttachmentBox(); self._openAttachmentBox();
self.getPreviewableAttachments().done(function (atts) { self.getPreviewableAttachments().done(function (atts) {
@ -82,21 +112,33 @@ odoo.define('attachment_preview', function (require) {
event.preventDefault(); event.preventDefault();
var self = this, var self = this,
$target = $(event.currentTarget), $target = $(event.currentTarget),
split_screen = $target.attr('data-target') !== 'new', split_screen = $target.attr("data-target") !== "new",
attachment_id = parseInt($target.attr('data-id'), 10), attachment_id = parseInt($target.attr("data-id"), 10),
attachment_url = $target.attr('data-url'), attachment_url = $target.attr("data-url"),
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_extension) { if (attachment_extension) {
this.showPreview(attachment_id, attachment_url, attachment_extension, attachment_title, split_screen); this.showPreview(
attachment_id,
attachment_url,
attachment_extension,
attachment_title,
split_screen
);
} else { } else {
this._rpc({ this._rpc({
model: 'ir.attachment', model: "ir.attachment",
method: 'get_attachment_extension', method: "get_attachment_extension",
args: [attachment_id], args: [attachment_id],
}).then(function (extension) { }).then(function (extension) {
self.showPreview(attachment_id, attachment_url, extension, null, split_screen); self.showPreview(
attachment_id,
attachment_url,
extension,
null,
split_screen
);
}); });
} }
}, },
@ -105,56 +147,67 @@ odoo.define('attachment_preview', function (require) {
var self = this; var self = this;
var deferred = $.Deferred(); var deferred = $.Deferred();
var $items = this.$el.find('.o_attachment_preview'); var $items = this.$el.find(".o_attachment_preview");
var attachments = _.object($items.map(function () { var attachments = _.object(
return parseInt($(this).attr('data-id'), 10); $items.map(function () {
}), $items.map(function () { return parseInt($(this).attr("data-id"), 10);
return { }),
url: $(this).attr('data-url'), $items.map(function () {
extension: $(this).attr('data-extension'), return {
title: $(this).attr('data-original-title'), url: $(this).attr("data-url"),
}; extension: $(this).attr("data-extension"),
})); title: $(this).attr("data-original-title"),
};
})
);
this._rpc({ this._rpc({
model: 'ir.attachment', model: "ir.attachment",
method: 'get_attachment_extension', method: "get_attachment_extension",
args: [ args: [
_.map(_.keys(attachments), function (id) { _.map(_.keys(attachments), function (id) {
return parseInt(id, 10); return parseInt(id, 10);
}), }),
], ],
}).then(function (extensions) { }).then(
var reviewableAttachments = _.map(_.keys(_.pick(extensions, function (extension, id) { function (extensions) {
return self.canPreview(extension); var reviewableAttachments = _.map(
})), function (id) { _.keys(
return { _.pick(extensions, function (extension, id) {
id: id, return self.canPreview(extension);
url: attachments[id].url, })
extension: extensions[id],
title: attachments[id].title,
previewUrl: self.getUrl(
id,
attachments[id].url,
extensions[id],
id + ' - ' + attachments[id].title
), ),
}; function (id) {
}); return {
deferred.resolve(reviewableAttachments); id: id,
}, function () { url: attachments[id].url,
deferred.reject(); extension: extensions[id],
}); title: attachments[id].title,
previewUrl: self.getUrl(
id,
attachments[id].url,
extensions[id],
id + " - " + attachments[id].title
),
};
}
);
deferred.resolve(reviewableAttachments);
},
function () {
deferred.reject();
}
);
return deferred.promise(); return deferred.promise();
}, },
updatePreviewButtons: function (previewableAttachments) { updatePreviewButtons: function (previewableAttachments) {
this.$el.find('.o_attachment_preview').each(function () { this.$el.find(".o_attachment_preview").each(function () {
var $this = $(this); var $this = $(this);
var id = $this.attr('data-id'); var id = $this.attr("data-id");
var att = _.findWhere(previewableAttachments, {id: id}); var att = _.findWhere(previewableAttachments, {id: id});
if (att) { if (att) {
$this.attr('data-extension', att.extension); $this.attr("data-extension", att.extension);
} else { } else {
$this.remove(); $this.remove();
} }
@ -165,7 +218,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-search": "_onPreview",
}), }),
_renderReadonly: function () { _renderReadonly: function () {
@ -183,23 +236,21 @@ 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-search mr-2");
this.$previewBtn.attr('href', 'javascript:void(0)'); this.$previewBtn.attr("href", "javascript:void(0)");
this.$previewBtn.attr('title', _.str.sprintf(_t('Preview %s'), this.field.string)); this.$previewBtn.attr(
this.$previewBtn.attr('data-extension', extension); "title",
this.$el.find('.fa-download').before(this.$previewBtn); _.str.sprintf(_t("Preview %s"), this.field.string)
);
this.$previewBtn.attr("data-extension", extension);
this.$el.find(".fa-download").before(this.$previewBtn);
}, },
_getBinaryExtension: function () { _getBinaryExtension: function () {
return this._rpc({ return this._rpc({
model: 'ir.attachment', model: "ir.attachment",
method: 'get_binary_extension', method: "get_binary_extension",
args: [ args: [this.model, this.recordData.id, this.name, this.attrs.filename],
this.model,
this.recordData.id,
this.name,
this.attrs.filename,
],
}); });
}, },
@ -207,13 +258,13 @@ odoo.define('attachment_preview', function (require) {
this.showPreview( this.showPreview(
null, null,
_.str.sprintf( _.str.sprintf(
'/web/content?model=%s&field=%s&id=%d', "/web/content?model=%s&field=%s&id=%d",
this.model, this.model,
this.name, this.name,
this.recordData.id this.recordData.id
), ),
$(event.currentTarget).attr('data-extension'), $(event.currentTarget).attr("data-extension"),
_.str.sprintf(_t('Preview %s'), this.field.string), _.str.sprintf(_t("Preview %s"), this.field.string),
false false
); );
event.stopPropagation(); event.stopPropagation();
@ -221,22 +272,22 @@ odoo.define('attachment_preview', function (require) {
}); });
var AttachmentPreviewWidget = Widget.extend({ var AttachmentPreviewWidget = Widget.extend({
template: 'attachment_preview.AttachmentPreviewWidget', template: "attachment_preview.AttachmentPreviewWidget",
activeIndex: 0, activeIndex: 0,
attachments: null, attachments: null,
events: { events: {
'click .attachment_preview_close': '_onCloseClick', "click .attachment_preview_close": "_onCloseClick",
'click .attachment_preview_previous': '_onPreviousClick', "click .attachment_preview_previous": "_onPreviousClick",
'click .attachment_preview_next': '_onNextClick', "click .attachment_preview_next": "_onNextClick",
'click .attachment_preview_popout': '_onPopoutClick', "click .attachment_preview_popout": "_onPopoutClick",
}, },
start: function () { start: function () {
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");
this.$current = this.$el.find('.attachment_preview_current'); this.$current = this.$el.find(".attachment_preview_current");
return res; return res;
}, },
@ -281,28 +332,32 @@ odoo.define('attachment_preview', function (require) {
}, },
show: function () { show: function () {
this.$el.removeClass('d-none'); this.$el.removeClass("d-none");
this.trigger('shown'); this.trigger("shown");
}, },
hide: function () { hide: function () {
this.$el.addClass('d-none'); this.$el.addClass("d-none");
this.trigger('hidden'); this.trigger("hidden");
}, },
updatePaginator: function () { updatePaginator: function () {
var value = _.str.sprintf('%s / %s', this.activeIndex + 1, this.attachments.length); var value = _.str.sprintf(
"%s / %s",
this.activeIndex + 1,
this.attachments.length
);
this.$current.html(value); this.$current.html(value);
}, },
loadPreview: function () { loadPreview: function () {
if (this.attachments.length === 0) { if (this.attachments.length === 0) {
this.$iframe.attr('src', 'about:blank'); this.$iframe.attr("src", "about:blank");
return; return;
} }
var att = this.attachments[this.activeIndex]; var att = this.attachments[this.activeIndex];
this.$iframe.attr('src', att.previewUrl); this.$iframe.attr("src", att.previewUrl);
}, },
setAttachments: function (attachments) { setAttachments: function (attachments) {
@ -315,7 +370,7 @@ odoo.define('attachment_preview', function (require) {
FormRenderer.include({ FormRenderer.include({
custom_events: _.extend({}, FormRenderer.prototype.custom_events, { custom_events: _.extend({}, FormRenderer.prototype.custom_events, {
onAttachmentPreview: '_onAttachmentPreview', onAttachmentPreview: "_onAttachmentPreview",
}), }),
attachmentPreviewWidget: null, attachmentPreviewWidget: null,
@ -323,7 +378,11 @@ odoo.define('attachment_preview', function (require) {
init: function () { init: function () {
var res = this._super.apply(this, arguments); var res = this._super.apply(this, arguments);
this.attachmentPreviewWidget = new AttachmentPreviewWidget(this); this.attachmentPreviewWidget = new AttachmentPreviewWidget(this);
this.attachmentPreviewWidget.on('hidden', this, this._attachmentPreviewWidgetHidden); this.attachmentPreviewWidget.on(
"hidden",
this,
this._attachmentPreviewWidgetHidden
);
return res; return res;
}, },
@ -335,11 +394,11 @@ odoo.define('attachment_preview', function (require) {
}, },
_attachmentPreviewWidgetHidden: function () { _attachmentPreviewWidgetHidden: function () {
this.$el.removeClass('attachment_preview'); this.$el.removeClass("attachment_preview");
}, },
showAttachmentPreviewWidget: function () { showAttachmentPreviewWidget: function () {
this.$el.addClass('attachment_preview'); this.$el.addClass("attachment_preview");
this.attachmentPreviewWidget.setAttachments( this.attachmentPreviewWidget.setAttachments(
this.chatter.previewableAttachments this.chatter.previewableAttachments
@ -357,7 +416,6 @@ odoo.define('attachment_preview', function (require) {
}, },
}); });
return { return {
AttachmentPreviewMixin: AttachmentPreviewMixin, AttachmentPreviewMixin: AttachmentPreviewMixin,
AttachmentPreviewWidget: AttachmentPreviewWidget, AttachmentPreviewWidget: AttachmentPreviewWidget,

View File

@ -7,8 +7,8 @@
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
alert('Unsupported file type'); alert("Unsupported file type");
} }
return original_Viewer(plugin, parameters); return original_Viewer(plugin, parameters);
}; };
}(window.Viewer)); })(window.Viewer);

View File

@ -44,7 +44,7 @@
padding: 4px; padding: 4px;
float: left; float: left;
width: 100%; width: 100%;
background-color: #FFF; background-color: #fff;
border-left: 1px solid $gray-800; border-left: 1px solid $gray-800;
button { button {

View File

@ -1,19 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8" ?>
<templates> <templates>
<t t-extend="mail.Attachment"> <t t-extend="mail.Attachment">
<t t-jquery=".o_attachment_download" t-operation="after"> <t t-jquery=".o_attachment_download" t-operation="after">
<span t-if="!attachment.callback and attachment.url" <span
class="fa fa-search ml4 o_attachment_preview" t-if="!attachment.callback and attachment.url"
t-att-data-id="attachment.id" class="fa fa-search ml4 o_attachment_preview"
t-att-data-url="attachment.url" t-att-data-id="attachment.id"
t-attf-title="Preview #{attachment.name} in side panel"/> t-att-data-url="attachment.url"
t-attf-title="Preview #{attachment.name} in side panel"
/>
<span t-if="!attachment.callback and attachment.url" <span
class="fa fa-external-link ml4 o_attachment_preview o_attachment_preview_new_tab" t-if="!attachment.callback and attachment.url"
data-target="new" class="fa fa-external-link ml4 o_attachment_preview o_attachment_preview_new_tab"
t-att-data-id="attachment.id" data-target="new"
t-att-data-url="attachment.url" t-att-data-id="attachment.id"
t-attf-title="Open preview #{attachment.name} in a new tab"/> t-att-data-url="attachment.url"
t-attf-title="Open preview #{attachment.name} in a new tab"
/>
</t> </t>
</t> </t>
@ -21,15 +25,25 @@
<div class="attachment_preview_widget d-none"> <div class="attachment_preview_widget d-none">
<div class="attachment_preview_buttons"> <div class="attachment_preview_buttons">
<div class="button-group pull-left"> <div class="button-group pull-left">
<button class="btn btn-sm btn-secondary attachment_preview_previous"><i class="fa fa-chevron-left"/></button> <button
<button class="btn btn-sm btn-secondary disabled attachment_preview_current">1 / 5</button> class="btn btn-sm btn-secondary attachment_preview_previous"
<button class="btn btn-sm btn-secondary attachment_preview_next"><i class="fa fa-chevron-right"/></button> ><i class="fa fa-chevron-left" /></button>
<button
class="btn btn-sm btn-secondary disabled attachment_preview_current"
>1 / 5</button>
<button class="btn btn-sm btn-secondary attachment_preview_next"><i
class="fa fa-chevron-right"
/></button>
</div> </div>
<button class="btn btn-sm btn-secondary pull-left ml8 attachment_preview_popout"><i class="fa fa-external-link"/></button> <button
class="btn btn-sm btn-secondary pull-left ml8 attachment_preview_popout"
><i class="fa fa-external-link" /></button>
<button class="btn btn-sm btn-secondary pull-right attachment_preview_close"><i class="fa fa-times"/></button> <button
class="btn btn-sm btn-secondary pull-right attachment_preview_close"
><i class="fa fa-times" /></button>
</div> </div>
<iframe class="attachment_preview_iframe"></iframe> <iframe class="attachment_preview_iframe" />
</div> </div>
</t> </t>
</templates> </templates>

View File

@ -1,9 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8" ?>
<odoo> <odoo>
<template id="assets_backend" name="attachment_preview assets" inherit_id="web.assets_backend"> <template
id="assets_backend"
name="attachment_preview assets"
inherit_id="web.assets_backend"
>
<xpath expr="." position="inside"> <xpath expr="." position="inside">
<script type="text/javascript" src="/attachment_preview/static/src/js/attachment_preview.js"></script> <script
<link rel="stylesheet" type="text/scss" href="/attachment_preview/static/src/scss/attachment_preview.scss" /> type="text/javascript"
src="/attachment_preview/static/src/js/attachment_preview.js"
/>
<link
rel="stylesheet"
type="text/scss"
href="/attachment_preview/static/src/scss/attachment_preview.scss"
/>
</xpath> </xpath>
</template> </template>
</odoo> </odoo>

View File

@ -2,45 +2,44 @@
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import base64 import base64
from odoo.tests.common import TransactionCase 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.'), {
'name': 'doc.txt', "datas": base64.b64encode(b"from this, to that."),
'datas_fname': '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",
"datas_fname": "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)