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

Revision 773, 10.7 kB (checked in by jalet, 21 years ago)

Internationalization continues...

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