1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
|
"""
Notification.py
by Jason Conti
February 19, 2010
updated: March 26, 2011
Monitors DBUS for org.freedesktop.Notifications.Notify messages, parses them,
and notifies listeners when they arrive.
"""
import dbus
import logging
import os
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GdkPixbuf, GObject, Gtk
import Icon
import Timestamp
logger = logging.getLogger("Notification")
class ImageDataException(Exception):
pass
class ImageData(object):
"""Parses the image_data hint from a DBUS message."""
def __init__(self, image_data):
if len(image_data) < 7:
raise ImageDataException("Invalid image_data: " + repr(image_data))
self.width = int(image_data[0])
self.height = int(image_data[1])
self.rowstride = int(image_data[2])
self.has_alpha = bool(image_data[3])
self.bits_per_sample = int(image_data[4])
self.channels = int(image_data[5])
self.data = self.dbus_array_to_str(image_data[6])
def dbus_array_to_str(self, array):
return "".join(map(chr, array))
def dbus_array_to_int(self, array):
return map(int, array)
def get_pixbuf(self, size):
"""Creates a pixbuf from the image data and scale it to the appropriate size."""
# Hack until Pixbuf.new_with_data is working
if self.width > 100 or self.height > 100:
return None
pixbuf = GdkPixbuf.Pixbuf.new_from_data(self.data, GdkPixbuf.Colorspace.RGB,
self.has_alpha, self.bits_per_sample, self.width, self.height,
self.rowstride, lambda *args: None, None)
# Hack part 2
copy_pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, self.has_alpha, self.bits_per_sample,
self.width, self.height)
pixbuf.copy_area(0, 0, self.width, self.height, copy_pixbuf, 0, 0)
result = copy_pixbuf.scale_simple(size, size, GdkPixbuf.InterpType.BILINEAR)
return result
class MessageException(Exception):
pass
class Message(GObject.GObject):
"""Parses a DBUS message in the Notify format specified at:
http://www.galago-project.org/specs/notification/0.9/index.html"""
# Message urgency
LOW = 0
NORMAL = 1
CRITICAL = 2
X_CANONICAL_PRIVATE_SYNCHRONOUS = "x-canonical-private-synchronous"
def __init__(self, dbus_message = None, timestamp = None):
GObject.GObject.__init__(self)
self.timestamp = timestamp
args = dbus_message.get_args_list()
if len(args) != 8:
raise MessageException("Invalid message args_list: " + repr(args))
self.app_name = str(args[0])
self.replaces_id = args[1]
self.app_icon = str(args[2])
self.summary = unicode(args[3])
self.body = unicode(args[4])
self.actions = args[5]
self.hints = dict(args[6])
self.expire_timeout = args[7]
if "urgency" in self.hints:
urgency = self.hints["urgency"]
if urgency == 0:
self.urgency = Message.LOW
elif urgency == 2:
self.urgency = Message.CRITICAL
else:
self.urgency = Message.NORMAL
else:
self.urgency = Message.NORMAL
if "image_data" in self.hints:
self.image_data = ImageData(self.hints["image_data"])
else:
self.image_data = None
if "icon_data" in self.hints:
self.icon_data = ImageData(self.hints["icon_data"])
else:
self.icon_data = None
self.log_message()
def get_icon(self, size = 48):
"""Loads the icon into a pixbuf. Adapted from the load_icon code in
bubble.c of notify-osd."""
icon_name = self.app_icon
# Try to load the pixbuf from a file
if icon_name.startswith("file://") or icon_name.startswith("/"):
icon = Icon.load_from_file(icon_name, size)
if icon != None:
return icon
# Try to load the pixbuf from the current icon theme
elif icon_name != "":
icon = Icon.load(icon_name, size)
if icon != None:
return icon
# Try to load the icon data from the message
elif self.icon_data != None:
return self.icon_data.get_pixbuf(size)
# Try to load the image data from the message
elif self.image_data != None:
return self.image_data.get_pixbuf(size)
return self.get_default_icon(size)
def get_default_icon(self, size = 48):
"""Attempts to load the default message icon, returns None on failure."""
if self.urgency == Message.LOW:
return Icon.load("notification-low", size)
elif self.urgency == Message.CRITICAL:
return Icon.load("notification-critical", size)
else:
return Icon.load("notification-normal", size)
def is_volume_notification(self):
"""Returns true if this is a volume message. The volume notifications
in Ubuntu are a special case, and mostly a blank message. Clutters up
the display and provides no useful information, so it is better to
discard them."""
if Message.X_CANONICAL_PRIVATE_SYNCHRONOUS in self.hints:
return str(self.hints[Message.X_CANONICAL_PRIVATE_SYNCHRONOUS]) == "volume"
def log_message(self):
"""Write debug info about a message."""
result = [
"-" * 50,
"Message created at: " + Timestamp.locale_datetime(self.timestamp),
"app_name: " + repr(self.app_name),
"replaces_id: " + repr(self.replaces_id),
"app_icon: " + repr(self.app_icon),
"summary: " + repr(self.summary),
"body: " + repr(self.body),
"actions: " + repr(self.actions),
"expire_timeout: " + repr(self.expire_timeout),
"hints:"
]
# Log all the hints except image_data
for key in self.hints:
if key not in ["icon_data", "image_data"]:
result.append(" " + str(key) + ": " + repr(self.hints[key]))
# Log info about icon_data
if self.icon_data != None:
result.append("icon_data:")
result.append(" width: " + repr(self.icon_data.width))
result.append(" height: " + repr(self.icon_data.height))
result.append(" rowstride: " + repr(self.icon_data.rowstride))
result.append(" has_alpha: " + repr(self.icon_data.has_alpha))
result.append(" bits_per_sample: " + repr(self.icon_data.bits_per_sample))
result.append(" channels: " + repr(self.icon_data.channels))
# Log info about the image_data
if self.image_data != None:
result.append("image_data:")
result.append(" width: " + repr(self.image_data.width))
result.append(" height: " + repr(self.image_data.height))
result.append(" rowstride: " + repr(self.image_data.rowstride))
result.append(" has_alpha: " + repr(self.image_data.has_alpha))
result.append(" bits_per_sample: " + repr(self.image_data.bits_per_sample))
result.append(" channels: " + repr(self.image_data.channels))
result.append("-" * 50)
logger.debug("\n" + "\n".join(result))
class Notification(GObject.GObject):
"""Monitors DBUS for org.freedesktop.Notifications.Notify messages, parses them,
and notifies listeners when they arrive."""
__gsignals__ = {
"message-received": (GObject.SignalFlags.RUN_LAST, None, [Message])
}
def __init__(self):
GObject.GObject.__init__(self)
self._blacklist = None
self._match_string = "type='method_call',interface='org.freedesktop.Notifications',member='Notify'"
DBusGMainLoop(set_as_default=True)
self._bus = dbus.SessionBus()
self._bus.add_match_string(self._match_string)
self._bus.add_message_filter(self._message_filter)
def close(self):
"""Closes the connection to the session bus."""
self._bus.close()
def set_blacklist(self, blacklist):
"""Defines the set of app_names of messages to be discarded."""
self._blacklist = blacklist
def _message_filter(self, connection, dbus_message):
"""Triggers when messages are received from the session bus."""
if dbus_message.get_member() == "Notify" and dbus_message.get_interface() == "org.freedesktop.Notifications":
try:
message = Message(dbus_message, Timestamp.now())
except:
logger.exception("Failed to parse dbus message: " + repr(dbus_message.get_args_list()))
else:
# Discard unwanted messages
if message.is_volume_notification():
return
if self._blacklist and self._blacklist.get_bool(message.app_name, False):
return
logger.debug("Sending message-received")
self.emit("message-received", message)
GObject.type_register(Message)
GObject.type_register(Notification)
|