~sdague/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
#! /usr/bin/python

#    Copyright (c) 2011 David Calle <davidc@framli.eu>

#    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
import glob
from gi.repository import GLib, GObject, Gio
from gi.repository import Dee
from gi.repository import Unity
import dbus
import urllib2
import simplejson
import locale
import datetime
import urlparse

from operator import attrgetter

import pprint
import xml.etree.ElementTree

BUS_NAME = "net.launchpad.lens.pidgin"

class Daemon:

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

        # 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("activate-uri", self.on_activate_uri);
        svg_dir = "/usr/share/icons/unity-icon-theme/places/svg/"

        # Populate categories
        cats = []
        cats.append (Unity.Category.new ("Online Buddies",
                                         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 on_activate_uri (self, scope, uri):
        print "uri = %s" % uri
        result = urlparse.urlparse(uri)
        self._pidgin.new_message(result.netloc, result.path.lstrip('/'))
        # self._pidgin.
        return Unity.ActivationResponse(handled=Unity.HandledType.HIDE_DASH, goto_uri='')

    def on_search_changed (self, scope, search, search_type, *_):
        #        if search_type is Unity.SearchType.DEFAULT:
        search_string = search.props.search_string.strip()
        model = search.props.results_model
        model.clear()
        self.update_results_model(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()

    def update_results_model (self, model, search):
        if search == '':
            return

        buddies = self._pidgin.search(search)

        for buddy in buddies:
            icon = "stock_person"
            if buddy.icon:
                icon = "file://%s" % buddy.icon

            model.append("pidgin://%s/%s" % (buddy.account, buddy.name),
                         icon,
                         0,
                         "text/html",
                         buddy.alias,
                         buddy.name,
                         icon
                         )


class Buddy:
    icon = None
    score = 1000

    def __init__(self, bid, account, name, alias):
        self.id = bid
        self.account = account
        self.name = name
        self.alias = alias


class Pidgin:

    def __init__(self):
        # self._parse_blist()
        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")

    def _gather_buddies(self):
        self._buddies = []
        for account in self._purple.PurpleAccountsGetAllActive():
            buddylist = self._purple.PurpleFindBuddies(account, '')
            for buddyid in buddylist:
                online = self._purple.PurpleBuddyIsOnline(buddyid)
                if online != 0:
                    name = self._purple.PurpleBuddyGetName(buddyid)
                    alias = self._purple.PurpleBuddyGetAlias(buddyid)
                    self._buddies.append(
                        Buddy(
                            buddyid,
                            account,
                            name,
                            alias)
                        )

        return self._buddies

    def new_message(self, account, buddy):
        self._purple.PurpleConversationNew(1, int(account), buddy)

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


    def is_active(self, buddy):
        presense = self._purple.PurpleBuddyGetPresence(buddy.id)
        status = self._purple.PurplePresenceGetActiveStatus(presense)
        return self._purple.PurpleStatusGetId(status) == "available"

    def search(self,  string):
        buddies = self._gather_buddies()
        results = []

        for buddy in buddies:
            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

                self.fill(buddy)

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

                buddy.score += min(scorename, scorealias)
                results.append(buddy)

        return sorted(results, key=attrgetter('score'))


if __name__ == "__main__":
    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()
    GObject.MainLoop().run()