~jconti/gm-notify/messaging-menu

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
#!/usr/bin/python
# -*- coding: utf-8 -*-

# gm-notify v0.10.3
# a simple and lightweight GMail-Notifier for ubuntu and notify-osd
#
# Copyright (c) 2009-2010, Alexander Hungenberg <alexander.hungenberg@gmail.com>
# 
# This program 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 3 of the License, or
# (at your option) any later version.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import print_function

import os
import sys
import subprocess
import gettext
import webbrowser

from gi.repository import Gio, GLib, MessagingMenu, Notify

from twisted.internet import gireactor
gireactor.install()
from twisted.internet import reactor
from twisted.words.protocols.jabber import jid

from gtalk import MailChecker
import gm_notify_keyring as keyring

_ = gettext.translation('gm-notify', fallback=True).ugettext

MAILBOXES_NAMES = { "inbox": _("Inbox") }

MAILBOXES_URLS = {  "inbox": "" }

class PathNotFound(Exception): pass

def get_executable_path(name):
    path = "%s/%s" % (os.getcwd(), name)
    if os.path.exists(path) and os.access(path, os.X_OK): return path
    path = "/usr/local/bin/" + name
    if os.path.exists(path) and os.access(path, os.X_OK): return path
    path = "/usr/bin/" + name
    if os.path.exists(path) and os.access(path, os.X_OK): return path
    raise PathNotFound("%s not found" % name)

def play_sound(name):
    '''Spawns a canberra-gtk-play process to play the sound'''
    if name is None:
        return
    player_path = "/usr/bin/canberra-gtk-play"
    # Not installed?
    if not os.path.exists(player_path):
        return
    command = [player_path]
    # File exists, so use the file flag
    if os.path.exists(name):
        command.extend(["-f", name])
    # Assume it is a sound id
    else:
        command.extend(["-i", name])
    try:
        result = GLib.spawn_async(command)
    except:
        return
    # Does nothing but the documentation says to do it anyway
    if len(result) > 0:
        GLib.spawn_close_pid(result[0])

class CheckMail(Gio.Application):
    def __init__(self):
        '''initiates DBUS-Messaging interface, creates the MailChecker and registers with indicator-applet.
        In the end it starts the periodic check timer and a gtk main-loop'''
        super(CheckMail, self).__init__(application_id="net.launchpad.gm-notify",
            flags=Gio.ApplicationFlags.FLAGS_NONE)

        self._has_activated = False
        self._counts = {}
        self.connect("activate", self.on_activate)

    def on_remote_quit(self, action, args):
        '''Stops the application when the "remote-quit" action is activated'''
        reactor.stop()
        
    def on_activate(self, app):
        '''When first receiving the activate signal, initialize the primary
        instance. On subsequent activate signals, we are being activated from a
        secondary instance, so treat it as if our name was clicked in the
        messaging menu.'''
        if self._has_activated:
            self.indicator_clicked()
            return

        self._has_activated = True

        # Add an action to quit
        quit_action = Gio.SimpleAction.new("remote-quit", None)
        quit_action.connect("activate", self.on_remote_quit)
        self.add_action(quit_action)

        # Initialize the desktop notifications
        if not Notify.init(_("GMail Notifier")):
            sys.exit(-1)

        keys = keyring.Keyring("GMail", "mail.google.com", "http")
        if keys.has_credentials():
            self.creds = keys.get_credentials()
        else:
            print("Failed to get credentials")
            # Start gm-notify-config if no credentials are found
            try:
                subprocess.call(get_executable_path("gm-notify-config"))
            except PathNotFound:
                print(_("gm-notify-config utility was not found"))
            sys.exit(-1)
        
        # check if we use Google Apps to start the correct webinterface
        gmail_domains = ['gmail.com','googlemail.com']
        self.jid = jid.JID(self.creds[0])
        if self.jid.host in gmail_domains:
            self.domain = None
        else:
            self.domain = self.jid.host
        
        self.client = Gio.Settings("net.launchpad.gm-notify")
        
        # Set up the sound file
        self._soundfile = self.client.get_string("soundfile")
        if self._soundfile == '':
            self._soundfile = "message-new-instant"
        if not self.client.get_boolean("play-sound"):
            self._soundfile = None
        
        # Messaging Menu integration
        self._m_menu = MessagingMenu.App.new("gm-notify.desktop")
        self._m_menu.register()
        self._m_menu.connect("activate-source", self.source_clicked)

        # Read ignore-inbox value. If true you will only receive notifications
        # about configured labels
        self.ignore_inbox = self.client.get_boolean("ignore-inbox")
        
        # Retrieve the mailbox we're gonna check
        self.mailboxes = self.client.get_strv("mailboxes")
        self.mailboxes.insert(0, "inbox")
        self.checker = MailChecker(self.jid, self.creds[1], self.mailboxes[1:], self.new_mail, self.update_count)
        self.checker.connect()
    
    def indicator_clicked(self):
        '''called when "Google Mail" is clicked in indicator-messages and
        performs a Mail Check'''
        for label in self.mailboxes:
            self.remove_attention(label)
        
        self.checker.queryInbox()

    def remove_attention(self, label):
        '''Removes attention from the label source if it exists'''
        if self._m_menu.has_source(label):
            self._m_menu.remove_attention(label)

    def has_source(self, label):
        '''Returns true if we have this label, or if we don't and it is in our
        mailboxes list, create it'''
        if label == "inbox" and self.ignore_inbox:
            return False
        elif label in self.mailboxes:
            if not self._m_menu.has_source(label):
                if label in MAILBOXES_NAMES:
                    name = MAILBOXES_NAMES[label]
                else:
                    name = label
                if label == "inbox":
                    self._m_menu.insert_source_with_string(0, label, None, name, _("empty"))
                else:
                    self._m_menu.append_source_with_string(label, None, name, _("empty"))
                if label in self._counts:
                    self._m_menu.set_source_count(label, self._counts[label])
            return True
        else:
            return False
    
    def update_count(self, count):
        '''Updates the count for all the mailboxes'''
        for mailbox in count.iteritems():
            if mailbox[0] == "inbox" and self.ignore_inbox:
                continue
            
            if self.has_source(mailbox[0]):
                # Get the last count
                last_count = 0
                if mailbox[0] in self._counts:
                    last_count = self._counts[mailbox[0]]
                current_count = int(mailbox[1])

                # Remove attention if the count has decreased
                if last_count > current_count:
                    self._m_menu.remove_attention(mailbox[0])
                if current_count > 0:
                    self._m_menu.set_source_count(mailbox[0], current_count)
                # Remove the source if 0 messages, to save space
                else:
                    self._m_menu.remove_source(mailbox[0])
                self._counts[mailbox[0]] = current_count
    
    def new_mail(self, mails):
        '''Takes mailbox name and titles of mails, to display notification and add indicators'''
        text = ""
        # aggregate the titles of the messages... cut the string if longer than 30 chars
        for mail in mails:
            got_label = False
            for label in mail['labels']:
                if label == u"^i": label = "inbox"
                if label == "inbox" and self.ignore_inbox:
                    continue
                if self.has_source(label):
                    got_label = True
                    self._m_menu.draw_attention(label)
            if not got_label: continue
            
            if "sender_name" in mail: text += mail['sender_name'] + ":\n"
            elif "sender_address" in mail: text += mail['sender_address'] + ":\n"
            
            if "subject" in mail and mail['subject']:
                title = mail['subject']
                if len(title) > 30:
                    title = title[:30] + "..."
            elif "snippet" in mail and mail['snippet']:
                title = mail['snippet'][:30] + "..."
            else:
                title = _("(no content)")
            text += "- " + title + "\n"
            
        if text:
            self.showNotification(_("Incoming message"), text.strip("\n"))
            play_sound(self._soundfile)
    
    def source_clicked(self, app, source_id):
        '''called when a label is clicked in the indicator-applet and opens the corresponding gmail page'''
        if self.domain:
            url = "https://mail.google.com/a/"+self.domain+"/"
        else:
            url = "https://mail.google.com/mail/"
        
        try:
            url += "#%s" % MAILBOXES_URLS[source_id]
        except KeyError:
            url += "#label/%s" % source_id
        
        # Open mail client
        if self.client.get_boolean("openclient"):
            try:
                info = Gio.AppInfo.get_default_for_type("x-scheme-handler/mailto", False)
                info.launch(None, None)
            except:
                pass
        else:
            webbrowser.open(url)

    def showNotification(self, title, message):
        '''takes a title and a message to display the email notification. Returns the
        created notification object'''
        
        n = Notify.Notification.new(title, message, "notification-message-email")
        n.show()
        
        return n
    
cm = CheckMail()
reactor.registerGApplication(cm)
reactor.run()