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

Revision 3036, 34.0 kB (checked in by jerome, 18 years ago)

Charging for ink usage, finally !

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