Exemple #1
0
 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
Exemple #3
0
    def testMeta(self):
        """ Test that adding a meta tag works """

        root = ET.Element("{http://xspf.org/ns/0/}x")
        t = xspf.Track()
        t.add_meta("key", "value")

        res = t.getXmlObject(root)
        expected = b"""<x xmlns="http://xspf.org/ns/0/"><track><meta rel="key">value</meta></track></x>"""
        xml = ET.tostring(res, "utf-8")
        self.assertEqual(expected, xml)

        t.add_meta("secondkey", "secondvalue")
        root = ET.Element("{http://xspf.org/ns/0/}x")
        res = t.getXmlObject(root)
        expected = b"""<x xmlns="http://xspf.org/ns/0/"><track><meta rel="key">value</meta><meta rel="secondkey">secondvalue</meta></track></x>"""
        xml = ET.tostring(res, "utf-8")
        self.assertEqual(expected, xml)

        m = t.meta
        self.assertEqual("value", m["key"])
        self.assertEqual("secondvalue", m["secondkey"])

        t.del_meta("key")
        root = ET.Element("{http://xspf.org/ns/0/}x")
        res = t.getXmlObject(root)
        expected = b"""<x xmlns="http://xspf.org/ns/0/"><track><meta rel="secondkey">secondvalue</meta></track></x>"""
        xml = ET.tostring(res, "utf-8")
        self.assertEqual(expected, xml)
Exemple #4
0
 def testAlbum(self):
     root = ET.Element("{http://xspf.org/ns/0/}x")
     t = xspf.Track()
     t.album = "album"
     root = t.getXmlObject(root)
     expected = """<ns0:x xmlns:ns0="http://xspf.org/ns/0/"><ns0:track><ns0:album>album</ns0:album></ns0:track></ns0:x>"""
     xml = ET.tostring(root, "utf-8")
     self.assertEqual(expected, xml)
Exemple #5
0
 def testInfo(self):
     root = ET.Element("{http://xspf.org/ns/0/}x")
     t = xspf.Track()
     t.info = "info"
     root = t.getXmlObject(root)
     expected = """<ns0:x xmlns:ns0="http://xspf.org/ns/0/"><ns0:track><ns0:info>info</ns0:info></ns0:track></ns0:x>"""
     xml = ET.tostring(root, "utf-8")
     self.assertEqual(expected, xml)
Exemple #6
0
 def testAnnotation(self):
     root = ET.Element("{http://xspf.org/ns/0/}x")
     t = xspf.Track()
     t.annotation = "ann"
     root = t.getXmlObject(root)
     expected = """<ns0:x xmlns:ns0="http://xspf.org/ns/0/"><ns0:track><ns0:annotation>ann</ns0:annotation></ns0:track></ns0:x>"""
     xml = ET.tostring(root, "utf-8")
     self.assertEqual(expected, xml)
Exemple #7
0
 def testTitle(self):
     root = ET.Element("{http://xspf.org/ns/0/}x")
     t = xspf.Track()
     t.title = "title"
     root = t.getXmlObject(root)
     expected = """<ns0:x xmlns:ns0="http://xspf.org/ns/0/"><ns0:track><ns0:title>title</ns0:title></ns0:track></ns0:x>"""
     xml = ET.tostring(root, "utf-8")
     self.assertEqual(expected, xml)
Exemple #8
0
    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())
Exemple #9
0
 def testIdentifier(self):
     root = ET.Element("{http://xspf.org/ns/0/}x")
     t = xspf.Track()
     t.identifier = "id"
     root = t.getXmlObject(root)
     expected = b"""<x xmlns="http://xspf.org/ns/0/"><track><identifier>id</identifier></track></x>"""
     xml = ET.tostring(root, "utf-8")
     self.assertEqual(expected, xml)
Exemple #10
0
    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))
Exemple #11
0
 def testImage(self):
     root = ET.Element("{http://xspf.org/ns/0/}x")
     t = xspf.Track()
     t.image = "image"
     root = t.getXmlObject(root)
     expected = b"""<x xmlns="http://xspf.org/ns/0/"><track><image>image</image></track></x>"""
     xml = ET.tostring(root, "utf-8")
     self.assertEqual(expected, xml)
 def to_playlist (self, playlist):
     for r in self:
         t = xspf.Track()
         t.location = r['location']
         t.duration = r['duration']
         t.title = r['title']
         t.creator = r['artist']
         playlist.tracks.append (t)
Exemple #13
0
 def tesCreator(self):
     root = ET.Element("{http://xspf.org/ns/0/}x")
     t = xspf.Track()
     t.creator = "creator"
     root = t.getXmlObject(root)
     expected = b"""<x xmlns="http://xspf.org/ns/0/"><track><creator>creator</creator></track></x>"""
     xml = ET.tostring(root, "utf-8")
     self.assertEqual(expected, xml)
Exemple #14
0
 def testTrackNum(self):
     root = ET.Element("{http://xspf.org/ns/0/}x")
     t = xspf.Track()
     t.trackNum = "1"
     root = t.getXmlObject(root)
     expected = b"""<x xmlns="http://xspf.org/ns/0/"><track><trackNum>1</trackNum></track></x>"""
     xml = ET.tostring(root, "utf-8")
     self.assertEqual(expected, xml)
Exemple #15
0
 def testDuration(self):
     root = ET.Element("{http://xspf.org/ns/0/}x")
     t = xspf.Track()
     t.duration = "1000"
     root = t.getXmlObject(root)
     expected = b"""<x xmlns="http://xspf.org/ns/0/"><track><duration>1000</duration></track></x>"""
     xml = ET.tostring(root, "utf-8")
     self.assertEqual(expected, xml)
 def testLocations(self):
     root = ET.Element("{http://xspf.org/ns/0/}x")
     t = xspf.Track()
     t.location = ["location1", "location2", "location3"]
     root = t.getXmlObject(root)
     expected = b"""<x xmlns="http://xspf.org/ns/0/"><track><location>location1</location><location>location2</location><location>location3</location></track></x>"""
     xml = ET.tostring(root, "utf-8")
     self.assertEqual(expected, xml)
Exemple #17
0
    def testLink(self):
        root = ET.Element("{http://xspf.org/ns/0/}x")
        t = xspf.Track()
        t.add_link("http://somehref/namespace", "http://somepath/here")

        res = t.getXmlObject(root)
        expected = b"""<x xmlns="http://xspf.org/ns/0/"><track><link rel="http://somehref/namespace">http://somepath/here</link></track></x>"""
        xml = ET.tostring(res, "utf-8")
        self.assertEqual(expected, xml)
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 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 addTrack(location, playlist):
    location_r = unquote(location.replace('file://', ''))
    try:

        mp3 = MP3File(location_r)
        tags = mp3.get_tags()
        tr = xspf.Track()
        tr.location = location

        if 'song' in tags['ID3TagV2'].keys():
            tr.title = tags['ID3TagV2']['song']
        if 'artist' in tags['ID3TagV2'].keys():
            tr.creator = tags['ID3TagV2']['artist']
        if 'album' in tags['ID3TagV2'].keys():
            tr.album = tags['ID3TagV2']['album']
        playlist.add_track(tr)
    except Exception as e:
        print('FileNotFoundError: ', location_r)

    return playlist
Exemple #21
0
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
Exemple #22
0
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
Exemple #23
0
    def testKwargs(self):
        """ Test that all attribute names as kwargs works"""
        t = xspf.Track(location="loc",
                       identifier="id",
                       title="atitle",
                       creator="cre",
                       annotation="annotation",
                       info="info",
                       image="image",
                       album="analbum",
                       trackNum="1",
                       duration="1000")

        self.assertEqual("loc", t.location)
        self.assertEqual("id", t.identifier)
        self.assertEqual("atitle", t.title)
        self.assertEqual("cre", t.creator)
        self.assertEqual("annotation", t.annotation)
        self.assertEqual("info", t.info)
        self.assertEqual("image", t.image)
        self.assertEqual("analbum", t.album)
        self.assertEqual("1", t.trackNum)
        self.assertEqual("1000", t.duration)
Exemple #24
0
parser.add_argument("playlist_id", help="the gs playlist id to export")
args = parser.parse_args()

client = gs.Client()
client.init()

try:
    playlist = client.playlist(args.playlist_id)
except:
    print("Parsing playlist %s failed, does it exist?", args.playlist_id)


def u(s):
    return unicode(s)


x = xspf.Xspf()
x.title = u(playlist.name)
x.info = 'From Grooveshark playlist %s' % (args.playlist_id)
x.image = playlist._cover_url

for song in playlist.songs:
    x.add_track(
        xspf.Track(title=u(song.name),
                   creator=u(song.artist),
                   album=u(song.album),
                   trackNum=song.track,
                   image=song.album._cover_url))

print(x.toXml())
def create_spiff():
    query_parameters = request.args
    playlist_id = query_parameters.get('playlist_id')

    if playlist_id is None:
        return page_not_found(404)

    #payload = {'playlist_id':playlist_id}

    # GET INFO OF PLAYLIST INTO THE XSPF PLAYLIST
    # This will hold the json containing playlist_id, playlist_title, description, username_id
    #playlist = requests.get("http://localhost:8000/playlists?playlist_id=", params=payload)
    playlist = requests.get("http://localhost:8000/playlists?playlist_id=" +
                            playlist_id)
    #playlist.json()
    #fetched_playlist_data = json.loads(playlist.json())

    #fetched_playlist_data = playlist.json()
    with open('debugging.txt', 'a') as f:
        f.write('\nplaylist:\n')
        f.write(str(playlist.json()[0]))
    # Set the xspf playlist params with data from requests
    x.title = str(playlist.json()[0]['playlist_title'])
    x.annotation = str(playlist.json()[0]['description'])
    x.creator = str(playlist.json()[0]['username_id'])
    x.identifier = str(playlist.json()[0]['playlist_id'])
    # x.title = fetched_playlist_data.playlist_title
    # x.annotation = fetched_playlist_data.description
    # x.creator = fetched_playlist_data.username_id

    #x.identifier = fetched_playlist_data['playlist_id']
    # x.title = fetched_playlist_data.playlist_title
    # x.annotation = fetched_playlist_data.description
    # x.creator = fetched_playlist_data.username_id
    # x.identifier = playlist["playlist_id"]
    # x.title = playlist["playlist_title"]
    # x.annotation = playlist["description"]
    # x.creator = playlist["username_id"]
    #
    # ADD TRACKS TO THE PLAYLIST
    # Look for track_ids that has the same playlist_id from the query
    query = "SELECT track_id FROM Tracks_List WHERE"
    to_filter = []

    if playlist_id:
        query += ' playlist_id=? AND'
        to_filter.append(playlist_id)

    if playlist_id is None:
        return page_not_found(404)

    # This holds the sql command to query for all of the track_ids in the Tracks_List
    query = query[:-4] + ';'

    # results now has all of the track_ids(songs) in this playlist
    #results = query_db(query, to_filter)

    response = query_db(query, to_filter)
    with open('debugging.txt', 'a') as f:
        f.write('\nresponse:\n')
        f.write(str(response))

    # Put all of these tracks in the xspf playlist
    for tracks in query_db(query, to_filter):
        # query the tracks service for the info of the track which returns a json
        trackidizzle = tracks['track_id']
        # trackidizzle = uuid.UUID(tracks['track_id'])
        with open('debugging.txt', 'a') as f:
            f.write('\ntrackidizzle:\n')
            f.write(str(trackidizzle))
        track_fetched = requests.get("http://localhost:8000/tracks?track_id=" +
                                     str(trackidizzle)).json()

        with open('debugging.txt', 'a') as f:
            f.write('tracks:\n')
            f.write(str(tracks))
            f.write('\ntracks_fetched:\n')
            f.write(str(track_fetched))
            f.write('\n')
        # Create a new track object
        track = xspf.Track()
        track.identifier = str(trackidizzle)
        track.title = str(track_fetched['track_title'])
        track.album = str(track_fetched['album_title'])
        track.creator = str(track_fetched['artist'])
        track.duration = str(track_fetched['length_seconds'])
        track.location = str(track_fetched['url_media'])
        track.image = str(track_fetched['url_art'])
        x.add_track(track)

        # track.identifier = track_fetched.track_id
        # track.title = track_fetched.track_title
        # track.album = track_fetched.album_title
        # track.creator = track_fetched.artist
        # track.duration = track_fetched.length_seconds
        # track.link = track_fetched.url_media
        # track.image = track_fetched.url_art
    # query = "SELECT track_id FROM Tracks_List WHERE playlist_id=" + playlist_id
    # result = g.db.execute(query)
    # found = result.fetchall()
    #
    # for track in found:
    #     track_fetched = requests.get("http://localhost:8000/tracks?track_id=" + track[0])
    #     track.identifier = track_fetched.track_id
    #     track.title = track_fetched.track_title
    #     track.album = track_fetched.album_title
    #     track.creator = track_fetched.artist
    #     track.duration = track_fetched.length_seconds
    #     track.location = track_fetched.url_media
    #     track.image = track_fetched.url_art
    # track.identifier = track_fetched["track_id"]
    # track.title = track_fetched["track_title"]
    # track.album = track_fetched["album_title"]
    # track.creator = track_fetched["artist"]
    # track.duration = track_fetched["length_seconds"]
    # track.location = track_fetched["url_media"]
    # track.image = track_fetched["url_art"]

    #return make_response(jsonify(playlist.json()))
    #return make_response(playlist.tostring())
    #return make_response(jsonify(playlist))
    #return make_response(x.toXml(pretty_print=true))
    #return make_response(jsonify(x.toXml()))
    return Response(x.toXml(), mimetype='application/xspf+xml')
Exemple #26
0
def create_spiff():
    query_parameters = request.args
    playlist_id = query_parameters.get('playlist_id')

    if playlist_id is None:
        return page_not_found(404)

    #payload = {'playlist_id':playlist_id}

    # GET INFO OF PLAYLIST INTO THE XSPF PLAYLIST
    # This will hold the json containing playlist_id, playlist_title, description, username_id
    #playlist = requests.get("http://localhost:8000/playlists?playlist_id=", params=payload)

    # Since we are using memcache, we check memcache before doing any get requests
    # is a playlist with this id already cached?
    client = Client(('localhost', 11211))
    # serializer=json_serializer, deserializer=json_deserializer
    cached_playlist = None
    try:
        cached_playlist = json.loads(client.get(playlist_id))
        with open('cached.txt', 'a') as f:
            f.write('obj retrieved from cache:' + '\n')
            f.write(str(cached_playlist) + '\n')
    except TypeError:
        with open('cached.txt', 'a') as f:
            f.write(str(cached_playlist) + '\n')

    # Initialize playlist variable here
    playlist = None

    # if cached_playlist returns None, we do have to fetch the playlist
    if cached_playlist == None:
        playlist = requests.get(
            "http://localhost:8000/playlists?playlist_id=" +
            playlist_id).json()
        with open('cached.txt', 'a') as f:
            f.write('obj retrieved VIA GET REQUEST FROM PLAYLIST ROUTE:' +
                    '\n')
            f.write(json.dumps(playlist) + '\n')
        # since the playlist is not cached, we cache it for 120 seconds
        client.set(str(playlist_id), json.dumps(playlist), expire=120)
    else:
        # the playlist was cached!  So assign it.
        playlist = cached_playlist

    #playlist.json()
    #fetched_playlist_data = json.loads(playlist.json())
    with open('cached.txt', 'a') as f:
        f.write('playlist.decode ' + '\n')
        f.write(str(type(playlist)))
    #fetched_playlist_data = playlist.json()

    # Set the xspf playlist params with data from requests
    x.title = playlist[0]['playlist_title']
    x.annotation = playlist[0]['description']
    x.creator = playlist[0]['username_id']
    x.identifier = str(playlist[0]['playlist_id'])
    # x.title = fetched_playlist_data.playlist_title
    # x.annotation = fetched_playlist_data.description
    # x.creator = fetched_playlist_data.username_id

    #x.identifier = fetched_playlist_data['playlist_id']
    # x.title = fetched_playlist_data.playlist_title
    # x.annotation = fetched_playlist_data.description
    # x.creator = fetched_playlist_data.username_id
    # x.identifier = playlist["playlist_id"]
    # x.title = playlist["playlist_title"]
    # x.annotation = playlist["description"]
    # x.creator = playlist["username_id"]
    #
    # ADD TRACKS TO THE PLAYLIST
    # Look for track_ids that has the same playlist_id from the query
    query = "SELECT track_id FROM Tracks_List WHERE"
    to_filter = []

    if playlist_id:
        query += ' playlist_id=? AND'
        to_filter.append(playlist_id)

    if playlist_id is None:
        return page_not_found(404)

    # This holds the sql command to query for all of the track_ids in the Tracks_List
    query = query[:-4] + ';'

    # results now has all of the track_ids(songs) in this playlist
    #results = query_db(query, to_filter)

    # THIS query_db WAS FOR TESTING PURPOSES
    response = query_db(query, to_filter)
    with open('debugging.txt', 'a') as f:
        f.write('\nresponse:\n')
        f.write(str(response))

    # Put all of these tracks in the xspf playlist
    for tracks in query_db(query, to_filter):
        # query the tracks service for the info of the track which returns a json
        trackidizzle = tracks['track_id']
        # trackidizzle = uuid.UUID(tracks['track_id'])
        with open('debugging.txt', 'a') as f:
            f.write('\ntrackidizzle:\n')
            f.write(str(trackidizzle))

        track_fetched = None
        # lets check memcached first to see if the track with the given track id (trackidizzle) exists
        try:
            track_fetched = json.loads(client.get(str(trackidizzle)))
            with open('trackidizzledebug.txt', 'a') as f:
                f.write('\nFetched the following track from memcached:\n')
                f.write(str(track_fetched))
        except TypeError as e:
            with open('trackidizzledebug.txt', 'a') as f:
                f.write(
                    '\nError fetching track from memcached or doesnt exist:\n')
                f.write(str(trackidizzle))

        if track_fetched == None:
            with open('trackidizzledebug.txt', 'a') as f:
                f.write('\nPerforming GET REQUEST TO FETCH TRACK:\n')
                track_fetched = requests.get(
                    "http://localhost:8000/tracks?track_id=" +
                    str(trackidizzle)).json()
                client.set(str(trackidizzle),
                           json.dumps(track_fetched),
                           expire=120)
                f.write('Track fetched:\n')
                f.write(str(track_fetched))

        with open('debugging.txt', 'a') as f:
            f.write('tracks:\n')
            f.write(str(tracks))
            f.write('\ntracks_fetched:\n')
            f.write(str(track_fetched))
            f.write('\n')
        # Create a new track object
        track = xspf.Track()
        track.identifier = str(trackidizzle)
        track.title = str(track_fetched['track_title'])
        track.album = str(track_fetched['album_title'])
        track.creator = str(track_fetched['artist'])
        track.duration = str(track_fetched['length_seconds'])
        track.location = str(track_fetched['url_media'])
        track.image = str(track_fetched['url_art'])
        x.add_track(track)

        # track.identifier = track_fetched.track_id
        # track.title = track_fetched.track_title
        # track.album = track_fetched.album_title
        # track.creator = track_fetched.artist
        # track.duration = track_fetched.length_seconds
        # track.link = track_fetched.url_media
        # track.image = track_fetched.url_art
    # query = "SELECT track_id FROM Tracks_List WHERE playlist_id=" + playlist_id
    # result = g.db.execute(query)
    # found = result.fetchall()
    #
    # for track in found:
    #     track_fetched = requests.get("http://localhost:8000/tracks?track_id=" + track[0])
    #     track.identifier = track_fetched.track_id
    #     track.title = track_fetched.track_title
    #     track.album = track_fetched.album_title
    #     track.creator = track_fetched.artist
    #     track.duration = track_fetched.length_seconds
    #     track.location = track_fetched.url_media
    #     track.image = track_fetched.url_art
    # track.identifier = track_fetched["track_id"]
    # track.title = track_fetched["track_title"]
    # track.album = track_fetched["album_title"]
    # track.creator = track_fetched["artist"]
    # track.duration = track_fetched["length_seconds"]
    # track.location = track_fetched["url_media"]
    # track.image = track_fetched["url_art"]

    # This is if you want to do both
    # with open('myPlaylist.xspf', 'a') as f:
    #     f.write(str(x.toXml()))

    #return make_response(jsonify(playlist.json()))
    #return make_response(playlist.tostring())
    #return make_response(jsonify(playlist))
    #return make_response(x.toXml(pretty_print=true))

    # This is when you just want to display the xml spiff file on the browser
    #return make_response(jsonify(x.toXml()))

    # This is when you want an xspf(html) file downloaded
    return Response(x.toXml(), mimetype='application/xspf+xml')
def makeplaylist(id):
    # Check cache for playlist
    result = client.get(str(id))
    # If cache value exists
    if result is not None:
        print(result)
        result = result.decode('utf-8')
        result = result.replace("\'", "\"")
        # result = json.dumps(result)
        result = json.loads(result)
        print(result)

            # construct XSPF repsonse
        x = xspf.Xspf()
        x.creator = result['Display_name']
        x.info = result['Homepage_url']
        x.title = result['PLaylistName']
        for track in result['Tracks']:
            a_track = xspf.Track()
            a_track.info = 'http://localhost:8000/api/v1/playlists?id='+str(id)
            a_track.title = track['TrackName']
            a_track.album = track['Album']
            a_track.duration = str(track['Length'])
            a_track.location = track['Url']
            a_track.image = track['Art']
            a_track.creator = track['Artist']
            try:
                a_track.annotation = track['Comment']
            except Exception as e:
                a_track.annotation = ""
            x.add_track(a_track)
        fileName = x.title + '.xspf'
        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)

    # If cache value does not exist
    elif result is None:
        #TODO: change to universal endpoint
        # make a get request for the playlist with given playlist id
        r = requests.get('http://localhost:5200/api/v1/playlists?id='+str(id))
        if r.status_code == 200:
            json_obj = {"Tracks": []}
            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:5000/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']
                    json_obj["Display_name"] = userInfo['Display_name']
                    json_obj["Homepage_url"] = "userInfo[Homepage_url]"

            x.title = r[0]['PLaylistName']
            json_obj["PLaylistName"] = 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:5300/api/v1/tracks?id='+str(track['TrackId'])).json()
                trackDesc = requests.get('http://localhost:5100/api/v1/users/'+str(track['UserId'])+'/tracks/'+str(track['TrackId'])+'/descriptions')

                #TODO: change to universal endpoint
                t = {
                "TrackName": t['TrackName'],
                "Album": t['Album'],
                "Length": str(t['Length']),
                "Url": t['Url'],
                "Art": t['Art'],
                "Artist": t['Artist'],
                "Comment": ""
                }
                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']
                    t["Comment"] = trackDesc['Comment']

                x.add_track(tr1)
                # tr = merge(t, trackDesc)
                json_obj["Tracks"].append(t)

            # 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()

            client.set(str(id), json_obj)
            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
Exemple #28
0
 def testDict(self):
     """ Test that attributes as a dictionary works """
     t = xspf.Track({"title": "atitle", "creator": "alastair"})
     self.assertEqual("atitle", t.title)
     self.assertEqual("alastair", t.creator)