File: LibNotify.py

package info (click to toggle)
emesene 1.0-dist-4
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 4,596 kB
  • ctags: 3,006
  • sloc: python: 25,171; makefile: 14; sh: 1
file content (375 lines) | stat: -rw-r--r-- 14,611 bytes parent folder | download
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# -*- coding: utf-8 -*-

#   This file is part of emesene.
#
#    Emesene is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    emesene is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with emesene; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import gtk
import gobject

import Plugin
import desktop
from emesenelib.common import escape
from emesenelib.common import unescape
from Parser import PangoDataType

ERROR = ''
try:
    import pynotify
    if not pynotify.init("emesene"):
        raise
except:
    ERROR = _('there was a problem initializing the pynotify module')

class MainClass(Plugin.Plugin):
    '''Main plugin class'''

    def __init__(self, controller, msn):
        '''Contructor'''

        Plugin.Plugin.__init__(self, controller, msn)

        self.description = _('Notify about diferent events using pynotify')
        self.authors = {'Mariano Guerra': 'luismarianoguerra at gmail dot com'}
        self.website = 'http://emesene-msn.blogspot.com'
        self.displayName = _('LibNotify')
        self.name = 'LibNotify'

        self.config = controller.config
        self.config.readPluginConfig(self.name)
        self.notifyOnline = int(self.config.getPluginValue(self.name, 'notifyOnline', '1'))
        self.notifyOffline = int(self.config.getPluginValue(self.name, 'notifyOffline', '1'))
        self.notifyNewMail = int(self.config.getPluginValue(self.name, 'notifyMail', '1'))
        self.notifyTyping = int(self.config.getPluginValue(self.name, 'typing', '0'))
        self.notifyNewMsg = int(self.config.getPluginValue(self.name, 'notifyMessage', '1'))
        #self.notifyStarted = int(self.config.getPluginValue(self.name, 'notifyStarted', '0'))
        self.notifyBusy = int(self.config.getPluginValue(self.name, 'notifyBusy', '0'))

        self.tray = self.controller.trayIcon.getNotifyObject()
        self.pixbuf = self.controller.theme.getImage('userPanel')

        self.controller = controller
        self.parser = controller.unifiedParser
        self.contacts = controller.contacts  # ref..

        self.notifications = []

        # callbacks ids
        self.onlineId = None
        self.offlineId = None
        self.newMsgId = None
        self.offMsgId = None
        self.typingId = None
        self.newMailId = None
        self.initMailId = None

    def start(self):
        '''start the plugin'''

        self.onlineId = self.connect('user-online', self.online)
        self.offlineId = self.connect('user-offline', self.offline)
        self.newMsgId = self.connect('message-received', self.newMsg)
        self.offMsgId = self.connect('offline-message-received', self.offMsg)
        self.typingId = self.connect('switchboard::typing', self.receiveTyping)
        self.newMailId = self.connect('new-mail-notification', self.newMail)
        self.initMailId = self.connect('initial-mail-notification', \
                self.initMail)
        self.enabled = True

    def stop(self):
        ''' stop the plugin '''

        # closes remaining notifications
        for i in self.notifications:
            i.close()

        self.notifications = []

        self.disconnect(self.onlineId)
        self.disconnect(self.offlineId)
        self.disconnect(self.newMsgId)
        self.disconnect(self.offMsgId)
        self.disconnect(self.typingId)
        self.disconnect(self.newMailId)
        self.disconnect(self.initMailId)
        self.enabled = False

    def check(self):
        '''check if everything is OK to start the plugin
        return a tuple whith a boolean and a message
        if OK -> ( True , 'some message' )
        else -> ( False , 'error message' )'''
        global ERROR

        if ERROR != '':
            return (False, ERROR)

        return (True, 'Ok')

    def configure(self):
        '''display a configuration dialog'''
        l = []

        l.append(Plugin.Option('notifyOnline', bool, \
                _('Notify when someone gets online'), '', self.config.\
                getPluginValue(self.name, 'notifyOnline', '1') == '1'))
        l.append(Plugin.Option('notifyOffline', bool, \
                _('Notify when someone gets offline'), '', self.config.\
                getPluginValue(self.name, 'notifyOffline', '1') == '1'))
        l.append(Plugin.Option('notifyMail', bool, \
                _('Notify when receiving an email'), '', self.config.\
                getPluginValue(self.name, 'notifyMail', '1') == '1'))
        l.append(Plugin.Option('typing', bool, \
                _('Notify when someone starts typing'), '', self.config.\
                getPluginValue(self.name, 'typing', '1') == '1'))
        l.append(Plugin.Option('notifyMessage', bool, \
                _('Notify when receiving a message'), '', self.config.\
                getPluginValue(self.name, 'notifyMessage', '1') == '1'))
        #l.append(Plugin.Option('notifyStarted', bool, \
        #        _('Don`t notify if conversation is started'), '', self.config.\
        #        getPluginValue(self.name, 'notifyStarted', '1') == '1'))
        l.append(Plugin.Option('notifyBusy', bool, \
                _('Disable notifications when busy'), '', self.config.\
                getPluginValue(self.name, 'notifyBusy', '1') == '1'))

        response = Plugin.ConfigWindow(_('Config LibNotify Plugin'), l).run()
        if response != None:
            def check(event):
                if response.has_key(event):
                    self.config.setPluginValue(self.name, event, \
                            str(int(response[event].value)))

            check('notifyOnline')

            if response.has_key('notifyOffline'):
                self.config.setPluginValue(self.name, 'notifyOffline', \
                    str(int(response['notifyOffline'].value)))
            if response.has_key('notifyMail'):
                self.config.setPluginValue(self.name, 'notifyMail', \
                    str(int(response['notifyMail'].value)))
            if response.has_key('typing'):
                self.config.setPluginValue(self.name, 'typing', \
                    str(int(response['typing'].value)))
            if response.has_key('notifyMessage'):
                self.config.setPluginValue(self.name, 'notifyMessage', \
                    str(int(response['notifyMessage'].value)))
            #if response.has_key('notifyStarted'):
            #    self.config.setPluginValue(self.name, 'notifyStarted', \
            #        str(int(response['notifyStarted'].value)))
            if response.has_key('notifyBusy'):
                self.config.setPluginValue(self.name, 'notifyBusy', \
                    str(int(response['notifyBusy'].value)))

        self.notifyOnline = (self.config.getPluginValue \
                (self.name, 'notifyOnline', '1') == '1')
        self.notifyOffline = (self.config.getPluginValue \
                (self.name, 'notifyOffline', '1') == '1')
        self.notifyNewMail = (self.config.getPluginValue \
                (self.name, 'notifyMail', '1') == '1')
        self.notifyTyping = (self.config.getPluginValue \
                (self.name, 'typing', '1') == '1')
        self.notifyNewMsg = (self.config.getPluginValue \
                (self.name, 'notifyMessage', '1') == '1')
        #self.notifyStarted = (self.config.getPluginValue \
        #        (self.name, 'notifyStarted', '1') == '1')
        self.notifyBusy = (self.config.getPluginValue \
                (self.name, 'notifyBusy', '1') == '1')

        return True

    def notifyEnabled(self, contact = None):
        '''checks if notifications are enabled'''
        if not self.enabled:
            return False
        if self.notifyBusy and self.msn.status == 'BSY':
            return False
        if contact != None:
            if self.contacts.get_blocked(contact):
                return False
        return True

    def notify(self, contact, title, text, execute = '', data = None):

        notification = pynotify.Notification(title, text, attach = self.tray)

        if contact != '':
            if self.controller.theme.hasUserDisplayPicture(contact):
                self.pixbuf = self.controller.theme.getUserDisplayPicture( \
                    contact, 48, 48)

        notification.set_icon_from_pixbuf(self.pixbuf)

        if contact != '':
            self.pixbuf = self.controller.theme.getImage('userPanel')

        if execute == 'conversation':
            def on_notify_action(notification, action):
                self.controller.newConversation(None, data[0], data[1], True)
            notification.add_action('default', 'default', on_notify_action)

        elif execute == 'mail':
            def openMail(notification, action):
                desktop.open(self.controller.hotmail.getLoginPage\
                    (data[0], data[1], data[2]))
            notification.add_action('default', 'Open Mail', openMail)

        if self.controller.trayIcon and \
           isinstance(self.controller.trayIcon.tray, gtk.StatusIcon):
            tray = self.controller.trayIcon.tray
            try:
                notification.attach_to_status_icon(tray)
                #notification.set_hint("x", tray.get_geometry()[1].x)
                #notification.set_hint("y", tray.get_geometry()[1].y)
            except:
                print "cant set geometry hints on libnotify plugin"

        try:
            notification.show()
        except gobject.GError:
            print "can't display notification" # TODO, retry?
            return
        notification.connect('closed', self.on_notify_close)
        self.notifications.append(notification)

    def getNickPM(self, email, name = ''):
        ''' returns the nick and pm of the contact '''
        
        contact = self.msn.contactManager.getContact(email)  # :(:(

        if not self.contacts.exists(email):
            text = name + ' <' + email + '>'
        else:
            # @roger, this is ugly
            nick = self.parser.getParser(
                self.contacts.get_display_name(email)).get()
            pm = self.parser.getParser(
                self.contacts.get_message(email)).get()
            text = nick + ' <span foreground="#AAAAAA">' + pm + '</span>'

        return contact, text

    def online(self, msnp, email, oldStatus):
        '''called when someone get online'''

        if not (self.notifyOnline and self.notifyEnabled(email)):
            return

        if oldStatus != 'FLN':
            return

        contact, text = self.getNickPM(email)
        text += "\n" + _("is online")
        self.notify(contact, "emesene", text, 'conversation', (email, None))

    def offline(self, msnp, email):
        '''called when someone get offline'''

        if not (self.notifyOffline and self.notifyEnabled(email)):
            return

        contact, text = self.getNickPM(email)
        text += "\n" + _("is offline")
        self.notify(contact, "emesene", text)

    def newMsg(self, msnp, email):
        '''called when someone send a message'''

        if not (self.notifyNewMsg and self.notifyEnabled(email)):
            return

	result = self.controller.conversationManager.getOpenConversation(email)
        if result != None:
            #if self.notifyStarted:
            #    return
            window, conversation = result
            windowFocus = window.is_active()
            tabFocus = (window.conversation == conversation)
            if windowFocus and tabFocus:
                return

        contact, text = self.getNickPM(email)
        text += "\n" + _("has send a message")
        self.notify(contact, "emesene", text, 'conversation', (email, None))

    def offMsg(self, msnp, oim):
        '''called when someone sent an offline message'''
        email = oim[0]['addr']

        if not (self.notifyNewMsg and self.notifyEnabled(email)):
            return

	result = self.controller.conversationManager.getOpenConversation(email)
        if result != None:
            window, conversation = result
            windowFocus = window.is_active()
            tabFocus = (window.conversation == conversation)
            if windowFocus and tabFocus:
                return

        contact, text = self.getNickPM(email)
        text += "\n" + _("sent an offline message")
        self.notify(contact, "emesene", text, 'conversation', (email, None))

    def receiveTyping(self, msn, switchboard, signal, args):
        '''called when someone starts typing'''
        email = args[0]

        if not (self.notifyTyping and self.notifyEnabled(email)):
            return

        if self.controller.conversationManager.getOpenConversation \
                (email, switchboard) != None:
            return

        contact, text = self.getNickPM(email)
        text += "\n" + _("starts typing")
        self.notify(contact, "emesene", text, 'conversation', \
                (email, switchboard))

    def newMail(self, msnp, From, FromAddr, Subject, MessageURL, PostURL, id):
        ''' called when receiving mail '''

        if not (self.notifyNewMail and self.notifyEnabled(FromAddr)):
            return

        contact, text = self.getNickPM(FromAddr, From)
        text = _('From: ') + text + '\n' + _('Subj: ') + escape(Subject) \
                + '\n\n<span foreground="#AAAAAA">emesene</span>'

        self.notify(contact, _('New email'), text, 'mail', \
                (MessageURL, PostURL, id))

    def initMail(self, msnp):
        if self.notifyNewMail:
            unread = self.controller.getUnreadMails()

            try:
                unread = int(unread)
            except ValueError, TypeError:
                unread = 0

            if unread > 0:
                if unread == 1:
                    s = ''
                else:
                    s = 's'
                self.notify('', "emesene", \
                        _('You have %(num)i unread message%(s)s') % \
                        {'num': unread, 's': s}, 'mail', (None, None, '2'))

    def on_notify_close(self, n):
        if n in self.notifications:
            self.notifications.remove(n)