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

Revision 2707, 33.3 kB (checked in by jerome, 18 years ago)

Improved user modification speed by around 15%.

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