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

Revision 2880, 31.7 kB (checked in by jerome, 18 years ago)

Double checked that all DateTime? objects are correctly handled in
all cases.

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