root / pykota / branches / 1.26_fixes / pykota / storage.py @ 3525

Revision 3525, 35.5 kB (checked in by jerome, 14 years ago)

Backported the improvement of the fix for #52. References #52.

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