root / pykota / trunk / bin / pkprinters @ 2267

Revision 2267, 11.1 kB (checked in by jerome, 19 years ago)

Moved the copyright strings out of the docstrings

  • 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#
26
27import os
28import sys
29import pwd
30
31from pykota.tool import PyKotaTool, PyKotaToolError, crashed, N_
32
33__doc__ = N_("""pkprinters v%s (c) %s %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 
112This program is free software; you can redistribute it and/or modify
113it under the terms of the GNU General Public License as published by
114the Free Software Foundation; either version 2 of the License, or
115(at your option) any later version.
116
117This program is distributed in the hope that it will be useful,
118but WITHOUT ANY WARRANTY; without even the implied warranty of
119MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
120GNU General Public License for more details.
121
122You should have received a copy of the GNU General Public License
123along with this program; if not, write to the Free Software
124Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
125
126Please e-mail bugs to: %s""")
127       
128class PKPrinters(PyKotaTool) :       
129    """A class for edpykota."""
130    def main(self, names, options) :
131        """Manage printers."""
132        if (not self.config.isAdmin) and (not options["list"]) :
133            raise PyKotaToolError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
134           
135        if options["list"] and not names :
136            names = ["*"]
137           
138        if options["groups"] :       
139            printersgroups = self.storage.getMatchingPrinters(options["groups"])
140            if not printersgroups :
141                raise PyKotaToolError, _("There's no printer matching %s") % " ".join(options["groups"].split(','))
142           
143        if options["charge"] :
144            try :
145                charges = [float(part) for part in options["charge"].split(',', 1)]
146            except ValueError :   
147                raise PyKotaToolError, _("Invalid charge amount value %s") % options["charge"]
148            else :   
149                if len(charges) > 2 :
150                    charges = charges[:2]
151                if len(charges) != 2 :
152                    charges = [charges[0], None]
153                (perpage, perjob) = charges
154               
155        if options["add"] :   
156            printers = []
157            for pname in names :
158                printer = self.storage.getPrinter(pname)
159                if printer.Exists :
160                    if options["skipexisting"] :
161                        self.printInfo(_("Printer %s already exists, skipping.") % printer.Name)
162                    else :   
163                        self.printInfo(_("Printer %s already exists, will be modified.") % printer.Name)
164                        printers.append(printer)
165                else :
166                    if self.isValidName(pname) :
167                        printer = self.storage.addPrinter(pname)
168                        if not printer.Exists :
169                            raise PyKotaToolError, _("Impossible to add printer %s") % pname
170                        else :   
171                            printers.append(printer)
172                    else :   
173                        raise PyKotaToolError, _("Invalid printer name %s") % pname
174        else :       
175            printers = self.storage.getMatchingPrinters(",".join(names))
176            if not printers :
177                raise PyKotaToolError, _("There's no printer matching %s") % " ".join(names)
178                   
179        for printer in printers :       
180            if options["delete"] :
181                printer.delete()
182            elif options["list"] :   
183                parents = ", ".join([p.Name for p in self.storage.getParentPrinters(printer)])
184                if parents : 
185                    parents = "%s %s" % (_("in"), parents)
186                print "%s [%s] (%s + #*%s) %s" % \
187                      (printer.Name, printer.Description, printer.PricePerJob, \
188                       printer.PricePerPage, parents)
189            else :   
190                if options["charge"] :
191                    printer.setPrices(perpage, perjob)   
192                if options["description"] is not None :
193                    printer.setDescription(options["description"].strip())
194                if options["groups"] :   
195                    for pgroup in printersgroups :
196                        if options["remove"] :
197                            pgroup.delPrinterFromGroup(printer)
198                        else :
199                            pgroup.addPrinterToGroup(printer)   
200                     
201if __name__ == "__main__" : 
202    retcode = 0
203    try :
204        short_options = "hvac:D:dg:lrs"
205        long_options = ["help", "version", "add", "charge=", "description=", "delete", "groups=", "list", "remove", "skipexisting"]
206       
207        # Initializes the command line tool
208        manager = PKPrinters(doc=__doc__)
209        manager.deferredInit()
210       
211        # parse and checks the command line
212        (options, args) = manager.parseCommandline(sys.argv[1:], short_options, long_options)
213       
214        # sets long options
215        options["help"] = options["h"] or options["help"]
216        options["version"] = options["v"] or options["version"]
217        options["add"] = options["a"] or options["add"]
218        options["charge"] = options["c"] or options["charge"]
219        options["description"] = options["D"] or options["description"]
220        options["delete"] = options["d"] or options["delete"] 
221        options["groups"] = options["g"] or options["groups"]
222        options["list"] = options["l"] or options["list"]
223        options["remove"] = options["r"] or options["remove"]
224        options["skipexisting"] = options["s"] or options["skipexisting"]
225       
226        if options["help"] :
227            manager.display_usage_and_quit()
228        elif options["version"] :
229            manager.display_version_and_quit()
230        elif (options["delete"] and (options["add"] or options["groups"] or options["charge"] or options["remove"] or options["description"])) \
231           or (options["skipexisting"] and not options["add"]) \
232           or (options["list"] and (options["add"] or options["delete"] or options["groups"] or options["charge"] or options["remove"] or options["description"])) :
233            raise PyKotaToolError, _("incompatible options, see help.")
234        elif options["remove"] and not options["groups"] :   
235            raise PyKotaToolError, _("You have to pass printer groups names on the command line")
236        elif (not args) and (not options["list"]) :   
237            raise PyKotaToolError, _("You have to pass printer names on the command line")
238        else :
239            retcode = manager.main(args, options)
240    except KeyboardInterrupt :       
241        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
242    except SystemExit :       
243        pass
244    except :
245        try :
246            manager.crashed("pkprinters failed")
247        except :   
248            crashed("pkprinters failed")
249        retcode = -1
250
251    try :
252        manager.storage.close()
253    except (TypeError, NameError, AttributeError) :   
254        pass
255       
256    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.