~gm-notify-maintainers/gm-notify/1.0

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
376
377
378
379
380
#!/usr/bin/python
# -*- coding: utf-8 -*-

# gm-notify v1.0
# a simple and lightweight GMail-Notifier for ubuntu and notify-osd
#
# Copyright (c) 2009-2010, Alexander Hungenberg <alexander.hungenberg@gmail.com>
# Copyright (c) 2015, Mateusz Balbus <balbusm@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

import gi
gi.require_version('Gst', '1.0')
gi.require_version('MessagingMenu', '1.0')
gi.require_version('Notify', '0.7')
from gi.repository import Gio, GLib, Gst, 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 account_settings_provider
import gm_notify_keyring as keyring

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

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

MAILBOXES_URLS = {  "inbox": "" }

GMAIL_DOMAINS = ['gmail.com','googlemail.com']

EMAIL_RETRIEVAL_ERROR = "--retrieval-error"

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)

class Account:
    def __init__(self):
        self.username = None
        self.client = None
        self.soundfile = None
        self.ignore_inbox = None
        self.domain = None
        self.labels = None
        self.use_mail_client = None

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.player = None
        self._has_activated = False
        self._counts = {}
        self.connect("activate", self.on_activate)

    def play_sound(self, name):
        '''Uses GSound to play the music'''
        if name is None:
            return
        
        if not self.player: 
            Gst.init()
            self.player = Gst.ElementFactory.make("playbin", "player")

        self.player.set_property("uri", "file://" + name)
        result = self.player.set_state(Gst.State.PLAYING)
        if result == Gst.StateChangeReturn.FAILURE:
            print("Unable to play " + name)

    def on_remote_quit(self, action, args):
        '''Stops the application when the "remote-quit" action is activated'''
        reactor.stop()

    def run(self, args):
        self.register();
        if self.get_is_remote():
            self.activate()
        else:
            super(CheckMail, self).run(args)

    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_any_credentials():
            creds = keys.get_all_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)
        
        # 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)

        self.accounts = self.init_accounts(creds)


    def init_accounts(self, creds):
        accounts = {}
        for credentails in creds:
            account = Account()
            account.username = credentails.username
            local_jid = jid.JID(account.username)
            # check if we use Google Apps to start the correct webinterface
            if local_jid.host not in GMAIL_DOMAINS:
                account.domain = local_jid.host
            
            client = account_settings_provider.create_settings_provider(account.username)
            account.client = client 
            
            account.use_mail_client = client.retrieve_use_mail_client()
            
            # Set up the sound file
            if client.retrieve_sound_enabled():
                account.soundfile = client.retrieve_sound_file("message-new-instant")
            # Read ignore-inbox value. If true you will only receive notifications
            # about configured labels
            account.ignore_inbox = client.retrieve_ignore_inbox()
            
            # Retrieve the mailbox we're gonna check
            account.labels = client.retrieve_labels()
            account.labels.insert(0, "inbox")
            account.checker = MailChecker(local_jid, credentails.password, client, account.labels[1:], self.new_mail, self.update_count)
            account.checker.setOnConnectionErrorCB(self.checker_connection_error)
            account.checker.setOnAuthFailed(self.checker_auth_failed)
            account.checker.setOnAuthSucceeded(self.checker_auth_succeeded)
            account.checker.connect()
            
            accounts[credentails.username] = account
        return accounts

    def indicator_clicked(self):
        '''called when "Google Mail" is clicked in indicator-messages and
        performs a Mail Check'''
        for username, account in self.accounts.items():
            for label in account.labels:
                self.remove_attention(self.compose_id(username, label))
            
        for username, account in self.accounts.items():
            account.checker.queryInbox()

    def compose_label(self, username, label):
        return "%s (%s)" % (username, label)

    def compose_id(self, username, label):
        return "%s&%s" % (username, label)
    
    def decompose_id(self, id):
        decomposed = id.split("&")
        return (decomposed[0], decomposed[1])

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

                # Remove attention if the count has decreased
                if last_count > current_count:
                    self._m_menu.remove_attention(mail_label)
                if current_count > 0:
                    self._m_menu.set_source_count(mail_label, current_count)
                # Remove the source if 0 messages, to save space
                else:
                    self._m_menu.remove_source(mail_label)
                self._counts[mail_label] = current_count
    
    def new_mail(self, username, mails):
        '''Takes mailbox name and titles of mails, to display notification and add indicators'''
        account = self.accounts[username]
        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 account.ignore_inbox:
                    continue
                if self.has_source(username, label):
                    got_label = True
                    mail_label = self.compose_id(username, label)
                    self._m_menu.draw_attention(mail_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.show_notification("{0}".format(username), text.strip("\n"))
            self.play_sound(self.accounts[username].soundfile)
    
    def source_clicked(self, app, source_id):
        '''called when a label is clicked in the indicator-applet and opens the corresponding gmail page'''
        # TODO: missing username
        username, label = self.decompose_id(source_id)
        if label == EMAIL_RETRIEVAL_ERROR:
            return
        account = self.accounts[username]
        
        # Open mail client
        if account.use_mail_client:
            try:
                info = Gio.AppInfo.get_default_for_type("x-scheme-handler/mailto", False)
                info.launch(None, None)
            except:
                pass
        else:
            url = self.prep_url(account, label)
            webbrowser.open(url)

    def prep_url(self, account, label):
        url_domain = self.prep_url_domain(account.domain)
        url_label = self.prep_url_label(label)

        return ("https://accounts.google.com/AccountChooser?"
                "Email={0}"
                "&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F{1}"
                "&service=mail"
                "&hd={2}").format(account.username, url_label, url_domain)

    def prep_url_label(self, label):
        if label in MAILBOXES_URLS:
            return "%23{0}".format(MAILBOXES_URLS[label])
        else:
            return "%23label%2F{0}".format(label)

    def prep_url_domain(self, domain):
        if domain:
            return domain
        else:
            return "default"
    
    def checker_auth_succeeded(self, username):
        error_label = self.compose_id(username, EMAIL_RETRIEVAL_ERROR)
        self._m_menu.remove_source(error_label)
    
    def checker_connection_error(self, username, error): 
        self.check_failed(username, _("Cannot retrieve emails"))
    
    def checker_auth_failed(self, username, error):
        self.check_failed(username, _("Authentication failed"))
    
    def check_failed(self, username, feed):
        
        for id in self._counts:
            local_username, local_label = self.decompose_id(id)
            if local_username == username:
                self._m_menu.remove_source(id)
            
        error_id = self.compose_id(username, EMAIL_RETRIEVAL_ERROR)
        if self._m_menu.has_source(error_id):
            return
        self._m_menu.append_source(error_id, None, username + _(" - Cannot retrieve emails"))
        n = Notify.Notification.new(_("Error for ") + username, feed, "messagebox_critical")
        n.show()
    
    def show_notification(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
    
    def shutdown(self):
        if self.accounts: 
            for username, account in self.accounts.items():
                if account.checker : account.checker.die()
    
cm = CheckMail()
reactor.registerGApplication(cm)
reactor.addSystemEventTrigger('before', 'shutdown', cm.shutdown)
reactor.run()