Changeset 672


Ignore:
Timestamp:
02/22/14 07:36:35 (11 years ago)
Author:
Nicholas Riley
Message:

StreamVision.py: Use notification userInfo for track information where possible.

Fixes several issues including StreamVision relaunching iTunes endlessly and no display of iTunes Store tracks.

Also (mostly) work around lack of track display when starting iTunes Radio station playback.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/StreamVision/StreamVision.py

    r670 r672  
    157157    return AmuaApp().is_playing()
    158158
     159def notifyTrackInfo(name, album=None, artist=None, rating=0, hasArtwork=False,
     160                    streamTitle=None, streamURL=None, playing=True, onChange=False):
     161    if not playing:
     162        growlNotify('iTunes is not playing.', name)
     163        return
     164    turnStereoOnOrOff()
     165
     166    if streamURL:
     167        if amuaPlaying():
     168            if onChange: # Amua displays it itself
     169                AmuaApp().display_song_information()
     170            return
     171        kw = {}
     172        if streamURL and streamURL.endswith('.jpg'):
     173            try:
     174                response, content = http.request(streamURL)
     175            except Exception, e:
     176                import sys
     177                print >> sys.stderr, 'Request for album art failed:', e
     178            else:
     179                if response['content-type'].startswith('image/'):
     180                    kw['image'] = content
     181        growlNotify(cleanStreamTitle(streamTitle),
     182                    cleanStreamTrackName(name), **kw)
     183        return
     184
     185    if not name:
     186        growlNotify('iTunes is playing.', '')
     187        return
     188
     189    kw = {}
     190    if hasArtwork:
     191        try:
     192            kw['image'] = iTunesApp().current_track.artworks[1].data_().data
     193        except CommandError:
     194            pass
     195
     196    growlNotify(name + '  ' + u'★' * (rating / 20),
     197                (album or '') + '\n' + (artist or ''),
     198                **kw)
     199
    159200class OneFileCache(object):
    160201    __slots__ = ('key', 'cache')
     
    184225    hotKeys = []
    185226
    186     def displayTrackInfo(self, playerInfo=None):
     227    def playerInfoChanged(self, playerInfo):
     228        infoDict = dict(playerInfo.userInfo())
     229        trackName = infoDict.get('Name', '')
     230        playerState = infoDict.get('Player State')
     231        if playerState != 'Playing':
     232            notifyTrackInfo(trackName, playing=False, onChange=True)
     233            return
     234        url = infoDict.get('Stream URL')
     235        if url:
     236            notifyTrackInfo(trackName, streamTitle=infoDict.get('Stream Title'),
     237                            streamURL=url, onChange=True)
     238            return
     239        artworkCount = int(infoDict.get('Artwork Count', 0))
     240        # XXX When starting iTunes Radio station playback, we get 2 notifications,
     241        # neither of which mention the track: the first has the station's artwork,
     242        # the second doesn't.  On the 2nd notification, wait 10 seconds and try again.
     243        # By then, we should have artwork.
     244        if not infoDict.has_key('Total Time') and artworkCount == 0:
     245            self.performSelector_withObject_afterDelay_(self.displayTrackInfo, None, 10)
     246            return
     247        notifyTrackInfo(trackName, infoDict.get('Album'), infoDict.get('Artist'),
     248                        infoDict.get('Rating', 0), artworkCount > 0, onChange=True)
     249
     250    def displayTrackInfo(self):
    187251        iTunes = iTunesApp()
    188252
     
    201265            playerState = None # probably iTunes quit
    202266        if playerState != k.playing:
    203             if playerState != None:
    204                 growlNotify('iTunes is not playing.', trackName)
    205             turnStereoOff()
    206             return
    207         turnStereoOnOrOff()
     267            notifyTrackInfo(trackName, playing=False)
     268            return
    208269        if trackClass == k.URL_track:
    209             if amuaPlaying():
    210                 if playerInfo is None: # Amua displays it itself
    211                     AmuaApp().display_song_information()
    212                 return
    213270            url = iTunes.current_stream_URL()
    214             kw = {}
    215             if url != k.missing_value and url.endswith('.jpg'):
    216                 try:
    217                     response, content = self.http.request(url)
    218                 except Exception, e:
    219                     import sys
    220                     print >> sys.stderr, 'Request for album art failed:', e
    221                 else:
    222                     if response['content-type'].startswith('image/'):
    223                         kw['image'] = content
    224             growlNotify(cleanStreamTitle(iTunes.current_stream_title()),
    225                         cleanStreamTrackName(trackName), **kw)
     271            if url == k.missing_value:
     272                url = None
     273            notifyTrackInfo(trackName, streamTitle=iTunes.current_stream_title(),
     274                            streamURL=url)
    226275            return
    227276        if trackClass == k.property:
    228             growlNotify('iTunes is playing.', '')
    229             return
    230         kw = {}
    231         # XXX iTunes doesn't let you get artwork for shared tracks
    232         if trackClass != k.shared_track:
    233             artwork = iTunes.current_track.artworks()
    234             if artwork:
    235                 try:
    236                     kw['image'] = artwork[0].data_().data
    237                 except CommandError:
    238                     pass
    239         growlNotify(trackName + '  ' +
    240                     u'★' * (iTunes.current_track.rating() / 20),
    241                     iTunes.current_track.album() + '\n' +
    242                     iTunes.current_track.artist(),
    243                     **kw)
     277            notifyTrackInfo(None)
     278            return
     279        # XXX iTunes doesn't let you get artwork for shared tracks (still?)
     280        notifyTrackInfo(trackName, iTunes.current_track.album(), iTunes.current_track.artist(),
     281                        iTunes.current_track.rating(), trackClass != k.shared_track)
    244282
    245283    def defaultOutputDeviceChanged(self):
     
    367405
    368406    def finishLaunching(self):
     407        global http
     408
    369409        super(StreamVision, self).finishLaunching()
    370410
     
    372412                                                     NSUserDomainMask, True)[0]
    373413        cache = os.path.join(caches, 'StreamVision')
    374         self.http = httplib2.Http(OneFileCache(cache), 5)
     414        http = httplib2.Http(OneFileCache(cache), 5)
    375415        self.imagePath = os.path.join(cache, 'image')
    376416
     
    385425
    386426        distributedNotificationCenter = NSDistributedNotificationCenter.defaultCenter()
    387         distributedNotificationCenter.addObserver_selector_name_object_(self, self.displayTrackInfo, 'com.apple.iTunes.playerInfo', None)
     427        distributedNotificationCenter.addObserver_selector_name_object_(self, self.playerInfoChanged, 'com.apple.iTunes.playerInfo', None)
    388428        distributedNotificationCenter.addObserver_selector_name_object_(self, self.terminate_, 'com.apple.logoutContinued', None)
    389429        try:
Note: See TracChangeset for help on using the changeset viewer.