1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
23 from document import document as nodes
24 from openerp.tools.safe_eval import safe_eval as eval
28 from openerp import SUPERUSER_ID
30 def dict_filter(srcdic, keys, res=None):
31 ''' Return a copy of srcdic that has only keys set.
32 If any of keys are missing from srcdic, the result won't have them,
34 @param res If given, result will be updated there, instead of a new dict.
43 class node_acl_mixin(object):
44 def _get_dav_owner(self, cr):
47 def _get_dav_group(self, cr):
50 def _get_dav_supported_privilege_set(self, cr):
53 def _get_dav_current_user_privilege_set(self, cr):
56 def _get_dav_props_hlpr(self, cr, par_class, prop_model,
57 prop_ref_field, res_id):
58 """ Helper for dav properties, usable in subclasses
60 @param par_class The parent class
61 @param prop_model The name of the orm model holding the properties
62 @param prop_ref_field The name of the field at prop_model pointing to us
63 @param res_id the id of self in the corresponing orm table, that should
64 match prop_model.prop_ref_field
66 ret = par_class.get_dav_props(self, cr)
68 propobj = self.context._dirobj.pool.get(prop_model)
69 uid = self.context.uid
70 ctx = self.context.context.copy()
72 # Not really needed because we don't do eval here:
73 # ctx.update({'uid': uid, 'dbname': self.context.dbname })
74 # dict_filter(self.context.extra_ctx, ['username', 'groupname', 'webdav_path'], ctx)
75 sdomain = [(prop_ref_field, '=', False),]
77 sdomain = ['|', (prop_ref_field, '=', res_id)] + sdomain
78 prop_ids = propobj.search(cr, uid, sdomain, context=ctx)
81 for pbro in propobj.browse(cr, uid, prop_ids, context=ctx):
82 ret[pbro.namespace] = ret.get(pbro.namespace, ()) + \
84 # Note that we cannot have properties to conditionally appear
85 # on the context, yet.
89 def _get_dav_eprop_hlpr(self, cr, ns, prop,
90 par_class, prop_model,
91 prop_ref_field, res_id):
92 """ Helper for get dav eprop, usable in subclasses
94 @param namespace the one to search for
95 @param name Name to search for
96 @param par_class The parent class
97 @param prop_model The name of the orm model holding the properties
98 @param prop_ref_field The name of the field at prop_model pointing to us
99 @param res_id the id of self in the corresponing orm table, that should
100 match prop_model.prop_ref_field
102 ret = par_class.get_dav_eprop(self, cr, ns, prop)
106 propobj = self.context._dirobj.pool.get(prop_model)
107 uid = self.context.uid
108 ctx = self.context.context.copy()
109 ctx.update(self.dctx)
110 ctx.update({'uid': uid, 'dbname': self.context.dbname })
111 ctx['node_classname'] = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
112 dict_filter(self.context.extra_ctx, ['username', 'groupname', 'webdav_path'], ctx)
113 sdomain = [(prop_ref_field, '=', False),('namespace', '=', ns), ('name','=', prop)]
115 sdomain = ['|', (prop_ref_field, '=', res_id)] + sdomain
116 prop_ids = propobj.search(cr, uid, sdomain, context=ctx)
118 pbro = propobj.browse(cr, uid, prop_ids[0], context=ctx)
121 if val.startswith("('") and val.endswith(")"):
122 glbls = { 'urlquote': urllib.quote, }
123 val = eval(val, glbls, ctx)
129 def _dav_lock_hlpr(self, cr, lock_data, par_class, prop_model,
130 prop_ref_field, res_id):
131 """ Helper, which uses the dav properties table for placing locks
133 @param lock_data a dictionary of input to this function.
134 @return list of tuples, DAV:activelock _contents_ structure.
135 See webdav.py:class Prop2Xml() for semantics
137 Note: although the DAV response shall be an <activelock/>, this
138 function will only return the elements inside the activelock,
139 because the calling function needs to append the <lockroot/> in
140 it. See webdav.py:mk_lock_response()
142 In order to reuse code, this function can be called with
143 lock_data['unlock_mode']=True, in order to unlock.
145 @return bool in unlock mode, (davstruct, prop_id, token) in lock/refresh,
146 or (False, prop_id, token) if already locked,
147 or (False, False, False) if lock not found to refresh
151 assert isinstance(lock_data, dict), '%r' % lock_data
152 propobj = self.context._dirobj.pool.get(prop_model)
153 uid = self.context.uid
154 ctx = self.context.context.copy()
155 ctx.update(self.dctx)
156 ctx.update({'uid': uid, 'dbname': self.context.dbname })
157 ctx['node_classname'] = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
158 dict_filter(self.context.extra_ctx, ['username', 'groupname', 'webdav_path'], ctx)
159 sdomain = [(prop_ref_field, '=', res_id), ('namespace', '=', 'DAV:'),
160 ('name','=', 'lockdiscovery')]
164 tmout2 = int(lock_data.get('timeout', 3*3600))
166 prop_ids = propobj.search(cr, uid, sdomain, context=ctx)
168 for pbro in propobj.browse(cr, uid, prop_ids, context=ctx):
171 if val.startswith("('") and val.endswith(")"):
172 glbls = { 'urlquote': urllib.quote, }
173 val = eval(val, glbls, ctx)
175 # all locks should be at "subst" format
177 if not (val and isinstance(val, tuple)
178 and val[0:2] == ( 'activelock','DAV:')):
179 # print "Value is not activelock:", val
185 # discover the timeout. If anything goes wrong, delete
189 if parm[1] != 'DAV:':
191 if parm[0] == 'timeout':
192 if isinstance(parm[2], basestring) \
193 and parm[2].startswith('Second-'):
194 tmout = int(parm[2][7:])
195 elif parm[0] == 'locktoken':
196 if isinstance(parm[2], basestring):
198 elif isinstance(parm[2], tuple) and \
199 parm[2][0:2] == ('href','DAV:'):
200 old_token = parm[2][2]
202 # print "Mangled token in DAV property: %r" % parm[2]
203 props_to_delete.append(pbro.id)
205 elif parm[0] == 'owner':
206 old_owner = parm[2] # not used yet
208 mdate = pbro.write_date or pbro.create_date
209 mdate = time.mktime(time.strptime(mdate,'%Y-%m-%d %H:%M:%S'))
210 if mdate + tmout < time.time():
211 props_to_delete.append(pbro.id)
214 props_to_delete.append(pbro.id)
217 props_to_delete.append(pbro.id)
220 # A valid lock is found here
221 if lock_data.get('refresh', False):
222 if old_token != lock_data.get('token'):
224 # refresh mode. Just touch anything and the ORM will update
225 # the write uid+date, won't it?
226 # Note: we don't update the owner, because incoming refresh
227 # wouldn't have a body, anyway.
228 propobj.write(cr, uid, [pbro.id,], { 'name': 'lockdiscovery'})
229 elif lock_data.get('unlock_mode', False):
230 if old_token != lock_data.get('token'):
232 props_to_delete.append(pbro.id)
237 if tmout2 > 3*3600: # 3 hours maximum
240 # 5 minutes minimum, but an unlock request can always
241 # break it at any time. Ensures no negative values, either.
245 # explicitly delete, as admin, any of the ids we have identified.
246 propobj.unlink(cr, SUPERUSER_ID, props_to_delete)
248 if lock_data.get('unlock_mode', False):
249 return lock_found and True
250 elif (not lock_found) and not (lock_data.get('refresh', False)):
251 # Create a new lock, attach and return it.
252 new_token = uuid.uuid4().urn
253 lock_val = ('activelock', 'DAV:',
254 [ ('locktype', 'DAV:', (lock_data.get('locktype',False) or 'write','DAV:')),
255 ('lockscope', 'DAV:', (lock_data.get('lockscope',False) or 'exclusive','DAV:')),
256 # ? ('depth', 'DAV:', lock_data.get('depth','0') ),
257 ('timeout','DAV:', 'Second-%d' % tmout2),
258 ('locktoken', 'DAV:', ('href', 'DAV:', new_token)),
259 # ('lockroot', 'DAV: ..., we don't store that, appended by caller
261 new_owner = lock_data.get('lockowner',False) or ctx.get('username', False)
263 lock_val[2].append( ('owner', 'DAV:', new_owner) )
264 prop_id = propobj.create(cr, uid, { prop_ref_field: res_id,
265 'namespace': 'DAV:', 'name': 'lockdiscovery',
266 'do_subst': True, 'value': repr(lock_val) })
267 return (lock_val[2], prop_id, new_token )
268 elif not lock_found: # and refresh
269 return (False, False, False)
270 elif lock_found and not lock_data.get('refresh', False):
272 return (False, lock_found, old_token)
274 return (lock_val[2], lock_found, old_token )
276 class node_dir(node_acl_mixin, nodes.node_dir):
277 """ override node_dir and add DAV functionality
279 DAV_PROPS = { "DAV:": ('owner', 'group',
280 'supported-privilege-set',
281 'current-user-privilege-set'),
283 DAV_M_NS = { "DAV:" : '_get_dav',}
284 http_options = { 'DAV': ['access-control',] }
286 def get_dav_resourcetype(self, cr):
287 return ('collection', 'DAV:')
289 def get_dav_props(self, cr):
290 return self._get_dav_props_hlpr(cr, nodes.node_dir,
291 'document.webdav.dir.property', 'dir_id', self.dir_id)
293 def get_dav_eprop(self, cr, ns, prop):
294 return self._get_dav_eprop_hlpr(cr, ns, prop, nodes.node_dir,
295 'document.webdav.dir.property', 'dir_id', self.dir_id)
298 class node_file(node_acl_mixin, nodes.node_file):
299 DAV_PROPS = { "DAV:": ('owner', 'group',
300 'supported-privilege-set',
301 'current-user-privilege-set',
304 DAV_M_NS = { "DAV:" : '_get_dav',}
305 http_options = { 'DAV': ['access-control', ] }
308 def get_dav_resourcetype(self, cr):
311 def get_dav_props(self, cr):
312 return self._get_dav_props_hlpr(cr, nodes.node_file,
313 'document.webdav.file.property', 'file_id', self.file_id)
315 def dav_lock(self, cr, lock_data):
316 """ Locks or unlocks the node, using DAV semantics.
318 Unlocking will be done when lock_data['unlock_mode'] == True
320 See _dav_lock_hlpr() for calling details.
322 It is fundamentally OK to use this function from non-DAV endpoints,
323 but they will all have to emulate the tuple-in-list structure of
324 the DAV lock data. RFC if this translation should be done inside
325 the _dav_lock_hlpr (to ease other protocols).
327 return self._dav_lock_hlpr(cr, lock_data, nodes.node_file,
328 'document.webdav.file.property', 'file_id', self.file_id)
330 def dav_unlock(self, cr, token):
331 """Releases the token lock held for the node
333 This is a utility complement of dav_lock()
335 lock_data = { 'token': token, 'unlock_mode': True }
336 return self._dav_lock_hlpr(cr, lock_data, nodes.node_file,
337 'document.webdav.file.property', 'file_id', self.file_id)
339 def get_dav_eprop(self, cr, ns, prop):
340 if ns == 'DAV:' and prop == 'supportedlock':
341 return [ ('lockentry', 'DAV:',
342 [ ('lockscope','DAV:', ('shared', 'DAV:')),
343 ('locktype','DAV:', ('write', 'DAV:')),
345 ('lockentry', 'DAV:',
346 [ ('lockscope','DAV:', ('exclusive', 'DAV:')),
347 ('locktype','DAV:', ('write', 'DAV:')),
350 return self._get_dav_eprop_hlpr(cr, ns, prop, nodes.node_file,
351 'document.webdav.file.property', 'file_id', self.file_id)
353 class node_database(nodes.node_database):
354 def get_dav_resourcetype(self, cr):
355 return ('collection', 'DAV:')
357 def get_dav_props(self, cr):
358 return self._get_dav_props_hlpr(cr, nodes.node_database,
359 'document.webdav.dir.property', 'dir_id', False)
361 def get_dav_eprop(self, cr, ns, prop):
362 return self._get_dav_eprop_hlpr(cr, nodes.node_database, ns, prop,
363 'document.webdav.dir.property', 'dir_id', False)
365 class node_res_obj(node_acl_mixin, nodes.node_res_obj):
366 DAV_PROPS = { "DAV:": ('owner', 'group',
367 'supported-privilege-set',
368 'current-user-privilege-set'),
370 DAV_M_NS = { "DAV:" : '_get_dav',}
371 http_options = { 'DAV': ['access-control',] }
373 def get_dav_resourcetype(self, cr):
374 return ('collection', 'DAV:')
376 def get_dav_props(self, cr):
377 return self._get_dav_props_hlpr(cr, nodes.node_res_obj,
378 'document.webdav.dir.property', 'dir_id', self.dir_id)
380 def get_dav_eprop(self, cr, ns, prop):
381 return self._get_dav_eprop_hlpr(cr, ns, prop, nodes.node_res_obj,
382 'document.webdav.dir.property', 'dir_id', self.dir_id)
385 class node_res_dir(node_acl_mixin, nodes.node_res_dir):
386 DAV_PROPS = { "DAV:": ('owner', 'group',
387 'supported-privilege-set',
388 'current-user-privilege-set'),
390 DAV_M_NS = { "DAV:" : '_get_dav',}
391 http_options = { 'DAV': ['access-control',] }
392 res_obj_class = node_res_obj
394 def get_dav_resourcetype(self, cr):
395 return ('collection', 'DAV:')
397 def get_dav_props(self, cr):
398 return self._get_dav_props_hlpr(cr, nodes.node_res_dir,
399 'document.webdav.dir.property', 'dir_id', self.dir_id)
401 def get_dav_eprop(self, cr, ns, prop):
402 return self._get_dav_eprop_hlpr(cr, ns, prop, nodes.node_res_dir,
403 'document.webdav.dir.property', 'dir_id', self.dir_id)
405 # Some copies, so that this module can replace 'from document import nodes'
406 get_node_context = nodes.get_node_context
407 node_context = nodes.node_context
408 node_class = nodes.node_class
409 node_descriptor = nodes.node_descriptor
414 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: