~jconti/recent-notifications/trunk

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
"""
Notification.py
by Jason Conti
February 19, 2010

Monitors DBUS for org.freedesktop.Notifications.Notify messages, parses them,
and notifies listeners when they arrive.
"""

import dbus
import glib
import gobject
import gtk
import logging
import time

from dbus.mainloop.glib import DBusGMainLoop
from locale import nl_langinfo, T_FMT

from Icon import load_icon, load_icon_from_file

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 get_pixbuf(self, size):
    """Creates a pixbuf from the image data and scale it to the appropriate size."""
    pixbuf = gtk.gdk.pixbuf_new_from_data(self.data, gtk.gdk.COLORSPACE_RGB,
        self.has_alpha, self.bits_per_sample, self.width, self.height,
        self.rowstride)

    return pixbuf.scale_simple(size, size, gtk.gdk.INTERP_BILINEAR)

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
  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 = str(args[3])
    self.body = str(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

    self.log_message()

  def formatted_timestamp(self):
    """Returned the timestamp in a different format."""
    #return time.strftime("%I:%M:%S %p", self.timestamp)
    return time.strftime(nl_langinfo(T_FMT), self.timestamp)

  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 = load_icon_from_file(icon_name, size)
      if icon != None:
        return icon

    # Try to load the pixbuf from the current icon theme
    elif icon_name != "":
      icon = load_icon(icon_name, size)
      if icon != None:
        return icon

    # Try to load the image data from the message
    elif self.image_data != None:
      return self.image_data.get_pixbuf(32)

    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 load_icon("notification-low", size)
    elif self.urgency == Message.CRITICAL:
      return load_icon("notification-critical", size)
    else:
      return load_icon("notification-normal", size)

  def log_message(self):
    """Write debug info about a message."""
    result = [
        "-" * 50,
        "Message created at: " + self.formatted_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),
        "hints: " + repr(self.hints),
        "expire_timeout: " + repr(self.expire_timeout),
        "-" * 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.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [Message])
  }
  def __init__(self):
    gobject.GObject.__init__(self)

    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):
    self._bus.close()

  def _message_filter(self, connection, dbus_message):
    if dbus_message.get_member() == "Notify" and dbus_message.get_interface() == "org.freedesktop.Notifications":
      try:
        message = Message(dbus_message, time.localtime())
      except:
        logger.exception("Failed to parse dbus message: " + repr(dbus_message.get_args_list()))
      else:
        glib.idle_add(self.emit, "message-received", message)

if gtk.pygtk_version < (2, 8, 0):
  gobject.type_register(Message)
  gobject.type_register(Notification)

if __name__ == '__main__':
  main()