root / pykota / trunk / bin / pkprinters @ 2463

Revision 2463, 10.8 kB (checked in by jerome, 19 years ago)

Now honors the passthrough mode for printers (although it can't be set with pkprinters for now).
The output format for pkprinters --list has changed.
Severity : can be high if thrid party tools rely on the old pkprinters' output format.

  • 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 Printers Manager
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003, 2004, 2005 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22#
23# $Id$
24#
25#
26
27import os
28import sys
29import pwd
30
31from pykota.tool import PyKotaTool, PyKotaToolError, crashed, N_
32
33__doc__ = N_("""pkprinters v%(__version__)s (c) %(__years__)s %(__author__)s
34
35A Printers Manager for PyKota.
36
37command line usage :
38
39  pkprinters [options] printer1 printer2 printer3 ... printerN
40
41options :
42
43  -v | --version       Prints pkprinters's version number then exits.
44  -h | --help          Prints this message then exits.
45 
46  -a | --add           Adds printers if they don't exist on the Quota
47                       Storage Server. If they exist, they are modified
48                       unless -s|--skipexisting is also used.
49                       
50  -d | --delete        Deletes printers from the quota storage.
51 
52  -D | --description d Adds a textual description to printers.
53                       
54  -c | --charge p[,j]  Sets the price per page and per job to charge.
55                       Job price is optional.
56                       If both are to be set, separate them with a comma.
57                       Floating point and negative values are allowed.
58 
59  -g | --groups pg1[,pg2...] Adds or Remove the printer(s) to the printer
60                       groups pg1, pg2, etc... which must already exist.
61                       A printer group is just like a normal printer,
62                       only that it is usually unknown from the printing
63                       system. Create printer groups exactly the same
64                       way that you create printers, then add other
65                       printers to them with this option.
66                       Accounting is done on a printer and on all
67                       the printer groups it belongs to, quota checking
68                       is done on a printer and on all the printer groups
69                       it belongs to.
70                       If the --remove option below is not used, the
71                       default action is to add printers to the specified
72                       printer groups.
73                       
74  -l | --list          List informations about the printer(s) and the
75                       printers groups it is a member of.
76                       
77  -r | --remove        In combination with the --groups option above,                       
78                       remove printers from the specified printers groups.
79                       
80  -s | --skipexisting  In combination with the --add option above, tells
81                       pkprinters to not modify existing printers.
82 
83  printer1 through printerN can contain wildcards if the --add option
84  is not set.
85 
86examples :                             
87
88  $ pkprinters --add -D "HP Printer" --charge 0.05,0.1 hp2100 hp2200 hp8000
89 
90  Will create three printers named hp2100, hp2200 and hp8000.
91  Their price per page will be set at 0.05 unit, and their price
92  per job will be set at 0.1 unit. Units are in your own currency,
93  or whatever you want them to mean.
94  All of their descriptions will be set to the string "HP Printer".
95  If any of these printers already exists, it will also be modified
96  unless the -s|--skipexisting command line option is also used.
97           
98  $ pkprinters --delete "*"
99 
100  This will completely delete all printers and associated quota information,
101  as well as their job history. USE WITH CARE !
102 
103  $ pkprinters --groups Laser,HP "hp*"
104 
105  This will put all printers which name matches "hp*" into printers groups
106  Laser and HP, which MUST already exist.
107 
108  $ pkprinters --groups LexMark --remove hp2200
109 
110  This will remove the hp2200 printer from the LexMark printer group.
111""")
112       
113class PKPrinters(PyKotaTool) :       
114    """A class for a printers manager."""
115    def main(self, names, options) :
116        """Manage printers."""
117        if (not self.config.isAdmin) and (not options["list"]) :
118            raise PyKotaToolError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
119           
120        if options["list"] and not names :
121            names = ["*"]
122           
123        if options["groups"] :       
124            printersgroups = self.storage.getMatchingPrinters(options["groups"])
125            if not printersgroups :
126                raise PyKotaToolError, _("There's no printer matching %s") % " ".join(options["groups"].split(','))
127           
128        if options["charge"] :
129            try :
130                charges = [float(part) for part in options["charge"].split(',', 1)]
131            except ValueError :   
132                raise PyKotaToolError, _("Invalid charge amount value %s") % options["charge"]
133            else :   
134                if len(charges) > 2 :
135                    charges = charges[:2]
136                if len(charges) != 2 :
137                    charges = [charges[0], None]
138                (perpage, perjob) = charges
139               
140        if options["add"] :   
141            printers = []
142            for pname in names :
143                printer = self.storage.getPrinter(pname)
144                if printer.Exists :
145                    if options["skipexisting"] :
146                        self.printInfo(_("Printer %s already exists, skipping.") % printer.Name)
147                    else :   
148                        self.printInfo(_("Printer %s already exists, will be modified.") % printer.Name)
149                        printers.append(printer)
150                else :
151                    if self.isValidName(pname) :
152                        printer = self.storage.addPrinter(pname)
153                        if not printer.Exists :
154                            raise PyKotaToolError, _("Impossible to add printer %s") % pname
155                        else :   
156                            printers.append(printer)
157                    else :   
158                        raise PyKotaToolError, _("Invalid printer name %s") % pname
159        else :       
160            printers = self.storage.getMatchingPrinters(",".join(names))
161            if not printers :
162                raise PyKotaToolError, _("There's no printer matching %s") % " ".join(names)
163                   
164        for printer in printers :       
165            if options["delete"] :
166                printer.delete()
167            elif options["list"] :   
168                parents = ", ".join([p.Name for p in self.storage.getParentPrinters(printer)])
169                if parents : 
170                    parents = "%s %s" % (_("in"), parents)
171                print "%s [%s] (%s + #*%s)" % \
172                      (printer.Name, printer.Description, printer.PricePerJob, \
173                       printer.PricePerPage)
174                print "    %s" % (_("Passthrough mode : %s") % ((printer.PassThrough and _("ON")) or _("OFF")))
175                print "    %s" % (_("Maximum job size : %s") % ((printer.MaxJobSize and (_("%s pages") % printer.MaxJobSize)) or _("Unlimited")))
176                if parents :       
177                    print "    %s" % parents
178            else :   
179                if options["charge"] :
180                    printer.setPrices(perpage, perjob)   
181                if options["description"] is not None :
182                    printer.setDescription(options["description"].strip())
183                if options["groups"] :   
184                    for pgroup in printersgroups :
185                        if options["remove"] :
186                            pgroup.delPrinterFromGroup(printer)
187                        else :
188                            pgroup.addPrinterToGroup(printer)   
189                     
190if __name__ == "__main__" : 
191    retcode = 0
192    try :
193        short_options = "hvac:D:dg:lrs"
194        long_options = ["help", "version", "add", "charge=", "description=", "delete", "groups=", "list", "remove", "skipexisting"]
195       
196        # Initializes the command line tool
197        manager = PKPrinters(doc=__doc__)
198        manager.deferredInit()
199       
200        # parse and checks the command line
201        (options, args) = manager.parseCommandline(sys.argv[1:], short_options, long_options)
202       
203        # sets long options
204        options["help"] = options["h"] or options["help"]
205        options["version"] = options["v"] or options["version"]
206        options["add"] = options["a"] or options["add"]
207        options["charge"] = options["c"] or options["charge"]
208        options["description"] = options["D"] or options["description"]
209        options["delete"] = options["d"] or options["delete"] 
210        options["groups"] = options["g"] or options["groups"]
211        options["list"] = options["l"] or options["list"]
212        options["remove"] = options["r"] or options["remove"]
213        options["skipexisting"] = options["s"] or options["skipexisting"]
214       
215        if options["help"] :
216            manager.display_usage_and_quit()
217        elif options["version"] :
218            manager.display_version_and_quit()
219        elif (options["delete"] and (options["add"] or options["groups"] or options["charge"] or options["remove"] or options["description"])) \
220           or (options["skipexisting"] and not options["add"]) \
221           or (options["list"] and (options["add"] or options["delete"] or options["groups"] or options["charge"] or options["remove"] or options["description"])) :
222            raise PyKotaToolError, _("incompatible options, see help.")
223        elif options["remove"] and not options["groups"] :   
224            raise PyKotaToolError, _("You have to pass printer groups names on the command line")
225        elif (not args) and (not options["list"]) :   
226            raise PyKotaToolError, _("You have to pass printer names on the command line")
227        else :
228            retcode = manager.main(args, options)
229    except KeyboardInterrupt :       
230        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
231    except SystemExit :       
232        pass
233    except :
234        try :
235            manager.crashed("pkprinters failed")
236        except :   
237            crashed("pkprinters failed")
238        retcode = -1
239
240    try :
241        manager.storage.close()
242    except (TypeError, NameError, AttributeError) :   
243        pass
244       
245    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.