~mikaelsahlstrom/onehundredscopes/spotify

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
#! /usr/bin/python
# coding=UTF-8

# Copyright (c) 2012 Mikael Sahlström <mick.sahlstrom@gmail.com>

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

# This product uses a SPOTIFY API but is not endorsed, certified or otherwise
# approved in any way by Spotify.
# Spotify is the registered trade mark of the Spotify Group.

import sys, dbus, json
from gi.repository import GLib, GObject, Gio
from gi.repository import Dee

_m = dir(Dee.SequenceModel)

from gi.repository import Unity
from urllib2 import urlopen, URLError, quote
from urllib2 import Request, urlopen, HTTPError

class Daemon:
	def __init__(self):
		self.scope = Unity.Scope.new("/net/launchpad/scope/music/spotify")
		self.scope.search_in_global = False
		self.scope.connect("notify::active-search", self.on_search_changed)
		self.scope.connect("filters-changed", self.on_search_changed)
		self.scope.export()
		self._albumart = {}

	def get_search_string(self):
		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()
		results = self.scope.props.results_model
		results.clear()
		self.scope.freeze_notify()
		self.update_results_model(search, results)
		results.flush_revision_queue()
		GObject.idle_add(self.thaw, scope)

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

	def update_results_model(self, search, model):
		if search is None or search == "":
			return
		
		filters = ""
		
		f = self.scope.get_filter("decade")
		if f.get_first_active() is not None and f.get_last_active() is not None:
			filters = "year:%s-%s+" % (f.get_first_active().props.id, int(f.get_last_active().props.id) + 9)
		f = self.scope.get_filter("genre")
		i = 0
		for option in f.options:
			if option.props.active:
				if option.props.id != "other":
					if i == 0:
						filters = filters + "genre:" + self._genre(option.props.id)
						i = 1
					else:
						filters = filters + "," + self._genre(option.props.id)
		
		search = quote(search)
		search = search.replace("%20", "+")
		
		if len(filters) > 0:
			search = filters + "+" + search
		
		result = self._search_track(search)

		if result is not None and result.get("info").get("num_results") != 0:
			sorted_results = sorted(result.get("tracks"), key=lambda track: float(track.get("popularity")), reverse=True)
			for track, i in zip(sorted_results, range(18)):
				uri = track.get("href")
				icon = self._get_thumb_path(track.get("album").get("href"))
				name = track.get("name")
				artist = dict(track.get("artists")[0]).get("name")
				model.append(uri, icon, 0, "x-scheme-handler/spotify", "%s\n%s" % (name, artist), artist, uri)
				if i % 3 == 0:
					model.flush_revision_queue()
			model.flush_revision_queue()

		result = self._search_album(search)

		if result is not None and result.get("info").get("num_results") != 0:
			sorted_results = sorted(result.get("albums"), key=lambda album: float(album.get("popularity")), reverse=True)
			for album, i in zip(sorted_results, range(18)):
				uri = album.get("href")
				icon = self._get_thumb_path(uri)
				name = album.get("name")
				artist = dict(album.get("artists")[0]).get("name")
				model.append(uri, icon, 1, "x-scheme-handler/spotify", "%s\n%s" % (name, artist), artist, uri)
				if i % 3 == 0:
					model.flush_revision_queue()

		if self.scope.props.active_search:
			self.scope.props.active_search.emit("finished")
		self._albumart = {}

	def _search_artist(self, query, page = 1):
		url = "http://ws.spotify.com/search/%s/artist.json?q=%s" % (page, query)
		result = self._do_request(url)
		if result is None:
			return None
		return json.loads(result)

	def _search_track(self, query, page = 1):
		url = "http://ws.spotify.com/search/%s/track.json?q=%s" % (page, query)
		result = self._do_request(url)
		if result is None:
			return None
		return json.loads(result)

	def _search_album(self, query, page = 1):
		url = "http://ws.spotify.com/search/%s/album.json?q=%s" % (page, query)
		result = self._do_request(url)
		if result is None:
			return None
		return json.loads(result)

	def _do_request(self, url):
		headers = {'User-Agent': 'Unity Scope Spotify'}
		req = Request(url, None, headers)
		try:
			url = urlopen(req)
			return url.read()
		except HTTPError, e:
			print "Connection to Spotify Metadata failed: %s" % (e.code)
			return None
		except:
			return None

	def _get_thumb_path(self, uri):
		if self._albumart.get(uri) is not None:
			return self._albumart.get(uri)
		turi = uri
		try:
			uri = uri.split(':')
			url = urlopen("http://open.spotify.com/%s/%s" % (uri[1], uri[2])).read()
			thumb_start = url.find('<meta property="og:image" content="')
			thumb_end = url.find('" />',thumb_start)
			url = url[thumb_start+35:thumb_end]
			self._albumart[turi] = url
			return url
		except URLError, e:
			print e.code
			if e.code == 503:
				# Some requests are getting 503. Try again.
				return self._get_thumb_path(turi)
			return ""

	def _genre(self, g):
		# Transform the genre filter to corresponding spotify filters.
		if g == "blues":
			return "blues"
		elif g == "country":
			return "country"
		elif g == "disco":
			return "post-disco"
		elif g == "funk":
			return "funk"
		elif g == "rock":
			return "rock"
		elif g == "metal":
			return "metal"
		elif g == "hip-hop":
			return "hip-hop,rap"
		elif g == "house":
			return "house"
		elif g == "new-wave":
			return "new-wave"
		elif g == "r-and-b":
			return "R%26amp%3BB"
		elif g == "punk":
			return "punk"
		elif g == "jazz":
			return "jazz"
		elif g == "pop":
			return "pop"
		elif g == "reggae":
			return "reggae"
		elif g == "soul":
			return "soul"
		elif g == "techno":
			return "techno"
		elif g == "classic":
			return "classical"		
	
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)", ("net.launchpad.scope.music.spotify", 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()