1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # Copyright (c) 2004 TINY SPRL. (http://tiny.be) All Rights Reserved.
5 # Fabien Pinckaers <fp@tiny.Be>
7 # WARNING: This program as such is intended to be used by professional
8 # programmers who take the whole responsability of assessing all potential
9 # consequences resulting from its eventual inadequacies and bugs
10 # End users who are looking for a ready-to-use solution with commercial
11 # garantees and support are strongly adviced to contract a Free Software
14 # This program is Free Software; you can redistribute it and/or
15 # modify it under the terms of the GNU General Public License
16 # as published by the Free Software Foundation; either version 2
17 # of the License, or (at your option) any later version.
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 # GNU General Public License for more details.
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
28 ##############################################################################
36 from string import joinfields, split, lower
38 from service import security
43 from DAV.constants import COLLECTION, OBJECT
44 from DAV.errors import *
45 from DAV.iface import *
48 from DAV.davcmd import copyone, copytree, moveone, movetree, delone, deltree
50 from cache import memoize
54 #hack for urlparse: add webdav in the net protocols
55 urlparse.uses_netloc.append('webdav')
56 urlparse.uses_netloc.append('webdavs')
58 class tinydav_handler(dav_interface):
60 This class models a Tiny ERP interface for the DAV server
62 PROPS={'DAV:': dav_interface.PROPS['DAV:'], }
64 M_NS={ "DAV:" : dav_interface.M_NS['DAV:'], }
66 def __init__(self, parent, verbose=False):
68 self.directory_id=False
71 self.baseuri = parent.baseuri
73 def get_propnames(self,uri):
75 self.parent.log_message('get propnames: %s' % uri)
76 if uri[-1]=='/':uri=uri[:-1]
77 cr, uid, pool, dbname, uri2 = self.get_cr(uri)
81 node = self.uri2object(cr,uid,pool, uri2)
83 props.update(node.get_dav_props(cr))
87 def get_prop(self,uri,ns,propname):
88 """ return the value of a given property
90 uri -- uri of the object to get the property of
91 ns -- namespace of the property
92 pname -- name of the property
94 if self.M_NS.has_key(ns):
95 return dav_interface.get_prop(self,uri,ns,propname)
97 if uri[-1]=='/':uri=uri[:-1]
98 cr, uid, pool, dbname, uri2 = self.get_cr(uri)
102 node = self.uri2object(cr,uid,pool, uri2)
106 res = node.get_dav_eprop(cr,ns,propname)
111 # def get_db(self,uri):
112 # names=self.uri2local(uri).split('/')
115 # self.db_name=self.uri2local(uri).split('/')[1]
116 # if self.db_name=='':
117 # raise Exception,'Plese specify Database name in folder'
118 # return self.db_name
121 def later_get_db_from_path(self,path):
124 def urijoin(self,*ajoin):
125 """ Return the base URI of this request, or even join it with the
128 return self.baseuri+ '/'.join(ajoin)
132 s = netsvc.LocalService('db')
135 for db_name in result:
136 db = pooler.get_db_only(db_name)
138 cr.execute("select id from ir_module_module where name = 'document' and state='installed' ")
141 self.db_name_list.append(db_name)
143 return self.db_name_list
145 def get_childs(self,uri):
146 """ return the child objects as self.baseuris for the given URI """
147 self.parent.log_message('get childs: %s' % uri)
148 if uri[-1]=='/':uri=uri[:-1]
149 cr, uid, pool, dbname, uri2 = self.get_cr(uri)
152 s = netsvc.LocalService('db')
153 return map(lambda x: self.urijoin(x), self.db_list())
155 node = self.uri2object(cr,uid,pool, uri2[:])
158 raise DAV_NotFound(uri2)
160 fp = node.full_path()
162 self.parent.log_message('childs: @%s' % fp)
166 for d in node.children(cr):
167 self.parent.log_message('child: %s' % d.path)
169 result.append( self.urijoin(dbname,fp,d.path) )
171 result.append( self.urijoin(dbname,d.path) )
175 def uri2local(self, uri):
176 uparts=urlparse.urlparse(uri)
178 if reluri and reluri[-1]=="/":
183 # pos: -1 to get the parent of the uri
185 def get_cr(self, uri):
186 pdb = self.parent.auth_proxy.last_auth
187 reluri = self.uri2local(uri)
189 dbname = reluri.split('/')[2]
193 return None, None, None, False, None
194 if not pdb and dbname:
195 # if dbname was in our uri, we should have authenticated
197 raise Exception("Programming error")
198 assert pdb == dbname, " %s != %s" %(pdb, dbname)
199 user, passwd, dbn2, uid = self.parent.auth_proxy.auth_creds[pdb]
200 db,pool = pooler.get_db_and_pool(dbname)
202 uri2 = reluri.split('/')[3:]
203 return cr, uid, pool, dbname, uri2
205 def uri2object(self, cr,uid, pool,uri):
208 return pool.get('document.directory').get_object(cr, uid, uri)
210 def get_data(self,uri):
211 self.parent.log_message('GET: %s' % uri)
212 if uri[-1]=='/':uri=uri[:-1]
213 cr, uid, pool, dbname, uri2 = self.get_cr(uri)
217 node = self.uri2object(cr,uid,pool, uri2)
219 raise DAV_NotFound(uri2)
221 datas = node.get_data(cr)
224 self.parent.log_error("GET typeError: %s", str(e))
225 self.parent.log_message("Exc: %s",traceback.format_exc())
227 except IndexError,e :
228 self.parent.log_error("GET IndexError: %s", str(e))
229 raise DAV_NotFound(uri2)
232 self.parent.log_error("GET exception: %s",str(e))
233 self.parent.log_message("Exc: %s", traceback.format_exc())
240 def _get_dav_resourcetype(self,uri):
241 """ return type of object """
242 self.parent.log_message('get RT: %s' % uri)
243 if uri[-1]=='/':uri=uri[:-1]
244 cr, uid, pool, dbname, uri2 = self.get_cr(uri)
248 node = self.uri2object(cr,uid,pool, uri2)
250 raise DAV_NotFound(uri2)
251 if node.type in ('collection','database'):
257 def _get_dav_displayname(self,uri):
258 self.parent.log_message('get DN: %s' % uri)
259 if uri[-1]=='/':uri=uri[:-1]
260 cr, uid, pool, dbname, uri2 = self.get_cr(uri)
264 node = self.uri2object(cr,uid,pool, uri2)
267 raise DAV_NotFound(uri2)
269 return node.displayname
272 def _get_dav_getcontentlength(self,uri):
273 """ return the content length of an object """
274 self.parent.log_message('get length: %s' % uri)
275 if uri[-1]=='/':uri=uri[:-1]
277 cr, uid, pool, dbname, uri2 = self.get_cr(uri)
281 node = self.uri2object(cr, uid, pool, uri2)
284 raise DAV_NotFound(uri2)
285 result = node.content_length or 0
290 def _get_dav_getetag(self,uri):
291 """ return the ETag of an object """
292 self.parent.log_message('get etag: %s' % uri)
293 if uri[-1]=='/':uri=uri[:-1]
295 cr, uid, pool, dbname, uri2 = self.get_cr(uri)
299 node = self.uri2object(cr, uid, pool, uri2)
302 raise DAV_NotFound(uri2)
303 result = node.get_etag(cr)
308 def get_lastmodified(self,uri):
309 """ return the last modified date of the object """
310 if uri[-1]=='/':uri=uri[:-1]
312 cr, uid, pool, dbname, uri2 = self.get_cr(uri)
316 node = self.uri2object(cr,uid,pool, uri2)
318 raise DAV_NotFound(uri2)
320 return time.mktime(time.strptime(node.write_date,'%Y-%m-%d %H:%M:%S'))
327 def get_creationdate(self,uri):
328 """ return the last modified date of the object """
330 if uri[-1]=='/':uri=uri[:-1]
331 cr, uid, pool, dbname, uri2 = self.get_cr(uri)
335 node = self.uri2object(cr,uid,pool, uri2)
337 raise DAV_NotFound(uri2)
339 result = time.strptime(node.create_date,'%Y-%m-%d %H:%M:%S')
341 result = time.gmtime()
347 def _get_dav_getcontenttype(self,uri):
348 self.parent.log_message('get contenttype: %s' % uri)
349 if uri[-1]=='/':uri=uri[:-1]
350 cr, uid, pool, dbname, uri2 = self.get_cr(uri)
353 return 'httpd/unix-directory'
354 node = self.uri2object(cr,uid,pool, uri2)
356 raise DAV_NotFound(uri2)
358 result = 'application/octet-stream'
359 #if node.type=='collection':
360 #result ='httpd/unix-directory'
362 result = node.mimetype
364 #raise DAV_NotFound, 'Could not find %s' % path
369 """ create a new collection """
370 self.parent.log_message('MKCOL: %s' % uri)
371 if uri[-1]=='/':uri=uri[:-1]
372 parent='/'.join(uri.split('/')[:-1])
373 if not parent.startswith(self.baseuri):
374 parent=self.baseuri + ''.join(parent[1:])
375 if not uri.startswith(self.baseuri):
376 uri=self.baseuri + ''.join(uri[1:])
379 cr, uid, pool,dbname, uri2 = self.get_cr(uri)
382 node = self.uri2object(cr,uid,pool, uri2[:-1])
383 object2=node and node.object2 or False
384 object=node and node.object or False
388 pool.get('document.directory').create(cr, uid, {
391 'ressource_type_id': False,
392 'ressource_id': False
395 pool.get('document.directory').create(cr, uid, {
397 'parent_id': object.id,
398 'ressource_type_id': object.ressource_type_id.id,
399 'ressource_id': object2 and object2.id or False
406 def put(self,uri,data,content_type=None):
407 """ put the object into the filesystem """
408 self.parent.log_message('Putting %s (%d), %s'%( unicode(uri,'utf8'), len(data), content_type))
409 parent='/'.join(uri.split('/')[:-1])
410 cr, uid, pool,dbname, uri2 = self.get_cr(uri)
414 node = self.uri2object(cr,uid,pool, uri2[:])
418 ext = objname.find('.') >0 and objname.split('.')[1] or False
421 dir_node = self.uri2object(cr,uid,pool, uri2[:-1])
423 raise DAV_NotFound('Parent folder not found')
425 dir_node.create_child(cr,objname,data)
428 self.parent.log_error("Cannot create %s: %s", objname, str(e))
429 self.parent.log_message("Exc: %s",traceback.format_exc())
433 node.set_data(cr,data)
436 self.parent.log_error("Cannot save %s: %s", objname, str(e))
437 self.parent.log_message("Exc: %s",traceback.format_exc())
445 """ delete a collection """
446 if uri[-1]=='/':uri=uri[:-1]
448 cr, uid, pool, dbname, uri2 = self.get_cr(uri)
449 if True or not dbname: # *-*
451 node = self.uri2object(cr,uid,pool, uri2)
452 object2=node and node.object2 or False
453 object=node and node.object or False
454 if object._table_name=='document.directory':
456 raise DAV_Forbidden # forbidden
458 raise DAV_Forbidden # forbidden
459 res = pool.get('document.directory').unlink(cr, uid, [object.id])
466 if uri[-1]=='/':uri=uri[:-1]
469 cr, uid, pool,dbname, uri2 = self.get_cr(uri)
473 node = self.uri2object(cr,uid,pool, uri2)
474 object2=node and node.object2 or False
475 object=node and node.object or False
479 self.parent.log_message(' rm %s "%s"'%(object._table_name,uri))
480 if object._table_name=='ir.attachment':
481 res = pool.get('ir.attachment').unlink(cr, uid, [object.id])
483 raise DAV_Forbidden # forbidden
484 parent='/'.join(uri.split('/')[:-1])
489 ### DELETE handlers (examples)
490 ### (we use the predefined methods in davcmd instead of doing
494 def delone(self,uri):
495 """ delete a single resource
497 You have to return a result dict of the form
499 or None if everything's ok
502 if uri[-1]=='/':uri=uri[:-1]
504 parent='/'.join(uri.split('/')[:-1])
507 def deltree(self,uri):
508 """ delete a collection
510 You have to return a result dict of the form
512 or None if everything's ok
514 if uri[-1]=='/':uri=uri[:-1]
515 res=deltree(self,uri)
516 parent='/'.join(uri.split('/')[:-1])
521 ### MOVE handlers (examples)
524 def moveone(self,src,dst,overwrite):
525 """ move one resource with Depth=0
527 an alternative implementation would be
532 r=os.system("rm -f '%s'" %dst)
534 r=os.system("mv '%s' '%s'" %(src,dst))
538 (untested!). This would not use the davcmd functions
539 and thus can only detect errors directly on the root node.
541 res=moveone(self,src,dst,overwrite)
544 def movetree(self,src,dst,overwrite):
545 """ move a collection with Depth=infinity
547 an alternative implementation would be
552 r=os.system("rm -rf '%s'" %dst)
554 r=os.system("mv '%s' '%s'" %(src,dst))
558 (untested!). This would not use the davcmd functions
559 and thus can only detect errors directly on the root node"""
561 res=movetree(self,src,dst,overwrite)
568 def copyone(self,src,dst,overwrite):
569 """ copy one resource with Depth=0
571 an alternative implementation would be
576 r=os.system("rm -f '%s'" %dst)
578 r=os.system("cp '%s' '%s'" %(src,dst))
582 (untested!). This would not use the davcmd functions
583 and thus can only detect errors directly on the root node.
585 res=copyone(self,src,dst,overwrite)
588 def copytree(self,src,dst,overwrite):
589 """ copy a collection with Depth=infinity
591 an alternative implementation would be
596 r=os.system("rm -rf '%s'" %dst)
598 r=os.system("cp -r '%s' '%s'" %(src,dst))
602 (untested!). This would not use the davcmd functions
603 and thus can only detect errors directly on the root node"""
604 res=copytree(self,src,dst,overwrite)
609 ### This methods actually copy something. low-level
610 ### They are called by the davcmd utility functions
611 ### copytree and copyone (not the above!)
612 ### Look in davcmd.py for further details.
615 def copy(self,src,dst):
616 src=urllib.unquote(src)
617 dst=urllib.unquote(dst)
618 ct = self._get_dav_getcontenttype(src)
619 data = self.get_data(src)
620 self.put(dst,data,ct)
623 def copycol(self,src,dst):
624 """ copy a collection.
626 As this is not recursive (the davserver recurses itself)
627 we will only create a new directory here. For some more
628 advanced systems we might also have to copy properties from
629 the source to the destination.
631 print " copy a collection."
632 return self.mkcol(dst)
635 def exists(self,uri):
636 """ test if a resource exists """
638 cr, uid, pool,dbname, uri2 = self.get_cr(uri)
642 node = self.uri2object(cr,uid,pool, uri2)
651 def is_collection(self,uri):
652 """ test if the given uri is a collection """
653 return self._get_dav_resourcetype(uri)==COLLECTION