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

Revision 804, 11.4 kB (checked in by jalet, 21 years ago)

Typos

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