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 nodes
24 from tools.safe_eval import safe_eval as eval
29 from tools.dict_tools import dict_filter
31 from document.dict_tools import dict_filter
33 class node_acl_mixin(object):
34 def _get_dav_owner(self, cr):
37 def _get_dav_group(self, cr):
40 def _get_dav_supported_privilege_set(self, cr):
43 def _get_dav_current_user_privilege_set(self, cr):
46 def _get_dav_props_hlpr(self, cr, par_class, prop_model,
47 prop_ref_field, res_id):
48 """ Helper for dav properties, usable in subclasses
50 @param par_class The parent class
51 @param prop_model The name of the orm model holding the properties
52 @param prop_ref_field The name of the field at prop_model pointing to us
53 @param res_id the id of self in the corresponing orm table, that should
54 match prop_model.prop_ref_field
56 ret = par_class.get_dav_props(self, cr)
58 propobj = self.context._dirobj.pool.get(prop_model)
59 uid = self.context.uid
60 ctx = self.context.context.copy()
62 # Not really needed because we don't do eval here:
63 # ctx.update({'uid': uid, 'dbname': self.context.dbname })
64 # dict_filter(self.context.extra_ctx, ['username', 'groupname', 'webdav_path'], ctx)
65 sdomain = [(prop_ref_field, '=', False),]
67 sdomain = ['|', (prop_ref_field, '=', res_id)] + sdomain
68 prop_ids = propobj.search(cr, uid, sdomain, context=ctx)
71 for pbro in propobj.browse(cr, uid, prop_ids, context=ctx):
72 ret[pbro.namespace] = ret.get(pbro.namespace, ()) + \
74 # Note that we cannot have properties to conditionally appear
75 # on the context, yet.
79 def _get_dav_eprop_hlpr(self, cr, ns, prop,
80 par_class, prop_model,
81 prop_ref_field, res_id):
82 """ Helper for get dav eprop, usable in subclasses
84 @param namespace the one to search for
85 @param name Name to search for
86 @param par_class The parent class
87 @param prop_model The name of the orm model holding the properties
88 @param prop_ref_field The name of the field at prop_model pointing to us
89 @param res_id the id of self in the corresponing orm table, that should
90 match prop_model.prop_ref_field
92 ret = par_class.get_dav_eprop(self, cr, ns, prop)
96 propobj = self.context._dirobj.pool.get(prop_model)
97 uid = self.context.uid
98 ctx = self.context.context.copy()
100 ctx.update({'uid': uid, 'dbname': self.context.dbname })
101 ctx['node_classname'] = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
102 dict_filter(self.context.extra_ctx, ['username', 'groupname', 'webdav_path'], ctx)
103 sdomain = [(prop_ref_field, '=', False),('namespace', '=', ns), ('name','=', prop)]
105 sdomain = ['|', (prop_ref_field, '=', res_id)] + sdomain
106 prop_ids = propobj.search(cr, uid, sdomain, context=ctx)
108 pbro = propobj.browse(cr, uid, prop_ids[0], context=ctx)
111 if val.startswith("('") and val.endswith(")"):
112 glbls = { 'urlquote': urllib.quote, }
113 val = eval(val, glbls, ctx)
119 def _dav_lock_hlpr(self, cr, lock_data, par_class, prop_model,
120 prop_ref_field, res_id):
121 """ Helper, which uses the dav properties table for placing locks
123 @param lock_data a dictionary of input to this function.
124 @return list of tuples, DAV:activelock _contents_ structure.
125 See webdav.py:class Prop2Xml() for semantics
127 Note: although the DAV response shall be an <activelock/>, this
128 function will only return the elements inside the activelock,
129 because the calling function needs to append the <lockroot/> in
130 it. See webdav.py:mk_lock_response()
132 In order to reuse code, this function can be called with
133 lock_data['unlock_mode']=True, in order to unlock.
135 @return bool in unlock mode, (davstruct, prop_id, token) in lock/refresh,
136 or (False, prop_id, token) if already locked,
137 or (False, False, False) if lock not found to refresh
141 assert isinstance(lock_data, dict), '%r' % lock_data
142 propobj = self.context._dirobj.pool.get(prop_model)
143 uid = self.context.uid
144 ctx = self.context.context.copy()
145 ctx.update(self.dctx)
146 ctx.update({'uid': uid, 'dbname': self.context.dbname })
147 ctx['node_classname'] = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
148 dict_filter(self.context.extra_ctx, ['username', 'groupname', 'webdav_path'], ctx)
149 sdomain = [(prop_ref_field, '=', res_id), ('namespace', '=', 'DAV:'),
150 ('name','=', 'lockdiscovery')]
154 tmout2 = int(lock_data.get('timeout', 3*3600))
156 prop_ids = propobj.search(cr, uid, sdomain, context=ctx)
158 for pbro in propobj.browse(cr, uid, prop_ids, context=ctx):
161 if val.startswith("('") and val.endswith(")"):
162 glbls = { 'urlquote': urllib.quote, }
163 val = eval(val, glbls, ctx)
165 # all locks should be at "subst" format
167 if not (val and isinstance(val, tuple)
168 and val[0:2] == ( 'activelock','DAV:')):
169 # print "Value is not activelock:", val
175 # discover the timeout. If anything goes wrong, delete
179 if parm[1] != 'DAV:':
181 if parm[0] == 'timeout':
182 if isinstance(parm[2], basestring) \
183 and parm[2].startswith('Second-'):
184 tmout = int(parm[2][7:])
185 elif parm[0] == 'locktoken':
186 if isinstance(parm[2], basestring):
188 elif isinstance(parm[2], tuple) and \
189 parm[2][0:2] == ('href','DAV:'):
190 old_token = parm[2][2]
192 # print "Mangled token in DAV property: %r" % parm[2]
193 props_to_delete.append(pbro.id)
195 elif parm[0] == 'owner':
196 old_owner = parm[2] # not used yet
198 mdate = pbro.write_date or pbro.create_date
199 mdate = time.mktime(time.strptime(mdate,'%Y-%m-%d %H:%M:%S'))
200 if mdate + tmout < time.time():
201 props_to_delete.append(pbro.id)
204 props_to_delete.append(pbro.id)
207 props_to_delete.append(pbro.id)
210 # A valid lock is found here
211 if lock_data.get('refresh', False):
212 if old_token != lock_data.get('token'):
214 # refresh mode. Just touch anything and the ORM will update
215 # the write uid+date, won't it?
216 # Note: we don't update the owner, because incoming refresh
217 # wouldn't have a body, anyway.
218 propobj.write(cr, uid, [pbro.id,], { 'name': 'lockdiscovery'})
219 elif lock_data.get('unlock_mode', False):
220 if old_token != lock_data.get('token'):
222 props_to_delete.append(pbro.id)
227 if tmout2 > 3*3600: # 3 hours maximum
230 # 5 minutes minimum, but an unlock request can always
231 # break it at any time. Ensures no negative values, either.
235 # explicitly delete, as admin, any of the ids we have identified.
236 propobj.unlink(cr, 1, props_to_delete)
238 if lock_data.get('unlock_mode', False):
239 return lock_found and True
240 elif (not lock_found) and not (lock_data.get('refresh', False)):
241 # Create a new lock, attach and return it.
242 new_token = uuid.uuid4().urn
243 lock_val = ('activelock', 'DAV:',
244 [ ('locktype', 'DAV:', (lock_data.get('locktype',False) or 'write','DAV:')),
245 ('lockscope', 'DAV:', (lock_data.get('lockscope',False) or 'exclusive','DAV:')),
246 # ? ('depth', 'DAV:', lock_data.get('depth','0') ),
247 ('timeout','DAV:', 'Second-%d' % tmout2),
248 ('locktoken', 'DAV:', ('href', 'DAV:', new_token)),
249 # ('lockroot', 'DAV: ..., we don't store that, appended by caller
251 new_owner = lock_data.get('lockowner',False) or ctx.get('username', False)
253 lock_val[2].append( ('owner', 'DAV:', new_owner) )
254 prop_id = propobj.create(cr, uid, { prop_ref_field: res_id,
255 'namespace': 'DAV:', 'name': 'lockdiscovery',
256 'do_subst': True, 'value': repr(lock_val) })
257 return (lock_val[2], prop_id, new_token )
258 elif not lock_found: # and refresh
259 return (False, False, False)
260 elif lock_found and not lock_data.get('refresh', False):
262 return (False, lock_found, old_token)
264 return (lock_val[2], lock_found, old_token )
266 class node_dir(node_acl_mixin, nodes.node_dir):
267 """ override node_dir and add DAV functionality
269 DAV_PROPS = { "DAV:": ('owner', 'group',
270 'supported-privilege-set',
271 'current-user-privilege-set'),
273 DAV_M_NS = { "DAV:" : '_get_dav',}
274 http_options = { 'DAV': ['access-control',] }
276 def get_dav_resourcetype(self, cr):
277 return ('collection', 'DAV:')
279 def get_dav_props(self, cr):
280 return self._get_dav_props_hlpr(cr, nodes.node_dir,
281 'document.webdav.dir.property', 'dir_id', self.dir_id)
283 def get_dav_eprop(self, cr, ns, prop):
284 return self._get_dav_eprop_hlpr(cr, ns, prop, nodes.node_dir,
285 'document.webdav.dir.property', 'dir_id', self.dir_id)
288 class node_file(node_acl_mixin, nodes.node_file):
289 DAV_PROPS = { "DAV:": ('owner', 'group',
290 'supported-privilege-set',
291 'current-user-privilege-set',
294 DAV_M_NS = { "DAV:" : '_get_dav',}
295 http_options = { 'DAV': ['access-control', ] }
298 def get_dav_resourcetype(self, cr):
301 def get_dav_props(self, cr):
302 return self._get_dav_props_hlpr(cr, nodes.node_file,
303 'document.webdav.file.property', 'file_id', self.file_id)
305 def dav_lock(self, cr, lock_data):
306 """ Locks or unlocks the node, using DAV semantics.
308 Unlocking will be done when lock_data['unlock_mode'] == True
310 See _dav_lock_hlpr() for calling details.
312 It is fundamentally OK to use this function from non-DAV endpoints,
313 but they will all have to emulate the tuple-in-list structure of
314 the DAV lock data. RFC if this translation should be done inside
315 the _dav_lock_hlpr (to ease other protocols).
317 return self._dav_lock_hlpr(cr, lock_data, nodes.node_file,
318 'document.webdav.file.property', 'file_id', self.file_id)
320 def dav_unlock(self, cr, token):
321 """Releases the token lock held for the node
323 This is a utility complement of dav_lock()
325 lock_data = { 'token': token, 'unlock_mode': True }
326 return self._dav_lock_hlpr(cr, lock_data, nodes.node_file,
327 'document.webdav.file.property', 'file_id', self.file_id)
329 def get_dav_eprop(self, cr, ns, prop):
330 if ns == 'DAV:' and prop == 'supportedlock':
331 return [ ('lockentry', 'DAV:',
332 [ ('lockscope','DAV:', ('shared', 'DAV:')),
333 ('locktype','DAV:', ('write', 'DAV:')),
335 ('lockentry', 'DAV:',
336 [ ('lockscope','DAV:', ('exclusive', 'DAV:')),
337 ('locktype','DAV:', ('write', 'DAV:')),
340 return self._get_dav_eprop_hlpr(cr, ns, prop, nodes.node_file,
341 'document.webdav.file.property', 'file_id', self.file_id)
343 class node_database(nodes.node_database):
344 def get_dav_resourcetype(self, cr):
345 return ('collection', 'DAV:')
347 def get_dav_props(self, cr):
348 return self._get_dav_props_hlpr(cr, nodes.node_database,
349 'document.webdav.dir.property', 'dir_id', False)
351 def get_dav_eprop(self, cr, ns, prop):
352 return self._get_dav_eprop_hlpr(cr, nodes.node_database, ns, prop,
353 'document.webdav.dir.property', 'dir_id', False)
355 class node_res_obj(node_acl_mixin, nodes.node_res_obj):
356 DAV_PROPS = { "DAV:": ('owner', 'group',
357 'supported-privilege-set',
358 'current-user-privilege-set'),
360 DAV_M_NS = { "DAV:" : '_get_dav',}
361 http_options = { 'DAV': ['access-control',] }
363 def get_dav_resourcetype(self, cr):
364 return ('collection', 'DAV:')
366 def get_dav_props(self, cr):
367 return self._get_dav_props_hlpr(cr, nodes.node_res_obj,
368 'document.webdav.dir.property', 'dir_id', self.dir_id)
370 def get_dav_eprop(self, cr, ns, prop):
371 return self._get_dav_eprop_hlpr(cr, ns, prop, nodes.node_res_obj,
372 'document.webdav.dir.property', 'dir_id', self.dir_id)
375 class node_res_dir(node_acl_mixin, nodes.node_res_dir):
376 DAV_PROPS = { "DAV:": ('owner', 'group',
377 'supported-privilege-set',
378 'current-user-privilege-set'),
380 DAV_M_NS = { "DAV:" : '_get_dav',}
381 http_options = { 'DAV': ['access-control',] }
382 res_obj_class = node_res_obj
384 def get_dav_resourcetype(self, cr):
385 return ('collection', 'DAV:')
387 def get_dav_props(self, cr):
388 return self._get_dav_props_hlpr(cr, nodes.node_res_dir,
389 'document.webdav.dir.property', 'dir_id', self.dir_id)
391 def get_dav_eprop(self, cr, ns, prop):
392 return self._get_dav_eprop_hlpr(cr, ns, prop, nodes.node_res_dir,
393 'document.webdav.dir.property', 'dir_id', self.dir_id)
395 # Some copies, so that this module can replace 'from document import nodes'
396 get_node_context = nodes.get_node_context
397 node_context = nodes.node_context
398 node_class = nodes.node_class
399 node_descriptor = nodes.node_descriptor
404 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: