~davidc3/onehundredscopes/cities

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
#! /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
from gi.repository import GLib, GObject, Gio
from gi.repository import Dee
_m = dir(Dee.SequenceModel)
from gi.repository import Unity
import socket, urllib, urllib2, simplejson
import locale
import os

socket.setdefaulttimeout(1)
BUS_NAME = "net.launchpad.scope.information.cities"


if not os.path.isdir('/tmp/unity-scope-cities'):
	os.makedirs('/tmp/unity-scope-cities')

locale.setlocale(locale.LC_NUMERIC, '')
global session_locale
#session_locale = locale.getlocale(locale.LC_MESSAGES)[0].split("_")[0]
session_locale = locale.getlocale(locale.LC_NUMERIC)[0].split("_")[1]

class Daemon:
	def __init__ (self):
		self.scope = Unity.Scope.new ("/net/launchpad/scope/information/cities")
		self.scope.search_in_global = True
		self.scope.connect ("notify::active-search", self.on_search_changed)
		self.scope.connect ("notify::active-global-search", self.on_search_changed)
		self.scope.connect ("filters-changed", self.on_search_changed);
		self.scope.export()

	def get_search_string (self):
		search = self.scope.props.active_global_search
		if search is None:
			search = self.scope.props.active_search
		return search.props.search_string if search else None

	def on_search_changed (self, scope, param_spec=None):
			search = self.get_search_string()
			print "Search changed to: '%s'" % search
			results_global = self.scope.props.global_results_model
			results_global.clear()
			self.update_results_model (search, results_global)
			results_global.flush_revision_queue ()

	def update_results_model(self, search, model):
		if search and not search[0].isdigit() and not search.lower().find(" in ")  > -1:
			self.timezone(search, model)
			self.weather(search, model)
			self.scope.props.active_global_search.emit("finished")
			
	#
	# Time Zone search
	# <http://www.worldweatheronline.com/time-zone-api.aspx>
	#
	def timezone_search(self, q):
		try:
		    query = urllib.urlencode({'q': q })
		    if query != '' or query != 'q=' or query != 'q':
		        url = ('http://www.worldweatheronline.com/feed/tz.ashx?key=7e70df21c3150016112010&format=json&%s'
		          % (query))
		        print url
		        f = urllib2.urlopen(url)
		        content = f.read()
		        results = simplejson.loads(content)
		        if results['data']:
		        	return results['data']
		        else:
		        	return
		    else:
		        return
		except (IOError, urllib2.URLError, urllib2.HTTPError, simplejson.JSONDecodeError):
		    print "timezone_search_is_error"
		    return

	#
	# Weather search
	# <http://www.worldweatheronline.com/time-zone-api.aspx>
	#
	def weather_search(self, q):
		try:
		    query = urllib.urlencode({'q': q })
		    if query != '' or query != 'q=' or query != 'q':
		        url = ('http://free.worldweatheronline.com/feed/weather.ashx?key=7e70df21c3150016112010&format=json&%s'
		          % (query))
		        print url
		        f = urllib2.urlopen(url)
		        content = f.read()
		        results = simplejson.loads(content)
		        if results['data']:
		        	return results['data']
		        else:
		        	return
		    else:
		        return
		except (IOError, urllib2.URLError, urllib2.HTTPError, simplejson.JSONDecodeError):
		    print "weather_search_is_error"
		    return

	# Google Images search
	# <http://code.google.com/apis/imagesearch/v1/jsondevguide.html>
	#
	def google_image_search(self, q):
		import urllib, urllib2, simplejson
		try:
			q = q.replace(" ", "+")
			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&%s'
				  % (query))
				print url
				f = urllib2.urlopen(url)
				content = f.read()
				results = simplejson.loads(content)
				print "google_image_search " + str(results['responseStatus'])
				if results['responseStatus'] == 200:
					return results['responseData']['results']
				else:
					pass
		except (IOError, urllib2.URLError, urllib2.HTTPError, simplejson.JSONDecodeError):
			print "google_image_search_is_error"

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

	def wikipedia(self, search, model,icon):
		for i in self.wikipedia_search(search):
			uri = "http://" + session_locale + ".wikipedia.org/wiki/"+ i
			title = "Wikipedia"
			if (uri.startswith("http://")):
				model.append(uri, icon, 0, "text/html", title, '', '')

	def timezone(self, search, model):
		if search:
			data_timezone = self.timezone_search("%s" % search)
			if data_timezone:
				title = ''
				comment = ''
				try:
					for i in data_timezone['request']:
						title = i['query']
				except (KeyError):
					pass
				try:
					for i in data_timezone['time_zone']:
						comment = i['localtime']
						print comment
						comment = comment.split(' ')[1]
						icon = 'http://cdn4.iconfinder.com/data/icons/Mobile-Icons/128/04_maps.png'
						model.append('http://maps.google.com/maps?q=%s' % title, icon, 0, "text/html",title, comment, '')
						
						
						hours = int(comment.split(':')[0])
						minutes = int(comment.split(':')[1])
						from PIL import Image
						clock_back = Image.open("/usr/share/unity/lenses/utilities/clock_empty.png")
						clock_hours = Image.open("/usr/share/unity/lenses/utilities/clock_hours.png")
						clock_minutes = Image.open("/usr/share/unity/lenses/utilities/clock_minutes.png")
						
						clock_hours = clock_hours.rotate((hours*-30)-(minutes*1/2))
						clock_minutes = clock_minutes.rotate(minutes*-6)
						i
						clock_back.paste(clock_hours, (0, 0), clock_hours)
						clock_back.paste(clock_minutes, (0, 0), clock_minutes)
						clock_back.save('/tmp/unity-scope-cities/%s.png' % comment)
						
						model.append('', '/tmp/unity-scope-cities/%s.png' % comment, 0, "text/html", comment, '', '')
						
						
						
				except (KeyError):
					pass

	def weather(self, search, model):
		icon = ''
		if search:
			data_weather = self.weather_search("%s" % search)
			if data_weather:
				title = ''
				comment = ''
				try:
					for i in data_weather['current_condition']:
						temp_C = i['temp_C']
						degree_C = u"\u00B0C"
						temp_F = i['temp_F']
						degree_F = u"\u00B0F"
						temp_information = "%s%s | %s%s" % (temp_C, degree_C, temp_F, degree_F)
						wind_direction = i['winddir16Point']
						if wind_direction in ['NNW', 'WNW']:
							wind_direction = 'NW'
						if wind_direction in ['WSW', 'SSW']:
							wind_direction = 'SW'
						if wind_direction in ['NNE', 'ENE']:
							wind_direction = 'NE'
						if wind_direction in ['SSE', 'ESE']:
							wind_direction = 'SE'
						 
						icon_wind = "/usr/share/unity/lenses/utilities/compass_%s.svg" % wind_direction
						wind_speed_Kmph = i['windspeedKmph']
						wind_speed_Miles = i['windspeedMiles']
						wind_information = "%s km/h | %s mph " % (wind_speed_Kmph, wind_speed_Miles)
						for j in i['weatherDesc']:
							comment = j['value']
						for k in i['weatherIconUrl']:
							icon_temp = k['value']
				except (KeyError):
					print "KeyError"
				try:
					for i in data_weather['request']:
						city = i['query']
						title_temp = temp_information
						title_wind = wind_information

						model.append('', icon_temp, 0, "text/html", title_temp, comment, '')
						model.append('', icon_wind, 0, "text/html", title_wind, comment, '')
#						for image in self.google_image_search("%s" % i['query']):
#							icon = image['tbUrl']
#							self.wikipedia(city, model, icon)
				except (KeyError):
					pass



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