~erigami/onehundredscopes/unity-lens-pidgin

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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#! /usr/bin/python

#    Copyright (c) 2011 David Calle <davidc@framli.eu>, 2012 Evan Hughes.

#    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/>.


import sys
import os, errno
import glob
from gi.repository import GLib, GObject, Gio
from gi.repository import GdkPixbuf, Gdk
from gi.repository import Dee
from gi.repository import Unity
import dbus
from dbus.mainloop.glib import DBusGMainLoop
import urllib2
import simplejson
import locale
import datetime, time 
import urlparse

import xdg.BaseDirectory

from operator import attrgetter

import pprint
import collections
import xml.etree.ElementTree

BUS_NAME = "net.launchpad.lens.pidgin"

CACHE = "%s/unity-lens-pidgin" % xdg.BaseDirectory.xdg_cache_home
try:
    os.makedirs(CACHE)
except OSError as exc: # Python >2.5
    if exc.errno == errno.EEXIST:
        pass
    else: raise


class Daemon:

    def __init__ (self):
        self._ct = 1
        self.error_connect = False
        self._pidgin = Pidgin(self._update_on_major_change)

        self._recent = collections.deque((), 10)

        # The path for the Lens *must* also match the one in our .lens file
        self._lens = Unity.Lens.new ("/net/launchpad/lens/pidgin", "pidgin")
        self._scope = Unity.Scope.new ("/net/launchpad/lens/pidgin/main")
        self._scope.search_in_global = True

        self._lens.props.search_hint = "Search Pidgin"
        self._lens.props.visible = True;
        self._lens.props.search_in_global = True;
        self._lens.props.sources_display_name = ("Pidgin Configs")

        self._lens.add_local_scope (self._scope);
        self._scope.connect("search-changed", self.on_search_changed)
        self._scope.connect("filters-changed", self.on_filter_changed)
        self._scope.connect("activate-uri", self.on_activate_uri);
        svg_dir = "/usr/share/icons/unity-icon-theme/places/svg/"

        self._filt_acct = filt = Unity.CheckOptionFilter.new("_filt_acct", "Accounts", None, False)
        self._lens.props.filters = [filt]

        self._set_filters()

        # Populate categories
        cats = []
        #cats.append (Unity.Category.new ("Recent",
        #                                 Gio.ThemedIcon.new(svg_dir+"group-recent.svg"),
        #                                 Unity.CategoryRenderer.HORIZONTAL_TILE))
        cats.append (Unity.Category.new ("Online",
                                         Gio.ThemedIcon.new(svg_dir+"group-installed.svg"),
                                         Unity.CategoryRenderer.HORIZONTAL_TILE))
        cats.append (Unity.Category.new ("Offline",
                                         Gio.ThemedIcon.new(svg_dir+"group-installed.svg"),
                                         Unity.CategoryRenderer.VERTICAL_TILE))
        self._lens.props.categories = cats

        locale.setlocale(locale.LC_MESSAGES, '')
        loc = locale.getlocale(locale.LC_MESSAGES)[0].split("_")[0]

        self._lens.export ();
        self._scope.export ();


    def _set_filters(self):
        accts = sorted(self._pidgin.accounts().values(), key=lambda acct: acct.stable_name)

        allActive = False

        for o in self._filt_acct.options:
            self._filt_acct.remove_option(o.props.id)

        for account in accts:
            opt = self._filt_acct.add_option(`int(account.id)`, account.name, None)


    def _update_on_major_change(self):
        self._set_filters()

        self._lens.export ();
        self._scope.export ();


    def on_activate_uri (self, scope, uri):
        print "uri = %s" % uri
        result = urlparse.urlparse(uri)
        self._pidgin.new_message(result.netloc, result.path.lstrip('/'))

        return Unity.ActivationResponse(handled=Unity.HandledType.HIDE_DASH, goto_uri='')


    def on_filter_changed(self, scope):
        accts = scope.get_filter("_filt_acct")
        result = {}
        full = self._pidgin.accounts()

        scope.queue_search_changed(Unity.SearchType.DEFAULT)


    def on_search_changed (self, scope, search, search_type, *_):
        t = time.time()
        #        if search_type is Unity.SearchType.DEFAULT:
        search_string = search.props.search_string.strip()
        print "search changed: \"%s\"" % search_string
        model = search.props.results_model
        model.clear()
        self.update_results_model(scope, model, search_string)
        search.set_reply_hint ("no-results-hint", GLib.Variant.new_string("Sorry, there are no buddies that match your search."))
        search.finished()
        print "total time: %s\n" % (time.time() - t)



    def _included_accounts(self, scope):
        acct_filter = scope.get_filter("_filt_acct")
        result = {}
        accounts = self._pidgin.accounts()
        for opt in acct_filter.options:
            if (not acct_filter.props.filtering) or opt.props.active:
                acctId = int(opt.props.id)
                result[acctId] = accounts[acctId]

        return result
            
                


    def update_results_model (self, scope, model, search):
        accts = self._included_accounts(scope)

        t = time.time()
        buddies = self._pidgin.search(search, accts)
        print "search time: %s" % (time.time() - t)

        def exists(path):
            try:
                if os.path.getsize(path) > 0:
                    return True
            except OSError:
                pass

            return False


        startTime = time.time()
        stale = time.time() - 3600
        for buddy in buddies.itervalues():
            icon = "stock_person"
            path = icon
            if buddy.icon:
                if time.time() < (startTime + 1):
                    storedPath = "%s/%s.png" % (CACHE, buddy.icon_hash())
                    if not exists(storedPath) or os.path.getmtime(storedPath) < stale:
                        statusPath = self._pidgin._get_status_path(buddy.status)
    
                        dst = GdkPixbuf.Pixbuf.new_from_file(buddy.icon)
                        dst = dst.scale_simple(128, 128, GdkPixbuf.InterpType.BILINEAR)
    
                        width = dst.get_width()
                        height = dst.get_height()
    
                        if statusPath:
                            emb = GdkPixbuf.Pixbuf.new_from_file(statusPath)
                            emb.composite(dst, 
                                    width - emb.get_width(), height - emb.get_height(),
                                    emb.get_width(), emb.get_height(),
                                    width - emb.get_width(), height - emb.get_height(),
                                    1, 1, 
                                    GdkPixbuf.InterpType.BILINEAR,
                                    255
                            )
    
                        protoPath = self._pidgin._get_proto_path(buddy.account)
                        if protoPath:
                            pro = GdkPixbuf.Pixbuf.new_from_file(protoPath)
                            pro = pro.scale_simple(32, 32, GdkPixbuf.InterpType.BILINEAR)
    
                            pro.composite(dst, 
                                    0, height - pro.get_height(),
                                    pro.get_width(), pro.get_height(),
                                    0, height - pro.get_height(),
                                    1, 1, 
                                    GdkPixbuf.InterpType.BILINEAR,
                                    255
                            )
    
    
                        dst.savev(storedPath, "png", (), ())
    
                    
                    icon = "file://" + storedPath 
    

            model.append("pidgin://%s/%s" % (buddy.account, buddy.name),
                         icon,
                         0 == buddy.online,
                         "text/html",
                         buddy.alias,
                         "%s - %s" % (buddy.status, accts[buddy.account].name),
                         path
                         )


        print "icon time: %s" % (time.time() - startTime)


class Buddy:
    icon = None
    score = 1000

    def __init__(self, bid, account, name, alias, proto):
        self.id = bid
        self.account = account
        self.name = name
        self.alias = alias
        self.online = None
        self.status = None
        self.proto = proto



    def icon_hash(self):
        """Returns a string suitable to use as a file name that is a hash of the buddy state, icon, and proto"""
        if self.icon:
            f = os.path.basename(self.icon)
            f = os.path.splitext(f)[0]

            return "x%s-%s-%s" % (f, self.proto, self.status)

        return None


class AccountInfo:

    def __init__(self, stableName, acctId, protoName, iconPath):
        self.stable_name = stableName
        self.id = acctId
        self.name = protoName
        self.icon_path = iconPath


class Pidgin:
    """Maintains our connection to the Pidg and provides access to the buddy list."""

    def __init__(self, update_ui_callback):
        # self._parse_blist()
        self._update_ui_callback = update_ui_callback
        self._connection_update_id = None

        self._bus = dbus.SessionBus()
        obj = self._bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
        self._purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")
        self._purple.PurpleAccountsInit()
        self._purple.PurpleBuddyIconsInit()

        self._buddies = {}
        self._populate_accounts()

        self._purple.connect_to_signal("BuddySignedOff", self._on_buddy_status_change, member_keyword='dbus-msg')
        self._purple.connect_to_signal("BuddySignedOn", self._on_buddy_status_change, member_keyword='dbus-msg')
        self._purple.connect_to_signal("BuddyRemoved", self._on_buddy_addRemove)
        self._purple.connect_to_signal("BuddyAdded", self._on_buddy_addRemove)

        self._purple.connect_to_signal("AccountSignedOn", self._on_connection_change, member_keyword='dbus-msg')
        self._purple.connect_to_signal("AccountSignedOff", self._on_connection_change, member_keyword='dbus-msg')


    def _populate_accounts(self):
        self._accounts = {}

        for account in self._purple.PurpleAccountsGetAllActive():
            self._get_proto_path(account)

        self._gather_buddies()


    def _on_buddy_status_change(self, buddy_id, *k, **kw):
        print "%s change: %s" % (kw['dbus-msg'], buddy_id)
        buddy = self._buddies[buddy_id]
        self.fill(buddy)


    def _on_buddy_addRemove(self, buddy_id, **kw):
        print "%s change: %s" % (kw['dbus-msg'], buddy_id)
        self._gather_buddies()
        

    def _on_connection_change(self, *k, **kw):
        print "%s change" % kw['dbus-msg']
        
        if self._connection_update_id:
            print "resched"
            GLib.source_remove(self._connection_update_id)
            self._connection_update_id = None

        self._connection_update_id = GLib.timeout_add_seconds(2, self._update_accounts_and_ui)        


    def _update_accounts_and_ui(self):
        print "run"
        self._populate_accounts()

        self._update_ui_callback()
        

    def accounts(self):
        return self._accounts


    def _gather_buddies(self):
        self._buddies = {}
        for account in self._purple.PurpleAccountsGetAllActive():
            proto = self._purple.PurpleAccountGetProtocolName(account)
            buddylist = self._purple.PurpleFindBuddies(account, '')
            for buddyid in buddylist:
                name = self._purple.PurpleBuddyGetName(buddyid)
                alias = self._purple.PurpleBuddyGetAlias(buddyid)

                buddy = Buddy(buddyid, account, name, alias, proto)
                self.fill(buddy)

                self._buddies[buddyid] = buddy


        return self._buddies


    def new_message(self, account, buddy):
        current = None
        for window in self._purple.PurpleGetIms():
            if buddy == self._purple.PurpleConversationGetName(window):
                current = window
                break

        if current:
            self._purple.PurpleConversationPresent(window)
        else:
            self._purple.PurpleConversationNew(1, int(account), buddy)


    def fill(self, buddy):
        buddy.online = self._purple.PurpleBuddyIsOnline(buddy.id)
        buddy.status = self._purple.PurpleStatusGetId(
                self._purple.PurplePresenceGetActiveStatus(
                        self._purple.PurpleBuddyGetPresence(buddy.id)
                )
        )

        buddy.groupName = self._purple.PurpleGroupGetName(
                self._purple.PurpleBuddyGetGroup(buddy.id)
        )

        icon = self._purple.PurpleBuddyGetIcon(buddy.id)
        if icon > 0:
            buddy.icon = self._purple.PurpleBuddyIconGetFullPath(icon)
        else:
            buddy.icon = None


    def is_active(self, buddy):
        return buddy.status == "available"

    def search(self, string, includedAccounts):
        results = {}

        for key, buddy in self._buddies.iteritems():
            if not buddy.account in includedAccounts:
                continue

            scorename = buddy.name.split('@')[0].lower().find(string)
            scorealias = buddy.alias.lower().find(string)
            if ((scorename >= 0) or (scorealias >= 0)):
                if scorename < 0:
                    scorename = 100
                if scorealias < 0:
                    scorealias = 100

                if self.is_active(buddy):
                    buddy.score = 0
                else:
                    buddy.score = 100

                buddy.score += min(scorename, scorealias)
                results[key] = buddy

        return results

    STATUS_MAP={
        "available" : "available",
        "active" : "available",

        "offline" : "offline",
        "away" : "away",

        "dnd" : "busy",
    }

    def _get_status_path(self, statusName):
        """Return a path to a status icon"""
        try:
            return  "/usr/share/pixmaps/pidgin/status/32/%s.png" % Pidgin.STATUS_MAP[statusName]
        except KeyError:
            print "Unknown status: %s" % statusName
            return None


    def _get_proto_path(self, account):
        """Return a path to the protocol icon"""
        if self._accounts.has_key(account):
            return self._accounts[account].icon_path

        proto = self._purple.PurpleAccountGetProtocolName(account)

        name = proto
        path = None
        if "Sametime" == proto:
            path = "meanwhile"

        elif "XMPP" == proto:
            disp = self._purple.PurpleAccountGetNameForDisplay(account)
            if disp.find("gmail.com") > -1:
                path = "google-talk"
                name = "GTalk"
            elif disp.find("facebook.com") > -1:
                path = "facebook"
                name = "Facebook"
            else:
                name = disp[disp.find("@") + 1 : disp.find("/")]

        if path:
            img = "/usr/share/pixmaps/pidgin/protocols/22/%s.png" % path
        else:
            img = None

        stableName = self._purple.PurpleAccountGetNameForDisplay(account)
        self._accounts[account] = AccountInfo(stableName, account, name, img)

        return img
        

def clear_cache():
    #os.listdir(CACHE)
    print "called"
    return False
    

if __name__ == "__main__":
    DBusGMainLoop(set_as_default=True)

    loop = GObject.MainLoop()
    session_bus_connection = Gio.bus_get_sync (Gio.BusType.SESSION, None)
    session_bus = Gio.DBusProxy.new_sync (session_bus_connection, 0, None,
                                          'org.freedesktop.DBus',
                                          '/org/freedesktop/DBus',
                                          'org.freedesktop.DBus', None)
    result = session_bus.call_sync('RequestName',
                                   GLib.Variant ("(su)", (BUS_NAME, 0x4)),
                                   0, -1, None)


    # Unpack variant response with signature "(u)". 1 means we got it.
    result = result.unpack()[0]

    if result != 1 :
        print >> sys.stderr, "Failed to own name %s. Bailing out." % BUS_NAME
        raise SystemExit (1)

    daemon = Daemon()
    loop.run()