root / pykota / trunk / bin / pykosd @ 3288

Revision 3288, 8.4 kB (checked in by jerome, 16 years ago)

Moved all exceptions definitions to a dedicated module.

  • 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
27import time
28
29try :
30    import pyosd
31except ImportError :   
32    sys.stderr.write("Sorry ! You need both xosd and the Python OSD library (pyosd) for this software to work.\n")
33    sys.exit(-1)
34
35from pykota.errors import PyKotaToolError, PyKotaCommandLineError
36from pykota.tool import PyKotaTool, crashed, N_
37
38__doc__ = N_("""pykosd v%(__version__)s (c) %(__years__)s %(__author__)s
39
40An OSD quota monitor for PyKota.
41
42command line usage :
43
44  pykosd [options]
45
46options :
47
48  -v | --version       Prints pykosd's version number then exits.
49  -h | --help          Prints this message then exits.
50 
51  -c | --color #rrggbb Sets the color to use for display as an hexadecimal
52                       triplet, for example #FF0000 is 100%% red.
53                       Defaults to 100%% green (#00FF00).
54                       
55  -d | --duration d    Sets the duration of the display in seconds.
56                       Defaults to 3 seconds.
57                       
58  -f | --font f        Sets the font to use for display.                     
59                       Defaults to the Python OSD library's default.
60 
61  -l | --loop n        Sets the number of times the info will be displayed.
62                       Defaults to 0, which means loop forever.
63                       
64  -s | --sleep s       Sets the sleeping duration between two displays
65                       in seconds. Defaults to 180 seconds (3 minutes).
66                       
67 
68examples :                             
69
70  $ pykosd -s 60 --loop 5
71 
72  Will launch pykosd. Display will be refreshed every 60 seconds,
73  and will last for 3 seconds (the default) each time. After five
74  iterations, the program will exit.
75""")
76
77
78class PyKOSD(PyKotaTool) :
79    """A class for an On Screen Display print quota monitor."""
80    def main(self, args, options) :
81        """Main function starts here."""
82        try :   
83            duration = int(options["duration"])
84            if duration <= 0 :
85                raise ValueError 
86        except :   
87            raise PyKotaCommandLineError, _("Invalid duration option %s") % str(options["duration"])
88           
89        try :   
90            loop = int(options["loop"])
91            if loop < 0 :
92                raise ValueError
93        except :   
94            raise PyKotaCommandLineError, _("Invalid loop option %s") % str(options["loop"])
95           
96        try :   
97            sleep = float(options["sleep"])
98            if sleep <= 0 :
99                raise ValueError
100        except :   
101            raise PyKotaCommandLineError, _("Invalid sleep option %s") % str(options["sleep"])
102           
103        color = options["color"]   
104        if not color.startswith("#") :
105            color = "#%s" % color
106        if len(color) != 7 :   
107            raise PyKotaCommandLineError, _("Invalid color option %s") % str(color)
108        savecolor = color
109       
110        uname = pwd.getpwuid(os.getuid())[0]
111        while 1 :
112            color = savecolor
113            user = self.storage.getUserFromBackend(uname)        # don't use cache
114            if not user.Exists :
115                raise PyKotaCommandLineError, _("User %s doesn't exist in PyKota's database") % uname
116            if user.LimitBy == "quota" :   
117                printers = self.storage.getMatchingPrinters("*")
118                upquotas = [ self.storage.getUserPQuotaFromBackend(user, p) for p in printers ] # don't use cache
119                nblines = len(upquotas)
120                display = pyosd.osd(font=options["font"], colour=color, timeout=duration, shadow=2, lines=nblines)
121                for line in range(nblines) :
122                    upq = upquotas[line]
123                    if upq.HardLimit is None :
124                        if upq.SoftLimit is None :
125                            percent = "%s" % upq.PageCounter
126                        else :       
127                            percent = "%s%%" % min((upq.PageCounter * 100) / upq.SoftLimit, 100)
128                    else :       
129                        percent = "%s%%" % min((upq.PageCounter * 100) / upq.HardLimit, 100)
130                    display.display(_("Pages used on %s : %s") % (upq.Printer.Name, percent), type=pyosd.TYPE_STRING, line=line)
131            elif user.LimitBy == "balance" :
132                if user.AccountBalance <= self.config.getBalanceZero() :
133                    color = "#FF0000"
134                display = pyosd.osd(font=options["font"], colour=color, timeout=duration, shadow=2)
135                display.display(_("PyKota Units left : %.2f") % user.AccountBalance, type=pyosd.TYPE_STRING)
136            elif user.LimitBy == "noprint" :   
137                display = pyosd.osd(font=options["font"], colour="#FF0000", timeout=duration, shadow=2)
138                display.display(_("Printing denied."), type=pyosd.TYPE_STRING)
139            elif user.LimitBy == "noquota" :   
140                display = pyosd.osd(font=options["font"], colour=savecolor, timeout=duration, shadow=2)
141                display.display(_("Printing not limited."), type=pyosd.TYPE_STRING)
142            elif user.LimitBy == "nochange" :   
143                display = pyosd.osd(font=options["font"], colour=savecolor, timeout=duration, shadow=2)
144                display.display(_("Printing not limited, no accounting."), type=pyosd.TYPE_STRING)
145            else :   
146                raise PyKotaToolError, "Incorrect limitation factor %s for user %s" % (repr(user.LimitBy), user.Name)
147               
148            time.sleep(duration + 1)
149            if loop :
150                loop -= 1
151                if not loop :
152                    break
153            time.sleep(sleep)       
154           
155        return 0   
156       
157if __name__ == "__main__" :
158    retcode = -1
159    try :
160        defaults = { \
161                     "color" : "#00FF00", \
162                     "duration" : "3", \
163                     "font" : pyosd.default_font, \
164                     "loop" : "0", \
165                     "sleep" : "180", \
166                   }
167        short_options = "hvc:d:f:l:s:"
168        long_options = ["help", "version", "color=", "colour=", "duration=", "font=", "loop=", "sleep="]
169       
170        cmd = PyKOSD(doc=__doc__)
171        cmd.deferredInit()
172       
173        # parse and checks the command line
174        (options, args) = cmd.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1)
175       
176        # sets long options
177        options["help"] = options["h"] or options["help"]
178        options["version"] = options["v"] or options["version"]
179        options["color"] = options["c"] or options["color"] or options["colour"] or defaults["color"]
180        options["duration"] = options["d"] or options["duration"] or defaults["duration"]
181        options["font"] = options["f"] or options["font"] or defaults["font"]
182        options["loop"] = options["l"] or options["loop"] or defaults["loop"]
183        options["sleep"] = options["s"] or options["sleep"] or defaults["sleep"]
184       
185        if options["help"] :
186            cmd.display_usage_and_quit()
187        elif options["version"] :
188            cmd.display_version_and_quit()
189        else :   
190            retcode = cmd.main(args, options)
191    except KeyboardInterrupt :
192        retcode = 0
193    except KeyboardInterrupt :       
194        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
195        retcode = -3
196    except PyKotaCommandLineError, msg :   
197        sys.stderr.write("%s : %s\n" % (sys.argv[0], msg))
198        retcode = -2
199    except SystemExit :       
200        pass
201    except :   
202        try :
203            cmd.crashed("pykosd failed")
204        except :   
205            crashed("pykosd failed")
206       
207    try :
208        cmd.storage.close()
209    except :   
210        pass
211       
212    sys.exit(retcode)
Note: See TracBrowser for help on using the browser.