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