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

Revision 711, 5.5 kB (checked in by jalet, 21 years ago)

Cleaner email messages

  • 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.6  2003/02/05 23:55:02  jalet
18# Cleaner email messages
19#
20# Revision 1.5  2003/02/05 23:45:09  jalet
21# Better DateTime manipulation wrt grace delay
22#
23# Revision 1.4  2003/02/05 23:26:22  jalet
24# Incorrect handling of grace delay
25#
26# Revision 1.3  2003/02/05 22:16:20  jalet
27# DEVICE_URI is undefined outside of CUPS, i.e. for normal command line tools
28#
29# Revision 1.2  2003/02/05 22:10:29  jalet
30# Typos
31#
32# Revision 1.1  2003/02/05 21:28:17  jalet
33# Initial import into CVS
34#
35#
36#
37
38import sys
39import os
40import smtplib
41
42from mx import DateTime
43
44from pykota import config
45from pykota import storage
46from pykota import logger
47
48class PyKotaToolError(Exception):
49    """An exception for PyKota config related stuff."""
50    def __init__(self, message = ""):
51        self.message = message
52        Exception.__init__(self, message)
53    def __repr__(self):
54        return self.message
55    __str__ = __repr__
56   
57class PyKotaTool :   
58    """Base class for all PyKota command line tools."""
59    def __init__(self, isfilter=0) :
60        """Initializes the command line tool."""
61        self.config = config.PyKotaConfig(os.environ.get("CUPS_SERVERROOT", "/etc/cups"))
62        self.logger = logger.openLogger(self.config)
63        self.storage = storage.openConnection(self.config, asadmin=(not isfilter))
64        self.printername = os.environ.get("PRINTER", None)
65        self.smtpserver = self.config.getSMTPServer()
66        self.admin = self.config.getAdmin()
67        self.adminmail = self.config.getAdminMail()
68       
69    def sendMessage(self, touser, fullmessage) :
70        """Sends an email message containing headers to some user."""
71        if "@" not in touser :
72            touser = "%s@%s" % (touser, self.smtpserver)
73        server = smtplib.SMTP(self.smtpserver)
74        server.sendmail(self.adminmail, [touser], fullmessage)
75        server.quit()
76       
77    def sendMessageToUser(self, username, subject, message) :
78        """Sends an email message to a user."""
79        message += "\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n" % (self.admin, self.adminmail)
80        self.sendMessage(username, "Subject: %s\n\n%s" % (subject, message))
81       
82    def sendMessageToAdmin(self, subject, message) :
83        """Sends an email message to the Print Quota administrator."""
84        self.sendMessage(self.adminmail, "Subject: %s\n\n%s" % (subject, message))
85       
86    def checkUserPQuota(self, username, printername) :
87        """Checks the user quota on a printer and deny or accept the job."""
88        now = DateTime.now()
89        quota = self.storage.getUserPQuota(username, printername)
90        pagecounter = quota["pagecounter"]
91        softlimit = quota["softlimit"]
92        hardlimit = quota["hardlimit"]
93        datelimit = quota["datelimit"]
94        if datelimit is not None :
95            datelimit = DateTime.ISO.ParseDateTime(datelimit)
96        if softlimit is not None :
97            if pagecounter < softlimit :
98                action = "ALLOW"
99            elif hardlimit is not None :
100                 gracedelay = self.config.getGraceDelay()
101                 if softlimit <= pagecounter < hardlimit :   
102                     if datelimit is None :
103                         datelimit = now + gracedelay
104                         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))))
105                     if (now + gracedelay) < datelimit :
106                         action = "WARN"
107                     else :   
108                         action = "DENY"
109                 else :         
110                     action = "DENY"
111            else :       
112                action = "DENY"
113        else :       
114            action = "ALLOW"
115        return (action, (hardlimit - pagecounter), datelimit)
116   
117    def warnQuotaPrinter(self, username) :
118        """Checks a user quota and send him a message if quota is exceeded on current printer."""
119        (action, grace, gracedate) = self.checkUserPQuota(username, self.printername)
120        if action == "DENY" :
121            adminmessage = "Print Quota exceeded for user %s on printer %s" % (username, self.printername)
122            self.logger.log_message(adminmessage)
123            self.sendMessageToUser(username, "Print Quota Exceeded", "You are not allowed to print anymore because\nyour Print Quota is exceeded.")
124            self.sendMessageToAdmin("Print Quota", adminmessage)
125        elif action == "WARN" :   
126            adminmessage = "Print Quota soft limit exceeded for user %s on printer %s" % (username, self.printername)
127            self.logger.log_message(adminmessage)
128            self.sendMessageToUser(username, "Print Quota Exceeded", "You will soon be forbidden to print anymore because\nyour Print Quota is almost reached.")
129            self.sendMessageToAdmin("Print Quota", adminmessage)
130        return action       
131   
Note: See TracBrowser for help on using the browser.