Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_fake_token_generator(self, monkeypatch):
spotify_tools.spotify = None
monkeypatch.setattr(spotify_tools, "generate_token", lambda: 123123)
with pytest.raises(spotipy.client.SpotifyException):
spotify_tools.generate_metadata("ncs - spectre")
def search(self, query, type='artist,track'):
try:
response = self._spotify().search(q='+'.join(query.split()), type=type, limit=self._limit)
except spotipy.client.SpotifyException:
print('Search went wrong? Please try again.')
return False
return response
if os.path.isfile(args.csv):
csvfile = args.csv
songs = get_songs_from_csvfile(csvfile, args)
download_songs(songs, folder)
else:
print 'No such csv file. Aborting..'
exit()
if args.username:
scope = 'playlist-read playlist-read-private'
token = util.prompt_for_user_token(args.username, scope)
if token:
sp = spotipy.Spotify(auth=token)
try:
playlists = sp.user_playlists(args.username)
except spotipy.client.SpotifyException:
print "Invalid Username"
exit()
if len(playlists) > 0:
print "All Playlists: "
for index, playlist in enumerate(playlists['items']):
print str(index + 1) + ": " + playlist['name']
n = raw_input("Enter S.N. of playlists (seprated by comma): ").split(",")
if n:
for i in xrange(0, len(n), 2):
playlist_folder = folder+"/"+playlists['items'][int(n[i]) - 1]['name']
print 'Storing files in', playlist_folder
if not os.path.isdir(playlist_folder):
try:
os.makedirs(playlist_folder )
except e:
print 'Error while creating folder'
out.write(
row["File"]
+ ";"
+ row["Artist"]
+ ";"
+ row["Title"]
+ ";"
+ "Not Found"
+ "\n"
)
except requests.exceptions.HTTPError as err:
print(err)
sys.exit(1)
except requests.ConnectionError as err:
print(err)
except spotipy.client.SpotifyException as sp:
print(sp)
f.close()
out.close()
print("Elapsed time: ", time() - start)
subprocess.call(["speech-dispatcher"]) # start speech dispatcher
subprocess.call(["spd-say", '"your process has finished"'])
def fetch_playlist(playlist):
try:
playlist_id = internals.extract_spotify_id(playlist)
except IndexError:
# Wrong format, in either case
log.error("The provided playlist URL is not in a recognized format!")
sys.exit(10)
try:
results = spotify.user_playlist(
user=None, playlist_id=playlist_id, fields="tracks,next,name"
)
except spotipy.client.SpotifyException:
log.error("Unable to find playlist")
log.info("Make sure the playlist is set to publicly visible and then try again")
sys.exit(11)
return results
def is_token_valid(self, token):
try:
spotify_client = spotipy.Spotify(auth=token)
spotify_client.current_user()
except spotipy.client.SpotifyException:
return False
return True
sp = tokenGen()
sp.trace = True
print(sp.currently_playing())
while True:
user = sp.currently_playing()
temp = user
try:
time.sleep(5)
user = sp.currently_playing()
if temp == user:
continue
else:
link = user['item']['album']['images'][0]['url']
os.system("gsettings set org.gnome.desktop.background picture-uri " + link)
time.sleep(5)
except spotipy.client.SpotifyException:
sp = tokenGen()
continue
length = 10
songs = []
if len(items) > 0:
spotify_list = choose_from_spotify_list(items, length=length)
list_type = spotify_list["type"]
name = spotify_list["name"]
if list_type != "playlist":
spotify_list = eval("spotify.%s" % list_type)(spotify_list["uri"])
else:
try:
spotify_list = spotify.user_playlist(spotify_list["owner"]["id"], \
playlist_id=spotify_list["uri"], fields="tracks,next")
except spotipy.client.SpotifyException:
fail_oauth()
print (bc.YELLOW + "\nFetching tracks and their metadata: " + bc.ENDC)
increment = 0
for song in spotify_list["tracks"]["items"]:
increment += 1
list_size = increment / len(spotify_list["tracks"]["items"])
drawProgressBar(list_size)
if list_type == "playlist":
song = song["track"]
artist = spotify.artist(song["artists"][0]["id"])
def wrapper(*args, **kwargs):
global spotify
try:
assert spotify
return func(*args, **kwargs)
except (AssertionError, spotipy.client.SpotifyException):
token = generate_token()
spotify = spotipy.Spotify(auth=token)
return func(*args, **kwargs)
lines = list(set(lines))
# ignore blank lines in text_file (if any)
try:
lines.remove('')
except ValueError:
pass
log.info(u'Preparing to download {} songs'.format(len(lines)))
downloaded_songs = []
for number, raw_song in enumerate(lines, 1):
print('')
try:
download_single(raw_song, number=number)
# token expires after 1 hour
except spotipy.client.SpotifyException:
# refresh token when it expires
log.debug('Token expired, generating new one and authorizing')
new_token = spotify_tools.generate_token()
spotify_tools.spotify = spotipy.Spotify(auth=new_token)
download_single(raw_song, number=number)
# detect network problems
except (urllib.request.URLError, TypeError, IOError):
lines.append(raw_song)
# remove the downloaded song from file
internals.trim_song(text_file)
# and append it at the end of file
with open(text_file, 'a') as myfile:
myfile.write(raw_song + '\n')
log.warning('Failed to download song. Will retry after other songs\n')
# wait 0.5 sec to avoid infinite looping
time.sleep(0.5)