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

Revision 772, 10.6 kB (checked in by jalet, 21 years ago)

Internationalization begins...

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