root / pykota / trunk / bin / repykota @ 3294

Revision 3294, 6.5 kB (checked in by jerome, 16 years ago)

Added modules to store utility functions and application
intialization code, which has nothing to do in classes.
Modified tool.py accordingly (far from being finished)
Use these new modules where necessary.
Now converts all command line arguments to unicode before
beginning to work. Added a proper logging method for already
encoded query strings.

  • 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: UTF-8 -*-
3#
4# PyKota : Print Quotas for CUPS
5#
6# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
7# This program is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program.  If not, see <http://www.gnu.org/licenses/>.
19#
20# $Id$
21#
22#
23
24import sys
25import os
26import pwd
27
28from mx import DateTime
29
30import pykota.appinit
31from pykota.utils import *
32
33from pykota.errors import PyKotaToolError, PyKotaCommandLineError
34from pykota.tool import PyKotaTool, crashed, N_
35from pykota import reporter
36
37__doc__ = N_("""repykota v%(__version__)s (c) %(__years__)s %(__author__)s
38
39Generates print quota reports.
40
41command line usage :
42
43  repykota [options]
44
45options :
46
47  -v | --version       Prints repykota's version number then exits.
48  -h | --help          Prints this message then exits.
49 
50  -u | --users         Generates a report on users quota, this is
51                       the default.
52 
53  -g | --groups        Generates a report on group quota instead of users.
54 
55  -i | --ingroups g1[,g2...]  Only lists users who are members of these
56                              groups. Reserved to PyKota Administrators.
57 
58  -P | --printer p     Report quotas on this printer only. Actually p can
59                       use wildcards characters to select only
60                       some printers. The default value is *, meaning
61                       all printers.
62                       You can specify several names or wildcards,
63                       by separating them with commas.
64 
65examples :                             
66
67  $ repykota --printer lp
68 
69  This will print the quota status for all users who use the lp printer.
70
71  $ repykota
72 
73  This will print the quota status for all users on all printers.
74 
75  $ repykota --printer "laser*,*pson" jerome "jo*"
76 
77  This will print the quota status for user jerome and all users
78  whose name begins with "jo" on all printers which name begins
79  with "laser" or ends with "pson".
80 
81  If launched by an user who is not a PyKota administrator, additionnal
82  arguments representing users or groups names are ignored, and only the
83  current user/group is reported.
84""")
85       
86class RePyKota(PyKotaTool) :       
87    """A class for repykota."""
88    def main(self, ugnames, options) :
89        """Print Quota reports generator."""
90        if self.config.isAdmin :
91            # PyKota administrator
92            if not ugnames :
93                # no username, means all usernames
94                ugnames = [ "*" ]
95               
96            if options["ingroups"] :
97                groupsnames = options["ingroups"].split(",")
98                groups = [self.storage.getGroup(gname) for gname in groupsnames]
99                members = {}
100                for group in groups :
101                    if not group.Exists :
102                        self.printInfo("Group %s doesn't exist." % group.Name, "warn")
103                    else :   
104                        for user in self.storage.getGroupMembers(group) :
105                            members[user.Name] = user
106                ugnames = [ m for m in members.keys() if self.matchString(m, ugnames) ]
107        else :       
108            # reports only the current user
109            if options["ingroups"] :
110                raise PyKotaCommandLineError, _("Option --ingroups is reserved to PyKota Administrators.")
111               
112            username = pwd.getpwuid(os.geteuid())[0]
113            if options["groups"] :
114                user = self.storage.getUser(username)
115                if user.Exists :
116                    ugnames = [ g.Name for g in self.storage.getUserGroups(user) ]
117                else :   
118                    ugnames = [ ]
119            else :
120                ugnames = [ username ]
121       
122        printers = self.storage.getMatchingPrinters(options["printer"])
123        if not printers :
124            raise PyKotaCommandLineError, _("There's no printer matching %s") % options["printer"]
125           
126        self.reportingtool = reporter.openReporter(self, "text", printers, ugnames, (options["groups"] and 1) or 0)   
127        print self.reportingtool.generateReport()
128                   
129if __name__ == "__main__" : 
130    retcode = 0
131    try :
132        defaults = { \
133                     "printer" : "*", \
134                   }
135        short_options = "vhugi:P:"
136        long_options = ["help", "version", "users", "groups", "ingroups=", "printer="]
137       
138        # Initializes the command line tool
139        reportTool = RePyKota(doc=__doc__)
140        reportTool.deferredInit()
141       
142        # parse and checks the command line
143        (options, args) = reportTool.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1)
144       
145        # sets long options
146        options["help"] = options["h"] or options["help"]
147        options["version"] = options["v"] or options["version"]
148        options["users"] = options["u"] or options["users"]
149        options["groups"] = options["g"] or options["groups"]
150        options["printer"] = options["P"] or options["printer"] or defaults["printer"]
151        options["ingroups"] = options["i"] or options["ingroups"]
152       
153        if options["help"] :
154            reportTool.display_usage_and_quit()
155        elif options["version"] :
156            reportTool.display_version_and_quit()
157        elif (options["users"] or options["ingroups"]) and options["groups"] :
158            raise PyKotaCommandLineError, _("incompatible options, see help.")
159        else :
160            retcode = reportTool.main(args, options)
161    except KeyboardInterrupt :       
162        logerr("\nInterrupted with Ctrl+C !\n")
163        retcode = -3
164    except PyKotaCommandLineError, msg :   
165        logerr("%s : %s\n" % (sys.argv[0], msg))
166        retcode = -2
167    except SystemExit :       
168        pass
169    except :
170        try :
171            reportTool.crashed("repykota failed")
172        except :   
173            crashed("repykota failed")
174        retcode = -1
175
176    try :
177        reportTool.storage.close()
178    except (TypeError, NameError, AttributeError) :   
179        pass
180       
181    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.