[MERGE]
[odoo/odoo.git] / addons / document / document_directory.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
24 from osv import osv, fields
25 from osv.orm import except_orm
26 import urlparse
27
28 import os
29 import nodes
30 from tools.translate import _
31
32 class document_directory(osv.osv):
33     _name = 'document.directory'
34     _description = 'Document directory'
35     _order = 'name desc'
36     _columns = {
37         'name': fields.char('Name', size=64, required=True, select=1),
38         'write_date': fields.datetime('Date Modified', readonly=True),
39         'write_uid':  fields.many2one('res.users', 'Last Modification User', readonly=True),
40         'create_date': fields.datetime('Date Created', readonly=True),
41         'create_uid':  fields.many2one('res.users', 'Creator', readonly=True),
42         'file_type': fields.char('Content Type', size=32),
43         'domain': fields.char('Domain', size=128, help="Use a domain if you want to apply an automatic filter on visible resources."),
44         'user_id': fields.many2one('res.users', 'Owner'),
45         'storage_id': fields.many2one('document.storage', 'Storage'),
46         'group_ids': fields.many2many('res.groups', 'document_directory_group_rel', 'item_id', 'group_id', 'Groups'),
47         'parent_id': fields.many2one('document.directory', 'Parent Item'),
48         'child_ids': fields.one2many('document.directory', 'parent_id', 'Children'),
49         'file_ids': fields.one2many('ir.attachment', 'parent_id', 'Files'),
50         'content_ids': fields.one2many('document.directory.content', 'directory_id', 'Virtual Files'),
51         'type': fields.selection([('directory','Static Directory'),('ressource','Other Resources')], 'Type', required=True),
52         'ressource_type_id': fields.many2one('ir.model', 'Directories Mapped to Objects',
53             help="Select an object here and Open ERP will create a mapping for each of these " \
54                  "objects, using the given domain, when browsing through FTP."),
55         'resource_field': fields.many2one('ir.model.fields', 'Name field', help='Field to be used as name on resource directories. If empty, the "name" will be used.'),
56         'ressource_parent_type_id': fields.many2one('ir.model', 'Parent Model',
57             help="If you put an object here, this directory template will appear bellow all of these objects. " \
58                  "Don't put a parent directory if you select a parent model."),
59         'ressource_id': fields.integer('Resource ID'),
60         'ressource_tree': fields.boolean('Tree Structure',
61             help="Check this if you want to use the same tree structure as the object selected in the system."),
62         'dctx_ids': fields.one2many('document.directory.dctx', 'dir_id', 'Context fields'),
63     }
64
65
66     def _get_root_directory(self, cr,uid, context=None):
67         objid=self.pool.get('ir.model.data')
68         try:
69             mid = objid._get_id(cr, uid, 'document', 'dir_root')
70             if not mid:
71                 return False
72             root_id = objid.read(cr, uid, mid, ['res_id'])['res_id']
73             return root_id
74         except Exception, e:
75             import netsvc
76             logger = netsvc.Logger()
77             logger.notifyChannel("document", netsvc.LOG_WARNING, 'Cannot set directory root:'+ str(e))
78             return False
79         return objid.browse(cr, uid, mid, context=context).res_id
80
81     def _get_def_storage(self,cr,uid,context=None):
82         if context and context.has_key('default_parent_id'):
83                 # Use the same storage as the parent..
84                 diro = self.browse(cr,uid,context['default_parent_id'])
85                 if diro.storage_id:
86                         return diro.storage_id.id
87         objid=self.pool.get('ir.model.data')
88         try:
89                 mid =  objid._get_id(cr, uid, 'document', 'storage_default')
90                 return objid.browse(cr, uid, mid, context=context).res_id
91         except Exception:
92                 return None
93         
94     _defaults = {
95         'user_id': lambda self,cr,uid,ctx: uid,
96         'domain': lambda self,cr,uid,ctx: '[]',
97         'type': lambda *args: 'directory',
98         'ressource_id': lambda *a: 0,        
99         'storage_id': _get_def_storage,
100     }
101     _sql_constraints = [
102         ('dirname_uniq', 'unique (name,parent_id,ressource_id,ressource_parent_type_id)', 'The directory name must be unique !'),
103         ('no_selfparent', 'check(parent_id <> id)', 'Directory cannot be parent of itself!')
104     ]
105     def name_get(self, cr, uid, ids, context={}):
106         res = []
107         all_ids = self.search(cr,uid,[])
108         for d in self.browse(cr, uid, ids, context=context):
109             if d.id not in all_ids:
110                 continue
111
112             s = ''
113             d2 = d
114             while d2 and d2.parent_id:
115                 s = d2.name + (s and ('/' + s) or '')
116                 d2 = d2.parent_id
117             res.append((d.id, s))
118         return res
119
120     def get_full_path(self, cr, uid, dir_id, context=None):
121         """ Return the full path to this directory, in a list, root first
122         """
123         def _parent(dir_id, path):
124             parent=self.browse(cr,uid,dir_id)
125             if parent.parent_id and not parent.ressource_parent_type_id:
126                 _parent(parent.parent_id.id,path)
127                 path.append(parent.name)
128             else:
129                 path.append(parent.name)
130                 return path
131         path = []
132         _parent(dir_id, path)
133         return path
134
135     def ol_get_resource_path(self,cr,uid,dir_id,res_model,res_id):
136         # this method will be used in process module
137         # to be need test and Improvement if resource dir has parent resource (link resource)
138         path=[]
139         def _parent(dir_id,path):
140             parent=self.browse(cr,uid,dir_id)
141             if parent.parent_id and not parent.ressource_parent_type_id:
142                 _parent(parent.parent_id.id,path)
143                 path.append(parent.name)
144             else:
145                 path.append(parent.name)
146                 return path
147
148         directory=self.browse(cr,uid,dir_id)
149         model_ids=self.pool.get('ir.model').search(cr,uid,[('model','=',res_model)])
150         if directory:
151             _parent(dir_id,path)
152             path.append(self.pool.get(directory.ressource_type_id.model).browse(cr,uid,res_id).name)
153             #user=self.pool.get('res.users').browse(cr,uid,uid)
154             #return "ftp://%s:%s@localhost:%s/%s/%s"%(user.login,user.password,config.get('ftp_server_port',8021),cr.dbname,'/'.join(path))
155             # No way we will return the password!
156             return "ftp://user:pass@host:port/test/this"
157         return False
158
159     def _check_recursion(self, cr, uid, ids):
160         level = 100
161         while len(ids):
162             cr.execute('select distinct parent_id from document_directory where id in ('+','.join(map(str,ids))+')')
163             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
164             if not level:
165                 return False
166             level -= 1
167         return True
168
169     _constraints = [
170         (_check_recursion, 'Error! You can not create recursive Directories.', ['parent_id'])
171     ]
172     def __init__(self, *args, **kwargs):
173         res = super(document_directory, self).__init__(*args, **kwargs)
174         #self._cache = {}
175
176     def onchange_content_id(self, cr, uid, ids, ressource_type_id):
177         return {}
178
179     """
180         PRE:
181             uri: of the form "Sales Order/SO001"
182         PORT:
183             uri
184             object: the object.directory or object.directory.content
185             object2: the other object linked (if object.directory.content)
186     """
187     def get_object(self, cr, uid, uri, context=None):
188         """ Return a node object for the given uri.
189            This fn merely passes the call to node_context
190         """
191         if not context:
192                 context = {}
193         lang = context.get('lang',False)
194         if not lang:
195             user = self.pool.get('res.users').browse(cr, uid, uid)
196             lang = user.context_lang 
197             context['lang'] = lang
198             
199         try: #just instrumentation
200                 return nodes.get_node_context(cr, uid, context).get_uri(cr,uri)
201         except Exception,e:
202                 print "exception: ",e
203                 raise
204
205
206     def _locate_child(self, cr, uid, root_id, uri,nparent, ncontext):
207         """ try to locate the node in uri,
208             Return a tuple (node_dir, remaining_path)
209         """
210         return (nodes.node_database(context=ncontext), uri)         
211         
212     def old_code():
213         if not uri:
214             return node_database(cr, uid, context=context)
215         turi = tuple(uri)
216         node = node_class(cr, uid, '/', False, context=context, type='database')
217         for path in uri[:]:
218             if path:
219                 node = node.child(path)
220                 if not node:
221                     return False
222         oo = node.object and (node.object._name, node.object.id) or False
223         oo2 = node.object2 and (node.object2._name, node.object2.id) or False
224         return node
225
226     def ol_get_childs(self, cr, uid, uri, context={}):
227         node = self.get_object(cr, uid, uri, context)
228         if uri:
229             children = node.children()
230         else:
231             children= [node]
232         result = map(lambda node: node.path_get(), children)
233         return result
234
235     def copy(self, cr, uid, id, default=None, context=None):
236         if not default:
237             default ={}
238         name = self.read(cr, uid, [id])[0]['name']
239         default.update({'name': name+ " (copy)"})
240         return super(document_directory,self).copy(cr,uid,id,default,context)
241
242     def _check_duplication(self, cr, uid,vals,ids=[],op='create'):
243         name=vals.get('name',False)
244         parent_id=vals.get('parent_id',False)
245         ressource_parent_type_id=vals.get('ressource_parent_type_id',False)
246         ressource_id=vals.get('ressource_id',0)
247         if op=='write':
248             for directory in self.browse(cr,uid,ids):
249                 if not name:
250                     name=directory.name
251                 if not parent_id:
252                     parent_id=directory.parent_id and directory.parent_id.id or False
253                 if not ressource_parent_type_id:
254                     ressource_parent_type_id=directory.ressource_parent_type_id and directory.ressource_parent_type_id.id or False
255                 if not ressource_id:
256                     ressource_id=directory.ressource_id and directory.ressource_id or 0
257                 res=self.search(cr,uid,[('id','<>',directory.id),('name','=',name),('parent_id','=',parent_id),('ressource_parent_type_id','=',ressource_parent_type_id),('ressource_id','=',ressource_id)])
258                 if len(res):
259                     return False
260         if op=='create':
261             res=self.search(cr,uid,[('name','=',name),('parent_id','=',parent_id),('ressource_parent_type_id','=',ressource_parent_type_id),('ressource_id','=',ressource_id)])
262             if len(res):
263                 return False
264         return True
265     def write(self, cr, uid, ids, vals, context=None):
266         if not self._check_duplication(cr,uid,vals,ids,op='write'):
267             raise osv.except_osv(_('ValidateError'), _('Directory name must be unique!'))
268         return super(document_directory,self).write(cr,uid,ids,vals,context=context)
269
270     def create(self, cr, uid, vals, context=None):
271         if not self._check_duplication(cr,uid,vals):
272             raise osv.except_osv(_('ValidateError'), _('Directory name must be unique!'))
273         if vals.get('name',False) and (vals.get('name').find('/')+1 or vals.get('name').find('@')+1 or vals.get('name').find('$')+1 or vals.get('name').find('#')+1) :
274             raise osv.except_osv(_('ValidateError'), _('Directory name contains special characters!'))
275         return super(document_directory,self).create(cr, uid, vals, context)
276
277 document_directory()
278
279 class document_directory_dctx(osv.osv):
280     """ In order to evaluate dynamic folders, child items could have a limiting
281         domain expression. For that, their parents will export a context where useful
282         information will be passed on.
283         If you define sth like "s_id" = "this.id" at a folder iterating over sales, its
284         children could have a domain like [('sale_id', = ,dctx_s_id )]
285         This system should be used recursively, that is, parent dynamic context will be
286         appended to all children down the tree.
287     """
288     _name = 'document.directory.dctx'
289     _description = 'Directory dynamic context'
290     _columns = {
291         'dir_id': fields.many2one('document.directory', 'Directory', required=True),
292         'field': fields.char('Field', size=20, required=True, select=1, help="The name of the field. Note that the prefix \"dctx_\" will be prepended to what is typed here."),
293         'expr': fields.char('Expression', size=64, required=True, help="A python expression used to evaluate the field.\n" + \
294                 "You can use 'dir_id' for current dir, 'res_id', 'res_model' as a reference to the current record, in dynamic folders"),
295         }
296
297 document_directory_dctx()
298
299
300 class document_directory_node(osv.osv):
301     _inherit = 'process.node'
302     _columns = {
303         'directory_id':  fields.many2one('document.directory', 'Document directory', ondelete="set null"),
304     }
305 document_directory_node()