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

Revision 2937, 31.9 kB (checked in by jerome, 18 years ago)

pkusers now supports the --email command line option.

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