Skip to content
Snippets Groups Projects
Commit f5ca31ad authored by Benoît Harrault's avatar Benoît Harrault
Browse files

Add "now playing" page

parent 3467804a
No related branches found
No related tags found
1 merge request!40Resolve "Add a "currently playing" page"
RewriteEngine On RewriteEngine On
RewriteRule ^playlist-generator index.php [L,QSA] RewriteRule ^playlist-generator index.php [L,QSA]
RewriteRule ^view-playlist-([^./]+)$ index.php?show-playlist=1&id=$1 [L,QSA] RewriteRule ^view-playlist-([^./]+)$ index.php?show-playlist=1&id=$1 [L,QSA]
RewriteRule ^now-playing playing.php [L,QSA]
<?php
// increase timeout limit
set_time_limit(60);
require '../spotify/spotify.php';
require '../spotify/lib.php';
if (isset($_GET['logout'])) {
$_SESSION['accessToken'] = '';
$_SESSION['refreshToken'] = '';
}
$_SESSION['accessToken'] = isset($_SESSION['accessToken']) ? $_SESSION['accessToken'] : '';
$_SESSION['refreshToken'] = isset($_SESSION['refreshToken']) ? $_SESSION['refreshToken'] : '';
if (!$_SESSION['accessToken']) {
header('Location: auth.php');
die();
}
$session = new SpotifyWebAPI\Session($CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI);
// Use previously requested tokens fetched from session
if ($_SESSION['accessToken']) {
$session->setAccessToken($_SESSION['accessToken']);
$session->setRefreshToken($_SESSION['refreshToken']);
} else {
// Or request a new access token
$session->refreshAccessToken($_SESSION['refreshToken']);
}
$options = [
'scope' => $SPOTIFY_REQUIRED_SCOPES,
'auto_refresh' => true,
];
$api = new SpotifyWebAPI\SpotifyWebAPI($options, $session);
// Save new tokens, they might have been updated
$_SESSION['accessToken'] = $session->getAccessToken();
$_SESSION['refreshToken'] = $session->getRefreshToken();
// ################################################################
$user = [
'id' => '',
'image_url' => '',
'display_name' => '',
'profile_url' => '',
];
try {
$me = $api->me();
$user = [
'id' => $me->id,
'image_url' => \count($me->images) ? $me->images[0]->url : '',
'display_name' => $me->display_name,
'profile_url' => $me->external_urls->spotify,
];
} catch (Exception $ex) {
error_log($ex->getMessage());
}
...@@ -11,10 +11,26 @@ ...@@ -11,10 +11,26 @@
max-width: 1rem; max-width: 1rem;
} }
.spotify-image>img { .spotify-image > img {
border: solid 1px #888; border: solid 1px #888;
text-align: center; text-align: center;
max-height: 1rem; max-height: 1rem;
max-width: 1rem; max-width: 1rem;
margin: auto; margin: auto;
} }
.now-playing {
background-color: black;
color: white;
}
.now-playing-cover {
padding: 2em;
}
.now-playing-title {
padding-top: 4em;
font-size: 400%;
font-weight: bolder;
}
.now-playing-artists {
font-size: 200%;
}
<?php <?php
// increase timeout limit require 'access.inc.php';
set_time_limit(60);
require '../spotify/spotify.php';
require '../spotify/lib.php';
if (isset($_GET['logout'])) {
$_SESSION['accessToken'] = '';
$_SESSION['refreshToken'] = '';
}
$_SESSION['accessToken'] = isset($_SESSION['accessToken']) ? $_SESSION['accessToken'] : '';
$_SESSION['refreshToken'] = isset($_SESSION['refreshToken']) ? $_SESSION['refreshToken'] : '';
if (!$_SESSION['accessToken']) {
header('Location: auth.php');
die();
}
$session = new SpotifyWebAPI\Session($CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI);
// Use previously requested tokens fetched from session
if ($_SESSION['accessToken']) {
$session->setAccessToken($_SESSION['accessToken']);
$session->setRefreshToken($_SESSION['refreshToken']);
} else {
// Or request a new access token
$session->refreshAccessToken($_SESSION['refreshToken']);
}
$options = [
'scope' => $SPOTIFY_REQUIRED_SCOPES,
'auto_refresh' => true,
];
$api = new SpotifyWebAPI\SpotifyWebAPI($options, $session);
// Save new tokens, they might have been updated
$_SESSION['accessToken'] = $session->getAccessToken();
$_SESSION['refreshToken'] = $session->getRefreshToken();
// ################################################################
$user = [
'id' => '',
'image_url' => '',
'display_name' => '',
'profile_url' => '',
];
try {
$me = $api->me();
$user = [
'id' => $me->id,
'image_url' => \count($me->images) ? $me->images[0]->url : '',
'display_name' => $me->display_name,
'profile_url' => $me->external_urls->spotify,
];
} catch (Exception $ex) {
error_log($ex->getMessage());
}
$topArtistsCount = 40; $topArtistsCount = 40;
$playlistsCount = 24; $playlistsCount = 24;
...@@ -74,6 +14,7 @@ $templateData = [ ...@@ -74,6 +14,7 @@ $templateData = [
'topArtists' => [], 'topArtists' => [],
'playlist' => null, 'playlist' => null,
'page' => 'playlist-generator',
'infos' => [], 'infos' => [],
'errors' => [], 'errors' => [],
]; ];
......
function updateNowPlaying() {
var apiUrl = "now-playing?api";
var newContent = fetch(apiUrl)
.then(function (response) {
return response.json();
})
.then(function (data) {
var nowPlayingBlock = document.getElementById("now-playing");
newContent = buildNowPlayingBlock(data);
nowPlayingBlock.innerHTML = newContent;
})
.catch(function (err) {
console.warn("Something went wrong.", err);
newContent =
'<div class="alert alert-warning">Error fetching API data.<br/>You may need to logout and refresh page.</div>';
var nowPlayingBlock = document.getElementById("now-playing");
nowPlayingBlock.innerHTML = newContent;
});
}
function buildNowPlayingBlock(apiResponse) {
var html = `
<div class="container-fluid now-playing">
<div class="row">
<div class="col">
<div class="now-playing-cover"><img src="COVER_URL" class="img-fluid"></div>
</div>
<div class="col">
<div class="now-playing-title">TITLE</div>
<div class="now-playing-artists">ARTISTS</div>
</div>
</div>
</div>`;
var nowPlayingData = apiResponse["playing"];
if (!nowPlayingData) {
return '<div class="alert alert-info">No currently playing track...</div>';
}
var item = nowPlayingData["item"];
var album = item["album"];
var artists = album["artists"];
var artistNames = artists.map((artist) => artist["name"]).join(", ");
var trackName = item["name"];
var coverUrl = album["images"][0]["url"];
html = html.replace("TITLE", trackName);
html = html.replace("ARTISTS", artistNames);
html = html.replace("COVER_URL", coverUrl);
return html;
}
setInterval(updateNowPlaying, 2000);
<?php
require 'access.inc.php';
$templateData = [
'user' => $user,
'page' => 'now-playing',
'infos' => [],
'errors' => [],
];
$callFromApi = isset($_GET['api']);
if ($callFromApi) {
$nowPlaying = $api->getMyCurrentTrack();
$data = [
'playing' => $nowPlaying,
];
echo json_encode($data);
} else {
require '../template.php';
}
...@@ -16,4 +16,5 @@ $SPOTIFY_REQUIRED_SCOPES = [ ...@@ -16,4 +16,5 @@ $SPOTIFY_REQUIRED_SCOPES = [
'playlist-modify-public', 'playlist-modify-public',
'user-read-private', 'user-read-private',
'user-top-read', 'user-top-read',
'user-read-currently-playing',
]; ];
...@@ -29,17 +29,23 @@ ...@@ -29,17 +29,23 @@
<div class="collapse navbar-collapse" id="navbarNav"> <div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav"> <ul class="navbar-nav">
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="<?php echo $templateData['user']['profile_url']; ?>">Profile</a> <a class="nav-link<?php echo ($templateData['page'] === 'playlist-generator') ? ' active' : ''; ?>" href="/playlist-generator">🔀 Playlist generator</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="?logout">Logout</a> <a class="nav-link<?php echo ($templateData['page'] === 'now-playing') ? ' active' : ''; ?>" href="/now-playing">🎧 Now playing</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?php echo $templateData['user']['profile_url']; ?>">👤 Profile</a>
</li>
<li class="nav-item">
<a class="nav-link" href="?logout">🚪 Logout</a>
</li> </li>
</ul> </ul>
</div> </div>
</div> </div>
</nav> </nav>
<div class="container-fluid mb-5"> <div class="container-fluid mb-5 mt-2">
<?php if (count($templateData['errors'])) { ?> <?php if (count($templateData['errors'])) { ?>
<?php foreach ($templateData['errors'] as $message) { ?> <?php foreach ($templateData['errors'] as $message) { ?>
...@@ -53,7 +59,7 @@ ...@@ -53,7 +59,7 @@
<?php } ?> <?php } ?>
<?php } ?> <?php } ?>
<?php if (count($templateData['topArtists'])) { ?> <?php if (array_key_exists('topArtists', $templateData) && count($templateData['topArtists'])) { ?>
<form class="clearfix mt-2"> <form class="clearfix mt-2">
<div class="row"> <div class="row">
<div class="col-md-12"> <div class="col-md-12">
...@@ -155,7 +161,7 @@ ...@@ -155,7 +161,7 @@
</form> </form>
<?php } ?> <?php } ?>
<?php if (count($templateData['playlists'])) { ?> <?php if (array_key_exists('playlists', $templateData) && count($templateData['playlists'])) { ?>
<form class="clearfix"> <form class="clearfix">
<legend>Generate playlist from tracks in existing playlist:</legend> <legend>Generate playlist from tracks in existing playlist:</legend>
<ul class="list-unstyled row row-cols-md-2 row-cols-1"> <ul class="list-unstyled row row-cols-md-2 row-cols-1">
...@@ -214,7 +220,7 @@ ...@@ -214,7 +220,7 @@
</form> </form>
<?php } ?> <?php } ?>
<?php if ($templateData['playlist'] && count($templateData['playlist'])) { ?> <?php if (array_key_exists('playlist', $templateData) && count($templateData['playlist'])) { ?>
<div class="alert alert-info"> <div class="alert alert-info">
<ul> <ul>
<?php foreach ($templateData['playlist']['artists'] as $artist) { ?> <?php foreach ($templateData['playlist']['artists'] as $artist) { ?>
...@@ -224,6 +230,13 @@ ...@@ -224,6 +230,13 @@
</div> </div>
<?php } ?> <?php } ?>
<?php if ($templateData['page'] === 'now-playing') { ?>
<div id="now-playing">
</div>
<script src="js/now-playing.js"></script>
<?php } ?>
</div> </div>
<script src="js/bootstrap.min.js"></script> <script src="js/bootstrap.min.js"></script>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment