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

Revision 2676, 33.5 kB (checked in by jerome, 18 years ago)

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