def get_track(provider_id): t = Track() try: ######MediaNet###### # reqUrl = 'http://ie-api.mndigital.com?method=track.get&format=json&'\ # + urllib.urlencode({'mnetid': provider_id})\ # + '&ApiKey=%s' % MusicProvider._mnDigitalIntegrationAPIKey reqUrl = "http://itunes.apple.com/lookup?" + urllib.urlencode({"id": provider_id}) # track_json = common.get_json(reqUrl)["Track"] track_json = common.get_json(reqUrl)["results"][0] t.provider_id = provider_id t.length_seconds = 0 t.url = "" # t.artist = track_json["Artist"]["Name"] # t.title = track_json["Title"] # t.length_friendly = track_json["Duration"] # t.album = track_json["Album"]["Title"] # t.art_url = track_json["Album"]["Images"]["Album150x150"] t.artist = track_json["artistName"] t.title = track_json["trackName"] t.length_friendly = "" t.album = track_json["collectionName"] t.art_url = track_json["artworkUrl100"] except Exception: pass return t
def create_track_from_uri(self, uri): if 'youtube' not in uri: return None m = re.search('http://www.youtube.com/get_video.video_id=(.*?)&t=(.*)',uri) client = gdata.youtube.service.YouTubeService() client.ssl = False entry = client.GetYouTubeVideoEntry(video_id=m.group(1)) logging.debug("Created track from uri %s in youtubesource", uri) #PrintEntryDetails(entry) swfuri = entry.GetSwfUrl() video_id = m.group(1) t = m.group(2) track = Track(uri) track.title = entry.media.title.text track.artist = "YOUTUBE VIDEO" track.album = entry.media.category[0].text #FIXME add search for author on album? track.album_uri = None track.duration = int(entry.media.duration.seconds)*1000 return track
def create_track_from_uri(self, uri): uri = SpotifySource.strip_protocol(uri) if uri == None: return None url = "http://ws.spotify.com/lookup/1/?uri=" + uri try: e = ET.parse(urllib.urlopen(url)) except Exception as e: return None ns = "http://www.spotify.com/ns/music/1" if 'album' in uri: title = "" artist = e.find('.//{%s}artist/{%s}name' % (ns, ns)).text album = e.find('.//{%s}name' % ns).text duration = 0 album_uri = uri else: title = e.find('.//{%s}name' % ns).text artist = e.find('.//{%s}artist/{%s}name' % (ns, ns)).text album = e.find('.//{%s}album/{%s}name' % (ns, ns)).text duration = int(float(e.find('.//{%s}length' % ns).text) * 1000) album_uri = "spotify://" + e.find('.//{%s}album' % ns).attrib['href'] track = Track("spotify://"+uri) track.title = title track.artist = artist track.album = album track.album_uri = album_uri track.duration = duration return track
def create_track_from_uri(self, uri): if 'asx' not in uri: return None logging.debug("Created track from uri %s in srradiosource", uri) u = urllib.urlopen(uri) str = re.search('\"mms:.+\"', u.read()) u = open("sr.xml") tree = ET.parse(u) u.close() track = Track(str.group(0)[1:-1]) for e in tree.findall('channel'): for k in e.findall('streamingurl'): for s in k.findall('url'): if uri in s.text: track.title = e.get('name') track.artist = "SR RADIOTRACK" track.album = "SR RADIOTRACK" track.album_uri = None track.duration = 1 return track
def trackFromResult(resultTrack): localTrack = Track() localTrack.title = resultTrack.name localTrack.artist = resultTrack.artists[0].name localTrack.album = resultTrack.album.name time = resultTrack.length / 1000 localTrack.timeAudio = str(int(time / 60)) + ":" + '%02d' % int(time % 60) image = m.library.get_images([resultTrack.album.uri]) localTrack.imageURI = image[resultTrack.album.uri][0].uri return localTrack
def create_tracks_from_album(self, album): tracks = [] for track in album['tracks']: tmptrack = Track(track['uri']) tmptrack.title = track['title'] tmptrack.artist = track['artist'] tmptrack.album = album['name'] tmptrack.album_uri = album['uri'] tmptrack.duration = track['duration'] tracks.append(tmptrack) return tracks
def index(self, path): for top, dirnames, filenames in os.walk(path): for filename in filenames: if filename.endswith('.mp3'): full_path = os.path.join(top, filename); f = tagpy.FileRef(full_path) t = Track("file://" + full_path) t.title = f.tag().title t.artist = f.tag().artist t.album = f.tag().album a = f.audioProperties() t.duration = a.length * 1000 # to msec self.add_track(t)
def search(self, criteria): print(f'searching Spotify with criteria of {criteria}') results = self.sp.search(q=criteria, limit=1) for i, t in enumerate(results['tracks']['items']): track = Track() track.title = t['name'] track.number = pad_track_number(t['track_number']) album_id = t['album']['id'] album = self.get_album_old(album_id) track.artist = album.artist track.album = album.title track.year = album.year track.genres = album.genres return track
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 indexFromFile(self): self.file = open(os.getcwd() + '/options/index.txt', 'r') path = None line = self.file.readline() while line != '': code = line[0:2] if code == "NP": path = line[2:-1] line = self.file.readline() t = Track() t.path = path + "/" + line[0:-1] t.artist = self.file.readline()[0:-1] t.title = self.file.readline()[0:-1] t.album = self.file.readline()[0:-1] self.tracks.append(t) self.gui.addTrack(t) line = self.file.readline() self.file.close() self.gui.loading_finished()
def getAllUploadedTracks(): tracksSet = OrderedSet() if not os.path.exists("library_cache.json") or \ ("--rebuild-cache" in sys.argv or "-rc" in sys.argv): print("Fetching list of uploaded songs. For a lot of songs, this may take a long time...") tracks = ytmusic.get_library_upload_songs(limit=100000) for yttrack in tracks: track = Track() if yttrack["artists"]: track.artist = yttrack["artists"][0]["name"].strip() if yttrack["album"]: track.album = yttrack["album"]["name"].strip() track.title = yttrack["title"].strip() track.entityId = yttrack["entityId"] tracksSet.add(track) dumpToCache(tracksSet) else: print("using library_cache.json") tracksSet = loadCache() return tracksSet
def create_track_from_uri(self, uri): url = "http://ws.spotify.com/lookup/1/?uri=" + uri try: e = ET.parse(urllib.urlopen(url)) except Exception as e: return None ns = "http://www.spotify.com/ns/music/1" title = e.find('.//{%s}name' % ns).text artist = e.find('.//{%s}artist/{%s}name' % (ns, ns)).text album = e.find('.//{%s}album/{%s}name' % (ns, ns)).text duration = int(float(e.find('.//{%s}length' % ns).text) * 1000) track = Track("spotify://"+uri) track.title = title track.artist = artist track.album = album track.duration = duration return track
def main(args): ''' Main method ''' if len(args) < 4: 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] days_to_add = 0 if len(args) > 4: days_to_add = args[4] #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 start = datetime.datetime.strptime(start_date, '%Y-%m-%dT%H:%M:%SZ') end = datetime.datetime.strptime(end_date, '%Y-%m-%dT%H:%M:%SZ') temp_tracks = [] if days_to_add > 0: days_count = 0 while days_count <= days_to_add: #Walk back for each day day_start = start + timedelta(days=-days_count) day_end = end + timedelta(days=-days_count) #Go to the end date and then come back #This is a terrible method but I have not figured out how the KEXP API really works yet uri = 'https://legacy-api.kexp.org/play/?limit=200&end_time=' + day_end.strftime("%Y-%m-%dT%H:%M:%SZ") + '&ordering=-airdate' temp_tracks.extend(get_tracks(uri, day_start, day_end)) days_count += 1 else: #Go to the end date and then come back #This is a terrible method but I have not figured out how the KEXP API really works yet uri = 'https://legacy-api.kexp.org/play/?limit=200&end_time=' + end.strftime("%Y-%m-%dT%H:%M:%SZ") + '&ordering=-airdate' temp_tracks = get_tracks(uri, start, end) 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 getAllLocalTracks(): print("Reading tags from local files...") folders = [] tracks = OrderedSet() with open("folders.json", "r") as foldersJson: folders = json.loads(foldersJson.read())["folders"] for folder in folders: for root, subdirs, files in os.walk(folder): for filename in files: filePath = os.path.join(root, filename) _filename, fileExtension = os.path.splitext(filename) fileExtension = fileExtension.lower() if fileExtension in SUPPORTED_EXTS: try: metadata = mutagen.File(filePath) except mutagen.MutagenError as e: print(f"{filename}: {e}") continue if not metadata: print("no tags for " + filePath) continue artist = None album = None title = None if (fileExtension == ".flac" or fileExtension == ".ogg"): if metadata.get("artist"): artist = metadata.get("artist")[0] elif metadata.get("albumartist"): artist = metadata.get("albumartist")[0] if metadata.get("album"): album = metadata.get("album")[0] if metadata.get("title"): title = metadata.get("title")[0] elif fileExtension == ".mp3": if metadata.get("TPE1"): artist = metadata.get("TPE1")[0] elif metadata.get("TPE2"): artist = metadata.get("TPE2")[0] if metadata.get("TALB"): album = metadata.get("TALB")[0] if metadata.get("TIT2"): title = metadata.get("TIT2")[0] elif fileExtension == ".m4a": if metadata.get("\xa9ART"): artist = metadata.get("\xa9ART")[0] elif metadata.get("aART"): artist = metadata.get("aART")[0] if metadata.get("\xa9alb"): album = metadata.get("\xa9alb")[0] if metadata.get("\xa9nam"): title = metadata.get("\xa9nam")[0] elif fileExtension == ".wma": if metadata.get("Author"): artist = metadata.get("Author")[0].value elif metadata.get("WM/Composer"): artist = metadata.get("WM/Composer")[0].value if metadata.get("WM/AlbumTitle"): album = metadata.get("WM/AlbumTitle")[0].value if metadata.get("Title"): title = metadata.get("Title")[0].value if artist: artist = artist.strip() if ", " in artist: splits = [] for split in artist.split(", "): splits.append(split.strip()) artist = ", ".join(splits) if album: album = album.strip() if title: title = title.strip() if not title: print("no tags for " + filePath) else: track = Track() track.artist = artist track.album = album track.title = title track.filePath = filePath tracks.add(track) return tracks
def start(self): print(f'Beginning file system crawling process....') finished = [] all_artists = os.listdir(self.base_path) for artist_name in all_artists: print(f'Processing artist: {artist_name}') artist_path = os.path.join(self.base_path, artist_name) if os.path.isdir(artist_path): # we have found a folder corresponding to an artist artist = Artist(path=artist_path) artist.name = artist_name all_material = os.listdir(artist_path) for item in all_material: item_path = os.path.join(artist_path, item) if os.path.isdir(item_path): # we have found a folder corresponding to an album album = Album(path=item_path) album.artist = artist.name album.title = item artist.albums.append(album) album_contents = os.listdir(item_path) for content in album_contents: content_path = os.path.join(item_path, content) if os.path.isdir(content_path): disc_contents = os.listdir(content_path) for disc_item in disc_contents: disc_item_path = os.path.join( content_path, disc_item) if os.path.isdir(disc_item_path): print( f'{disc_item}: Processing a directory at this level is currently unsupported' ) else: if content.endswith( ".mp3") or content.endswith( ".wma"): track = Track(path=content_path) track.artist = artist.name track.title = util.clean_file_name( content) track.number = util.get_track_number_from_file_name( content) # get disc number from folder name track.disc_number = 1 # a disc object needs created and the track added to the disc # album.tracks.append(track) else: print( f'{content}: Processing a file type other than mp3 at this level is currently unsupported' ) # TODO: This must be a multi-disc set print( f'{content} is actually another directory') else: if content.endswith( ".mp3") or content.endswith(".wma"): track = Track(path=content_path) track.artist = artist.name track.title = util.clean_file_name(content) track.number = util.get_track_number_from_file_name( content) album.tracks.append(track) else: print( f'{content}: Processing a file type other than mp3 at this level is currently unsupported' ) else: # we have potentially found a track that isn't associated with an album if item.endswith(".mp3"): track = Track(path=item_path) track.artist = artist.name track.title = util.clean_file_name(item) track.number = util.get_track_number_from_file_name( item) artist.songs.append(track) else: print( f'{item}: Processing a file type other than mp3 at this level is currently unsupported' ) finished.append(artist) else: print( f'{artist_name}: Processing a file at this level in the file system is currently unsupported' ) for artist in finished: print(artist.pretty_print(include_paths=True))