root / pykota / trunk / bin / pykotme @ 1447

Revision 1285, 7.4 kB (checked in by jalet, 21 years ago)

New formula to compute a job's price

  • 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# -*- coding: ISO-8859-15 -*-
3
4# PyKota Print Quota Quote sender
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program; if not, write to the Free Software
21# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22#
23# $Id$
24#
25# $Log$
26# Revision 1.7  2004/01/12 22:43:40  jalet
27# New formula to compute a job's price
28#
29# Revision 1.6  2004/01/08 14:10:32  jalet
30# Copyright year changed.
31#
32# Revision 1.5  2003/10/09 21:25:25  jalet
33# Multiple printer names or wildcards can be passed on the command line
34# separated with commas.
35# Beta phase.
36#
37# Revision 1.4  2003/10/07 09:07:27  jalet
38# Character encoding added to please latest version of Python
39#
40# Revision 1.3  2003/07/29 20:55:17  jalet
41# 1.14 is out !
42#
43# Revision 1.2  2003/07/25 10:41:29  jalet
44# Better documentation.
45# pykotme now displays the current user's account balance.
46# Some test changed in ldap module.
47#
48# Revision 1.1  2003/07/03 09:44:01  jalet
49# Now includes the pykotme utility
50#
51#
52#
53
54import sys
55import os
56import pwd
57
58from pykota import version
59from pykota.tool import PyKotaTool, PyKotaToolError
60from pykota.config import PyKotaConfigError
61from pykota.storage import PyKotaStorageError
62
63__doc__ = """pykotme v%s (c) 2003-2004 C@LL - Conseil Internet & Logiciels Libres
64
65Gives print quotes to users.
66
67command line usage :
68
69  pykotme  [options]  [files]
70
71options :
72
73  -v | --version       Prints pykotme's version number then exits.
74  -h | --help          Prints this message then exits.
75 
76  -P | --printer p     Gives a quote for this printer only. Actually p can
77                       use wildcards characters to select only
78                       some printers. The default value is *, meaning
79                       all printers.
80                       You can specify several names or wildcards,
81                       by separating them with commas.
82 
83examples :                             
84
85  $ pykotme --printer apple file1.ps file2.ps
86 
87  This will give a print quote to the current user. The quote will show
88  the price and size of a job consisting in file1.ps and file2.ps
89  which would be sent to the apple printer.
90 
91  $ pykotme --printer apple,hplaser <file1.ps
92 
93  This will give a print quote to the current user. The quote will show
94  the price and size of a job consisting in file1.ps as read from
95  standard input, which would be sent to the apple or hplaser
96  printer.
97
98  $ pykotme
99 
100  This will give a quote for a job consisting of what is on standard
101  input. The quote will list the job size, and the price the job
102  would cost on each printer.
103
104
105This program is free software; you can redistribute it and/or modify
106it under the terms of the GNU General Public License as published by
107the Free Software Foundation; either version 2 of the License, or
108(at your option) any later version.
109
110This program is distributed in the hope that it will be useful,
111but WITHOUT ANY WARRANTY; without even the implied warranty of
112MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
113GNU General Public License for more details.
114
115You should have received a copy of the GNU General Public License
116along with this program; if not, write to the Free Software
117Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
118
119Please e-mail bugs to: %s""" % (version.__version__, version.__author__)
120       
121class PyKotMe(PyKotaTool) :       
122    """A class for pykotme."""
123    def main(self, files, options) :
124        """Gives print quotes."""
125        if not files :
126            files = [ sys.stdin ]
127           
128        nbpages = 0   
129        for filename in files :
130            if filename is sys.stdin :
131                stream = filename
132            else :
133                if filename == "-" :
134                    stream = sys.stdin
135                else :   
136                    try :
137                        stream = open(filename, "rb")
138                    except IOError, msg :   
139                        sys.stderr.write("%s\n" % msg)
140                        continue
141            nb = self.getNbPages(stream)
142            if nb is None :
143                sys.stderr.write(_("Unable to compute size of %s in number of pages.\n") % filename)
144            else :
145                nbpages += nb
146            if not (filename is sys.stdin) :       
147                stream.close()
148               
149        # get current user
150        uid = os.geteuid()
151        username = pwd.getpwuid(uid)[0]
152        user = self.storage.getUser(username)
153        if user.Exists and user.LimitBy and (user.LimitBy.lower() == "balance"):
154            print _("Your account balance : %.2f") % (user.AccountBalance or 0.0)
155           
156        printers = self.storage.getMatchingPrinters(options["printer"])
157        if not printers :
158            raise PyKotaToolError, _("There's no printer matching %s") % options["printer"]
159           
160        print _("Job size : %i pages") % nbpages   
161        for printer in printers :
162            userpquota = self.storage.getUserPQuota(user, printer)
163            cost = userpquota.computeJobPrice(nbpages)
164            print _("Cost on printer %s : %.2f") % (printer.Name, cost)
165           
166    def getNbPages(self, stream) :       
167        """Tries to compute the file's size in number of pages, the best we can."""
168        nbpages = [] # in case some user wants to put several %%Pages: entries in the file
169        for line in stream.xreadlines() :
170            line = line.strip()
171            if line.startswith("%%Pages: ") :
172                try :
173                    nbpages.append(int(line[9:]))
174                except ValueError :   
175                    pass
176        if nbpages :           
177            return max(nbpages)
178       
179if __name__ == "__main__" : 
180    retcode = 0
181    try :
182        defaults = { \
183                     "printer" : "*", \
184                   }
185        short_options = "vhP:"
186        long_options = ["help", "version", "printer="]
187       
188        # Initializes the command line tool
189        sender = PyKotMe(doc=__doc__)
190       
191        # parse and checks the command line
192        (options, args) = sender.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1)
193       
194        # sets long options
195        options["help"] = options["h"] or options["help"]
196        options["version"] = options["v"] or options["version"]
197        options["printer"] = options["P"] or options["printer"] or defaults["printer"]
198       
199        if options["help"] :
200            sender.display_usage_and_quit()
201        elif options["version"] :
202            sender.display_version_and_quit()
203        else :
204            retcode = sender.main(args, options)
205    except (PyKotaToolError, PyKotaConfigError, PyKotaStorageError), msg :           
206        sys.stderr.write("%s\n" % msg)
207        sys.stderr.flush()
208        retcode = -1
209
210    try :
211        sender.storage.close()
212    except (TypeError, NameError, AttributeError) :   
213        pass
214       
215    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.