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