~markjtully/+junk/rhythmbox-scope-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
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
#! /usr/bin/python

import sys
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

from datetime import date
from urllib2 import urlopen
import dbus, webbrowser
import os, urlparse

MAX = 100

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

# Categories (as per the music lens)
SONGS = 0
ALBUMS = 1

class Daemon:

	def __init__ (self):
		# The path for the Lens *must* also match the one in our .lens file
		self.scope = Unity.Scope.new ("/net/launchpad/scope/music/rhythmbox")
		
		# 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 ("activate-uri", self.activate_uri)
		self.scope.export ()

	def getMusicFromRhythmbox(self):
		import os.path
		import xml.etree.cElementTree as ElementTree
		
		rhythmbox_dbFile = os.getenv("HOME") + "/.local/share/rhythmbox/rhythmdb.xml"
		
		artdir = os.getenv("HOME") + "/.cache/rhythmbox/covers"
		keys = set(("title", "artist", "album", "track-number", "location", "mimetype", "album-artist", "genre", "date", "track-number"))
		tracks = []
		strmap = {}

		if not os.path.exists(rhythmbox_dbFile):
			self.tracks = tracks
			return tracks

		# Parse with iterparse; we get the elements when
		# they are finished, and can remove them directly after use.

		for event, entry in ElementTree.iterparse(rhythmbox_dbFile):
			if not (entry.tag == ("entry") and entry.get("type") == "song"):
				continue

			info = {}
			for child in entry.getchildren():
				if child.tag in keys:
					tag = self._lookup_string(child.tag, strmap)
					text = self._lookup_string(child.text, strmap)
					info[tag] = text

			track = {}
			track[0] = info['title']
			track[1] = info['location']
			track[2] = info['artist']
			track[3] = info['album']
			track[4] = "audio/mp3"
			if info.has_key('album-artist'):
				track[5] = info['album-artist']
			else:
				track[5] = info['artist']
			if info.has_key('genre'):
				track[6] = info['genre']
			else:
				track[6] = ""
			if info.has_key('date'):
				track[7] = int(info["date"])/365
			else:
				track[7] = 0
			if info.has_key('track-number'):
				track[8] = info['track-number']
			else:
				track[8] = 0
			tracks.append(track)
			entry.clear()
			
		print "Updated tracks from Rhythmbox database"
		self.tracks = tracks
		return tracks
	
	def getAlbumArt(self, track):
		# First, try "/.cache/rhythmbox/covers"
		artdir = os.getenv("HOME") + "/.cache/rhythmbox/covers"
		if os.path.exists(artdir + track[2] + " - " + track[3]):
			return "%s/%s - %s.jpg" % (artdir, track[2], track[3])

		# If that didn't work, try "/.cache/media-art"
		artdir = os.getenv("HOME") + "/.cache/media-art"
		import unicodedata
		import hashlib
		
		hashname = unicode(track[5])
		hashname2 = unicode(track[3])
		hashname = unicodedata.normalize("NFKD", hashname)
		hashname2 = unicodedata.normalize("NFKD", hashname2)
		md5album = hashlib.md5()
		md5album2 = hashlib.md5()
		try:
			md5album.update(hashname)
			md5album2.update(hashname2)
			value = md5album.hexdigest() + "-" + md5album2.hexdigest()
		except:
			value = ""
		
		if os.path.exists(artdir + "/album-" + value + ".jpeg"):
			return "%s/album-%s.jpeg" % (artdir, value)
				
		# 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 _lookup_string(self, string, strmap):
		"""Look up @string in the string map,
		and return the copy in the map.

		If not found, update the map with the string.
		"""
		string = string or ""
		try:
			return strmap[string]
		except KeyError:
			strmap[string] = string
			return string

	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
		else:
			results = scope.props.global_results_model
		
		print "Search changed to: '%s'" % search_string
		self.update_results_model (search_string, results)
		if hasattr(search, "finished"):
			search.finished()

	def update_results_model (self, search, model):
		self.getMusicFromRhythmbox()
		# 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 = []
		for option in f.options:
			if option.props.active:
				print option.props.id
				activegenre.append(option.props.id)
		activegenre = self.genres(activegenre)

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

		for track in self.tracks:
			title     = "" if track[0] is None else track[0]
			uri       = "" if track[1] is None else track[1]
			artist    = "" if track[2] is None else track[2]
			album     = "" if track[3] is None else track[3]
			mimetype  = "" if track[4] is None else track[4]
			albumartist = "" if track[5] is None else track[5]
			itemtype  = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Audio"
			trackname = title + " - " + album + " - " + artist
			if not trackname.lower().find(search.lower()) == -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[7]) <= int(firstdecadefilter) or int(track[7]) >= int(lastdecadefilter):
						decade = False

					# If the genre is a selected genre, include
					genre = True
					if activegenre:
						if not track[6].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
								SONGS,					# 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
								ALBUMS,					# numeric group id
								mimetype,				# mimetype
								album,					# display name
								artist + "\n" + album,	# comment
								uri)					# 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
		print uri
		albumtracks = []
		
		albumtracks.append("rhythmbox-client")
		albumtracks.append("--enqueue")
		
		# If uri starts with album:// then we need to play all the songs on it
		if uri.startswith("album://"):
			trackdetails = []
			for track in self.tracks:
				trackdetail = []
				album = "album://" + track[5] + "/" + track[3]
				if not album.find(uri) == -1:
					albumtrack = track[1]
					trackdetail.append(albumtrack)
					trackdetail.append(track[8])
					trackdetails.append(trackdetail)

			for track in trackdetails:
				print track
				if int(track[1]) == 1:
					albumtracks.append(track[0])
			
			subprocess.Popen(albumtracks)
			
		else:
			albumtracks.append(uri)
			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()