Merge pull request #40 from StefanRijnhart/6.1-attachment_file_type_therp

6.1 attachment file type
This commit is contained in:
Pedro M. Baeza 2015-03-02 13:00:04 +01:00
commit 068b45384f
6 changed files with 200 additions and 0 deletions

View File

@ -10,6 +10,7 @@ virtualenv:
system_site_packages: true
install:
- pip install python-magic
- git clone https://github.com/OCA/maintainer-quality-tools.git ${HOME}/maintainer-quality-tools
- export PATH=${HOME}/maintainer-quality-tools/travis:${PATH}
- travis_install_nightly ${VERSION}

View File

@ -0,0 +1 @@
from . import models

View File

@ -0,0 +1,79 @@
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name": "File types for attachments",
"version": "1.0",
"author": "Therp BV",
"license": "AGPL-3",
"description": """
File types for attachments
==========================
Adds a content type to attachments. This is useful for instance in combination
with http://bazaar.launchpad.net/~ocb/ocb-web/6.1/revision/2524, which makes
Odoo offer downloads with the correct file type based on this field.
The document module makes this field available as well. This module does not
interfere with its functionality when both are installed.
Installation
============
To install this module, you need to install python-magic in your environment
first.
Configuration
=============
This module comes with a daily scheduled task to provide content types for
attachments without one in small batches (instead of trying to do this for all
attachments at installation time). Depending on the number of attachments in
your system you may deactivate this task after some time. You can follow the
progress in the logs at the time that the cron job is fired.
Credits
=======
Contributors
------------
* Stefan Rijnhart <stefan@therp.nl>
* Holger Brunn <hbrunn@therp.nl>
Maintainer
----------
.. image:: http://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: http://odoo-community.org
This module is maintained by the OCA.
OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.
To contribute to this module, please visit http://odoo-community.org.
""",
"category": "Knowledge Management",
"depends": ['base'],
"data": ['data/ir_cron.xml'],
"license": 'AGPL-3',
"external_dependencies": {
'python': ['magic'],
},
}

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data noupdate="1">
<record id="cron_update_file_type" model="ir.cron">
<field name="name">Provide file types for attachments without one</field>
<field name="interval_number">24</field>
<field name="interval_type">hours</field>
<field name="numbercall">-1</field>
<field name="active">True</field>
<field name="doall" eval="False" />
<field name="model">ir.attachment</field>
<field name="function">update_file_type_from_cron</field>
<field name="args">(10000,)</field>
</record>
</data>
</openerp>

View File

@ -0,0 +1 @@
from . import ir_attachment

View File

@ -0,0 +1,100 @@
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import logging
from openerp.osv import orm, fields
from base64 import b64decode
class Attachment(orm.Model):
_inherit = 'ir.attachment'
def update_file_type_from_cron(self, cr, uid, count=10000, context=None):
ids = self.search(
cr, uid, [('file_type', '=', False)], context=context)
logging.getLogger('openerp.addons.attachment_file_type').info(
'Found %s attachments without file type in the database.',
len(ids))
if ids:
logging.getLogger('openerp.addons.attachment_file_type').info(
'Providing file types for a maximum of %s of them',
count)
return self.update_file_type(
cr, uid, ids[:count], force=True, context=None)
return False
def update_file_type(self, cr, uid, ids, force=False, context=None):
""" Write the file types for these attachments. If the document module
is installed, don't do anything unless in force mode. """
if not ids:
return True
if not force:
cr.execute(
"SELECT id from ir_module_module WHERE name = 'document' "
"AND state = 'installed'")
if cr.fetchone():
return True
if isinstance(ids, (int, long)):
ids = [ids]
logger = logging.getLogger('openerp.addons.attachment_file_type')
import magic
ms = magic.open(
# MAGIC_MIME gives additional encoding, but old versions of the
# 'file' package come with py_magic.c that lack MAGIC_MIME_TYPE
magic.MAGIC_MIME_TYPE if hasattr(magic, 'MAGIC_MIME_TYPE')
else magic.MAGIC_MIME)
ms.load()
for attachment_id in ids:
attachment = self.browse(cr, uid, attachment_id, context=context)
if not attachment.datas:
continue
file_type = ms.buffer(
b64decode(attachment.datas)).split(';')[0]
logger.debug(
'Found file type %s for attachment with id %s',
file_type, attachment.id)
# Use SQL, not ORM, to prevent write triggers which are harmful
# in 6.1 on attachments of which the model or the record no longer
# exists
cr.execute(
"UPDATE ir_attachment SET file_type = %s WHERE id = %s",
(file_type, attachment_id))
return True
def write(self, cr, uid, ids, vals, context=None):
""" Update the mime type when the contents are overwritten """
res = super(Attachment, self).write(
cr, uid, ids, vals, context=context)
if vals.get('datas'):
self.update_file_type(cr, uid, ids, context=context)
return res
def create(self, cr, uid, vals, context=None):
""" Determine the mime type when the attachment is created """
res_id = super(Attachment, self).create(
cr, uid, vals, context=context)
if vals.get('datas'):
self.update_file_type(cr, uid, [res_id], context=context)
return res_id
_columns = {
'file_type': fields.char('Content Type', size=128),
}