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

Revision 1062, 33.5 kB (checked in by jalet, 21 years ago)

The previous bug fix was incomplete.

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