grml-lang: sort languages alphabetically
[grml-scripts.git] / usr_bin / notifyd.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2005-2009 Alexander Bernauer <alex@copton.net>
4 # Copyright (C) 2005-2009 Rico Schiekel <fire@downgra.de>
5 # Copyright (C) 2005-2009 Ulrich Dangel <uli@spamt.net>
6 #
7 # This program is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License
9 # as published by the Free Software Foundation version 2
10 # of the License.
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, write to the Free Software
19 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA # 02111-1307, USA.
20
21
22 """
23 example of ~/.notifid.conf:
24 ---------------------------
25
26 import os
27
28 host = "127.0.0.1"
29 port = 8901
30 logfile = os.path.expanduser("~/.event.log")
31 osdparams = "-p bottom  --color=red --delay=4 --age=4 " \
32  "--font=\-\*\-helvetica\-medium\-r\-\*\-\*\-34\-\*\-\*\-\*\-\*\-\*\-\*\-15 " \
33      "--offset=100 --shadow=0 --lines=5 --align=right --indent=100"
34 actions = (
35     (".*", [log], True),
36     ("IRC:&bitlbee:bitlbee", [], False),
37     (".*shutdown.*", [command('sudo shutdown -h now %(msg)s')], False),
38     (".*", [libnotify], False),
39 )
40
41 """
42
43 import os
44 import sys
45 import re
46 import string
47 import socket
48 import logging
49 import getopt
50
51 default_hostname = 'localhost'
52 default_port = 1234
53 default_osd_params = osdparams = "-p bottom  --color=red --delay=4 --age=4 " \
54            "--font=\-\*\-helvetica\-medium\-r\-\*\-\*\-34\-\*\-\*\-\*\-\*\-\*\-\*\-15 " \
55             "--offset=100 --shadow=0 --lines=5 --align=right --indent=100"
56 default_logfile = None
57
58
59 def play(sound_file):
60     def play_wrapper(msg):
61         os.system('/usr/bin/aplay "%s" 2> /dev/null &' % sound_file)
62     return play_wrapper
63
64 def execute(command):
65     def command_wrapper(msg):
66         os.system(command % dict(msg = msg))
67     return command_wrapper
68
69 def osd(msg):
70     osdcmd = "/usr/bin/osd_cat"
71     osdpipe = os.popen("%s %s" % (osdcmd, osdparams), 'w')
72     osdpipe.write(msg)
73     osdpipe.close()
74
75 def libnotify(msg):
76     try:
77         import dbus
78     except ImportError:
79         sys.stderr.write('Please install python-dbus\n')
80         raise SystemExit(1)
81
82     bus = dbus.SessionBus()
83     notifyService = bus.get_object("org.freedesktop.Notifications", '/org/freedesktop/Notifications')
84     interface = dbus.Interface(notifyService, 'org.freedesktop.Notifications')
85
86     message, title = (':' + msg).split(':')[::-1][0:2]
87     if not title:
88         title, message = message, title
89     interface.Notify('notify-server', 0, 'notification-message-im', title, message, [], {'x-canonical-append':'allowed'}, -1)
90
91 def log(msg):
92     if logger:
93         logger.info(msg)
94
95 def syntax():
96     print "osd_server.py [options]"
97     print "   options:"
98     print "     -h --help       print this message"
99     print "     -H --host       host of the osd server (def: " + default_hostname + ")"
100     print "     -P --port       port of the osd server (def: " + str(default_port) + ")"
101     print "     -l --log        log file ('-' logs to stdout)"
102
103
104 env = { 'play' : play,
105         'execute' : execute,
106         'osd' : osd,
107         'libnotify' : libnotify,
108         'log' : log,
109         'host' : default_hostname,
110         'port' : default_port,
111         'logfile' : default_logfile,
112         }
113
114 default_actions = (
115     (".*", [log], True),
116     (".*", [libnotify], False),
117 )
118
119
120 default_bind = (default_hostname, default_port)
121
122 try:
123     execfile(os.path.expanduser('~/.notifyd.conf'), {}, env)
124 except IOError:
125     pass
126
127 try:
128     opts, args = getopt.getopt(sys.argv[1:], "hH:P:l:", ["help", "host=", "port=", "log="])
129 except getopt.GetoptError:
130     syntax()
131     sys.exit(2)
132
133 for opt, arg in opts:
134     if opt in ("-h", "--help"):
135         syntax()
136         sys.exit(3)
137     elif opt in ("-H", "--host"):
138         env['host'] = arg
139     elif opt in ("-P", "--port"):
140         env['port'] = int(arg)
141     elif opt in ("-l", "--log"):
142         env['logfile'] = arg
143
144
145 actions = env.get('actions', default_actions)
146 logfile_name = env.get('logfile')
147 logfile_format = env.get('logformat', '%(asctime)s %(message)s')
148 bind_address = (env['host'], env['port'])
149 osd_params = env.get('osdparams', default_osd_params)
150
151 if logfile_name:
152     logger = logging.getLogger('notify_server')
153     lformatter = logging.Formatter(logfile_format)
154     if logfile_name not in ('', '-'):
155         lfh = logging.FileHandler(logfile_name)
156         lfh.setFormatter(lformatter)
157         logger.addHandler(lfh)
158     else:
159         lout = logging.StreamHandler(sys.stdout)
160         lout.setFormatter(lformatter)
161         logger.addHandler(lout)
162     logger.setLevel(logging.INFO)
163 else:
164     logger = None
165
166 l = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
167 l.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
168 l.bind(bind_address)
169 l.listen(5)
170
171 def filter_char(c):
172     return c in string.printable + "äöüßÄÖÜ" and c or '_'
173
174 while 1:
175     try:
176         (con, addr) = l.accept()
177     except:
178         continue
179     data = con.recv(50).strip()
180     con.close()
181
182     log = ''.join(filter_char(c) for c in data)
183
184     for pattern, handlers, cont in actions:
185         if re.match(pattern, log):
186             for handler in handlers:
187                 handler(log)
188             if not cont:
189                 break