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

Revision 788, 11.0 kB (checked in by jalet, 21 years ago)

Localization

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