root / pykota / trunk / pykota / storage.py @ 2733

Revision 2733, 34.4 kB (checked in by jerome, 18 years ago)

Improved cache flush for user and group print quota entries.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25from mx import DateTime
26
27class PyKotaStorageError(Exception):
28    """An exception for database related stuff."""
29    def __init__(self, message = ""):
30        self.message = message
31        Exception.__init__(self, message)
32    def __repr__(self):
33        return self.message
34    __str__ = __repr__
35       
36class StorageObject :
37    """Object present in the database."""
38    def __init__(self, parent) :
39        "Initialize minimal data."""
40        self.parent = parent
41        self.ident = None
42        self.Description = None
43        self.isDirty = False
44        self.Exists = False
45       
46    def setDescription(self, description=None) :
47        """Sets the object's description."""
48        if description is not None :
49            self.Description = str(description)
50            self.isDirty = True   
51           
52    def save(self) :       
53        """Saves the object to the database."""
54        if self.isDirty :
55            getattr(self.parent, "save%s" % self.__class__.__name__[7:])(self)
56            self.isDirty = False
57       
58class StorageUser(StorageObject) :       
59    """User class."""
60    def __init__(self, parent, name) :
61        StorageObject.__init__(self, parent)
62        self.Name = name
63        self.LimitBy = None
64        self.AccountBalance = None
65        self.LifeTimePaid = None
66        self.Email = None
67        self.OverCharge = 1.0
68        self.Payments = [] # TODO : maybe handle this smartly for SQL, for now just don't retrieve them
69       
70    def consumeAccountBalance(self, amount) :     
71        """Consumes an amount of money from the user's account balance."""
72        self.parent.decreaseUserAccountBalance(self, amount)
73        self.AccountBalance = float(self.AccountBalance or 0.0) - amount
74       
75    def setAccountBalance(self, balance, lifetimepaid, comment="") :
76        """Sets the user's account balance in case he pays more money."""
77        diff = float(lifetimepaid or 0.0) - float(self.LifeTimePaid or 0.0)
78        self.AccountBalance = balance
79        self.LifeTimePaid = lifetimepaid
80        self.parent.writeNewPayment(self, diff, comment)
81        self.isDirty = True
82       
83    def setLimitBy(self, limitby) :   
84        """Sets the user's limiting factor."""
85        try :
86            limitby = limitby.lower()
87        except AttributeError :   
88            limitby = "quota"
89        if limitby in ["quota", "balance", \
90                       "noquota", "noprint", "nochange"] :
91            self.LimitBy = limitby
92            self.isDirty = True
93       
94    def setOverChargeFactor(self, factor) :   
95        """Sets the user's overcharging coefficient."""
96        self.OverCharge = factor
97        self.isDirty = True
98       
99    def delete(self) :   
100        """Deletes an user from the database."""
101        self.parent.beginTransaction()
102        try :
103            self.parent.deleteUser(self)
104        except PyKotaStorageError, msg :   
105            self.parent.rollbackTransaction()
106            raise PyKotaStorageError, msg
107        else :   
108            self.parent.commitTransaction()
109            self.parent.flushEntry("USERS", self.Name)
110            if self.parent.usecache :
111                for (k, v) in self.parent.caches["USERPQUOTAS"].items() :
112                    if v.User.Name == self.Name :
113                        self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (v.User.Name, v.Printer.Name))
114            self.Exists = 0
115       
116class StorageGroup(StorageObject) :       
117    """User class."""
118    def __init__(self, parent, name) :
119        StorageObject.__init__(self, parent)
120        self.Name = name
121        self.LimitBy = None
122        self.AccountBalance = None
123        self.LifeTimePaid = None
124       
125    def setLimitBy(self, limitby) :   
126        """Sets the user's limiting factor."""
127        try :
128            limitby = limitby.lower()
129        except AttributeError :   
130            limitby = "quota"
131        if limitby in ["quota", "balance", "noquota"] :
132            self.LimitBy = limitby
133            self.isDirty = True
134       
135    def addUserToGroup(self, user) :
136        """Adds an user to an users group."""
137        self.parent.addUserToGroup(user, self)
138       
139    def delUserFromGroup(self, user) :
140        """Removes an user from an users group."""
141        self.parent.delUserFromGroup(user, self)
142       
143    def delete(self) :   
144        """Deletes a group from the database."""
145        self.parent.beginTransaction()
146        try :
147            self.parent.deleteGroup(self)
148        except PyKotaStorageError, msg :   
149            self.parent.rollbackTransaction()
150            raise PyKotaStorageError, msg
151        else :   
152            self.parent.commitTransaction()
153            self.parent.flushEntry("GROUPS", self.Name)
154            if self.parent.usecache :
155                for (k, v) in self.parent.caches["GROUPPQUOTAS"].items() :
156                    if v.Group.Name == self.Name :
157                        self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (v.Group.Name, v.Printer.Name))
158            self.Exists = 0
159       
160class StoragePrinter(StorageObject) :
161    """Printer class."""
162    def __init__(self, parent, name) :
163        StorageObject.__init__(self, parent)
164        self.Name = name
165        self.PricePerPage = None
166        self.PricePerJob = None
167        self.MaxJobSize = None
168        self.PassThrough = None
169        self.Coefficients = None
170       
171    def __getattr__(self, name) :   
172        """Delays data retrieval until it's really needed."""
173        if name == "LastJob" : 
174            self.LastJob = self.parent.getPrinterLastJob(self)
175            return self.LastJob
176        else :
177            raise AttributeError, name
178           
179    def addJobToHistory(self, jobid, user, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None, jobmd5sum=None, jobpages=None, jobbilling=None, precomputedsize=None, precomputedprice=None) :
180        """Adds a job to the printer's history."""
181        self.parent.writeJobNew(self, user, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options, clienthost, jobsizebytes, jobmd5sum, jobpages, jobbilling, precomputedsize, precomputedprice)
182        # TODO : update LastJob object ? Probably not needed.
183       
184    def addPrinterToGroup(self, printer) :   
185        """Adds a printer to a printer group."""
186        if (printer not in self.parent.getParentPrinters(self)) and (printer.ident != self.ident) :
187            self.parent.writePrinterToGroup(self, printer)
188            # TODO : reset cached value for printer parents, or add new parent to cached value
189           
190    def delPrinterFromGroup(self, printer) :   
191        """Deletes a printer from a printer group."""
192        self.parent.removePrinterFromGroup(self, printer)
193        # TODO : reset cached value for printer parents, or add new parent to cached value
194       
195    def setPrices(self, priceperpage = None, priceperjob = None) :   
196        """Sets the printer's prices."""
197        if priceperpage is None :
198            priceperpage = self.PricePerPage or 0.0
199        else :   
200            self.PricePerPage = float(priceperpage)
201        if priceperjob is None :   
202            priceperjob = self.PricePerJob or 0.0
203        else :   
204            self.PricePerJob = float(priceperjob)
205        self.isDirty = True   
206       
207    def setPassThrough(self, passthrough) :
208        """Sets the printer's passthrough mode."""
209        self.PassThrough = passthrough
210        self.isDirty = True
211       
212    def setMaxJobSize(self, maxjobsize) :
213        """Sets the printer's maximal job size."""
214        self.MaxJobSize = maxjobsize
215        self.isDirty = True
216       
217    def delete(self) :   
218        """Deletes a printer from the database."""
219        self.parent.beginTransaction()
220        try :
221            self.parent.deletePrinter(self)
222        except PyKotaStorageError, msg :   
223            self.parent.rollbackTransaction()
224            raise PyKotaStorageError, msg
225        else :   
226            self.parent.commitTransaction()
227            self.parent.flushEntry("PRINTERS", self.Name)
228            if self.parent.usecache :
229                for (k, v) in self.parent.caches["USERPQUOTAS"].items() :
230                    if v.Printer.Name == self.Name :
231                        self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (v.User.Name, v.Printer.Name))
232                for (k, v) in self.parent.caches["GROUPPQUOTAS"].items() :
233                    if v.Printer.Name == self.Name :
234                        self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (v.Group.Name, v.Printer.Name))
235            self.isDirty = False           
236            self.Exists = False
237       
238class StorageUserPQuota(StorageObject) :
239    """User Print Quota class."""
240    def __init__(self, parent, user, printer) :
241        StorageObject.__init__(self, parent)
242        self.User = user
243        self.Printer = printer
244        self.PageCounter = None
245        self.LifePageCounter = None
246        self.SoftLimit = None
247        self.HardLimit = None
248        self.DateLimit = None
249        self.WarnCount = None
250        self.MaxJobSize = None
251       
252    def __getattr__(self, name) :   
253        """Delays data retrieval until it's really needed."""
254        if name == "ParentPrintersUserPQuota" : 
255            self.ParentPrintersUserPQuota = (self.User.Exists and self.Printer.Exists and self.parent.getParentPrintersUserPQuota(self)) or []
256            return self.ParentPrintersUserPQuota
257        else :
258            raise AttributeError, name
259       
260    def setDateLimit(self, datelimit) :   
261        """Sets the date limit for this quota."""
262        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
263        self.parent.writeUserPQuotaDateLimit(self, date)
264        self.DateLimit = date
265       
266    def setLimits(self, softlimit, hardlimit) :   
267        """Sets the soft and hard limit for this quota."""
268        self.parent.writeUserPQuotaLimits(self, softlimit, hardlimit)
269        self.SoftLimit = softlimit
270        self.HardLimit = hardlimit
271        self.DateLimit = None
272        self.WarnCount = 0
273       
274    def setUsage(self, used) :
275        """Sets the PageCounter and LifePageCounter to used, or if used is + or - prefixed, changes the values of {Life,}PageCounter by that amount."""
276        vused = int(used)
277        if used.startswith("+") or used.startswith("-") :
278            self.parent.beginTransaction()
279            try :
280                self.parent.increaseUserPQuotaPagesCounters(self, vused)
281                self.parent.writeUserPQuotaDateLimit(self, None)
282                self.parent.writeUserPQuotaWarnCount(self, 0)
283            except PyKotaStorageError, msg :   
284                self.parent.rollbackTransaction()
285                raise PyKotaStorageError, msg
286            else :
287                self.parent.commitTransaction()
288            self.PageCounter += vused
289            self.LifePageCounter += vused
290        else :
291            self.parent.writeUserPQuotaPagesCounters(self, vused, vused)
292            self.PageCounter = self.LifePageCounter = vused
293        self.DateLimit = None
294        self.WarnCount = 0
295
296    def incDenyBannerCounter(self) :
297        """Increment the deny banner counter for this user quota."""
298        self.parent.increaseUserPQuotaWarnCount(self)
299        self.WarnCount = (self.WarnCount or 0) + 1
300       
301    def resetDenyBannerCounter(self) :
302        """Resets the deny banner counter for this user quota."""
303        self.parent.writeUserPQuotaWarnCount(self, 0)
304        self.WarnCount = 0
305       
306    def reset(self) :   
307        """Resets page counter to 0."""
308        self.parent.writeUserPQuotaPagesCounters(self, 0, int(self.LifePageCounter or 0))
309        self.PageCounter = 0
310        self.DateLimit = None
311       
312    def hardreset(self) :   
313        """Resets actual and life time page counters to 0."""
314        self.parent.writeUserPQuotaPagesCounters(self, 0, 0)
315        self.PageCounter = self.LifePageCounter = 0
316        self.DateLimit = None
317       
318    def computeJobPrice(self, jobsize) :   
319        """Computes the job price as the sum of all parent printers' prices + current printer's ones."""
320        totalprice = 0.0   
321        if jobsize :
322            if self.User.OverCharge != 0.0 :    # optimization, but TODO : beware of rounding errors
323                for upq in [ self ] + self.ParentPrintersUserPQuota :
324                    price = (float(upq.Printer.PricePerPage or 0.0) * jobsize) + float(upq.Printer.PricePerJob or 0.0)
325                    totalprice += price
326        if self.User.OverCharge != 1.0 : # TODO : beware of rounding errors
327            overcharged = totalprice * self.User.OverCharge       
328            self.parent.tool.logdebug("Overcharging %s by a factor of %s ===> User %s will be charged for %s units." % (totalprice, self.User.OverCharge, self.User.Name, overcharged))
329            return overcharged
330        else :   
331            return totalprice
332           
333    def increasePagesUsage(self, jobsize) :
334        """Increase the value of used pages and money."""
335        jobprice = self.computeJobPrice(jobsize)
336        if jobsize :
337            if jobprice :
338                self.User.consumeAccountBalance(jobprice)
339            for upq in [ self ] + self.ParentPrintersUserPQuota :
340                self.parent.increaseUserPQuotaPagesCounters(upq, jobsize)
341                upq.PageCounter = int(upq.PageCounter or 0) + jobsize
342                upq.LifePageCounter = int(upq.LifePageCounter or 0) + jobsize
343        return jobprice
344       
345    def delete(self) :   
346        """Deletes an user print quota entry from the database."""
347        self.parent.beginTransaction()
348        try :
349            self.parent.deleteUserPQuota(self)
350        except PyKotaStorageError, msg :   
351            self.parent.rollbackTransaction()
352            raise PyKotaStorageError, msg
353        else :   
354            self.parent.commitTransaction()
355            if self.parent.usecache :
356                self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (self.User.Name, self.Printer.Name))
357            self.Exists = 0
358       
359class StorageGroupPQuota(StorageObject) :
360    """Group Print Quota class."""
361    def __init__(self, parent, group, printer) :
362        StorageObject.__init__(self, parent)
363        self.Group = group
364        self.Printer = printer
365        self.PageCounter = None
366        self.LifePageCounter = None
367        self.SoftLimit = None
368        self.HardLimit = None
369        self.DateLimit = None
370        self.MaxJobSize = None
371       
372    def __getattr__(self, name) :   
373        """Delays data retrieval until it's really needed."""
374        if name == "ParentPrintersGroupPQuota" : 
375            self.ParentPrintersGroupPQuota = (self.Group.Exists and self.Printer.Exists and self.parent.getParentPrintersGroupPQuota(self)) or []
376            return self.ParentPrintersGroupPQuota
377        else :
378            raise AttributeError, name
379       
380    def reset(self) :   
381        """Resets page counter to 0."""
382        self.parent.beginTransaction()
383        try :
384            for user in self.parent.getGroupMembers(self.Group) :
385                uq = self.parent.getUserPQuota(user, self.Printer)
386                uq.reset()
387            self.parent.writeGroupPQuotaDateLimit(self, None)
388        except PyKotaStorageError, msg :   
389            self.parent.rollbackTransaction()
390            raise PyKotaStorageError, msg
391        else :   
392            self.parent.commitTransaction()
393        self.PageCounter = 0
394        self.DateLimit = None
395       
396    def hardreset(self) :   
397        """Resets actual and life time page counters to 0."""
398        self.parent.beginTransaction()
399        try :
400            for user in self.parent.getGroupMembers(self.Group) :
401                uq = self.parent.getUserPQuota(user, self.Printer)
402                uq.hardreset()
403            self.parent.writeGroupPQuotaDateLimit(self, None)
404        except PyKotaStorageError, msg :   
405            self.parent.rollbackTransaction()
406            raise PyKotaStorageError, msg
407        else :   
408            self.parent.commitTransaction()
409        self.PageCounter = self.LifePageCounter = 0
410        self.DateLimit = None
411       
412    def setDateLimit(self, datelimit) :   
413        """Sets the date limit for this quota."""
414        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, \
415                                                  datelimit.month, \
416                                                  datelimit.day, \
417                                                  datelimit.hour, \
418                                                  datelimit.minute, \
419                                                  datelimit.second)
420        self.parent.writeGroupPQuotaDateLimit(self, date)
421        self.DateLimit = date
422       
423    def setLimits(self, softlimit, hardlimit) :   
424        """Sets the soft and hard limit for this quota."""
425        self.parent.writeGroupPQuotaLimits(self, softlimit, hardlimit)
426        self.SoftLimit = softlimit
427        self.HardLimit = hardlimit
428        self.DateLimit = None
429       
430    def delete(self) :   
431        """Deletes a group print quota entry from the database."""
432        self.parent.beginTransaction()
433        try :
434            self.parent.deleteGroupPQuota(self)
435        except PyKotaStorageError, msg :   
436            self.parent.rollbackTransaction()
437            raise PyKotaStorageError, msg
438        else :   
439            self.parent.commitTransaction()
440            if self.parent.usecache :
441                self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (self.Group.Name, self.Printer.Name))
442            self.Exists = 0
443       
444class StorageJob(StorageObject) :
445    """Printer's Job class."""
446    def __init__(self, parent) :
447        StorageObject.__init__(self, parent)
448        self.UserName = None
449        self.PrinterName = None
450        self.JobId = None
451        self.PrinterPageCounter = None
452        self.JobSizeBytes = None
453        self.JobSize = None
454        self.JobAction = None
455        self.JobDate = None
456        self.JobPrice = None
457        self.JobFileName = None
458        self.JobTitle = None
459        self.JobCopies = None
460        self.JobOptions = None
461        self.JobHostName = None
462        self.JobMD5Sum = None
463        self.JobPages = None
464        self.JobBillingCode = None
465        self.PrecomputedJobSize = None
466        self.PrecomputedJobPrice = None
467       
468    def __getattr__(self, name) :   
469        """Delays data retrieval until it's really needed."""
470        if name == "User" : 
471            self.User = self.parent.getUser(self.UserName)
472            return self.User
473        elif name == "Printer" :   
474            self.Printer = self.parent.getPrinter(self.PrinterName)
475            return self.Printer
476        else :
477            raise AttributeError, name
478       
479class StorageLastJob(StorageJob) :
480    """Printer's Last Job class."""
481    def __init__(self, parent, printer) :
482        StorageJob.__init__(self, parent)
483        self.PrinterName = printer.Name # not needed
484        self.Printer = printer
485       
486class StorageBillingCode(StorageObject) :
487    """Billing code class."""
488    def __init__(self, parent, name) :
489        StorageObject.__init__(self, parent)
490        self.BillingCode = name
491        self.PageCounter = None
492        self.Balance = None
493       
494    def delete(self) :   
495        """Deletes the billing code from the database."""
496        self.parent.deleteBillingCode(self)
497        self.parent.flushEntry("BILLINGCODES", self.BillingCode)
498        self.isDirty = False
499        self.Exists = False
500       
501    def reset(self, balance=0.0, pagecounter=0) :   
502        """Resets the pagecounter and balance for this billing code."""
503        self.Balance = balance
504        self.PageCounter = pagecounter
505        self.isDirty = True
506       
507    def consume(self, pages, price) :
508        """Consumes some pages and credits for this billing code."""
509        if pages :
510           self.parent.consumeBillingCode(self, pages, price)
511           self.PageCounter += pages
512           self.Balance -= price
513       
514class BaseStorage :
515    def __init__(self, pykotatool) :
516        """Opens the storage connection."""
517        self.closed = 1
518        self.tool = pykotatool
519        self.usecache = pykotatool.config.getCaching()
520        self.disablehistory = pykotatool.config.getDisableHistory()
521        self.privacy = pykotatool.config.getPrivacy()
522        if self.privacy :
523            pykotatool.logdebug("Jobs' title, filename and options will be hidden because of privacy concerns.")
524        if self.usecache :
525            self.tool.logdebug("Caching enabled.")
526            self.caches = { "USERS" : {}, \
527                            "GROUPS" : {}, \
528                            "PRINTERS" : {}, \
529                            "USERPQUOTAS" : {}, \
530                            "GROUPPQUOTAS" : {}, \
531                            "JOBS" : {}, \
532                            "LASTJOBS" : {}, \
533                            "BILLINGCODES" : {} }
534       
535    def close(self) :   
536        """Must be overriden in children classes."""
537        raise RuntimeError, "BaseStorage.close() must be overriden !"
538       
539    def __del__(self) :       
540        """Ensures that the database connection is closed."""
541        self.close()
542       
543    def getFromCache(self, cachetype, key) :
544        """Tries to extract something from the cache."""
545        if self.usecache :
546            entry = self.caches[cachetype].get(key)
547            if entry is not None :
548                self.tool.logdebug("Cache hit (%s->%s)" % (cachetype, key))
549            else :   
550                self.tool.logdebug("Cache miss (%s->%s)" % (cachetype, key))
551            return entry   
552           
553    def cacheEntry(self, cachetype, key, value) :       
554        """Puts an entry in the cache."""
555        if self.usecache and getattr(value, "Exists", 0) :
556            self.caches[cachetype][key] = value
557            self.tool.logdebug("Cache store (%s->%s)" % (cachetype, key))
558           
559    def flushEntry(self, cachetype, key) :       
560        """Removes an entry from the cache."""
561        if self.usecache :
562            try :
563                del self.caches[cachetype][key]
564            except KeyError :   
565                pass
566            else :   
567                self.tool.logdebug("Cache flush (%s->%s)" % (cachetype, key))
568           
569    def getUser(self, username) :       
570        """Returns the user from cache."""
571        user = self.getFromCache("USERS", username)
572        if user is None :
573            user = self.getUserFromBackend(username)
574            self.cacheEntry("USERS", username, user)
575        return user   
576       
577    def getGroup(self, groupname) :       
578        """Returns the group from cache."""
579        group = self.getFromCache("GROUPS", groupname)
580        if group is None :
581            group = self.getGroupFromBackend(groupname)
582            self.cacheEntry("GROUPS", groupname, group)
583        return group   
584       
585    def getPrinter(self, printername) :       
586        """Returns the printer from cache."""
587        printer = self.getFromCache("PRINTERS", printername)
588        if printer is None :
589            printer = self.getPrinterFromBackend(printername)
590            self.cacheEntry("PRINTERS", printername, printer)
591        return printer   
592       
593    def getUserPQuota(self, user, printer) :       
594        """Returns the user quota information from cache."""
595        useratprinter = "%s@%s" % (user.Name, printer.Name)
596        upquota = self.getFromCache("USERPQUOTAS", useratprinter)
597        if upquota is None :
598            upquota = self.getUserPQuotaFromBackend(user, printer)
599            self.cacheEntry("USERPQUOTAS", useratprinter, upquota)
600        return upquota   
601       
602    def getGroupPQuota(self, group, printer) :       
603        """Returns the group quota information from cache."""
604        groupatprinter = "%s@%s" % (group.Name, printer.Name)
605        gpquota = self.getFromCache("GROUPPQUOTAS", groupatprinter)
606        if gpquota is None :
607            gpquota = self.getGroupPQuotaFromBackend(group, printer)
608            self.cacheEntry("GROUPPQUOTAS", groupatprinter, gpquota)
609        return gpquota   
610       
611    def getPrinterLastJob(self, printer) :       
612        """Extracts last job information for a given printer from cache."""
613        lastjob = self.getFromCache("LASTJOBS", printer.Name)
614        if lastjob is None :
615            lastjob = self.getPrinterLastJobFromBackend(printer)
616            self.cacheEntry("LASTJOBS", printer.Name, lastjob)
617        return lastjob   
618       
619    def getBillingCode(self, label) :       
620        """Returns the user from cache."""
621        code = self.getFromCache("BILLINGCODES", label)
622        if code is None :
623            code = self.getBillingCodeFromBackend(label)
624            self.cacheEntry("BILLINGCODES", label, code)
625        return code
626       
627    def getParentPrinters(self, printer) :   
628        """Extracts parent printers information for a given printer from cache."""
629        if self.usecache :
630            if not hasattr(printer, "Parents") :
631                self.tool.logdebug("Cache miss (%s->Parents)" % printer.Name)
632                printer.Parents = self.getParentPrintersFromBackend(printer)
633                self.tool.logdebug("Cache store (%s->Parents)" % printer.Name)
634            else :
635                self.tool.logdebug("Cache hit (%s->Parents)" % printer.Name)
636        else :       
637            printer.Parents = self.getParentPrintersFromBackend(printer)
638        for parent in printer.Parents[:] :   
639            printer.Parents.extend(self.getParentPrinters(parent))
640        uniquedic = {}   
641        for parent in printer.Parents :
642            uniquedic[parent.Name] = parent
643        printer.Parents = uniquedic.values()   
644        return printer.Parents
645       
646    def getGroupMembers(self, group) :       
647        """Returns the group's members list from in-group cache."""
648        if self.usecache :
649            if not hasattr(group, "Members") :
650                self.tool.logdebug("Cache miss (%s->Members)" % group.Name)
651                group.Members = self.getGroupMembersFromBackend(group)
652                self.tool.logdebug("Cache store (%s->Members)" % group.Name)
653            else :
654                self.tool.logdebug("Cache hit (%s->Members)" % group.Name)
655        else :       
656            group.Members = self.getGroupMembersFromBackend(group)
657        return group.Members   
658       
659    def getUserGroups(self, user) :       
660        """Returns the user's groups list from in-user cache."""
661        if self.usecache :
662            if not hasattr(user, "Groups") :
663                self.tool.logdebug("Cache miss (%s->Groups)" % user.Name)
664                user.Groups = self.getUserGroupsFromBackend(user)
665                self.tool.logdebug("Cache store (%s->Groups)" % user.Name)
666            else :
667                self.tool.logdebug("Cache hit (%s->Groups)" % user.Name)
668        else :       
669            user.Groups = self.getUserGroupsFromBackend(user)
670        return user.Groups   
671       
672    def getParentPrintersUserPQuota(self, userpquota) :     
673        """Returns all user print quota on the printer and all its parents recursively."""
674        upquotas = [ ]
675        for printer in self.getParentPrinters(userpquota.Printer) :
676            upq = self.getUserPQuota(userpquota.User, printer)
677            if upq.Exists :
678                upquotas.append(upq)
679        return upquotas       
680       
681    def getParentPrintersGroupPQuota(self, grouppquota) :     
682        """Returns all group print quota on the printer and all its parents recursively."""
683        gpquotas = [ ]
684        for printer in self.getParentPrinters(grouppquota.Printer) :
685            gpq = self.getGroupPQuota(grouppquota.Group, printer)
686            if gpq.Exists :
687                gpquotas.append(gpq)
688        return gpquotas       
689       
690    def databaseToUserCharset(self, text) :
691        """Converts from database format (UTF-8) to user's charset."""
692        if text is not None :
693            try :
694                return unicode(text, "UTF-8").encode(self.tool.getCharset()) 
695            except UnicodeError :   
696                try :
697                    # Incorrect locale settings ?
698                    return unicode(text, "UTF-8").encode("ISO-8859-15") 
699                except UnicodeError :   
700                    pass
701        return text
702       
703    def userCharsetToDatabase(self, text) :
704        """Converts from user's charset to database format (UTF-8)."""
705        if text is not None :
706            try :
707                return unicode(text, self.tool.getCharset()).encode("UTF-8") 
708            except UnicodeError :   
709                try :
710                    # Incorrect locale settings ?
711                    return unicode(text, "ISO-8859-15").encode("UTF-8") 
712                except UnicodeError :   
713                    pass
714        return text
715       
716    def cleanDates(self, startdate, enddate) :   
717        """Clean the dates to create a correct filter."""
718        if startdate :   
719            startdate = startdate.strip().lower()
720        if enddate :   
721            enddate = enddate.strip().lower()
722        if (not startdate) and (not enddate) :   
723            return (None, None)
724           
725        now = DateTime.now()   
726        nameddates = ('yesterday', 'today', 'now', 'tomorrow')
727        datedict = { "start" : startdate, "end" : enddate }   
728        for limit in datedict.keys() :
729            dateval = datedict[limit]
730            if dateval :
731                for name in nameddates :
732                    if dateval.startswith(name) :
733                        try :
734                            offset = int(dateval[len(name):])
735                        except :   
736                            offset = 0
737                        dateval = dateval[:len(name)]   
738                        if limit == "start" :
739                            if dateval == "yesterday" :
740                                dateval = (now - 1 + offset).Format("%Y%m%d000000")
741                            elif dateval == "today" :
742                                dateval = (now + offset).Format("%Y%m%d000000")
743                            elif dateval == "now" :
744                                dateval = (now + offset).Format("%Y%m%d%H%M%S")
745                            else : # tomorrow
746                                dateval = (now + 1 + offset).Format("%Y%m%d000000")
747                        else :
748                            if dateval == "yesterday" :
749                                dateval = (now - 1 + offset).Format("%Y%m%d235959")
750                            elif dateval == "today" :
751                                dateval = (now + offset).Format("%Y%m%d235959")
752                            elif dateval == "now" :
753                                dateval = (now + offset).Format("%Y%m%d%H%M%S")
754                            else : # tomorrow
755                                dateval = (now + 1 + offset).Format("%Y%m%d235959")
756                        break
757                       
758                if not dateval.isdigit() :
759                    dateval = None
760                else :   
761                    lgdateval = len(dateval)
762                    if lgdateval == 4 :
763                        if limit == "start" : 
764                            dateval = "%s0101 00:00:00" % dateval
765                        else : 
766                            dateval = "%s1231 23:59:59" % dateval
767                    elif lgdateval == 6 :
768                        if limit == "start" : 
769                            dateval = "%s01 00:00:00" % dateval
770                        else : 
771                            mxdate = DateTime.ISO.ParseDateTime("%s01 00:00:00" % dateval)
772                            dateval = "%s%02i 23:59:59" % (dateval, mxdate.days_in_month)
773                    elif lgdateval == 8 :
774                        if limit == "start" : 
775                            dateval = "%s 00:00:00" % dateval
776                        else : 
777                            dateval = "%s 23:59:59" % dateval
778                    elif lgdateval == 10 :
779                        if limit == "start" : 
780                            dateval = "%s %s:00:00" % (dateval[:8], dateval[8:])
781                        else : 
782                            dateval = "%s %s:59:59" % (dateval[:8], dateval[8:])
783                    elif lgdateval == 12 :
784                        if limit == "start" : 
785                            dateval = "%s %s:%s:00" % (dateval[:8], dateval[8:10], dateval[10:])
786                        else : 
787                            dateval = "%s %s:%s:59" % (dateval[:8], dateval[8:10], dateval[10:])
788                    elif lgdateval == 14 :       
789                        dateval = "%s %s:%s:%s" % (dateval[:8], dateval[8:10], dateval[10:12], dateval[12:])
790                    else :   
791                        dateval = None
792                    try :   
793                        DateTime.ISO.ParseDateTime(dateval)
794                    except :   
795                        dateval = None
796                datedict[limit] = dateval   
797        (start, end) = (datedict["start"], datedict["end"])
798        if start and end and (start > end) :
799            (start, end) = (end, start)
800        return (start, end)   
801       
802def openConnection(pykotatool) :
803    """Returns a connection handle to the appropriate database."""
804    backendinfo = pykotatool.config.getStorageBackend()
805    backend = backendinfo["storagebackend"]
806    try :
807        exec "from pykota.storages import %s as storagebackend" % backend.lower()
808    except ImportError :
809        raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend
810    else :   
811        host = backendinfo["storageserver"]
812        database = backendinfo["storagename"]
813        admin = backendinfo["storageadmin"] or backendinfo["storageuser"]
814        adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"]
815        return storagebackend.Storage(pykotatool, host, database, admin, adminpw)
Note: See TracBrowser for help on using the browser.