~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
#! /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 locale
import urllib
import urllib2
import simplejson
import time
import gobject
from zeitgeist import client, datamodel
import socket

# Timeout in seconds
timeout = 5
socket.setdefaulttimeout(timeout)

#
# Basic pinger to find out response time of a source
# FIXME It does not belong to an API "fun park", another file needs to be created: tools_land?
#
def timer(host):
    t1 = time.time()
    try:
        urllib.urlopen(host).read()
        return (time.time() - t1) * 1000
    except (IOError, urllib2.URLError, urllib2.HTTPError, simplejson.JSONDecodeError):
        print "blekko_is_not_reachable"
        return 10000

#
# Determine session's locale to optimize queries
#
locale.setlocale(locale.LC_MESSAGES, '')
global session_locale
session_locale = locale.getlocale(locale.LC_MESSAGES)[0].split("_")[0]
print "session locale:" + session_locale

#
# Blekko API 
#
def blekko_search(q):
    try:
        q = q.replace(" ", "+")
        url = ('https://blekko.com/ws/?auth=70fc3602&q=%s' % (q))
        f = urllib2.urlopen(url)
        content = f.read()
        results = simplejson.loads(content)
        print "blekko_search"
        return results['RESULT']
    except KeyError:
        return
    except (IOError, urllib2.URLError, urllib2.HTTPError, simplejson.JSONDecodeError):
        print "blekko_search_is_error"
        return

#
# Wikipedia API 
#
def wikipedia_search(q):
    try:
        q = q.replace(" ", "|")
        url = ("http://" + session_locale +'.wikipedia.org/w/api.php?action=opensearch&limit=6&format=json&search=%s' % (q))
        f = urllib2.urlopen(url)
        content = f.read()
        results = simplejson.loads(content)
        print "wikipedia_search"
        return results[1]
    except KeyError:
        return
    except (IOError, urllib2.URLError, urllib2.HTTPError, simplejson.JSONDecodeError):
        print "wikipedia_search_is_error"
        return

#
# Google Books API "first search"
# This first search is used to avoid an encoding nightmare. 
# It's different from others as it directly gets values from the search bar.
# <http://code.google.com/apis/books/docs/js/jsondevguide.html>
#
def google_books_first_search(q, as_brr):
    try:
        query = urllib.urlencode({'q': q })
        if query != '' or query != 'q=' or query != 'q':
            url = ('https://ajax.googleapis.com/ajax/services/search/books?v=1.0&hl=' + session_locale + '&rsz=6&as_brr=%s' % (as_brr) + '&%s'
              % (query))
            f = urllib2.urlopen(url)
            content = f.read()
            results = simplejson.loads(content)
            print "google_books_first_search " + str(results['responseStatus'])
            return results['responseData']['results']
        else:
            return
    except (IOError, urllib2.URLError, urllib2.HTTPError, simplejson.JSONDecodeError):
        print "google_books_first_search_is_error"
        return
#
# Google Books API 
# <http://code.google.com/apis/books/docs/js/jsondevguide.html>
#
def google_books_search(q, as_brr):
    try:
        query = urllib.urlencode({'q': q.encode('utf-8') })
        if query != '' or query != 'q=' or query != 'q':
            url = ('https://ajax.googleapis.com/ajax/services/search/books?v=1.0&hl=' + session_locale + '&rsz=6&as_brr=%s' % (as_brr) + '&%s'
              % (query))
            f = urllib2.urlopen(url)
            content = f.read()
            results = simplejson.loads(content)
            print "google_books_search " + str(results['responseStatus'])
            return results['responseData']['results']
        else:
            return
    except (IOError, urllib2.URLError, urllib2.HTTPError, simplejson.JSONDecodeError):
        print "google_books_search_is_error"
        return

#
# Google Images search (openlibrary.org)
# <http://code.google.com/apis/imagesearch/v1/jsondevguide.html>
#
def google_image_ol_search(q):
    try:
        query = urllib.urlencode({'q': q.encode('utf-8') })
        if query != '' or query != 'q=' or query != 'q':
            url = ('https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=1&safe=active&imgtype=face&as_sitesearch=openlibrary.org&%s'
              % (query))
            f = urllib2.urlopen(url)
            content = f.read()
            results = simplejson.loads(content)
            print "google_image_ol_search " + str(results['responseStatus'])
            return results['responseData']['results']
        else:
            return
    except (IOError, urllib2.URLError, urllib2.HTTPError, simplejson.JSONDecodeError):
        print "google_image_ol_search_is_error"
        return
#
# Google Images search
# <http://code.google.com/apis/imagesearch/v1/jsondevguide.html>
#
def google_image_search(q):
    try:
        query = urllib.urlencode({'q': q.encode('utf-8') })
        if query != '' or query != 'q=' or query != 'q':
            url = ('https://ajax.googleapis.com/ajax/services/search/images?v=1.0&imgtype=face&rsz=1&safe=active&%s'
              % (query))
            f = urllib2.urlopen(url)
            content = f.read()
            results = simplejson.loads(content)
            print "google_image_search " + str(results['responseStatus'])
            return results['responseData']['results']
        else:
            return
    except (IOError, urllib2.URLError, urllib2.HTTPError, simplejson.JSONDecodeError):
        print "google_image_search_is_error"
        return

#
# The Zeitgeist Query
# <http://zeitgeist-project.com/development/documentation/>
#
def zeitgeist_latest():
    try:
        zeitgeist = client.ZeitgeistClient()
    except RuntimeError:
        import sys
        sys.exit(1)
    mainloop = gobject.MainLoop()
    def on_events_received(events):
        events = [datamodel.Event(event) for event in events]
        for event in events:
            global subject
            for subject in event.get_subjects():
                subject = subject.text or subject.uri
        mainloop.quit()
    zeitgeist.find_events_for_templates(
        [datamodel.Event.new_for_values(
            subject_interpretation=datamodel.Interpretation)],
        on_events_received,
        result_type=datamodel.ResultType.MostRecentSubjects,
        num_events=1)
    mainloop.run()
    return subject