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

Revision 2717, 34.6 kB (checked in by jerome, 18 years ago)

Added deletion methods for user and group print quota entries.

  • 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 database 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 database."""
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 database."""
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 database."""
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 database."""
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       
345    def delete(self) :   
346        """Deletes an user print quota entry from the database."""
347        self.parent.beginTransaction()
348        try :
349            self.parent.deleteUserPQuota(self)
350        except PyKotaStorageError, msg :   
351            self.parent.rollbackTransaction()
352            raise PyKotaStorageError, msg
353        else :   
354            self.parent.commitTransaction()
355            if self.parent.usecache :
356                for (k, v) in self.parent.caches["USERPQUOTAS"].items() :
357                    if v.User.Name == self.User.Name :
358                        self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (v.User.Name, v.Printer.Name))
359            self.Exists = 0
360       
361class StorageGroupPQuota(StorageObject) :
362    """Group Print Quota class."""
363    def __init__(self, parent, group, printer) :
364        StorageObject.__init__(self, parent)
365        self.Group = group
366        self.Printer = printer
367        self.PageCounter = None
368        self.LifePageCounter = None
369        self.SoftLimit = None
370        self.HardLimit = None
371        self.DateLimit = None
372        self.MaxJobSize = None
373       
374    def __getattr__(self, name) :   
375        """Delays data retrieval until it's really needed."""
376        if name == "ParentPrintersGroupPQuota" : 
377            self.ParentPrintersGroupPQuota = (self.Group.Exists and self.Printer.Exists and self.parent.getParentPrintersGroupPQuota(self)) or []
378            return self.ParentPrintersGroupPQuota
379        else :
380            raise AttributeError, name
381       
382    def reset(self) :   
383        """Resets page counter 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.reset()
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 = 0
396        self.DateLimit = None
397       
398    def hardreset(self) :   
399        """Resets actual and life time page counters to 0."""
400        self.parent.beginTransaction()
401        try :
402            for user in self.parent.getGroupMembers(self.Group) :
403                uq = self.parent.getUserPQuota(user, self.Printer)
404                uq.hardreset()
405            self.parent.writeGroupPQuotaDateLimit(self, None)
406        except PyKotaStorageError, msg :   
407            self.parent.rollbackTransaction()
408            raise PyKotaStorageError, msg
409        else :   
410            self.parent.commitTransaction()
411        self.PageCounter = self.LifePageCounter = 0
412        self.DateLimit = None
413       
414    def setDateLimit(self, datelimit) :   
415        """Sets the date limit for this quota."""
416        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, \
417                                                  datelimit.month, \
418                                                  datelimit.day, \
419                                                  datelimit.hour, \
420                                                  datelimit.minute, \
421                                                  datelimit.second)
422        self.parent.writeGroupPQuotaDateLimit(self, date)
423        self.DateLimit = date
424       
425    def setLimits(self, softlimit, hardlimit) :   
426        """Sets the soft and hard limit for this quota."""
427        self.parent.writeGroupPQuotaLimits(self, softlimit, hardlimit)
428        self.SoftLimit = softlimit
429        self.HardLimit = hardlimit
430        self.DateLimit = None
431       
432    def delete(self) :   
433        """Deletes a group print quota entry from the database."""
434        self.parent.beginTransaction()
435        try :
436            self.parent.deleteGroupPQuota(self)
437        except PyKotaStorageError, msg :   
438            self.parent.rollbackTransaction()
439            raise PyKotaStorageError, msg
440        else :   
441            self.parent.commitTransaction()
442            if self.parent.usecache :
443                for (k, v) in self.parent.caches["GROUPPQUOTAS"].items() :
444                    if v.Group.Name == self.Group.Name :
445                        self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (v.Group.Name, v.Printer.Name))
446            self.Exists = 0
447       
448class StorageJob(StorageObject) :
449    """Printer's Job class."""
450    def __init__(self, parent) :
451        StorageObject.__init__(self, parent)
452        self.UserName = None
453        self.PrinterName = None
454        self.JobId = None
455        self.PrinterPageCounter = None
456        self.JobSizeBytes = None
457        self.JobSize = None
458        self.JobAction = None
459        self.JobDate = None
460        self.JobPrice = None
461        self.JobFileName = None
462        self.JobTitle = None
463        self.JobCopies = None
464        self.JobOptions = None
465        self.JobHostName = None
466        self.JobMD5Sum = None
467        self.JobPages = None
468        self.JobBillingCode = None
469        self.PrecomputedJobSize = None
470        self.PrecomputedJobPrice = None
471       
472    def __getattr__(self, name) :   
473        """Delays data retrieval until it's really needed."""
474        if name == "User" : 
475            self.User = self.parent.getUser(self.UserName)
476            return self.User
477        elif name == "Printer" :   
478            self.Printer = self.parent.getPrinter(self.PrinterName)
479            return self.Printer
480        else :
481            raise AttributeError, name
482       
483class StorageLastJob(StorageJob) :
484    """Printer's Last Job class."""
485    def __init__(self, parent, printer) :
486        StorageJob.__init__(self, parent)
487        self.PrinterName = printer.Name # not needed
488        self.Printer = printer
489       
490class StorageBillingCode(StorageObject) :
491    """Billing code class."""
492    def __init__(self, parent, name) :
493        StorageObject.__init__(self, parent)
494        self.BillingCode = name
495        self.PageCounter = None
496        self.Balance = None
497       
498    def delete(self) :   
499        """Deletes the billing code from the database."""
500        self.parent.deleteBillingCode(self)
501        self.parent.flushEntry("BILLINGCODES", self.BillingCode)
502        self.isDirty = False
503        self.Exists = False
504       
505    def reset(self, balance=0.0, pagecounter=0) :   
506        """Resets the pagecounter and balance for this billing code."""
507        self.Balance = balance
508        self.PageCounter = pagecounter
509        self.isDirty = True
510       
511    def consume(self, pages, price) :
512        """Consumes some pages and credits for this billing code."""
513        if pages :
514           self.parent.consumeBillingCode(self, pages, price)
515           self.PageCounter += pages
516           self.Balance -= price
517       
518class BaseStorage :
519    def __init__(self, pykotatool) :
520        """Opens the storage connection."""
521        self.closed = 1
522        self.tool = pykotatool
523        self.usecache = pykotatool.config.getCaching()
524        self.disablehistory = pykotatool.config.getDisableHistory()
525        self.privacy = pykotatool.config.getPrivacy()
526        if self.privacy :
527            pykotatool.logdebug("Jobs' title, filename and options will be hidden because of privacy concerns.")
528        if self.usecache :
529            self.tool.logdebug("Caching enabled.")
530            self.caches = { "USERS" : {}, \
531                            "GROUPS" : {}, \
532                            "PRINTERS" : {}, \
533                            "USERPQUOTAS" : {}, \
534                            "GROUPPQUOTAS" : {}, \
535                            "JOBS" : {}, \
536                            "LASTJOBS" : {}, \
537                            "BILLINGCODES" : {} }
538       
539    def close(self) :   
540        """Must be overriden in children classes."""
541        raise RuntimeError, "BaseStorage.close() must be overriden !"
542       
543    def __del__(self) :       
544        """Ensures that the database connection is closed."""
545        self.close()
546       
547    def getFromCache(self, cachetype, key) :
548        """Tries to extract something from the cache."""
549        if self.usecache :
550            entry = self.caches[cachetype].get(key)
551            if entry is not None :
552                self.tool.logdebug("Cache hit (%s->%s)" % (cachetype, key))
553            else :   
554                self.tool.logdebug("Cache miss (%s->%s)" % (cachetype, key))
555            return entry   
556           
557    def cacheEntry(self, cachetype, key, value) :       
558        """Puts an entry in the cache."""
559        if self.usecache and getattr(value, "Exists", 0) :
560            self.caches[cachetype][key] = value
561            self.tool.logdebug("Cache store (%s->%s)" % (cachetype, key))
562           
563    def flushEntry(self, cachetype, key) :       
564        """Removes an entry from the cache."""
565        if self.usecache :
566            try :
567                del self.caches[cachetype][key]
568            except KeyError :   
569                pass
570            else :   
571                self.tool.logdebug("Cache flush (%s->%s)" % (cachetype, key))
572           
573    def getUser(self, username) :       
574        """Returns the user from cache."""
575        user = self.getFromCache("USERS", username)
576        if user is None :
577            user = self.getUserFromBackend(username)
578            self.cacheEntry("USERS", username, user)
579        return user   
580       
581    def getGroup(self, groupname) :       
582        """Returns the group from cache."""
583        group = self.getFromCache("GROUPS", groupname)
584        if group is None :
585            group = self.getGroupFromBackend(groupname)
586            self.cacheEntry("GROUPS", groupname, group)
587        return group   
588       
589    def getPrinter(self, printername) :       
590        """Returns the printer from cache."""
591        printer = self.getFromCache("PRINTERS", printername)
592        if printer is None :
593            printer = self.getPrinterFromBackend(printername)
594            self.cacheEntry("PRINTERS", printername, printer)
595        return printer   
596       
597    def getUserPQuota(self, user, printer) :       
598        """Returns the user quota information from cache."""
599        useratprinter = "%s@%s" % (user.Name, printer.Name)
600        upquota = self.getFromCache("USERPQUOTAS", useratprinter)
601        if upquota is None :
602            upquota = self.getUserPQuotaFromBackend(user, printer)
603            self.cacheEntry("USERPQUOTAS", useratprinter, upquota)
604        return upquota   
605       
606    def getGroupPQuota(self, group, printer) :       
607        """Returns the group quota information from cache."""
608        groupatprinter = "%s@%s" % (group.Name, printer.Name)
609        gpquota = self.getFromCache("GROUPPQUOTAS", groupatprinter)
610        if gpquota is None :
611            gpquota = self.getGroupPQuotaFromBackend(group, printer)
612            self.cacheEntry("GROUPPQUOTAS", groupatprinter, gpquota)
613        return gpquota   
614       
615    def getPrinterLastJob(self, printer) :       
616        """Extracts last job information for a given printer from cache."""
617        lastjob = self.getFromCache("LASTJOBS", printer.Name)
618        if lastjob is None :
619            lastjob = self.getPrinterLastJobFromBackend(printer)
620            self.cacheEntry("LASTJOBS", printer.Name, lastjob)
621        return lastjob   
622       
623    def getBillingCode(self, label) :       
624        """Returns the user from cache."""
625        code = self.getFromCache("BILLINGCODES", label)
626        if code is None :
627            code = self.getBillingCodeFromBackend(label)
628            self.cacheEntry("BILLINGCODES", label, code)
629        return code
630       
631    def getParentPrinters(self, printer) :   
632        """Extracts parent printers information for a given printer from cache."""
633        if self.usecache :
634            if not hasattr(printer, "Parents") :
635                self.tool.logdebug("Cache miss (%s->Parents)" % printer.Name)
636                printer.Parents = self.getParentPrintersFromBackend(printer)
637                self.tool.logdebug("Cache store (%s->Parents)" % printer.Name)
638            else :
639                self.tool.logdebug("Cache hit (%s->Parents)" % printer.Name)
640        else :       
641            printer.Parents = self.getParentPrintersFromBackend(printer)
642        for parent in printer.Parents[:] :   
643            printer.Parents.extend(self.getParentPrinters(parent))
644        uniquedic = {}   
645        for parent in printer.Parents :
646            uniquedic[parent.Name] = parent
647        printer.Parents = uniquedic.values()   
648        return printer.Parents
649       
650    def getGroupMembers(self, group) :       
651        """Returns the group's members list from in-group cache."""
652        if self.usecache :
653            if not hasattr(group, "Members") :
654                self.tool.logdebug("Cache miss (%s->Members)" % group.Name)
655                group.Members = self.getGroupMembersFromBackend(group)
656                self.tool.logdebug("Cache store (%s->Members)" % group.Name)
657            else :
658                self.tool.logdebug("Cache hit (%s->Members)" % group.Name)
659        else :       
660            group.Members = self.getGroupMembersFromBackend(group)
661        return group.Members   
662       
663    def getUserGroups(self, user) :       
664        """Returns the user's groups list from in-user cache."""
665        if self.usecache :
666            if not hasattr(user, "Groups") :
667                self.tool.logdebug("Cache miss (%s->Groups)" % user.Name)
668                user.Groups = self.getUserGroupsFromBackend(user)
669                self.tool.logdebug("Cache store (%s->Groups)" % user.Name)
670            else :
671                self.tool.logdebug("Cache hit (%s->Groups)" % user.Name)
672        else :       
673            user.Groups = self.getUserGroupsFromBackend(user)
674        return user.Groups   
675       
676    def getParentPrintersUserPQuota(self, userpquota) :     
677        """Returns all user print quota on the printer and all its parents recursively."""
678        upquotas = [ ]
679        for printer in self.getParentPrinters(userpquota.Printer) :
680            upq = self.getUserPQuota(userpquota.User, printer)
681            if upq.Exists :
682                upquotas.append(upq)
683        return upquotas       
684       
685    def getParentPrintersGroupPQuota(self, grouppquota) :     
686        """Returns all group print quota on the printer and all its parents recursively."""
687        gpquotas = [ ]
688        for printer in self.getParentPrinters(grouppquota.Printer) :
689            gpq = self.getGroupPQuota(grouppquota.Group, printer)
690            if gpq.Exists :
691                gpquotas.append(gpq)
692        return gpquotas       
693       
694    def databaseToUserCharset(self, text) :
695        """Converts from database format (UTF-8) to user's charset."""
696        if text is not None :
697            try :
698                return unicode(text, "UTF-8").encode(self.tool.getCharset()) 
699            except UnicodeError :   
700                try :
701                    # Incorrect locale settings ?
702                    return unicode(text, "UTF-8").encode("ISO-8859-15") 
703                except UnicodeError :   
704                    pass
705        return text
706       
707    def userCharsetToDatabase(self, text) :
708        """Converts from user's charset to database format (UTF-8)."""
709        if text is not None :
710            try :
711                return unicode(text, self.tool.getCharset()).encode("UTF-8") 
712            except UnicodeError :   
713                try :
714                    # Incorrect locale settings ?
715                    return unicode(text, "ISO-8859-15").encode("UTF-8") 
716                except UnicodeError :   
717                    pass
718        return text
719       
720    def cleanDates(self, startdate, enddate) :   
721        """Clean the dates to create a correct filter."""
722        if startdate :   
723            startdate = startdate.strip().lower()
724        if enddate :   
725            enddate = enddate.strip().lower()
726        if (not startdate) and (not enddate) :   
727            return (None, None)
728           
729        now = DateTime.now()   
730        nameddates = ('yesterday', 'today', 'now', 'tomorrow')
731        datedict = { "start" : startdate, "end" : enddate }   
732        for limit in datedict.keys() :
733            dateval = datedict[limit]
734            if dateval :
735                for name in nameddates :
736                    if dateval.startswith(name) :
737                        try :
738                            offset = int(dateval[len(name):])
739                        except :   
740                            offset = 0
741                        dateval = dateval[:len(name)]   
742                        if limit == "start" :
743                            if dateval == "yesterday" :
744                                dateval = (now - 1 + offset).Format("%Y%m%d000000")
745                            elif dateval == "today" :
746                                dateval = (now + offset).Format("%Y%m%d000000")
747                            elif dateval == "now" :
748                                dateval = (now + offset).Format("%Y%m%d%H%M%S")
749                            else : # tomorrow
750                                dateval = (now + 1 + offset).Format("%Y%m%d000000")
751                        else :
752                            if dateval == "yesterday" :
753                                dateval = (now - 1 + offset).Format("%Y%m%d235959")
754                            elif dateval == "today" :
755                                dateval = (now + offset).Format("%Y%m%d235959")
756                            elif dateval == "now" :
757                                dateval = (now + offset).Format("%Y%m%d%H%M%S")
758                            else : # tomorrow
759                                dateval = (now + 1 + offset).Format("%Y%m%d235959")
760                        break
761                       
762                if not dateval.isdigit() :
763                    dateval = None
764                else :   
765                    lgdateval = len(dateval)
766                    if lgdateval == 4 :
767                        if limit == "start" : 
768                            dateval = "%s0101 00:00:00" % dateval
769                        else : 
770                            dateval = "%s1231 23:59:59" % dateval
771                    elif lgdateval == 6 :
772                        if limit == "start" : 
773                            dateval = "%s01 00:00:00" % dateval
774                        else : 
775                            mxdate = DateTime.ISO.ParseDateTime("%s01 00:00:00" % dateval)
776                            dateval = "%s%02i 23:59:59" % (dateval, mxdate.days_in_month)
777                    elif lgdateval == 8 :
778                        if limit == "start" : 
779                            dateval = "%s 00:00:00" % dateval
780                        else : 
781                            dateval = "%s 23:59:59" % dateval
782                    elif lgdateval == 10 :
783                        if limit == "start" : 
784                            dateval = "%s %s:00:00" % (dateval[:8], dateval[8:])
785                        else : 
786                            dateval = "%s %s:59:59" % (dateval[:8], dateval[8:])
787                    elif lgdateval == 12 :
788                        if limit == "start" : 
789                            dateval = "%s %s:%s:00" % (dateval[:8], dateval[8:10], dateval[10:])
790                        else : 
791                            dateval = "%s %s:%s:59" % (dateval[:8], dateval[8:10], dateval[10:])
792                    elif lgdateval == 14 :       
793                        dateval = "%s %s:%s:%s" % (dateval[:8], dateval[8:10], dateval[10:12], dateval[12:])
794                    else :   
795                        dateval = None
796                    try :   
797                        DateTime.ISO.ParseDateTime(dateval)
798                    except :   
799                        dateval = None
800                datedict[limit] = dateval   
801        (start, end) = (datedict["start"], datedict["end"])
802        if start and end and (start > end) :
803            (start, end) = (end, start)
804        return (start, end)   
805       
806def openConnection(pykotatool) :
807    """Returns a connection handle to the appropriate database."""
808    backendinfo = pykotatool.config.getStorageBackend()
809    backend = backendinfo["storagebackend"]
810    try :
811        exec "from pykota.storages import %s as storagebackend" % backend.lower()
812    except ImportError :
813        raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend
814    else :   
815        host = backendinfo["storageserver"]
816        database = backendinfo["storagename"]
817        admin = backendinfo["storageadmin"] or backendinfo["storageuser"]
818        adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"]
819        return storagebackend.Storage(pykotatool, host, database, admin, adminpw)
Note: See TracBrowser for help on using the browser.