Add support for alternate character set in termex
[centerim5.git] / contrib / extnotify.py
blobc723b34a8c171289f33d650681926ddd004637db
1 #!/usr/bin/env python3
3 """
4 This script processes events generated by the extaction plugin and displays
5 notifications of these events on the screen.
6 """
8 import base64
9 import html
10 import os
11 import sys
13 import gi
14 gi.require_version('GdkPixbuf', '2.0')
15 gi.require_version('Notify', '0.7')
16 from gi.repository import GdkPixbuf, Notify
19 # The module requires html.escape() and os.environb which first appeared in
20 # Python 3.2.
21 if sys.hexversion < 0x03020000:
22 print("This program requires at least Python 3.2.", file=sys.stderr)
23 sys.exit(1)
26 def get_env(key):
27 bkey = key.encode()
28 if bkey not in os.environb:
29 print("Environment variable '{}' is not set.".format(key))
30 raise KeyError
31 return os.environb[bkey].decode()
34 def main():
35 # Make the parameters saved in environment variables easier accessible.
36 try:
37 event_type = get_env('EVENT_TYPE')
38 # This script can handle only the msg type.
39 if event_type != 'msg':
40 print("EVENT_TYPE='{}' is not recognized.".format(event_type))
41 sys.exit(1)
43 # event_network = get_env('EVENT_NETWORK')
44 # event_local_user = get_env('EVENT_LOCAL_USER')
45 event_remote_user = get_env('EVENT_REMOTE_USER')
46 event_message = get_env('EVENT_MESSAGE')
47 # event_message_html = get_env('EVENT_MESSAGE_HTML')
48 except KeyError as e:
49 # Some necessary parameter is missing.
50 sys.exit(1)
52 if not Notify.init("Extaction-plugin handler"):
53 print("Initialization of libnotify failed.")
54 sys.exit(1)
56 title = "Message from {}:".format(event_remote_user)
57 # Select first 256 characters from the message.
58 body = event_message[:256]
59 # Escape the '&', '<', '>' characters.
60 body = html.escape(body)
62 notification = Notify.Notification.new(title, body)
63 if b'EVENT_REMOTE_USER_ICON' in os.environb:
64 # The icon is encoded in base64, decode it first.
65 icon_encoded = os.environb[b'EVENT_REMOTE_USER_ICON']
66 icon_decoded = base64.b64decode(icon_encoded)
68 # Create a pixbuf loader.
69 loader = GdkPixbuf.PixbufLoader.new()
70 loader.set_size(48, 48)
71 loader.write(icon_decoded)
72 loader.close()
74 # Set icon from the pixbuf.
75 pixbuf = loader.get_pixbuf()
76 notification.set_icon_from_pixbuf(pixbuf)
78 # Get the notification on the screen.
79 notification.show()
81 Notify.uninit()
83 if __name__ == '__main__':
84 main()
86 # vim: set tabstop=4 shiftwidth=4 textwidth=79 expandtab :