root / pykota / trunk / pykota / storages / ldapstorage.py @ 1084

Revision 1084, 33.9 kB (checked in by jalet, 21 years ago)

Wrong documentation strings

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[1016]1# PyKota
2#
3# PyKota : Print Quotas for CUPS and LPRng
4#
5# (c) 2003 Jerome Alet <alet@librelogiciel.com>
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
19#
20# $Id$
21#
22# $Log$
[1084]23# Revision 1.19  2003/07/14 14:18:16  jalet
24# Wrong documentation strings
25#
[1081]26# Revision 1.18  2003/07/11 14:23:13  jalet
27# When adding an user only adds one object containing both the user and
28# its account balance instead of two objects.
29#
[1075]30# Revision 1.17  2003/07/07 12:51:07  jalet
31# Small fix
32#
[1070]33# Revision 1.16  2003/07/07 12:11:13  jalet
34# Small fix
35#
[1068]36# Revision 1.15  2003/07/07 11:49:24  jalet
37# Lots of small fixes with the help of PyChecker
38#
[1067]39# Revision 1.14  2003/07/07 08:33:18  jalet
40# Bug fix due to a typo in LDAP code
41#
[1062]42# Revision 1.13  2003/07/05 07:46:50  jalet
43# The previous bug fix was incomplete.
44#
[1051]45# Revision 1.12  2003/06/30 13:54:21  jalet
46# Sorts by user / group name
47#
[1041]48# Revision 1.11  2003/06/25 14:10:01  jalet
49# Hey, it may work (edpykota --reset excepted) !
50#
[1032]51# Revision 1.10  2003/06/16 21:55:15  jalet
52# More work on LDAP, again. Problem detected.
53#
[1031]54# Revision 1.9  2003/06/16 11:59:09  jalet
55# More work on LDAP
56#
[1030]57# Revision 1.8  2003/06/15 22:26:52  jalet
58# More work on LDAP
59#
[1029]60# Revision 1.7  2003/06/14 22:44:21  jalet
61# More work on LDAP storage backend.
62#
[1027]63# Revision 1.6  2003/06/13 19:07:57  jalet
64# Two big bugs fixed, time to release something ;-)
65#
[1021]66# Revision 1.5  2003/06/10 16:37:54  jalet
67# Deletion of the second user which is not needed anymore.
68# Added a debug configuration field in /etc/pykota.conf
69# All queries can now be sent to the logger in debug mode, this will
70# greatly help improve performance when time for this will come.
71#
[1020]72# Revision 1.4  2003/06/10 10:45:32  jalet
73# Not implemented methods now raise an exception when called.
74#
[1018]75# Revision 1.3  2003/06/06 20:49:15  jalet
76# Very latest schema. UNTESTED.
77#
[1017]78# Revision 1.2  2003/06/06 14:21:08  jalet
79# New LDAP schema.
80# Small bug fixes.
81#
[1016]82# Revision 1.1  2003/06/05 11:19:13  jalet
83# More good work on LDAP storage.
84#
85#
86#
87
88#
89# My IANA assigned number, for
90# "Conseil Internet & Logiciels Libres, J�me Alet"
91# is 16868. Use this as a base to create the LDAP schema.
92#
93
[1030]94import time
95import md5
[1016]96
97from pykota.storage import PyKotaStorageError
[1041]98from pykota.storage import StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
[1016]99
100try :
101    import ldap
[1030]102    from ldap import modlist
[1016]103except ImportError :   
104    import sys
105    # TODO : to translate or not to translate ?
106    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the python-ldap module installed correctly." % sys.version.split()[0]
107   
108class Storage :
[1021]109    def __init__(self, pykotatool, host, dbname, user, passwd) :
[1016]110        """Opens the LDAP connection."""
111        # raise PyKotaStorageError, "Sorry, the LDAP backend for PyKota is not yet implemented !"
[1029]112        self.closed = 1
[1021]113        self.tool = pykotatool
114        self.debug = pykotatool.config.getDebug()
[1029]115        self.info = pykotatool.config.getLDAPInfo()
[1016]116        try :
117            self.database = ldap.initialize(host) 
118            self.database.simple_bind_s(user, passwd)
119            self.basedn = dbname
120        except ldap.SERVER_DOWN :   
121            raise PyKotaStorageError, "LDAP backend for PyKota seems to be down !" # TODO : translate
[1031]122        except ldap.LDAPError :   
123            raise PyKotaStorageError, "Unable to connect to LDAP server %s as %s." % (host, user) # TODO : translate
[1016]124        else :   
125            self.closed = 0
[1021]126            if self.debug :
127                self.tool.logger.log_message("Database opened (host=%s, dbname=%s, user=%s)" % (host, dbname, user), "debug")
[1016]128           
129    def __del__(self) :       
130        """Closes the database connection."""
131        if not self.closed :
132            del self.database
133            self.closed = 1
[1021]134            if self.debug :
135                self.tool.logger.log_message("Database closed.", "debug")
[1016]136       
[1030]137    def genUUID(self) :   
138        """Generates an unique identifier.
139       
140           TODO : this one is not unique accross several print servers, but should be sufficient for testing.
141        """
142        return md5.md5("%s" % time.time()).hexdigest()
143       
[1041]144    def beginTransaction(self) :   
145        """Starts a transaction."""
146        if self.debug :
147            self.tool.logger.log_message("Transaction begins... WARNING : No transactions in LDAP !", "debug")
148       
149    def commitTransaction(self) :   
150        """Commits a transaction."""
151        if self.debug :
152            self.tool.logger.log_message("Transaction committed. WARNING : No transactions in LDAP !", "debug")
153       
154    def rollbackTransaction(self) :     
155        """Rollbacks a transaction."""
156        if self.debug :
157            self.tool.logger.log_message("Transaction aborted. WARNING : No transaction in LDAP !", "debug")
158       
[1030]159    def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE) :
[1016]160        """Does an LDAP search query."""
161        try :
[1030]162            base = base or self.basedn
[1021]163            if self.debug :
[1041]164                self.tool.logger.log_message("QUERY : Filter : %s, BaseDN : %s, Scope : %s, Attributes : %s" % (key, base, scope, fields), "debug")
[1017]165            result = self.database.search_s(base or self.basedn, scope, key, fields)
[1030]166        except ldap.LDAPError :   
167            raise PyKotaStorageError, _("Search for %s(%s) from %s(scope=%s) returned no answer.") % (key, fields, base, scope)
[1016]168        else :     
[1031]169            if self.debug :
170                self.tool.logger.log_message("QUERY : Result : %s" % result, "debug")
[1016]171            return result
[1030]172           
173    def doAdd(self, dn, fields) :
174        """Adds an entry in the LDAP directory."""
175        try :
176            if self.debug :
177                self.tool.logger.log_message("QUERY : ADD(%s, %s)" % (dn, str(fields)), "debug")
178            self.database.add_s(dn, modlist.addModlist(fields))
179        except ldap.LDAPError :
180            raise PyKotaStorageError, _("Problem adding LDAP entry (%s, %s)") % (dn, str(fields))
181        else :
182            return dn
183           
[1041]184    def doDelete(self, dn) :
185        """Deletes an entry from the LDAP directory."""
186        try :
187            if self.debug :
188                self.tool.logger.log_message("QUERY : Delete(%s)" % dn, "debug")
189            self.database.delete_s(dn)
190        except ldap.LDAPError :
191            raise PyKotaStorageError, _("Problem deleting LDAP entry (%s)") % dn
192           
193    def doModify(self, dn, fields, ignoreold=1) :
[1030]194        """Modifies an entry in the LDAP directory."""
195        try :
196            oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE)
197            if self.debug :
198                self.tool.logger.log_message("QUERY : Modify(%s, %s ==> %s)" % (dn, oldentry[0][1], fields), "debug")
[1041]199            self.database.modify_s(dn, modlist.modifyModlist(oldentry[0][1], fields, ignore_oldexistent=ignoreold))
[1030]200        except ldap.LDAPError :
201            raise PyKotaStorageError, _("Problem modifying LDAP entry (%s, %s)") % (dn, fields)
202        else :
203            return dn
[1016]204           
[1041]205    def getUser(self, username) :   
206        """Extracts user information given its name."""
207        user = StorageUser(self, username)
208        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaLimitBy"], base=self.info["userbase"])
[1016]209        if result :
[1041]210            fields = result[0][1]
211            user.ident = result[0][0]
[1062]212            user.LimitBy = fields.get("pykotaLimitBy")
213            if user.LimitBy is not None :
214                user.LimitBy = user.LimitBy[0]
[1041]215            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["balancerdn"], username), ["pykotaBalance", "pykotaLifeTimePaid"], base=self.info["balancebase"])
216            if result :
217                fields = result[0][1]
218                user.idbalance = result[0][0]
219                user.AccountBalance = fields.get("pykotaBalance")
220                if user.AccountBalance is not None :
221                    if user.AccountBalance[0].upper() == "NONE" :
222                        user.AccountBalance = None
223                    else :   
224                        user.AccountBalance = float(user.AccountBalance[0])
225                user.AccountBalance = user.AccountBalance or 0.0       
226                user.LifeTimePaid = fields.get("pykotaLifeTimePaid")
227                if user.LifeTimePaid is not None :
228                    if user.LifeTimePaid[0].upper() == "NONE" :
229                        user.LifeTimePaid = None
230                    else :   
231                        user.LifeTimePaid = float(user.LifeTimePaid[0])
232                user.LifeTimePaid = user.LifeTimePaid or 0.0       
233            user.Exists = 1
234        return user
235       
236    def getGroup(self, groupname) :   
237        """Extracts group information given its name."""
238        group = StorageGroup(self, groupname)
239        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaLimitBy"], base=self.info["groupbase"])
[1030]240        if result :
[1041]241            fields = result[0][1]
242            group.ident = result[0][0]
[1062]243            group.LimitBy = fields.get("pykotaLimitBy")
244            if group.LimitBy is not None :
245                group.LimitBy = group.LimitBy[0]
[1041]246            group.AccountBalance = 0.0
247            group.LifeTimePaid = 0.0
248            group.Members = self.getGroupMembers(group)
249            for member in group.Members :
[1075]250                if member.Exists :
251                    group.AccountBalance += member.AccountBalance
252                    group.LifeTimePaid += member.LifeTimePaid
[1041]253            group.Exists = 1
254        return group
255       
256    def getPrinter(self, printername) :       
257        """Extracts printer information given its name."""
258        printer = StoragePrinter(self, printername)
259        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaPricePerPage", "pykotaPricePerJob"], base=self.info["printerbase"])
[1016]260        if result :
[1041]261            fields = result[0][1]
262            printer.ident = result[0][0]
263            printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
264            printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
265            printer.LastJob = self.getPrinterLastJob(printer)
266            printer.Exists = 1
267        return printer   
[1016]268           
[1041]269    def getUserGroups(self, user) :       
270        """Returns the user's groups list."""
271        groups = []
272        result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], user.Name), [self.info["grouprdn"]], base=self.info["groupbase"])
[1016]273        if result :
[1041]274            for (groupid, fields) in result :
275                groups.append(self.getGroup(fields.get(self.info["grouprdn"])[0]))
276        return groups       
277       
278    def getGroupMembers(self, group) :       
279        """Returns the group's members list."""
280        groupmembers = []
281        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (group.Name, self.info["grouprdn"], group.Name), [self.info["groupmembers"]], base=self.info["groupbase"])
[1031]282        if result :
[1041]283            for username in result[0][1].get(self.info["groupmembers"], []) :
284                groupmembers.append(self.getUser(username))
285        return groupmembers       
[1027]286       
[1041]287    def getUserPQuota(self, user, printer) :       
288        """Extracts a user print quota."""
289        userpquota = StorageUserPQuota(self, user, printer)
290        if user.Exists :
291            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s)(pykotaPrinterName=%s))" % (user.Name, printer.Name), ["pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
[1017]292            if result :
[1041]293                fields = result[0][1]
294                userpquota.ident = result[0][0]
295                userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
296                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
297                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
298                if userpquota.SoftLimit is not None :
299                    if userpquota.SoftLimit[0].upper() == "NONE" :
300                        userpquota.SoftLimit = None
301                    else :   
302                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
303                userpquota.HardLimit = fields.get("pykotaHardLimit")
304                if userpquota.HardLimit is not None :
305                    if userpquota.HardLimit[0].upper() == "NONE" :
306                        userpquota.HardLimit = None
307                    elif userpquota.HardLimit is not None :   
308                        userpquota.HardLimit = int(userpquota.HardLimit[0])
309                userpquota.DateLimit = fields.get("pykotaDateLimit")
310                if userpquota.DateLimit is not None :
311                    if userpquota.DateLimit[0].upper() == "NONE" : 
312                        userpquota.DateLimit = None
313                    else :   
314                        userpquota.DateLimit = userpquota.DateLimit[0]
315                userpquota.Exists = 1
316        return userpquota
[1016]317       
[1041]318    def getGroupPQuota(self, group, printer) :       
319        """Extracts a group print quota."""
320        grouppquota = StorageGroupPQuota(self, group, printer)
321        if group.Exists :
322            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s)(pykotaPrinterName=%s))" % (group.Name, printer.Name), ["pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["groupquotabase"])
323            if result :
324                fields = result[0][1]
325                grouppquota.ident = result[0][0]
326                grouppquota.SoftLimit = fields.get("pykotaSoftLimit")
327                if grouppquota.SoftLimit is not None :
328                    if grouppquota.SoftLimit[0].upper() == "NONE" :
329                        grouppquota.SoftLimit = None
330                    else :   
331                        grouppquota.SoftLimit = int(grouppquota.SoftLimit[0])
332                grouppquota.HardLimit = fields.get("pykotaHardLimit")
333                if grouppquota.HardLimit is not None :
334                    if grouppquota.HardLimit[0].upper() == "NONE" :
335                        grouppquota.HardLimit = None
336                    else :   
337                        grouppquota.HardLimit = int(grouppquota.HardLimit[0])
338                grouppquota.DateLimit = fields.get("pykotaDateLimit")
339                if grouppquota.DateLimit is not None :
340                    if grouppquota.DateLimit[0].upper() == "NONE" : 
341                        grouppquota.DateLimit = None
342                    else :   
343                        grouppquota.DateLimit = grouppquota.DateLimit[0]
344                grouppquota.PageCounter = 0
345                grouppquota.LifePageCounter = 0
346                if (not hasattr(group, "Members")) or (group.Members is None) :
347                    group.Members = self.getGroupMembers(group)
348                usernamesfilter = "".join(["(pykotaUserName=%s)" % member.Name for member in group.Members])
349                result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, usernamesfilter), ["pykotaPageCounter", "pykotaLifePageCounter"], base=self.info["userquotabase"])
350                if result :
351                    for userpquota in result :   
352                        grouppquota.PageCounter += int(userpquota[1].get("pykotaPageCounter")[0] or 0)
353                        grouppquota.LifePageCounter += int(userpquota[1].get("pykotaLifePageCounter")[0] or 0)
354                grouppquota.Exists = 1
355        return grouppquota
356       
357    def getPrinterLastJob(self, printer) :       
358        """Extracts a printer's last job information."""
359        lastjob = StorageLastJob(self, printer)
360        result = self.doSearch("(&(objectClass=pykotaLastjob)(|(pykotaPrinterName=%s)(%s=%s)))" % (printer.Name, self.info["printerrdn"], printer.Name), ["pykotaLastJobIdent"], base=self.info["lastjobbase"])
[1016]361        if result :
[1041]362            lastjob.lastjobident = result[0][0]
363            lastjobident = result[0][1]["pykotaLastJobIdent"][0]
364            result = self.doSearch("objectClass=pykotaJob", ["pykotaUserName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "createTimestamp"], base="cn=%s,%s" % (lastjobident, self.info["jobbase"]), scope=ldap.SCOPE_BASE)
[1017]365            if result :
[1041]366                fields = result[0][1]
367                lastjob.ident = result[0][0]
368                lastjob.JobId = fields.get("pykotaJobId")[0]
369                lastjob.User = self.getUser(fields.get("pykotaUserName")[0])
370                lastjob.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter")[0] or 0)
371                lastjob.JobSize = int(fields.get("pykotaJobSize", [0])[0])
372                lastjob.JobAction = fields.get("pykotaAction")[0]
373                date = fields.get("createTimestamp")[0]
374                year = int(date[:4])
375                month = int(date[4:6])
376                day = int(date[6:8])
377                hour = int(date[8:10])
378                minute = int(date[10:12])
379                second = int(date[12:14])
380                lastjob.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
381                lastjob.Exists = 1
382        return lastjob
[1016]383       
[1041]384    def getMatchingPrinters(self, printerpattern) :
385        """Returns the list of all printers for which name matches a certain pattern."""
386        printers = []
387        # see comment at the same place in pgstorage.py
388        result = self.doSearch("objectClass=pykotaPrinter", ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob"], base=self.info["printerbase"])
[1016]389        if result :
[1041]390            for (printerid, fields) in result :
391                printername = fields["pykotaPrinterName"][0]
392                if self.tool.matchString(printername, [ printerpattern ]) :
393                    printer = StoragePrinter(self, printername)
394                    printer.ident = printerid
395                    printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
396                    printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
397                    printer.LastJob = self.getPrinterLastJob(printer)
398                    printer.Exists = 1
399                    printers.append(printer)
400        return printers       
[1016]401       
[1041]402    def getPrinterUsersAndQuotas(self, printer, names=None) :       
403        """Returns the list of users who uses a given printer, along with their quotas."""
404        usersandquotas = []
405        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s))" % printer.Name, ["pykotaUserName", "pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
406        if result :
407            for (userquotaid, fields) in result :
408                user = self.getUser(fields["pykotaUserName"][0])
409                if (names is None) or self.tool.matchString(user.Name, names) :
410                    userpquota = StorageUserPQuota(self, user, printer)
411                    userpquota.ident = userquotaid
412                    userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
413                    userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
414                    userpquota.SoftLimit = fields.get("pykotaSoftLimit")
415                    if userpquota.SoftLimit is not None :
416                        if userpquota.SoftLimit[0].upper() == "NONE" :
417                            userpquota.SoftLimit = None
418                        else :   
419                            userpquota.SoftLimit = int(userpquota.SoftLimit[0])
420                    userpquota.HardLimit = fields.get("pykotaHardLimit")
421                    if userpquota.HardLimit is not None :
422                        if userpquota.HardLimit[0].upper() == "NONE" :
423                            userpquota.HardLimit = None
424                        elif userpquota.HardLimit is not None :   
425                            userpquota.HardLimit = int(userpquota.HardLimit[0])
426                    userpquota.DateLimit = fields.get("pykotaDateLimit")
427                    if userpquota.DateLimit is not None :
428                        if userpquota.DateLimit[0].upper() == "NONE" : 
429                            userpquota.DateLimit = None
430                        else :   
431                            userpquota.DateLimit = userpquota.DateLimit[0]
432                    userpquota.Exists = 1
433                    usersandquotas.append((user, userpquota))
[1051]434        usersandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
[1041]435        return usersandquotas
436               
437    def getPrinterGroupsAndQuotas(self, printer, names=None) :       
438        """Returns the list of groups which uses a given printer, along with their quotas."""
439        groupsandquotas = []
440        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s))" % printer.Name, ["pykotaGroupName"], base=self.info["groupquotabase"])
441        if result :
442            for (groupquotaid, fields) in result :
443                group = self.getGroup(fields.get("pykotaGroupName")[0])
[1068]444                if (names is None) or self.tool.matchString(group.Name, names) :
[1041]445                    grouppquota = self.getGroupPQuota(group, printer)
446                    groupsandquotas.append((group, grouppquota))
[1051]447        groupsandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
[1041]448        return groupsandquotas
[1016]449       
450    def addPrinter(self, printername) :       
[1041]451        """Adds a printer to the quota storage, returns it."""
[1030]452        fields = { self.info["printerrdn"] : printername,
453                   "objectClass" : ["pykotaObject", "pykotaPrinter"],
[1041]454                   "cn" : printername,
[1030]455                   "pykotaPrinterName" : printername,
456                   "pykotaPricePerPage" : "0.0",
457                   "pykotaPricePerJob" : "0.0",
458                 } 
459        dn = "%s=%s,%s" % (self.info["printerrdn"], printername, self.info["printerbase"])
[1041]460        self.doAdd(dn, fields)
461        return self.getPrinter(printername)
[1016]462       
[1041]463    def addUser(self, user) :       
464        """Adds a user to the quota storage, returns it."""
465        fields = { self.info["userrdn"] : user.Name,
[1081]466                   "objectClass" : ["pykotaObject", "pykotaAccount", "pykotaAccountBalance"],
[1041]467                   "cn" : user.Name,
468                   "pykotaUserName" : user.Name,
469                   "pykotaLimitBY" : (user.LimitBy or "quota"),
470                   "pykotaBalance" : str(user.AccountBalance or 0.0),
471                   "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0),
472                 } 
[1081]473        dn = "%s=%s,%s" % (self.info["userrdn"], user.Name, self.info["userbase"])
[1041]474        self.doAdd(dn, fields)
475        return self.getUser(user.Name)
[1016]476       
[1041]477    def addGroup(self, group) :       
478        """Adds a group to the quota storage, returns it."""
479        fields = { self.info["grouprdn"] : group.Name,
[1030]480                   "objectClass" : ["pykotaObject", "pykotaGroup"],
[1041]481                   "cn" : group.Name,
482                   "pykotaGroupName" : group.Name,
483                   "pykotaLimitBY" : (group.LimitBy or "quota"),
[1030]484                 } 
[1041]485        dn = "%s=%s,%s" % (self.info["grouprdn"], group.Name, self.info["groupbase"])
486        self.doAdd(dn, fields)
487        return self.getGroup(group.Name)
[1016]488       
[1041]489    def addUserToGroup(self, user, group) :   
490        """Adds an user to a group."""
491        if user.Name not in [u.Name for u in group.Members] :
492            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
493            if result :
494                fields = result[0][1]
[1070]495                if not fields.has_key(self.info["groupmembers"]) :
496                    fields[self.info["groupmembers"]] = []
[1041]497                fields[self.info["groupmembers"]].append(user.Name)
498                self.doModify(group.ident, fields)
499                group.Members.append(user)
500               
501    def addUserPQuota(self, user, printer) :
502        """Initializes a user print quota on a printer."""
[1030]503        uuid = self.genUUID()
[1041]504        fields = { "cn" : uuid,
505                   "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
506                   "pykotaUserName" : user.Name,
507                   "pykotaPrinterName" : printer.Name,
508                   "pykotaDateLimit" : "None",
[1030]509                   "pykotaPageCounter" : "0",
510                   "pykotaLifePageCounter" : "0",
511                 } 
512        dn = "cn=%s,%s" % (uuid, self.info["userquotabase"])
[1031]513        self.doAdd(dn, fields)
[1041]514        return self.getUserPQuota(user, printer)
[1016]515       
[1041]516    def addGroupPQuota(self, group, printer) :
517        """Initializes a group print quota on a printer."""
[1030]518        uuid = self.genUUID()
[1041]519        fields = { "cn" : uuid,
520                   "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
521                   "pykotaGroupName" : group.Name,
522                   "pykotaPrinterName" : printer.Name,
[1030]523                   "pykotaDateLimit" : "None",
524                 } 
525        dn = "cn=%s,%s" % (uuid, self.info["groupquotabase"])
[1031]526        self.doAdd(dn, fields)
[1041]527        return self.getGroupPQuota(group, printer)
[1016]528       
[1041]529    def writePrinterPrices(self, printer) :   
530        """Write the printer's prices back into the storage."""
531        fields = {
532                   "pykotaPricePerPage" : str(printer.PricePerPage),
533                   "pykotaPricePerJob" : str(printer.PricePerJob),
534                 }
535        self.doModify(printer.ident, fields)
[1016]536       
[1041]537    def writeUserLimitBy(self, user, limitby) :   
538        """Sets the user's limiting factor."""
[1031]539        fields = {
[1041]540                   "pykotaLimitBy" : limitby,
[1031]541                 }
[1041]542        self.doModify(user.ident, fields)         
[1016]543       
[1041]544    def writeGroupLimitBy(self, group, limitby) :   
545        """Sets the group's limiting factor."""
[1031]546        fields = {
[1041]547                   "pykotaLimitBy" : limitby,
[1031]548                 }
[1041]549        self.doModify(group.ident, fields)         
[1016]550       
[1041]551    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
552        """Sets the date limit permanently for a user print quota."""
[1031]553        fields = {
554                   "pykotaDateLimit" : "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second),
555                 }
[1041]556        return self.doModify(userpquota.ident, fields)
557           
558    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
559        """Sets the date limit permanently for a group print quota."""
[1031]560        fields = {
561                   "pykotaDateLimit" : "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second),
562                 }
[1041]563        return self.doModify(grouppquota.ident, fields)
[1016]564       
[1041]565    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
566        """Sets the new page counters permanently for a user print quota."""
567        fields = {
568                   "pykotaPageCounter" : str(newpagecounter),
569                   "pykotaLifePageCounter" : str(newlifepagecounter),
570                 } 
571        return self.doModify(userpquota.ident, fields)         
572       
573    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
574        """Sets the new account balance and eventually new lifetime paid."""
575        fields = {
576                   "pykotaBalance" : str(newbalance),
577                 }
578        if newlifetimepaid is not None :
579            fields.update({ "pykotaLifeTimePaid" : str(newlifetimepaid) })
580        return self.doModify(user.idbalance, fields)         
581           
582    def writeLastJobSize(self, lastjob, jobsize) :       
583        """Sets the last job's size permanently."""
584        fields = {
585                   "pykotaJobSize" : str(jobsize),
586                 }
587        self.doModify(lastjob.ident, fields)         
588       
589    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None) :   
590        """Adds a job in a printer's history."""
[1032]591        uuid = self.genUUID()
592        fields = {
593                   "objectClass" : ["pykotaObject", "pykotaJob"],
594                   "cn" : uuid,
[1041]595                   "pykotaUserName" : user.Name,
596                   "pykotaPrinterName" : printer.Name,
[1032]597                   "pykotaJobId" : jobid,
598                   "pykotaPrinterPageCounter" : str(pagecounter),
599                   "pykotaAction" : action,
600                 }
601        if jobsize is not None :         
602            fields.update({ "pykotaJobSize" : str(jobsize) })
603        dn = "cn=%s,%s" % (uuid, self.info["jobbase"])
604        self.doAdd(dn, fields)
[1041]605        if printer.LastJob.Exists :
[1032]606            fields = {
607                       "pykotaLastJobIdent" : uuid,
608                     }
[1041]609            self.doModify(printer.LastJob.lastjobident, fields)         
[1032]610        else :   
611            lastjuuid = self.genUUID()
[1067]612            lastjdn = "cn=%s,%s" % (lastjuuid, self.info["lastjobbase"])
[1032]613            fields = {
614                       "objectClass" : ["pykotaObject", "pykotaLastJob"],
615                       "cn" : lastjuuid,
[1041]616                       "pykotaPrinterName" : printer.Name,
[1032]617                       "pykotaLastJobIdent" : uuid,
618                     } 
619            self.doAdd(lastjdn, fields)         
[1041]620           
621    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
622        """Sets soft and hard limits for a user quota."""
623        fields = { 
624                   "pykotaSoftLimit" : str(softlimit),
625                   "pykotaHardLimit" : str(hardlimit),
626                 }
627        self.doModify(userpquota.ident, fields)
628       
629    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
[1084]630        """Sets soft and hard limits for a group quota on a specific printer."""
[1041]631        fields = { 
632                   "pykotaSoftLimit" : str(softlimit),
633                   "pykotaHardLimit" : str(hardlimit),
634                 }
635        self.doModify(grouppquota.ident, fields)
636           
637    def deleteUser(self, user) :   
638        """Completely deletes an user from the Quota Storage."""
639        # TODO : What should we do if we delete the last person who used a given printer ?
640        # TODO : we can't reassign the last job to the previous one, because next user would be
641        # TODO : incorrectly charged (overcharged).
642        result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaUserName=%s))" % user.Name, base=self.info["lastjobbase"])
643        for (ident, fields) in result :
644            self.doDelete(ident)
645        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s))" % user.Name, base=self.info["jobbase"])
646        for (ident, fields) in result :
647            self.doDelete(ident)
648        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["userquotabase"])
649        for (ident, fields) in result :
650            self.doDelete(ident)
651        result = self.doSearch("objectClass=pykotaAccount", None, base=user.ident, scope=ldap.SCOPE_BASE)   
[1032]652        if result :
[1041]653            fields = result[0][1]
654            for k in fields.keys() :
655                if k.startswith("pykota") :
656                    del fields[k]
657                elif k.lower() == "objectclass" :   
658                    todelete = []
659                    for i in range(len(fields[k])) :
660                        if fields[k][i].startswith("pykota") : 
661                            todelete.append(i)
662                    todelete.sort()       
663                    todelete.reverse()
664                    for i in todelete :
665                        del fields[k][i]
666            if fields.get("objectclass") :           
667                self.doModify(user.ident, fields, ignoreold=0)       
668            else :   
669                self.doDelete(user.ident)
670        result = self.doSearch("(&(objectClass=pykotaAccountBalance)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["balancebase"])
671        for (ident, fields) in result :
672            self.doDelete(ident)
673       
674    def deleteGroup(self, group) :   
675        """Completely deletes a group from the Quota Storage."""
676        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s))" % group.Name, ["pykotaGroupName"], base=self.info["groupquotabase"])
677        for (ident, fields) in result :
678            self.doDelete(ident)
679        result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
[1016]680        if result :
[1027]681            fields = result[0][1]
[1041]682            for k in fields.keys() :
683                if k.startswith("pykota") :
684                    del fields[k]
685                elif k.lower() == "objectclass" :   
686                    todelete = []
687                    for i in range(len(fields[k])) :
688                        if fields[k][i].startswith("pykota") : 
689                            todelete.append(i)
690                    todelete.sort()       
691                    todelete.reverse()
692                    for i in todelete :
693                        del fields[k][i]
694            if fields.get("objectclass") :           
695                self.doModify(group.ident, fields, ignoreold=0)       
696            else :   
697                self.doDelete(group.ident)
698           
Note: See TracBrowser for help on using the browser.