Exemple #1
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
Exemple #2
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 '''
Exemple #3
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
Exemple #4
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"
Exemple #5
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'))
Exemple #6
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)
Exemple #7
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
Exemple #8
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})
Exemple #9
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')
Exemple #10
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)
Exemple #11
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':
Exemple #12
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']:
Exemple #13
0
 def rdio(self):
     if self.__cached_rdio is None:
         self.__cached_rdio = Rdio(CONSUMER_TOKEN, CONSUMER_SECRET,
                                   self.cookies)
     return self.__cached_rdio
# 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:
Exemple #15
0
 def setUp(self):
     self.consumer = ('test', 'test')
     self.rdio = Rdio(self.consumer)
Exemple #16
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)
Exemple #17
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:
Exemple #18
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:
Exemple #19
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
Exemple #20
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 = []