[MIG] attachment_preview: Migration to 15.0

This commit is contained in:
vancouver29 2022-08-23 16:36:54 +02:00 committed by anusrinps96
parent 1ee243d342
commit e3debed66d
14 changed files with 849 additions and 508 deletions

View File

@ -3,17 +3,27 @@
{
"name": "Preview attachments",
"version": "12.0.1.0.2",
"version": "15.0.1.0.0",
"author": "Therp BV," "Onestein," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/knowledge",
"license": "AGPL-3",
"summary": "Preview attachments supported by Viewer.js",
"category": "Knowledge Management",
"depends": ["web", "mail"],
"data": [
"templates/assets.xml",
],
"qweb": [
"static/src/xml/attachment_preview.xml",
],
"data": [],
"qweb": [],
"assets": {
"web._assets_primary_variables": [],
"web.assets_backend": [
"attachment_preview/static/src/js/models/attachment_card/attachment_card.esm.js",
"attachment_preview/static/src/js/attachmentPreviewWidget.esm.js",
"attachment_preview/static/src/js/components/chatter/chatter.esm.js",
"attachment_preview/static/src/scss/attachment_preview.scss",
],
"web.assets_frontend": [],
"web.assets_tests": [],
"web.qunit_suite_tests": [],
"web.assets_qweb": ["attachment_preview/static/src/xml/attachment_preview.xml"],
},
"installable": True,
}

View File

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

View File

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

View File

@ -0,0 +1,43 @@
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * attachment_preview
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 15.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2022-08-23 14:29+0000\n"
"PO-Revision-Date: 2022-08-23 14:29+0000\n"
"Last-Translator: \n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: \n"
#. module: attachment_preview
#: model:ir.model,name:attachment_preview.model_ir_attachment
msgid "Attachment"
msgstr "Tập tin đính kèm"
#. module: attachment_preview
#. openerp-web
#: code:addons/attachment_preview/static/src/xml/attachment_preview.xml:0
#, python-format
msgid "Open in new page"
msgstr "Mở trong trang mới"
#. module: attachment_preview
#. openerp-web
#: code:addons/attachment_preview/static/src/xml/attachment_preview.xml:0
#, python-format
msgid "Preview"
msgstr "Xem trước"
#. module: attachment_preview
#. openerp-web
#: code:addons/attachment_preview/static/src/js/components/chatter/chatter.js:0
#: code:addons/attachment_preview/static/src/js/components/chatter/chatter.js:0
#, python-format
msgid "Preview %s"
msgstr "Xem trước %s"

View File

@ -17,7 +17,7 @@ class IrAttachment(models.Model):
@api.model
def get_binary_extension(self, model, ids, binary_field, filename_field=None):
result = {}
ids_to_browse = ids if isinstance(ids, collections.Iterable) else [ids]
ids_to_browse = ids if isinstance(ids, collections.abc.Iterable) else [ids]
# First pass: load fields in bin_size mode to avoid loading big files
# unnecessarily.
@ -25,9 +25,7 @@ class IrAttachment(models.Model):
for this in (
self.env[model].with_context(bin_size=True).browse(ids_to_browse)
):
if not this.id:
result[this.id] = False
continue
result[this.id] = False
extension = ""
if this[filename_field]:
filename, extension = os.path.splitext(this[filename_field])
@ -42,9 +40,7 @@ class IrAttachment(models.Model):
# to get the extension from the content
ids_to_browse = [_id for _id in ids_to_browse if _id not in result]
for this in self.env[model].with_context(bin_size=True).browse(ids_to_browse):
if not this[binary_field]:
result[this.id] = False
continue
result[this.id] = False
try:
import magic
@ -52,25 +48,25 @@ class IrAttachment(models.Model):
mimetype = magic.from_file(
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:
mimetype = magic.from_buffer(this[binary_field], mime=True)
_logger.debug("Magic determined mimetype %s from buffer", mimetype)
except ImportError:
(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(mimetype.split(";")[0], strict=False)
result[this.id] = extension
for _id in result:
result[_id] = (result[_id] or "").lstrip(".").lower()
return result if isinstance(ids, collections.Iterable) else result[ids]
return result if isinstance(ids, collections.abc.Iterable) else result[ids]
@api.model
def get_attachment_extension(self, ids):
return self.get_binary_extension(self._name, ids, "datas", "datas_fname")
return self.get_binary_extension(self._name, ids, "datas", "name")

View File

@ -0,0 +1,134 @@
/** @odoo-module */
import Widget from "web.Widget";
var active_attachment_index = 0;
var is_first_click = true;
var AttachmentPreviewWidget = Widget.extend({
template: "attachment_preview.AttachmentPreviewWidget",
activeIndex: 0,
events: {
"click .attachment_preview_close": "_onCloseClick",
"click .attachment_preview_previous": "_onPreviousClick",
"click .attachment_preview_next": "_onNextClick",
"click .attachment_preview_popout": "_onPopoutClick",
},
start: function () {
// First_click = true;
var res = this._super.apply(this, arguments);
this.$overlay = $(".attachment_preview_overlay");
this.$iframe = $(".attachment_preview_iframe");
this.$current = $(".attachment_preview_current");
return res;
},
_onCloseClick: function () {
this.hide();
},
_onPreviousClick: function () {
this.previous();
},
_onNextClick: function () {
this.next();
},
_onPopoutClick: function () {
if (!this.attachments[this.activeIndex]) {
return;
}
window.open(this.attachments[this.activeIndex].previewUrl);
},
next: function () {
if (is_first_click) {
is_first_click = !is_first_click;
}
var index = this.activeIndex + 1;
if (index >= this.attachments.length) {
index = 0;
}
this.activeIndex = index;
this.updatePaginator();
this.loadPreview();
},
previous: function () {
if (is_first_click) {
is_first_click = !is_first_click;
}
var index = this.activeIndex - 1;
if (index < 0) {
index = this.attachments.length - 1;
}
this.activeIndex = index;
this.updatePaginator();
this.loadPreview();
},
show: function () {
this.$el.removeClass("d-none");
this.trigger("shown");
},
hide: function () {
is_first_click = true;
this.$el.addClass("d-none");
this.trigger("hidden");
},
updatePaginator: function () {
var value = _.str.sprintf(
"%s / %s",
this.activeIndex + 1,
this.attachments.length
);
this.$overlay = $(".attachment_preview_overlay");
this.$iframe = $(".attachment_preview_iframe");
this.$current = $(".attachment_preview_current");
this.$current.html(value);
},
loadPreview: function () {
if (this.attachments.length === 0) {
this.$iframe.attr("src", "about:blank");
return;
}
if (is_first_click) {
for (let i = 0; i < this.attachments.length; i++) {
if (
parseInt(this.attachments[i].id, 10) === this.active_attachment_id
) {
active_attachment_index = i;
is_first_click = false;
}
}
} else {
active_attachment_index = this.activeIndex;
}
var att = this.attachments[active_attachment_index];
this.$iframe.attr("src", att.previewUrl);
},
setAttachments: function (attachments, active_attachment_id, first_click) {
is_first_click = first_click;
if (active_attachment_id) {
this.active_attachment_id = active_attachment_id;
}
if (attachments) {
this.attachments = attachments;
this.activeIndex = 0;
this.updatePaginator();
this.loadPreview();
}
},
});
export default AttachmentPreviewWidget;

View File

@ -1,423 +0,0 @@
/* Copyright 2014 Therp BV (<http://therp.nl>)
* License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). */
odoo.define("attachment_preview", function (require) {
"use strict";
var core = require("web.core");
var _t = core._t;
var qweb = core.qweb;
var Chatter = require("mail.Chatter");
var basic_fields = require("web.basic_fields");
var FormRenderer = require("web.FormRenderer");
var FormController = require("web.FormController");
var Widget = require("web.Widget");
var AttachmentPreviewMixin = {
canPreview: function (extension) {
return (
$.inArray(extension, [
"odt",
"odp",
"ods",
"fodt",
"pdf",
"ott",
"fodp",
"otp",
"fods",
"ots",
]) > -1
);
},
getUrl: function (
attachment_id,
attachment_url,
attachment_extension,
attachment_title
) {
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;
},
showPreview: function (
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) {
this.trigger_up("onAttachmentPreview", {url: url});
} else {
window.open(url);
}
},
};
Chatter.include(AttachmentPreviewMixin);
Chatter.include({
events: _.extend({}, Chatter.prototype.events, {
"click .o_attachment_preview": "_onPreviewAttachment",
}),
previewableAttachments: null,
_openAttachmentBox: function () {
var res = this._super.apply(this, arguments);
this.getPreviewableAttachments().done(
function (atts) {
this.previewableAttachments = atts;
this.updatePreviewButtons(atts);
this.getParent().attachmentPreviewWidget.setAttachments(atts);
}.bind(this)
);
return res;
},
update: function () {
var res = this._super.apply(this, arguments);
var self = this;
if (this.getParent().$el.hasClass("attachment_preview")) {
this._fetchAttachments().done(function () {
self._openAttachmentBox();
self.getPreviewableAttachments().done(function (atts) {
self.updatePreviewButtons(self.previewableAttachments);
self.previewableAttachments = atts;
self.getParent().attachmentPreviewWidget.setAttachments(atts);
});
});
}
return res;
},
_onPreviewAttachment: function (event) {
event.preventDefault();
var self = this,
$target = $(event.currentTarget),
split_screen = $target.attr("data-target") !== "new",
attachment_id = parseInt($target.attr("data-id"), 10),
attachment_url = $target.attr("data-url"),
attachment_extension = $target.attr("data-extension"),
attachment_title = $target.attr("data-original-title");
if (attachment_extension) {
this.showPreview(
attachment_id,
attachment_url,
attachment_extension,
attachment_title,
split_screen
);
} else {
this._rpc({
model: "ir.attachment",
method: "get_attachment_extension",
args: [attachment_id],
}).then(function (extension) {
self.showPreview(
attachment_id,
attachment_url,
extension,
null,
split_screen
);
});
}
},
getPreviewableAttachments: function () {
var self = this;
var deferred = $.Deferred();
var $items = this.$el.find(".o_attachment_preview");
var attachments = _.object(
$items.map(function () {
return parseInt($(this).attr("data-id"), 10);
}),
$items.map(function () {
return {
url: $(this).attr("data-url"),
extension: $(this).attr("data-extension"),
title: $(this).attr("data-original-title"),
};
})
);
this._rpc({
model: "ir.attachment",
method: "get_attachment_extension",
args: [
_.map(_.keys(attachments), function (id) {
return parseInt(id, 10);
}),
],
}).then(
function (extensions) {
var reviewableAttachments = _.map(
_.keys(
_.pick(extensions, function (extension, id) {
return self.canPreview(extension);
})
),
function (id) {
return {
id: id,
url: attachments[id].url,
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();
},
updatePreviewButtons: function (previewableAttachments) {
this.$el.find(".o_attachment_preview").each(function () {
var $this = $(this);
var id = $this.attr("data-id");
var att = _.findWhere(previewableAttachments, {id: id});
if (att) {
$this.attr("data-extension", att.extension);
} else {
$this.remove();
}
});
},
});
basic_fields.FieldBinaryFile.include(AttachmentPreviewMixin);
basic_fields.FieldBinaryFile.include({
events: _.extend({}, basic_fields.FieldBinaryFile.prototype.events, {
"click .fa-search": "_onPreview",
}),
_renderReadonly: function () {
var self = this;
this._super.apply(this, arguments);
if (this.recordData.id) {
this._getBinaryExtension().done(function (extension) {
if (self.canPreview(extension)) {
self._renderPreviewButton(extension);
}
});
}
},
_renderPreviewButton: function (extension) {
this.$previewBtn = $("<a/>");
this.$previewBtn.addClass("fa fa-search mr-2");
this.$previewBtn.attr("href", "javascript:void(0)");
this.$previewBtn.attr(
"title",
_.str.sprintf(_t("Preview %s"), this.field.string)
);
this.$previewBtn.attr("data-extension", extension);
this.$el.find(".fa-download").before(this.$previewBtn);
},
_getBinaryExtension: function () {
return this._rpc({
model: "ir.attachment",
method: "get_binary_extension",
args: [this.model, this.recordData.id, this.name, this.attrs.filename],
});
},
_onPreview: function (event) {
this.showPreview(
null,
_.str.sprintf(
"/web/content?model=%s&field=%s&id=%d",
this.model,
this.name,
this.recordData.id
),
$(event.currentTarget).attr("data-extension"),
_.str.sprintf(_t("Preview %s"), this.field.string),
false
);
event.stopPropagation();
},
});
var AttachmentPreviewWidget = Widget.extend({
template: "attachment_preview.AttachmentPreviewWidget",
activeIndex: 0,
attachments: null,
events: {
"click .attachment_preview_close": "_onCloseClick",
"click .attachment_preview_previous": "_onPreviousClick",
"click .attachment_preview_next": "_onNextClick",
"click .attachment_preview_popout": "_onPopoutClick",
},
start: function () {
var res = this._super.apply(this, arguments);
this.$overlay = this.$el.find(".attachment_preview_overlay");
this.$iframe = this.$el.find(".attachment_preview_iframe");
this.$current = this.$el.find(".attachment_preview_current");
return res;
},
_onCloseClick: function () {
this.hide();
},
_onPreviousClick: function () {
this.previous();
},
_onNextClick: function () {
this.next();
},
_onPopoutClick: function () {
if (!this.attachments[this.activeIndex]) {
return;
}
window.open(this.attachments[this.activeIndex].previewUrl);
},
next: function () {
var index = this.activeIndex + 1;
if (index >= this.attachments.length) {
index = 0;
}
this.activeIndex = index;
this.updatePaginator();
this.loadPreview();
},
previous: function () {
var index = this.activeIndex - 1;
if (index < 0) {
index = this.attachments.length - 1;
}
this.activeIndex = index;
this.updatePaginator();
this.loadPreview();
},
show: function () {
this.$el.removeClass("d-none");
this.trigger("shown");
},
hide: function () {
this.$el.addClass("d-none");
this.trigger("hidden");
},
updatePaginator: function () {
var value = _.str.sprintf(
"%s / %s",
this.activeIndex + 1,
this.attachments.length
);
this.$current.html(value);
},
loadPreview: function () {
if (this.attachments.length === 0) {
this.$iframe.attr("src", "about:blank");
return;
}
var att = this.attachments[this.activeIndex];
this.$iframe.attr("src", att.previewUrl);
},
setAttachments: function (attachments) {
this.attachments = attachments;
this.activeIndex = 0;
this.updatePaginator();
this.loadPreview();
},
});
FormRenderer.include({
custom_events: _.extend({}, FormRenderer.prototype.custom_events, {
onAttachmentPreview: "_onAttachmentPreview",
}),
attachmentPreviewWidget: null,
init: function () {
var res = this._super.apply(this, arguments);
this.attachmentPreviewWidget = new AttachmentPreviewWidget(this);
this.attachmentPreviewWidget.on(
"hidden",
this,
this._attachmentPreviewWidgetHidden
);
return res;
},
start: function () {
var self = this;
return this._super.apply(this, arguments).then(function () {
return self.attachmentPreviewWidget.insertAfter(self.$el);
});
},
_attachmentPreviewWidgetHidden: function () {
this.$el.removeClass("attachment_preview");
},
showAttachmentPreviewWidget: function () {
this.$el.addClass("attachment_preview");
this.attachmentPreviewWidget.setAttachments(
this.chatter.previewableAttachments
);
this.attachmentPreviewWidget.show();
},
on_detach_callback: function () {
this.attachmentPreviewWidget.hide();
return this._super.apply(this, arguments);
},
_onAttachmentPreview: function (event) {
this.showAttachmentPreviewWidget();
},
});
return {
AttachmentPreviewMixin: AttachmentPreviewMixin,
AttachmentPreviewWidget: AttachmentPreviewWidget,
};
});

View File

@ -0,0 +1,272 @@
/** @odoo-module **/
import AttachmentPreviewWidget from "../../attachmentPreviewWidget";
import {Chatter} from "@mail/components/chatter/chatter";
import {patch} from "web.utils";
odoo.define("attachment_preview.chatter", function (require) {
const components = {Chatter};
var rpc = require("web.rpc");
var basic_fields = require("web.basic_fields");
var core = require("web.core");
var _t = core._t;
function getUrl(
attachment_id,
attachment_url,
attachment_extension,
attachment_title
) {
var url = "";
if (attachment_url) {
if (attachment_url.slice(0, 21) === "/web/static/lib/pdfjs") {
url = (window.location.origin || "") + attachment_url;
} else {
url =
(window.location.origin || "") +
"/attachment_preview/static/lib/ViewerJS/index.html" +
"?type=" +
encodeURIComponent(attachment_extension) +
"&zoom=automatic" +
"&title=" +
encodeURIComponent(attachment_title) +
"#" +
attachment_url.replace(window.location.origin, "");
}
} else {
url =
(window.location.origin || "") +
"/attachment_preview/static/lib/ViewerJS/index.html" +
"?type=" +
encodeURIComponent(attachment_extension) +
"&title=" +
encodeURIComponent(attachment_title) +
"&zoom=automatic" +
"#" +
"/web/content/" +
attachment_id +
"?model%3Dir.attachment";
}
return url;
}
function canPreview(extension) {
return (
$.inArray(extension, [
"odt",
"odp",
"ods",
"fodt",
"pdf",
"ott",
"fodp",
"otp",
"fods",
"ots",
]) > -1
);
}
patch(
components.Chatter.prototype,
"attachment_preview/static/src/js/components/chatter/chatter.js",
{
/**
* @override
*/
constructor(...args) {
this._super(...args);
this._showPreview = this._showPreview.bind(this);
this.canPreview = this.canPreview.bind(this);
},
/**
* @override
*/
_update() {
// Var res = this._super.apply(this, arguments);
var self = this;
self._getPreviewableAttachments().then(function (atts) {
self.previewableAttachments = atts;
self._updatePreviewButtons(self.previewableAttachments);
if (!self.attachmentPreviewWidget) {
self.attachmentPreviewWidget = new AttachmentPreviewWidget(
self
);
self.attachmentPreviewWidget.setAttachments(atts);
}
self.previewableAttachments = atts;
// ChatterpreviewableAttachments = atts;
self.attachmentPreviewWidget.setAttachments(atts);
});
},
_getPreviewableAttachments: function () {
var self = this;
var deferred = $.Deferred();
const chatter = self.messaging.models["mail.chatter"].get(
self.props.chatterLocalId
);
const thread = chatter ? chatter.thread : undefined;
var attachments = {};
if (thread) {
attachments = thread.allAttachments;
}
attachments = _.object(
attachments.map((attachment) => {
return attachment.id;
}),
attachments.map((attachment) => {
if (attachment.defaultSource) {
return {
url: attachment.defaultSource,
extension: attachment.extension,
title: attachment.name,
};
}
return {
url: "/web/content?id=" + attachment.id + "&download=true",
extension: attachment.extension,
title: attachment.name,
};
})
);
rpc.query({
model: "ir.attachment",
method: "get_attachment_extension",
args: [
_.map(_.keys(attachments), function (id) {
return parseInt(id, 10);
}),
],
}).then(
function (extensions) {
var reviewableAttachments = _.map(
_.keys(
_.pick(extensions, function (extension) {
return canPreview(extension);
})
),
function (id) {
return {
id: id,
url: attachments[id].url,
extension: extensions[id],
title: attachments[id].title,
previewUrl: getUrl(
id,
attachments[id].url,
extensions[id],
attachments[id].title
),
};
}
);
deferred.resolve(reviewableAttachments);
},
function () {
deferred.reject();
}
);
return deferred.promise();
},
_updatePreviewButtons: function (previewableAttachments) {
$(this)
.find(".o_attachment_preview")
.each(function () {
var $this = $(this);
var att = _.findWhere(previewableAttachments, {
id: $this.attr("data-id"),
});
if (att) {
$this.attr("data-extension", att.extension);
} else {
$this.remove();
}
});
},
}
);
basic_fields.FieldBinaryFile.include(components.Chatter);
basic_fields.FieldBinaryFile.include({
showPreview(
attachment_id,
attachment_url,
attachment_extension,
attachment_title,
split_screen
) {
var url = getUrl(
attachment_id,
attachment_url,
attachment_extension,
attachment_title
);
if (split_screen) {
this.trigger("onAttachmentPreview", {url: url});
} else {
window.open(url);
}
},
_renderReadonly: function () {
var self = this;
this._super.apply(this, arguments);
if (this.recordData.id) {
this._getBinaryExtension().then(function (extension) {
if (canPreview(extension)) {
// Self._renderPreviewButton(extension, recordData);
self._renderPreviewButton(extension);
}
});
}
},
_renderPreviewButton: function (extension) {
this.$previewBtn = $("<a/>");
this.$previewBtn.addClass("fa fa-external-link mr-2");
this.$previewBtn.attr("href");
this.$previewBtn.attr(
"title",
_.str.sprintf(_t("Preview %s"), this.field.string)
);
this.$previewBtn.attr("data-extension", extension);
this.$el.find(".fa-download").after(this.$previewBtn);
this.$previewBtn.on("click", this._onPreview.bind(this));
},
_getBinaryExtension: function () {
return rpc.query({
model: "ir.attachment",
method: "get_binary_extension",
args: [this.model, this.recordData.id, this.name, this.attrs.filename],
});
},
_onPreview: function (event) {
this.showPreview(
null,
_.str.sprintf(
"/web/content?model=%s&field=%s&id=%d",
this.model,
this.name,
this.recordData.id
),
$(event.currentTarget).attr("data-extension"),
_.str.sprintf(_t("Preview %s"), this.field.string),
false
);
event.stopPropagation();
},
});
});

View File

@ -0,0 +1,276 @@
/** @odoo-module **/
import AttachmentPreviewWidget from "../../attachmentPreviewWidget.esm";
import FormRenderer from "web.FormRenderer";
import {registerInstancePatchModel} from "@mail/model/model_core";
odoo.define("attachment_preview.attachment_card", function (require) {
var rpc = require("web.rpc");
var chatterpreviewableAttachments = [];
var active_attachment_id = 0;
var first_click = true;
FormRenderer.include({
custom_events: _.extend({}, FormRenderer.prototype.custom_events, {
onAttachmentPreview: "_onAttachmentPreview",
}),
attachmentPreviewWidget: null,
init: function () {
var res = this._super(...arguments);
this.attachmentPreviewWidget = new AttachmentPreviewWidget(this);
this.attachmentPreviewWidget.on(
"hidden",
this,
this._attachmentPreviewWidgetHidden
);
return res;
},
start: function () {
var self = this;
return this._super.apply(this, arguments).then(function () {
self.attachmentPreviewWidget.insertAfter(self.$el);
});
},
_attachmentPreviewWidgetHidden: function () {
this.$el.removeClass("attachment_preview");
},
showAttachmentPreviewWidget: function (first_c) {
this.$el.addClass("attachment_preview");
this.attachmentPreviewWidget.setAttachments(
chatterpreviewableAttachments,
active_attachment_id,
first_c
);
this.attachmentPreviewWidget.show();
},
on_detach_callback: function () {
this.attachmentPreviewWidget.hide();
return this._super.apply(this, arguments);
},
_onAttachmentPreview: function () {
first_click = true;
this.showAttachmentPreviewWidget(first_click);
},
});
function canPreview(extension) {
return (
$.inArray(extension, [
"odt",
"odp",
"ods",
"fodt",
"pdf",
"ott",
"fodp",
"otp",
"fods",
"ots",
]) > -1
);
}
function getUrl(
attachment_id,
attachment_url,
attachment_extension,
attachment_title
) {
var url = "";
if (attachment_url) {
if (attachment_url.slice(0, 21) === "/web/static/lib/pdfjs") {
url = (window.location.origin || "") + attachment_url;
} else {
url =
(window.location.origin || "") +
"/attachment_preview/static/lib/ViewerJS/index.html" +
"?type=" +
encodeURIComponent(attachment_extension) +
"&title=" +
encodeURIComponent(attachment_title) +
"&zoom=automatic" +
"#" +
attachment_url.replace(window.location.origin, "");
}
return url;
}
url =
(window.location.origin || "") +
"/attachment_preview/static/lib/ViewerJS/index.html" +
"?type=" +
encodeURIComponent(attachment_extension) +
"&title=" +
encodeURIComponent(attachment_title) +
"&zoom=automatic" +
"#" +
"/web/content/" +
attachment_id +
"?model%3Dir.attachment";
return url;
}
registerInstancePatchModel(
"mail.attachment_card",
"attachment_preview/static/src/js/models/attachment_card/attachment_card.js",
{
/**
* @override
*/
_created() {
this._super();
this._onPreviewAttachment = this._onPreviewAttachment.bind(this);
var attachments = _.object(
this.attachmentList.attachments.map((attachment) => {
console.log("attachment", attachment);
return attachment.id;
}),
this.attachmentList.attachments.map((attachment) => {
if (
attachment.defaultSource &&
attachment.defaultSource.length > 38
) {
return {
url: attachment.defaultSource,
extension: attachment.extension,
title: attachment.name,
};
}
return {
url: "/web/content?id=" + attachment.id + "&download=true",
extension: attachment.extension,
title: attachment.name,
};
})
);
rpc.query({
model: "ir.attachment",
method: "get_attachment_extension",
args: [
_.map(_.keys(attachments), function (id) {
return parseInt(id, 10);
}),
],
}).then(function (extensions) {
var reviewableAttachments = _.map(
_.keys(
_.pick(extensions, function (extension) {
return canPreview(extension);
})
),
function (id) {
return {
id: id,
url: attachments[id].url,
extension: extensions[id],
title: attachments[id].title,
previewUrl: getUrl(
id,
attachments[id].url,
extensions[id],
attachments[id].title
),
};
}
);
chatterpreviewableAttachments = reviewableAttachments;
});
},
/**
* @private
* @param {attachment_id} attachment_id of the attachment
* @param {attachment_url} attachment_url of the attachment
* @param {attachment_extension} attachment_extension of the attachment
* @param {attachment_title} attachment_title of the attachment
* @param {split_screen} split_screen of the attachment
*/
_showPreview(
attachment_id,
attachment_url,
attachment_extension,
attachment_title,
split_screen
) {
// Let active_attURL = "";
// this.attachmentList.attachments.forEach((att) => {
// if (
// parseInt(att.localId.slice(20).slice(0, -1)) === attachment_id
// ) {
// if (att.__values.url === undefined) {
// att.__values.url = attachment_url.slice(
// window.location.origin.length
// );
// active_attURL = att.__values.url;
// }
// }
// });
var url = getUrl(
attachment_id,
attachment_url,
attachment_extension,
attachment_title
);
if (split_screen) {
this.component.trigger("onAttachmentPreview", {
url: url,
active_attachment_id: active_attachment_id,
});
} else {
window.open(url);
}
},
/**
* @private
* @param {event} event
*/
_onPreviewAttachment(event) {
event.preventDefault();
var self = this,
$target = $(event.currentTarget),
split_screen = $target.attr("data-target") !== "new",
attachment_id = this.attachment.id,
attachment_extension = "pdf",
attachment_title = this.attachment.filename,
attachment_url = this.attachment.defaultSource;
active_attachment_id = attachment_id;
if (attachment_extension) {
self._showPreview(
attachment_id,
attachment_url,
attachment_extension,
attachment_title,
split_screen
);
} else {
rpc.query({
model: "ir.attachment",
method: "get_attachment_extension",
args: [attachment_id],
}).then(function (extension) {
self.showPreview(
attachment_id,
attachment_url,
extension,
null,
split_screen
);
});
}
},
}
);
});

View File

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

View File

@ -55,3 +55,10 @@
}
}
}
.o_group {
.mr-2,
.mx-2 {
margin-left: 0.5rem !important;
}
}

View File

@ -1,24 +1,47 @@
<?xml version="1.0" encoding="UTF-8" ?>
<templates>
<t t-extend="mail.Attachment">
<t t-jquery=".o_attachment_download" t-operation="after">
<span
t-if="!attachment.callback and attachment.url"
class="fa fa-search ml4 o_attachment_preview"
t-att-data-id="attachment.id"
t-att-data-url="attachment.url"
t-attf-title="Preview #{attachment.name} in side panel"
/>
<span
t-if="!attachment.callback and attachment.url"
class="fa fa-external-link ml4 o_attachment_preview o_attachment_preview_new_tab"
data-target="new"
t-att-data-id="attachment.id"
t-att-data-url="attachment.url"
t-attf-title="Open preview #{attachment.name} in a new tab"
/>
</t>
<t
t-name="Attachment"
t-inherit="mail.AttachmentCard"
t-inherit-mode="extension"
owl="1"
>
<xpath expr="//div[hasclass('o_AttachmentCard_aside')]" position="before">
<div
class="o_AttachmentCard_aside position-relative overflow-hidden"
t-att-class="{ 'o-has-multiple-action d-flex flex-column': !attachmentCard.attachmentList.composerView and attachmentCard.attachment.isEditable }"
>
<div
t-if="attachmentCard.attachment.downloadUrl"
class="o_AttachmentCard_asideItem d-flex justify-content-center align-items-center ml4 o_attachment_preview"
t-att-data-id="attachmentCard.attachment.id"
t-att-data-url="attachmentCard.attachment.defaultSource"
t-on-click="attachmentCard._onPreviewAttachment"
t-att-data-original-title="attachmentCard.attachment.name"
t-attf-title="Preview {{attachmentCard.attachment.displayName}} in side panel"
tabindex="0"
role="menuitem"
aria-label="Preview"
>
<i class="fa fa-search" />
</div>
<div
t-if="attachmentCard.attachment.downloadUrl"
class="o_AttachmentCard_asideItem d-flex justify-content-center align-items-center ml4 o_attachment_preview o_attachment_preview_new_tab"
data-target="new"
t-att-data-id="attachmentCard.attachment.id"
t-att-data-url="attachmentCard.attachment.defaultSource"
t-on-click="attachmentCard._onPreviewAttachment"
t-att-data-original-title="attachmentCard.attachment.name"
t-attf-title="Open preview {{attachmentCard.attachment.name}} in a new tab"
tabindex="0"
role="menuitem"
aria-label="Open in new page"
>
<i class="fa fa-external-link" />
</div>
</div>
</xpath>
</t>
<t t-name="attachment_preview.AttachmentPreviewWidget">
@ -38,7 +61,6 @@
<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>

View File

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<template
id="assets_backend"
name="attachment_preview assets"
inherit_id="web.assets_backend"
>
<xpath expr="." position="inside">
<script
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>
</template>
</odoo>

View File

@ -12,14 +12,12 @@ class TestAttachmentPreview(TransactionCase):
{
"datas": base64.b64encode(b"from this, to that."),
"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)