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

Revision 742, 9.8 kB (checked in by jalet, 21 years ago)

Indentation problem

  • 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.14  2003/02/07 10:42:45  jalet
18# Indentation problem
19#
20# Revision 1.13  2003/02/07 08:34:16  jalet
21# Test wrt date limit was wrong
22#
23# Revision 1.12  2003/02/06 23:20:02  jalet
24# warnpykota doesn't need any user/group name argument, mimicing the
25# warnquota disk quota tool.
26#
27# Revision 1.11  2003/02/06 22:54:33  jalet
28# warnpykota should be ok
29#
30# Revision 1.10  2003/02/06 15:03:11  jalet
31# added a method to set the limit date
32#
33# Revision 1.9  2003/02/06 10:39:23  jalet
34# Preliminary edpykota work.
35#
36# Revision 1.8  2003/02/06 09:19:02  jalet
37# More robust behavior (hopefully) when the user or printer is not managed
38# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
39# printer and/or user not 'yet?' in storage.
40#
41# Revision 1.7  2003/02/06 00:00:45  jalet
42# Now includes the printer name in email messages
43#
44# Revision 1.6  2003/02/05 23:55:02  jalet
45# Cleaner email messages
46#
47# Revision 1.5  2003/02/05 23:45:09  jalet
48# Better DateTime manipulation wrt grace delay
49#
50# Revision 1.4  2003/02/05 23:26:22  jalet
51# Incorrect handling of grace delay
52#
53# Revision 1.3  2003/02/05 22:16:20  jalet
54# DEVICE_URI is undefined outside of CUPS, i.e. for normal command line tools
55#
56# Revision 1.2  2003/02/05 22:10:29  jalet
57# Typos
58#
59# Revision 1.1  2003/02/05 21:28:17  jalet
60# Initial import into CVS
61#
62#
63#
64
65import sys
66import os
67import getopt
68import smtplib
69
70from mx import DateTime
71
72from pykota import version, config, storage, logger
73
74class PyKotaToolError(Exception):
75    """An exception for PyKota config related stuff."""
76    def __init__(self, message = ""):
77        self.message = message
78        Exception.__init__(self, message)
79    def __repr__(self):
80        return self.message
81    __str__ = __repr__
82   
83class PyKotaTool :   
84    """Base class for all PyKota command line tools."""
85    def __init__(self, isfilter=0, doc="PyKota %s (c) 2003 %s" % (version.__version__, version.__author__)) :
86        """Initializes the command line tool."""
87        self.documentation = doc
88        self.config = config.PyKotaConfig(os.environ.get("CUPS_SERVERROOT", "/etc/cups"))
89        self.logger = logger.openLogger(self.config)
90        self.storage = storage.openConnection(self.config, asadmin=(not isfilter))
91        self.printername = os.environ.get("PRINTER", None)
92        self.smtpserver = self.config.getSMTPServer()
93        self.admin = self.config.getAdmin()
94        self.adminmail = self.config.getAdminMail()
95       
96    def display_version_and_quit(self) :
97        """Displays version number, then exists successfully."""
98        print version.__version__
99        sys.exit(0)
100   
101    def display_usage_and_quit(self) :
102        """Displays command line usage, then exists successfully."""
103        print self.documentation
104        sys.exit(0)
105       
106    def parseCommandline(self, argv, short, long, allownothing=0) :
107        """Parses the command line, controlling options."""
108        # split options in two lists: those which need an argument, those which don't need any
109        withoutarg = []
110        witharg = []
111        lgs = len(short)
112        i = 0
113        while i < lgs :
114            ii = i + 1
115            if (ii < lgs) and (short[ii] == ':') :
116                # needs an argument
117                witharg.append(short[i])
118                ii = ii + 1 # skip the ':'
119            else :
120                # doesn't need an argument
121                withoutarg.append(short[i])
122            i = ii
123               
124        for option in long :
125            if option[-1] == '=' :
126                # needs an argument
127                witharg.append(option[:-1])
128            else :
129                # doesn't need an argument
130                withoutarg.append(option)
131       
132        # we begin with all possible options unset
133        parsed = {}
134        for option in withoutarg + witharg :
135            parsed[option] = None
136       
137        # then we parse the command line
138        args = []       # to not break if something unexpected happened
139        try :
140            options, args = getopt.getopt(argv, short, long)
141            if options :
142                for (o, v) in options :
143                    # we skip the '-' chars
144                    lgo = len(o)
145                    i = 0
146                    while (i < lgo) and (o[i] == '-') :
147                        i = i + 1
148                    o = o[i:]
149                    if o in witharg :
150                        # needs an argument : set it
151                        parsed[o] = v
152                    elif o in withoutarg :
153                        # doesn't need an argument : boolean
154                        parsed[o] = 1
155                    else :
156                        # should never occur
157                        raise PyKotaToolError, "Unexpected problem when parsing command line"
158            elif (not args) and (not allownothing) and sys.stdin.isatty() : # no option and no argument, we display help if we are a tty
159                self.display_usage_and_quit()
160        except getopt.error, msg :
161            sys.stderr.write("%s\n" % msg)
162            sys.stderr.flush()
163            self.display_usage_and_quit()
164        return (parsed, args)
165   
166    def sendMessage(self, touser, fullmessage) :
167        """Sends an email message containing headers to some user."""
168        if "@" not in touser :
169            touser = "%s@%s" % (touser, self.smtpserver)
170        server = smtplib.SMTP(self.smtpserver)
171        server.sendmail(self.adminmail, [touser], fullmessage)
172        server.quit()
173       
174    def sendMessageToUser(self, username, subject, message) :
175        """Sends an email message to a user."""
176        message += "\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n" % (self.admin, self.adminmail)
177        self.sendMessage(username, "Subject: %s\n\n%s" % (subject, message))
178       
179    def sendMessageToAdmin(self, subject, message) :
180        """Sends an email message to the Print Quota administrator."""
181        self.sendMessage(self.adminmail, "Subject: %s\n\n%s" % (subject, message))
182       
183    def checkUserPQuota(self, username, printername) :
184        """Checks the user quota on a printer and deny or accept the job."""
185        quota = self.storage.getUserPQuota(username, printername)
186        if quota is None :
187            # Unknown user or printer or combination
188            policy = self.config.getPrinterPolicy(printername)
189            if policy in [None, "ALLOW"] :
190                action = "ALLOW"
191            else :   
192                action = "DENY"
193            self.logger.log_message("Unable to match user %s on printer %s, applying default policy (%s)" % (username, printername, action), "warn")
194            return (action, None, None)
195        else :   
196            pagecounter = quota["pagecounter"]
197            softlimit = quota["softlimit"]
198            hardlimit = quota["hardlimit"]
199            datelimit = quota["datelimit"]
200            if datelimit is not None :
201                datelimit = DateTime.ISO.ParseDateTime(datelimit)
202            if softlimit is not None :
203                if pagecounter < softlimit :
204                    action = "ALLOW"
205                elif hardlimit is not None :
206                    if softlimit <= pagecounter < hardlimit :   
207                        now = DateTime.now()
208                        if datelimit is None :
209                            datelimit = now + self.config.getGraceDelay()
210                            self.storage.setDateLimit(username, printername, datelimit)
211                        if now < datelimit :
212                            action = "WARN"
213                        else :   
214                            action = "DENY"
215                    else :         
216                        action = "DENY"
217                else :       
218                    action = "DENY"
219            else :       
220                action = "ALLOW"
221            return (action, (hardlimit - pagecounter), datelimit)
222   
223    def warnGroupPQuota(self, username, printername=None) :
224        """Checks a user quota and send him a message if quota is exceeded on current printer."""
225        pname = printername or self.printername
226        raise PyKotaToolError, "Group quotas are currently not implemented."
227       
228    def warnUserPQuota(self, username, printername=None) :
229        """Checks a user quota and send him a message if quota is exceeded on current printer."""
230        pname = printername or self.printername
231        (action, grace, gracedate) = self.checkUserPQuota(username, pname)
232        if action == "DENY" :
233            if (grace is not None) and (gracedate is not None) :
234                # only when both user and printer are known
235                adminmessage = "Print Quota exceeded for user %s on printer %s" % (username, pname)
236                self.logger.log_message(adminmessage)
237                self.sendMessageToUser(username, "Print Quota Exceeded", "You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s." % pname)
238                self.sendMessageToAdmin("Print Quota", adminmessage)
239        elif action == "WARN" :   
240            adminmessage = "Print Quota soft limit exceeded for user %s on printer %s" % (username, pname)
241            self.logger.log_message(adminmessage)
242            self.sendMessageToUser(username, "Print Quota Exceeded", "You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s." % pname)
243            self.sendMessageToAdmin("Print Quota", adminmessage)
244        return action       
245   
Note: See TracBrowser for help on using the browser.