~markjtully/ubuntu-app-review-board/unity-scopes-music-extras-precise

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

import sys, shutil
import urllib
import os, sqlite3
from gi.repository import GLib, GObject, 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

import os, hashlib, unicodedata

# An arbitrary maximum number of results the scope will return
# It's difficult to navigate more than 25 results in the lens interface
# and if the desired result isn't in the top 25, the search probably
# isn't specific enough
MAX = 100

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

# Categories (as per the music lens)
SONGS = 0
ALBUMS = 1
PURCHASE = 2
MUSIC = 3

class Daemon:

	def __init__ (self):
		# The path for the Lens *must* also match the one in our .scope file
		self.scope = Unity.Scope.new ("/net/launchpad/scope/music/guayadeque")
		
		# Listen for changes and requests
		self.scope.search_in_global = False
		self.scope.connect ("search-changed",  self.on_search_changed)
		self.scope.connect ("filters-changed", self.on_filters_changed)
		self.scope.connect ("activate-uri",    self.activate_uri)
		self.scope.connect ("notify::active",  self.on_lens_active)
		self.scope.export ()
			
	def getMusicFromGuayadeque(self):
		tracks = []

		# Copy guayadeque's database to a backup so we can run searches on that rather than the main database
		guayadeque_directory = os.getenv("HOME") + "/.guayadeque/Collections"
		for collection in os.listdir(guayadeque_directory):
			collection_tracks = []
			guayadeque_dbFile = guayadeque_directory + "/" + collection + "/guayadeque.db"

			if not os.path.exists(guayadeque_dbFile):
				continue

			guayadeque_backupfile = guayadeque_directory + "/" + collection + "/guayadeque-scope-backup.db"
		
			shutil.copy2(guayadeque_dbFile, guayadeque_backupfile)
		
			# Grab all the data we need from the backup
			conn = sqlite3.connect(guayadeque_backupfile)
			c = conn.cursor()
			# Go through the safe and grab track names, their uris, the artist name, the album title and the track's mimetypes
			# We'll have to call them all mp3s as the mimetype isn't explicitly in the database, but as long as it's an audio mimetype, it shouldn't matter
			rows = c.execute('''SELECT songs.song_name, songs.song_path, songs.song_filename, songs.song_artist, songs.song_album, "taglib/mp3", songs.song_albumartist, covers.cover_path, songs.song_year, songs.song_genre
							FROM songs, covers
							WHERE songs.song_coverid = covers.cover_id
							ORDER BY song_number''')
			collection_tracks = c.fetchall()
			c.close()
			for track in collection_tracks:
				tracks.append(track)
		self.tracks = tracks
		print "Updated tracks from Guayadeque database"

	def getAlbumArt(self, track):
		if not track[7] is None:
			return track[7]

		# If that fails, thumbnail any embedded album art and use that
		hashname = unicodedata.normalize("NFKD", unicode(track[5])) + "\t" + unicodedata.normalize("NFKD", unicode(track[3]))
		file_hash = hashlib.md5(hashname).hexdigest()
		tb_filename = os.path.join(os.path.expanduser("~/.cache/media-art"), ("album-" + file_hash)) + ".jpg"
		if os.path.exists(tb_filename):
			return tb_filename
		else:
			try:
				from mutagen import File
				audio = File(track[1])
				if audio.has_key("APIC:"):
					artwork = audio.tags["APIC:"].data
					if not os.path.exists(os.path.expanduser("~/.cache/media-art")):
						os.makedirs(os.path.expanduser("~/.cache/media-art"))
					with open(tb_filename, "wb") as img:
						img.write(artwork)
					return tb_filename
				else:
					return "audio-x-generic"
			except:
				# Otherwise, return a generic audio icon
				return "audio-x-generic"

	def genres(self, selectedgenres):
		genrelist = (
			("blues", "blues"),
			("classic", "classic"),
			("classic", "classical"),
			("country", "country"),
			("disco", "disco"),
			("funk", "funk"),
			("rock", "rock"),
			("rock", "heavy"),
			("rock", "hard"),
			("metal", "metal"),
			("metal", "heavy"),
			("hip-hop", "hip-hop"),
			("house", "house"),
			("house", "chillout"),
			("house", "minimal"),
			("house", "hard"),
			("house", "electronic"),
			("new-wave", "new-wave"),
			("r-and-b", "r-and-b"),
			("punk", "punk"),
			("punk", "punk rock"),
			("punk", "hard"),
			("punk", "heavy"),
			("jazz", "jazz"),
			("pop", "pop"),
			("reggae", "reggae"),
			("soul", "soul"),
			("soul", "gospel"),
			("techno", "techno"),
			("techno", "trance"),
			("techno", "dance"),
			("techno", "chillout"),
			("trance", "electronic"),
			("trance", "electronica"),
			("other", "other"),
			("other", "african"),
			("other", "alternative"),
			("other", "ambient"),
			("other", "asian"),
			("other", "brazilian"),
			("other", "folk"),
			("other", "traditional"),
				)
		genrenames = []
		for selectedgenre in selectedgenres:
			for genre in genrelist:
				if genre[0] == selectedgenre:
					genrenames.append(genre[1])
		return genrenames

	def on_filters_changed(self, *_):
		self.scope.queue_search_changed(Unity.SearchType.DEFAULT)

	def on_lens_active(self, *_):
		if self.scope.props.active:
			self.scope.queue_search_changed(Unity.SearchType.DEFAULT)

	def on_search_changed (self, scope, search=None, search_type=0, cancellable=None):
		if hasattr(search, "props"):
			search_string = search.props.search_string
		else:
			search_string = ""

		if search_type == Unity.SearchType.DEFAULT:
			results = scope.props.results_model
			is_global = False
		else:
			results = scope.props.global_results_model
			is_global = True
		
		print "Search changed to: '%s'" % search_string
		self.update_results_model (search_string, results, is_global)
		if hasattr(search, "finished"):
			search.finished()
		
	def update_results_model (self, search, model, is_global=False):
		self.getMusicFromGuayadeque()
		# Available filters are: decade & genre
		f = self.scope.get_filter("decade")
		firstdecadefilter = -1
		lastdecadefilter = 3000
		o = None
		p = None
		if f != None:
			o = f.get_first_active()
			p = f.get_last_active()
		if o != None:
			firstdecadefilter = int(o.props.id)
		if p != None:
			lastdecadefilter = int(p.props.id) + 9

		f = self.scope.get_filter("genre")
		activegenre = []
		if f != None:
			for option in f.options:
				if option.props.active:
					activegenre.append(option.props.id)
		activegenre = self.genres(activegenre)

		# For a Global search, use the Music category for results
		# For a music lens search, use the Songs and Albums categories
		if is_global:
			songgroup = MUSIC
			albumgroup = MUSIC
		else:
			songgroup = SONGS
			albumgroup = ALBUMS

		search = u"" if search is None else search
		self.i = 0
		albums = []
		model.clear ()

		for track in self.tracks:
			title     = u"" if track[0] is None else unicode(track[0])
			uri       = u"" if track[2] is None else unicode(track[1]) + unicode(track[2])
			artist    = u"" if track[3] is None else unicode(track[3])
			album     = u"" if track[4] is None else unicode(track[4])
			mimetype  = u"" if track[5] is None else unicode(track[5])
			albumartist  = u"" if track[6] is None else unicode(track[6])
			itemtype  = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Audio"
			trackname = title + " - " + album + " - " + artist + " - " + albumartist
			if not trackname.lower().find(unicode(search.lower(), "utf-8")) == -1:
				if self.i < MAX:
					albumart = self.getAlbumArt(track)
					albumuri = "album://" + albumartist + "/" + album
					
					# If the album is outside the decades filtered, exclude.
					decade = True
					if int(track[8]) <= int(firstdecadefilter) or int(track[8]) >= int(lastdecadefilter):
						decade = False

					# If the genre is a selected genre, include
					genre = True
					if activegenre:
						if not track[9].lower() in activegenre:
							genre = False

					include = False
					if genre:
						if decade:
							include = True

					# If the result is included, then add it to the model
					if include == True:
						model.append (uri,				# uri
								albumart,				# string formatted GIcon
								songgroup,					# numeric group id
								mimetype,				# mimetype
								title,					# display name
								artist + "\n" + album,	# comment
								uri)					# dnduri
					
						if album not in albums:
							model.append (albumuri,		# uri
								albumart,				# string formatted GIcon
								albumgroup,					# numeric group id
								mimetype,				# mimetype
								album,					# display name
								artist + "\n" + album,	# comment
								albumuri)				# dnduri
							if album != None:
								albums.append(album)
					
						# Increment the number of results which have displayed, so we know when to stop showing more
						self.i = self.i + 1
			
	def activate_uri(self, scope, uri):
		import subprocess
		albumtracks = []
		albumtracks.append("guayadeque")
		# If uri starts with album:// then we need to play al the songs on it
		if uri.startswith("album://"):
			for track in self.tracks:
				album = "album://" + unicode(track[6]) + "/" + unicode(track[4])
				if not album.find(uri) == -1:
					albumtrack = unicode(urllib.unquote(str(track[1]) + str(track[2])),"utf-8")
					albumtracks.append(albumtrack)
			subprocess.Popen(albumtracks)
		else:
			albumtracks.append(unicode(uri,"utf-8"))
			subprocess.Popen(albumtracks)
		return Unity.ActivationResponse (handled = Unity.HandledType.HIDE_DASH, goto_uri = '')

if __name__ == "__main__":
	# NOTE: If we used the normal 'dbus' module for Python we'll get
	#       slightly odd results because it uses a default connection
	#       to the session bus that is different from the default connection
	#       GDBus (hence libunity) will use. Meaning that the daemon name
	#       will be owned by a connection different from the one all our
	#       Dee + Unity magic is working on...
	#       Still waiting for nice GDBus bindings to land:
	#                        http://www.piware.de/2011/01/na-zdravi-pygi/
	
	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()