예제 #1
0
    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()
예제 #2
0
파일: main.py 프로젝트: NavjotPanesar/skipr
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)
예제 #3
0
 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
예제 #4
0
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")
예제 #5
0
파일: main.py 프로젝트: shkhaksar/smd
 def __init__(self):
     self.__youtube = Youtube()
     self.__spotify = Spotify()
     self.__editor = TagEditor()
     self.__last = LastFM()
     self.__apple = AppleMusic()
     self.__deezer = Deezer()
예제 #6
0
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 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.")
예제 #8
0
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('/')
예제 #9
0
def main(options):
    options = process_options(options)

    gmusic = GMusic()
    spotify = Spotify(options.spotify_user_id)

    migrator = GMusicToSpotifyMigrator(gmusic, spotify)

    migrator.migrate()

    if options.output == 'text':
        not_found_tracks_count = len(migrator.tracks_not_found)
        print(f'not found {not_found_tracks_count} tracks:')
        print('\n\n')

        for not_found_track in migrator.tracks_not_found:
            print(not_found_track.get('track'))
            print(not_found_track.get('gmusic_link'))
            print(not_found_track.get('search_link'))

        print('\n\n')
        print('\n\n')
        print('\n\n')

        not_filtered_tracks_count = len(migrator.tracks_not_filtered)
        print(f'not filtered {not_filtered_tracks_count} tracks:')
        print('\n\n')

        for not_filtered_track in migrator.tracks_not_filtered:
            print(not_filtered_track.get('track'))

            for found_track_version in not_filtered_track.get('founds'):
                print(found_track_version)

        print('\n\n')
        print('\n\n')
        print('\n\n')

        migrated_tracks_count = len(migrator.tracks_found)
        print(f'migrated {migrated_tracks_count} tracks:')
        print('\n\n')

        for migrated_track in migrator.tracks_found:
            print(migrated_track.get('track'))
            print(migrated_track.get('gmusic_link'))
            print(migrated_track.get('spotify_link'))

    else:
        output = {
            'migrated_tracks': migrator.tracks_found,
            'not_found_tracks': migrator.tracks_not_found,
            'not_filtered_tracks': migrator.tracks_not_filtered
        }

        print(output)
    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! --------"
        )
예제 #11
0
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')
예제 #12
0
    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)}
예제 #13
0
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)
예제 #14
0
 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
예제 #15
0
def main():
    options = parse_args()

    r = Reddit(options.subreddit)

    info('Fecthing threads from Reddit')
    top_titles = r.top(options.period, options.limit)
    entities = [Entity(title) for title in top_titles]
    info('Found {} threads'.format(len(entities)))
    
    for entity in entities:
        try:
            entity.search_term = search_term_from_title(entity.reddit_title)
        except:
            error('Failed to convert Reddit title "{}" to a search term'.format(title))

    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
예제 #16
0
    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"]}')
예제 #17
0
def spotify_actor(actor, say):
    mpd = Spotify()
    actor.add_keyword(_('listen to playlist'),
                      SpotifyCommand(say, mpd, _('Listen to playlist')))
    actor.add_keyword(_('pause'), SpotifyCommand(say, mpd, 'pause'))
    actor.add_keyword(_('refresh spotify'),
                      SpotifyCommand(say, mpd, 'refresh'))
    actor.add_keyword(_('shut up'), SpotifyCommand(say, mpd, 'pause'))
    actor.add_keyword(_('resume'), SpotifyCommand(say, mpd, 'resume'))
    actor.add_keyword(_('next song'), SpotifyCommand(say, mpd, 'next'))
    actor.add_keyword(_('what songs'), SpotifyCommand(say, mpd, 'playlists'))
    actor.add_keyword(_('listen to music'),
                      SpotifyCommand(say, mpd, _('Listen to music')))
예제 #18
0
    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')
예제 #19
0
def spotify_api():
    '''
        Attempting to use the 'Spotify-api' API wrapper
    '''
    credentials = Client(c.sp_client_id, c.sp_client_secret)

    print(credentials)
    spfy = Spotify(credentials)
    print(spfy)

    search_result = spotify.search('shadows', ['track'])

    for trach in search_result:
        print(track.name)
예제 #20
0
    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)
예제 #21
0
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.')
예제 #22
0
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)
예제 #23
0
    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)}
예제 #24
0
async def sync(token: str,
               reader: StreamReader,
               writer: StreamWriter,
               lock: Lock,
               *,
               server: bool = False) -> None:
    connector = aiohttp.TCPConnector(resolver=aiohttp.AsyncResolver())
    async with aiohttp.ClientSession(connector=connector) as session:
        spot = Spotify(session, token)
        context = Context(lock, server=server)
        await asyncio.wait([
            publish(writer, spot, context) if server else subscribe(
                reader, spot, context)
        ],
                           return_when=asyncio.FIRST_COMPLETED)
예제 #25
0
    def __init__(self):
        try:
            self.spotify = Spotify()
        except requests.exceptions.ConnectionError:
            send_notif('Spotify Helper closed',
                       'Check you have a working internet connection.')
            sys.exit(1)

        self.currently_pressed_keys = list()
        self.looking_for = {}
        self.has_released_key = True

        self.load_bindings_from_file(bindings_file)
        self.atomic_method_groups = SpotifyHelper.get_atomic_method_groups()
        self.method_group_thread_queues = self.get_method_group_thread_queues()
예제 #26
0
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')
예제 #27
0
def update_playlists():
  users = users_db.get_all()
  for user in users:
    access_token = Spotify.update_token(user['refresh_token'])['access_token']
    spotify = Spotify(user['spotify_id'], access_token)
    for playlist in user['playlists']:
      new_tracks = spotify.get_track_uris(playlist['original_id'], since=playlist['last_checked'])
      users_db.playlist_updated(user['spotify_id'], playlist['id'])
      i = 0
      split = new_tracks[0:100]
      while len(split) > 0:
        spotify.add_tracks(playlist['id'], split)
        i += 1
        split = new_tracks[(i * 100):(i * 100 + 100)]
  return 'OK', 200
예제 #28
0
    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)
예제 #29
0
    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)
예제 #30
0
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