~unity-team/unity-lens-video/remote-videos-scope-12.04

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

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

"""The unity remote videos scope."""

import json
import sys
from urllib import urlencode
import time

#pylint: disable=E0611
from zeitgeist.client import ZeitgeistClient
from zeitgeist.datamodel import (
    Event, 
    Subject, 
    Interpretation, 
    Manifestation,
)

from gi.repository import (
    GLib,
    GObject,
    Gio,
    Unity,
    Soup,
    SoupGNOME,
)
#pylint: enable=E0611

BUS_NAME = "net.launchpad.scope.RemoteVideos"
SERVER = "http://videosearch.ubuntu.com/v0"

REFRESH_INTERVAL = 3600         # fetch sources & recommendations once an hour
RETRY_INTERVAL = 60             # retry sources/recommendations after a minute

# Be cautious with Zeitgeist, don't assume it's ready
try:
    ZGCLIENT = ZeitgeistClient()
    # Creation of the Zg data source
    ZGCLIENT.register_data_source("98898", "Unity Videos lens",
        "",[Event.new_for_values(actor="lens://unity-lens-video")])
except:
    print "Unable to connect to Zeitgeist, won't send events."
    ZGCLIENT = None

class Daemon:

    """Create the scope and listen to Unity signals"""

    def __init__(self):
        self._pending = None
        self.sources_list = []
        self.recommendations = []
        self.scope = Unity.Scope.new("/net/launchpad/scope/remotevideos")
        self.scope.search_in_global = False
        self.scope.connect("search-changed", self.on_search_changed)
        self.scope.connect("notify::active", self.on_lens_active)
        self.scope.connect("filters-changed", self.on_filtering_changed)
        self.scope.props.sources.connect("notify::filtering",
            self.on_filtering_changed)
        self.scope.connect ("activate-uri", self.on_activate_uri)
        self.session = Soup.SessionAsync()
        self.session.props.user_agent = "Unity Video Lens Remote Scope v0.4"
        self.session.add_feature_by_type(SoupGNOME.ProxyResolverGNOME)
        self.query_list_of_sources()
        self.update_recommendations()
        self.scope.export()

    def update_recommendations(self):
        """Query the server for 'recommendations'.

        In v0, that means simply do an empty search.
        """
        msg = Soup.Message.new("GET", SERVER + "/search")
        self.session.queue_message(msg, self._recs_cb, None)

    def _recs_cb(self, session, msg, user_data):
        recs = self._handle_search_msg(msg)
        print "Got %d recommendations from the server" % len(recs)
        if recs:
            self.recommendations = recs
            dt = REFRESH_INTERVAL
        else:
            dt = RETRY_INTERVAL
        GLib.timeout_add_seconds(dt, self.update_recommendations)

    def query_list_of_sources(self):
        """Query the server for a list of sources that will be used
        to build sources filter options and search queries."""
        msg = Soup.Message.new("GET", SERVER + "/sources")
        self.session.queue_message(msg, self._sources_cb, None)

    def _sources_cb(self, session, msg, user_data):
        if msg.status_code != 200:
            print "Error: Unable to query the server for a list of sources"
            print "       %d: %s" % (msg.status_code, msg.reason_phrase)
        else:
            try:
                sources_list = json.loads(msg.response_body.data)
            except ValueError:
                print "Error: got garbage json from the server"
            else:
                if isinstance(sources_list, dict):
                    sources_list = sources_list.get('results', [])
                if sources_list and sources_list != self.sources_list:
                    self.sources_list = sources_list
                    sources = self.scope.props.sources
                    for opt in sources.options[:]:
                        sources.remove_option(opt.props.id)
                    for source in self.sources_list:
                        sources.add_option(source, source, None)
        if self.sources_list:
            # refresh later
            dt = REFRESH_INTERVAL
        else:
            # retry soon
            dt = RETRY_INTERVAL
        GLib.timeout_add_seconds(dt, self.query_list_of_sources)

    def on_filtering_changed(self, *_):
        """Run another search when a filter change is notified."""
        self.scope.queue_search_changed(Unity.SearchType.DEFAULT)

    def on_lens_active(self, *_):
        """ Run a search when the lens is opened """
        if self.scope.props.active:
            self.scope.queue_search_changed(Unity.SearchType.DEFAULT)

    def source_activated(self, source):
        """Return the state of a sources filter option."""
        active = self.scope.props.sources.get_option(source).props.active
        filtering = self.scope.props.sources.props.filtering
        if (active and filtering) or (not active and not filtering):
            return True
        else:
            return False
            
    def at_least_one_source_is_on(self, sources):
        """Return a general activation state of all sources of this scope.
        This is needed, because we don't want to show recommends if an option
        from another scope is the only one activated"""
        filtering = self.scope.props.sources.props.filtering
        if filtering and len(sources) > 0 or not filtering:
            return True
        else:
            return False

    def on_search_changed(self, scope, search, search_type, _):
        """Get the search string, prepare a list of activated sources for 
        the server, update the model and notify the lens when we are done."""
        search_string = search.props.search_string.strip()
        # note search_string is a utf-8 encoded string, now:
        print "Search changed to %r" % search_string
        model = search.props.results_model
        model.clear()
        # Create a list of activated sources
        sources = [source for source in self.sources_list
                   if self.source_activated(source)]
        # If all the sources are activated, don't bother
        # passing them as arguments
        if len(sources) == len(self.sources_list):
            sources = ''
        else:
            sources = ','.join(sources)
        working = False
        # Ensure that we are not in Global search
        if search_type is Unity.SearchType.DEFAULT: 
            if self.at_least_one_source_is_on(sources):
                self.get_results(search_string, search, model, sources)
                working = True
        if search and not working:
            search.finished()

    def update_results_model(self, search, model, results):
        """Run the search method and check if a list of sources is present.
        This is useful when coming out of a network issue."""
        for i in results:
            try:
                uri = i['url'].encode('utf-8')
                title = i['title'].encode('utf-8')
                icon = i['img'].encode('utf-8')
                comment = i['source'].encode('utf-8')
                if uri.startswith('http'):
                    # Instead of an uri, we pass a string of uri + metadata
                    model.append(uri+'lens-meta://'+title+'lens-meta://'+icon,
                    icon, 2, "text/html", str(title), str(comment), str(uri))
            except (KeyError, TypeError, AttributeError):
                print "Malformed result, skipping."
        model.flush_revision_queue()
        if search:
            search.finished()
        if self.sources_list == []:
            self.query_list_of_sources()

    def get_results(self, search_string, search, model, sources):
        """Query the server with the search string and the list of sources."""
        if not search_string and not sources and self.recommendations:
            self.update_results_model(search, model, self.recommendations)
            return
        if self._pending is not None:
            self.session.cancel_message(self._pending,
                                        Soup.KnownStatusCode.CANCELLED)
        query = dict(q=search_string)
        if sources:
            query['sources'] = sources.encode("utf-8")
        query = urlencode(query)
        url = "%s/search?%s" % (SERVER, query)
        print "Querying the server:", url
        self._pending = Soup.Message.new("GET", url)
        self.session.queue_message(self._pending,
                                   self._search_cb,
                                   (search, model))

    def _search_cb(self, session, msg, (search, model)):
        if msg is not self._pending:
            # nothing to do here
            print "WAT? _search_cb snuck in on a non-pending msg"
            return
        self._pending = None
        results = self._handle_search_msg(msg)
        self.update_results_model(search, model, results)

    def _handle_search_msg(self, msg):
        results = []
        if msg.status_code != 200:
            print "Error: Unable to get results from the server"
            print "       %d: %s" % (msg.status_code, msg.reason_phrase)
        else:
            try:
                results = json.loads(msg.response_body.data)
            except ValueError:
                print "Error: got garbage json from the server"
        if isinstance(results, dict):
            results = results.get('results', [])
        return results


    def on_activate_uri (self, scope, rawuri):
        """On item clicked, parse the custom uri items"""
        # Parse the metadata before passing the whole to Zg
        uri = rawuri.split('lens-meta://')[0]
        title = rawuri.split('lens-meta://')[1]
        icon = rawuri.split('lens-meta://')[2]
        if ZGCLIENT:
            self.zeitgeist_insert_event(uri, title, icon)
        # Use direct glib activation instead of Unity's own method
        # to workaround an ActivationResponse bug.
        GLib.spawn_async(["/usr/bin/gvfs-open", uri])
        # Then close the Dash
        return Unity.ActivationResponse(goto_uri='', handled=2 )

    def zeitgeist_insert_event(self, uri, title, icon):
        """Insert item uri as a new Zeitgeist event"""
        # "storage" is an optional zg string 
        # we use is to host the icon link. 
        # Storing it another way and referring to it lens side
        # would be more elegant but much more expensive.
        subject = Subject.new_for_values(
            uri = uri,
            interpretation=unicode(Interpretation.VIDEO),
            manifestation=unicode(Manifestation.FILE_DATA_OBJECT.REMOTE_DATA_OBJECT),
            origin=uri,
            storage=icon,
            text = title)
        event = Event.new_for_values(
            timestamp=int(time.time()*1000),
            interpretation=unicode(Interpretation.ACCESS_EVENT),
            manifestation=unicode(Manifestation.USER_ACTIVITY),
            actor="lens://unity-lens-video",
            subjects=[subject,])
        ZGCLIENT.insert_event(event)

def main():
    """Connect to the session bus, exit if there is a running instance."""
    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()
    GObject.MainLoop().run()

if __name__ == "__main__":
    main()