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

Revision 2452, 32.4 kB (checked in by jerome, 19 years ago)

Upgraded database schema.
Added -i | --ingroups command line option to repykota.
Added -C | --comment command line option to edpykota.
Added 'noquota', 'noprint', and 'nochange' as switches for edpykota's
-l | --limitby command line option.
Severity : entirely new features, in need of testers :-)

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