Skip to content
This repository has been archived by the owner on Mar 23, 2024. It is now read-only.

Commit

Permalink
:octocat: examples cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
codemasher committed Mar 5, 2024
1 parent 1081d98 commit 0a0858d
Show file tree
Hide file tree
Showing 16 changed files with 93 additions and 256 deletions.
2 changes: 1 addition & 1 deletion examples/OAuthExampleSessionStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public function getAccessToken(string $service = null):AccessToken{
}
}

throw new OAuthStorageException('token not found');
throw new OAuthStorageException(sprintf('token for service "%s" not found', $service));
}

}
10 changes: 4 additions & 6 deletions examples/Providers/GitHub/gist-spotify-top-tracks.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,7 @@
* @license MIT
*/

namespace chillerlan\OAuthAppExamples\GitHub;

use chillerlan\HTTP\Utils\MessageUtil;
use RuntimeException;
use function sprintf;

/**
* invoke the spotify client first
Expand All @@ -22,12 +18,14 @@
require_once __DIR__.'/../Spotify/spotify-common.php';

/**
* @var \chillerlan\OAuth\Providers\GitHub $github
* @var \Psr\Log\LoggerInterface $logger
* @var \OAuthProviderFactory $factory
* @var \chillerlan\OAuth\Providers\GitHub $github
*/

require_once __DIR__.'/github-common.php';

$logger = $factory->getLogger();

$gistID = null; // set to null to create a new gist
$gistname = '🎵 My Spotify Top Tracks';
$description = 'auto generated spotify track list';
Expand Down
20 changes: 2 additions & 18 deletions examples/Providers/GitHub/github-common.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,11 @@
* @license MIT
*/

namespace chillerlan\OAuthAppExamples\GitHub;

use chillerlan\OAuth\Core\AccessToken;
use chillerlan\OAuth\Providers\GitHub;

$ENVVAR = 'GITHUB';

/**
* @var \Psr\Http\Client\ClientInterface $http
* @var \chillerlan\Settings\SettingsContainerInterface $options
* @var \chillerlan\OAuth\Storage\OAuthStorageInterface $storage
* @var \Psr\Log\LoggerInterface $logger
* @var string $CFGDIR
*/

require_once __DIR__.'/../../provider-example-common.php';

$github = new GitHub($http, $options, $logger);
$github->setStorage($storage);

if(!$storage->hasAccessToken('GitHub')){
$token = (new AccessToken)->fromJSON(file_get_contents($CFGDIR.'/GitHub.token.json'));
$github->storeAccessToken($token);
}
/** @var \OAuthProviderFactory $factory */
$github = $factory->getProvider(GitHub::class, $ENVVAR);
Empty file.
23 changes: 3 additions & 20 deletions examples/Providers/LastFM/lastfm-common.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,11 @@
* @license MIT
*/

namespace chillerlan\OAuthExamples\Providers\LastFM;

use chillerlan\OAuth\Core\AccessToken;
use chillerlan\OAuth\Providers\LastFM;
use function file_get_contents;

$ENVVAR = 'LASTFM';

/**
* @var \Psr\Http\Client\ClientInterface $http
* @var \chillerlan\Settings\SettingsContainerInterface $options
* @var \chillerlan\OAuth\Storage\OAuthStorageInterface $storage
* @var \Psr\Log\LoggerInterface $logger
* @var string $CFGDIR
*/

require_once __DIR__.'/../provider-api-example-common.php';

$lfm = new LastFM($http, $options, $logger);
$lfm->setStorage($storage);
require_once __DIR__.'/../../provider-example-common.php';

if(!$storage->hasAccessToken()){
$token = (new AccessToken)->fromJSON(file_get_contents(($CFGDIR ?? '').'/LastFM.token.json'));
$lfm->storeAccessToken($token);
}
/** @var \OAuthProviderFactory $factory */
$lfm = $factory->getProvider(LastFM::class, $ENVVAR);
64 changes: 15 additions & 49 deletions examples/Providers/LastFM/topalbum-patchwork.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,55 +13,16 @@
* @noinspection PhpComposerExtensionStubsInspection
*/

namespace chillerlan\OAuthExamples\Providers\LastFM;

use chillerlan\HTTP\Utils\MessageUtil;
use Exception;
use function array_column;
use function array_shift;
use function count;
use function dirname;
use function file_exists;
use function file_get_contents;
use function file_put_contents;
use function header;
use function imagecolorallocate;
use function imagecopyresampled;
use function imagecreatefromgif;
use function imagecreatefromjpeg;
use function imagecreatefrompng;
use function imagecreatetruecolor;
use function imagedestroy;
use function imagefill;
use function imagejpeg;
use function imagesx;
use function imagesy;
use function intval;
use function json_decode;
use function json_encode;
use function max;
use function min;
use function mkdir;
use function parse_url;
use function sha1;
use function strlen;
use function substr;
use function trim;
use const JSON_PRETTY_PRINT;
use const PHP_URL_PATH;

$ENVVAR = 'LASTFM';

/**
* @var \Psr\Log\LoggerInterface $logger
* @var \chillerlan\OAuth\Providers\LastFM $lfm
*/

require_once __DIR__.'/lastfm-common.php';

$urlcache = './urlcache';
$imgcache = './cache'; // public access

$urlcache = './urlcache'; // downloaded album covers
$imgcache = './cache'; // generated patchworks

try{
$request = json_decode(file_get_contents('php://input'));
Expand Down Expand Up @@ -115,13 +76,19 @@
continue;
}

$path = getImage($img[(count($img) - 1)]->{'#text'}, $urlcache);
$ext = substr($path, (strlen($path) - 3));
$res[] = match($ext){
'jpg' => imagecreatefromjpeg($path),
'png' => imagecreatefrompng($path),
'gif' => imagecreatefromgif($path),
};
try{
$path = getImage($img[(count($img) - 1)]->{'#text'}, $urlcache);
$ext = pathinfo($path, PATHINFO_EXTENSION);

$res[] = match($ext){
'jpg' => imagecreatefromjpeg($path),
'png' => imagecreatefrompng($path),
'gif' => imagecreatefromgif($path),
};
}
catch(Throwable){
continue;
}
}

$patchwork = imagecreatetruecolor(($cols * $imageSize), ($rows * $imageSize));
Expand Down Expand Up @@ -160,7 +127,6 @@
exit;

function getImage(string $url, string $urlcache):string{

$path = parse_url($url, PHP_URL_PATH);

if(file_exists($urlcache.$path)){
Expand Down
Empty file.
27 changes: 6 additions & 21 deletions examples/Providers/Spotify/MixesDBTrackSearch.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,7 @@
* @license MIT
*/

namespace chillerlan\OAuthExamples\Providers\Spotify;

use chillerlan\HTTP\Utils\MessageUtil;
use function array_column;
use function array_map;
use function array_merge;
use function explode;
use function file_get_contents;
use function implode;
use function json_decode;
use function preg_replace;
use function sprintf;
use function str_replace;
use function strtotime;
use function trim;
use function usleep;

/**
*
Expand All @@ -35,11 +20,11 @@ class MixesDBTrackSearch extends SpotifyClient{
*/
public function getTracks(
string $clubnightsJSON,
int $since,
int $until,
array $find = [],
int $limit = 5,
bool $playlistPerSet = false,
int $since,
int $until,
array $find = [],
int $limit = 5,
bool $playlistPerSet = false,
):void{
$clubnights = json_decode(file_get_contents($clubnightsJSON), true);
$tracks = [];
Expand Down Expand Up @@ -69,7 +54,7 @@ public function getTracks(

$this->logger->info(sprintf('search: %s', $track));

$response = $this->spotify->request('/v1/search', [
$response = $this->request('/v1/search', [
'q' => $this->getSearchTerm($track),
'type' => 'track',
'limit' => $limit,
Expand Down
55 changes: 26 additions & 29 deletions examples/Providers/Spotify/SpotifyClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,23 @@
* @license MIT
*/

namespace chillerlan\OAuthExamples\Providers\Spotify;

use chillerlan\HTTP\Utils\MessageUtil;
use chillerlan\OAuth\OAuthOptions;
use chillerlan\OAuth\Providers\Spotify;
use chillerlan\OAuth\Storage\MemoryStorage;
use chillerlan\OAuth\Storage\OAuthStorageInterface;
use chillerlan\Settings\SettingsContainerInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use RuntimeException;
use function array_chunk;
use function array_map;
use function array_values;
use function file_exists;
use function file_get_contents;
use function file_put_contents;
use function json_decode;
use function json_encode;
use function rtrim;
use function sprintf;
use function usleep;
use const JSON_PRETTY_PRINT;
use const JSON_UNESCAPED_SLASHES;
use const JSON_UNESCAPED_UNICODE;

/**
*
*/
abstract class SpotifyClient{
class SpotifyClient extends Spotify{

protected const sleepTimer = 250000; // sleep between requests (µs)

Expand All @@ -43,13 +34,19 @@ abstract class SpotifyClient{
protected array $artists = [];
protected array $albums = [];

/**
*
*/
public function __construct(
protected Spotify $spotify,
protected LoggerInterface $logger = new NullLogger(),
OAuthOptions|SettingsContainerInterface $options,
ClientInterface $http,
RequestFactoryInterface $requestFactory,
StreamFactoryInterface $streamFactory,
UriFactoryInterface $uriFactory,
OAuthStorageInterface $storage = new MemoryStorage,
LoggerInterface $logger = new NullLogger
){
parent::__construct($options, $http, $requestFactory, $streamFactory, $uriFactory, $storage, $logger);

// set the servicename to the original provider's name so that we use the same tokens
$this->serviceName = 'Spotify';
$this->getMe();
}

Expand Down Expand Up @@ -95,7 +92,7 @@ protected function loadFromFile(array $vars, string $dir):bool{
* fetch the currently authenticated user
*/
protected function getMe():void{
$me = $this->spotify->request('/v1/me');
$me = $this->me();

if($me->getStatusCode() !== 200){
throw new RuntimeException('could not fetch data from /me endpoint');
Expand Down Expand Up @@ -125,7 +122,7 @@ public function getFollowedArtists():array{
];

do{
$meFollowing = $this->spotify->request('/v1/me/following', $params);
$meFollowing = $this->request('/v1/me/following', $params);
$data = MessageUtil::decodeJSON($meFollowing);

if($meFollowing->getStatusCode() === 200){
Expand Down Expand Up @@ -167,7 +164,7 @@ public function getArtistReleases():array{

foreach($this->artists as $artistID => $artist){
// WTB bulk endpoint /artists/albums?ids=artist_id1,artist_id2,...
$artistAlbums = $this->spotify->request(sprintf('/v1/artists/%s/albums', $artistID), ['market' => $this->market]);
$artistAlbums = $this->request(sprintf('/v1/artists/%s/albums', $artistID), ['market' => $this->market]);

if($artistAlbums->getStatusCode() !== 200){
$this->logger->warning(sprintf('could not fetch albums for artist "%s"', $artist->name));
Expand Down Expand Up @@ -212,7 +209,7 @@ public function getPlaylist(string $playlistID):array{
$retry = 0;

do{
$response = $this->spotify->request(sprintf('/v1/playlists/%s/tracks', $playlistID), $params);
$response = $this->request(sprintf('/v1/playlists/%s/tracks', $playlistID), $params);

if($retry > 3){
throw new RuntimeException('error while retrieving playlist');
Expand Down Expand Up @@ -254,7 +251,7 @@ public function getPlaylist(string $playlistID):array{
*/
public function createPlaylist(string $name, string $description):string{

$createPlaylist = $this->spotify->request(
$createPlaylist = $this->request(
path : sprintf('/v1/users/%s/playlists', $this->id),
method : 'POST',
body : [
Expand Down Expand Up @@ -296,7 +293,7 @@ public function addTracks(string $playlistID, array $trackIDs):static{

foreach($uris as $i => $chunk){

$playlistAddTracks = $this->spotify->request(
$playlistAddTracks = $this->request(
path : sprintf('/v1/playlists/%s/tracks', $playlistID),
method : 'POST',
body : ['uris' => $chunk],
Expand Down
Loading

0 comments on commit 0a0858d

Please sign in to comment.