Reorganize build process
[mspang/pyceo.git] / pylib / csc / apps / urwid / ldapfilter.py
1 import ldap
2
3 class LdapFilter:
4     def __init__(self, widget):
5         self.widget = widget
6
7     def set_ldap_filter(self, ldap_uri, ldap_base, ldap_attr, ldap_map):
8         try:
9             self.ldap = ldap.initialize(ldap_uri)
10             self.ldap.simple_bind_s("", "")
11         except ldap.LDAPError:
12             return
13         self.base = ldap_base
14         self.attr = ldap_attr
15         self.map = ldap_map
16
17     def keypress(self, size, key):
18         if self.ldap != None:
19             if key == 'enter' or key == 'down' or key == 'up':
20                 attr = self.escape(self.attr)
21                 search = self.escape(self.widget.get_edit_text(self))
22                 filter = '(%s=%s)' % (attr, search)
23                 try:
24                     matches = self.ldap.search_s(self.base,
25                         ldap.SCOPE_SUBTREE, filter)
26                     if len(matches) > 0:
27                         (_, attrs) = matches[0]
28                         for (k, v) in self.map.items():
29                             if attrs.has_key(k) and len(attrs[k]) > 0:
30                                 v.set_edit_text(attrs[k][0])
31                 except ldap.LDAPError:
32                     pass
33         return self.widget.keypress(self, size, key)
34
35     def escape(self, value):
36         value = str(value)
37         value = value.replace('\\', '\\5c').replace('*', '\\2a')
38         value = value.replace('(', '\\28').replace(')', '\\29')
39         value = value.replace('\x00', '\\00')
40         return value