root / pykota / trunk / pykota / tool.py @ 713

Revision 713, 6.6 kB (checked in by jalet, 21 years ago)

More robust behavior (hopefully) when the user or printer is not managed
correctly by the Quota System : e.g. cupsFilter added in ppd file, but
printer and/or user not 'yet?' in storage.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#! /usr/bin/env python
2
3# PyKota - Print Quotas for CUPS
4#
5# (c) 2003 Jerome Alet <alet@librelogiciel.com>
6# You're welcome to redistribute this software under the
7# terms of the GNU General Public Licence version 2.0
8# or, at your option, any higher version.
9#
10# You can read the complete GNU GPL in the file COPYING
11# which should come along with this software, or visit
12# the Free Software Foundation's WEB site http://www.fsf.org
13#
14# $Id$
15#
16# $Log$
17# Revision 1.8  2003/02/06 09:19:02  jalet
18# More robust behavior (hopefully) when the user or printer is not managed
19# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
20# printer and/or user not 'yet?' in storage.
21#
22# Revision 1.7  2003/02/06 00:00:45  jalet
23# Now includes the printer name in email messages
24#
25# Revision 1.6  2003/02/05 23:55:02  jalet
26# Cleaner email messages
27#
28# Revision 1.5  2003/02/05 23:45:09  jalet
29# Better DateTime manipulation wrt grace delay
30#
31# Revision 1.4  2003/02/05 23:26:22  jalet
32# Incorrect handling of grace delay
33#
34# Revision 1.3  2003/02/05 22:16:20  jalet
35# DEVICE_URI is undefined outside of CUPS, i.e. for normal command line tools
36#
37# Revision 1.2  2003/02/05 22:10:29  jalet
38# Typos
39#
40# Revision 1.1  2003/02/05 21:28:17  jalet
41# Initial import into CVS
42#
43#
44#
45
46import sys
47import os
48import smtplib
49
50from mx import DateTime
51
52from pykota import config
53from pykota import storage
54from pykota import logger
55
56class PyKotaToolError(Exception):
57    """An exception for PyKota config related stuff."""
58    def __init__(self, message = ""):
59        self.message = message
60        Exception.__init__(self, message)
61    def __repr__(self):
62        return self.message
63    __str__ = __repr__
64   
65class PyKotaTool :   
66    """Base class for all PyKota command line tools."""
67    def __init__(self, isfilter=0) :
68        """Initializes the command line tool."""
69        self.config = config.PyKotaConfig(os.environ.get("CUPS_SERVERROOT", "/etc/cups"))
70        self.logger = logger.openLogger(self.config)
71        self.storage = storage.openConnection(self.config, asadmin=(not isfilter))
72        self.printername = os.environ.get("PRINTER", None)
73        self.smtpserver = self.config.getSMTPServer()
74        self.admin = self.config.getAdmin()
75        self.adminmail = self.config.getAdminMail()
76       
77    def sendMessage(self, touser, fullmessage) :
78        """Sends an email message containing headers to some user."""
79        if "@" not in touser :
80            touser = "%s@%s" % (touser, self.smtpserver)
81        server = smtplib.SMTP(self.smtpserver)
82        server.sendmail(self.adminmail, [touser], fullmessage)
83        server.quit()
84       
85    def sendMessageToUser(self, username, subject, message) :
86        """Sends an email message to a user."""
87        message += "\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n" % (self.admin, self.adminmail)
88        self.sendMessage(username, "Subject: %s\n\n%s" % (subject, message))
89       
90    def sendMessageToAdmin(self, subject, message) :
91        """Sends an email message to the Print Quota administrator."""
92        self.sendMessage(self.adminmail, "Subject: %s\n\n%s" % (subject, message))
93       
94    def checkUserPQuota(self, username, printername) :
95        """Checks the user quota on a printer and deny or accept the job."""
96        now = DateTime.now()
97        quota = self.storage.getUserPQuota(username, printername)
98        if quota is None :
99            # Unknown user or printer or combination
100            policy = self.config.getPrinterPolicy(printername)
101            if policy in [None, "ALLOW"] :
102                action = "ALLOW"
103            else :   
104                action = "DENY"
105            self.logger.log_message("Unable to match user %s on printer %s, applying default policy (%s)" % (username, printername, action), "warn")
106            return (action, None, None)
107        else :   
108            pagecounter = quota["pagecounter"]
109            softlimit = quota["softlimit"]
110            hardlimit = quota["hardlimit"]
111            datelimit = quota["datelimit"]
112            if datelimit is not None :
113                datelimit = DateTime.ISO.ParseDateTime(datelimit)
114            if softlimit is not None :
115                if pagecounter < softlimit :
116                    action = "ALLOW"
117                elif hardlimit is not None :
118                     gracedelay = self.config.getGraceDelay()
119                     if softlimit <= pagecounter < hardlimit :   
120                         if datelimit is None :
121                             datelimit = now + gracedelay
122                             self.storage.doQuery("UPDATE userpquota SET datelimit=%s::DATETIME WHERE userid=%s AND printerid=%s;" % (self.doQuote("%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)), self.doQuote(self.getUserId(username)), self.doQuote(self.getPrinterId(printername))))
123                         if (now + gracedelay) < datelimit :
124                             action = "WARN"
125                         else :   
126                             action = "DENY"
127                     else :         
128                         action = "DENY"
129                else :       
130                    action = "DENY"
131            else :       
132                action = "ALLOW"
133            return (action, (hardlimit - pagecounter), datelimit)
134   
135    def warnQuotaPrinter(self, username) :
136        """Checks a user quota and send him a message if quota is exceeded on current printer."""
137        (action, grace, gracedate) = self.checkUserPQuota(username, self.printername)
138        if action == "DENY" :
139            if (grace is not None) and (gracedate is not None) :
140                # only when both user and printer are known
141                adminmessage = "Print Quota exceeded for user %s on printer %s" % (username, self.printername)
142                self.logger.log_message(adminmessage)
143                self.sendMessageToUser(username, "Print Quota Exceeded", "You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s." % self.printername)
144                self.sendMessageToAdmin("Print Quota", adminmessage)
145        elif action == "WARN" :   
146            adminmessage = "Print Quota soft limit exceeded for user %s on printer %s" % (username, self.printername)
147            self.logger.log_message(adminmessage)
148            self.sendMessageToUser(username, "Print Quota Exceeded", "You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s." % self.printername)
149            self.sendMessageToAdmin("Print Quota", adminmessage)
150        return action       
151   
Note: See TracBrowser for help on using the browser.