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

Revision 782, 10.8 kB (checked in by jalet, 21 years ago)

External requester is about to work, but I must sleep

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