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