Пример #1
0
def search(song):
    song = song.replace(';', '')
    song = song.replace('&', '')
    song = song.replace('With Lyrics', '')
    song = song.replace('(Official Video)', '')
    song = song.replace('(Official Music Video)', '')
    song = song.replace('[Official Video]', '')
    song = song.replace('[Official Music Video]', '')
    song = song.replace('-', '')

    spotify_request = requests.get('http://ws.spotify.com/search/1/track?q=%s' % song)
    spotify_root = ET.fromstring(spotify_request.content) #parse the xml out so we can do things with it
    spotify_song = ''
    spotify_attrib =''
    if spotify_root[1].text != '0':
        spotify_attrib = spotify_root[4].attrib #this looks like {'href': 'spotify:track:5TdAgcKS5HlxMcclStHODW'}
        spotify_attrib = spotify_attrib["href"]
        spotify_song = spotify_root[4][0].text
        spotify_attrib = spotify_attrib.replace('spotify:track:', 'http://open.spotify.com/track/');
        #at this point, we have the spotify song
    
    #rdio is up next
    rdio_title = ''
    rdio_artist = ''
    rdio_url = ''
    rdio = Rdio(("ad6x8mefbh2b2kh3deezgfq2", "tdWYdpKBfH"))
    rdio_song = rdio.call("search", {"query": song, "types": "Track"})
    if (rdio_song["status"] == "ok" and rdio_song["result"]["track_count"] != 0):
        rdio_turl = rdio_song["result"]["results"][0]["url"]
        rdio_url = "http://rdio.com"
        rdio_url += rdio_turl
    
    return jsonify(spotify_url = spotify_attrib, rdio_url = rdio_url)
Пример #2
0
def login():
    access_token = session.get('at')
    access_token_secret = session.get('ats')
    if access_token and access_token_secret:
        rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET), (access_token, access_token_secret))
        try:
            rdio_data = rdio.call('currentUser', params={'extras': 'username,displayName'})['result']
            username = rdio_data['username']
            user = User.query.filter(User.username == username).first()
            session['user_id'] = user.id
            print current_user
            return redirect(url_for('main'))
        except urllib2.HTTPError:
            # Something went horribly wrong, like Rdio told us our app sucks.
            logout()
            return redirect(url_for('main'))
    else:
        session['at'] = ''
        session['ats'] = ''
        session['rt'] = ''
        session['rts'] = ''
        rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET))
        login_url = rdio.begin_authentication(callback_url='http://' + request.host + '/auth')
        session['rt'] = rdio.token[0]
        session['rts'] = rdio.token[1]
        return jsonify(login_url=login_url)
Пример #3
0
def auth():
    request_token = session.get('rt')
    request_token_secret = session.get('rts')
    verifier = request.args.get('oauth_verifier', '')
    if request_token and request_token_secret and verifier:
        rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET), (request_token, request_token_secret))
        rdio.complete_authentication(verifier)
        session['at'] = rdio.token[0]
        session['ats'] = rdio.token[1]
        session['rt'] = ''
        session['rts'] = ''
        rdio_data = rdio.call('currentUser', params={'extras': 'username,displayName'})['result']
        username = rdio_data['username']
        print 'Creating user model.'
        user = User.query.filter(User.username == username).first()
        if user is None:
            user = User(username=username, key=rdio_data['key'], icon=rdio_data['icon'], name=rdio_data['displayName'])
            db_session.add(user)
            db_session.commit()
            playlists = rdio.call('getPlaylists', params={'extras': 'tracks,description,isViewable'})['result']['owned']
            #print playlists
            import_new_user_playlists(playlists, user.id)
        print 'Committed.'
        session['user_id'] = user.id
        print session
        return redirect(url_for('main'))
    else:
        # Login failed, clear everything
        print 'Auth failed.'
        logout()
        return redirect(url_for('main'))
Пример #4
0
  def GET(self):
    access_token = web.cookies().get('at')
    access_token_secret = web.cookies().get('ats')
    if access_token and access_token_secret:
      rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET),
        (access_token, access_token_secret))
      # make sure that we can make an authenticated call

      try:
        currentUser = rdio.call('currentUser')['result']
      except urllib2.HTTPError:
        # this almost certainly means that authentication has been revoked for the app. log out.
        raise web.seeother('/logout')

      myPlaylists = rdio.call('getPlaylists')['result']['owned']

      response = '''
      <html><head><title>Rdio-Simple Example</title></head><body>
      <p>%s's playlists:</p>
      <ul>
      ''' % currentUser['firstName']
      for playlist in myPlaylists:
        response += '''<li><a href="%(shortUrl)s">%(name)s</a></li>''' % playlist
      response += '''</ul><a href="/logout">Log out of Rdio</a></body></html>'''
      return response
    else:
      return '''
Пример #5
0
def callback():
    app.logger.info('yayyyyyy')
    #get the state from cookies and the query string
    request_token = request.cookies.get('rt')
    request_token_secret = request.cookies.get('rts')
    verifier = request.args['oauth_verifier']
    print(request_token + 'rts' + request_token_secret + 'verifer' + verifier)
    #make sure we have everything we need
    if request_token and request_token_secret and verifier:
        rdio = Rdio(RDIO_CREDENTIALS, (request_token, request_token_secret))
        rdio.complete_authentication(verifier)
        print('blah' + rdio.token)
        redirect_to_home = redirect('/')
        response = make_response(redirect_to_home)
        print(rdio.token[0])
        response.set_cookie('at', rdio.token[0],
                            expires=60 * 60 * 24 * 14)  # expires in two weeks
        response.set_cookie('ats', rdio.token[1],
                            expires=60 * 60 * 24 * 14)  # expires in two weeks
        response.set_cookie('rt', '', expires=-1)
        response.set_cookie('rts', '', expires=-1)
        return response
    else:
        response_to_home = make_response(redirect('/'))
        return response_to_home
Пример #6
0
def get_rdio_api():

  token = session.get('at')
  secret = session.get('ats')
  if token and secret:
    api = Rdio((rdio_key, rdio_secret), (token, secret))
  else:
    api = Rdio((rdio_key, rdio_secret))
  return api
Пример #7
0
def rdio_access_token(request=None, oauth_temp_db=None):
    '''OAuth dance.'''
    callback_token = request.args.get('oauth_token')
    callback_verifier = request.args.get('oauth_verifier')
    oauth_dance_token = oauth_temp_db.find_one({'oauth token': callback_token}) 
    oauth_dance_token = oauth_dance_token['oauth_dance_token']
    rdio = Rdio((CONSUMER_KEY, CONSUMER_SECRET), oauth_dance_token)
    rdio.complete_authentication(callback_verifier)
    access_token = rdio.token
    return access_token
Пример #8
0
def login_callback():
  params = dict([part.split('=') for part in request.query_string.split('&')])
  token = session['rt']
  secret = session['rts']
  api = Rdio((rdio_key, rdio_secret), (token, secret))
  api.complete_authentication(params.get('oauth_verifier'))
  session['rt'] = None
  session['rts'] = None
  session['at'] = api.token[0]
  session['ats'] = api.token[1]
  return redirect(url_for('index'))
Пример #9
0
def login_callback():
  params = dict([part.split('=') for part in request.query_string.split('&')])
  token = session['rt']
  secret = session['rts']
  api = Rdio((rdio_key, rdio_secret), (token, secret))
  api.complete_authentication(params.get('oauth_verifier'))
  session['rt'] = None
  session['rts'] = None
  session['at'] = api.token[0]
  session['ats'] = api.token[1]
  return redirect(url_for('index'))
Пример #10
0
def login_callback():
    params = dict([part.split("=") for part in request.query_string.split("&")])
    token = session["rt"]
    secret = session["rts"]
    api = Rdio((rdio_key, rdio_secret), (token, secret))
    api.complete_authentication(params.get("oauth_verifier"))
    session["rt"] = None
    session["rts"] = None
    session["at"] = api.token[0]
    session["ats"] = api.token[1]
    return redirect(url_for("index"))
Пример #11
0
def login():
    session['at'] = ''
    session['ats'] = ''
    session['rt'] = ''
    session['rts'] = ''
    # begin the authentication process
    rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET))
    url = rdio.begin_authentication(callback_url = 'http://localhost:5000/callback')
    # save our request token in cookies
    session['rt'] = rdio.token[0]
    session['rts'] = rdio.token[1]
    # go to Rdio to authenticate the app
    return redirect(url)
Пример #12
0
def home():
    access_token = session['at']
    access_token_secret = session['ats']
    if len(access_token) > 0 and len(access_token_secret) > 0 and access_token and access_token_secret:
        rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET), (access_token, access_token_secret))
        try:
            currentUser = rdio.call('currentUser')['result']
        except urllib2.HTTPError:
        # this almost certainly means that authentication has been revoked for the app. log out.
            return redirect(url_for(logout))
        return render_template('search_form.html')
    else:
        return redirect(url_for('login'))
Пример #13
0
def login():
    #clear all of our auth cookies
    #begin auth
    rdio = Rdio(RDIO_CREDENTIALS)
    app.logger.debug(request.host)
    url = rdio.begin_authentication(callback_url='http://'+request.host+'/callback')
    redirect_to_rdio = redirect(url)
    #save our request token in cookies
    response = make_response(redirect_to_rdio)
    print(rdio.token)
    response.set_cookie('rt', rdio.token[0], expires=60*60*24)
    response.set_cookie('rts', rdio.token[1], expires=60*60*24)
    #go to Rdio to authenticate the app
    return response
Пример #14
0
 def GET(self):
   # clear all of our auth cookies
   web.setcookie('at', '', expires=-1)
   web.setcookie('ats', '', expires=-1)
   web.setcookie('rt', '', expires=-1)
   web.setcookie('rts', '', expires=-1)
   # begin the authentication process
   rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET))
   url = rdio.begin_authentication(callback_url = web.ctx.homedomain+'/callback')
   # save our request token in cookies
   web.setcookie('rt', rdio.token[0], expires=60*60*24) # expires in one day
   web.setcookie('rts', rdio.token[1], expires=60*60*24) # expires in one day
   # go to Rdio to authenticate the app
   raise web.seeother(url)
Пример #15
0
def login():
    #clear all of our auth cookies
    #begin auth
    rdio = Rdio(RDIO_CREDENTIALS)
    app.logger.debug(request.host)
    url = rdio.begin_authentication(callback_url='http://' + request.host +
                                    '/callback')
    redirect_to_rdio = redirect(url)
    #save our request token in cookies
    response = make_response(redirect_to_rdio)
    print(rdio.token)
    response.set_cookie('rt', rdio.token[0], expires=60 * 60 * 24)
    response.set_cookie('rts', rdio.token[1], expires=60 * 60 * 24)
    #go to Rdio to authenticate the app
    return response
Пример #16
0
class rdio_simple:

	def __init__(self, CK, CS):
		self.rdio_obj = Rdio((CK, CS))

	def get_user_key_from_name(self, user_name):
		name = self.rdio_obj.call("findUser", {"vanityName": user_name})
		return name['result']['key']

	def get_collection_from_key(self, key):
		collection = self.rdio_obj.call("getTracksInCollection", {"user":key})
		return collection
	
	def get_tracks_from_collection(self, collection):
		for item in collection['result']:
			print item['name']
Пример #17
0
class MainTest(unittest.TestCase):
    def setUp(self):
        self.consumer = ('test', 'test')
        self.rdio = Rdio(self.consumer)

    @patch('rdio.urlopen', mock_urlopen)
    def test_unicode_params(self):
        r = self.rdio.call('search', {'query': 'Röyksopp'})
Пример #18
0
class rdio_simple:

	def __init__(self, CK, CS):
		self.rdio_obj = Rdio((CK, CS))

	def get_user_key_from_name(self, user_name):
		name = self.rdio_obj.call("findUser", {"vanityName": user_name})
		return name['result']['key']

	def get_collection_from_key(self, key, count="100"):
		collection = self.rdio_obj.call("getTracksInCollection", {"user":key, "extras":"playCount", "count":count})
		return collection
	
	def get_artists_from_collection(self, collection):
		my_list = []
		for item in collection['result']:
			my_list.append(item['artist'].encode('utf-8'))
		return my_list
Пример #19
0
def top_track(sesh):
    access_token = sesh['at']
    access_token_secret = sesh['ats']
    if len(access_token) > 0 and len(access_token_secret) > 0 and access_token and access_token_secret:
        rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET), (access_token, access_token_secret))
        try:
            currentUser = rdio.call('currentUser')['result']
        except urllib2.HTTPError:
        # this almost certainly means that authentication has been revoked for the app. log out.
            return {"error" : "failure"}
        topcharts = rdio.call('getTopCharts', {'type': 'Track', 'count' : 100})
        playbackToken = rdio.call('getPlaybackToken', {'domain' : 'localhost'})
        import random
        randomint = random.randint(0,99)
        song = topcharts['result'][randomint]
        song['playbackToken'] = playbackToken['result']
        return song
    else:
        return {"error" : "failure"}
Пример #20
0
class MainTest(unittest.TestCase):

    def setUp(self):
        self.consumer = ('test', 'test')
        self.rdio = Rdio(self.consumer)

    @patch('rdio.urlopen', mock_urlopen)
    def test_unicode_params(self):
        r = self.rdio.call('search', {
            'query': 'Röyksopp'
        })
Пример #21
0
 def GET(self):
   # get the state from cookies and the query string
   request_token = web.cookies().get('rt')
   request_token_secret = web.cookies().get('rts')
   verifier = web.input()['oauth_verifier']
   # make sure we have everything we need
   if request_token and request_token_secret and verifier:
     # exchange the verifier and request token for an access token
     rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET),
       (request_token, request_token_secret))
     rdio.complete_authentication(verifier)
     # save the access token in cookies (and discard the request token)
     web.setcookie('at', rdio.token[0], expires=60*60*24*14) # expires in two weeks
     web.setcookie('ats', rdio.token[1], expires=60*60*24*14) # expires in two weeks
     web.setcookie('rt', '', expires=-1)
     web.setcookie('rts', '', expires=-1)
     # go to the home page
     raise web.seeother('/')
   else:
     # we're missing something important
     raise web.seeother('/logout')
Пример #22
0
def callback():
    request_token = session['rt']
    request_token_secret = session['rts']
    verifier = request.args["oauth_verifier"]
    
    # make sure we have everything we need
    if request_token and request_token_secret and verifier:
        # exchange the verifier and request token for an access token
        rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET), (request_token, request_token_secret))
        rdio.complete_authentication(verifier)
        # save the access token in cookies (and discard the request token)
        session['at'] = rdio.token[0]
        session['ats'] = rdio.token[1]
        session['rt'] = ''
        session['rts'] = ''

        # go to the home page
        return redirect(url_for('home'))
    else:
        # we're missing something important
        return redirect(url_for('logout'))
Пример #23
0
def search(song):
    song = song.replace(';', '')
    song = song.replace('&', '')
    song = song.replace('With Lyrics', '')
    song = song.replace('(Official Video)', '')
    song = song.replace('(Official Music Video)', '')
    song = song.replace('[Official Video]', '')
    song = song.replace('[Official Music Video]', '')
    song = song.replace('-', '')

    spotify_request = requests.get(
        'http://ws.spotify.com/search/1/track?q=%s' % song)
    spotify_root = ET.fromstring(
        spotify_request.content
    )  #parse the xml out so we can do things with it
    spotify_song = ''
    spotify_attrib = ''
    if spotify_root[1].text != '0':
        spotify_attrib = spotify_root[
            4].attrib  #this looks like {'href': 'spotify:track:5TdAgcKS5HlxMcclStHODW'}
        spotify_attrib = spotify_attrib["href"]
        spotify_song = spotify_root[4][0].text
        spotify_attrib = spotify_attrib.replace(
            'spotify:track:', 'http://open.spotify.com/track/')
        #at this point, we have the spotify song

    #rdio is up next
    rdio_title = ''
    rdio_artist = ''
    rdio_url = ''
    rdio = Rdio(("ad6x8mefbh2b2kh3deezgfq2", "tdWYdpKBfH"))
    rdio_song = rdio.call("search", {"query": song, "types": "Track"})
    if (rdio_song["status"] == "ok"
            and rdio_song["result"]["track_count"] != 0):
        rdio_turl = rdio_song["result"]["results"][0]["url"]
        rdio_url = "http://rdio.com"
        rdio_url += rdio_turl

    return jsonify(spotify_url=spotify_attrib, rdio_url=rdio_url)
Пример #24
0
def create_rdio_playlist(token, request):
    '''Rdio call, create playlist.'''
    logger.debug('Creating playlist')
    rdio = Rdio((CONSUMER_KEY, CONSUMER_SECRET), token)
    artist_key = request.form['create playlist']
    search = rdio.call('get', {'keys': artist_key})
    artist = search['result'][artist_key]['name']
    artist_top_ten_tracks = rdio.call('getTracksForArtist',
                                      {'artist': artist_key})
    if len(artist_top_ten_tracks['result']) == 0:
        # Flash message instead.
        return 'Could not find any tracks. Click back to try another artist.'
    api_call_key_list = []
    for track in artist_top_ten_tracks['result']:
        api_call_key_list.append(track['key'])
    playlist = ','.join(api_call_key_list)
    created_playlist = rdio.call('createPlaylist', {
        'name': '{}\'s Top Ten'.format(artist),
        'description': 'Top ten tracks by play count',
        'tracks': playlist})
    playlist_url = created_playlist['result']['url']
    logger.debug('Playlist created successfully.\n') 
    return playlist_url
Пример #25
0
def rdio_search(query, sesh):
    access_token = sesh['at']
    access_token_secret = sesh['ats']
    if len(access_token) > 0 and len(access_token_secret) > 0 and access_token and access_token_secret:
        rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET), (access_token, access_token_secret))
        try:
            currentUser = rdio.call('currentUser')['result']
        except urllib2.HTTPError:
        # this almost certainly means that authentication has been revoked for the app. log out.
            return {"error" : "failure"}

        result = rdio.call('search', {'query' : query, 'types' : "Artist,Track" })
        result = result['result']['results']

        pop = result[0]

        while pop['type'] != 't':
            pop = result.pop(0)
        
        return pop

    else:
        return {"error" : "failure"}
Пример #26
0
def callback():
    app.logger.info('yayyyyyy')
    #get the state from cookies and the query string
    request_token = request.cookies.get('rt')
    request_token_secret = request.cookies.get('rts')
    verifier = request.args['oauth_verifier']
    print(request_token+'rts'+request_token_secret+'verifer'+verifier)
    #make sure we have everything we need
    if request_token and request_token_secret and verifier:
        rdio = Rdio(RDIO_CREDENTIALS, (request_token, request_token_secret))
        rdio.complete_authentication(verifier)
        print('blah'+rdio.token)
        redirect_to_home = redirect('/')
        response = make_response(redirect_to_home)
        print(rdio.token[0])
        response.set_cookie('at', rdio.token[0], expires=60*60*24*14)   # expires in two weeks
        response.set_cookie('ats', rdio.token[1], expires=60*60*24*14)  # expires in two weeks
        response.set_cookie('rt', '', expires=-1)
        response.set_cookie('rts', '', expires=-1)
        return response
    else:
        response_to_home = make_response(redirect('/'))
        return response_to_home
Пример #27
0
def run(options):
    store = load_store()
    token = None
    if "token" in store:
        token = (store.get("token"), store.get("token_secret"))
    rdio = Rdio((options.key, options.secret), token)

    if rdio.token == None:
        # No token, log in
        url = rdio.begin_authentication("oob")
        print "Go to: " + url
        verifier = raw_input("Then enter the code: ").strip()
        rdio.complete_authentication(verifier)
        # TODO: Why aren't saved tokens working?
        # token, token_secret = rdio.token
        # store['token'] = token
        # store['token_secret'] = token_secret
        # write_store(store)

    year = options.year
    if year == None:
        year = get_current_year()
    year_key = str(year)

    last_run = None
    if year_key in store:
        last_run = store.get(year_key)

    print "Loading albums"
    albums, last_run = get_albums(rdio, year, last_run)
    print "Loaded %s new albums to add" % len(albums)

    if len(albums) > 0:
        add_to_playlist(rdio, year, albums)

    store[year_key] = last_run
    write_store(store)
Пример #28
0
def main():
    CONSUMER_KEY, CONSUMER_SECRET = get_consumer_credentials()
    rdio = Rdio((CONSUMER_KEY, CONSUMER_SECRET))
    auth_url = rdio.begin_authentication('oob')

    # redirect user to rdio, will give pin back

    verifier = get_pin(auth_url)
    saved_token = rdio.token  # a two element tuple
    rdio.complete_authentication(verifier)

    print "fetching last fm artists..."
    lastfm = LastfmQuery.LastfmQuery()
    lastfm_list_of_artists = lastfm.getAlbums("jaisrael")

    print "adding artists to collection..."
    for artist in lastfm_list_of_artists:
        try:
            response = rdio.call('search', {
                'query': artist,
                'types': 'Artist'
            })
        except UnicodeEncodeError:
            print "unicode issue. skipping this artist"
            continue

        artist_key = response['result']['results'][0]['key']
        if artist_key is not None:
            track_objs = rdio.call('getTracksForArtist',
                                   {'artist': artist_key})['result']
            track_keys_unicode_list = [track['key'] for track in track_objs]
            if track_keys_unicode_list is not None:
                # convert track keys to unicode
                track_keys_ascii_list = [
                    unicodedata.normalize('NFKD', u).encode('ascii', 'ignore')
                    for u in track_keys_unicode_list
                ]
                track_keys_str = ""
                for u in track_keys_ascii_list:
                    track_keys_str += u + ","
                if track_keys_str.endswith(','):
                    track_keys_str = track_keys_str[:-1]
                atc = rdio.call('addToCollection', {'keys': track_keys_str})
Пример #29
0
def login():
    args = request.args
    if 'token' in session and 'oauth_verifier' in args:
        verifier = request.args.get('oauth_verifier')
        rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET), session['token'])
        rdio.complete_authentication(verifier)
        session['token'] = rdio.token
        user = rdio.call('currentUser')['result']
        session['user'] = user['key']
        users[user['key']] = user
        username = rdio.call('currentUser', {'extras': 'username'})['result']['username']
        return redirect(url_for('playlists', username=username))
    rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET))
    auth_url = rdio.begin_authentication(SITE_URL + '/login')
    session['token'] = rdio.token
    return redirect(auth_url)
Пример #30
0
def tester():
    rdio = Rdio(("u35btmntr29vd3n9hnuy9m6n", "jb8DTyHpVf"))
    url = rdio.begin_authentication('oob')
    saved_token = rdio.token
    print saved_token
    rdio = Rdio(("u35btmntr29vd3n9hnuy9m6n", "jb8DTyHpVf"), saved_token)
    #print "Go to website to verify: " + url
    #verifier = input("Enter pin: ")
    #rdio.complete_authentication(saved_token)
    print saved_token
    song = rdio.call("search", {"query": "Lose yourself", "types": "Track"})
    if (song["status"] == "ok"):
        track = song["result"]["results"][0]["key"]
        rdio.call("addToPlaylist", {
            "playlist": "p8696966",
            "tracks": str(track)
        })
    else:
        print "failed"
    return "Song Added"
Пример #31
0
def tester():
    rdio = Rdio(("u35btmntr29vd3n9hnuy9m6n", "jb8DTyHpVf"))
    url = rdio.begin_authentication('oob')
    saved_token = rdio.token
    print saved_token
    rdio = Rdio(("u35btmntr29vd3n9hnuy9m6n", "jb8DTyHpVf"), saved_token)
    #print "Go to website to verify: " + url
    #verifier = input("Enter pin: ")
    #rdio.complete_authentication(saved_token)
    print saved_token 
    song = rdio.call("search",{"query": "Lose yourself","types":"Track"})
    if(song["status"] == "ok"):
        track =  song["result"]["results"][0]["key"]
        rdio.call("addToPlaylist",{"playlist":"p8696966","tracks":str(track)})
    else:
        print "failed"
    return "Song Added"
Пример #32
0
def main():
	CONSUMER_KEY, CONSUMER_SECRET = get_consumer_credentials()
	rdio = Rdio((CONSUMER_KEY, CONSUMER_SECRET))
	auth_url = rdio.begin_authentication('oob')

	# redirect user to rdio, will give pin back

	verifier = get_pin(auth_url)
	saved_token = rdio.token # a two element tuple
	rdio.complete_authentication(verifier)

	print "fetching last fm artists..."
	lastfm = LastfmQuery.LastfmQuery()
	lastfm_list_of_artists = lastfm.getAlbums("jaisrael")
	
	print "adding artists to collection..." 
	for artist in lastfm_list_of_artists:
		try:
			response = rdio.call('search', {'query':artist, 'types':'Artist'})		
		except UnicodeEncodeError:
			print "unicode issue. skipping this artist"
			continue
	
		artist_key = response['result']['results'][0]['key']
		if artist_key is not None:
			track_objs = rdio.call('getTracksForArtist', {'artist':artist_key})['result']
			track_keys_unicode_list = [ track['key'] for track in track_objs ]
			if track_keys_unicode_list is not None:
				# convert track keys to unicode
				track_keys_ascii_list = [ unicodedata.normalize('NFKD', u).encode('ascii','ignore') for u in track_keys_unicode_list ]
				track_keys_str = ""
				for u in track_keys_ascii_list:
					track_keys_str += u + ","
				if track_keys_str.endswith(','):
					track_keys_str = track_keys_str[:-1]
				atc = rdio.call('addToCollection', {'keys':track_keys_str})
Пример #33
0
def get_obj_listing(obj, view):
    rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET), session['token'])
    user = session['user']
    if obj:
        req = rdio.call('get', {'keys':obj})
        res = req['result'][obj]
        if res['type'] == 'al':
            req = rdio.call('get', {'keys':','.join(res['trackKeys'])})
            res = req['result']
            tracks = res.values()
            return tracks

    if view == 'albums':
        req = rdio.call('getAlbumsInCollection', {'user': user})
        return req['result']

    if view == 'tracks':
        req = rdio.call('getTracksInCollection', {'user': user})
        return req['result']

    req = rdio.call('getArtistsInCollection', {'user': user})
    return req['result']
Пример #34
0
    tracks_path = os.path.join(GIT_REPO_PATH, 'tracks.json')
    with open(tracks_path, 'w') as json_file:
        json.dump(tracks, json_file, indent=4)

    git = sh.git.bake(_cwd=GIT_REPO_PATH)
    print git.add(tracks_path)
    print git.commit(m='Updating rdio collection.')
    print git.push()

if __name__ == "__main__":

    try:
        if '' in RDIO_TOKEN:

            # create an instance of the Rdio object with our consumer credentials
            rdio = Rdio(RDIO_CREDENTIALS)

            # authenticate against the Rdio service
            url = rdio.begin_authentication('oob')
            print('Go to: ' + url)
            verifier = input('Then enter the code: ').strip()
            rdio.complete_authentication(verifier)

        else:
            rdio = Rdio(RDIO_CREDENTIALS, RDIO_TOKEN)

    except HTTPError as e:
        # if we have a protocol error, print it
        print(e.read())
    
    update_collection(rdio)
from urllib2 import HTTPError

from rdio import Rdio
from rdio_consumer_credentials import *

rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET))
keys = []

try:
    # authenticate against the Rdio service
    url = rdio.begin_authentication('oob')
    print "Go to: " + url
    verifier = raw_input("Then enter the code: ").strip()
    rdio.complete_authentication(verifier)

    # get tracks in collection
    tracks = rdio.call('getTracksInCollection', {'sort': 'artist'})
    if (tracks['status'] == 'ok'):
        for track in tracks['result']:
            # add keys to a list
            keys.append(track['key'])
    else:
        print "ERROR: " + tracks['message']

    # create a comma separated string
    keys_string = ",".join(keys)
    print "Sending request to Rdio"
    rdio.call('setAvailableOffline', {'keys': keys_string, 'offline': True})
    print "Request sent. Open your Rdio mobile app to check the syncing status."

except HTTPError, e:
Пример #36
0
"""
RdioUtil.py
"""

CONSUMER_KEY = '...'
CONSUMER_SECRET = '...'
domain = "example.com"

# https://github.com/rdio/rdio-python
from rdio import Rdio
from pprint import pprint

state = {}
rdio = Rdio(CONSUMER_KEY, CONSUMER_SECRET, state)

pprint(rdio.getPlaybackToken(domain=domain))
Пример #37
0
from rdio_cred import *
import csv
from rdio import Rdio


def create_playlist(key_string):
    rdio.call(
        'createPlaylist', {
            'name': PLAYLIST_NAME,
            'description': PLAYLIST_DESCRIPTION,
            'tracks': key_string
        })


# initiate rdio object
rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET),
            (OAUTH_TOKEN, OAUTH_TOKEN_SECRET))

csv_tracks = []
f = open('track_list.csv', 'rU')
reader = csv.reader(f)
for row in reader:
    csv_tracks.append({'artist': row[0], 'title': row[1]})
f.close()

# first build a list of all tracks found that can be streamed
key_list = []
for track in csv_tracks:
    query = track['artist'] + ' ' + track['title']
    search = rdio.call('search', {'query': query, 'types': 'Track'})
    if search['result']['number_results'] > 0:
        if search['result']['results'][0]['canStream']:
Пример #38
0
 def setUp(self):
     self.consumer = ('test', 'test')
     self.rdio = Rdio(self.consumer)
Пример #39
0
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

# include the parent directory in the Python path
import sys, os.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from rdio import Rdio
from rdio_consumer_credentials import *
from urllib2 import HTTPError

# create an instance of the Rdio object with our consumer credentials
rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET))

try:
    # authenticate against the Rdio service
    url = rdio.begin_authentication('oob')
    print 'Go to: ' + url
    verifier = raw_input('Then enter the code: ').strip()
    rdio.complete_authentication(verifier)

    # find out what playlists you created
    myPlaylists = rdio.call('getPlaylists')['result']['owned']

    # list them
    for playlist in myPlaylists:
        print '%(shortUrl)s\t%(name)s' % playlist
except HTTPError, e:
Пример #40
0
 def setUp(self):
     self.consumer = ('test', 'test')
     self.rdio = Rdio(self.consumer)
Пример #41
0
from rdio import Rdio
from rdio_consumer_credentials import RDIO_CREDENTIALS
try:
    from urllib.error import HTTPError
except ImportError:
    from urllib2 import HTTPError

# Fix for Python 2.X
try:
    input = raw_input
except NameError:
    pass

# create an instance of the Rdio object with our consumer credentials
rdio = Rdio(RDIO_CREDENTIALS)

try:
    # authenticate against the Rdio service
    url = rdio.begin_authentication('oob')
    print('Go to: ' + url)
    verifier = input('Then enter the code: ').strip()
    rdio.complete_authentication(verifier)

    # find out what playlists you created
    myPlaylists = rdio.call('getPlaylists')['result']['owned']

    # list them
    for playlist in myPlaylists:
        print('%(shortUrl)s\t%(name)s' % playlist)
except HTTPError as e:
Пример #42
0
from match import match_tracks
from playmusic import PlayMusic
from rdio import Rdio
from report import Report

parser = argparse.ArgumentParser(
    description='Export playlists and favorites from Rdio to Play Music')
parser.add_argument('rdio_username', help='username on Rdio')
parser.add_argument('google_email', help='Google account email address')
args = parser.parse_args()

google_password = getpass.getpass('%s password:'******'Connecting to Rdio...'
rdio = Rdio()
print 'Connecting to Play Music...'
pm = PlayMusic(args.google_email, google_password)
if not pm.is_authenticated():
    print 'Google login failed.'
    sys.exit(1)


def migrate_playlist(user_key, playlist):
    print u'\nMigrating playlist: %s' % playlist['name']
    name = playlist['name']
    if playlist['ownerKey'] != user_key:
        name += u' (by %s)' % playlist['owner']
    description = u'Imported from Rdio playlist %s\n' % playlist['shortUrl']
    play_track_ids = []
    failed = []
Пример #43
0
 def rdio(self):
     if self.__cached_rdio is None:
         self.__cached_rdio = Rdio(CONSUMER_TOKEN, CONSUMER_SECRET,
                                   self.cookies)
     return self.__cached_rdio
Пример #44
0
	def __init__(self, CK, CS):
		self.rdio_obj = Rdio((CK, CS))
Пример #45
0
import sys

from urllib2 import HTTPError

from rdio import Rdio
from rdio_consumer_credentials import *

rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET))
song_data = {}

try:
    # authenticate against the Rdio service
    url = rdio.begin_authentication('oob')
    print "Go to: " + url
    verifier = raw_input("Then enter the code: ").strip()
    rdio.complete_authentication(verifier)

    print "\nFinding Duplicate Songs..."

    # get songs in collection
    songs = rdio.call('getTracksInCollection', {'sort': 'artist'})
    if (songs['status'] == 'ok'):

        # mape all songs by song name - artist
        for song in songs['result']:
            uuid = song['name'] + ' - ' + song['artist']
            data = {
                'name': song['name'],
                'artist': song['artist'],
                'album': song['album'],
                'key': song['key'],
Пример #46
0
    title = title.text
    title = re.sub(r'\[.*\]\s*|,', '',
                   title)  #removes bracketed text (usually collaborators)
    title_list.append(title.replace("\"", ""))

#combine the two
for i in range(0, len(artist_list)):
    new = {'artist': artist_list[i], 'title': title_list[i], 'status': '0'}

    #check if combined tracks is already in csv & if not, add it
    if not is_in_csv(csv_tracks, new, 'title'):
        csv_tracks.append(new)
        print "Adding new track", new['title'], "to the CSV file"

#initiate rdio object
rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET),
            (RDIO_TOKEN, RDIO_TOKEN_SECRET))

#loop through any unadded tracks and see if they're on rdio, add 'em if they are
for track in csv_tracks:
    if track['status'] == '0':
        if find_track(track) != None:
            key = find_track(track)
            add_to_playlist(key)
            track['status'] = '1'
            print 'Adding %s by %s to the playlist' % (track['title'],
                                                       track['artist'])

# write csv_tracks back out to file
f = open('/home/barretts/pitchfork/tracks.csv', 'w')
writer = csv.writer(f)
for record in csv_tracks:
Пример #47
0
    config = {'auth_state': {}}

if options.consumer_key is not None:
    config['consumer_key'] = options.consumer_key
if options.consumer_secret is not None:
    config['consumer_secret'] = options.consumer_secret

if not config.has_key('consumer_key') or not config.has_key('consumer_secret'):
    sys.stderr.write(
        'Both the consumer key and consumer secret must be specified')
    sys.exit(1)

if options.forget_auth or options.authenticate:
    config['auth_state'] = {}

rdio = Rdio(config['consumer_key'], config['consumer_secret'],
            config['auth_state'])

if options.authenticate:
    import webbrowser
    webbrowser.open(rdio.begin_authentication('oob'))
    verifier = raw_input('Enter the PIN from the Rdio site: ').strip()
    rdio.complete_authentication(verifier)

f = file(config_path, 'w')
json.dump(config, f, indent=True)
f.write('\n')

method = args.pop(0)
args = dict([a.split('=', 1) for a in args])
response, content = rdio.call_raw(method, **args)
if response['status'] == '200':
Пример #48
0
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from rdio import Rdio
from rdio_consumer_credentials import RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET
from urllib2 import HTTPError

import csv

rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET))

try:

    # Authentication.
    url = rdio.begin_authentication('oob')
    print 'Go to: ' + url
    verifier = raw_input('Then enter the code: ').strip()
    rdio.complete_authentication(verifier)

    # Playlist initialization.
    my_playlists = rdio.call('getPlaylists', {
        'extras': 'trackKeys',
    })['result']['owned']

    playlist = None
Пример #49
0
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

# include the parent directory in the Python path
import sys,os.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from rdio import Rdio
from rdio_consumer_credentials import *
from urllib2 import HTTPError

# create an instance of the Rdio object with our consumer credentials
rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET))

try:
  # authenticate against the Rdio service
  url = rdio.begin_authentication('oob')
  print 'Go to: ' + url
  verifier = raw_input('Then enter the code: ').strip()
  rdio.complete_authentication(verifier)

  # find out what playlists you created
  myPlaylists = rdio.call('getPlaylists')['result']['owned']

  # list them
  for playlist in myPlaylists:
    print '%(shortUrl)s\t%(name)s' % playlist
except HTTPError, e:
Пример #50
0
config.ECHO_NEST_API_KEY = 'ZMBQQBZ4DBZVTKOTB'

oauth = OAuth()
facebook = oauth.remote_app(
    'facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key='255490651260325',
    consumer_secret='8fd6a30d356b85bfa58daa327c9eacea',
    request_token_params={'scope': 'email'})

redis = StrictRedis()

_rdio_token = None
_rdio = Rdio(('yjgnkcp2kr8ykwwjtujb5ajv', 'trpsv6n6gm'))


def rdio_token():
    global _rdio_token
    if _rdio_token is None:
        _rdio_token = _rdio.call('getPlaybackToken',
                                 {'domain': domain})['result']
    return _rdio_token


import musicroom.login
import musicroom.models
import musicroom.views
Пример #51
0
from rdio import Rdio
from config import CONSUMER_KEY, CONSUMER_SECRET


RDIO_CONSUMER_KEY = CONSUMER_KEY
RDIO_CONSUMER_SECRET = CONSUMER_SECRET

rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET))

ian = rdio.call("findUser", {"vanityName": "ian"})

print ian