root / pykota / trunk / bin / pknotify @ 2779

Revision 2779, 7.8 kB (checked in by jerome, 18 years ago)

pknotify now works just fine with PyKotIcon? and is 100% generic.

  • 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# A notifier for PyKota
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003, 2004, 2005, 2006 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 popen2
30import xmlrpclib
31
32from pykota.tool import Tool, PyKotaToolError, PyKotaCommandLineError, crashed, N_
33
34__doc__ = N_("""pknotify v%(__version__)s (c) %(__years__)s %(__author__)s
35
36Notifies or ask questions to end users who launched the PyKotIcon application.
37
38command line usage :
39
40  pknotify  [options]  [arguments]
41
42options :
43
44  -v | --version             Prints pkbanner's version number then exits.
45  -h | --help                Prints this message then exits.
46 
47  -d | --destination h[:p]   Sets the destination hostname and optional
48                             port onto which contact the remote PyKotIcon
49                             application. This option is mandatory.
50                             When not specified, the port defaults to 7654.
51                             
52  -a | --ask                 Tells pknotify to ask something to the end
53                             user. Then pknotify will output the result.
54                       
55  -c | --confirm             Tells pknotify to ask for either a confirmation                       
56                             or abortion.
57                             
58  -n | --notify              Tells pknotify to send an informational message
59                             message to the end user.
60                             
61  -q | --quit                Tells pknotify to send a message asking the
62                             PyKotIcon application to exit. This option can
63                             be combined with the other ones to make PyKotIcon
64                             exit after having sent the answer from the dialog.
65                             
66  You MUST specify either --ask, --confirm, --notify or --quit.
67
68  arguments :             
69 
70    -a | --ask : Several arguments are accepted, or the form
71                 "label:varname:defaultvalue". The result will
72                 be printed to stdout in the following format :
73                 VAR1NAME=VAR1VALUE
74                 VAR2NAME=VAR2VALUE
75                 ...
76                 If the dialog was cancelled, nothing will be
77                 printed. If one of the varname is 'password'
78                 then this field is asked as a password (you won't
79                 see what you type in).
80                 
81    -c | --confirm : A single argument is expected, representing the
82                     message to display. If the dialog is confirmed
83                     then pknotify will print OK, else CANCEL.
84                     
85    -n | --notify : A single argument is expected, representing the                 
86                    message to display. In this case pknotify will
87                    always print OK.
88                   
89examples :                   
90
91  pknotify -d client:7654 --confirm "This job costs :\n10 credits !"
92 
93  would display the cost of a print job and asks for confirmation.
94""")
95       
96class PyKotaNotify(Tool) :       
97    """A class for pknotify."""
98    def sanitizeMessage(self, msg) :
99        """Replaces \\n and returns a messagee in xmlrpclib Binary format."""
100        return xmlrpclib.Binary(msg.replace("\\n", "\n"))
101       
102    def main(self, arguments, options) :
103        """Notifies or asks questions to end users through PyKotIcon."""
104        try :
105            (destination, port) = options["destination"].split(":")
106        except ValueError :
107            destination = options["destination"]
108            port = 7654
109        server = xmlrpclib.ServerProxy("http://%s:%s" % (destination, port))
110        if options["ask"] :
111            labels = []
112            varnames = []
113            varvalues = {}
114            for arg in arguments :
115                try :
116                    (label, varname, varvalue) = arg.split(":", 2)
117                except ValueError :   
118                    raise PyKotaCommandLineError, "argument '%s' is invalid !" % arg
119                labels.append(self.sanitizeMessage(label))
120                varname = varname.lower()
121                varnames.append(varname)
122                varvalues[varname] = self.sanitizeMessage(varvalue)
123            result = server.askDatas(labels, varnames, varvalues)   
124            if result["isValid"] :
125                for varname in varnames :
126                    print "%s=%s" % (varname.upper(), result[varname])
127        elif options["confirm"] :
128            print server.showDialog(self.sanitizeMessage(arguments[0]), True)
129        elif options["notify"] :
130            print server.showDialog(self.sanitizeMessage(arguments[0]), False)
131           
132        if options["quit"] :   
133            server.quitApplication()
134       
135if __name__ == "__main__" :
136    retcode = 0
137    try :
138        defaults = { \
139                   }
140        short_options = "vhd:acnq"
141        long_options = ["help", "version", "destination=", \
142                        "ask", "confirm", "notify", "quit" ]
143       
144        # Initializes the command line tool
145        notifier = PyKotaNotify(doc=__doc__)
146        notifier.deferredInit()
147       
148        # parse and checks the command line
149        (options, args) = notifier.parseCommandline(sys.argv[1:], short_options, long_options)
150       
151        # sets long options
152        options["help"] = options["h"] or options["help"]
153        options["version"] = options["v"] or options["version"]
154        options["destination"] = options["d"] or options["destination"]
155        options["ask"] = options["a"] or options["ask"]
156        options["confirm"] = options["c"] or options["confirm"]
157        options["notify"] = options["n"] or options["notify"]
158        options["quit"] = options["q"] or options["quit"]
159       
160        if options["help"] :
161            notifier.display_usage_and_quit()
162        elif options["version"] :
163            notifier.display_version_and_quit()
164        elif (options["ask"] and (options["confirm"] or options["notify"])) \
165             or (options["confirm"] and (options["ask"] or options["notify"])) \
166             or (options["notify"] and (options["ask"] or options["confirm"])) :
167            raise PyKotaCommandLineError, _("incompatible options, see help.")
168        elif (not options["destination"]) \
169             or not (options["quit"] or options["ask"] or options["confirm"] or options["notify"]) :
170            raise PyKotaCommandLineError, _("some options are mandatory, see help.")
171        elif (not args) and (not options["quit"]) :
172            raise PyKotaCommandLineError, _("some options require arguments, see help.")
173        else :
174            retcode = notifier.main(args, options)
175    except KeyboardInterrupt :       
176        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
177        retcode = -3
178    except PyKotaCommandLineError, msg :   
179        sys.stderr.write("%s : %s\n" % (sys.argv[0], msg))
180        retcode = -2
181    except SystemExit :       
182        pass
183    except :
184        try :
185            notifier.crashed("%s failed" % sys.argv[0])
186        except :   
187            crashed("%s failed" % sys.argv[0])
188        retcode = -1
189       
190    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.