def api(): global __rdio__, __rdio_state__ if not __rdio__: __rdio__ = Rdio("u4lennlndjhvfnitfntn3mcvzi", "YO2oHvLK5rOCQTnFJvNq-Q", __rdio_state__) if not __rdio_state__.get('device_code'): url, device_code = __rdio__.begin_authentication() raw_input('After entering the device code "{}" into {} press enter'.format(device_code, url)) __rdio__.complete_authentication() print __rdio_state__ return __rdio__
class RdioHelper: RDIO_USER_CONFIG = "~/.rdio-tool.json" def __init__(self, options): # load the persistent state config_path = os.path.expanduser(self.RDIO_USER_CONFIG) if os.path.exists(config_path): self.config = json.load(file(config_path)) else: self.config = {"auth_state": {}} # set up the keys if options.consumer_key is not None: self.config["consumer_key"] = options.consumer_key if options.consumer_secret is not None: self.config["consumer_secret"] = options.consumer_secret # create the Rdio client object self.client = Rdio(self.config["consumer_key"], self.config["consumer_secret"], self.config["auth_state"]) if options.authenticate: import webbrowser webbrowser.open(self.client.begin_authentication("oob")) verifier = raw_input("Enter the PIN from the Rdio site: ").strip() self.client.complete_authentication(verifier) # save state with file(config_path, "w") as f: json.dump(self.config, f, indent=True) f.write("\n") def authenticate(self): import webbrowser webbrowser.open(self.client.begin_authentication("oob")) verifier = raw_input("Enter the PIN from the Rdio site: ").strip() self.client.complete_authentication(verifier) def getObjectFromShortCode(self, short_code): return self.client.getObjectFromShortCode(short_code=short_code) def getObjectFromUrl(self, path): return self.client.getObjectFromUrl(url=path) def getNewReleases(self, **args): return self.client.getNewReleases(**args) def getArtistsInCollection(self, **args): return self.client.getArtistsInCollection(**args)
def __init__(self, options): # load the persistent state config_path = os.path.expanduser(self.RDIO_USER_CONFIG) if os.path.exists(config_path): self.config = json.load(file(config_path)) else: self.config = {"auth_state": {}} # set up the keys if options.consumer_key is not None: self.config["consumer_key"] = options.consumer_key if options.consumer_secret is not None: self.config["consumer_secret"] = options.consumer_secret # create the Rdio client object self.client = Rdio(self.config["consumer_key"], self.config["consumer_secret"], self.config["auth_state"]) if options.authenticate: import webbrowser webbrowser.open(self.client.begin_authentication("oob")) verifier = raw_input("Enter the PIN from the Rdio site: ").strip() self.client.complete_authentication(verifier) # save state with file(config_path, "w") as f: json.dump(self.config, f, indent=True) f.write("\n")
def generate_rdio_playlist(): """ Generate a list of Rdio track IDs """ state = {} rdio_api = Rdio(secrets['RDIO_CONSUMER_KEY'], secrets['RDIO_CONSUMER_SECRET'], state) songs = [] with open('data/songs.csv') as f: rows = csv.DictReader(f) for row in rows: if row['rdio']: song_object = rdio_api.getObjectFromUrl(url=row['rdio']) if song_object['type'] == 't': songs.append(song_object['key']) print ','.join(songs)
def generate_rdio_playlist(): """ Generate a list of Rdio track IDs """ state = {} rdio_api = Rdio( secrets['RDIO_CONSUMER_KEY'], secrets['RDIO_CONSUMER_SECRET'], state ) songs = [] with open('data/songs.csv') as f: rows = csv.DictReader(f) for row in rows: if row['rdio']: song_object = rdio_api.getObjectFromUrl(url=row['rdio']) if song_object['type'] == 't': songs.append(song_object['key']) print ','.join(songs)
def handle(self, room_name, *args, **kwargs): self.firebase = firebase.FirebaseApplication(settings.FIREBASE_URL) auth = firebase.FirebaseAuthentication(settings.FIREBASE_TOKEN, '*****@*****.**') self.firebase.authentication = auth self.rdio = Rdio(RDIO_OAUTH2_KEY, RDIO_OAUTH2_SECRET, {}) self.party_name = room_name self.party_data = self.get_party_data() self.currently_playing = None self.last_saw_users = datetime.now() self.currently_playing = None if 'player' in self.party_data and 'playingTrack' in self.party_data[ 'player']: track_key = self.party_data['player']['playingTrack']['trackKey'] self.current_track_duration = self.rdio.get( keys=track_key)[track_key]['duration'] self.current_start_time = datetime.now() - timedelta( seconds=self.party_data['player']['position']) else: self.current_track_duration = None self.current_start_time = None self.run()
def handle(self, room_name, *args, **kwargs): self.firebase = firebase.FirebaseApplication(settings.FIREBASE_URL) auth = firebase.FirebaseAuthentication(settings.FIREBASE_TOKEN, '*****@*****.**') self.firebase.authentication = auth self.rdio = Rdio(RDIO_OAUTH2_KEY, RDIO_OAUTH2_SECRET, {}) self.party_name = room_name self.party_data = self.get_party_data() self.currently_playing = None self.last_saw_users = datetime.now() self.currently_playing = None if 'player' in self.party_data and 'playingTrack' in self.party_data['player']: track_key = self.party_data['player']['playingTrack']['trackKey'] self.current_track_duration = self.rdio.get(keys=track_key)[track_key]['duration'] self.current_start_time = datetime.now() - timedelta(seconds=self.party_data['player']['position']) else: self.current_track_duration = None self.current_start_time = None self.run()
def get_base_rdio_client(): config = _get_stored_config() config = _add_missing_config(config) needs_auth = len(config.client_state) == 0 rdio = Rdio( config.credentials.client_id, config.credentials.client_secret, config.client_state ) if needs_auth: rdio.begin_authentication() url, device_code = rdio.begin_authentication() print u"Please enter device code {} on {}".format(device_code, url) rdio.complete_authentication() _set_stored_config(config) return rdio
class Command(BaseCommand): def handle(self, room_name, *args, **kwargs): self.firebase = firebase.FirebaseApplication(settings.FIREBASE_URL) auth = firebase.FirebaseAuthentication(settings.FIREBASE_TOKEN, '*****@*****.**') self.firebase.authentication = auth self.rdio = Rdio(RDIO_OAUTH2_KEY, RDIO_OAUTH2_SECRET, {}) self.party_name = room_name self.party_data = self.get_party_data() self.currently_playing = None self.last_saw_users = datetime.now() self.currently_playing = None if 'player' in self.party_data and 'playingTrack' in self.party_data[ 'player']: track_key = self.party_data['player']['playingTrack']['trackKey'] self.current_track_duration = self.rdio.get( keys=track_key)[track_key]['duration'] self.current_start_time = datetime.now() - timedelta( seconds=self.party_data['player']['position']) else: self.current_track_duration = None self.current_start_time = None self.run() def get_party_data(self): pd = defaultdict(lambda: defaultdict(int)) pd.update(self.firebase.get(self.party_name, None) or {}) return pd def run(self): self.keep_running = True while self.keep_running: try: self.keep_running = self.tick() except Exception: logging.exception("AH DAEMON PROBLEM") time.sleep(1) def play_next_track(self): if 'queue' in self.party_data: queue = self.party_data['queue'] ordered_tracks = sorted(queue.values(), key=lambda x: len(x['votes']), reverse=True) try: next_track = ordered_tracks[0] except IndexError: next_track = None if next_track: self.firebase.delete(self.party_name + '/queue', next_track['id']) self.play_track(next_track) else: self.play_track(None) else: self.play_track(None) def send_play_track_message(self, rdio_track): message = { 'artist': rdio_track['artist'], 'title': rdio_track['name'], 'iconUrl': rdio_track['icon'], 'timestamp': datetime.now().isoformat(), 'trackUrl': rdio_track['shortUrl'], 'trackKey': rdio_track['key'], 'type': 'NewTrack' } self.firebase.post(self.party_name + "/messages/", message) def play_track(self, track): self.currently_playing = track player_object = { 'position': 0, 'playState': 1 if track else 0, 'playingTrack': track } self.firebase.put(self.party_name, 'player', player_object) if track: track_key = track['trackKey'] rdio_track = self.rdio.get(keys=track_key)[track_key] self.current_track_duration = rdio_track['duration'] self.current_start_time = datetime.now() self.send_play_track_message(rdio_track) else: self.current_track_duration = None self.current_start_time = None self.reset_skippers() def get_skippers(self): try: return dict([(skipper['key'], skipper) for skipper in self.party_data['skippers'].values() ]).values() except KeyError: return [] def get_online_users(self): return [ user for user in self.party_data.get('people', {}).values() if user['isOnline'] ] def should_skip(self): return len(self.get_skippers()) > len(self.get_online_users()) / 2 def tick(self): self.party_data = self.get_party_data() position = (datetime.now() - (self.current_start_time or datetime.now())).seconds if (not self.currently_playing or position > self.current_track_duration or self.should_skip()): self.play_next_track() else: self.firebase.put(self.party_name + '/player/', 'position', position) return self.should_keep_running() def reset_skippers(self): self.firebase.delete(self.party_name, 'skippers') def should_keep_running(self): """ Kill if no one is online in the room any more """ people = self.party_data['people'] users_online = bool( [person for person in people.values() if person['isOnline']]) if not users_online and (datetime.now() - self.last_saw_users) > WAIT_FOR_USERS: return False else: self.last_saw_users = datetime.now() return True
class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('room_name', type=str) def handle(self, room_name, *args, **kwargs): self.firebase = firebase.FirebaseApplication(settings.FIREBASE_URL) auth = firebase.FirebaseAuthentication(settings.FIREBASE_TOKEN, '*****@*****.**') self.firebase.authentication = auth self.rdio = Rdio(RDIO_OAUTH2_KEY, RDIO_OAUTH2_SECRET, {}) self.party_name = room_name self.party_data = self.get_party_data() self.currently_playing = None self.last_saw_users = datetime.now() self.currently_playing = None if 'player' in self.party_data and 'playingTrack' in self.party_data['player']: track_key = self.party_data['player']['playingTrack']['trackKey'] self.current_track_duration = self.rdio.get(keys=track_key)[track_key]['duration'] self.current_start_time = datetime.now() - timedelta(seconds=self.party_data['player']['position']) else: self.current_track_duration = None self.current_start_time = None self.run() def get_party_data(self): pd = defaultdict(lambda: defaultdict(int)) pd.update(self.firebase.get(self.party_name, None) or {}) return pd def run(self): self.keep_running = True while self.keep_running: try: self.keep_running = self.tick() except Exception: logging.exception("AH DAEMON PROBLEM") time.sleep(1) def _vote_score(self, track): votes = track['votes'].values() upvotes = filter(lambda x: x == "like", votes) downvotes = filter(lambda x: x == "dislike", votes) return len(upvotes) - len(downvotes) def _track_comparator(self, track_a, track_b): a_score = self._vote_score(track_a) b_score = self._vote_score(track_b) if a_score == b_score: try: a_time = parser.parse(track_a['timestamp']) b_time = parser.parse(track_b['timestamp']) return -cmp(a_time, b_time) except KeyError: pass return cmp(a_score, b_score) def play_next_track(self): if 'queue' in self.party_data: queue = self.party_data['queue'] ordered_tracks = sorted(queue.values(), cmp=self._track_comparator, reverse=True) try: next_track = ordered_tracks[0] except IndexError: next_track = None if next_track: self.firebase.delete(self.party_name + '/queue', next_track['id']) self.play_track(next_track) else: self.play_track(None) else: self.play_track(None) def send_play_track_message(self, rdio_track): message = { 'artist': rdio_track['artist'], 'title': rdio_track['name'], 'iconUrl': rdio_track['icon'], 'timestamp': datetime.utcnow().isoformat(), 'trackUrl': rdio_track['shortUrl'], 'trackKey': rdio_track['key'], 'type': 'NewTrack' } self.firebase.post(self.party_name + "/messages/", message) def play_track(self, track): self.currently_playing = track player_object = { 'position': 0, 'playState': 1 if track else 0, 'playingTrack': track } self.firebase.put(self.party_name, 'player', player_object) if track: track_key = track['trackKey'] rdio_track = self.rdio.get(keys=track_key)[track_key] self.current_track_duration = rdio_track['duration'] self.current_start_time = datetime.now() self.send_play_track_message(rdio_track) else: self.current_track_duration = None self.current_start_time = None self.reset_skippers() def get_skippers(self): try: return dict([ (skipper['key'], skipper) for skipper in self.party_data['skippers'].values() ]).values() except KeyError: return [] def get_online_users(self): return [ user for user in self.party_data.get('people', {}).values() if user['isOnline'] ] def should_skip(self): return len(self.get_skippers()) > len(self.get_online_users()) / 2 def tick(self): self.party_data = self.get_party_data() position = (datetime.now() - (self.current_start_time or datetime.now())).seconds if (not self.currently_playing or position > self.current_track_duration or self.should_skip()): self.play_next_track() else: self.firebase.put(self.party_name + '/player/', 'position', position) return self.should_keep_running() def reset_skippers(self): self.firebase.delete(self.party_name, 'skippers') def should_keep_running(self): """ Kill if no one is online in the room any more """ people = self.party_data['people'] users_online = bool([ person for person in people.values() if person['isOnline'] ]) if users_online: self.last_saw_users = datetime.now() if not users_online and (datetime.now() - self.last_saw_users) > WAIT_FOR_USERS: return False else: return True
def _init_rdio(self): self._rdio = Rdio(self._addon.get_setting('apikey'), self._addon.get_setting('apisecret'), self._state['rdio_api'])
class RdioApi: _AMF_ENDPOINT = 'http://www.rdio.com/api/1/amf/' _STATE_FILE_NAME = 'rdio-state.json' _RDIO_DOMAIN = 'localhost' _RDIO_PLAYBACK_SECRET = "A3wxEb2mooMZYl8nDOi2rg" _RDIO_PLAYBACK_SECRET_SEED = 5381 _INITIAL_STATE = {'rdio_api': {'auth_state': {}}, 'playback_token': None, 'current_user': None, 'rdio_cookie': None} def __init__(self, addon): self._addon = addon self._net = Net() self._state = addon.load_data(self._STATE_FILE_NAME) if not self._state: addon.log_debug("Persistent auth state not loaded - initialising new state") self._state = self._INITIAL_STATE else: addon.log_debug("Loaded persistent auth state") self._init_rdio() def _init_rdio(self): self._rdio = Rdio(self._addon.get_setting('apikey'), self._addon.get_setting('apisecret'), self._state['rdio_api']) def authenticate(self): # TODO Should internationalize error messages in exceptions thrown here self._addon.log_notice("Authenticating to Rdio") try: auth_url = self._rdio.begin_authentication('oob') except RdioProtocolException, rpe: self._addon.log_error('Rdio begin_authentication failed: ' + str(rpe)) raise RdioAuthenticationException('Check your API credentials in plugin settings') parsed_auth_url = urlparse(auth_url) url_base = "%s://%s" % (parsed_auth_url.scheme, parsed_auth_url.netloc) self._addon.log_notice("Authorizing OAuth token " + auth_url) html = self._net.http_GET(auth_url).content login_path = CommonFunctions.parseDOM(html, 'form', {'name': 'login'}, 'action') if login_path: login_url = url_base + login_path[0] username = self._addon.get_setting('username') password = self._addon.get_setting('password') self._addon.log_notice("Logging in to Rdio using URL %s" % (login_url)) html = self._net.http_POST(login_url, {'username': username, 'password': password}).content login_error_html = CommonFunctions.parseDOM(html, 'div', {'class': 'error-message'}) if login_error_html: error_messages = CommonFunctions.parseDOM(login_error_html, 'li') if error_messages: error_message = error_messages[0] if type(error_messages) is list else error_messages else: error_message = login_error_html raise RdioAuthenticationException(error_message) oauth_token_values = CommonFunctions.parseDOM(html, 'input', {'name': 'oauth_token'}, 'value') if not oauth_token_values: raise RdioAuthenticationException("Login failed, check username in plugin settings") oauth_token = oauth_token_values[0] verifier = CommonFunctions.parseDOM(html, 'input', {'name': 'verifier'}, 'value')[0] self._addon.log_notice("Approving oauth token %s with pin %s" % (oauth_token, verifier)) approval_result = self._net.http_POST(auth_url, {'oath_token': oauth_token, 'verifier': verifier, 'approve': ''}) self._addon.log_debug(approval_result.content) self._addon.log_notice("Verifying OAuth token on Rdio API with pin " + verifier) self._rdio.complete_authentication(verifier) self._addon.log_notice("Extracting Rdio cookie") self._addon.log_debug("Cookies: " + str(self._net.get_cookies())) self._state['rdio_cookie'] = self._net.get_cookies()['.rdio.com']['/']['r'].value self._addon.log_debug("Extracted Rdio cookie: " + self._state['rdio_cookie']) self._addon.log_notice("Getting playback token") self._state['playback_token'] = self._rdio.call('getPlaybackToken', domain=self._RDIO_DOMAIN) self._addon.log_notice("Getting current user") self._state['current_user'] = self._rdio.call('currentUser')['key'] self._save_state() self._addon.log_notice("Successfully authenticated to Rdio")
#!/usr/bin/python from rdio_consumer_credentials import * from rdioapi import Rdio state = {} r = Rdio(RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET, state) import webbrowser webbrowser.open(r.begin_authentication('oob')) verifier = raw_input('Enter the PIN from the Rdio site: ').strip() r.complete_authentication(verifier) from pprint import pprint i = 0 batch = 2500 while True: print "fetching collection tracks %d -> %d" % (i, i+batch) tracks = r.call('getTracksInCollection', count=i+batch, start=i) trackIds = [] for t in tracks: if 'isAvailableOffline' in t and t['isAvailableOffline']: trackIds.append(t['key']) print "\tfound %d synced tracks tracks" % (len(trackIds)) if len(trackIds): keys = ','.join(trackIds) r.call('setAvailableOffline', offline=False, keys=keys) i += batch if len(tracks) < batch: print "that was it"
class RdioApi: _RDIO_API_ENDPOINT = 'https://www.rdio.com/api/1' _AMF_ENDPOINT = _RDIO_API_ENDPOINT + '/amf/' _STATE_FILE_NAME = 'rdio-state.json' _RDIO_DOMAIN = 'localhost' _RDIO_PLAYBACK_SECRET = "6JSuiNxJ2cokAK9T2yWbEOPX" _RDIO_PLAYBACK_SECRET_SEED = 5381 _INITIAL_STATE = { 'rdio_api': { 'auth_state': {} }, 'playback_token': None, 'current_user': None, 'rdio_cookie': None, 'authorization_key': None } def __init__(self, addon): self._addon = addon self._cookie_file = os.path.join(self._addon.get_profile(), 'rdio_cookies.txt') self._net = Net(user_agent=getUserAgent(), cookie_file=self._cookie_file) self._state = addon.load_data(self._STATE_FILE_NAME) if not self._state: addon.log_debug( "Persistent auth state not loaded - initialising new state") self._state = self._INITIAL_STATE else: # Check for keys added to state that might not be in the saved copy if 'authorization_key' not in self._state: self._state['authorization_key'] = None addon.log_debug("Loaded persistent auth state") self._init_rdio() def _init_rdio(self): self._rdio = Rdio(self._addon.get_setting('apikey'), self._addon.get_setting('apisecret'), self._state['rdio_api']) def authenticate(self): self._addon.log_notice("Authenticating to Rdio") try: auth_url = self._rdio.begin_authentication('oob') except RdioProtocolException, rpe: self._addon.log_error('Rdio begin_authentication failed: ' + str(rpe)) raise RdioAuthenticationException( 'Check your API credentials in plugin settings') parsed_auth_url = urlparse(auth_url) parsed_params = parse_qs(parsed_auth_url.query) oauth_token = parsed_params['oauth_token'][0] self._addon.log_notice("Authorizing OAuth token") oauth_state = self.call_direct('getOAuth1State', token=oauth_token) verifier = oauth_state['verifier'] self.call_direct('approveOAuth1App', token=oauth_token, verifier=verifier) self._addon.log_notice("Appoved oauth token") self._addon.log_notice("Extracting Rdio cookie") self._state['rdio_cookie'] = self._net.get_cookies( )['.rdio.com']['/']['r'].value self._addon.log_notice("Verifying OAuth token on Rdio API") self._rdio.complete_authentication(verifier) self._addon.log_notice("Getting playback token") self._state['playback_token'] = self._rdio.call( 'getPlaybackToken', domain=self._RDIO_DOMAIN) self._addon.log_notice("Getting current user") self._state['current_user'] = self._rdio.call('currentUser')['key'] self._save_state() self._addon.log_notice("Successfully authenticated to Rdio")
class RdioApi: _RDIO_API_ENDPOINT = 'https://www.rdio.com/api/1' _AMF_ENDPOINT = _RDIO_API_ENDPOINT + '/amf/' _STATE_FILE_NAME = 'rdio-state.json' _RDIO_DOMAIN = 'localhost' _RDIO_PLAYBACK_SECRET = "6JSuiNxJ2cokAK9T2yWbEOPX" _RDIO_PLAYBACK_SECRET_SEED = 5381 _INITIAL_STATE = {'rdio_api': {'auth_state': {}}, 'playback_token': None, 'current_user': None, 'rdio_cookie': None, 'authorization_key': None} def __init__(self, addon): self._addon = addon self._cookie_file = os.path.join(self._addon.get_profile(), 'rdio_cookies.txt') self._net = Net(user_agent = getUserAgent(), cookie_file = self._cookie_file) self._state = addon.load_data(self._STATE_FILE_NAME) if not self._state: addon.log_debug("Persistent auth state not loaded - initialising new state") self._state = self._INITIAL_STATE else: # Check for keys added to state that might not be in the saved copy if 'authorization_key' not in self._state: self._state['authorization_key'] = None addon.log_debug("Loaded persistent auth state") self._init_rdio() def _init_rdio(self): self._rdio = Rdio(self._addon.get_setting('apikey'), self._addon.get_setting('apisecret'), self._state['rdio_api']) def authenticate(self): self._addon.log_notice("Authenticating to Rdio") try: auth_url = self._rdio.begin_authentication('oob') except RdioProtocolException, rpe: self._addon.log_error('Rdio begin_authentication failed: ' + str(rpe)) raise RdioAuthenticationException('Check your API credentials in plugin settings') parsed_auth_url = urlparse(auth_url) parsed_params = parse_qs(parsed_auth_url.query) oauth_token = parsed_params['oauth_token'][0] self._addon.log_notice("Authorizing OAuth token") oauth_state = self.call_direct('getOAuth1State', token = oauth_token) verifier = oauth_state['verifier'] self.call_direct('approveOAuth1App', token = oauth_token, verifier = verifier) self._addon.log_notice("Appoved oauth token") self._addon.log_notice("Extracting Rdio cookie") self._state['rdio_cookie'] = self._net.get_cookies()['.rdio.com']['/']['r'].value self._addon.log_notice("Verifying OAuth token on Rdio API") self._rdio.complete_authentication(verifier) self._addon.log_notice("Getting playback token") self._state['playback_token'] = self._rdio.call('getPlaybackToken', domain=self._RDIO_DOMAIN) self._addon.log_notice("Getting current user") self._state['current_user'] = self._rdio.call('currentUser')['key'] self._save_state() self._addon.log_notice("Successfully authenticated to Rdio")
class RdioApi: _RDIO_API_ENDPOINT = 'https://www.rdio.com/api/1' _AMF_ENDPOINT = _RDIO_API_ENDPOINT + '/amf/' _STATE_FILE_NAME = 'rdio-state.json' _RDIO_DOMAIN = 'localhost' _RDIO_PLAYBACK_SECRET = "6JSuiNxJ2cokAK9T2yWbEOPX" _RDIO_PLAYBACK_SECRET_SEED = 5381 _INITIAL_STATE = {'rdio_api': {'auth_state': {}}, 'playback_token': None, 'current_user': None, 'rdio_cookie': None, 'authorization_key': None} @staticmethod def debug(statement): print statement def __init__(self): self._cookie_file = os.path.join('rdio_cookies.txt') self._net = Net(user_agent = getUserAgent(), cookie_file = self._cookie_file) self.debug('Persistent auth state not loaded') self._state = self._INITIAL_STATE self._init_rdio() self.authenticate() radio = RdioRadio(self) radio.start_radio("r139688", None) track = radio.next_track() if track: print "Play" print track['key'] stream_url = self.resolve_playback_url(track['key']) if stream_url: print "Play this" print stream_url def _init_rdio(self): self._rdio = Rdio('by3ypa9tdw5qbmbthk6x89yf', 'HNMaWqBTND', self._state['rdio_api']) def authenticate(self): self.debug("Authenticating to Rdio") try: auth_url = self._rdio.begin_authentication('oob') except RdioProtocolException, rpe: self.debug('Rdio begin_authentication failed: ' + str(rpe)) raise RdioAuthenticationException('Check your API credentials in plugin settings') parsed_auth_url = urlparse(auth_url) parsed_params = parse_qs(parsed_auth_url.query) oauth_token = parsed_params['oauth_token'][0] self.debug("Authorizing OAuth token") oauth_state = self.call_direct('getOAuth1State', token = oauth_token) verifier = oauth_state['verifier'] self.call_direct('approveOAuth1App', token = oauth_token, verifier = verifier) self.debug("Appoved oauth token") self.debug("Extracting Rdio cookie") self._state['rdio_cookie'] = self._net.get_cookies()['.rdio.com']['/']['r'].value self._state['rdio_cookie'] = '.eJyrVorPyU9OzElVslJQSs1T0lFQigexjQ1NTc0sjcxA_FIg39DCCChkYAnilwH5BrUAvXEOGg.9G6g7Q_SSvlPMzhL81TvUMKUJx0' self.debug("Verifying OAuth token on Rdio API") self._rdio.complete_authentication(verifier) self.debug("Getting playback token") self._state['playback_token'] = self._rdio.call('getPlaybackToken', domain=self._RDIO_DOMAIN) self.debug("Getting current user") self._state['current_user'] = self._rdio.call('currentUser')['key'] self._save_state() self.debug("Successfully authenticated to Rdio")
API.''') opts, args = op.parse_args() if len(args) < 3: op.error('missing required arguments') key = args[0] secret = args[1] query = ' '.join(args[2:]) # Figure out the URL for the Flash player that we're going to # impersonate flash_url = resolve_url(FLASH_PLAYER_URL) # Create a REST API client ra = Rdio(key, secret, {}) # Create an AMF API client svc = RemotingService(AMF_ENDPOINT, referer=flash_url, amf_version=3) svc.addHeader('Auth', chr(5)) rdio_svc = svc.getService('rdio') # Search for the track to play results = ra.search(query=query, types=','.join(['Track']), count=1)['results'] if not results: fail('no results found') # Get a playback token token = ra.getPlaybackToken(domain='std.in')
def rdio(self): if self._cached_rdio is None: self._cached_rdio = Rdio( self.client_id, self.client_secret, self.oauth_state) return self._cached_rdio
def _init_rdio(self): self._rdio = Rdio('by3ypa9tdw5qbmbthk6x89yf', 'HNMaWqBTND', self._state['rdio_api'])
def test_creation_with_urls(self): """Can the Rdio class be instantiated with the optional urls param?""" state = {} rdio_client = Rdio(self.client_id, self.consumer_secret, state, {}) self.assertIsInstance(rdio_client, Rdio)
def test_creation(self): """Can the Rdio class be instantiated?""" state = {} rdio_client = Rdio(self.client_id, self.consumer_secret, state) self.assertIsInstance(rdio_client, Rdio)
def test_creation(self): state = {} rdio_client = Rdio(self.CONSUMER_KEY, self.CONSUMER_SECRET, state) self.assertIsInstance(rdio_client, Rdio)
default=None, help="Description for playlist") parser.add_argument('-c', dest='track_count', action='store', default=3, help="How many tracks per artists to add to playlist. Defaults to 3") args = parser.parse_args() if not args.input_file or not args.pl_name or not args.pl_desc: raise InputError('You must specify an input file containing a list of artists, \ a name for your playlist, and a description for the playlist') # Oauth authentication needed for creating the new playlist state = {} r = Rdio(CONSUMER_KEY, CONSUMER_SECRET, state) print 'Get PIN code from the following URL: %s' % r.begin_authentication('oob') r.complete_authentication(raw_input('enter pin code:')) # Read the list of artists artists = open(args.input_file, 'r').readlines() # Find track keys for top 3 tracks per artist pl_tracks = [] for a in artists: try: url = '/artist/' + a.strip().title().replace(' ', '_').replace('&', '') + '/' artist_key = r.getObjectFromUrl(url=url)['key'] tracks = r.getTracksForArtist(artist=artist_key, count=args.track_count) # make sure key is for a track and for the right artist track_keys = [t['key'] for t in tracks \
def rdio(self): if self.__cached_rdio is None: self.__cached_rdio = Rdio('7v2443fffahpt4fazmmh3hx7', '2nzyX96YAu', self.oauth_state) return self.__cached_rdio