source: trunk/StreamVision/StreamVision.py@ 638

Last change on this file since 638 was 638, checked in by Nicholas Riley, 13 years ago

StreamVision.py: iTunes 10.1.2 AirPlay fix for iTunes Store layout too.

File size: 13.1 KB
RevLine 
[188]1#!/usr/bin/pythonw
2# -*- coding: utf-8 -*-
3
[232]4from appscript import app, k, its, CommandError
[300]5from AppKit import NSApplication, NSApplicationDefined, NSBeep, NSSystemDefined, NSURL, NSWorkspace
[486]6from Foundation import NSDistributedNotificationCenter, NSSearchPathForDirectoriesInDomains, NSCachesDirectory, NSUserDomainMask
[188]7from PyObjCTools import AppHelper
8from Carbon.CarbonEvt import RegisterEventHotKey, GetApplicationEventTarget
[232]9from Carbon.Events import cmdKey, shiftKey, controlKey
[486]10import httplib2
11import os
[188]12import struct
13import scrape
[211]14import HotKey
[188]15
16GROWL_APP_NAME = 'StreamVision'
17NOTIFICATION_TRACK_INFO = 'iTunes Track Info'
18NOTIFICATIONS_ALL = [NOTIFICATION_TRACK_INFO]
19
20kEventHotKeyPressedSubtype = 6
21kEventHotKeyReleasedSubtype = 9
22
[300]23kHIDUsage_Csmr_ScanNextTrack = 0xB5
24kHIDUsage_Csmr_ScanPreviousTrack = 0xB6
25kHIDUsage_Csmr_PlayOrPause = 0xCD
26
[340]27def growlRegister():
28 global growl
29 growl = app(id='com.Growl.GrowlHelperApp')
[188]30
[340]31 growl.register(
32 as_application=GROWL_APP_NAME,
33 all_notifications=NOTIFICATIONS_ALL,
34 default_notifications=NOTIFICATIONS_ALL,
35 icon_of_application='iTunes.app')
36 # if we leave off the .app, we can get Classic iTunes's icon
[188]37
38def growlNotify(title, description, **kw):
[340]39 try:
40 growl.notify(
41 with_name=NOTIFICATION_TRACK_INFO,
42 title=title,
43 description=description,
44 application_name=GROWL_APP_NAME,
45 **kw)
46 except CommandError:
47 growlRegister()
48 growlNotify(title, description, **kw)
[195]49
[188]50def radioParadiseURL():
[315]51 # XXX better to use http://www2.radioparadise.com/playlist.xml ?
[188]52 session = scrape.Session()
[195]53 session.go('http://www2.radioparadise.com/nowplay_b.php')
54 return session.region.firsttag('a')['href']
[188]55
[194]56def cleanStreamTitle(title):
[316]57 if title == k.missing_value:
[194]58 return ''
59 title = title.split(' [')[0] # XXX move to description
[341]60 try: # incorrectly encoded?
61 title = title.encode('iso-8859-1').decode('utf-8')
[459]62 except (UnicodeDecodeError, UnicodeEncodeError):
[341]63 pass
[194]64 title = title.replace('`', u'’')
[323]65 return title
[195]66
[194]67def cleanStreamTrackName(name):
[188]68 name = name.split('. ')[0]
69 name = name.split(': ')[0]
[190]70 name = name.split(' - ')
71 if len(name) > 1:
72 name = ' - '.join(name[:-1])
73 else:
74 name = name[0]
[188]75 return name
[195]76
[199]77def iTunesApp(): return app(id='com.apple.iTunes')
78def XTensionApp(): return app(creator='SHEx')
[414]79def AmuaApp(): return app('Amua.app')
[188]80
[199]81HAVE_XTENSION = False
82try:
83 XTensionApp()
84 HAVE_XTENSION = True
85except:
86 pass
87
[414]88HAVE_AMUA = False
89try:
90 AmuaApp()
91 HAVE_AMUA = True
92except:
93 pass
94
[324]95needsStereoPowerOn = HAVE_XTENSION
96
[580]97def mayUseStereo():
98 if not HAVE_XTENSION:
99 return False
100 systemEvents = app(id='com.apple.systemEvents')
[632]101 iTunesWindow = systemEvents.application_processes[u'iTunes'].windows[u'iTunes']
102 try:
[637]103 remote_speakers = iTunesWindow.buttons[its.attributes['AXDescription'].value.endswith(u'AirPlay')].title()
[632]104 except CommandError:
105 # with iTunes Store visible, the query fails with errAENoSuchObject
106 for button in iTunesWindow.buttons():
107 try:
[638]108 if button.attributes['AXDescription'].value().endswith('AirPlay'):
[632]109 remote_speakers = [button.title()]
[633]110 break
[632]111 except CommandError:
112 pass
[638]113 else:
114 return False # XXX shouldn't get here
115 return remote_speakers and remote_speakers[0] not in (None, k.missing_value)
[580]116
117def turnStereoOn():
118 global needsStereoPowerOn
119 if not mayUseStereo():
[631]120 if HAVE_XTENSION and XTensionApp().status('Stereo'):
121 XTensionApp().turnoff('Stereo')
[580]122 return
123 if not XTensionApp().status('Stereo'):
124 XTensionApp().turnon('Stereo')
125 needsStereoPowerOn = False
126
127def turnStereoOff():
128 global needsStereoPowerOn
129 if not mayUseStereo():
130 return
131 if not needsStereoPowerOn and XTensionApp().status('Stereo'):
132 XTensionApp().turnoff('Stereo')
133 needsStereoPowerOn = True
134
[414]135def amuaPlaying():
136 if not HAVE_AMUA:
137 return False
138 return AmuaApp().is_playing()
139
[486]140class OneFileCache(object):
141 __slots__ = ('key', 'cache')
142
143 def __init__(self, cache):
144 if not os.path.exists(cache):
145 os.makedirs(cache)
146 self.cache = os.path.join(cache, 'file')
147 self.key = None
148
149 def get(self, key):
150 if key == self.key:
151 return file(self.cache, 'r').read()
152
153 def set(self, key, value):
154 self.key = key
155 file(self.cache, 'w').write(value)
156
157 def delete(self, key):
158 if key == self.key:
159 self.key = None
160 os.remove(cache)
161
[188]162class StreamVision(NSApplication):
163
164 hotKeyActions = {}
165 hotKeys = []
166
[414]167 def displayTrackInfo(self, playerInfo=None):
[188]168 iTunes = iTunesApp()
[195]169
[497]170 try:
171 trackClass = iTunes.current_track.class_()
172 except CommandError:
173 trackClass = k.property
174
[211]175 trackName = ''
[315]176 if trackClass != k.property:
177 trackName = iTunes.current_track.name()
[211]178
[315]179 if iTunes.player_state() != k.playing:
[211]180 growlNotify('iTunes is not playing.', trackName)
[580]181 turnStereoOff()
[211]182 return
[580]183 turnStereoOn()
[211]184 if trackClass == k.URL_track:
[414]185 if amuaPlaying():
186 if playerInfo is None: # Amua displays it itself
187 AmuaApp().display_song_information()
188 return
[486]189 url = iTunes.current_stream_URL()
190 kw = {}
191 if url != k.missing_value and url.endswith('.jpg'):
192 response, content = self.http.request(url)
193 if response['content-type'].startswith('image/'):
194 file(self.imagePath, 'w').write(content)
195 kw['image_from_location'] = self.imagePath
[315]196 growlNotify(cleanStreamTitle(iTunes.current_stream_title()),
[486]197 cleanStreamTrackName(trackName), **kw)
[211]198 return
[315]199 if trackClass == k.property:
[324]200 growlNotify('iTunes is playing.', '')
201 return
[211]202 kw = {}
203 # XXX iTunes doesn't let you get artwork for shared tracks
204 if trackClass != k.shared_track:
[315]205 artwork = iTunes.current_track.artworks()
[211]206 if artwork:
[487]207 try:
[636]208 kw['pictImage'] = artwork[0].data_()
[487]209 except CommandError:
210 pass
[211]211 growlNotify(trackName + ' ' +
[323]212 u'★' * (iTunes.current_track.rating() / 20),
213 iTunes.current_track.album() + '\n' +
[315]214 iTunes.current_track.artist(),
[211]215 **kw)
216
[188]217 def goToSite(self):
218 iTunes = iTunesApp()
[315]219 if iTunes.player_state() == k.playing:
[414]220 if amuaPlaying():
221 AmuaApp().display_album_details()
222 return
[315]223 url = iTunes.current_stream_URL()
[316]224 if url != k.missing_value:
[252]225 if 'radioparadise.com' in url and 'review' not in url:
[188]226 url = radioParadiseURL()
227 NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_(url))
228 return
229 NSBeep()
[195]230
[188]231 def registerHotKey(self, func, keyCode, mods=0):
232 hotKeyRef = RegisterEventHotKey(keyCode, mods, (0, 0),
233 GetApplicationEventTarget(), 0)
234 self.hotKeys.append(hotKeyRef)
[211]235 self.hotKeyActions[HotKey.HotKeyAddress(hotKeyRef)] = func
[235]236 return hotKeyRef
[188]237
[235]238 def unregisterHotKey(self, hotKeyRef):
239 self.hotKeys.remove(hotKeyRef)
240 del self.hotKeyActions[HotKey.HotKeyAddress(hotKeyRef)]
241 hotKeyRef.UnregisterEventHotKey()
242
[199]243 def incrementRatingBy(self, increment):
244 iTunes = iTunesApp()
[414]245 if amuaPlaying():
[415]246 if increment < 0:
[414]247 AmuaApp().ban_song()
[458]248 growlNotify('Banned song.', '', icon_of_application='Amua.app')
[414]249 else:
250 AmuaApp().love_song()
[458]251 growlNotify('Loved song.', '', icon_of_application='Amua.app')
[414]252 return
[315]253 rating = iTunes.current_track.rating()
[199]254 rating += increment
255 if rating < 0:
256 rating = 0
257 NSBeep()
258 elif rating > 100:
259 rating = 100
260 NSBeep()
261 iTunes.current_track.rating.set(rating)
262
[300]263 def playPause(self, useStereo=True):
[324]264 global needsStereoPowerOn
265
[199]266 iTunes = iTunesApp()
[315]267 was_playing = (iTunes.player_state() == k.playing)
[324]268 if not useStereo:
269 needsStereoPowerOn = False
[414]270 if was_playing and amuaPlaying():
271 AmuaApp().stop()
272 else:
273 iTunes.playpause()
[315]274 if not was_playing and iTunes.player_state() == k.stopped:
[234]275 # most likely, we're focused on the iPod, so playing does nothing
[315]276 iTunes.browser_windows[1].view.set(iTunes.user_playlists[its.name=='Stations'][1]())
[234]277 iTunes.play()
[580]278 if not useStereo:
279 return
280 if iTunes.player_state() == k.playing:
281 turnStereoOn()
282 else:
283 turnStereoOff()
[235]284
[301]285 def playPauseFront(self):
286 systemEvents = app(id='com.apple.systemEvents')
[340]287 frontName = systemEvents.processes[its.frontmost == True][1].name()
[301]288 if frontName == 'RealPlayer':
289 realPlayer = app(id='com.RealNetworks.RealPlayer')
[315]290 if len(realPlayer.players()) > 0:
291 if realPlayer.players[1].state() == k.playing:
292 realPlayer.pause()
293 else:
294 realPlayer.play()
295 return
[301]296 elif frontName == 'VLC':
297 app(id='org.videolan.vlc').play() # equivalent to playpause
298 else:
[302]299 self.playPause(useStereo=False)
[301]300
[414]301 def nextTrack(self):
302 if amuaPlaying():
303 AmuaApp().skip_song()
304 return
305 iTunesApp().next_track()
306
[235]307 def registerZoomWindowHotKey(self):
308 self.zoomWindowHotKey = self.registerHotKey(self.zoomWindow, 42, cmdKey | controlKey) # cmd-ctrl-\
309
310 def unregisterZoomWindowHotKey(self):
311 self.unregisterHotKey(self.zoomWindowHotKey)
312 self.zoomWindowHotKey = None
313
[232]314 def zoomWindow(self):
[313]315 # XXX detect if "enable access for assistive devices" needs to be enabled
[232]316 systemEvents = app(id='com.apple.systemEvents')
[340]317 frontName = systemEvents.processes[its.frontmost == True][1].name()
[233]318 if frontName == 'iTunes':
[232]319 systemEvents.processes['iTunes'].menu_bars[1]. \
320 menu_bar_items['Window'].menus.menu_items['Zoom'].click()
321 return
[631]322 elif frontName in ('X11', 'XQuartz', 'Emacs'): # preserve C-M-\
[235]323 self.unregisterZoomWindowHotKey()
324 systemEvents.key_code(42, using=[k.command_down, k.control_down])
325 self.registerZoomWindowHotKey()
326 return
[340]327 frontPID = systemEvents.processes[its.frontmost == True][1].unix_id()
[232]328 try:
[339]329 zoomed = app(pid=frontPID).windows[1].zoomed
[232]330 zoomed.set(not zoomed())
[235]331 except (CommandError, RuntimeError):
[313]332 systemEvents.processes[frontName].windows \
333 [its.subrole == 'AXStandardWindow'].windows[1]. \
334 buttons[its.subrole == 'AXZoomButton'].buttons[1].click()
[199]335
[188]336 def finishLaunching(self):
337 super(StreamVision, self).finishLaunching()
[486]338
339 caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
340 NSUserDomainMask, True)[0]
341 cache = os.path.join(caches, 'StreamVision')
342 self.http = httplib2.Http(OneFileCache(cache), 5)
343 self.imagePath = os.path.join(cache, 'image')
344
[188]345 self.registerHotKey(self.displayTrackInfo, 100) # F8
346 self.registerHotKey(self.goToSite, 100, cmdKey) # cmd-F8
[199]347 self.registerHotKey(self.playPause, 101) # F9
[188]348 self.registerHotKey(lambda: iTunesApp().previous_track(), 109) # F10
[414]349 self.registerHotKey(self.nextTrack, 103) # F11
[211]350 self.registerHotKey(lambda: self.incrementRatingBy(-20), 109, shiftKey) # shift-F10
351 self.registerHotKey(lambda: self.incrementRatingBy(20), 103, shiftKey) # shift-F11
[235]352 self.registerZoomWindowHotKey()
[193]353 NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, self.displayTrackInfo, 'com.apple.iTunes.playerInfo', None)
[300]354 try:
[302]355 import HIDRemote
[300]356 HIDRemote.connect()
[302]357 except ImportError:
358 print "failed to import HIDRemote (XXX fix - on Intel)"
[300]359 except OSError, e:
360 print "failed to connect to remote: ", e
[188]361
362 def sendEvent_(self, theEvent):
[300]363 eventType = theEvent.type()
364 if eventType == NSSystemDefined and \
[188]365 theEvent.subtype() == kEventHotKeyPressedSubtype:
366 self.hotKeyActions[theEvent.data1()]()
[300]367 elif eventType == NSApplicationDefined:
368 key = theEvent.data1()
369 if key == kHIDUsage_Csmr_ScanNextTrack:
[415]370 self.nextTrack()
[300]371 elif key == kHIDUsage_Csmr_ScanPreviousTrack:
372 iTunesApp().previous_track()
373 elif key == kHIDUsage_Csmr_PlayOrPause:
[301]374 self.playPauseFront()
[188]375 super(StreamVision, self).sendEvent_(theEvent)
376
377if __name__ == "__main__":
[340]378 growlRegister()
[195]379 AppHelper.runEventLoop()
[339]380 try:
381 HIDRemote.disconnect()
382 except:
383 pass
Note: See TracBrowser for help on using the repository browser.