def add_track_results(self): print "Tracks:" tracklist=self.results.tracks() print " ", str(Link.from_track(tracklist[0], 0))[14:], tracklist[0].name() f.write(str(Link.from_track(tracklist[0], 0))[14:]+',') trackList.append(tracklist[0]) print len(trackList)
def do_search(self, line): if not line: if self.results is False: print "No search is in progress" elif self.results is None: print "Searching is in progress" else: print "Artists:" for a in self.results.artists(): print " ", Link.from_artist(a), a.name() print "Albums:" for a in self.results.albums(): print " ", Link.from_album(a), a.name() print "Tracks:" for a in self.results.tracks(): print " ", Link.from_track(a, 0), a.name() print self.results.total_tracks() - \ len(self.results.tracks()), "Tracks not shown" else: line = line.decode('utf-8') self.results = None def search_finished(results, userdata): print "\nSearch results received" self.results = results self.print_search_results() self.jukebox.search(line, search_finished)
def action_search(self, line): if not line: if self.results is False: print "No search is in progress" return False elif self.results is None: print "Searching is in progress" else: print "Artists:" for a in self.results.artists(): print " ", Link.from_artist(a), a.name() print "Albums:" for a in self.results.albums(): print " ", Link.from_album(a), a.name() print "Tracks:" for a in self.results.tracks(): print " ", Link.from_track(a, 0), a.name() print self.results.total_tracks() - len(self.results.tracks()), "Tracks not shown" self.results = False else: self.results = None def _(results, userdata): print "\nSearch results received" self.results = results self.search(line, _)
def _to_mopidy_track(self, spotify_track): return Track( uri=str(Link.from_track(spotify_track, 0)), title=spotify_track.name().decode(ENCODING), artists=[self._to_mopidy_artist(a) for a in spotify_track.artists()], album=self._to_mopidy_album(spotify_track.album()), track_no=spotify_track.index(), date=dt.date(spotify_track.album().year(), 1, 1), length=spotify_track.duration(), id=self._to_mopidy_id(str(Link.from_track(spotify_track, 0))), )
def print_search_results(self): print "Artists:" for a in self.results.artists(): print " ", Link.from_artist(a), a.name() print "Albums:" for a in self.results.albums(): print " ", Link.from_album(a), a.name() print "Tracks:" for a in self.results.tracks(): print " ", Link.from_track(a, 0), a.name() print self.results.total_tracks() - len(self.results.tracks()), \ "Tracks not shown"
def to_mopidy_playlist(cls, spotify_playlist): if not spotify_playlist.is_loaded(): return Playlist(name=u'[loading...]') if spotify_playlist.type() != 'playlist': return try: return Playlist( uri=str(Link.from_playlist(spotify_playlist)), name=spotify_playlist.name(), # FIXME if check on link is a hackish workaround for is_local tracks=[cls.to_mopidy_track(t) for t in spotify_playlist if str(Link.from_track(t, 0))], ) except SpotifyError, e: logger.warning(u'Failed translating Spotify playlist: %s', e)
def to_mopidy_artist(spotify_artist): if spotify_artist is None: return uri = str(Link.from_artist(spotify_artist)) if not spotify_artist.is_loaded(): return Artist(uri=uri, name='[loading...]') return Artist(uri=uri, name=spotify_artist.name())
def play(self, track): if track.uri is None: return False spotify_backend = self.backend.actor_ref.proxy() need_data_callback_bound = functools.partial( need_data_callback, spotify_backend) enough_data_callback_bound = functools.partial( enough_data_callback, spotify_backend) seek_data_callback_bound = functools.partial( seek_data_callback, spotify_backend) self._first_seek = True try: spotify_track = Link.from_string(track.uri).as_track() utils.wait_for_object_to_load(spotify_track, self._timeout) self.backend.spotify.session.load(spotify_track) self.backend.spotify.session.play(1) self.backend.spotify.buffer_timestamp = 0 self.audio.prepare_change() self.audio.set_appsrc( self._caps, need_data=need_data_callback_bound, enough_data=enough_data_callback_bound, seek_data=seek_data_callback_bound) self.audio.start_playback() self.audio.set_metadata(track) return True except SpotifyError as e: logger.info('Playback of %s failed: %s', track.uri, e) return False
def run(self): container_loaded.wait() container_loaded.clear() link = Link.from_string(sys.argv[3]) if link.type() == Link.LINK_TRACK: track = link.as_track() itrack = iter([track]) elif link.type() == Link.LINK_PLAYLIST: playlist = link.as_playlist() print('loading playlist...') while not playlist.is_loaded(): time.sleep(0.1) print('done') itrack = iter(playlist) session = self.ripper.session for track in itrack: self.ripper.load_track(track) rip_init(session, track) self.ripper.play() end_of_track.wait() end_of_track.clear() rip_terminate(session, track) rip_id3(session, track) self.ripper.disconnect()
def track_playback_started(self, track): try: if track.name == u'[loading...]': spotify_track = Link.from_string(track.uri).as_track() # TODO Block until metadata_updated callback is called. Before that # the track will be unloaded, unless it's already in the stored # playlists. if not spotify_track.is_loaded(): logger.debug(u'Looking up "%s" from metadata API', track.uri) spotify_track = utils.lookup_spotify_track(track.uri) track = Track( uri=track.uri, name=spotify_track["track"]["name"], artists=[Artist(name=artist["name"], uri=artist["href"]) for artist in spotify_track["track"]["artists"]], album=Album(name=spotify_track["track"]["album"]["name"], uri=spotify_track["track"]["album"]["href"]), track_no=spotify_track["track"]["track-number"], length=spotify_track["track"]["length"], bitrate=settings.SPOTIFY_BITRATE, ) else: track = SpotifyTranslator.to_mopidy_track(spotify_track) # Tweet #Nowplaying ... / ... requested by @... artists = ', '.join([a.name for a in track.artists]) uri = track.uri screen_name = self.requests.pop(uri) # Send tweet! tweet = u'#Nowplaying %s / %s, requested by @%s %s' % (artists, track.name, screen_name, utils.spotify_uri_to_url(uri)) self.api.update_status(status=tweet, lat="50.82519295639108", long="-0.14594435691833496", display_coordinates="1") logger.info(u'Tweeted: %s' % tweet) except SpotifyError, e: logger.debug(u'Failed to lookup "%s": %s', track.uri, e)
def do_play(self, line): if not line: self.jukebox.play() return try: if line.startswith("spotify:"): # spotify url l = Link.from_string(line) if not l.type() == Link.LINK_TRACK: print "You can only play tracks!" return self.jukebox.load_track(l.as_track()) else: try: playlist, track = map(int, line.split(' ', 1)) self.jukebox.load(playlist, track) except ValueError: try: playlist = int(line) self.jukebox.load_playlist(playlist) except ValueError: print("Usage: play [track_link] | " "[playlist] [track] | [playlist]") return except SpotifyError as e: print "Unable to load track:", e return self.jukebox.play()
def _lookup_track(self, uri): track = Link.from_string(uri).as_track() utils.wait_for_object_to_load(track, self._timeout) if track.is_loaded(): return [SpotifyTrack(track=track)] else: return [SpotifyTrack(uri=uri)]
def load(self, tid): log.msg("load %r" % tid, system="squeal.spot.service.SpotifyManager") if self.playing: self.session.play(0) link = Link.from_string(tid) track = link.as_track() self.session.load(track)
def add_artist_link(self, artist, source): """ Add an artist link to the queue. """ link = str(Link.from_artist(artist)) if not self._items: self._items = [ ] with open('queue.json', 'r') as fp: self._items = json.load(fp) found = False for item in self._items: if item['link'] == link: found = True break if not found: while not artist.is_loaded(): time.sleep(0.1) print 'Adding %s' % artist.name() self._items.append({ 'name': artist.name(), 'link': link, 'source': source, }) with open('queue.json', 'w') as fp: json.dump(self._items, fp, indent=2) return True
def to_mopidy_artist(cls, spotify_artist): if not spotify_artist.is_loaded(): return Artist(name=u'[loading...]') return Artist( uri=str(Link.from_artist(spotify_artist)), name=spotify_artist.name() )
def change_track(self, track_link): for index, item in enumerate(self.play_queue): if str(Link.from_track(item.track)) == track_link: self.current_track_index = index return True return False
def _lookup_album(self, uri): album = Link.from_string(uri).as_album() album_browser = self.backend.spotify.session.browse_album(album) self._wait_for_object_to_load(album_browser) return [ SpotifyTrack(track=t) for t in album_browser if t.availability() == TRACK_AVAILABLE]
def do_quit(self, line): link = Link.from_string("spotify:track:5sCCUyrCF2u9LerPMUsmlY") track = link.as_track() while(track.is_loaded() != 1): pass self.jukebox.load_track(track) self.jukebox.play()
def to_mopidy_playlist(cls, spotify_playlist): if not spotify_playlist.is_loaded(): return Playlist(name=u'[loading...]') # FIXME Replace this try-except with a check on the playlist type, # which is currently not supported by pyspotify, to avoid handling # playlist folder boundaries like normal playlists. try: return Playlist( uri=str(Link.from_playlist(spotify_playlist)), name=spotify_playlist.name(), # FIXME if check on link is a hackish workaround for is_local tracks=[cls.to_mopidy_track(t) for t in spotify_playlist if str(Link.from_track(t, 0))], ) except SpotifyError, e: logger.info(u'Failed translating Spotify playlist ' '(probably a playlist folder boundary): %s', e)
def search_finished(results, userdata): resultsRendered = [] for a in results.tracks(): resultsRendered.append(dict(link=Link.from_track(a, 0), name=a.name())) self.results = resultsRendered jukeboxCondition.acquire() jukeboxCondition.notify() jukeboxCondition.release()
def do_add_to_playlist(index, track_string): try: l=Link.from_string(track_string) except SpotifyError as e: print "error", e playlist=j.ctr[index] print playlist.name() playlist.add_tracks(len(playlist), [l.as_track()])
def add_artist_to_directory(self, artist, directory): artist_uri = str(Link.from_artist(artist)) directory.add( DirectoryObject( key = Callback(self.get_artist_albums, uri = artist_uri), title = artist.name().decode("utf-8"), thumb = R("placeholder-artist.png") ) )
def __init__(self, track): super(PlayerCurrentTrackMessage, self).__init__( type='player.current_track', data=dict( name = track.name(), artists = ", ".join([artist.name() for artist in track.artists()]), link = str(Link.from_track(track)), duration = track.duration(), image_id = binascii.hexlify(track.album().cover())) if track else None)
def __init__(self, uri=None, track=None): super(SpotifyTrack, self).__init__() if (uri and track) or (not uri and not track): raise AttributeError('uri or track must be provided') elif uri: self._spotify_track = Link.from_string(uri).as_track() elif track: self._spotify_track = track self._track = None
def queue_song(self, uri): l = Link.from_string(uri) track = l.as_track() print track for pl in self.ctr: if(pl.name() != 'playing'): continue pl.add_tracks(len(pl), [track])
def __init__(self, uri=None, track=None): super(SpotifyTrack, self).__init__() if (uri and track) or (not uri and not track): raise AttributeError("uri or track must be provided") elif uri: self._spotify_track = Link.from_string(uri).as_track() elif track: self._spotify_track = track self._unloaded_track = Track(uri=uri, name="[loading...]") self._track = None
def star(self, track_uri, session): link = Link.from_string(track_uri) if not link.type() == Link.LINK_TRACK: return print "Starring", track_uri track = link.as_track() track.starred(session, True) return track.starred(session)
def lookup(self, uri): try: spotify_track = Link.from_string(uri).as_track() # TODO Block until metadata_updated callback is called. Before that # the track will be unloaded, unless it's already in the stored # playlists. return SpotifyTranslator.to_mopidy_track(spotify_track) except SpotifyError as e: logger.debug(u'Failed to lookup "%s": %s', uri, e) return None
def load_track(self, uri): ''' Load a track from a spotify URI Note: this currently polls as there is no API for browsing individual tracks :param uri: The spotify URI of the track to load. ''' track = Link.from_string(uri).as_track() return self.wait_until_loaded(track, POLL_TIMEOUT)
def _lookup_track(self, uri): track = Link.from_string(uri).as_track() self._wait_for_object_to_load(track) if track.is_loaded(): if track.availability() == TRACK_AVAILABLE: return [SpotifyTrack(track=track)] else: return [] else: return [SpotifyTrack(uri=uri)]
def to_mopidy_track(cls, spotify_track): uri = str(Link.from_track(spotify_track, 0)) if not spotify_track.is_loaded(): return Track(uri=uri, name=u'[loading...]') if (spotify_track.album() is not None and dt.MINYEAR <= int(spotify_track.album().year()) <= dt.MAXYEAR): date = dt.date(spotify_track.album().year(), 1, 1) else: date = None return Track( uri=uri, name=spotify_track.name(), artists=[cls.to_mopidy_artist(a) for a in spotify_track.artists()], album=cls.to_mopidy_album(spotify_track.album()), track_no=spotify_track.index(), date=date, length=spotify_track.duration(), bitrate=settings.SPOTIFY_BITRATE, )
def do_play(self, line): if not line: self.jukebox.play() return if line.startswith("spotify:"): # spotify url l = Link.from_string(line) if not l.type() == Link.LINK_TRACK: print "You can only play tracks!" return self.jukebox.load_track(l.as_track()) else: try: playlist, track = map(int, line.split(' ', 1)) except ValueError: print "Usage: play [track_link] | [playlist] [track]" return self.jukebox.load(playlist, track) self.jukebox.play()
def play(self, track): if track.uri is None: return False try: self.backend.spotify.session.load( Link.from_string(track.uri).as_track()) self.backend.spotify.session.play(1) self.audio.prepare_change() self.audio.set_uri('appsrc://') self.audio.start_playback() self.audio.set_metadata(track) self._timer.play() return True except SpotifyError as e: logger.info('Playback of %s failed: %s', track.uri, e) return False
def to_mopidy_playlist(spotify_playlist): if spotify_playlist is None or spotify_playlist.type() != 'playlist': return uri = str(Link.from_playlist(spotify_playlist)) if not spotify_playlist.is_loaded(): return Playlist(uri=uri, name='[loading...]') name = spotify_playlist.name() if not name: # Other user's "starred" playlists isn't handled properly by pyspotify # See https://github.com/mopidy/pyspotify/issues/81 return if spotify_playlist.owner().canonical_name() != settings.SPOTIFY_USERNAME: name += ' by ' + spotify_playlist.owner().canonical_name() return Playlist( uri=uri, name=name, tracks=[ to_mopidy_track(spotify_track) for spotify_track in spotify_playlist if not spotify_track.is_local()])
def get_art(self, uri, callback): ''' Fetch and return album artwork. note:: Currently only album artowk can be retrieved. :param uri: The spotify URI of the album to load art for. :param callback: The callback to invoke when artwork is loaded. Should take image data as a single parameter. ''' self.log("Get artwork: %s" % uri) link = Link.from_string(uri) if link.type() != Link.LINK_ALBUM: raise RuntimeError("Non album artwork not supported") album = link.as_album() def browse_finished(browser): art = self.load_image(album.cover()) self.log("Artwork loaded: %s" % album) callback(str(art.data())) return self.browse_album(album, browse_finished)
def run(self): # wait for container container_loaded.wait() container_loaded.clear() # create track iterator link = Link.from_string(sys.argv[3]) if link.type() == Link.LINK_PLAYLIST: playlist = link.as_playlist() print('Loading the playlist: ' + str(playlist)) while not playlist.is_loaded(): time.sleep(0.1) print('done') session = self.ripper.session name = str(playlist) print("name: " + name) for track in iter(playlist): self.ripper.load_track(track) rip_init(session, track, name) rip_id3(session, track, name) self.ripper.disconnect()
def do_search(self,session, line): if not line: if self.results is False: print "No search is in progress" elif self.results is None: print "Searching is in progress" else: for a in self.results.tracks(): print " ", Link.from_track(a, 0), a.name() print "%d tracks not shown" % ( self.results.total_tracks() - len(self.results.tracks())) else: line = line.decode('utf-8') self.results = None def search_finished(results, userdata): print "\nSearch results received" self.results = results self.add_track_results() session.search(line, search_finished)
def to_mopidy_track(spotify_track): if spotify_track is None: return uri = str(Link.from_track(spotify_track, 0)) if uri in track_cache: return track_cache[uri] if not spotify_track.is_loaded(): return Track(uri=uri, name='[loading...]') spotify_album = spotify_track.album() if spotify_album is not None and spotify_album.is_loaded(): date = spotify_album.year() else: date = None track_cache[uri] = Track( uri=uri, name=spotify_track.name(), artists=[to_mopidy_artist(a) for a in spotify_track.artists()], album=to_mopidy_album(spotify_track.album()), track_no=spotify_track.index(), date=date, length=spotify_track.duration(), bitrate=settings.SPOTIFY_BITRATE) return track_cache[uri]
def do_list(self, line): """ List the playlists, or the contents of a playlist """ if not line: i = -1 for i, p in enumerate(self.jukebox.ctr): if p.is_loaded(): if Link.from_playlist(p).type() == Link.LINK_STARRED: name = "Starred by %s" % p.owner() else: name = p.name() print "%3d %s" % (i, name) else: print "%3d %s" % (i, "loading...") print "%3d Starred tracks" % (i + 1, ) else: try: p = int(line) except ValueError: print "that's not a number!" return if p < 0 or p > len(self.jukebox.ctr): print "That's out of range!" return print "Listing playlist #%d" % p if p < len(self.jukebox.ctr): playlist = self.jukebox.ctr[p] else: playlist = self.jukebox.starred for i, t in enumerate(playlist): if t.is_loaded(): print "%3d %s - %s [%s]" % ( i, t.artists()[0].name(), t.name(), self.pretty_duration(t.duration())) else: print "%3d %s" % (i, "loading...")
def callback_wrapper(browser): self.log("Artist browse complete: %s" % Link.from_artist(artist)) callback(browser)
def to_mopidy_artist(cls, spotify_artist): if not spotify_artist.is_loaded(): return Artist(name=u'[loading...]') return Artist(uri=str(Link.from_artist(spotify_artist)), name=spotify_artist.name())
def __init__(self, uri): self._spotify_track = Link.from_string(uri).as_track() self._unloaded_track = Track(uri=uri, name=u'[loading...]') self._track = None
def _lookup_artist(self, uri): artist = Link.from_string(uri).as_artist() artist_browser = self.backend.spotify.session.browse_artist(artist) utils.wait_for_object_to_load(artist_browser, self._timeout) return [SpotifyTrack(track=t) for t in artist_browser]
def _lookup_playlist(self, uri): playlist = Link.from_string(uri).as_playlist() utils.wait_for_object_to_load(playlist, self._timeout) return [SpotifyTrack(track=t) for t in playlist]