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

Revision 2686, 33.9 kB (checked in by jerome, 18 years ago)

Modified pkprinters to improve speed just like I did for pkbcodes earlier.
edpykota had to be modified as well to use the new printer API.
The time spent to modify printers has been almost halved.

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