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