[IMP] project_long_term: improve gantt view
[odoo/odoo.git] / addons / document / document.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import base64
23 from osv import osv, fields
24 import os
25
26 # from psycopg2 import Binary
27 #from tools import config
28 import tools
29 from tools.translate import _
30 import nodes
31
32 DMS_ROOT_PATH = tools.config.get('document_path', os.path.join(tools.config['root_path'], 'filestore'))
33
34 class document_file(osv.osv):
35     _inherit = 'ir.attachment'
36     _rec_name = 'datas_fname'
37     def _get_filestore(self, cr):
38         return os.path.join(DMS_ROOT_PATH, cr.dbname)
39
40     def _data_get(self, cr, uid, ids, name, arg, context):
41         fbrl = self.browse(cr, uid, ids, context=context)
42         nctx = nodes.get_node_context(cr, uid, context={})
43         # nctx will /not/ inherit the caller's context. Most of
44         # it would be useless, anyway (like active_id, active_model,
45         # bin_size etc.)
46         result = {}
47         bin_size = context.get('bin_size', False)
48         for fbro in fbrl:
49             fnode = nodes.node_file(None, None, nctx, fbro)
50             if not bin_size:
51                     data = fnode.get_data(cr, fbro)
52                     result[fbro.id] = base64.encodestring(data or '')
53             else:
54                     result[fbro.id] = fnode.get_data_len(cr, fbro)
55
56         return result
57
58     #
59     # This code can be improved
60     #
61     def _data_set(self, cr, uid, id, name, value, arg, context):
62         if not value:
63             return True
64         fbro = self.browse(cr, uid, id, context=context)
65         nctx = nodes.get_node_context(cr, uid, context={})
66         fnode = nodes.node_file(None, None, nctx, fbro)
67         res = fnode.set_data(cr, base64.decodestring(value), fbro)
68         return res
69
70     _columns = {
71         # Columns from ir.attachment:
72         'create_date': fields.datetime('Date Created', readonly=True),
73         'create_uid':  fields.many2one('res.users', 'Creator', readonly=True),
74         'write_date': fields.datetime('Date Modified', readonly=True),
75         'write_uid':  fields.many2one('res.users', 'Last Modification User', readonly=True),
76         'res_model': fields.char('Attached Model', size=64, readonly=True),
77         'res_id': fields.integer('Attached ID', readonly=True),
78
79         # If ir.attachment contained any data before document is installed, preserve
80         # the data, don't drop the column!
81         'db_datas': fields.binary('Data', oldname='datas'),
82         'datas': fields.function(_data_get, method=True, fnct_inv=_data_set, string='File Content', type="binary", nodrop=True),
83
84         # Fields of document:
85         'user_id': fields.many2one('res.users', 'Owner', select=1),
86         # 'group_ids': fields.many2many('res.groups', 'document_group_rel', 'item_id', 'group_id', 'Groups'),
87         # the directory id now is mandatory. It can still be computed automatically.
88         'parent_id': fields.many2one('document.directory', 'Directory', select=1, required=True),
89         'index_content': fields.text('Indexed Content'),
90         'partner_id':fields.many2one('res.partner', 'Partner', select=1),
91         'file_size': fields.integer('File Size', required=True),
92         'file_type': fields.char('Content Type', size=128),
93
94         # fields used for file storage
95         'store_fname': fields.char('Stored Filename', size=200),
96     }
97     _order = "create_date desc"
98
99     def __get_def_directory(self, cr, uid, context=None):
100         dirobj = self.pool.get('document.directory')
101         return dirobj._get_root_directory(cr, uid, context)
102
103     _defaults = {
104         'user_id': lambda self, cr, uid, ctx:uid,
105         'file_size': lambda self, cr, uid, ctx:0,
106         'parent_id': __get_def_directory
107     }
108     _sql_constraints = [
109         ('filename_uniq', 'unique (name,parent_id,res_id,res_model)', 'The file name must be unique !')
110     ]
111     def _check_duplication(self, cr, uid, vals, ids=[], op='create'):
112         name = vals.get('name', False)
113         parent_id = vals.get('parent_id', False)
114         res_model = vals.get('res_model', False)
115         res_id = vals.get('res_id', 0)
116         if op == 'write':
117             for file in self.browse(cr, uid, ids): # FIXME fields_only
118                 if not name:
119                     name = file.name
120                 if not parent_id:
121                     parent_id = file.parent_id and file.parent_id.id or False
122                 if not res_model:
123                     res_model = file.res_model and file.res_model or False
124                 if not res_id:
125                     res_id = file.res_id and file.res_id or 0
126                 res = self.search(cr, uid, [('id', '<>', file.id), ('name', '=', name), ('parent_id', '=', parent_id), ('res_model', '=', res_model), ('res_id', '=', res_id)])
127                 if len(res):
128                     return False
129         if op == 'create':
130             res = self.search(cr, uid, [('name', '=', name), ('parent_id', '=', parent_id), ('res_id', '=', res_id), ('res_model', '=', res_model)])
131             if len(res):
132                 return False
133         return True
134
135     def copy(self, cr, uid, id, default=None, context=None):
136         if not default:
137             default = {}
138         if 'name' not in default:
139             name = self.read(cr, uid, [id])[0]['name']
140             default.update({'name': name + " (copy)"})
141         return super(document_file, self).copy(cr, uid, id, default, context)
142
143     def write(self, cr, uid, ids, vals, context=None):
144         result = False
145         if not isinstance(ids, list):
146             ids = [ids]
147         res = self.search(cr, uid, [('id', 'in', ids)])
148         if not len(res):
149             return False
150         if not self._check_duplication(cr, uid, vals, ids, 'write'):
151             raise osv.except_osv(_('ValidateError'), _('File name must be unique!'))
152
153         # if nodes call this write(), they must skip the code below
154         from_node = context and context.get('__from_node', False)
155         if (('parent_id' in vals) or ('name' in vals)) and not from_node:
156             # perhaps this file is renaming or changing directory
157             nctx = nodes.get_node_context(cr,uid,context={})
158             dirobj = self.pool.get('document.directory')
159             if 'parent_id' in vals:
160                 dbro = dirobj.browse(cr, uid, vals['parent_id'], context=context)
161                 dnode = nctx.get_dir_node(cr, dbro)
162             else:
163                 dbro = None
164                 dnode = None
165             ids2 = []
166             for fbro in self.browse(cr, uid, ids, context=context):
167                 if ('parent_id' not in vals or fbro.parent_id.id == vals['parent_id']) \
168                     and ('name' not in vals or fbro.name == vals['name']) :
169                         ids2.append(fbro.id)
170                         continue
171                 fnode = nctx.get_file_node(cr, fbro)
172                 res = fnode.move_to(cr, dnode or fnode.parent, vals.get('name', fbro.name), fbro, dbro, True)
173                 if isinstance(res, dict):
174                     vals2 = vals.copy()
175                     vals2.update(res)
176                     wid = res.get('id', fbro.id)
177                     result = super(document_file,self).write(cr,uid,wid,vals2,context=context)
178                     # TODO: how to handle/merge several results?
179                 elif res == True:
180                     ids2.append(fbro.id)
181                 elif res == False:
182                     pass
183             ids = ids2
184         if 'file_size' in vals: # only write that field using direct SQL calls
185             del vals['file_size']
186         if len(ids) and len(vals):
187             result = super(document_file,self).write(cr, uid, ids, vals, context=context)
188         cr.commit() # ?
189         return result
190
191     def create(self, cr, uid, vals, context=None):
192         if context is None:
193             context = {}
194         vals['parent_id'] = context.get('parent_id', False) or vals.get('parent_id', False)
195         if not vals['parent_id']:
196             vals['parent_id'] = self.pool.get('document.directory')._get_root_directory(cr,uid, context)
197         if not vals.get('res_id', False) and context.get('default_res_id', False):
198             vals['res_id'] = context.get('default_res_id', False)
199         if not vals.get('res_model', False) and context.get('default_res_model', False):
200             vals['res_model'] = context.get('default_res_model', False)
201         if vals.get('res_id', False) and vals.get('res_model', False) \
202                 and not vals.get('partner_id', False):
203             vals['partner_id'] = self.__get_partner_id(cr, uid, \
204                 vals['res_model'], vals['res_id'], context)
205
206         datas = None
207         if vals.get('link', False) :
208             import urllib
209             datas = base64.encodestring(urllib.urlopen(vals['link']).read())
210         else:
211             datas = vals.get('datas', False)
212
213         if datas:
214             vals['file_size'] = len(datas)
215         else:
216             if vals.get('file_size'):
217                 del vals['file_size']
218         if not self._check_duplication(cr, uid, vals):
219             raise osv.except_osv(_('ValidateError'), _('File name must be unique!'))
220         result = super(document_file, self).create(cr, uid, vals, context)
221         cr.commit() # ?
222         return result
223
224     def __get_partner_id(self, cr, uid, res_model, res_id, context):
225         """ A helper to retrieve the associated partner from any res_model+id
226             It is a hack that will try to discover if the mentioned record is
227             clearly associated with a partner record.
228         """
229         obj_model = self.pool.get(res_model)
230         if obj_model._name == 'res.partner':
231             return res_id
232         elif 'partner_id' in obj_model._columns and obj_model._columns['partner_id']._obj == 'res.partner':
233             bro = obj_model.browse(cr, uid, res_id, context=context)
234             return bro.partner_id.id
235         elif 'address_id' in obj_model._columns and obj_model._columns['address_id']._obj == 'res.partner.address':
236             bro = obj_model.browse(cr, uid, res_id, context=context)
237             return bro.address_id.partner_id.id
238         return False
239
240     def unlink(self, cr, uid, ids, context=None):
241         stor = self.pool.get('document.storage')
242         unres = []
243         # We have to do the unlink in 2 stages: prepare a list of actual
244         # files to be unlinked, update the db (safer to do first, can be
245         # rolled back) and then unlink the files. The list wouldn't exist
246         # after we discard the objects
247
248         for f in self.browse(cr, uid, ids, context):
249             # TODO: update the node cache
250             par = f.parent_id
251             storage_id = None
252             while par:
253                 if par.storage_id:
254                     storage_id = par.storage_id
255                     break
256                 par = par.parent_id
257             #assert storage_id, "Strange, found file #%s w/o storage!" % f.id #TOCHECK: after run yml, it's fail
258             if storage_id:
259                 r = stor.prepare_unlink(cr, uid, storage_id, f)
260                 if r:
261                     unres.append(r)
262         res = super(document_file, self).unlink(cr, uid, ids, context)
263         stor.do_unlink(cr, uid, unres)
264         return res
265
266 document_file()
267