Defines a Soundcloud client object
332242
def get_client
      init_opts = {
        client_id:     @CLIENT_ID,
        client_secret: @CLIENT_SECRET
      }

      if username? and password?
        init_opts[:username] = @USERNAME
        init_opts[:password] = @PASSWORD
      end

      Soundcloud.new(init_opts)
    end
1001599
function createMediaObject(item, callback) {
    var transaction = item.transaction;
    delete item.transaction;

    var constructor = createConstructor(item, strict);

    item = constructor.item;
    delete constructor.item;

    var params = item.params || {};
    delete item.params;

    if (params.mediaPipeline == undefined && host instanceof register.classes
      .MediaPipeline)
      params.mediaPipeline = host;

    var params_ = extend({}, params)
    item.constructorParams = checkParams(params_, constructor.constructorParams,
      item.type);

    if (Object.keys(params_)) {
      item.properties = params_;
    }

    if (!Object.keys(item.constructorParams).length)
      delete item.constructorParams;

    try {
      var mediaObject = createObject(constructor)
    } catch (error) {
      return callback(error)
    };

    Object.defineProperty(item, 'object', {
      value: mediaObject
    });

    encodeCreate(transaction, item, callback);

    return mediaObject
  }
763491
function Client (globalRequest, maxSockets) {
  var emptyResponse = JSON.parse(JSON.stringify(response))
  var body = ''
  var httpAgent = null
  var httpsAgent = null

  if (maxSockets) {
    httpAgent = new http.Agent({ maxSockets: maxSockets })
    httpsAgent = new https.Agent({ maxSockets: maxSockets })
  }

  // utility function to create an empty request object
  this.emptyRequest = function () {
    return JSON.parse(JSON.stringify(request))
  }

  // utility function to detect empty objects
  function isEmpty (obj) {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        return false
      }
    }
    return true
  }

  // add query paramaters to a URL
  function buildPath (basePath, queryParams) {
    basePath = basePath.concat('?')
    var url = basePath.concat(queryString.stringify(queryParams))
    return url
  }

  function buildRequest (globalRequest, endpointRequest) {
    var request = JSON.parse(JSON.stringify(globalRequest))
    request.host = endpointRequest.host || globalRequest.host
    request.method = endpointRequest.method

    if (endpointRequest.port) {
      request.port = endpointRequest.port
    }

    // build URL
    request.path = !isEmpty(endpointRequest.queryParams)
      ? buildPath(endpointRequest.path, endpointRequest.queryParams)
      : endpointRequest.path

    // add headers
    if (!isEmpty(endpointRequest.headers)) {
      for (var attrname in endpointRequest.headers) {
        request.headers[attrname] = endpointRequest.headers[attrname]
      }
    }

    // add the request body's content length
    if (!isEmpty(endpointRequest.body)) {
      body = JSON.stringify(endpointRequest.body)
      request.headers['Content-Length'] = Buffer.byteLength(body)
      request.headers['Content-Type'] = 'application/json'
    }

    // if maxsockets where provided use the apropriate agent
    if (maxSockets) {
      request.agent = endpointRequest.test === true ? httpAgent : httpsAgent
    }
    return request
  }

  // API is the main interface to the API.
  this.API = function (endpointRequest, callback) {
    var request = buildRequest(globalRequest, endpointRequest)

    var requestProtocol = null;

    if (endpointRequest.test === true) {
      requestProtocol = http
      request.port = endpointRequest.port
    } else {
      requestProtocol = https
    }

    var httpRequest = requestProtocol.request(request, function (httpResponse) {
      var responseBody = ''

      // cature the response from the API
      httpResponse.on('data', function (chunk) {
        responseBody += chunk
      })

      // after the call is complete, build the response object
      httpResponse.on('end', function () {
        var response = JSON.parse(JSON.stringify(emptyResponse))
        response.statusCode = httpResponse.statusCode
        response.body = responseBody
        response.headers = httpResponse.headers
        callback(response)
      })
    })

    httpRequest.on('error', function (e) {
      var response = JSON.parse(JSON.stringify(emptyResponse))
      response.statusCode = e.statusCode || 500
      response.body = JSON.stringify({
        message: e.message,
        name: e.name,
        stack: e.stack
      })
      callback(response)
    })

    // if thre is a request body, sent it
    if (!isEmpty(endpointRequest.body)) {
      httpRequest.write(body)
    }

    httpRequest.end()
  }

  return this
}
232877
def get_hard_track_url(item_id):
    

    streams_url = "https://api.soundcloud.com/i1/tracks/%s/streams/?client_id=%s&app_version=%s" % (
    item_id, AGGRESSIVE_CLIENT_ID, APP_VERSION)
    response = requests.get(streams_url)
    json_response = response.json()

    if response.status_code == 200:
        hard_track_url = json_response['http_mp3_128_url']
        return hard_track_url
    else:
        return None
885292
function CFClient(config) {
    if (!(config instanceof CFConfig)) {
        throw CFClientException(
            new Error('Given tokens must be an instance of CFConfig'),
            'tokens must be an instance of CFConfig that contains: "protocol", "host", "username", "password", "skipSslValidation');
    }

    this.config = config;
    this.infoData = null;
    this.client = null;
}
168676
function ( source ) {
      var _this = this;
      this.path = source ? source.src : this.path;

      this.isLoaded = false;
      this.progress = 0;

      !window.soundManager && !smLoading && loadSM.call( this );

      if ( window.soundManager ) {
        this.audio = soundManager.createSound({
          id       : 'dancer' + Math.random() + '',
          url      : this.path,
          stream   : true,
          autoPlay : false,
          autoLoad : true,
          whileplaying : function () {
            _this.update();
          },
          whileloading : function () {
            _this.progress = this.bytesLoaded / this.bytesTotal;
          },
          onload   : function () {
            _this.fft = new FFT( SAMPLE_SIZE, SAMPLE_RATE );
            _this.signal = new Float32Array( SAMPLE_SIZE );
            _this.waveform = new Float32Array( SAMPLE_SIZE );
            _this.isLoaded = true;
            _this.progress = 1;
            _this.dancer.trigger( 'loaded' );
          }
        });
        this.dancer.audio = this.audio;
      }

      // Returns audio if SM already loaded -- otherwise,
      // sets dancer instance's audio property after load
      return this.audio;
    }
612674
function getById(hypemId, callback) {
        var options = {
            method: 'HEAD',
            url: HYPEM_GO_URL + hypemId,
            followRedirect: false,
            timeout: FIVE_SECONDS_IN_MILLIS
        };

        request(options, function (error, response) {
            if (error || response.statusCode !== 302) {
                callback(error, null);
                return;
            }
            var songUrl = response.headers.location;
            if (isSoundcloudUrl(songUrl)) {
                var soundcloudUrl = getNormalizedSoundcloudUrl(songUrl);
                callback(null, soundcloudUrl);
            } else {
                requestHypemKey(hypemId, function (error, hypemKey) {
                    if (error) {
                        callback(error, null);
                        return;
                    }
                    requestMp3Url(hypemId, hypemKey, callback);
                });
            }
        });
    }
558088
def get_mixcloud_data(url):
    

    data = {}
    request = requests.get(url)
    preview_mp3_url = request.text.split('m-preview="')[1].split('" m-preview-light')[0]
    song_uuid = request.text.split('m-preview="')[1].split('" m-preview-light')[0].split('previews/')[1].split('.mp3')[0]

    # Fish for the m4a..
    for server in range(1, 23):
        # Ex: https://stream6.mixcloud.com/c/m4a/64/1/2/0/9/30fe-23aa-40da-9bf3-4bee2fba649d.m4a
        mp3_url = "https://stream" + str(server) + ".mixcloud.com/c/m4a/64/" + song_uuid + '.m4a'
        try:
            if requests.head(mp3_url).status_code == 200:
                if '?' in mp3_url:
                    mp3_url = mp3_url.split('?')[0]
                break
        except Exception as e:
            continue

    full_title = request.text.split("<title>")[1].split(" | Mixcloud")[0]
    title = full_title.split(' by ')[0].strip()
    artist = full_title.split(' by ')[1].strip()

    img_thumbnail_url = request.text.split('m-thumbnail-url="')[1].split(" ng-class")[0]
    artwork_url = img_thumbnail_url.replace('60/', '300/').replace('60/', '300/').replace('//', 'https://').replace('"',
                                                                                                                    '')

    data['mp3_url'] = mp3_url
    data['title'] = title
    data['artist'] = artist
    data['artwork_url'] = artwork_url
    data['year'] = None

    return data
907593
def share(track_id=None, url=None, users=None):
    

    client = get_client()

    if url:
        track_id = client.get('/resolve', url=url).id

    if not users:
        return client.get('/tracks/%d/permissions' % track_id)

    permissions = {'user_id': []}

    for username in users:
        # check cache for user
        user = settings.users.get(username, None)
        if user:
            permissions['user_id'].append(user['id'])
        else:
            user = client.get('/resolve', url='http://soundcloud.com/%s' % username)
            permissions['user_id'].append(user.id)
            settings.users[username] = user.obj
    settings.save()

    return client.put('/tracks/%d/permissions' % track_id, permissions=permissions)
1132443
public void play(SoundCloudTrack track) {
        checkState();
        ArrayList<SoundCloudTrack> tracks = mPlayerPlaylist.getPlaylist().getTracks();
        int position = tracks.indexOf(track);
        if (position > -1) {
            mPlayerPlaylist.setPlayingTrack(position);
            PlaybackService.play(getContext(), mClientKey, track);
        }
    }
1168734
function(o) {
      var self = this;

      // If we don't have an AudioContext created yet, run the setup.
      if (!Howler.ctx) {
        setupAudioContext();
      }

      // Setup user-defined default properties.
      self._autoplay = o.autoplay || false;
      self._format = (typeof o.format !== 'string') ? o.format : [o.format];
      self._html5 = o.html5 || false;
      self._muted = o.mute || false;
      self._loop = o.loop || false;
      self._pool = o.pool || 5;
      self._preload = (typeof o.preload === 'boolean') ? o.preload : true;
      self._rate = o.rate || 1;
      self._sprite = o.sprite || {};
      self._src = (typeof o.src !== 'string') ? o.src : [o.src];
      self._volume = o.volume !== undefined ? o.volume : 1;
      self._xhrWithCredentials = o.xhrWithCredentials || false;

      // Setup all other default properties.
      self._duration = 0;
      self._state = 'unloaded';
      self._sounds = [];
      self._endTimers = {};
      self._queue = [];
      self._playLock = false;

      // Setup event listeners.
      self._onend = o.onend ? [{fn: o.onend}] : [];
      self._onfade = o.onfade ? [{fn: o.onfade}] : [];
      self._onload = o.onload ? [{fn: o.onload}] : [];
      self._onloaderror = o.onloaderror ? [{fn: o.onloaderror}] : [];
      self._onplayerror = o.onplayerror ? [{fn: o.onplayerror}] : [];
      self._onpause = o.onpause ? [{fn: o.onpause}] : [];
      self._onplay = o.onplay ? [{fn: o.onplay}] : [];
      self._onstop = o.onstop ? [{fn: o.onstop}] : [];
      self._onmute = o.onmute ? [{fn: o.onmute}] : [];
      self._onvolume = o.onvolume ? [{fn: o.onvolume}] : [];
      self._onrate = o.onrate ? [{fn: o.onrate}] : [];
      self._onseek = o.onseek ? [{fn: o.onseek}] : [];
      self._onunlock = o.onunlock ? [{fn: o.onunlock}] : [];
      self._onresume = [];

      // Web Audio or HTML5 Audio?
      self._webAudio = Howler.usingWebAudio && !self._html5;

      // Automatically try to enable audio.
      if (typeof Howler.ctx !== 'undefined' && Howler.ctx && Howler.autoUnlock) {
        Howler._unlockAudio();
      }

      // Keep track of this Howl group in the global controller.
      Howler._howls.push(self);

      // If they selected autoplay, add a play event to the load queue.
      if (self._autoplay) {
        self._queue.push({
          event: 'play',
          action: function() {
            self.play();
          }
        });
      }

      // Load the source file unless otherwise specified.
      if (self._preload) {
        self.load();
      }

      return self;
    }
242427
private void playTrack(SoundCloudTrack track) {
        pauseTimer();
        try {
            // acquire lock on wifi.
            mWifiLock.acquire();

            mIsPaused = false;
            mIsPausedAfterAudioFocusChanged = false;
            mHasAlreadyPlayed = true;

            // 1 - UPDATE ALL VISUAL CALLBACK FIRST TO IMPROVE USER EXPERIENCE

            updateNotification();
            // update playback state as well as meta data.
            mMediaSession.setPlaybackState(MediaSessionWrapper.PLAYBACK_STATE_PLAYING);
            // start loading of the artwork.
            loadArtwork(this,
                    SoundCloudArtworkHelper.getArtworkUrl(track, SoundCloudArtworkHelper.XXXLARGE));
            // broadcast events
            Intent intent = new Intent(PlaybackListener.ACTION_ON_TRACK_PLAYED);
            intent.putExtra(PlaybackListener.EXTRA_KEY_TRACK, track);
            mLocalBroadcastManager.sendBroadcast(intent);
            Intent bufferingStart = new Intent(PlaybackListener.ACTION_ON_BUFFERING_STARTED);
            mLocalBroadcastManager.sendBroadcast(bufferingStart);

            // 2 - THEN PREPARE THE TRACK STREAMING

            // set media player to stop state in order to be able to call prepare.
            mMediaPlayer.reset();

            // set new data source
            mMediaPlayer.setDataSource(track.getStreamUrl() + SOUND_CLOUD_CLIENT_ID_PARAM
                    + mSoundCloundClientId);

            // Try to gain the audio focus before preparing and starting the media player.
            if (mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)
                    == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                // prepare asynchronously the stream to be able to handle new action on the
                // service thread such as a pause command.
                mIsPreparing = true;
                mMediaPlayer.prepareAsync();
            }

        } catch (IOException e) {
            Log.e(TAG, "File referencing not exist : " + track);
        }
    }
784657
function() {
		var api_url,
			self = this;

		// Create Dom element
		this._el.content_item	= TL.Dom.create("div", "tl-media-item tl-media-iframe tl-media-spotify", this._el.content);

		// Get Media ID
		if (this.data.url.match(/^spotify:track/) || this.data.url.match(/^spotify:album/) || this.data.url.match(/^spotify:user:.+:playlist:/)) {
			this.media_id = this.data.url;
		}

		if (this.data.url.match(/spotify\.com\/track\/(.+)/)) {
			this.media_id = "spotify:track:" + this.data.url.match(/spotify\.com\/track\/(.+)/)[1];
		} else if (this.data.url.match(/spotify\.com\/album\/(.+)/)) {
			this.media_id = "spotify:album:" + this.data.url.match(/spotify\.com\/album\/(.+)/)[1];
		} else if (this.data.url.match(/spotify\.com\/user\/(.+?)\/playlist\/(.+)/)) {
			var user = this.data.url.match(/spotify\.com\/user\/(.+?)\/playlist\/(.+)/)[1];
			var playlist = this.data.url.match(/spotify\.com\/user\/(.+?)\/playlist\/(.+)/)[2];
			this.media_id = "spotify:user:" + user + ":playlist:" + playlist;
		} else if (this.data.url.match(/spotify\.com\/artist\/(.+)/)) {
			var artist = this.data.url.match(/spotify\.com\/artist\/(.+)/)[1];
			this.media_id = "spotify:artist:" + artist;
		}


		if (this.media_id) {
			// API URL
			api_url = "https://embed.spotify.com/?uri=" + this.media_id + "&theme=white&view=coverart";

			this.player = TL.Dom.create("iframe", "tl-media-shadow", this._el.content_item);
			this.player.width 		= "100%";
			this.player.height 		= "100%";
			this.player.frameBorder = "0";
			this.player.src 		= api_url;

			// After Loaded
			this.onLoaded();

		} else {
				this.loadErrorDisplay(this._('spotify_invalid_url'));
		}
	}
722169
function(object, object_id) {
    var res = {
      client_id:     this._credentials.client_id,
      client_secret: this._credentials.client_secret,
      object:        object,
      aspect:        'media',
      verify_token:  'hummingbird',
      callback_url:  this._callback
    };
    if (object_id) res.object_id = object_id;
    return res;
  }
177845
function addTrackToNewPlaylist(options) {
    return new Promise(function (resolve, reject) {
        var form = new FormData();
        form.append('format', 'json');

        if (!options.tracks) {
            return reject('Error while addTrackToNewPlaylist options.tracks is null');
        } else {
            _.each(options.tracks, function (track) {
                form.append('playlist[tracks][][id]', track.id);
            });
        }
        if (!options.title) {
            return reject('Error while addTrackToNewPlaylist options.title is null');
        } else {
            form.append('playlist[title]', options.title);
        }
        if (!options.sharing) {
            return reject('Error while addTrackToNewPlaylist options.sharing is null');
        } else {
            form.append('playlist[sharing]', options.sharing);
        }
        if (!options.oauth_token) {
            return reject('Error while addTrackToNewPlaylist options.oauth_token is null');
        } else {
            form.append('oauth_token', options.oauth_token);
        }

        form.getLength(function (err, length) {

            fetch(`https://api.soundcloud.com/playlists?oauth_token=${options.oauth_token}`, {
                method: 'POST',
                body: form,
                headers: {'content-length': length}
            }).then(function (res) {

                if (res.status === 201) {
                    if (DEBUG_MODE_ON) {
                        console.log(`INFO: addTrackToNewPlaylist, OK -> ${res.statusCode}.`);
                    }
                    return res.json();
                } else {
                    return null;
                }
            }).then(function (json) {
                if (!json) {
                    reject();
                } else {
                    if (DEBUG_MODE_ON) {
                        console.log('INFO: addTrack successful');
                    }
                    resolve(json);
                }
            }).catch(function (e) {
                reject(e);
            });

        });
    });
}
46265
def client(cls, config):
        
        if not hasattr(cls, "_client"):
            cls._client = statsd.StatsClient(config.STATSD_HOST, config.STATSD_PORT, config.STATSD_PREFIX)
        return cls._client
941953
def volume_attach(provider, names, **kwargs):
    '''
    

    '''
    client = _get_client()
    info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
    return info