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
RevLine 
[1595]1#! /usr/bin/env python
[3260]2# -*- coding: UTF-8 -*-
[1595]3#
[3260]4# PyKota : Print Quotas for CUPS
[1595]5#
[3133]6# (c) 2003, 2004, 2005, 2006, 2007 Jerome Alet <alet@librelogiciel.com>
[3260]7# This program is free software: you can redistribute it and/or modify
[1595]8# it under the terms of the GNU General Public License as published by
[3260]9# the Free Software Foundation, either version 3 of the License, or
[1595]10# (at your option) any later version.
[3260]11#
[1595]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
[3260]18# along with this program.  If not, see <http://www.gnu.org/licenses/>.
[1595]19#
20# $Id$
21#
[2028]22#
[1595]23
24import sys
25import os
26import pwd
27import time
28
[1607]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
[2512]35from pykota.tool import PyKotaTool, PyKotaToolError, PyKotaCommandLineError, crashed, N_
[1595]36
[2344]37__doc__ = N_("""pykosd v%(__version__)s (c) %(__years__)s %(__author__)s
[2267]38
[1605]39An OSD quota monitor for PyKota.
[1597]40
[1605]41command line usage :
42
43  pykosd [options]
44
45options :
46
[1832]47  -v | --version       Prints pykosd's version number then exits.
[1605]48  -h | --help          Prints this message then exits.
49 
[1608]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                       
[1605]54  -d | --duration d    Sets the duration of the display in seconds.
55                       Defaults to 3 seconds.
[1607]56                       
57  -f | --font f        Sets the font to use for display.                     
58                       Defaults to the Python OSD library's default.
[1605]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.
[2344]74""")
[1605]75
76
77class PyKOSD(PyKotaTool) :
[2829]78    """A class for an On Screen Display print quota monitor."""
[1605]79    def main(self, args, options) :
80        """Main function starts here."""
81        try :   
82            duration = int(options["duration"])
[2512]83            if duration <= 0 :
84                raise ValueError 
[1605]85        except :   
[2512]86            raise PyKotaCommandLineError, _("Invalid duration option %s") % str(options["duration"])
[1605]87           
88        try :   
89            loop = int(options["loop"])
[2512]90            if loop < 0 :
91                raise ValueError
[1605]92        except :   
[2512]93            raise PyKotaCommandLineError, _("Invalid loop option %s") % str(options["loop"])
[1605]94           
95        try :   
96            sleep = float(options["sleep"])
[2512]97            if sleep <= 0 :
98                raise ValueError
[1605]99        except :   
[2512]100            raise PyKotaCommandLineError, _("Invalid sleep option %s") % str(options["sleep"])
[1605]101           
[1608]102        color = options["color"]   
103        if not color.startswith("#") :
104            color = "#%s" % color
105        if len(color) != 7 :   
[2512]106            raise PyKotaCommandLineError, _("Invalid color option %s") % str(color)
[1608]107        savecolor = color
108       
[2232]109        uname = pwd.getpwuid(os.getuid())[0]
[1605]110        while 1 :
[1608]111            color = savecolor
[2692]112            user = self.storage.getUserFromBackend(uname)        # don't use cache
[1595]113            if not user.Exists :
[2512]114                raise PyKotaCommandLineError, _("User %s doesn't exist in PyKota's database") % uname
[1596]115            if user.LimitBy == "quota" :   
[2692]116                printers = self.storage.getMatchingPrinters("*")
117                upquotas = [ self.storage.getUserPQuotaFromBackend(user, p) for p in printers ] # don't use cache
[1596]118                nblines = len(upquotas)
[1608]119                display = pyosd.osd(font=options["font"], colour=color, timeout=duration, shadow=2, lines=nblines)
[1596]120                for line in range(nblines) :
121                    upq = upquotas[line]
122                    if upq.HardLimit is None :
123                        if upq.SoftLimit is None :
[1597]124                            percent = "%s" % upq.PageCounter
[1596]125                        else :       
[1597]126                            percent = "%s%%" % min((upq.PageCounter * 100) / upq.SoftLimit, 100)
[1596]127                    else :       
[1597]128                        percent = "%s%%" % min((upq.PageCounter * 100) / upq.HardLimit, 100)
[1605]129                    display.display(_("Pages used on %s : %s") % (upq.Printer.Name, percent), type=pyosd.TYPE_STRING, line=line)
[2544]130            elif user.LimitBy == "balance" :
[2692]131                if user.AccountBalance <= self.config.getBalanceZero() :
[1597]132                    color = "#FF0000"
[1607]133                display = pyosd.osd(font=options["font"], colour=color, timeout=duration, shadow=2)
[1605]134                display.display(_("PyKota Units left : %.2f") % user.AccountBalance, type=pyosd.TYPE_STRING)
[2544]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)
[1608]146               
[1605]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 = { \
[1608]160                     "color" : "#00FF00", \
[1605]161                     "duration" : "3", \
[1607]162                     "font" : pyosd.default_font, \
[1605]163                     "loop" : "0", \
164                     "sleep" : "180", \
165                   }
[1608]166        short_options = "hvc:d:f:l:s:"
167        long_options = ["help", "version", "color=", "colour=", "duration=", "font=", "loop=", "sleep="]
[1605]168       
169        cmd = PyKOSD(doc=__doc__)
[2210]170        cmd.deferredInit()
[1605]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"]
[1608]178        options["color"] = options["c"] or options["color"] or options["colour"] or defaults["color"]
[1605]179        options["duration"] = options["d"] or options["duration"] or defaults["duration"]
[1607]180        options["font"] = options["f"] or options["font"] or defaults["font"]
[1605]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
[2216]192    except KeyboardInterrupt :       
193        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
[2609]194        retcode = -3
[2512]195    except PyKotaCommandLineError, msg :   
196        sys.stderr.write("%s : %s\n" % (sys.argv[0], msg))
[2609]197        retcode = -2
[1605]198    except SystemExit :       
199        pass
200    except :   
[1595]201        try :
[1605]202            cmd.crashed("pykosd failed")
[1595]203        except :   
[1605]204            crashed("pykosd failed")
205       
206    try :
207        cmd.storage.close()
208    except :   
209        pass
210       
[1595]211    sys.exit(retcode)
Note: See TracBrowser for help on using the browser.