root / pykota / trunk / bin / pkprinters @ 1517

Revision 1517, 11.2 kB (checked in by jalet, 20 years ago)

Improved error logging.
crashrecipient directive added.
Now exports the job's size in bytes too.

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