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

Revision 3033, 32.8 kB (checked in by jerome, 18 years ago)

Added lazy retrieval of a printer's coefficients.
Removed pykoef from setup script.
Added pksetup to setup script.

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