# Spotify Random Song Picker A PHP CLI utility that selects a random, unplayed track from a specified Spotify playlist. It handles OAuth2 authorization locally, stores access/refresh tokens, and keeps track of played history in a local JSON file so songs aren't repeated. ## Prerequisites - **PHP 8.5+** with standard extensions (`curl`, `json`) - **Composer** for dependency autoloading - **Spotify Developer Account** (to obtain Client Credentials) --- ## Installation & Environment Setup ### Option A: Using Nix (Recommended) If you use Nix, a `shell.nix` file is provided with PHP 8.5, Composer, and code quality tools pre-configured: ```bash nix-shell composer install ``` ### Option B: Standard Installation 1. Clone or download the repository. 2. Install Composer dependencies to set up PSR-4 autoloading: ```bash composer install ``` --- ## Configuration ### 1. Register a Spotify Application 1. Go to the [Spotify Developer Dashboard](https://developer.spotify.com/dashboard). 2. Create an app and set the **Redirect URI** to: ``` [http://127.0.0.1:8080/callback](http://127.0.0.1:8080/callback) ``` _(Ensure the IP and port match your `.env.php` config below)_ ### 2. Create `.env.php` Create a `.env.php` file in the root directory returning an array with your credentials and configuration: A `.env.example.php` is provided. ```php 'YOUR_SPOTIFY_CLIENT_ID', 'clientSecret' => 'YOUR_SPOTIFY_CLIENT_SECRET', 'redirectURI' => '[http://127.0.0.1:8080/callback](http://127.0.0.1:8080/callback)', 'state' => 'random_secure_string_here', 'serverAddress' => '127.0.0.1', 'serverPort' => 8080, 'serverTimeout' => 60, 'playlistName' => 'My Favorite Playlist', ]; ``` --- ## Usage Run the entry point script from your terminal: ```bash php pick-random-song.php ``` ### Initial Authorization Flow 1. On the first run, the script starts a temporary local HTTP server and prints an authorization URL. 2. Open the URL in your browser and authorize access to your Spotify account. 3. Spotify redirects back to `http://127.0.0.1:8080/callback`, capturing the OAuth code and shutting down the local server automatically. 4. Tokens are saved locally to `.token_storage.json`. Subsequent executions refresh tokens automatically without requiring browser authorization. ### Output Example ```text Picking a random song from the playlist My Favorite Playlist. Looking up the Spotify playlist ID. The song picked is Bring Tha Noize by Anthrax,Public Enemy ``` --- ## How It Works - **`HistoryStorage`**: Saves selected song IDs to `.history_storage.json` along with timestamps. Songs already in the history map are excluded from selection. - **`SpotifyApiClient`**: Resolves the playlist ID by name via `/v1/me/playlists` and fetches track items using `/v1/playlists/{id}/items` with a reduced field response filter. - **`TokenManager`**: Automatically handles initial authorization code flow, access token retrieval, and background refresh when tokens expire.