Commit 74bc8fa7 authored by Dainis Abols's avatar Dainis Abols
Browse files

Radio Naba init

Version 3.3.3
parents
Pipeline #145 canceled with stages
<?php
namespace Lu\LuNabamusic\Controller;
use Lu\LuNabamusic\Domain\Model\Play;
use Lu\LuNabamusic\Domain\Model\Top;
use Lu\LuNabamusic\Domain\Repository\SongRepository;
use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Lang\LanguageService;
/**
* Class FrontController
*
* @author Dainis Abols <dainis.abols@lu.lv>
* @owner University of Latvia
* @version 2.0.0
* @since 20.07.2018
*
* @package Lu\LuNabamusic\Controller
*/
class FrontController extends ActionController
{
/**
* @var SongRepository
*/
private $songRepository;
/**
* Frontend-Session
*
* @var \Lu\LuNabamusic\Domain\Session\FrontendSessionHandler
*/
protected $frontendSession;
/**
* Frontend- or Backend-Session
* The type of session is set automatically in initializeAction().
*
* @var \Lu\LuNabamusic\Domain\Session\SessionHandler
*/
protected $session;
/**
* Current page ID
*
* @var int
*/
protected $pageUid;
/**
* Plugin configuration settings
*
* @var array
*/
private $conf;
/**
* MusicController constructor.
*
* Assign page ID
*/
public function __construct()
{
parent::__construct();
if (!$this->pageUid) {
$this->pageUid = $_REQUEST['id'];
}
// Fetch config
$this->conf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get('lu_nabamusic');
}
/**
* Inject the product repository
*
* @param \Lu\LuNabamusic\Domain\Repository\SongRepository $songRepository
*/
public function injectProductRepository(SongRepository $songRepository)
{
$this->songRepository = $songRepository;
}
/**
* List Action
*
* @return void
*/
public function listAction()
{
// Preset used variables
$playModel = new Play();
$swap = $this->settings['pluginType'] ?? '';
$cache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_naba_top');
$data = [];
// Swap view types @TODO Make data gather to methods!
switch ($swap) {
default:
case "frontpageTop":
$data = $this->getTopSongs();
$this->setTemplateUrl('Front/MiniList.html');
break;
case "extendedTop":
$data = $this->getTopSongs();
// Add CSS and JavaScript files
$pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
$pageRenderer->addCssFile("/typo3conf/ext/lu_nabamusic/Resources/Public/Css/tinyPlayer.css");
$pageRenderer->addCssFile("https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css");
$pageRenderer->addJsFooterFile("/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/scripts.js");
$pageRenderer->addJsFooterFile("/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/howler.min.js");
$pageRenderer->addJsFooterFile("/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/tinyPlayer.js");
break;
case "frontpageLive":
// Check to small song list, if voting not allowed
$data = [
'programme' => $playModel->getCurrentProgramme(),
'songString' => $playModel->getCurrentSong(true),
];
// Add scripts for correct frontend remndering
$pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
$pageRenderer->addJsFooterFile("/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/jquery-3.4.1.min.js");
$pageRenderer->addJsFooterFile("/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/jquery.hammer.js");
$pageRenderer->addJsFooterFile("/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/lunabamusic.js");
// Set custom view
$this->setTemplateUrl('Front/FrontLive.html');
break;
case "monthSearch":
$args = $this->request->getArguments();
$pickedMonth = $args['month'];
$limit = $this->settings['songsInTop'] ? $this->settings['songsInTop'] : 50;
if ($pickedMonth) {
$data['mostPlayedSongs'] = [
'songs' => $playModel->getMostPlayedSongs($limit, $pickedMonth),
'month' => $pickedMonth
];
} else {
$data['mostPlayedSongs'] = [
'songs' => $cache->get('most_played_songs') ?: $playModel->getMostPlayedSongs($limit),
];
}
$this->setTemplateUrl('Front/SongHistoryMonth.html');
$this->request->setArguments([]);
$pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
$pageRenderer->addCssFile("https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css");
$pageRenderer->addJsFooterFile("/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/bootstrap-datepicker.min.js");
$pageRenderer->addJsFooterFile("/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/bootstrap-datepicker.lv.min.js");
$pageRenderer->addCssFile("/typo3conf/ext/lu_nabamusic/Resources/Public/Css/bootstrap-datepicker3.min.css");
$pageRenderer->addJsFooterFile("/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/datepicker-setup.js");
break;
case "search":
$args = $this->request->getArguments();
$pickedDay = $args['date'];
$query = $args['name'];
// If date or query was passed in search for them
// Otherwise get songs played on current day
if ($pickedDay || $query) {
$data['mostPlayedSongs'] = [
'songs' => $playModel->searchSongs($pickedDay, $query),
'date' => $pickedDay,
'name' => $query
];
} else {
$data['mostPlayedSongs'] = [
'songs' => $cache->get('todays_songs') ?: $playModel->getTodaysSongs(),
];
}
$this->setTemplateUrl('Front/SongSearch.html');
$this->request->setArguments([]);
$pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
$pageRenderer->addCssFile("https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css");
$pageRenderer->addJsFooterFile("/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/bootstrap-datepicker.min.js");
$pageRenderer->addJsFooterFile("/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/bootstrap-datepicker.lv.min.js");
$pageRenderer->addCssFile("/typo3conf/ext/lu_nabamusic/Resources/Public/Css/bootstrap-datepicker3.min.css");
$pageRenderer->addJsFooterFile("/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/datepicker-setup.js");
break;
}
// Assign data to view
$this->view->assign('data', $data);
}
/**
* Get songs from cache
*
* @return mixed
*/
private function getTopSongs()
{
$cache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_naba_top');
$data = $cache->get('naba_top_'.$this->settings['songsInTop']);
$UriBuilder = $this->controllerContext->getUriBuilder()->reset()->setCreateAbsoluteUri(true);
// If songs list is not cached do it now
if(!$data) {
GeneralUtility::makeInstance(Top::class)->executeCron();
$data = $cache->get('naba_top_'.$this->settings['songsInTop']);
}
foreach ($data['songs'] as $key => $item) {
// Create voting url
$data['songs'][$key]['votes']['current']['plus'] = $UriBuilder->reset()->setCreateAbsoluteUri(true)->uriFor('increase', ['time_period' => $data['currentDate'], 'song_id' => $item[0], 'admin' => true], 'Votes');
}
// Add full list view url
$data['fullListView'] = !empty($this->settings['fullListView']) ? $this->settings['fullListView'] : 0;
return $data;
}
/**
* Returns the LanguageService
*
* @return LanguageService
*/
protected function getLanguageService()
{
return $GLOBALS['LANG'] ?? new LanguageService();
}
/**
* Get a CSRF token
*
* @param bool $tokenOnly Set it to TRUE to get only the token, otherwise including the &moduleToken= as prefix
*
* @return string
*/
protected function getToken($tokenOnly = false)
{
$token = FormProtectionFactory::get()->generateToken('moduleCall', 'web_LuNabamusicMusic');
if ($tokenOnly) {
return $token;
} else {
return '&moduleToken='.$token;
}
}
/**
* Get tempate path with config params and sets the it
*
* @param $name
*
* @return string
*/
private function setTemplateUrl($name)
{
$extbaseFrameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
if (is_array($extbaseFrameworkConfiguration['view']['templateRootPaths'])) {
for ($k = sizeof($extbaseFrameworkConfiguration['view']['templateRootPaths']); $k--; $k < 0) {
$templateRootPath = $extbaseFrameworkConfiguration['view']['templateRootPaths'][$k];
if (!empty($templateRootPath)) {
break;
}
}
}
$tempaltePath = trim($templateRootPath, ' /') . '/' . $name;
$this->view->setTemplatePathAndFilename($tempaltePath);
}
}
<?php
namespace Lu\LuNabamusic\Controller;
use Lu\LuNabamusic\Domain\Model\Song;
use Lu\LuNabamusic\Domain\Repository\SongRepository;
use TYPO3\CMS\Backend\Routing\UriBuilder as BackendUriBuilder;
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Backend\View\BackendTemplateView;
use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\HttpUtility;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Extbase\Mvc\View\ViewInterface;
use TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder;
use TYPO3\CMS\Lang\LanguageService;
/**
* Class MusicController
*
* @author Dainis Abols <dainis.abols@lu.lv>
* @owner University of Latvia
* @version 2.0.0
* @since 11.07.2018
*
* @package Lu\LuNabamusic\Controller
*/
class MusicController extends ActionController
{
/**
* @var SongRepository
*/
private $songRepository;
/**
* Backend Template Container
*
* @var string
*/
protected $defaultViewObjectName = \TYPO3\CMS\Backend\View\BackendTemplateView::class;
/**
* Backend-Session
*
* @var \Lu\LuNabamusic\Domain\Session\BackendSessionHandler
*/
protected $backendSession;
/**
* Frontend-Session
*
* @var \Lu\LuNabamusic\Domain\Session\FrontendSessionHandler
*/
protected $frontendSession;
/**
* Frontend- or Backend-Session
* The type of session is set automatically in initializeAction().
*
* @var \Lu\LuNabamusic\Domain\Session\SessionHandler
*/
protected $session;
/**
* Current page ID
*
* @var int
*/
protected $pageUid;
/**
* MusicController constructor.
*
* Assign page ID
*/
public function __construct()
{
parent::__construct();
if (!$this->pageUid) {
$this->pageUid = $_REQUEST['id'];
}
}
/**
* Set up the doc header properly here
*
* @param ViewInterface $view
*
* @return void
*/
protected function initializeView(ViewInterface $view)
{
parent::initializeView($view);
if ($view instanceof BackendTemplateView) {
$view->getModuleTemplate()->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/Modal');
}
}
/**
* Inject the entire repository
*
* @param \Lu\LuNabamusic\Domain\Repository\SongRepository $songRepository
*/
public function injectEntryRepository(SongRepository $songRepository)
{
$this->songRepository = $songRepository;
}
/**
* Define custom JS
*/
private function defineCustomJs()
{
$pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
$pageRenderer->addRequireJsConfiguration([
'paths' => [
'chart-bundle' => '/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/Backend/Chart.bundle',
'chart' => '/typo3conf/ext/lu_nabamusic/Resources/Public/JavaScript/Backend/Chart',
],
'shim' => [
'chart-bundle' => ['jquery'],
'chart' => ['jquery', 'chart-bundle'],
],
]);
$pageRenderer->loadRequireJsModule('TYPO3/CMS/LuNabamusic/Backend/LuNabamusic');
}
/**
* List Action
*
* @return void
*/
public function listAction()
{
// Preset used variables
$data = [];
$SongModel = new Song();
$UriBuilder = $this->controllerContext->getUriBuilder()->reset()->setCreateAbsoluteUri(true);
$routeBuilder = GeneralUtility::makeInstance(BackendUriBuilder::class);
// Get request, this will need to be mage into `$this->request->getArguments()`
$request = $_REQUEST['tx_lunabamusic'] ?? [];
$sort = !empty($request['sort']) ? $request['sort'] : 'votesweekago';
$order = !empty($request['order']) ? $request['order'] : 'desc';
// Load songs
$songs = $this->songRepository->findAll();
if (count($songs)) {
$returnUrl = 'index.php?route=/web/LuNabamusicMusic/&id='.$this->pageUid.$this->getToken();
foreach ($songs as $item) {
// Load extra data for songs
$item->loadAdditionalInfo();
// Add edit url
$url = $routeBuilder->buildUriFromRoute(
'record_edit', [
'edit[tx_lunabamusic_domain_model_song]['.$item->getUid().']' => 'edit',
'returnUrl' => $returnUrl,
]
);
$item->setOnclick("window.location.href='{$url}'; return false;");
// Load votes
$item->loadVotes();
$votes = $item->getVotes();
$data['votes'] = [
'current' => $votes['current']['start']->format('d.m.Y H:i').' - '.$votes['current']['end']->format('d.m.Y H:i'),
'weekAgo' => $votes['weekAgo']['start']->format('d.m.Y H:i').' - '.$votes['weekAgo']['end']->format('d.m.Y H:i'),
'2WeekAgo' => $votes['2WeeksAgo']['start']->format('d.m.Y H:i').' - '.$votes['2WeeksAgo']['end']->format('d.m.Y H:i'),
];
// Create vote increase and decrease links
$item->votes['current']['plus'] = $UriBuilder->reset()->uriFor('increase', ['time_period' => $votes['current']['start']->getTimestamp(), 'song_id' => $item->getUid(), 'admin' => true], 'Votes');
$item->votes['current']['minus'] = $UriBuilder->reset()->uriFor('decrease', ['time_period' => $votes['current']['start']->getTimestamp(), 'song_id' => $item->getUid(), 'admin' => true], 'Votes');
$item->votes['weekAgo']['plus'] = $UriBuilder->reset()->uriFor('increase', ['time_period' => $votes['weekAgo']['start']->getTimestamp(), 'song_id' => $item->getUid(), 'admin' => true], 'Votes');
$item->votes['weekAgo']['minus'] = $UriBuilder->reset()->uriFor('decrease', ['time_period' => $votes['weekAgo']['start']->getTimestamp(), 'song_id' => $item->getUid(), 'admin' => true], 'Votes');
$item->votes['2WeeksAgo']['plus'] = $UriBuilder->reset()->uriFor('increase', ['time_period' => $votes['2WeeksAgo']['start']->getTimestamp(), 'song_id' => $item->getUid(), 'admin' => true], 'Votes');
$item->votes['2WeeksAgo']['minus'] = $UriBuilder->reset()->uriFor('decrease', ['time_period' => $votes['2WeeksAgo']['start']->getTimestamp(), 'song_id' => $item->getUid(), 'admin' => true], 'Votes');
// Load weeks
$item->loadWeeks();
// Add detailed info for graphs
$item->loadDetailInfo();
// Assign value to data array
$data['songs'][] = $item->toArray();
}
// Create sort links
$data['weekOrder']['current'] = $UriBuilder->setArguments([
'tx_lunabamusic[action]' => 'list',
'tx_lunabamusic[sort]' => 'votescurrent',
])->buildBackendUri();
$data['weekOrder']['weekAgo'] = $UriBuilder->setArguments([
'tx_lunabamusic[action]' => 'list',
'tx_lunabamusic[sort]' => 'votesweekago',
])->buildBackendUri();
$data['weekOrder']['2WeeksAgo'] = $UriBuilder->setArguments([
'tx_lunabamusic[action]' => 'list',
'tx_lunabamusic[sort]' => 'votes2weeksago',
])->buildBackendUri();
// Set currently active sort
if ($sort == 'votescurrent') {
$data['sort']['current'] = true;
} else if ($sort == 'votes2weeksago') {
$data['sort']['2WeeksAgo'] = true;
} else {
$data['sort']['weekAgo'] = true;
}
// Resort data
$SongModel->sortArrayByKey($data['songs'], 'artist');
$SongModel->sortArrayByKey($data['songs'], $sort, true, false);
}
// Add header buttons
$this->createButtons();
// Add custom JS
$this->defineCustomJs();
// Assign data to view
$this->view->assign('data', $data);
}
/**
* Redirects to native content create window
*/
public function addAction()
{
// Predefine values/models
$songModel = new Song();
$table = $songModel->getTableName();
$routeBuilder = GeneralUtility::makeInstance(BackendUriBuilder::class);
// Create redirect url
$returnUrl = 'index.php?route=/web/LuNabamusicMusic/&id='.$this->pageUid.$this->getToken();
$url = $routeBuilder->buildUriFromRoute(
'record_edit', [
'edit['.$table.'][0]' => 'new',
'returnUrl' => $returnUrl,
]
);
// Redirect
HttpUtility::redirect($url);
}
/**
* Adds header buttons
*/
protected function createButtons()
{
// Preset used variables
$buttonBar = $this->view->getModuleTemplate()->getDocHeaderComponent()->getButtonBar();
$iconFactory = new IconFactory();
$uriBuilder = $this->objectManager->get(UriBuilder::class);
// Set basic uri
$uriBuilder->setRequest($this->request);
// Create Add button
$title = $this->getLanguageService()->sL('LLL:EXT:lu_nabamusic/Resources/Private/Language/locallang.xlf:buttons.add');
$viewButton = $buttonBar->makeLinkButton()
->setHref($uriBuilder->reset()->setRequest($this->request)->uriFor('add', [], 'Music'))
->setTitle($title)
->setIcon($iconFactory->getIcon('actions-document-new', Icon::SIZE_SMALL));
$buttonBar->addButton($viewButton, ButtonBar::BUTTON_POSITION_LEFT, 1);
// Create preview button
$title = $this->getLanguageService()->sL('LLL:EXT:lu_nabamusic/Resources/Private/Language/locallang.xlf:buttons.preview');
$viewButton = $buttonBar->makeLinkButton()
->setHref('#')
->setOnClick(BackendUtility::viewOnClick($this->pageUid, '', BackendUtility::BEgetRootLine($this->pageUid)))
->setTitle($title)
->setIcon($iconFactory->getIcon('actions-document-view', Icon::SIZE_SMALL));
$buttonBar->addButton($viewButton, ButtonBar::BUTTON_POSITION_LEFT, 2);
}
/**
* Returns the LanguageService
*
* @return LanguageService
*/
protected function getLanguageService()
{
return $GLOBALS['LANG'] ?? new LanguageService();
}
/**
* Get a CSRF token
*
* @param bool $tokenOnly Set it to TRUE to get only the token, otherwise including the &token= as prefix
*
* @return string
*/
protected function getToken($tokenOnly = false)
{
$token = FormProtectionFactory::get('backend')->generateToken('route', 'web_LuNabamusicMusic');
if ($tokenOnly) {
return $token;
} else {
return '&token='.$token;
}
}
}