~davidc3/unity-books-lens/trunk

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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
#! /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, locale, re

# Unity imports
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gio
from gi.repository import Dee
# FIXME: Some weird bug in Dee or PyGI makes Dee fail unless we probe
#        it *before* we import the Unity module... ?!
_m = dir(Dee.SequenceModel)
from gi.repository import Unity

# google API imports
import api_fun_park



# The primary bus name we grab *must* match what we specify in our .place file
BUS_NAME = "net.launchpad.UnityBooksLens"


# Group ids. Must match the offset into the group models
GROUP_BOOKS = 0
GROUP_DOCUMENTATION = 1
GROUP_AUTHORS = 2

GROUP_SEARCH_ENGINES = 3
GROUP_SOURCES = 4

# Section ids. Must match the offset into the section model
SECTION_ALL_BOOKS = 0
ABOUT = "?"

# Timers:
# If a secondary API takes more than 2 seconds to answer a test call, skip it for this session.
timer_limit = 1500.0
blekko_timer = float(api_fun_park.timer('http://blekko.com'))
#blekko_timer = 500.0
google_books_timer = 500.0
google_images_timer = 500.0

active_bug_workaround = [1,2,3]
old_search = ''

class Daemon (object):
    
    active_section = 0
    global url_list_for_single_search
    url_list_for_single_search = []
    
    def __init__(self):
        #
        # Safe for the signal handlers, I don't know what any of the things
        # in this method mean. Should have to ask someone.
        #
        self._entry = Unity.PlaceEntryInfo.new(
            "/net/launchpad/unitybookslens/mainentry")

        #
        # Set up all the datamodels we'll share with the Unity process
        # See https://wiki.ubuntu.com/Unity/Lenses
        #
        # Terminology:
        #
        #   - "sections" A set of disjoint browsable categories.
        #                Fx. "Books", "Film", and "Music"
        #
        #   - "groups" A set of labels that partition the result set into
        #              user-visible chunks. "Popular Books", "Recent Books"
        #
        sections_model = Dee.SharedModel.new(BUS_NAME + 
            ".SectionsModel")
        sections_model.set_schema("s", "s")
        self._entry.props.sections_model = sections_model

        groups_model = Dee.SharedModel.new(BUS_NAME + 
            ".GroupsModel")
        groups_model.set_schema("s", "s", "s")
        self._entry.props.entry_renderer_info.props.groups_model = groups_model

        global_groups_model = Dee.SharedModel.new(BUS_NAME +
            ".GlobalGroupsModel")
        global_groups_model.set_schema("s", "s", "s")
        self._entry.props.global_renderer_info.props.groups_model = (
            global_groups_model)

        results_model = Dee.SharedModel.new(BUS_NAME + 
            ".ResultsModel")
        results_model.set_schema("s", "s", "u", "s", "s", "s")
        self._entry.props.entry_renderer_info.props.results_model = (
            results_model)

        global_results_model = Dee.SharedModel.new(BUS_NAME +
            ".GlobalResultsModel")
        global_results_model.set_schema("s", "s", "u", "s", "s", "s")
        self._entry.props.global_renderer_info.props.results_model = (
            global_results_model)

        #
        # Populate the sections and groups once we are in sync with Unity
        #
        sections_model.connect("notify::synchronized",
            self._on_sections_synchronized)
        groups_model.connect("notify::synchronized",
            self._on_groups_synchronized)
        global_groups_model.connect("notify::synchronized",
            self._on_global_groups_synchronized)

        #
        # Set up the signals we'll receive when Unity starts to talk to us
        #

        # The 'active-search' property is changed when the users searches
        # within this particular place
        self._entry.connect("notify::active-search", self.on_search_changed)

        # The 'active-global-search' property is changed when the user searches
        # from the Dash aka Home Screen
        self._entry.connect("notify::active-global-search",
            self.on_global_search_changed)

        # Listen for changes to the section
        self._entry.connect("notify::active-section", self.on_section_change)
        
        # Listen for changes to the status
        self._entry.connect("notify::active", self.on_active_change)

        #
        # PlaceEntries are housed by PlaceControllers.
        # You may have mutiple entries per controller if you like.
        # The controller *must* have the DBus Object path you specify
        # in your .place file
        #
        self._ctrl = Unity.PlaceController.new("/net/launchpad/unitybookslens")
        self._ctrl.add_entry(self._entry)
        self._ctrl.export()

    def on_active_change(self, entry, section):
    # FIXME "active" is NOT reliable to check for lens closing/opening.
    # It can be sent during long or slow searches. Here is an ugly hack:
        print "on_active_change"
        global active_bug_workaround
        active_bug_workaround.append('ON_ACTIVE_CHANGE')
        try:
            if active_bug_workaround[-1] == active_bug_workaround[-2] == 'ON_ACTIVE_CHANGE':

                results = entry.get_property("entry_renderer_info").get_property("results_model")
                self.update_results_model (search=None, model=results, zeitgeist="yes")
        except:
            active_bug_workaround = [1,2,3]
            pass
        


    def on_section_change(self, entry, section):
        print "on_section_change"
        self.active_section = entry.get_property("active-section")
        active_search = entry.get_property("active-search")
        if active_search:
            search = active_search.get_search_string()
        else:
            search = None
        results = entry.get_property("entry_renderer_info").get_property("results_model")
        self.update_results_model (search=search, model=results, zeitgeist=None)
#        active_search.finished()
            

    def _on_sections_synchronized(self, sections_model, *args):
        # Column0: display name
        # Column1: GIcon in string format
        sections_model.clear()
        sections_model.append("All Books",
            Gio.ThemedIcon.new("document").to_string())

    def _on_groups_synchronized(self, groups_model, *args):
        # Column0: group renderer
        # Column1: display name
        # Column2: GIcon in string format
        groups_model.clear()
        
        # !! The row offsets must match the GROUP_* constants !!
        groups_model.append("UnityHorizontalTileRenderer",
            "Books",
            Gio.ThemedIcon.new("account-logged-in").to_string())
        
        # !! The row offsets must match the GROUP_* constants !!
        groups_model.append("UnityHorizontalTileRenderer",
            "Documentation",
            Gio.ThemedIcon.new("account-logged-in").to_string())

        # !! The row offsets must match the GROUP_* constants !!
        groups_model.append("UnityHorizontalTileRenderer",
            "Focused Author",
            Gio.ThemedIcon.new("stock_person-panel").to_string())
            
        # !! The row offsets must match the GROUP_* constants !!
        groups_model.append("UnityDefaultRenderer",
            "Powered by",
            Gio.ThemedIcon.new("system-run").to_string())

        # !! The row offsets must match the GROUP_* constants !!
        groups_model.append("UnityDefaultRenderer",
            "Sources",
            Gio.ThemedIcon.new("account-logged-in").to_string())


    def _on_global_groups_synchronized(self, global_groups_model, *args):
        # Just the same as the normal groups
        self._on_groups_synchronized(global_groups_model)

    def thaw(self, entry):
        entry.thaw_notify()
        return False

    def on_search_changed (self, entry, *args):
        global active_bug_workaround
        active_bug_workaround.append('on_search_changed')
        print "on_search_changed"
        # Prevent concurrent searches and concurrent updates of our models,
        # by preventing any notify signals from propagating to us.
        # Important: Remember to thaw the notifys again! 
        entry.freeze_notify ()
        active_search = entry.get_property("active_search")
        search = active_search.get_search_string()
        search = search.replace(" ", "+")
        results = entry.get_property("entry_renderer_info").get_property("results_model")
        self.update_results_model (search, results, zeitgeist=None)
#        active_search.finished()
        GObject.idle_add(self.thaw, entry)

    def on_global_search_changed (self, entry, param_spec):
        print "on_global_search_changed"
        # Prevent concurrent searches and concurrent updates of our models,
        # by preventing any notify signals from propagating to us.
        # Important: Remember to thaw the notifys again! 
        entry.freeze_notify ()
        active_search = entry.get_property("active_global_search")
        search = active_search.get_search_string()
        search = search.replace(" ", "+")
        results = entry.get_property("global_renderer_info").get_property("results_model")
        self.update_simple_results_model (search, results)
#        active_search.finished()
        GObject.idle_add(self.thaw, entry)

    def clean_auto_query(self, query):
        #
        # This method is used to clean the query provided by Zeitgeist
        # FIXME This should be tested with popular websites/applications/file naming schemes
        #
        query_crop = re.sub('[^a-zA-Z0-9 ].*', '', query)
        if len(query_crop) < 4:
            query_crop = re.sub('^[a-zA-Z0-9 ]{3,}[^a-zA-Z0-9 ]', '', query)
            query_crop = re.sub('[^a-zA-Z0-9 ].*', '', query_crop)
        return query_crop.strip()

    def clean_title(self, title):
        #
        # This method is very sensitive to changes in the search API.
        # It should be the first place to look if results "look odd".
        #
        title = title.replace("- Google ebookstore", "")
        title = title.replace("- Google eBookstore", "")
        title = title.replace("- Wikipedia, the free encyclopedia", "")
        title = title.replace("Project Gutenberg&#39;s", "")
        title = title.replace(" -&nbsp;Project Gutenberg", "")
        title = title.replace(" Google", "")
        title = title.replace("&#39;", "'")
        title = title.replace("&amp;", "&")
        title = title.replace("&lt;", "<")
        title = title.replace("&gt;", ">")
        title = title.replace("File:", "")
        title = title.replace("Category:", "")
        title = title.replace(" - Wikimedia Commons", "")
        title = title.replace(" - Wikipedia", "")
        title = title.replace(" - Full Text Free Book", "")
        title = title.replace("<strong>", "")
        title = title.replace("</strong>", "")
        return title.strip()

#
# Method to deal with Google Books results
#
    def google_books_display(self, data, group, model):
        if data != '' and data:
            for i in data:
                url = i['unescapedUrl']
                icon_hint = i['tbUrl']
                authors = i['authors']
                title = i['titleNoFormatting']
                if (icon_hint.startswith("/googlebooks")):
                    icon_hint = "http://books.google.com/googlebooks/images/no_cover_thumb.gif"
                # Until update of Google Books API, skip unknown authors to avoid displaying magazines
                if (url.startswith("http://")) and authors != "unknown" and url.split("&")[0] not in url_list_for_single_search:
                    #print "    " + title
                    if (title.count(" - ") >= 1 and title.split(" - ")[0] ==
                        title.split(" - ")[0].lower()):  # this is a hack, but it's
                        title = ' - '.join(title.split(" - ")[1:])  # acceptable.
                    title = self.clean_title(title)
                    url_list_for_single_search.append(url.split("&")[0])
                    model.append(url, icon_hint, group, "text/html",
                        title, authors)

#
# Method to deal with Blekko results
#                    
    def blekko_display(self, data, group, model):
        if data != '' and data:
            for i in data:
                author = ""
                url = i['url']
                title = i['url_title']
                icon_hint = "http://books.google.com/googlebooks/images/no_cover_thumb.gif"
                if (url.startswith("http://")):
                    #print "    " + title
                    title = self.clean_title(title)
                    if (title.count(" by ") >= 1 ):
                        title_minus_author = title.split(" by ")[0]
                        author_minus_title = title.split(" by ")[1]
                        title = title_minus_author
                        author = author_minus_title
                    title = self.clean_title(title)
                    author = self.clean_title(author)
                    model.append(url, icon_hint, group, "text/html",
                        title, author)
                        
#
# Method to deal with Wikipedia results
#                    
    def wikipedia_display(self, data, group, model):
        if data != '' and data:
            for i in data:
                author = ""
                url = "http://" + api_fun_park.session_locale + ".wikipedia.org/wiki/"+ i
                title = i
                icon_hint = "http://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/Wikipedia-logo.svg/48px-Wikipedia-logo.svg.png"
                if (url.startswith("http://")):
                    #print "    " + title
                    title = self.clean_title(title)
                    title = self.clean_title(title)
                    author = "Wikipedia article"
                    model.append(url, icon_hint, group, "text/html",
                        title, author)


#
# Blekko search with user keywords
#               
    def blekko_all_results(self, search, model):
            # /davidc/books-lens is a predefined search slashtag on my Blekko account.
            # At the time being, it searches Project Gutenberg and Forgotten Books to the extent of Blekko capabilities.
            data_blekko = api_fun_park.blekko_search("%s+/davidc/books-lens+/json" % search)
            self.blekko_display(data_blekko, GROUP_BOOKS, model)     

#
# Wikipedia search with user keywords
#               
    def wikipedia_all_results(self, search, model):
            data_wikipedia = api_fun_park.wikipedia_search("%s" % search)
            self.wikipedia_display(data_wikipedia, GROUP_DOCUMENTATION, model)               

#
# Google Books search with user keywords
#
    def google_books_all_results(self, search, model):
            # Make these results global for "author focus"
            global data_google
            data_google = api_fun_park.google_books_first_search("%s" % 
                search, 0)
            self.google_books_display(data_google, GROUP_BOOKS, model)

#
# Google Books search with inauthor:"author_focus"
#
    def google_books_authors_results(self, search, model):
        if not (re.match(".*unknown.*", author_focus, flags=re.IGNORECASE)):
            author_focus_sane = "\"" + author_focus + "\""
            data_google = api_fun_park.google_books_search("inauthor:%s" % 
                author_focus_sane, 0)
            self.google_books_display(data_google, GROUP_AUTHORS, model)
            
#
# Google FREE Books search with user keywords
#
    def google_books_free_results(self, search, model):
        # Make these results global for "author focus"
        data_google = api_fun_park.google_books_first_search("%s" % 
            search, 1)
        self.google_books_display(data_google, GROUP_BOOKS, model)
            
#
# Google FREE Books search with inauthor:"author_focus"
#
    def google_books_authors_free_results(self, search, model):
        if not (re.match(".*unknown.*", author_focus, flags=re.IGNORECASE)):
            author_focus_sane = "\"" + author_focus + "\""
            data_google = api_fun_park.google_books_search("inauthor:%s" % 
                author_focus_sane, 1)
            self.google_books_display(data_google, GROUP_AUTHORS, model)
                            
#
# Google Image search for first author's face
#
    def authors_face_results(self, search, model):
        #
        # Author Focus: 
        # we use the first author from the first Google query,
        # to hopefully display the same group results whether we search 
        # "Moby Dick" or "Melville"
        #
        global author_focus
        if data_google:
            author_focus = data_google[0]['authors'].split(",")[0]
            global author_focus_sane
            author_focus_sane = author_focus.replace(" ", "+")
        else:
            author_focus = "unknown"
        if not (re.match(".*unknown.*", author_focus, flags=re.IGNORECASE)):
#            author_data = api_fun_park.google_image_ol_search("%s" % author_focus_sane)
            test = url = icon_hint = ""
            title = author_focus
#
# FIXME OpenLibrary Image search (google_image_ol_search) slows things down, fix it or remove it.
#
#            if author_data != '':
#                for i in author_data:
#                    test = i['unescapedUrl']
#                if not (re.match(".*covers.openlibrary.org/a.*", test, flags=re.IGNORECASE)):
            author_data = api_fun_park.google_image_search("author+%s" % 
                author_focus_sane)
            if author_data:
                for i in author_data:
                    icon_hint = i['tbUrl']
                    url = "http://" + api_fun_park.session_locale + ".wikipedia.org/wiki/"+ author_focus
                if (icon_hint == ""):
                        icon_hint = Gio.ThemedIcon.new("stock_person").to_string()
                model.append(url, icon_hint, GROUP_AUTHORS, "text/html",
                    title, "Wikipedia article")

#
# About Lens, the "?" query.
#
    def about_display(self, data, group, model):
        for i in data:
            url = i['url']
            title = i['source']
            icon_hint = i['icon']
            model.append(url, icon_hint, group, "text/html",
                title, title)
                
    def about_results(self, model):
        search_engines = {
            "source":"Google",
            "url":"http://books.google.com",
            "icon":"http://www.google.com/images/logos/ps_logo2.png"},{
            "source":"Blekko",
            "url":"http://www.blekko.com",
            "icon":"http://a.blekko-img.com/045/gz/theme19/imgs/logo_135x53.png"}
        sources = {
            "source":"Google Books",
            "url":"http://books.google.com",
            "icon":"http://books.google.com/intl/en/images/logos/books_logo.gif"},{
            "source":"Open Library",
            "url":"http://openlibrary.org",
            "icon":"http://openlibrary.org/images/logo_OL-lg.png"},{
            "source":"Project Gutenberg",
            "url":"http://www.gutenberg.org",
            "icon":"http://www.gutenbergnews.org/images/project-gutenberg-logo.jpg"},{
            "source":"Google Images",
            "url":"http://images.google.com",
            "icon":"http://www.google.fr/intl/fr_ALL/images/logos/images_logo_lg.gif"}
        self.about_display(search_engines, GROUP_SEARCH_ENGINES, model)
        self.about_display(sources, GROUP_SOURCES, model)

#
# Update results model
#
    def update_results_model(self, search, model, zeitgeist):
        global active_bug_workaround
        global old_search
        active_bug_workaround.append('update_results_model')
        print "update_results_model"
        potential_search = self.clean_auto_query(api_fun_park.zeitgeist_latest())
        if potential_search != old_search and not search:
            model.clear()
            if zeitgeist and active_bug_workaround[-2] == active_bug_workaround[-3] == 'ON_ACTIVE_CHANGE':
                search = potential_search
        if search != ABOUT and search != '' and search:
            model.clear()
            if self.active_section == SECTION_ALL_BOOKS:
                if blekko_timer < timer_limit:
                    self.blekko_all_results(search, model)
                if google_books_timer < timer_limit: 
                    self.google_books_all_results(search, model)
                if google_books_timer < timer_limit: 
                    self.google_books_free_results(search, model)

                model.flush_revision_queue()
                self.wikipedia_all_results(search, model)
                model.flush_revision_queue()
                
                global url_list_for_single_search
                url_list_for_single_search = []
                
                if google_images_timer < timer_limit:
                    self.authors_face_results(search, model)
                if google_books_timer < timer_limit: 
                    self.google_books_authors_results(search, model)
                model.flush_revision_queue()
        if search == ABOUT:
            model.clear()
            self.about_results(model)
    
        active_bug_workaround = [1,2,3]
        old_search = potential_search

    def update_simple_results_model(self, search, model):
        print "update_simple_results_model"
        model.clear()
        if self.active_section == SECTION_ALL_BOOKS:
            # keep only the fastest and less intrusive search for global
            self.wikipedia_all_results(search, model)
            self.google_books_all_results(search, model)

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)
    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()