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

Migrate to Symfony framework

parent ba66f83f
No related branches found
No related tags found
1 merge request!42Resolve "Migrate to Symfony framework"
Showing
with 207 additions and 347 deletions
webpack_encore:
# The path where Encore is building the assets - i.e. Encore.setOutputPath()
output_path: '%kernel.project_dir%/public/build'
# If multiple builds are defined (as shown below), you can disable the default build:
# output_path: false
# if using Encore.enableIntegrityHashes() and need the crossorigin attribute (default: false, or use 'anonymous' or 'use-credentials')
# crossorigin: 'anonymous'
# preload all rendered script and link tags automatically via the http2 Link header
# preload: true
# Throw an exception if the entrypoints.json file is missing or an entry is missing from the data
# strict_mode: false
# if you have multiple builds:
# builds:
# pass "frontend" as the 3rg arg to the Twig functions
# {{ encore_entry_script_tags('entry1', null, 'frontend') }}
# frontend: '%kernel.project_dir%/public/frontend/build'
# Cache the entrypoints.json (rebuild Symfony's cache when entrypoints.json changes)
# Put in config/packages/prod/webpack_encore.yaml
# cache: true
controllers:
resource: ../../src/Controller/
type: annotation
kernel:
resource: ../../src/Kernel.php
type: annotation
_errors:
resource: '@FrameworkBundle/Resources/config/routing/errors.xml'
prefix: /_error
web_profiler_wdt:
resource: '@WebProfilerBundle/Resources/config/routing/wdt.xml'
prefix: /_wdt
web_profiler_profiler:
resource: '@WebProfilerBundle/Resources/config/routing/profiler.xml'
prefix: /_profiler
parameters:
spotify.client_id: '%env(CLIENT_ID)%'
spotify.client_secret: '%env(CLIENT_SECRET)%'
spotify.redirect_uri: '%env(REDIRECT_URI)%'
services:
_defaults:
autowire: true
autoconfigure: true
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
- '../src/Tests/'
App\Controller\:
resource: '../src/Controller/'
tags: ['controller.service_arguments']
{
"devDependencies": {
"@popperjs/core": "^2.11.5",
"@symfony/webpack-encore": "^2.1.0",
"bootstrap": "^5.2.0",
"core-js": "^3.22.8",
"file-loader": "^6.0.0",
"jquery": "^3.6.0",
"node-sass": "^7.0.1",
"popper.js": "^1.16.1",
"regenerator-runtime": "^0.13.2",
"sass-loader": "^13.0.0",
"webpack-notifier": "^1.15.0"
},
"license": "UNLICENSED",
"private": true,
"scripts": {
"dev-server": "encore dev-server",
"dev": "encore dev",
"watch": "encore dev --watch",
"build": "encore production --progress"
},
"dependencies": {
"bootswatch": "^4.5.3"
}
}
<?php
$CLIENT_ID = '';
$CLIENT_SECRET = '';
$REDIRECT_URI = '';
<?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.readthedocs.io/en/latest/configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="bin/.phpunit/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="tests/bootstrap.php"
>
<php>
<ini name="error_reporting" value="-1" />
<server name="APP_ENV" value="test" force="true" />
<server name="SHELL_VERBOSITY" value="-1" />
<server name="SYMFONY_PHPUNIT_REMOVE" value="" />
<server name="SYMFONY_PHPUNIT_VERSION" value="7.5" />
</php>
<testsuites>
<testsuite name="Project Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
<listeners>
<listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener" />
</listeners>
</phpunit>
RewriteEngine On # Use the front controller as index file. It serves as a fallback solution when
RewriteRule ^playlist-generator index.php [L,QSA] # every other rewrite/redirect fails (e.g. in an aliased environment without
RewriteRule ^view-playlist-([^./]+)$ index.php?show-playlist=1&id=$1 [L,QSA] # mod_rewrite). Additionally, this reduces the matching process for the
RewriteRule ^now-playing playing.php [L,QSA] # start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex index.php
# By default, Apache does not evaluate symbolic links if you did not enable this
# feature in your server configuration. Uncomment the following line if you
# install assets as symlinks or if you experience problems related to symlinks
# when compiling LESS/Sass/CoffeScript assets.
# Options +FollowSymlinks
# Disabling MultiViews prevents unwanted negotiation, e.g. "/index" should not resolve
# to the front controller "/index.php" but be rewritten to "/index.php/index".
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
# Determine the RewriteBase automatically and set it as environment variable.
# If you are using Apache aliases to do mass virtual hosting or installed the
# project in a subdirectory, the base path will be prepended to allow proper
# resolution of the index.php file and to redirect to the correct URI. It will
# work in environments without path prefix as well, providing a safe, one-size
# fits all solution. But as you do not need it in this case, you can comment
# the following 2 lines to eliminate the overhead.
RewriteCond %{REQUEST_URI}::$0 ^(/.+)/(.*)::\2$
RewriteRule .* - [E=BASE:%1]
# Sets the HTTP_AUTHORIZATION header removed by Apache
RewriteCond %{HTTP:Authorization} .+
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0]
# Redirect to URI without front controller to prevent duplicate content
# (with and without `/index.php`). Only do this redirect on the initial
# rewrite by Apache and not on subsequent cycles. Otherwise we would get an
# endless redirect loop (request -> rewrite to front controller ->
# redirect -> request -> ...).
# So in case you get a "too many redirects" error or you always get redirected
# to the start page because your Apache does not expose the REDIRECT_STATUS
# environment variable, you have 2 choices:
# - disable this feature by commenting the following 2 lines or
# - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
# following RewriteCond (best solution)
RewriteCond %{ENV:REDIRECT_STATUS} =""
RewriteRule ^index\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]
# If the requested filename exists, simply serve it.
# We only want to let Apache serve files and not directories.
# Rewrite all other queries to the front controller.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ %{ENV:BASE}/index.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
<IfModule mod_alias.c>
# When mod_rewrite is not available, we instruct a temporary redirect of
# the start page to the front controller explicitly so that the website
# and the generated links can still be used.
RedirectMatch 307 ^/$ /index.php/
# RedirectTemp cannot be used instead
</IfModule>
</IfModule>
<?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());
}
<?php
require '../spotify/spotify.php';
$session = new SpotifyWebAPI\Session($CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI);
$state = $session->generateState();
$_SESSION['state'] = $state;
$options = [
'scope' => $SPOTIFY_REQUIRED_SCOPES,
'state' => $state,
];
header('Location: '.$session->getAuthorizeUrl($options));
die();
<?php
require '../spotify/spotify.php';
$session = new SpotifyWebAPI\Session($CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI);
$storedState = $_SESSION['state'];
$state = $_GET['state'];
if ($state !== $storedState) {
header('Location: auth.php');
}
$session->requestAccessToken($_GET['code']);
$_SESSION['accessToken'] = $session->getAccessToken();
$_SESSION['refreshToken'] = $session->getRefreshToken();
header('Location: playlist-generator');
die();
This diff is collapsed.
File moved
File moved
public/img/repository.jpg

9.07 KiB

<?php <?php
require 'access.inc.php'; use App\Kernel;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\ErrorHandler\Debug;
use Symfony\Component\HttpFoundation\Request;
$topArtistsCount = 40; require dirname(__DIR__).'/vendor/autoload.php';
$playlistsCount = 24;
$tracksCountInShortPlaylist = 50; (new Dotenv())->bootEnv(dirname(__DIR__).'/.env');
$tracksCountInLongPlaylist = 100;
$templateData = [ if ($_SERVER['APP_DEBUG']) {
'user' => $user, umask(0000);
'playlists' => [],
'topArtists' => [],
'playlist' => null,
'page' => 'playlist-generator', Debug::enable();
'infos' => [],
'errors' => [],
];
$generatePlaylistFromPlaylist = isset($_GET['generate-playlist-from-playlist']);
$generatePlaylistFromSelectedTopArtists = isset($_GET['generate-playlist-top-artists']);
$generatePlaylistFromRandomTopArtists = isset($_GET['generate-playlist-random-top-artists']);
$generateQuickPlaylistFromDailyMixes = isset($_GET['generate-quick-playlist-from-daily-mixes']);
$generateQuickPlaylistTambouilleMix = isset($_GET['generate-quick-playlist-tambouille-mix']);
$showPlaylistContent = isset($_GET['show-playlist']);
$action = '';
if ($generatePlaylistFromPlaylist) {
$action = 'generate-playlist-from-playlist';
} elseif ($generatePlaylistFromSelectedTopArtists) {
$action = 'generate-playlist-from-selected-top-artists';
} elseif ($generatePlaylistFromRandomTopArtists) {
$action = 'generate-playlist-from-random-top-artists';
} elseif ($generateQuickPlaylistFromDailyMixes) {
$action = 'generate-playlist-from-daily-mixes';
} elseif ($generateQuickPlaylistTambouilleMix) {
$action = 'generate-playlist-tambouille-mix';
} elseif ($showPlaylistContent) {
$action = 'show-playlist-content';
} else {
} }
switch ($action) { if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) {
case 'generate-playlist-from-playlist': Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
$selectedPlaylists = $_GET['selected-playlist']; }
printLog('Will create new playlist with recommendations from playlists: '.join(', ', $selectedPlaylists).'".');
$recommendedTrackIds = [];
$shouldFilterByArtists = isset($_GET['check-playlist-filter-artists']);
printLog('Filter by artists in source playlists: '.($shouldFilterByArtists ? 'yes' : 'no'));
$generateLongPlaylist = isset($_GET['check-playlist-long-playlist']);
printLog('Generate long playlist: '.($generateLongPlaylist ? 'yes' : 'no'));
$artistsInSourcePlaylists = [];
foreach ($selectedPlaylists as $selectedPlaylistId) {
$playlist = $api->getPlaylist($selectedPlaylistId);
printLog('Will get recommendations from tracks in playlist "'.$playlist->name.'".');
$playlistTracks = $playlist->tracks->items;
printLog('Found '.count($playlistTracks).' tracks.');
foreach ($playlistTracks as $track) {
$artists = [];
foreach ($track->track->artists as $artist) {
$artists[] = $artist->name;
$artistsInSourcePlaylists[$artist->id] = 1;
}
printLog('Track "'.$track->track->name.'" ('.join(', ', $artists).')');
$recommendations = $api->getRecommendations([
'seed_tracks' => [$track->track->id],
'limit' => ($generateLongPlaylist ? 50 : 30)
]);
printLog(' -> Got '.count($recommendations->tracks).' recommendatations.');
foreach ($recommendations->tracks as $recommendedTrack) {
$recommendedTrackIds[$recommendedTrack->id] = $recommendedTrack;
}
}
}
if ($shouldFilterByArtists) {
$artistsInSourcePlaylists = array_keys($artistsInSourcePlaylists);
printLog('Filter by artists found in source playlists ('.count($artistsInSourcePlaylists).')');
$filteredTrackIds = [];
foreach ($recommendedTrackIds as $trackId => $track) {
$trackArtistInWantedArtists = false;
foreach ($track->artists as $trackArtist) {
if (\in_array($trackArtist->id, $artistsInSourcePlaylists)) {
$filteredTrackIds[$track->id] = 1;
}
}
}
$recommendedTrackIds = $filteredTrackIds;
}
$newPlaylist = createPlaylistWithRandomTracks(
$api,
$recommendedTrackIds,
$generateLongPlaylist ? $tracksCountInLongPlaylist : $tracksCountInShortPlaylist
);
$templateData['infos'][] = getCreatedPlaylistInformationMessage($api, $newPlaylist);
break;
case 'generate-playlist-from-selected-top-artists':
$selectedArtists = $_GET['selected-artist'];
printLog('Will create new playlist with filterted recommendations from artists: '.join(', ', $selectedArtists).'".');
$recommendedTrackIds = [];
$shouldFilterByArtists = isset($_GET['check-top-artist-filter-artists']);
printLog('Filter by artists in selection: '.($shouldFilterByArtists ? 'yes' : 'no'));
$generateLongPlaylist = isset($_GET['check-top-artist-long-playlist']);
printLog('Generate long playlist: '.($generateLongPlaylist ? 'yes' : 'no'));
foreach ($selectedArtists as $selectedArtist) {
printLog('Get recommendations for artist '.$selectedArtist.'');
$recommendations = $api->getRecommendations([
'seed_artists' => $selectedArtist,
'limit' => 100
]);
printLog(' -> Got '.count($recommendations->tracks).' recommendatations.');
// Filter by artist if requested, remove duplicates
foreach ($recommendations->tracks as $recommendedTrack) {
if ($shouldFilterByArtists) {
$trackArtistInWantedArtists = false;
foreach ($recommendedTrack->artists as $trackArtist) {
if (\in_array($trackArtist->id, $selectedArtists)) {
$recommendedTrackIds[$recommendedTrack->id] = 1;
}
}
} else {
$recommendedTrackIds[$recommendedTrack->id] = 1;
}
}
}
$newPlaylist = createPlaylistWithRandomTracks(
$api,
$recommendedTrackIds,
$generateLongPlaylist ? $tracksCountInLongPlaylist : $tracksCountInShortPlaylist
);
$templateData['infos'][] = getCreatedPlaylistInformationMessage($api, $newPlaylist);
break;
case 'generate-playlist-from-random-top-artists':
$countInTopArtists = random_int(4, 6);
$countInLessTopArtists = random_int(4, 6);
$limitBetweenTopAndLessTop = $topArtistsCount;
$selectedArtists = getRandomArtistsFromTopArtists(
$api,
$countInTopArtists,
$countInLessTopArtists,
$limitBetweenTopAndLessTop
);
printLog('Will create new playlist with filterted recommendations from random artists: '.join(', ', $selectedArtists).'".');
$recommendedTrackIds = [];
$shouldFilterByArtists = isset($_GET['check-top-artist-filter-artists']);
printLog('Filter by artists in selection: '.($shouldFilterByArtists ? 'yes' : 'no'));
$generateLongPlaylist = isset($_GET['check-top-artist-long-playlist']);
printLog('Generate long playlist: '.($generateLongPlaylist ? 'yes' : 'no'));
foreach ($selectedArtists as $selectedArtist) {
printLog('Get recommendations for artist '.$selectedArtist.'');
$recommendations = $api->getRecommendations([
'seed_artists' => $selectedArtist,
'limit' => 100
]);
printLog(' -> Got '.count($recommendations->tracks).' recommendations.');
// Filter by artist if requested, remove duplicates
foreach ($recommendations->tracks as $recommendedTrack) {
if ($shouldFilterByArtists) {
$trackArtistInWantedArtists = false;
foreach ($recommendedTrack->artists as $trackArtist) {
if (\in_array($trackArtist->id, $selectedArtists)) {
$recommendedTrackIds[$recommendedTrack->id] = 1;
}
}
} else {
$recommendedTrackIds[$recommendedTrack->id] = 1;
}
}
}
$newPlaylist = createPlaylistWithRandomTracks(
$api,
$recommendedTrackIds,
$generateLongPlaylist ? $tracksCountInLongPlaylist : $tracksCountInShortPlaylist
);
$templateData['infos'][] = getCreatedPlaylistInformationMessage($api, $newPlaylist);
break;
case 'generate-playlist-from-daily-mixes':
$generateLongPlaylist = isset($_GET['check-quick-create-long-playlist']);
printLog('Generate playlist from Daily Mixes (long playlist :'.($generateLongPlaylist ? 'yes' : 'no').')');
$newPlaylist = createPlaylistFromDailyMixesTracks(
$api,
$generateLongPlaylist ? $tracksCountInLongPlaylist : $tracksCountInShortPlaylist
);
$templateData['infos'][] = getCreatedPlaylistInformationMessage($api, $newPlaylist);
break;
case 'generate-playlist-tambouille-mix':
$generateLongPlaylist = isset($_GET['check-quick-create-long-playlist']);
printLog('Generate tambouille mix playlist (long playlist :'.($generateLongPlaylist ? 'yes' : 'no').')');
$newPlaylist = createPlaylistTambouilleMix(
$api,
$generateLongPlaylist ? $tracksCountInLongPlaylist : $tracksCountInShortPlaylist
);
$templateData['infos'][] = getCreatedPlaylistInformationMessage($api, $newPlaylist);
break;
case 'show-playlist-content':
printLog('Get content of playlist');
$playlistId = $_GET['id'];
$playlist = $api->getPlaylist($playlistId);
$templateData['infos'][] = getPlaylistInformationMessage($api, $playlist);
$templateData['playlist'] = createDisplayablePlaylist($playlist);
break;
default: if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? false) {
$templateData['topArtists'] = $api->getMyTop('artists', ['limit' => $topArtistsCount, 'time_range' => 'short_term'])->items; Request::setTrustedHosts([$trustedHosts]);
$templateData['playlists'] = $api->getUserPlaylists($user['id'], ['limit' => $playlistsCount])->items;
break;
} }
require '../template.php'; $kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment