Exemplo n.º 1
0
/**
 * getSpotifyWebAPI function.
 *
 * @access public
 * @param mixed $w
 * @return void
 */
function getSpotifyWebAPI($w, $old_api = null)
{
    if (!$w->internet()) {
        throw new SpotifyWebAPI\SpotifyWebAPIException("No internet connection", 100);
    }
    //
    // Read settings from JSON
    //
    $settings = getSettings($w);
    $oauth_client_id = $settings->oauth_client_id;
    $oauth_client_secret = $settings->oauth_client_secret;
    $oauth_redirect_uri = $settings->oauth_redirect_uri;
    $oauth_access_token = $settings->oauth_access_token;
    $oauth_expires = $settings->oauth_expires;
    $oauth_refresh_token = $settings->oauth_refresh_token;
    if ($old_api == null) {
        // create a new api object
        $session = new SpotifyWebAPI\Session($oauth_client_id, $oauth_client_secret, $oauth_redirect_uri);
        $session->setRefreshToken($oauth_refresh_token);
        $api = new SpotifyWebAPI\SpotifyWebAPI();
    }
    // Check if refresh token necessary
    // if token validity < 20 minutes
    if (time() - $oauth_expires > 2400) {
        if ($old_api != null) {
            // when refresh needed:
            // create a new api object (even if api not null)
            $session = new SpotifyWebAPI\Session($oauth_client_id, $oauth_client_secret, $oauth_redirect_uri);
            $session->setRefreshToken($oauth_refresh_token);
            $api = new SpotifyWebAPI\SpotifyWebAPI();
        }
        if ($session->refreshToken() == true) {
            $oauth_access_token = $session->getAccessToken();
            // Set new token to settings
            $ret = updateSetting($w, 'oauth_access_token', $oauth_access_token);
            if ($ret == false) {
                throw new SpotifyWebAPI\SpotifyWebAPIException("Cannot set oauth_access_token", 100);
            }
            $ret = updateSetting($w, 'oauth_expires', time());
            if ($ret == false) {
                throw new SpotifyWebAPI\SpotifyWebAPIException("Cannot set oauth_expires", 100);
            }
            $api->setAccessToken($oauth_access_token);
        } else {
            throw new SpotifyWebAPI\SpotifyWebAPIException("Token could not be refreshed", 100);
        }
    } else {
        // no need to refresh, the old api is
        // stil valid
        if ($old_api != null) {
            $api = $old_api;
        } else {
            // set the access token for the new api
            $api->setAccessToken($oauth_access_token);
        }
    }
    return $api;
}