root / pykota / trunk / bin / pykosd @ 3133

Revision 3133, 8.5 kB (checked in by jerome, 17 years ago)

Changed copyright years.

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