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

Revision 802, 11.3 kB (checked in by jalet, 21 years ago)

More options can now be set per printer or globally :

admin
adminmail
gracedelay
requester

the printer option has priority when both are defined.

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