root / pykota / trunk / bin / pykota @ 728

Revision 728, 4.9 kB (checked in by jalet, 21 years ago)

warnpykota should be ok

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1#! /usr/bin/env python
2
3# PyKota accounting filter
4#
5# PyKota - Print Quotas for CUPS
6#
7# (c) 2003 Jerome Alet <alet@librelogiciel.com>
8# You're welcome to redistribute this software under the
9# terms of the GNU General Public Licence version 2.0
10# or, at your option, any higher version.
11#
12# You can read the complete GNU GPL in the file COPYING
13# which should come along with this software, or visit
14# the Free Software Foundation's WEB site http://www.fsf.org
15#
16# $Id$
17#
18# $Log$
19# Revision 1.6  2003/02/06 22:54:33  jalet
20# warnpykota should be ok
21#
22# Revision 1.5  2003/02/05 22:45:25  jalet
23# Forgotten import
24#
25# Revision 1.4  2003/02/05 22:42:51  jalet
26# Typo
27#
28# Revision 1.3  2003/02/05 22:38:39  jalet
29# Typo
30#
31# Revision 1.2  2003/02/05 22:16:20  jalet
32# DEVICE_URI is undefined outside of CUPS, i.e. for normal command line tools
33#
34# Revision 1.1  2003/02/05 21:28:17  jalet
35# Initial import into CVS
36#
37#
38#
39
40import sys
41import os
42
43from pykota.tool import PyKotaTool, PyKotaToolError
44from pykota import requester
45
46class PyKotaFilter(PyKotaTool) :   
47    """Class for the PyKota filter."""
48    def __init__(self, username) :
49        PyKotaTool.__init__(self, isfilter=1)
50        self.username = username
51        self.requester = requester.openRequester(self.config, self.printername)
52        self.printerhostname = self.getPrinterHostname()
53   
54    def getPrinterHostname(self) :
55        """Returns the printer hostname."""
56        device_uri = os.environ.get("DEVICE_URI", "")
57        # TODO : check this for more complex urls than ipp://myprinter.dot.com:631/printers/lp
58        try :
59            (backend, destination) = device_uri.split(":", 1) 
60        except ValueError :   
61            raise PyKotaToolError, "Invalid DEVICE_URI : %s\n" % device_uri
62        while destination.startswith("/") :
63            destination = destination[1:]
64        return destination.split("/")[0].split(":")[0]
65       
66    def filterInput(self, inputfile) :
67        """Transparent filter."""
68        mustclose = 0   
69        if inputfile is not None :   
70            infile = open(inputfile, "rb")
71            mustclose = 1
72        else :   
73            infile = sys.stdin
74        data = infile.read(65536)   
75        while data :
76            sys.stdout.write(data)
77            data = infile.read(65536)
78        if mustclose :   
79            infile.close()
80           
81def main() :   
82    """Do it, and do it right !"""
83    #
84    # This is a CUPS filter, so we should act and die like a CUPS filter when needed
85    narg = len(sys.argv)
86    if narg not in (6, 7) :   
87        sys.stderr.write("ERROR: %s job-id user title copies options [file]\n" % sys.argv[0])
88        return 1
89    elif narg == 7 :   
90        # input file
91        inputfile = sys.argv[6]
92    else :   
93        # stdin
94        inputfile = None
95       
96    #   
97    # According to CUPS documentation, the username is the third command line argument
98    username = sys.argv[2].strip()   
99   
100    # Initializes the current tool
101    tool = PyKotaFilter(username)   
102   
103    # Get the page counter directly from the printer itself
104    counterbeforejob = tool.requester.getPrinterPageCounter(tool.printerhostname) # TODO use printername instead, make them match from CUPS' config files
105   
106    # Get the last page counter and last username from the Quota Storage backend
107    pgc = tool.storage.getPrinterPageCounter(tool.printername)   
108    if pgc is None :
109        # The printer is unknown from the Quota Storage perspective
110        # we let the job pass through, but log a warning message
111        tool.logger.log_message("Printer %s not registered in the PyKota system" % tool.printername, "warn")
112    else :   
113        (lastpagecounter, lastusername) = (pgc["pagecounter"], pgc["lastusername"])
114       
115        # Update the last page counter and last username in the Quota Storage backend
116        # set them to current user and
117        tool.storage.updatePrinterPageCounter(tool.printername, username, counterbeforejob) # TODO : allow or deny users not in quota system, and die cleanly if needed
118       
119        # Is the current user allowed to print at all ?
120        action = tool.warnUserPQuota(username)
121        if action == "DENY" :
122            # No, just die cleanly
123            return 1
124           
125        # Yes     
126        if (lastpagecounter is None) or (lastusername is None) :
127            lastusername = username
128            lastpagecounter = counterbeforejob
129        jobsize = (counterbeforejob - lastpagecounter)   
130        if jobsize >= 0:
131            tool.storage.updateUserPQuota(lastusername, tool.printername, jobsize)
132            tool.warnUserPQuota(lastusername)
133        else :   
134            tool.logger.log_message("Error in page count value %i for user %s on printer %s" % (jobsize, tool.printername, lastusername), "error")
135       
136    # pass the job untouched to the underlying layer
137    tool.filterInput(inputfile)     
138   
139    return 0
140
141if __name__ == "__main__" :   
142    sys.exit(main() or 0)
Note: See TracBrowser for help on using the browser.