~openerp-commiter/openobject-addons/trunk-extra-addons

« back to all changes in this revision

Viewing changes to product_images_olbs/product.py

  • Committer: Cubic ERP
  • Date: 2012-11-28 00:54:54 UTC
  • mfrom: (5823.1.19 openobject-addons)
  • Revision ID: info@cubicerp.com-20121128005454-bbtsmufafj4hwady
[UPG]

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- encoding: utf-8 -*-
2
 
#########################################################################
3
 
# Copyright (C) 2009  Sharoon Thomas, Open Labs Business solutions      #
4
 
# Copyright (C) 2011 Akretion Sébastien BEAU sebastien.beau@akretion.com#
5
 
#                                                                       #
6
 
#This program is free software: you can redistribute it and/or modify   #
7
 
#it under the terms of the GNU General Public License as published by   #
8
 
#the Free Software Foundation, either version 3 of the License, or      #
9
 
#(at your option) any later version.                                    #
10
 
#                                                                       #
11
 
#This program is distributed in the hope that it will be useful,        #
12
 
#but WITHOUT ANY WARRANTY; without even the implied warranty of         #
13
 
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          #
14
 
#GNU General Public License for more details.                           #
15
 
#                                                                       #
16
 
#You should have received a copy of the GNU General Public License      #
17
 
#along with this program.  If not, see <http://www.gnu.org/licenses/>.  #
18
 
#########################################################################
19
 
import os
20
 
import shutil
21
 
import logging
22
 
import unicodedata
23
 
import base64, urllib
24
 
 
25
 
from osv import osv,fields
26
 
from tools.translate import _
27
 
 
28
 
class product_product(osv.osv):
29
 
    _inherit = "product.product"
30
 
 
31
 
    def copy(self, cr, uid, id, default=None, context=None):
32
 
        if not default:
33
 
            default = {}
34
 
        original = self.read(cr, uid, id, fields=['default_code', 'image_ids'], context=context)
35
 
        default.update({
36
 
            'default_code': original['default_code'] + '.copy',
37
 
            'images_ids': False,
38
 
        })
39
 
        local_media_repository = self.pool.get('res.company').get_local_media_repository(cr, uid, context=context)
40
 
        if local_media_repository:
41
 
            if original['image_ids']:
42
 
                old_path = os.path.join(local_media_repository, original['default_code'])
43
 
                if os.path.isdir(old_path):
44
 
                    try:
45
 
                        shutil.copytree(old_path, old_path+'.copy')
46
 
                    except:
47
 
                        logger = logging.getLogger('product_images_olbs')
48
 
                        logger.exception('error while trying to copy images from %s to %s', old_path, old_path+'.copy')
49
 
 
50
 
        return super(product_product, self).copy(cr, uid, id, default, context=context)
51
 
 
52
 
    def get_main_image(self, cr, uid, id, context=None):
53
 
        if isinstance(id, list):
54
 
            id = id[0]
55
 
        images_ids = self.read(cr, uid, id, ['image_ids'], context=context)['image_ids']
56
 
        if images_ids:
57
 
            return images_ids[0]
58
 
        return False
59
 
 
60
 
    def _get_main_image(self, cr, uid, ids, field_name, arg, context=None):
61
 
        res = {}
62
 
        img_obj = self.pool.get('product.images')
63
 
        for id in ids:
64
 
            image_id = self.get_main_image(cr, uid, id, context=context)
65
 
            if image_id:
66
 
                image = img_obj.browse(cr, uid, image_id, context=context)
67
 
                res[id] = image.file
68
 
            else:
69
 
                res[id] = False
70
 
        return res
71
 
 
72
 
    _columns = {
73
 
        'image_ids':fields.one2many(
74
 
                'product.images',
75
 
                'product_id',
76
 
                'Product Images'
77
 
        ),
78
 
        'default_code': fields.char('Reference', size=64, require='True'),
79
 
        'product_image': fields.function(_get_main_image, type="binary", method=True),
80
 
    }
81
 
 
82
 
    def write(self, cr, uid, ids, vals, context=None):
83
 
        if isinstance(ids, (int, long)):
84
 
            ids = [ids]
85
 
        # here we expect that the write on default_code is always on 1 product because there is an unique constraint on the default code
86
 
        if vals.get('default_code', False) and ids:
87
 
            local_media_repository = self.pool.get('res.company').get_local_media_repository(cr, uid, context=context)
88
 
            if local_media_repository:
89
 
                old_product = self.read(cr, uid, ids[0], ['default_code', 'image_ids'], context=context)
90
 
                res = super(product_product, self).write(cr, uid, ids, vals, context=context)
91
 
                if old_product['image_ids']:
92
 
                    if old_product['default_code'] != vals['default_code']:
93
 
                        old_path = os.path.join(local_media_repository, old_product['default_code'])
94
 
                        new_path = os.path.join(local_media_repository, vals['default_code'])
95
 
                        if os.path.isdir(old_path):
96
 
                            if not os.path.isdir(os.path.dirname(new_path)):
97
 
                                os.makedirs(os.path.dirname(new_path))
98
 
                            if os.path.isdir(new_path):
99
 
                                shutil.rmtree(new_path)
100
 
                            shutil.copytree(old_path, new_path)
101
 
                            shutil.rmtree(old_path)
102
 
                return res
103
 
        return super(product_product, self).write(cr, uid, ids, vals, context=context)
104
 
 
105
 
    #This constraint should be by default in openerp
106
 
    _sql_constraints = [('default_code', 'UNIQUE(default_code)',
107
 
                _('Default code should be uniq'))]
108
 
 
109
 
    def create_image_from_url(self, cr, uid, id, url, image_name=None, context=None):
110
 
        (filename, header) = urllib.urlretrieve(url)
111
 
        f = open(filename , 'rb')
112
 
        data = f.read()
113
 
        f.close()
114
 
        img = base64.encodestring(data)
115
 
        filename, extention = os.path.splitext(os.path.basename(url))
116
 
        data = {'name': image_name or filename,
117
 
            'extention': extention,
118
 
            'file': img,
119
 
            'product_id': id,
120
 
            }
121
 
        new_image_id = self.pool.get('product.images').create(cr, uid, data, context=context)
122
 
        return True
123
 
 
124
 
 
125
 
product_product()