]> code.delx.au - pymsnt/blob - src/xdb.py
98cdfadcc1688596cdac593023a13c2d9c1fcdc1
[pymsnt] / src / xdb.py
1 # Copyright 2004 James Bunton <james@delx.cjb.net>
2 # Licensed for distribution under the GPL version 2, check COPYING for details
3
4 import utils
5 if(utils.checkTwisted()):
6 from twisted.xish.domish import Element
7 else:
8 from tlib.domish import Element
9
10 import os
11 import os.path
12 import debug
13 import config
14 import legacy
15
16 SPOOL_UMASK = 0177
17
18 class XDB:
19 """
20 Class for storage of data. Compatible with xdb_file from Jabberd1.4.x
21 Allows PyMSN-t to be compatible with MSN-t
22
23 Create one instance of the class for each XDB 'folder' you want.
24 Call request()/set() with the xdbns argument you wish to retrieve
25 """
26 def __init__(self, name, mangle=False):
27 """ Creates an XDB object. If mangle is True then any '@' signs in filenames will be changed to '%' """
28 self.name = utils.doPath(config.spooldir) + '/' + name
29 if not os.path.exists(self.name) :
30 os.makedirs(self.name)
31 self.mangle = mangle
32
33 def __getFile(self, file):
34 if(self.mangle):
35 file = file.replace('@', '%')
36
37 document = utils.parseFile(self.name + "/" + file + ".xml")
38
39 return document
40
41 def __writeFile(self, file, text):
42 if(self.mangle):
43 file = file.replace('@', '%')
44
45 prev_umask = os.umask(SPOOL_UMASK)
46 f = open(self.name + "/" + file + ".xml", "w")
47 f.write(text)
48 f.close()
49 os.umask(prev_umask)
50
51
52 def request(self, file, xdbns):
53 """ Requests a specific xdb namespace from the XDB 'file' """
54 try:
55 document = self.__getFile(file)
56 for child in document.elements():
57 if(child.getAttribute("xdbns") == xdbns):
58 return child
59 except:
60 return None
61
62 def set(self, file, xdbns, element):
63 """ Sets a specific xdb namespace in the XDB 'file' to element """
64 try:
65 element.attributes["xdbns"] = xdbns
66 document = None
67 try:
68 document = self.__getFile(file)
69 except IOError:
70 pass
71 if(not document):
72 document = Element((None, "xdb"))
73
74 # Remove the existing node (if any)
75 for child in document.elements():
76 if(child.getAttribute("xdbns") == xdbns):
77 document.children.remove(child)
78 # Add the new one
79 document.addChild(element)
80
81 self.__writeFile(file, document.toXml())
82 except:
83 debug.log("XDB error writing entry %s to file %s" % (xdbns, file))
84 raise
85
86 def remove(self, file):
87 """ Removes an XDB file """
88 file = self.name + "/" + file + ".xml"
89 if(self.mangle):
90 file = file.replace('@', '%')
91 try:
92 os.remove(file)
93 except:
94 debug.log("XDB error removing file " + file)
95 raise
96