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

Revision 709, 5.4 kB (checked in by jalet, 21 years ago)

Better DateTime? manipulation wrt grace delay

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