root / pykota / trunk / bin / pykosd @ 3260

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

Changed license to GNU GPL v3 or later.
Changed Python source encoding from ISO-8859-15 to UTF-8 (only ASCII
was used anyway).

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