root / pykota / trunk / bin / pykotme @ 1257

Revision 1257, 7.3 kB (checked in by jalet, 21 years ago)

Copyright year changed.

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