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

Revision 824, 11.8 kB (checked in by jalet, 21 years ago)

WARN log priority doesn't exist.

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