root / pykota / trunk / bin / pkprinters @ 2132

Revision 2028, 12.8 kB (checked in by jalet, 20 years ago)

Modified copyright years

  • 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22#
23# $Id$
24#
25# $Log$
26# Revision 1.19  2005/01/17 08:44:24  jalet
27# Modified copyright years
28#
29# Revision 1.18  2004/10/20 12:32:51  jalet
30# Fixed typo in help
31#
32# Revision 1.17  2004/10/13 21:40:10  jalet
33# Now mandates that the user be a PyKota administrator to allow dangerous
34# command line options. --list is still allowed to mere mortals though.
35#
36# Revision 1.16  2004/10/11 22:53:05  jalet
37# Postponed string interpolation to help message's output method
38#
39# Revision 1.15  2004/10/11 12:49:06  jalet
40# Renders help translatable
41#
42# Revision 1.14  2004/07/19 22:37:13  jalet
43# pykosd is now a very good tool
44#
45# Revision 1.13  2004/07/01 19:56:41  jalet
46# Better dispatching of error messages
47#
48# Revision 1.12  2004/07/01 17:45:47  jalet
49# Added code to handle the description field for printers
50#
51# Revision 1.11  2004/06/18 13:34:48  jalet
52# Now all tracebacks include PyKota's version number
53#
54# Revision 1.10  2004/06/07 18:43:40  jalet
55# Fixed over-verbose exits when displaying help or version number
56#
57# Revision 1.9  2004/06/03 21:50:34  jalet
58# Improved error logging.
59# crashrecipient directive added.
60# Now exports the job's size in bytes too.
61#
62# Revision 1.8  2004/05/06 20:30:24  jalet
63# Added --skipexisting command line option to pkprinters
64#
65# Revision 1.7  2004/05/06 12:51:58  jalet
66# Documentation
67#
68# Revision 1.6  2004/05/06 12:37:29  jalet
69# pkpgcounter : comments
70# pkprinters : when --add is used, existing printers are now skipped.
71#
72# Revision 1.5  2004/04/16 16:52:09  jalet
73# Better formatting
74#
75# Revision 1.4  2004/04/16 16:47:57  jalet
76# pkprinters now accept the --list command line option
77#
78# Revision 1.3  2004/02/04 13:24:41  jalet
79# pkprinters can now remove printers from printers groups.
80#
81# Revision 1.2  2004/02/04 12:52:37  jalet
82# pkprinters' help
83#
84# Revision 1.1  2004/02/04 11:16:59  jalet
85# pkprinters command line tool added.
86#
87#
88#
89
90import os
91import sys
92import pwd
93
94from pykota.tool import PyKotaTool, PyKotaToolError, crashed, N_
95
96__doc__ = N_("""pkprinters v%s (c) 2003, 2004, 2005 C@LL - Conseil Internet & Logiciels Libres
97A Printers Manager for PyKota.
98
99command line usage :
100
101  pkprinters [options] printer1 printer2 printer3 ... printerN
102
103options :
104
105  -v | --version       Prints pkprinters's version number then exits.
106  -h | --help          Prints this message then exits.
107 
108  -a | --add           Adds printers if they don't exist on the Quota
109                       Storage Server. If they exist, they are modified
110                       unless -s|--skipexisting is also used.
111                       
112  -d | --delete        Deletes printers from the quota storage.
113 
114  -D | --description d Adds a textual description to printers.
115                       
116  -c | --charge p[,j]  Sets the price per page and per job to charge.
117                       Job price is optional.
118                       If both are to be set, separate them with a comma.
119                       Floating point and negative values are allowed.
120 
121  -g | --groups pg1[,pg2...] Adds or Remove the printer(s) to the printer
122                       groups pg1, pg2, etc... which must already exist.
123                       A printer group is just like a normal printer,
124                       only that it is usually unknown from the printing
125                       system. Create printer groups exactly the same
126                       way that you create printers, then add other
127                       printers to them with this option.
128                       Accounting is done on a printer and on all
129                       the printer groups it belongs to, quota checking
130                       is done on a printer and on all the printer groups
131                       it belongs to.
132                       If the --remove option below is not used, the
133                       default action is to add printers to the specified
134                       printer groups.
135                       
136  -l | --list          List informations about the printer(s) and the
137                       printers groups it is a member of.
138                       
139  -r | --remove        In combination with the --groups option above,                       
140                       remove printers from the specified printers groups.
141                       
142  -s | --skipexisting  In combination with the --add option above, tells
143                       pkprinters to not modify existing printers.
144 
145  printer1 through printerN can contain wildcards if the --add option
146  is not set.
147 
148examples :                             
149
150  $ pkprinters --add -D "HP Printer" --charge 0.05,0.1 hp2100 hp2200 hp8000
151 
152  Will create three printers named hp2100, hp2200 and hp8000.
153  Their price per page will be set at 0.05 unit, and their price
154  per job will be set at 0.1 unit. Units are in your own currency,
155  or whatever you want them to mean.
156  All of their descriptions will be set to the string "HP Printer".
157  If any of these printers already exists, it will also be modified
158  unless the -s|--skipexisting command line option is also used.
159           
160  $ pkprinters --delete "*"
161 
162  This will completely delete all printers and associated quota information,
163  as well as their job history. USE WITH CARE !
164 
165  $ pkprinters --groups Laser,HP "hp*"
166 
167  This will put all printers which name matches "hp*" into printers groups
168  Laser and HP, which MUST already exist.
169 
170  $ pkprinters --groups LexMark --remove hp2200
171 
172  This will remove the hp2200 printer from the LexMark printer group.
173 
174This program is free software; you can redistribute it and/or modify
175it under the terms of the GNU General Public License as published by
176the Free Software Foundation; either version 2 of the License, or
177(at your option) any later version.
178
179This program is distributed in the hope that it will be useful,
180but WITHOUT ANY WARRANTY; without even the implied warranty of
181MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
182GNU General Public License for more details.
183
184You should have received a copy of the GNU General Public License
185along with this program; if not, write to the Free Software
186Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
187
188Please e-mail bugs to: %s""")
189       
190class PKPrinters(PyKotaTool) :       
191    """A class for edpykota."""
192    def main(self, names, options) :
193        """Manage printers."""
194        if (not self.config.isAdmin) and (not options["list"]) :
195            raise PyKotaToolError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
196           
197        if options["list"] and not names :
198            names = ["*"]
199           
200        if options["groups"] :       
201            printersgroups = self.storage.getMatchingPrinters(options["groups"])
202            if not printersgroups :
203                raise PyKotaToolError, _("There's no printer matching %s") % " ".join(options["groups"].split(','))
204           
205        if options["charge"] :
206            try :
207                charges = [float(part) for part in options["charge"].split(',', 1)]
208            except ValueError :   
209                raise PyKotaToolError, _("Invalid charge amount value %s") % options["charge"]
210            else :   
211                if len(charges) > 2 :
212                    charges = charges[:2]
213                if len(charges) != 2 :
214                    charges = [charges[0], None]
215                (perpage, perjob) = charges
216               
217        if options["add"] :   
218            printers = []
219            for pname in names :
220                printer = self.storage.getPrinter(pname)
221                if printer.Exists :
222                    if options["skipexisting"] :
223                        self.printInfo(_("Printer %s already exists, skipping.") % printer.Name)
224                    else :   
225                        self.printInfo(_("Printer %s already exists, will be modified.") % printer.Name)
226                        printers.append(printer)
227                else :
228                    if self.isValidName(pname) :
229                        printer = self.storage.addPrinter(pname)
230                        if not printer.Exists :
231                            raise PyKotaToolError, _("Impossible to add printer %s") % pname
232                        else :   
233                            printers.append(printer)
234                    else :   
235                        raise PyKotaToolError, _("Invalid printer name %s") % pname
236        else :       
237            printers = self.storage.getMatchingPrinters(",".join(names))
238            if not printers :
239                raise PyKotaToolError, _("There's no printer matching %s") % " ".join(names)
240                   
241        for printer in printers :       
242            if options["delete"] :
243                printer.delete()
244            elif options["list"] :   
245                parents = ", ".join([p.Name for p in self.storage.getParentPrinters(printer)])
246                if parents : 
247                    parents = "%s %s" % (_("in"), parents)
248                print "%s [%s] (%s + #*%s) %s" % \
249                      (printer.Name, printer.Description, printer.PricePerJob, \
250                       printer.PricePerPage, parents)
251            else :   
252                if options["charge"] :
253                    printer.setPrices(perpage, perjob)   
254                if options["description"] is not None :
255                    printer.setDescription(options["description"].strip())
256                if options["groups"] :   
257                    for pgroup in printersgroups :
258                        if options["remove"] :
259                            pgroup.delPrinterFromGroup(printer)
260                        else :
261                            pgroup.addPrinterToGroup(printer)   
262                     
263if __name__ == "__main__" : 
264    retcode = 0
265    try :
266        short_options = "hvac:D:dg:lrs"
267        long_options = ["help", "version", "add", "charge=", "description=", "delete", "groups=", "list", "remove", "skipexisting"]
268       
269        # Initializes the command line tool
270        manager = PKPrinters(doc=__doc__)
271       
272        # parse and checks the command line
273        (options, args) = manager.parseCommandline(sys.argv[1:], short_options, long_options)
274       
275        # sets long options
276        options["help"] = options["h"] or options["help"]
277        options["version"] = options["v"] or options["version"]
278        options["add"] = options["a"] or options["add"]
279        options["charge"] = options["c"] or options["charge"]
280        options["description"] = options["D"] or options["description"]
281        options["delete"] = options["d"] or options["delete"] 
282        options["groups"] = options["g"] or options["groups"]
283        options["list"] = options["l"] or options["list"]
284        options["remove"] = options["r"] or options["remove"]
285        options["skipexisting"] = options["s"] or options["skipexisting"]
286       
287        if options["help"] :
288            manager.display_usage_and_quit()
289        elif options["version"] :
290            manager.display_version_and_quit()
291        elif (options["delete"] and (options["add"] or options["groups"] or options["charge"] or options["remove"] or options["description"])) \
292           or (options["skipexisting"] and not options["add"]) \
293           or (options["list"] and (options["add"] or options["delete"] or options["groups"] or options["charge"] or options["remove"] or options["description"])) :
294            raise PyKotaToolError, _("incompatible options, see help.")
295        elif options["remove"] and not options["groups"] :   
296            raise PyKotaToolError, _("You have to pass printer groups names on the command line")
297        elif (not args) and (not options["list"]) :   
298            raise PyKotaToolError, _("You have to pass printer names on the command line")
299        else :
300            retcode = manager.main(args, options)
301    except SystemExit :       
302        pass
303    except :
304        try :
305            manager.crashed("pkprinters failed")
306        except :   
307            crashed("pkprinters failed")
308        retcode = -1
309
310    try :
311        manager.storage.close()
312    except (TypeError, NameError, AttributeError) :   
313        pass
314       
315    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.