def __init__(self): QtGui.QWidget.__init__(self) # Create and setup the UI self.ui = Ui_Spotimute() self.ui.setupUi(self) self.ui.pbBlacklistThis.clicked.connect(self._blacklist_song) self._spotify = Spotify() self._audio = AudioManager() self._timer = QtCore.QTimer() self._timer.start(500) self._timer.timeout.connect(self._get_status) self._yes_style = 'background: red; color: white;' self._no_style = 'background: green; color: white;' self._last_song = None # Tray stuff self._icon_muted = QtGui.QIcon(':/images/flag-red.png') self._icon_unmuted = QtGui.QIcon(':/images/flag-green.png') self._tray_icon = self._icon_unmuted self.createActions() self.createTrayIcon() self.trayIcon.activated.connect(self._tray_icon_activated) self.trayIcon.show()
def run(): # Get a list of playlists from yt youtube = Youtube('./credentials/client_secrets.json') spotify = Spotify(getenv('SPOTIFY_OAUTH_TOKEN')) playlists = youtube.get_playlists() # Ask which playlist we want to get the music videos from for index, playlist in enumerate(playlists): print(f"{index}: {playlist.title}") choice = int(input("Enter desired playlist number: ")) chosen_playlist = playlists[choice] print(f"Selected playlist name: {chosen_playlist.title}") # For each video in the playlist get the song info from yt songs = youtube.get_videos_from_playlist(chosen_playlist.id) print(f"Attempting to add {len(songs)}") # Search for desired song on Spotify for song in songs: spotify_song_id = spotify.search_song(song.artist, song.track) if spotify_song_id: added_song = spotify.add_song_to_spotify(spotify_song_id) if added_song: print( f"Successfully added {song.artist} to Spotify liked songs")
def createRoom(): userId = request.form['userId'] token = request.form['token'] roomName = getRoomName() sp = Spotify(secrets.CLIENT_ID, secrets.CLIENT_SECRET, token) tracks, error = sp.getPlaylistTracks('spotify', sp.PLAYLIST_ID_TOP_50) if error == None: # Persist room in db resp = app.db.post(params={ 'createdAt' : int(time.time() * 1000), 'name':roomName, 'owner':userId, 'token':token, 'users':[userId], 'tracks':tracks }) roomId = resp.json()['id'] return jsonify(id=roomId, name=roomName) else: return jsonify(error), error.get('status', 500)
def __init__(self): self.__youtube = Youtube() self.__spotify = Spotify() self.__editor = TagEditor() self.__last = LastFM() self.__apple = AppleMusic() self.__deezer = Deezer()
def get_spotify_data(keywords, num_playlists): """Master function get retrieve data from Spotify.""" # Create instance of Spotify class SpotifyMaster = Spotify(CLIENT_ID, CLIENT_SECRET) # Only retrieve playlists if not at num_playlists playlist_table_size = return_table_len("Playlists") if playlist_table_size < num_playlists - 10: # Pull playlist data a keyword print("Getting Spotify playlists") cache_dict = json_helper.read_cache() keyword_index = cache_dict["keyword_index"] keyword = keywords[keyword_index] print("Keyword: " + keyword) # Get playlists json_result = SpotifyMaster.search(keyword, "playlist") playlists = json_result["playlists"]["items"] # Write playlists to database write_playlists_to_database(SpotifyMaster, playlists) playlist_table_size = return_table_len("Playlists") print("Playlist table size: " + str(playlist_table_size)) return # Otherwise, start getting tracks until reach limit tracks_table_size = return_table_len("Tracks") track_features_table_size = return_table_len("TrackFeatures") # Finish if over 100 rows for either if tracks_table_size > 120 and track_features_table_size > 120: print("Gathered sufficient data for the database.") return if tracks_table_size != num_playlists * 10: print("Getting Spotify Tracks") # Get the correct playlist href and increment the index counter cache_dict = json_helper.read_cache() cache_dict["playlist_href_index"] = cache_dict.get( "playlist_href_index", -1) + 1 playlist_href_index = cache_dict["playlist_href_index"] json_helper.write_cache(cache_dict) playlist_href = cache_dict["playlist_hrefs"][playlist_href_index] # Get track ids from the playlist and write to database track_ids = SpotifyMaster.get_tracks_from_playlist(playlist_href) write_tracks_and_features_to_database(SpotifyMaster, track_ids, playlist_href, playlist_href_index + 1) print("Tracks table size: " + str(tracks_table_size)) print("Track Features table size: " + str(track_features_table_size)) return # Done getting data, JOIN time. print("Done retrieving Spotify playlists and track data.")
def callback(): code = request.args['code'] token_info = Spotify.exchange_code(code) spotify = Spotify(None, token_info['access_token']) user = users_db.create_user(spotify, token_info['refresh_token']) session['access_token'] = token_info['access_token'] session['expires'] = datetime.datetime.now() + datetime.timedelta(0, token_info['expires_in']) session['spotify_id'] = user['spotify_id'] return redirect('/')
class SpotifyTest(unittest.TestCase): def setup(self): self.spotify = Spotify() self.spotify.authenticate() def test_constructor(self): Spotify() def test_authenticate(self): self.setup() def test_whoami(self): self.setup() user = self.spotify.whoami() def test_get_user_playlists(self): self.setup() user = self.spotify.whoami() self.spotify.get_user_playlists(user) def test_get_user_tracks(self): self.setup() user = self.spotify.whoami() self.spotify.get_user_tracks(user)
def callback(): """callback from spotify.com""" application.logger.debug('Returning from callback') # this is the whole reason to do the call back, to get the code auth_token = request.args['code'] # create the spotify object and store in session spotify = Spotify(auth_code=auth_token) session['spotify'] = spotify session['spotify_token'] = spotify.get_spotify_token() # redirect to the playlist view return redirect('playlists')
def index(): session['expires'] = datetime.datetime.now() if 'access_token' in session and session['expires'] > datetime.datetime.now(): user = db['users'].find_one({'spotify_id': session['spotify_id']}) return render_template('index.html', playlists=user['playlists']) if 'spotify_id' in session: user = db['users'].find_one({'spotify_id': session['spotify_id']}) token_info = Spotify.update_token(user['refresh_token']) session['access_token'] = token_info['access_token'] session['expires'] = datetime.datetime.now() + datetime.timedelta(0, token_info['expires_in']) return render_template('index.html', playlists=user['playlists']) return render_template('login.html', redirect_url=Spotify.get_redirect_url())
def authtarget(): sp = Spotify() db = Database() resultList = [] while True: resultList = db.getAllEventID() time.sleep(10) for i in resultList: t = threading.Thread(target=authtarget) t.daemon = True t.start() sp.timer(i)
def post(self): try: # Parse the arguments parser = reqparse.RequestParser() parser.add_argument('eventID', type=str) args = parser.parse_args() spotify = Spotify() songs = spotify.recommend_ui(args['eventID']) return json.dumps(songs) except Exception as e: return {'error': str(e)}
def __init__( self, client_id: str, client_secret: str, webhook_url: str, playlist_id: str, interval: int = 60, ): self.spotify_api = Spotify(client_id, client_secret) self.webhook_url = webhook_url self.playlist_id = playlist_id self.interval = interval
def downloadBySpotifyUriAlbumMode(self, album_uri, path): user = Spotify() playlist = user.getAlbum(album_uri) for info, i in zip(playlist['tracks'],range(len(playlist['tracks']))): info['uri'] = str(info['uri']).split('/')[-1] info['uri'] = str(info['uri']).split('?')[0] notify.send(f'{info["artist"][0]} - {info["name"]}', downloaded=False) print(f'Downloading {i+1} of {len(playlist["tracks"])}') fixed_name = f'{info["artist"][0]} - {info["name"]}' fixed_name = fixed_name.replace('.','') fixed_name = fixed_name.replace(',','') fixed_name = fixed_name.replace("'",'') fixed_name = fixed_name.replace("/","") #finding and downloading from YouTube and tagging self.__downloadMusicFromYoutube(fixed_name, info['uri'], info['duration_ms']) self.__editor.setTags( data=info ) cachepath = os.getcwd() + '/cache' fullpath = os.getcwd() + '/Downloads' if not os.path.exists(fullpath): os.makedirs(fullpath) name = f'{info["artist"][0]} - {info["name"]}' os.rename( f"{cachepath}/{info['uri']}/{info['uri']}.mp3", f"{fullpath}/{getCorrect(name)}.mp3" ) if path: os.rename( f"{fullpath}/{getCorrect(name)}.mp3", f"{path}/{getCorrect(name)}.mp3" ) #deleting cache try: shutil.rmtree(f"cache/{info['uri']}") except: pass notify.send(f'{info["artist"][0]} - {info["name"]}')
class SpotifyAuthTests(unittest.TestCase): def setUp(self): self.spotify = Spotify() def test_authfails(self): res = self.spotify._get_rel('/tracks/2TpxZ7JUBn3uw46aR7qd6V') self.assertTrue( res is not None, "Something went wrong with intial request for authfails") self.spotify.session.auth.token = "asdfasdxfasf" res = self.spotify._get_rel('/tracks/2TpxZ7JUBn3uw46aR7qd6V') self.assertTrue('error' not in res.json(), "The ClientAuth didn't renew")
def main(): sp = Spotify() yt = Youtube() yt_playlist_id = input("Enter youtube playlist id: ") spotify_playlist_name = input("Enter a name for your spotify playlist: ") songs = yt.get_songs_from_playlist(yt_playlist_id) spotify_playlist_id = sp.create_playlist(spotify_playlist_name) for song in songs: song_uri = sp.get_song_uri(song.artist, song.title) was_added = sp.add_song_to_playlist(song_uri, spotify_playlist_id) if was_added: print(f'{song.artist} - {song.title} was added to playlist.')
def start(self): if self.sp: self.sp.disconnect() self.sp = None self.sp = Spotify() self.ready_event = Event() self.messages = [] self.sp.on('error', self.on_error)\ .on('close', self.on_close) self.sp.login(self.host.username, self.host.password, self.on_login)
def __init__(self): print 'Initializing Driver' session = Session() self.modules = session.query(LightModule).all() self.strips = {s.name: s for s in session.query(Strip).all()} session.close() print 'starting engine' self.engine = LightEngine(self.modules) print 'engine running' self.sp = Spotify() print 'spotify loaded' if SIM: self.sim = Client('127.0.0.1:7890')
def post(self): try: # Parse the arguments parser = reqparse.RequestParser() parser.add_argument('explicitAllowed', type=str) parser.add_argument('eventName', type=str) parser.add_argument('authCode', type=str) args = parser.parse_args() _authCode = args['authCode'] tokens = auth2Token(_authCode) #print(tokens) #t = threading.Thread(target = authtarget) #t.daemon = True #t.start() accessToken = tokens[0] refreshToken = tokens[1] #print("here0") sp = Spotify() ids = sp.createPlaylist(accessToken) #print("here1") #print(ids[0]) #print(ids[1]) hostID = CreateHost("0", "0", "1", ids[0], ids[1], accessToken, refreshToken) #######username, playlistid db = Database() #print(hostID) db.insertEvent("LIVE", hostID, args['explicitAllowed'], args['eventName']) #print("here2") eventID = db.getEventid(args['eventName']) db.updateHostEventID(hostID, eventID) print("here3") sp.addTwo(eventID) print("here9") #sp.addFive(eventID) print("HERE") #sp.start(eventID) print("here4") #sp.play(eventID) print("here5") #sp.authtarget(hostID) #print("here6") return json.dumps({'eventID': eventID, 'hostID': hostID}) except Exception as e: return {'error': str(e)}
def main(args): ''' Main method ''' if len(args) < 3: print( "Please provide the necessary parameters ie kexp.py [playlist_name] [start_date] [end_date] [playlist_description]" ) else: #The name of the playlist you want to use in Spotify #If this playlist does not exist a new one with this name will be created #If this playlist exists it will be used playlist_name = args[0] #The start date time of the tracks you want to return. #The KEXP API is in UTC format so make this date must be in the UTC format and timezone #Example: 2019-02-15T02:00:00Z start_date = args[1] #The end date time of the tracks you want to return. #The KEXP API is in UTC format so make this date must be in the UTC format and timezone #Example: 2019-02-15T05:00:00Z end_date = args[2] #The description of the playlist you want to appear in Spotify playlist_description = args[3] #Create new Playlist object #Set this particular playlist properties #Send the playlist object into Spotify to create/update the latest playlist = Playlist() spotify = Spotify() playlist.name = playlist_name playlist.description = playlist_description temp_tracks = [] uri = f'https://api.kexp.org/v2/plays/?airdate_after={start_date}&airdate_before={end_date}&album=&album_exact=&artist=&artist_exact=&exclude_airbreaks=&has_comment=&host_ids=&label=&label_exact=&limit=2000&ordering=airdate&recording_id=&show_ids=&song=&song_exact=' temp_tracks = get_tracks(uri, start_date, end_date) for temp_track in temp_tracks: if not any(x.airdate == temp_track['airdate'] for x in playlist.tracks): track = Track() track.artist = temp_track['artist'] track.title = temp_track['song'] track.airdate = temp_track['airdate'] playlist.tracks.append(track) playlist.tracks.sort(key=extract_time, reverse=False) spotify.create_playlist(playlist)
def login(): """logon route""" session.permanent = True # check to see if token exists if session.get('spotify_token') is None: application.logger.debug('No spotify token in session, resigning in') # use spotify to handle loging in auth_url = Spotify.get_auth_url() return redirect(auth_url) else: # just get token from the session application.logger.debug('Reloading spotify token from session') spotify = Spotify(token=session['spotify_token']) session['spotify'] = spotify return redirect('playlists')
class TrackInfo: def __init__(self, track_id): self.sp = Spotify() self.data = self.sp.get_analysis(track_id) def get_all_beats(self): return [b['start'] for b in self.data['beats']] def get_all_bars(self): return [b['start'] for b in self.data['bars']] def get_beats(self, start_time, end_time): beats = self.get_all_beats() return filter(lambda b: b >= start_time and b <= end_time, beats) def get_i_beat_in_bar(self, i, start_time=0.0, end_time=99999): bars = set(self.get_all_bars()) beats = self.get_all_beats() beat_idx = 0 i_beats = [] for beat in beats: if beat in bars: beat_idx = 0 else: beat_idx += 1 if beat_idx == i: i_beats.append(beat) return filter(lambda b: b >= start_time and b <= end_time, i_beats)
def test_get_current_playing(self, mock__get_response): spotify = Spotify() test_path = os.path.join("test-responses-spotify", "currentPlayingResponse.json") exp_res_path = os.path.join("test-responses-spotify", "currentPlayingExpResponse.json") exp_res_json = json.loads(open(exp_res_path, "r").read()) test_json = json.loads(open(test_path, "r").read()) mock__get_response.return_value = test_json response = spotify.get_current_playing() self.assertEqual(response, exp_res_json)
def __init__(self): self.spotify: Spotify = Spotify() self.current_media_list: vlc.MediaList = vlc.get_default_instance( ).media_list_new() self.current_playlist_urls: List[str] = [] self.current_page: int = -1 self.total_items: int = 0
def __init__(self, host, port): # Make socket self._transport = TSocket.TSocket(host, port) # Buffering is critical. Raw sockets are very slow self._transport = TTransport.TBufferedTransport(self._transport) # Wrap in a protocol self._protocol = TBinaryProtocol.TBinaryProtocol(self._transport) # Create a client to use the protocol encoder self._client = Spotify.Client(self._protocol) # Connect! try: self._transport.open() except thrift.transport.TTransport.TTransportException: print "Couldn't connect to server on {}:{}".format(host, port) sys.exit(1) #status self._success = True # Empty credential self._credentials = None # Empty playlist array self._playlists = [] # Empty selected playlist self._currentplaylist = None
def __init__(self, username, station): if station not in STATIONS: raise UnknownStation self.station = station self.username = username self.db = Database(station) self.spotify = Spotify(username)
def test_get_device_id(self, mock__get_response): spotify = Spotify() test_path = os.path.join("test-responses-spotify", "deviceIdResponse.json") test_json = json.loads(open(test_path, "r").read()) mock__get_response.return_value = test_json device = "Connect150SE 305890942ae5" spotify.get_device_id(device) exp_res = "f5b81d7cf3c22cc1098598b69fcd3f6f52fe8961" res = spotify.deviceID self.assertEqual(res, exp_res)
class SpotifyRequestTest(unittest.TestCase): def setUp(self): self.spotify = Spotify() def test_rawgettrack(self): res = self.spotify._get_rel('/tracks/2TpxZ7JUBn3uw46aR7qd6V') self.assertTrue(res is not None, "Authentication didn't work for some reason")
def sp_client(): if not os.path.isfile(CONFFILE): pytest.skip('No spotify config found') with open(CONFFILE) as f: config = json.load(f) client, secret = ( config.get("SPOTIFY_CLIENT_ID", ''), config.get("SPOTIFY_CLIENT_SECRET", ''), ) if not client or not secret: pytest.skip('Spotify keys not found in config') sp = Spotify() sp.discography_cache.clear() sp.configure(client, secret) return sp
def get(self): s = Spotify() verbs = ["skip"] if s.isPlaying(): verbs.append("pause") else: verbs.append("play") volume_filled = int(s.getVolume() / 10) self.render( "index.html", verbs=verbs, track_name=s.getTrackName(), track_artist=s.getTrackArtist(), volume_filled=volume_filled, volume_empty=10 - volume_filled, )
def test_get_playlist(self, mock__get_response): spotify = Spotify() test_path = os.path.join("test-responses-spotify", "playlistResponse.json") exp_res_path = os.path.join("test-responses-spotify", "playlistExpResponse.json") exp_res_json = json.loads( open(exp_res_path, "r", encoding='cp850').read()) test_json = json.loads(open(test_path, "r", encoding='cp850').read()) mock__get_response.return_value = test_json response = spotify.get_playlist("workout") self.assertEqual(response, exp_res_json)
def copy_playlist(self): spotify = Spotify(self.username) token = spotify.authenticate_spotify() driver = webdriver.Chrome(self.chrome_driver) driver.get(self.playlist_url) html = driver.page_source spotify_uris = [] soup = BeautifulSoup(html, 'html.parser') playlist_name = self.get_soundcloud_playlist_info(soup)[0] playlist_description = self.get_soundcloud_playlist_info(soup)[1] # start our beautiful soup search with the parent element results = soup.find_all( "li", class_="trackList__item sc-border-light-bottom") # traverse through the all the sub elements of our search to find all the song divs in a page then retrieve their links and song data for x in results: div = x.find_all( "div", class_="trackItem g-flex-row sc-type-small sc-type-light") for z in div: final_div = z.find_all("div", class_="trackItem__content sc-truncate") for ref in final_div: href = ref.find( "a", class_= "trackItem__trackTitle sc-link-dark sc-font-light", href=True) track_name = href.text.lower().replace(" ", "+") artist_name = ref.find( "a", class_="trackItem__username sc-link-light").text.lower( ).replace(" ", "+") # if spotify can find a uri for this song, then we append it to our list, else we send it to our dictionary which will download the song instead if spotify.get_spotify_uri(track_name, artist_name, token) is not None: spotify_uris.append( spotify.get_spotify_uri(track_name, artist_name, token)) else: link = "https://soundcloud.com" + href["href"] self.tracks.update({href.text: link}) driver.close() playlist_id = spotify.create_playlist(token, playlist_name, playlist_description) spotify.add_songs_to_playlist(spotify_uris, token, playlist_id) self.download_soundcloud(self.tracks) print( "-------- Succesfully copied your playlist on Soundcloud to Spotify! --------" )
def main(): options = parse_args() info('Fecthing threads from Reddit') raw = open('rap_pl.json') json_object = json.load(raw) entities = [] for song in json_object: ss = song['artist']+" "+song['song'] + '[' entities.append(Entity(ss)) raw.close() info('Found {} threads'.format(len(entities))) for entity in entities: try: entity.search_term = search_term_from_title(entity.reddit_title) except Exception as e: error(e) error('Failed to convert Reddit title "{}" to a search term'.format(entity)) refresh_token = read_refresh_token(options.refresh_token_file) try: s = Spotify(options.spotify_client_id, options.spotify_client_secret, refresh_token) except Exception as e: error('Failed to create Spotify agent') error(e) return 1 info('Searching Spotify for tracks') for entity in entities: try: entity.spotify_track = s.search_track(entity.search_term) except Exception as e: error(e) error('Skipping...') # list to Set to list - done to dedupe tracks_found = list(Set([entity.spotify_track for entity in entities if entity.spotify_track is not None])) info('Found {} Spotify tracks'.format(len(tracks_found))) if not (float(len(tracks_found)) / len(entities)) > options.search_threshold: error('Search of Spotify tracks under threshold of {}'.format(options.search_threshold)) return 1 if options.dry_run == False: try: info('Removing existing tracks from playlist') s.clear_playlist(options.playlist_id) info('Adding {} new tracks to playlist'.format(len(tracks_found))) s.add_tracks_to_playlist(options.playlist_id, tracks_found) except Exception as e: error(e) return 1 info('Run completed successfully') return 0
def main(): playlist_url = input("Youtube playlist url: ") playlist_name = input("Playlist name: ") yt = Youtube(playlist_url) song_titles = yt.get_songs_title() print(len(song_titles)) songs_info = yt.get_songs_info(song_titles) print(len(songs_info)) spotify = Spotify() playlst_id = spotify.create_playlist(playlist_name) for song_name, artist in songs_info.items(): uri = spotify.get_spotify_uri(artist, song_name) status = spotify.add_songs_to_playlist(playlst_id, {"uris": [uri]}) if status: print(f"{artist}-{song_name} was added to playlist.") else: print(f"\nERROR!! {artist}-{song_name} could not be added.\n")
def spotifyDataFetcher(): global currentlyPlaying global displayText global displayTextWidth global durationMs global progressMs global progressFetchMs global start_time accessToken = '' while time.time() - start_time < 50400: try : if accessToken == '': accessToken = Spotify.getAccessToken() currentlyPlayingData = Spotify.currentlyPlaying(accessToken) if currentlyPlayingData['is_playing'] == True: currentlyPlaying = True songName = currentlyPlayingData['item']['name'].encode('iso-8859-1').strip() artistName = currentlyPlayingData['item']['artists'][0]['name'].encode('iso-8859-1').strip() displayText = artistName + ' - ' + songName displayTextWidth = textWidth(displayText, fontSmall) durationMs = currentlyPlayingData['item']['duration_ms'] progressMs = currentlyPlayingData['progress_ms'] progressFetchMs = int(round(time.time() * 1000)) print displayText time.sleep(1) else: print currentlyPlayingData currentlyPlaying = False if currentlyPlayingData.get('token_expired', False) == True: accessToken = '' time.sleep(10) except Exception as e: logging.exception("Failed to fetch spotify data") time.sleep(10) accessToken = ''
class SomaListener(object): def __init__(self, username, station): if station not in STATIONS: raise UnknownStation self.station = station self.username = username self.db = Database(station) self.spotify = Spotify(username) def now_playing(self): return now_playing(self.station) def listen(self): previous = None while True: current = self.now_playing() self.spotify.re_authorize() if previous != current: print_track(current) self.store_track(current) previous = current else: sleep(60) continue def store_track(self, track): artist = track['artist'] title = track['title'] album = track['album'] db = self.db db.add_to_history(artist, title, album) if title is None or title == "": return if not db.track_exists(artist, title, album): added = self.spotify.add_track(self.station, artist, title, album) db.add_to_spotify(artist, title, album, added)
def post(self): verb = self.get_argument("verb") s = Spotify() if verb == "+": s.louder() elif verb == "-": s.quieter() else: s.tell(verb) self.redirect("/")
def start(self): if self.sp: self.sp.disconnect() self.sp = None self.sp = Spotify() self.ready_event = Event() self.messages = [] self.sp.on('error', self.on_error)\ .on('close', self.on_close) self.sp.login(self.host.username, self.host.password, self.on_login)
def main(argv): parser = setup_parser() args = parser.parse_args(argv[1:]) spotify = Spotify() spotify.authenticate() if not os.path.exists(args.out): os.makedirs(args.out) for track_list in spotify.get_user_tracks(): for track in track_list['items']: track = track['track'] artist = None title = None try: artist = to_ascii(track['artists'][0]['name'].encode('utf-8')) title = to_ascii(track['name'].encode('utf-8')) assert artist and title except Exception, e: logger.critical('FAIL/%s\n - %s', json.dumps(track, indent=4), e) raise e print json.dumps(track, indent=4) sys.exit(-1) name = '%s - %s.mp3' % (title, artist) out = os.path.join(args.out, '%s' % (name)) try: cmdline = 'youtube.py --artist="%s" --track="%s" --out="%s"' % (artist, title, out) logger.debug('Downloading %s' % (out)) youtube.main(shlex.split(cmdline)) logger.info('OK/%s' % (name)) except youtube.FileExistsException, e: logger.info('SKIP/%s - %s', name, e) except youtube.NoSearchResultException, e: logger.critical('FAIL/%s - %s', name, e)
def awakeFromNib(self): self.state = "album_browsing" self.selected_album = None self.selected_album_details = None self.track_names = [] self.img_cache = {} self.result = [] self.last_query = None # configuration self.config = {} config_path = abspath(expanduser("~/.minispot")) if isfile(config_path): with open(config_path) as conf_file: self.config = json.load(conf_file) else: with open(config_path, "w") as conf_file: json.dump(self.config, conf_file, indent=4) # ui setup self._initStatusBarItem() self._initTableView() NSApp.hide_(None) # spotify self.spotify = Spotify.alloc().init() logged_in = self.spotify.login_saved_credentials() if not logged_in: self.display_login_window() self.addObserver_forKeyPath_options_context_(self, "spotify.login_state", 0, None) self.addObserver_forKeyPath_options_context_(self, "spotify.current_track", 0, None) # hotkeys self.hotkey = hotkeys.register_key_from_string("alt+ctrl+f", self, "focusSearchWindow:") self.hotkey = hotkeys.register_key_from_string("alt+ctrl+x", self, "exit:") self.hotkey = hotkeys.register_key_from_string("alt+ctrl+n", self, "nextTrack:") self.hotkey = hotkeys.register_key_from_string("alt+ctrl+r", self, "previousTrack:") self.hotkey = hotkeys.register_key_from_string("alt+ctrl+p", self, "togglePause:")
def __init__(self, sp=Spotify): self.sp = Spotify()
class SimpleTrackConverter(object): def __init__(self, sp=Spotify): self.sp = Spotify() def line_to_song(self, line): """ Finds the tracks on Spotify that match the most words using the least amount of tracks. Parameters ---------- line: str A line or segment of words Returns ------- hit : Hit Best hit for the segment """ par = partition(line.split()) best_hit = Hit(0, [None], [line]) for p in par: matched_words = 0 sp_tracks = [] # group in partition for n in p: sp_track = self.sp.search_track(" ".join(n)) if sp_track: matched_words += len(n) sp_tracks.append(sp_track) # store the hit only if it is better if matched_words > best_hit.match_count: best_hit = Hit(matched_words, sp_tracks, [" ".join(n) for n in p]) # take the one using the least amount of tracks if the number of # matched words is equal if matched_words == best_hit.match_count: if len(sp_tracks) < best_hit.sp_tracks: best_hit = Hit(matched_words, sp_tracks, [" ".join(n) for n in p]) return best_hit def poem_to_song(self, text): """ Splits up the text at newlines, ',' '(' ')' and '-'. Parameters ---------- text: str A poem of possibly multiple lines Returns ------- hit : Hit Best hits for each segment of the text """ sentences = split_multiple(text, ["\n", ",", "(", ")", "-"]) logging.debug(sentences) hits = [] for s in sentences: hits.append(self.line_to_song(s)) return hits
def setup(self): self.spotify = Spotify() self.spotify.authenticate()
from spotify import Spotify from kkbox_parser import get_chart, test_url data = get_chart(test_url) sp = Spotify() f = open("jobs.txt", "r") jobs = f.readlines() for i in jobs: playlist, url = i.split(" ") data = get_chart(url) tracks = sp.search_tracks(data) old_tracks = sp.get_playlist_tracks(playlist) sp.removes_tracks(old_tracks, playlist) sp.add_tracks(tracks, playlist) sp.get_playlist_tracks(playlist)
class SpotifyClient(object): def __init__(self, host): self.host = host self.direct = Direct(self) self.server = None self.sp = None self.reconnect_time = None self.reconnect_timer = None self.ready_event = Event() self.messages = [] def start(self): if self.sp: self.sp.disconnect() self.sp = None self.sp = Spotify() self.ready_event = Event() self.messages = [] self.sp.on('error', self.on_error)\ .on('close', self.on_close) self.sp.login(self.host.username, self.host.password, self.on_login) def on_login(self): # Refresh server info self.host.refresh() # Release request hold self.ready_event.set() def on_error(self, message): self.messages.append((logging.ERROR, message)) Log.Error(message) def on_close(self, code, reason=None): # Force re-authentication self.sp.authenticated = False # Reconnect self.connect() def connect(self): # Rate-limit re-connections if self.reconnect_time: span = time.time() - self.reconnect_time Log.Debug('Last reconnection attempt was %s seconds ago', span) # Delay next reconnection if span < 120: self.connect_delayed() return Log.Info('Attempting reconnection to Spotify...') self.reconnect_time = time.time() # Hold requests while we re-connect self.ready_event = Event() # Start connecting... self.sp.connect() def connect_delayed(self): self.reconnect_timer = Timer(180, self.connect) self.reconnect_timer.start() Log.Info('Reconnection will be attempted again in 180 seconds') @property def constructed(self): return self.sp and self.ready_event @property def ready(self): if not self.constructed: return False return self.ready_event.wait(10) def shutdown(self): self.sp.api.shutdown() self.sp = None # # Public methods # def search(self, query, query_type='all', max_results=50, offset=0): """ Execute a search :param query: A query string. """ return self.sp.search(query, query_type, max_results, offset) def artist_uris(self, artist): top_tracks = self.artist_top_tracks(artist) # Top Track URIs track_uris = [] if top_tracks: track_uris = [tr.uri for tr in top_tracks.tracks if tr is not None] # Album URIs album_uris = [al.uri for al in artist.albums if al is not None] return track_uris, album_uris def artist_top_tracks(self, artist): for tt in artist.top_tracks: # TopTracks matches account region? if tt.country == self.sp.country: return tt # Unable to find TopTracks for account region return None # # Streaming # def track_url(self, track): if self.host.proxy_tracks and self.server: return self.server.get_track_url(str(track.uri), hostname=self.host.hostname) return function_path('play', uri=str(track.uri), ext='mp3') def stream_url(self, uri): if self.host.proxy_tracks and self.server: return self.server.get_track_url(str(uri), hostname=self.host.hostname) return self.direct.get(uri) def last_message(self): if not self.messages: return None, '' return self.messages[-1]
def get(self): s = Spotify() self.set_header("Content-Type", "image/jpeg") self.write(s.getArt())
def main(): # TODO(sedivy): Store user_id in a config file user_id = '11124246152' playlist_id = '3dDVf6yzpX5IQK2R7GtYcq' playlist = Manager.load_playlist(user_id=user_id, playlist_id=playlist_id) parser = argparse.ArgumentParser(description='Spotify command line') parser.add_argument('command', metavar='command', nargs='+', help='Command') args = parser.parse_args() command = args.command[0] arguments = ' '.join(args.command[1:]) spotify = Spotify() if command == 'list': playlist.print_songs() elif command == 'play': spotify.play_song_from_playlist(playlist.find(arguments), playlist) elif command == 'pause': spotify.pause() elif command == 'start': spotify.start() elif command == 'toggle': spotify.toggle() elif command == 'next_track': spotify.next_track() elif command == 'previous_track': spotify.previous_track() elif command == 'play_song': spotify.play_song(arguments) else: print('Undefined command "{}"'.format(command))