def main():
    # create a client object with your app credentials
    client = soundcloud.Client(client_id=os.environ['SC_CLIENT_ID'])

    # find all sounds of buskers licensed under 'creative commons share alike'
    tracks = client.get('/tracks',
                        user_id='36111',
                        limit=200,
                        linked_partitioning=1)

    for track in tracks.collection:
        slug = track.permalink
        with open(os.path.join('songs', slug + '.md'), 'w') as f:
            f.write('title: %s\n' % track.title)
            f.write('date: %s\n' % track.created_at[:10])
            f.write('duration: %s\n' % track.duration)
            f.write('tags: %r\n' % track.tag_list.split(' '))
            f.write('\n')
            f.write('%s\n' % track.description)

        if hasattr(track, 'download_url'):
            print('Downloading %s...' % track.title)
            resp = requests.get(
                track.download_url,
                params={'client_id': os.environ['SC_CLIENT_ID']})
            if resp.status_code != 200:
                print('WARNING: could not download '
                      'http://soundcloud.com/travis-briggs/%s' %
                      track.permalink)
            with open(os.path.join('static', slug + '.mp3'), 'wb') as f:
                for chunk in resp.iter_content(1024):
                    f.write(chunk)
        else:
            print('WARNING: could not download '
                  'http://soundcloud.com/travis-briggs/%s' % track.permalink)
Beispiel #2
0
    def get_1(self):
        artist = self.get_artist_from_session()
        artist_id = artist.strkey

        client = soundcloud.Client(access_token=artist.access_token)
        current_user = client.get('/me')

        self.say(current_user.fields())
        logging.info('artist exists')

        # track login on mixpanel
        properties = {
            '$username': current_user.username,
            'city': current_user.city,
            'country': current_user.country,
            '$last_login': str(dt.now())
        }
        # set the first name for display purposes
        properties['$first_name'] = \
         current_user.full_name or current_user.username
        logging.info(properties)
        rpc = mixpanel.track_person(str(current_user.id), properties)

        # create a session for the artist
        self.log_in(artist_id)

        # complete mixpanel rpc
        mp_result = rpc.get_result()
        self.say(mp_result.content)
        self.say(type(mp_result.content))
        assert int(mp_result.content) == 1, \
         'mixpanel "login" rpc for user {} failed'.format(str(current_user.id))
Beispiel #3
0
def findplaylist():
    client_id = "2t9loNQH90kzJcsFCODdigxfp325aq4z"
    client = soundcloud.Client(client_id=client_id)
    url = raw_input("url : ")
    playlistsearch = client.get("http://api.soundcloud.com/resolve?url=" +
                                url + "&client_id=" + client_id)
    print "PLAYLIST = ", playlistsearch.id, playlistsearch.title, playlistsearch.user
    print "TRACKLIST = "
    for track in playlistsearch.tracks:
        print track['title']

    question = raw_input("download all of these ? (y/n)")

    if question == "y":
        save_path = raw_input("directory to save in : ")
        print "dowloading"
        for track in playlistsearch.tracks:
            track_id = str(track['id'])
            trackname = track['title']
            trackname = format_filename(trackname)
            url = "http://api.soundcloud.com/tracks/" + track_id + "/download?client_id=" + client_id
            r = requests.get(url)
            completefilename = str(os.path.join(save_path, trackname + ".mp3"))

            if os.path.exists(completefilename) == True:
                print "file already exists, skipping"
                continue
            else:
                open(completefilename, 'wb').write(r.content)
                print "completed", track['title'], url
    else:
        raise SystemExit(0)
Beispiel #4
0
def soundcloud_upload(data, token, file_path):
    """
    Upload a file to SoundCloud

    :param data:      associative array containing SoundCloud metadata
    :param token:     OAuth2 client access token
    :param file_path: path to the file being uploaded

    :return: JSON formatted string of the SoundCloud response object
    :rtype: string
    """
    client = soundcloud.Client(access_token=token)
    # Open the file with urllib2 if it's a cloud file
    data['asset_data'] = open(
        file_path,
        'rb') if os.path.isfile(file_path) else urllib2.urlopen(file_path)
    try:
        logger.info('Uploading track: {0}'.format(data))
        track = client.post('/tracks', track=data)
    except Exception as e:
        logger.info('Error uploading track {title}: {0}'.format(
            e.message, **data))
        raise e
    data['asset_data'].close()
    return json.dumps(track.fields())
Beispiel #5
0
	def __init__(self, _clientId, _clientSecret, _username, _password, _bpm=0, _pages=2):
		self.client = soundcloud.Client(client_id=_clientId,
			client_secret=_clientSecret,
			username=_username,
			password=_password)
		self.bpm = _bpm
		self.pages = _pages
Beispiel #6
0
def main(tg):
    # Read keys.ini file at program start (don't forget to put your keys in there!)
    keyConfig = configparser.ConfigParser()
    keyConfig.read(["keys.ini", "config.ini", "..\keys.ini", "..\config.ini"])

    chat_id = tg.message['chat']['id']
    message = tg.message['text']
    user = tg.message['from']['username'] \
        if not tg.message['from']['username'] == '' \
        else tg.message['from']['first_name'] + (' ' + tg.message['from']['last_name']) \
        if not tg.message['from']['last_name'] == '' \
        else ''
    botName = tg.misc['bot_info']['username']

    message = message.replace(botName, '')

    splitText = message.split(' ', 1)

    requestText = splitText[1] if ' ' in message else ''

    bot = telegram.Bot(keyConfig['BOT_CONFIG']['token'])

    client = soundcloud.Client(client_id=keyConfig.get('Soundcloud', 'SC_CLIENT_ID'))
    track = client.get('/tracks', q=requestText, sharing='public')
    if len(track) >= 1:
        bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.TYPING)
        return bot.sendMessage(chat_id=chat_id, text=(user + ': ' if not user == '' else '') + \
                                                     track[0].permalink_url)

    bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.TYPING)
    return bot.sendMessage(chat_id=chat_id, text='I\'m sorry ' + (user if not user == '' else 'Dave') + \
                                                 ', I\'m afraid I can\'t find the sound of ' + \
                                                 requestText + '.')
Beispiel #7
0
    def exchange_code(self, code, callback_url, client_id, client_secret):
        """Fetch auth and user data from the soundcloud api

        Returns a dictionary of a auth and user object.
        """
        auth_obj = self.client.exchange_token(code)
        try:
            expires_in = auth_obj.expires_in
            refresh_token = auth_obj.refresh_token
        except:
            expires_in = 864000
            refresh_token = None

        auth_data = {
            'access_token': auth_obj.access_token,
            'refresh_token': refresh_token,
            'expires_in': expires_in,
            'scope': auth_obj.scope
        }

        self.client = soundcloud.Client(access_token=auth_obj.access_token)
        user_obj = self.client.get('/me')

        user_data = {
            'id': user_obj.id,
            'country': user_obj.country,
            'username': user_obj.username,
            'profile_url': user_obj.permalink_url,
            'avatar_url': user_obj.avatar_url
        }

        response = {'auth': auth_data, 'user': user_data}

        return response
    def execute(self, quals, columns, **kwargs):
        """
        This method is invoked every time a SELECT is executed
        on the foreign table.

        Parses the quals argument searching for search criteria,
        contacts soundcloud using the official soundcloud python library
        and returns the search results inside the columns of the foreign table.

        Available columns are: title, url, search.

        :param list quals:a list of conditions which are used
          are used in the WHERE part of the select and can be used
          to restrict the number of the results
        :param list columns: the columns of the foreign table
        """
        if not quals:
            msg = 'specify a search term'
            log_to_postgres(level=ERROR, message=msg)
        # create a client object using the apikey
        client = soundcloud.Client(client_id=self.apikey)
        for qual in quals:
            # Manage quals, pass it as search therm if the field is 'search'
            if qual.field_name == "search" or qual.operator == "=":
                # Perform a simple search using the qual value
                # and the soundcloud client (limit to 10 results)
                tracks = client.get('/tracks', q=qual.value, limit=10)
                for track in tracks:
                    # Format the response line
                    line = {
                        'title': track.title,
                        'url': track.permalink_url,
                        'search': qual.value
                    }
                    yield line
Beispiel #9
0
    def __init__(s, auth):
        s.client = soundcloud.Client(client_id=auth.CLIENT_ID,
                                     client_secret=auth.CLIENT_SECRET,
                                     username=auth.username,
                                     password=auth.password)

        if not s.client:
            Abort("failed to login to soundcloud")
Beispiel #10
0
  def __init__(self, track):
    self.track = track

    # UNSAFE
    self.client = soundcloud.Client(client_id='YOUR CLIENT ID',
                                   client_secret='YOUR CLIENT SECRET',
                                   username='******',
                                   password='******')
Beispiel #11
0
    def __init__(self):
        client = soundcloud.Client(client_id=self.client_id,
                                   client_secret=self.cliend_secreat,
                                   redirect_url=self.redirect_url)


#if __name__ === '__main__':
#    SoundCloudSearch("Eminem Yourself")
Beispiel #12
0
def songs(source):
    
    client = soundcloud.Client(client_id='Bo3dsyRIYdM3bp3SnNQ9xl3ax0IyWu38')

    # find all tracks with the genre chosen by user
    tracks = client.get('/tracks', genres=source)

    return tracks
Beispiel #13
0
def soundcloud_login():
    with open('/home/ubuntu/soundcloud_creds.properties','r') as fin:
        d = dict( l.rstrip().split('=') for l in fin)
    client = soundcloud.Client(client_id=d['client_id'], 
                            client_secret=d['client_secret'],
                            username=d['username'],
                           password=d['password'])
    return client
Beispiel #14
0
def token():
    # create client object with app credentials
    client = soundcloud.Client(client_id=client_id,
                               client_secret=client_secret,
                               redirect_uri='http://localhost:5000/token')
    code = request.args.get('code', '')
    access_token = client.exchange_token(code)
    return 'hey bro: ' + access_token.access_token + ' lol'
Beispiel #15
0
 def client(self):
     """V1 API Endpoints"""
     return soundcloud.Client(
         client_id=self.secret_config["client_id"],
         client_secret=self.secret_config["client_secret"],
         username=self.secret_config["username"],
         password=self.secret_config["password"],
     )
Beispiel #16
0
def enumerate_plsts(client_id, base_url):
    #list all playlists for given user
    client = soundcloud.Client(client_id=client_id)
    user = client.get('/resolve', url=base_url)
    playlists = client.get('/users/%d/playlists' % user.id)

    for i in range(0, len(playlists)):
        print('%d - %s' % (i, playlists[i].title))
Beispiel #17
0
 def login_url(self, callback_url, client_id, client_secret):
     """Generates a login url, for the user to authenticate the app."""
     self.client = soundcloud.Client(
         client_id=client_id,
         client_secret=client_secret,
         redirect_uri=callback_url
     )
     return self.client.authorize_url()
Beispiel #18
0
def like_track(request):
    try:
        url = request.GET.get('url')
        SOUNDCLOUD_KEY = settings.SOCIAL_AUTH_SOUNDCLOUD_KEY
        client = soundcloud.Client(client_id=SOUNDCLOUD_KEY)
        track = client.get('/resolve', url=url)
        if request.user and request.user.is_anonymous(
        ) is False and request.user.is_superuser is False:
            soundcloud_data = UserSocialAuth.objects.get(user=request.user,
                                                         provider="soundcloud")
            if soundcloud_data:
                client = soundcloud.Client(
                    access_token=soundcloud_data.extra_data['access_token'])
                response = client.put('/me/favorites/' + str(track.id))
                print json.loads(response.text)
    except Exception, e:
        print e
Beispiel #19
0
def connect(request):

    # Creating the soundcloud client object
    client = soundcloud.Client(client_id=SOUNCLOUD_CLIENT_ID,
                               client_secret=SOUNCLOUD_CLIENT_SECRET,
                               redirect_uri=SOUNCLOUD_REDIRECT_URI)

    # Redirecting the user to the authorized URL for authorizing the app
    return HttpResponseRedirect(client.authorize_url())
Beispiel #20
0
def soundcloudStream():
    global embed
    client = soundcloud.Client(client_id='7dbcff055170cdc49bc5f6d555009c39')
    track = client.get('/tracks/' + str(embed[0]))
    stream_url = client.get(track.stream_url, allow_redirects=False)
    url = stream_url.location
    wavfile = urllib.request.urlopen(url)
    with open(str(embed[1]) + ".wav", 'wb') as output:
        output.write(wavfile.read())
def test_bad_responses(fake):
    """Anything in the 400 or 500 range should raise an exception."""
    client = soundcloud.Client(client_id='foo', client_secret='foo')
    for status in range(400, 423):
        with response_status(fake, status):
            assert_raises(HTTPError, lambda: client.get('/me'))
    for status in (500, 501, 502, 503, 504, 505):
        with response_status(fake, status):
            assert_raises(HTTPError, lambda: client.get('/me'))
Beispiel #22
0
def go(user, path, client_id, client_secret):
    """Download all of a SoundCloud user's liked tracks to a directory."""
    print("Initializing SoundCloud client...")
    global client
    client = soundcloud.Client(
        client_id=client_id,
        client_secret=client_secret)
    print("Client initialization successful. Getting a listing of tracks from SoundCloud.")
    dlSongs(getLikes('/users/' + resolveUid(user) + '/likes/tracks'), path)
def run(channel_id):
    ''' Driver for program '''

    print "Starting scraper..."
    with open('credentials.json', 'r') as readfile:
        credentials = json.load(readfile).get('soundcloud')
    client = soundcloud.Client(client_id=credentials.get('client_id'))
    scrape(client, channel_id)
    print "Ending scraper..."
Beispiel #24
0
    def __init__(self):
        self.client = soundcloud.Client(
            client_id='jDtJOucgyacN8CELJ8vR3vJ4KuDwcTGQ',
            client_secret='PTlD6rjotNUi3En6Eo4Ctrxyho4PqSWk',
            username='******',
            password='******')

        self.client_id = str(self.client.get('/me').id)
        self.client_name = self.client.get('/me').username
Beispiel #25
0
	def __init__(self, args=None):
		self.args = args
		self.url = args.url
		self.dirname = args.dir
		self.client = soundcloud.Client(client_id=secret)
		self.session = requests.Session()
		self.session.mount("http://", requests.adapters.HTTPAdapter(max_retries=2))
		self.session.mount("https://", requests.adapters.HTTPAdapter(max_retries=2))
		self.completed = 0
 def __init__(self, oauth_token):
     self.__api = soundcloud.Client(client_id=self.CLIENT_ID,
                                    access_token=oauth_token)
     self.queue = list()
     self.queue_index = -1
     self.play_queue_order = list()
     self.play_modes = TizEnumeration(["NORMAL", "SHUFFLE"])
     self.current_play_mode = self.play_modes.NORMAL
     self.now_playing_track = None
Beispiel #27
0
def init_soundcloud(token_store):
    """
    Returns SoundCloud client to use.
    """
    logging.debug('Initialising SoundCloud client...')
    return soundcloud.Client(client_id=env['SOUNDCLOUD_CLIENT_ID'],
                             client_secret=env['SOUNDCLOUD_CLIENT_SECRET'],
                             username=env['SOUNDCLOUD_ACCOUNT_USERNAME'],
                             password=env['SOUNDCLOUD_ACCOUNT_PASSWORD'])
def upload_soundcloud(title, song_path, token):
    # create a client object with access token
    client = soundcloud.Client(access_token=token)
    # upload audio file
    track = client.post('/tracks',
                        track={
                            'title': title,
                            'asset_data': open(song_path, 'rb')
                        })
Beispiel #29
0
def getSoundCloudSong(data):
    data.canvas.create_text(710,
                            790,
                            text="Finding Random SoundCloud Song...",
                            fill="white",
                            font="Helvetica 20")

    # create a client object with your app credentials. Unused now due to authorization issues in reading tracks
    client = soundcloud.Client(
        client_id='97cb40ade708093de0c9276826222021',
        client_secret='f63f9a9d2594537edc2f6e5acd0d5995',
        username='******',
        password='******')

    #tracks = client.get('/tracks', genres='edm', license='cc-by-sa') #Gets the top 10 tracks from this search. Commented due to authorization issues

    #A bit of brute force to find a working track id for soundcloud, because of authorization issues
    client = soundcloud.Client(client_id='97cb40ade708093de0c9276826222021')
    i = random.randrange(9986) + 30709986
    track = None

    while (track == None):
        try:
            track = client.get('/tracks/' + str(i))
            stream_url = client.get(track.stream_url, allow_redirects=False)
        except Exception as e:
            print("<1> Error: ", str(e))
            track = None
            i = random.randrange(9986) + 30709986

    # print the tracks stream URL
    print(stream_url.location)

    #We sound a song, now let's download it
    tarSong = stream_url.location
    fileName = randomString(10)
    urllib.request.urlretrieve(tarSong, "input.mp3")

    #And now let's convert it
    subprocess.call(['ffmpeg', '-i', 'input.mp3', fileName + '.wav'])

    #And finally, let's push it into the game and begin
    setSong(fileName + '.wav')
Beispiel #30
0
def resolve(url):
    '''
	Transforms a 'url' into a soundcloud object. False if not found.
	'''
    client_id = "nF5U0gNsNB8529U1rHetpIywdIlnEKk7"
    client = soundcloud.Client(client_id=client_id)
    try:
        track = client.get("/resolve?url=" + url)
        return track
    except:
        new_client_id = get_client_id()
        if not new_client_id:
            return False
        try:
            client = soundcloud.Client(client_id=new_client_id)
            track = client.get("/resolve?url=" + url)
            return track
        except:
            return False