def main(): print("Parsing rhythmbox playlists file") tree = ET.parse('/home/dodo/.local/share/rhythmbox/playlists.xml') root = tree.getroot() playlists = dict() print("Getting playlists from file") for child in root: if child.attrib['type'] == 'static': playlists[child.attrib['name']] = child print('Converte to ".xspf"') xspf_playlists = dict() for title, playlist in playlists.items(): x = xspf.Xspf() x.title = title print("* playlist: ", title) for location in playlist: x = addTrack(location.text, x) xspf_playlists[title] = x if not os.path.exists('out'): os.makedirs('out') print("Created 'out' dirrectory") print("Saving in out/ converted lpaylisns") for tltie, playlist in xspf_playlists.items(): file = open('out/' + tltie + '.xspf', 'wb') file.write(playlist.toXml().replace(b'\x00', b'')) file.close()
def testAddTrackByKwargs(self): """ Add a track via kwargs and check the XML """ x = xspf.Xspf(title="my title") x.add_track(title="title", creator="artist") expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><title>my title</title><trackList><track><title>title</title><creator>artist</creator></track></trackList></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False))
def testLink(self): """ Test adding a link tag """ x = xspf.Xspf() x.add_link("http://somehref/namespace", "http://somepath/here") expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><link rel="http://somehref/namespace">http://somepath/here</link></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False))
def testAddTrackByKwargs(self): """ Add a track via kwargs and check the XML """ x = xspf.Xspf(title="my title") x.add_track(title="title", creator="artist") expected = """<ns0:playlist version="1" xmlns:ns0="http://xspf.org/ns/0/"><ns0:title>my title</ns0:title><ns0:trackList><ns0:track><ns0:title>title</ns0:title><ns0:creator>artist</ns0:creator></ns0:track></ns0:trackList></ns0:playlist>""" self.assertEqual(expected, x.toXml())
def testDictTracks(self): """ Test that tracks from a dict work """ x = xspf.Xspf({"title": "atitle", "track": [{"title": "tr1"}, {"title": "tr2"}]}) self.assertEqual("atitle", x.title) self.assertEqual(2, len(x.track)) self.assertEqual("tr1", x.track[0].title) self.assertEqual("tr2", x.track[1].title)
def testAddTracks(self): """ Add more than 1 track at a time """ x = xspf.Xspf(title="my title") t = xspf.Track(title="t", creator="c") u = xspf.Track(title="u", creator="d") x.add_tracks([t, u]) self.assertEqual(2, len(x.track))
def makeplaylist(id): #TODO: change to universal endpoint # make a get request for the playlist with given playlist id r = requests.get('http://localhost:8000/api/v1/playlists?id=' + str(id)) if r.status_code == 200: r = r.json() # all info will be added onto this x = xspf.Xspf() #TODO: change to universal endpoint # request user info and check if it went through to get the userInfo = requests.get('http://localhost:8000/api/v1/users/' + str(r[0]['UserId'])) if userInfo.status_code == 200: userInfo = userInfo.json() x.creator = userInfo['Display_name'] x.info = userInfo['Homepage_url'] x.title = r[0]['PLaylistName'] # add tracks one by one, requesting # from endpoint: tracks and Track Descriptions for track in r: #TODO: change to universal endpoint # get tracks t = requests.get('http://localhost:8000/api/v1/tracks?id=' + str(track['TrackId'])).json() trackDesc = requests.get('http://localhost:8000/api/v1/users/' + str(track['UserId']) + '/tracks/' + str(track['TrackId']) + '/descriptions') #TODO: change to universal endpoint tr1 = xspf.Track() tr1.info = 'http://localhost:8000/api/v1/playlists?id=' + str(id) tr1.title = t['TrackName'] tr1.album = t['Album'] tr1.duration = str(t['Length']) tr1.location = t['Url'] tr1.image = t['Art'] tr1.creator = t['Artist'] if trackDesc.status_code == 200: trackDesc = trackDesc.json() tr1.annotation = trackDesc['Comment'] x.add_track(tr1) # make a filename to store the xml # using playlist title with spaces being replaced with '_' fileName = x.title + '.xspf' # make the file, and since the xml is rendered in bytes, # will have to store it as b, so "wb" fileName = fileName.replace(' ', '_') f = open('Playlists/' + fileName, "wb") f.write(x.toXml()) f.close() try: return send_file(os.path.join('Playlists', fileName), as_attachment=True) except Exception as e: return str(e) else: return {"info": "Does not exist"}, r.status_code
def generatePlaylist(): id = request.args.get('id') x = xspf.Xspf() client = base.Client(('localhost', 11211)) playlist = client.get('playlist.' + id) if playlist is None: playlist = requests.get('http://127.0.0.1:5300/v1/playlists/' + str(id)) playlist = playlist.json() # Cache the result for next time: client.set('playlist.' + id, playlist, expire=120) # cache for 2 minutes x.title = playlist.get('title') x.info = playlist.get('playlist_description') x.creator = playlist.get('creator') if (playlist.get('tracks')): tracks = playlist.get('tracks') for track in tracks: x.add_track(title=track.get('title'), creator=track.get('artist'), album=track.get('album_title'), location=track.get('media_url')) xml = x.toXml() return Response(xml, mimetype='audio/xspf')
def testAddTrackByDict(self): """ Add a track via a dictionary and check the XML """ x = xspf.Xspf(title="my title") t = xspf.Track() x.add_track({"title": "title", "creator": "artist"}) expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><title>my title</title><trackList><track><title>title</title><creator>artist</creator></track></trackList></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False))
def testAddTrackByDict(self): """ Add a track via a dictionary and check the XML """ x = xspf.Xspf(title="my title") t = xspf.Track() x.add_track({"title": "title", "creator": "artist"}) expected = """<ns0:playlist version="1" xmlns:ns0="http://xspf.org/ns/0/"><ns0:title>my title</ns0:title><ns0:trackList><ns0:track><ns0:title>title</ns0:title><ns0:creator>artist</ns0:creator></ns0:track></ns0:trackList></ns0:playlist>""" self.assertEqual(expected, x.toXml())
def playlists(id): #instantiating the client client = base.Client(('localhost', 11211)) #now client object started on port 11211 #store the key-value pair! result = client.get(id) #client.set(id, result) #if the cached object does not exist: if result is None: #make the HTTP request from the microservice and store the json response in Memcached with expiration time! result = do_playlist_query(id) print("first result:", result) #result key=value(result[username]=do_user_query) user_details = do_user_query(result['username']) result.update(user_details) trackList = result['track_list'] #loop to request track details(from desc service) of different tracks in the playlist for tracks in trackList: #calling the tracks service here: (directly from db) track_details = requests.get(tracks['trackurl']) track_details = track_details.json()[0] #for each track, calling the description service user_desc = requests.get( "http://127.0.0.1:9001/api/users/gettrackdesc/" + result['username'] + '/' + track_details['URL_media']) user_desc = user_desc.json() #track_details.update(user_desc) #store the JSON response in Memcached with expiration of atleast 60 sec print("Random: ", result) result.update(track_details) print("Random1 : ", result) client.append(id, result, 100) #print("the json objects are not properly appended!") #print("please check how I am appending the json objects to store in cache") #if the cached object exists: use its value(result) to construct the xspf! x = xspf.Xspf() print("please find the below result") print(result) #using result json object to construct the xspf x.title = result['playlist_title'] x.creator = result['full_name'] x.info = result['email'] # trackList=result['track_list'] print("below result") print(result) #each playlist of user has multiple tracks such as file1, file2, file3,file4.mp3 for track in trackList: tr1 = xspf.Track() tr1.title = result['track_title'] tr1.creator = result['artist'] tr1.duration = result['track_length'] tr1.album = result['album_title'] tr1.identifier = result['URL_media'] tr1.annotation = result['description'] x.add_track(tr1) y = x.toXml() return y, 200, {'Content-Type': 'application/xml; charset=utf-8'}
def playlists(id): #using requests module r = requests.get("http://localhost:8000/playlists/" + id) r = r.json() #using the xspf to convert in the XSPF format x = xspf.Xspf() x.title = r['playlist_title'] username = r['username'] user_details = requests.get("http://localhost:8000/users/" + username) user_details = user_details.json() #x.creator=user_details['full_name'] print(user_details) x.creator = user_details['full_name'] x.info = user_details['email'] #x.creator=user_details['homeurl'] trackList = r['track_list'] for tracks in trackList: track_details = requests.get(tracks['trackurl']) track_details = track_details.json()[0] print(track_details) print(track_details['track_title']) #requesting the description microservice to fetch the track's description user_desc = requests.get("http://localhost:8000/description/" + username + '/' + track_details['URL_media']) user_desc = user_desc.json() print(user_desc) #{'night.co3': {'description': 'My Favourite Track1'}} # y= user_desc[track_details['URL_media']] # x.annotation=y['description'] y = "http://localhost:9000/media/" + track_details['URL_media'] x.add_track( annotation=user_desc[track_details['URL_media']]['description'], title=track_details['track_title'], creator=track_details['artist'], duration=track_details['track_length'], album=track_details['album_title'], identifier=y) # {'id': 1, 'playlist_title': 'MyPlaylist', 'URL_list': '["Track1","Track2","Track3","Track4"]', 'username': '******', 'description': 'This Track is good'} print(x.toXml()) y = x.toXml() return y, 200, {'Content-Type': 'application/xml; charset=utf-8'}
def getPlaylistxspf(self,playlistName): global xspfAvailable if ( xspfAvailable ): x = xspf.Xspf() for playlist in self.il['Playlists']: if playlist['Name'] == playlistName: x.title = playlistName x.info = "" for track in playlist['Playlist Items']: id=int(track['Track ID']) x.add_track(title=self.songs[id].name, creator="",location=self.songs[id].location) return x.toXml() else: logger.warning("xspf library missing, go to https://github.com/alastair/xspf to install.") return None
def Convert_JsonToXSPF(json_value): json_value = json.loads(json_value) x = xspf.Xspf() x.title = json_value['title'] x.info = json_value['info'] x.creator = json_value['creator'] x.annotation = json_value['annotation'] for track_details in json_value['all_tracks']: x.add_track(title=track_details['title'], creator=track_details['creator'], location=track_details['location'], album=track_details['album'], annotation=track_details['annotation'], duration=track_details['duration'], image=track_details['image']) return str.encode('<?xml version="1.0" encoding="UTF-8"?>') + x.toXml()
def testMeta(self): """ Test that adding a meta tag works """ x = xspf.Xspf() x.add_meta("key", "value") expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><meta rel="key">value</meta></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False)) x.add_meta("secondkey", "secondvalue") expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><meta rel="key">value</meta><meta rel="secondkey">secondvalue</meta></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False)) m = x.meta self.assertEqual("value", m["key"]) self.assertEqual("secondvalue", m["secondkey"]) x.del_meta("key") expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><meta rel="secondkey">secondvalue</meta></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False))
def get_all_playlistbyid(playlist_id): try: url = 'http://127.0.0.1:5000/playlists/' + playlist_id headers = {'content-type': 'application/xspf+xml'} playlist_res = requests.get(url, headers=headers) json_object = playlist_res.json() print("playlist json:", json_object) if len(json_object) > 0: xmlObj = xspf.Xspf() xmlObj.title = json_object[0][1] xmlObj.creator = json_object[0][0] for list1 in json_object: track_id = list1[3] print("track_id:", track_id) track_url = 'http://127.0.0.1:5001/tracksbyid/' + str(track_id) track_headers = {'content-type': 'application/xspf+xml'} track_res = requests.get(track_url, headers=track_headers) track_jsonObj = track_res.json() print("track_jsonObj:", track_jsonObj) if len(track_jsonObj) > 0: for trackList in track_jsonObj: trackTitle = trackList["track_title"] trackCreator = trackList["track_artist"] track_node = xspf.Track(title=trackTitle, creator=trackCreator, album=trackList["album_title"]) track_node.trackNum = str(trackList["track_id"]) track_node.location = trackList["media_url"] track_node.duration = str(trackList["track_length"]) xmlObj.add_track(track_node) else: return { 'message': "Track not found" }, status.HTTP_404_NOT_FOUND except Exception as e: return {'error': str(e)}, status.HTTP_404_NOTFOUND return xmlObj.toXml(), status.HTTP_200_OK
def testKwargs(self): """ Test that all attribute names as kwargs works""" x = xspf.Xspf(title="my title", creator="creator", info="info", annotation="ann", location="location", identifier="id", image="image", date="date", license="license") self.assertEqual("my title", x.title) self.assertEqual("creator", x.creator) self.assertEqual("info", x.info) self.assertEqual("ann", x.annotation) self.assertEqual("location", x.location) self.assertEqual("id", x.identifier) self.assertEqual("image", x.image) self.assertEqual("date", x.date) self.assertEqual("license", x.license)
def makeXspfPlaylistFromList(array,FileName,PLAYLIST_DIRECTORY,VIDEOS_LOCATION): if(d): print "* makeXspfPlaylistFromList" x = xspf.Xspf(title="AWS", creator="thejsj") # Add First Track tr1 = xspf.Track() tr1.location = "file://" + os.path.join(VIDEOS_LOCATION, array[0][0]) x.add_track(tr1) # Mix up the array shuffleArray = [ i+1 for i,a in enumerate(array[1:])] random.shuffle(shuffleArray) for i,t in enumerate(array[1:]): tr1 = xspf.Track() tr1.location = "file://" + os.path.join(VIDEOS_LOCATION, array[shuffleArray[i]][0]) x.add_track(tr1) playlist_file = open(os.path.join(PLAYLIST_DIRECTORY,FileName),"w") playlist_file.write(x.toXml().replace("ns0:","")) playlist_file.close()
def getXSPFXml(json_object): print("In getXSPFXml()",json_object) #json_object = json_object.replace("b\\"," ") if len(json_object) > 0: xmlObj = xspf.Xspf() print("1:",json_object[0]) play_jsn = json_object[0] print("2:playlist_title:",play_jsn["playlist_title"]) xmlObj.title = play_jsn["playlist_title"] xmlObj.creator = play_jsn["user_name"] for list1 in json_object: track_title = list1["track_title"] print("3:track_title:",track_title) track_url = 'http://localhost:8000/tracks/'+str(track_title) track_headers = {'content-type': 'application/xspf+xml'} track_res = requests.get(track_url,headers=track_headers) track_jsonObj = track_res.json() print("4:track_jsonObj:",track_jsonObj) if len(track_jsonObj) > 0: track_jsn = track_jsonObj[0] print("5:track json:::",track_jsn) #for trackList in track_jsonObj: trackTitle = track_jsn["track_title"] trackCreator = track_jsn["track_artist"] track_node = xspf.Track(title=trackTitle, creator=trackCreator,album=track_jsn["album_title"]) track_node.trackNum = str(track_jsn["track_id"]) track_node.location = track_jsn["media_url"] track_node.duration = str(track_jsn["track_length"]) xmlObj.add_track(track_node) finalxml = xmlObj.toXml() #finalxml = finalxml.replace("b'"," ") print("End getXSPFXml() final xspf xml:",finalxml) return finalxml
def csv_to_xspf(csvloc, xspfloc): if not os.path.exists(csvloc): print usagerules print "csv location doesn't exist" return playlist = xspf.Xspf(title='GrooveShark Playlist') csvreader = unicode_csv_reader(open(csvloc)) csvreader.next() for row in csvreader: name, artist, album = row[0], row[1], row[2] # album is least likely to be clean or accurate - not included playlist.add_track(title=name, creator=artist) playlistxspf = playlist.toXml() with open(xspfloc, 'w') as xspffile: try: xspffile.write(playlistxspf) print "xspf saved at: " + str(xspfloc) except: print "unable to save xspf"
def testCreator(self): x = xspf.Xspf() x.creator = "creator" expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><creator>creator</creator></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False))
def testLocation(self): x = xspf.Xspf() x.location = "loc" expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><location>loc</location></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False))
def testDict(self): """ Test that attributes as a dictionary works """ x = xspf.Xspf({"title": "atitle", "creator": "alastair"}) self.assertEqual("atitle", x.title) self.assertEqual("alastair", x.creator)
def testLicense(self): x = xspf.Xspf() x.license = "CC BY-SA" expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><license>CC BY-SA</license></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False))
def testDate(self): x = xspf.Xspf() x.date = "date" expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><date>date</date></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False))
def testImage(self): x = xspf.Xspf() x.image = "image" expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><image>image</image></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False))
def testAnnotation(self): x = xspf.Xspf() x.annotation = "ann" expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><annotation>ann</annotation></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False))
from xml.etree import ElementTree from mutagen.easyid3 import EasyID3 conn = sqlite3.connect('songs.db') c = conn.cursor() sql_genre = 'select distinct genre from songs order by genre;' for row in c.execute(sql_genre): genre = row[0] t = (row[0], ) cg = conn.cursor() radio_file = open('Target/' + genre.replace('/', '') + '/' + 'radio.xml', 'w') sql_radio = "select filepath,filename,title,artist from songs where genre = ? and ( com = 'Mix' or com = 'Listen' or com = 'Radio' )" x = xspf.Xspf() x.title = "LetsDance " + genre + " playlist" for row_radio in cg.execute(sql_radio, t): title = row_radio[2] creator = row_radio[3] location = row_radio[0].replace('Target/', 'oc://') + '/' + row_radio[1] x.add_track({"title": title, "creator": creator, "location": location}) d = x.toXml().decode('utf-8') # xmldata = ElementTree.tostring(d,encoding="unicode") print(d) radio_file.write(d) cg.close() radio_file.close() cg = conn.cursor()
def testIdentifier(self): x = xspf.Xspf() x.identifier = "id" expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><identifier>id</identifier></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False))
def testInfo(self): x = xspf.Xspf() x.info = "info" expected = b"""<playlist xmlns="http://xspf.org/ns/0/" version="1"><info>info</info></playlist>""" self.assertEqual(expected, x.toXml(pretty_print=False))