def run(): xdg_config_home = os.getenv("XDG_CONFIG_HOME") if xdg_config_home: config_dir = Path(xdg_config_home) else: config_dir = Path.home() / '.config' config_file = config_dir / 'undercurrent.conf' config = configparser.ConfigParser() config.read(config_file) if not config.has_section('tidal_auth'): print('Missing tidal auth') exit() tidal_config = tidalapi.Config(quality=tidalapi.Quality.lossless) tidal = tidalapi.Session(config=tidal_config) tidal.login(config.get('tidal_auth', 'user'), config.get('tidal_auth', 'pass')) gui = PlayerGUI(tidal) player = Player(tidal, gui) gui.set_player(player) playlists = tidal.user.playlists() for pl in playlists: gui.add_playlist(pl) gui.run()
def main(): session = tidalapi.Session() login(session) track_queue = Queue() print("enter number based off of wanted track ",end="") print("append A if you want to append to end of ",end="") print("playlist, or P to play single time") if __name__ == '__main__': p = Process(target=server,args=(track_queue,)) p.start() while True: search_result = query(session) print_result(search_result) selection = input("Selection requested") selection = selection.lower().strip("abcdefghijklmnopqrstuvwxyz.,;'[] ") num = int(selection) - 1 track_queue.put("rtmp://"+session.get_media_url(search_result.tracks[num].id))
def Getmusic(request): print('hello view') session = tidalapi.Session() session.login('username', 'password') tracks = session.get_album_tracks(album_id=16909093) for track in tracks: print(track.name)
def on_toggle_authorize_account(self, event): if config.app["services"]["tidal"]["access_token"] != "" and config.app[ "services"]["tidal"]["refresh_token"] != "": config.app["services"]["tidal"]["access_token"] = "" config.app["services"]["tidal"]["refresh_token"] = "" config.app["services"]["tidal"]["token_type"] = "" config.app["services"]["tidal"]["session_id"] = "" config.app.write() self.account_button.SetLabel(_("Authorize account")) return wx.MessageDialog( self, _("Your Tidal account has been removed from MusicDL successfully." ), _("Account removed")).ShowModal() dlg = wx.MessageDialog( self, _("In order to use Tidal on MusicDL, you need to authorise your account. You will need to log-in in your web browser and grant access to the application. After doing that, you will be able to come back here and continue using the app. Would you like to authorize your account?" ), _("Account authorization"), wx.YES_NO | wx.ICON_QUESTION) if dlg.ShowModal() == wx.ID_YES: session = tidalapi.Session() login_link, future = session.login_oauth() # Sometimes, Tidal just returns the domain name of the URL without a procotol. if not "http" in login_link.verification_uri_complete: url = "https://{}".format(login_link.verification_uri_complete) else: url = login_link.vericication_uri_complete webbrowser.open_new_tab(url) threading.Thread(target=self._manage_authorization, args=[session, future]).start()
def connect_to_tidal(tidal_username, tidal_pwd): tidal_session = tidalapi.Session() try: tidal_session.login(tidal_username, tidal_pwd) except requests.exceptions.HTTPError as e: print("Can't login to tidal for username="******", password=" + tidal_pwd) sys.exit() return tidal_session
def connect_tidal(): session = tidalapi.Session() try: session.login(tidal_username, tidal_password) except: print("Unable to login to Tidal for username="******", password="******"Successfully logged into Tidal account " + tidal_username) return session
def open_tidal_session(config): quality_mapping = { 'low': tidalapi.Quality.low, 'high': tidalapi.Quality.high, 'lossless': tidalapi.Quality.lossless } quality = quality_mapping[config.get('quality', 'high').lower()] session = tidalapi.Session(tidalapi.Config(quality=quality)) session.login(config['username'], config['password']) return session
def test_load_session(session): """ Test loading a session from a session id without supplying country code and user_id """ user_id = session.user.id country_code = session.country_code session_id = session.session_id session = tidalapi.Session() session.load_session(session_id) assert user_id == session.user.id assert country_code == session.country_code
def _connect(self, username, password): """Connect to tidal and return a session object. Parameters ---------- username: str Tidal username password: str Tidal password """ tidal_session = tidalapi.Session() tidal_session.login(username, password) return tidal_session
def get_playlist(): session = tidalapi.Session() session.login("*****@*****.**", "raforafo11241124") tracks = session.get_playlist_tracks(playlist_id="6f9bc48e-b3cf-494f-931d-0fdc15b27707") tracks_obj = [] for track in tracks: tracks_obj.append({"name": track.name, "artist": track.artist.name}) with open("playlist.list", 'w+') as playlist: playlist.write(json.dumps(tracks_obj))
def maybelogin(a={}): global session global quality global httphp global pathprefix global is_logged_in # Do this always setidprefix(tidalidprefix) if is_logged_in: return True if "UPMPD_HTTPHOSTPORT" not in os.environ: raise Exception("No UPMPD_HTTPHOSTPORT in environment") httphp = os.environ["UPMPD_HTTPHOSTPORT"] if "UPMPD_PATHPREFIX" not in os.environ: raise Exception("No UPMPD_PATHPREFIX in environment") pathprefix = os.environ["UPMPD_PATHPREFIX"] if "UPMPD_CONFIG" not in os.environ: raise Exception("No UPMPD_CONFIG in environment") upconfig = conftree.ConfSimple(os.environ["UPMPD_CONFIG"]) if 'user' in a: username = a['user'] password = a['password'] else: username, password = getserviceuserpass(upconfig, 'tidal') if not username or not password: raise Exception("tidaluser and/or tidalpass not set in configuration") qalstr = upconfig.get('tidalquality') if qalstr == 'lossless': quality = Quality.lossless elif qalstr == 'high': quality = Quality.high elif qalstr == 'low': quality = Quality.low elif not qalstr: quality = Quality.high else: raise Exception("Bad tidal quality string in config. " + "Must be lossless/high/low") tidalconf = tidalapi.Config(quality) session = tidalapi.Session(config=tidalconf) session.login(username, password) is_logged_in = True if quality == Quality.lossless: setMimeAndSamplerate('audio/flac', "44100") else: setMimeAndSamplerate('audio/mpeg', "44100")
def tidal_to_dict(url): #generate a dictionary of artists, tracks, and images given a Tidal url cred = Credentials() session = tidalapi.Session() plid = urlsplit(url) print(cred.secret_key) session.login(cred.tidal_username, cred.tidal_password) retdict = {'Tracks' : [], 'Images' : []} playlist = session.get_playlist(plid) retdict['Name'] = playlist.name retdict['Description'] = playlist.description for item in session.get_playlist_tracks(plid): retdict['Tracks'].append("|Track|: " + item.name + ' |Artist|: ' + item.artist.name + ' |URL|: ' + item.album.name) retdict['Images'].append(item.album.image) return(retdict)
def create_session(self): self.settings.validate() session_config = tdl.Config(self.settings.get("quality")) session = tdl.Session(session_config) try: session.login( self.settings.get_username(self.ui.uname_input, self.ui.yesno_prompt), self.settings.get_password(self.ui.pass_input, self.ui.yesno_prompt)) if session.check_login() == False: self.ui.error("Invalid Login Credentials", exit=True) except: self.ui.error("Error Creating Login Session", exit=True) return session
def add_tidal(spotify_tracks): session = tidalapi.Session() session.login(tidal_login, tidal_password) user = tidalapi.User(session, session.user.id) for spotify_track in spotify_tracks: found = False tidal_results = session.search('track', spotify_track, limit=15) print(bcolors.OKBLUE + "SPOTIFY SONG: " + spotify_track + " - " + spotify_tracks[spotify_track]) if len(tidal_results.tracks) > 0: count = 1 print(bcolors.HEADER + "TIDAL RESULTS:") for tidal_track in tidal_results.tracks: print(bcolors.HEADER + " " + str(count) + ". " + tidal_track.name + " - " + tidal_track.artist.name) count = count + 1 else: print(bcolors.FAIL + "NOT FOUND \n") print(bcolors.HEADER + "---------------------------------------- \n") found = True for tidal_track in tidal_results.tracks: if tidal_track.artist.name == spotify_tracks[spotify_track]: print(bcolors.OKGREEN + "ONE MATCH > " + tidal_track.name + " - " + tidal_track.artist.name) print(bcolors.HEADER + "---------------------------------------- \n") try: time.sleep(10) print(bcolors.HEADER + "ADDING TRACK") user.favorites.add_track(tidal_track.id) print(bcolors.OKGREEN + "DONE") except: print(bcolors.FAIL + "FAIL") found = True break if not found: print(bcolors.FAIL + "NO ONE MATCH \n") print(bcolors.HEADER + "---------------------------------------- \n")
def __init__(self): parser = argparse.ArgumentParser( description= 'Scrapes metadata from tidal and writes it to the tags or as nfo') parser.add_argument('username', help="The username") parser.add_argument('password', help="The password") parser.add_argument('command', choices=Type.__members__) args = parser.parse_args(sys.argv[1:4]) if not hasattr(self, args.command): print("Unrecognized command") parser.print_help() exit(1) self.tidal = tidalapi.Session() self.tidal.login(args.username, args.password) getattr(self, args.command)()
def setup(self): # Assign quality or switch to high if not specified/not found. if hasattr(tidalapi.Quality, config.app["services"]["tidal"]["quality"]): quality = getattr(tidalapi.Quality, config.app["services"]["tidal"]["quality"]) else: quality = tidalapi.Quality.high # We need to instantiate a config object to pass quality settings. _config = tidalapi.Config(quality=quality) session_id = config.app["services"]["tidal"]["session_id"] token_type = config.app["services"]["tidal"]["token_type"] access_token = config.app["services"]["tidal"]["access_token"] refresh_token = config.app["services"]["tidal"]["refresh_token"] log.debug("Using quality: %s" % (quality, )) self.session = tidalapi.Session(config=_config) self.session.load_oauth_session(session_id, token_type, access_token, refresh_token)
def main(args): args_parsed = parse_args(args) session = tidalapi.Session() if args_parsed.ini is not None: config = ConfigParser() config.read([args_parsed.ini]) try: session.load_oauth_session( config['session']['id'], config['session']['token_type'], config['session']['access_token'], config['session'].get('refresh_token', None)) except KeyError: print('supplied configuration to restore session is incomplete') else: if not session.check_login(): print('loaded session appears to be not authenticated') if not session.check_login(): print('authenticating new session') session.login_oauth_simple() print('To load the session next time you run this program, ' 'supply the following information via an INI file:') print() print(f'[session]') print(f'id = {session.session_id }') print(f'token_type = {session.token_type}') print(f'access_token = {session.access_token}') print(f'refresh_token = {session.refresh_token}') print() if args_parsed.backup: backup(session, args_parsed.filename or 'tidal_favorites.json') if args_parsed.restore: restore(session, args_parsed.filename or 'tidal_favorites.json')
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim:fileencoding=utf-8 import tidalapi from transliterate import translit import os from mutagen.flac import Picture, FLAC from requests import get session = tidalapi.Session(tidalapi.Config('LOSSLESS')) session._config.api_token='MbjR4DLXz1ghC4rV' session.login('YOUR TIDAL LOGIN', 'YOUR TIDAL PASSWORD') def start(): if not os.path.exists("music/"): os.mkdir("music/") mode = raw_input("Mode: \n 1) Playlist grabber\n 2) Track grabber\n 3) Album grabber\n 4) Search \n") if int(mode) == 1: playlist_id = raw_input("Enter playlist id: ") try: playlist = session.get_playlist_tracks(playlist_id=playlist_id) can_download = 1 except Exception: print("Playlist not found.") can_download = 0 if can_download == 1: for track in playlist:
soundcloud_id = os.environ.get('CX_SOUNDCLOUD') pandora_id = os.environ.get('CX_PANDORA') play_id = os.environ.get('CX_PLAY_MUSIC') credentials = oauth2.SpotifyClientCredentials( client_id=spotify_id, client_secret=spotify_secret) token = credentials.get_access_token() spotify = spotipy.Spotify(auth=token) lastfm = pylast.LastFMNetwork(api_key=lastfm_id, api_secret=lastfm_secret) deezerClient = deezer.Client() tidal = tidalapi.Session() tidal.login(tidal_id, tidal_secret) pp = pprint.PrettyPrinter(indent=4) def google_search(search_term, api_key, cse_id, **kwargs): service = build("customsearch", "v1", developerKey=api_key) res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute() return res @app.route('/', methods=['GET', 'POST']) def homepage(): error = None
def get_session(): try: session = tidalapi.Session() except HTTPError, e: raise Exception(e)
def session(): session = tidalapi.Session() username = os.getenv("TIDAL_USERNAME") password = os.getenv("TIDAL_PASSWORD") session.login(username, password) return session
#!/usr/bin/env python # -*- coding: utf-8 -*- import tidalapi import argparse import urllib2 import os from mutagen.flac import FLAC config = tidalapi.Config(quality=tidalapi.Quality.lossless) session = tidalapi.Session(config=config) session.login("*****@*****.**", "ozturk.99") def downloadFile(url, path, fileName): u = urllib2.urlopen(url) meta = u.info() contentLength = meta.getheaders("Content-Length") if len(contentLength): fileSize = int(contentLength[0]) else: fileSize = 1 print "Downloading: %s Bytes: %s" % (fileName.encode("utf8"), fileSize) if not os.path.exists(path.encode("utf8")): os.makedirs(path.encode("utf8")) fileName = os.path.join( path, fileName) if os.path.isfile(fileName.encode("utf8")): return f = open(fileName.encode("utf8"), 'wb') fileDownloaded = 0 blockSize = 8192 while True:
def session(): session = tidalapi.Session() session.country_code = session.local_country_code() # Trial Mode without login ! # session.login('username', 'password') return session
def __init__(self, keys): self.session = tidalapi.Session() self.session.login(keys.passes['tidal_username'], keys.passes['tidal_password'])
import csv import sys import pprint import time import tidalapi TIDAL_USERNAME = '' TIDAL_PASSWORD = '' artist_names = [] file = open("artists.txt", "r", encoding="utf8") for line in file: artist_names.append(line.rstrip()) session = tidalapi.Session() session.login(TIDAL_USERNAME, TIDAL_PASSWORD) favorites = tidalapi.Favorites(session, session.user.id) for artist_name in artist_names: artist_data = session.search('artist', artist_name) if len(artist_data.artists) == 0: print( 'WARNING: No artist found for {}, continuing'.format(artist_name)) continue favorites.add_artist(artist_data.artists[0].id) print('Added {}'.format(artist_name)) time.sleep(2)
def main(): # Initialize TIDAL session using credentials defined in .env print('Logging into TIDAL session...') session = tidalapi.Session() session.login(TIDAL_EMAIL, TIDAL_PASS) if session.check_login(): print(f'Successfully logged into TIDAL as {TIDAL_EMAIL}') else: print('Uh oh! Error logging in to TIDAL.') exit() # Authenticate Spotify and get access token spotify_user_id = auth_spotify() print(f"Successfully logged into Spotify as {spotify_user_id}") # Queries user for valid TIDAL playlist URL print_hdiv() while True: tidal_url = input('Enter TIDAL playlist URL: ') tidal_playlist_id = tidal_url[34:] try: tidal_playlist = session.get_playlist(tidal_playlist_id) tidal_playlist_items = session.get_playlist_items( tidal_playlist_id) break except requests.exceptions.HTTPError: print('Invalid TIDAL playlist URL.') print('TIDAL Playlist Information:') print_tidal_playlist(tidal_playlist, tidal_playlist_items) print_hdiv() # Ask user if they would like to create a Spotify playlist under the same name while True: same_name = input( f'Would you like create the Spotify playlist under the same TIDAL playlist name \'{tidal_playlist.name}\' (y/n)? ' ) if same_name.lower() == 'y': spotify_playlist_name = tidal_playlist.name break elif same_name.lower() == 'n': spotify_playlist_name = input( 'Enter your desired new Spotify playlist name: ') break # Check if user already has a Spotify playlist under the inputted playlist name spotify_playlists = get_users_spotify_playlists() i = 0 while i < len(spotify_playlists): if spotify_playlist_name == spotify_playlists[i]: print( f'A Spotify playlist named \'{spotify_playlist_name}\' already exists under your user!' ) spotify_playlist_name = input( 'Please enter a playlist name that does not already exist: ') i = 0 else: i += 1 # Create new Spotify playlist as inputted name. print( f'Creating a new Spotify playlist named \'{spotify_playlist_name}\'...' ) payload = { 'name': spotify_playlist_name, 'public': True, 'collaborative': False, 'description': tidal_playlist.description } spotify_playlist = requests.post( f'https://api.spotify.com/v1/users/{spotify_user_id}/playlists', headers={ 'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/json' }, data=json.dumps(payload)).json() print(f'Successfully created Spotify playlist \'{spotify_playlist_name}\'') # Search Spotify for tracks in TIDAL playlist print('Adding tracks from TIDAL playlist to Spotify playlist...') spotify_uris = [] tracks_not_added = [] for item in tidal_playlist_items: try: # If Spotify track found, add Spotify URI to spotify_uris. item_name = item.name # Remove part of track name with '(feat. ...)' or '[feat. ...]' - can break Spotify search functionality if ' (feat. ' in item_name: item_name = item_name[:item_name.find(' (feat. ')] + item_name[ item_name.find(')', item_name.find(' (feat. ')) + 1:] elif ' [feat. ' in item_name: item_name = item_name[:item_name.find(' [feat. ')] + item_name[ item_name.find(']', item_name.find(' [feat. ')) + 1:] results = search_spotify(item_name + ' ' + item.artist.name) spotify_uris.append(results['tracks']['items'][0]['uri']) except IndexError: # If not, add TIDAL track to tracks_not_added. tracks_not_added.append(item.name + ' by ' + item.artist.name) # Add Spotify tracks from spotify_uris to Spotify playlist requests.post( f"https://api.spotify.com/v1/playlists/{spotify_playlist['id']}/tracks", headers={ 'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/json' }, data=json.dumps(spotify_uris)) # Print completed status with number of tracks added and contents of tracks_not_added print( f'Successfully added {len(spotify_uris)} track(s) to Spotify playlist \'{spotify_playlist_name}\'.' ) print(f'{len(tracks_not_added)} track(s) could not be found on Spotify.') if len(tracks_not_added) > 0: print('TIDAL tracks not found on Spotify:') for track in tracks_not_added: print(' ' + track) # Open Spotify playlist in web browser webbrowser.open(spotify_playlist['external_urls']['spotify'])
def open_tidal_session(config): session = tidalapi.Session() session.login(config['username'], config['password']) return session
def dict_to_tidal(username, password, url,service): #take in a dict from another service, add tracks to favorites idlist = [] misses = [] apple = service == 'apple' spotify = service == 'spotify' if apple: import app.appcrawl try: indict = app.appcrawl.get_artists_tracks(url) except: yield "data:ERROR\n\n" #yield error, stop program, user imput wrong URL return None elif spotify: import app.spotifyapi try: indict = app.spotifyapi.get_artists_tracks(url) except: yield "data:ERROR\n\n" #yield error, stop program, user imput wrong URL return None else: yield "data:ERROR\n\n" #yield error, stop program, something wrong on my end return None session = tidalapi.Session() #create Tidal session session.login(username, password) favs = tidalapi.Favorites(session,session.user.id) yield "data: 20\n\n" #about 20% done displaypercent = 20 exactpercent = 20.0 length = len(indict['Tracks']) for item in indict['Tracks']: #begin adding songs ids to be added to favs artistname = item[(item.find('|Artist|:') + 10):item.find(' |URL|:')] #search queries trackname = item[(item.find('|Track|:') + 9):item.find('|Artist|:')] query = trackname + artistname query = query.replace(" "," ") retquery = artistname + ' - ' + trackname searches = session.search('track', query) miss = True for thing in searches.tracks: if thing.artist.name.lower() == artistname.lower(): idlist.append(str(thing.id)) #add id miss = False break else: #search again using different queries if '-' in trackname: searches = session.search('track', trackname[:trackname.find('-')] + artistname) for stuff in searches.tracks: if stuff.artist.name.lower() == artistname.lower(): idlist.append(str(stuff.id)) miss = False break if miss and " & " in artistname or ("(" in trackname and ")" in trackname): secartist = artistname sectrack = trackname if " & " in artistname: secartist = artistname[:artistname.find(" & ")] if ',' in secartist: secartist = secartist[:secartist.find(",")] if "(" in trackname and ")" in trackname: sectrack = removeParen(trackname) if "[" in trackname and "]" in trackname: sectrack = removeBrack(trackname) secquery = sectrack + secartist secquery = secquery.replace(" "," ") searchsec = session.search('track', secquery ) for stuff in searchsec.tracks: if stuff.artist.name.lower() == secartist.lower(): idlist.append(str(stuff.id)) miss = False break if '*' in trackname: trackname = uncensor(trackname) query = trackname + artistname query = query.replace(" "," ") searches = session.search('track', query) for stuff in searches.tracks: if stuff.artist.name.lower() == artistname.lower(): idlist.append(str(stuff.id)) miss = False break if miss: #add all missed songs to a list misses.append(retquery) exactpercent = ((50) / length) + exactpercent displaypercent = int(exactpercent) if displaypercent > 70: displaypercent = 70 yield "data:" +str(displaypercent) + "\n\n" #about 70% done idlength = len(idlist) for item in reversed(idlist): #reverse; Tidal adds songs backwards try: track_to_favs(item, favs) #add track except: yield "data: ERROR\n\n" exactpercent = ((30) / idlength) + exactpercent displaypercent = int(exactpercent) if displaypercent > 100: displaypercent = 100 #we're done yield "data:" +str(displaypercent) + "\n\n" yield "data:100\n\n" urlstring = 'https://listen.tidal.com/my-music/tracks' yield "data:URL"+urlstring+"\n\n" #link to URL for item in misses: yield "data:MISS"+item+"\n\n" yield "data:NAME"+indict['Name']+"\n\n" yield "data:COMPLETE\n\n"
def session(): return tidalapi.Session()