Play.php 14.5 KB
Newer Older
Dainis Abols's avatar
Dainis Abols committed
1
2
3
4
5
<?php

namespace Lu\LuNabamusic\Domain\Model;

use DateTime;
Dainis Abols's avatar
Dainis Abols committed
6
use HDNET\Calendarize\Domain\Model\Event;
Dainis Abols's avatar
Dainis Abols committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
use Lu\LuNabamusic\Helpers\DataHelper;
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Connection;
use GuzzleHttp\Client as Guzzle;

/**
 * Class Access
 *
 * @author  Dainis Abols <dainis.abols@lu.lv>
 * @owner   University of Latvia
 * @version 1.0.0
 * @since   01.11.2019
 *
 * @package Lu\lunabamusic\Domain\Model
 */
class Play extends AbstractEntity
{
    /**
     * Table name
     *
     * @var string
     */
    private $tableName = 'tx_lunabamusic_domain_model_play';

    /**
     * Events table name
     *
     * @var string
     */
    private $eventTableName = 'tx_calendarize_domain_model_event';

    /**
     * Events configuration table
     *
     * @var string
     */
    private $eventConfTableName = 'tx_calendarize_domain_model_configuration';

    /**
     * Config values
     *
     * @var array
     */
    private $conf = [];

    /**
     * Unit ID
     *
     * @var int
     */
    public $uid;

    /**
     * Artist name
     *
     * @var string
     */
    public $artist;

    /**
     * Song name
     *
     * @var string
     */
    public $title;

    /**
     * Play time
     *
     * @var int
     */
    public $time;

    /**
     * Previous time played
     *
     * @var int
     */
    public $prev;

    /**
     * First time played
     *
     * @var int
     */
    public $first;


    /**
     * Cron script
     *
     * @return bool
     */
    public function executeCron()
    {
        // Pre-define models
        $dataHelper = new DataHelper();

        // Call song fetch option and fail if none available!
        $apiSong = $this->fetchLiveEntry();
        if (empty($apiSong)) {
111
112
113
            // Update last song end time
            $this->addEndTime();

Dainis Abols's avatar
Dainis Abols committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
            return false;
        }

        // Get last song entry (this needs to be in cache)
        $lastSong = $this->getLastEntry();

        // Get previous entry
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($this->tableName)->createQueryBuilder();
        $queryBuilder->select('*')
                     ->where(
                         $queryBuilder->expr()->eq('artist', $queryBuilder->createNamedParameter($apiSong['artist']))
                     )
                     ->andWhere(
                         $queryBuilder->expr()->eq('title', $queryBuilder->createNamedParameter($apiSong['title']))
                     )
                     ->orderBy('time', 'DESC')
                     ->from($this->tableName)
                     ->setMaxResults(1);
        $statement = $queryBuilder->execute();
        $result    = $queryBuilder->execute()->fetchAll();

        // Set first and previous song time entry (or current, if none found)
        $currentTime  = time();
        $previousTime = !empty($result[0]['prev']) ? $result[0]['prev'] : $currentTime;
        $firstTime    = !empty($result[0]['first']) ? $result[0]['first'] : $previousTime;

        // Check if song has changed
        if ($apiSong['artist'] != $lastSong['artist'] && $apiSong['artist'] != $lastSong['artist']) {
142
143
144
            // Update last song end time
            $this->addEndTime();

Dainis Abols's avatar
Dainis Abols committed
145
146
147
148
149
150
151
152
153
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tableName);
            $affectedRows = $queryBuilder
                ->insert($this->tableName)
                ->values([
                    'pid'     => 0,
                    'artist'  => $apiSong['artist'],
                    'title'   => $apiSong['title'],
                    'first'   => $firstTime,
                    'time'    => $currentTime,
154
                    'endtime' => 0,
Dainis Abols's avatar
Dainis Abols committed
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
                    'prev'    => $previousTime,
                    'checked' => 1,
                    'cron'    => 1,
                ])
                ->execute();

            // Update cache
            $currentSong = $this->getLastEntry();
            $dataHelper->saveInCache(DataHelper::CACHED_SONG_ENTRY, $currentSong, DataHelper::CACHED_SONG_TIME);
        }

        // Return true, if all succesfull
        return true;
    }

    /**
     * Returns programm entry from calendar
     * This requires Calendarize dependency!
     *
     * @return string
     */
    public function getCurrentProgramme()
    {
        // Set default programm name
        $hoursNow   = $sincemidnight = time() - mktime(0, 0, 0);
        $DataHelper = new DataHelper();
        $title      = !empty($DataHelper->getLangString('programme.music')) ? $DataHelper->getLangString('programme.music') : 'Mūzika';

        // Get config
        $this->getConfig();
        if ($this->conf['eventPageId']) {
            $eventPageId = $this->conf['eventPageId'];

            // Fetch event configs for current time
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($this->eventConfTableName)->createQueryBuilder();
            $queryBuilder->select('*')->where("`deleted` = 0 AND `start_date` <= UNIX_TIMESTAMP() AND (`all_day` = 1 OR (`start_time` <= {$hoursNow} AND (`end_time` >= {$hoursNow} OR `end_time` = 0))) AND `pid` = {$eventPageId}")->from($this->eventConfTableName);
            $statement = $queryBuilder->execute();

            // If timestamp matches, getch actual event
            while ($row = $statement->fetch()) {
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($this->eventTableName)->createQueryBuilder();
                $queryBuilder->select('*')->where("`deleted` = 0 AND `hidden` = 0 AND `calendarize` = {$row['uid']}")->from($this->eventTableName);
                $programmResults = $queryBuilder->execute();

                // If entry found, assign the name
                while ($data = $programmResults->fetch()) {
                    $newCDate = new \DateTime();
202
203
204
205
206
                    $newSDate = DateTime::createFromFormat('Y-m-d', $row['start_date'], new \DateTimeZone('UTC'));
                    $newEDate = new DateTime('today');
                    if (!empty($row['end_date'])) {
                        $newEDate = DateTime::createFromFormat('Y-m-d', $row['end_date'], new \DateTimeZone('UTC'));
                    }
Dainis Abols's avatar
Dainis Abols committed
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242

                    // Check if day of week matches
                    if ($newSDate->format('w') <= $newCDate->format('w') && $newCDate->format('w') <= $newEDate->format('w')) {
                        $title = $data['title'];
                    }
                    break;
                }
            }
        }

        // Return title
        return $title;
    }

    /**
     * Retreive song
     */
    public function getCurrentSong($onLine = false)
    {
        // Pre-define models
        $dataHelper = new DataHelper();
        $defaultProgramme = !empty($dataHelper->getLangString('programme.music')) ? $dataHelper->getLangString('programme.music') : 'Mūzika';

        // If current programme isn't music return programme title
        if ($this->getCurrentProgramme() != $defaultProgramme) {
            return $this->getCurrentProgramme();
        }

        // Fetch info from cache or create new one, if none present
        $cachedSong = $dataHelper->getFromCache(DataHelper::CACHED_SONG_ENTRY);
        if (!$cachedSong) {
            $currentSong = $this->getLastEntry();
            $dataHelper->saveInCache(DataHelper::CACHED_SONG_ENTRY, $currentSong, DataHelper::CACHED_SONG_TIME);
            $cachedSong = $currentSong;
        }

243
244
245
246
247
        // If last song has ended return programme title
        if ($cachedSong['endtime'] != 0) {
            return $this->getCurrentProgramme();
        }

Dainis Abols's avatar
Dainis Abols committed
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
        // Check if one-line return requested
        if ($onLine) {
            return $cachedSong['artist']." - ".$cachedSong['title'];
        }

        return $cachedSong;
    }

    /**
     * Returns array of most played songs of the current month
     *
     * @param int    $limit
     *
     * @param string $pickedMonth
     *
     * @return array
     */
    public function getMostPlayedSongs(int $limit, string $pickedMonth = null) {
        if ($pickedMonth) {
            $firstDayOfMonth = DateTime::createFromFormat('m/d/Y', $pickedMonth);
            $firstDayOfMonth->modify('first day of this month midnight');
            $lastDayOfMonth = DateTime::createFromFormat('m/d/Y', $pickedMonth);
            $lastDayOfMonth->modify('first day of next month midnight');
        } else {
            $firstDayOfMonth = new DateTime('first day of this month midnight');
            $lastDayOfMonth = new DateTime('first day of next month midnight');
        }

        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($this->tableName)->createQueryBuilder();
        $queryBuilder->addSelectLiteral(
                        // $queryBuilder->count() can't assign an alias. ExpressionBuilder used instead.
                        $queryBuilder->expr()->count('*', 'timesPlayed')
                     )
                     ->addSelect('artist', 'title', 'first')
                     ->from($this->tableName)
                     ->where(
                         $queryBuilder->expr()->gte('time', $queryBuilder->createNamedParameter($firstDayOfMonth->getTimestamp())),
                         $queryBuilder->expr()->lte('time', $queryBuilder->createNamedParameter($lastDayOfMonth->getTimestamp()))
                     )
                     ->groupBy('artist', 'title', 'first')
                     ->orderBy('timesPlayed', 'DESC')
                     ->addOrderBy('artist', 'ASC')
                     ->setMaxResults($limit);

        return $queryBuilder->execute()->fetchAll();
    }

    /**
     * Searches songs by date and/or query in artist and title
     *
     * @param        $date
     * @param string $query
     *
     * @return array
     */
    public function searchSongs($date = null, string $query = null)
    {
        $connection   = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($this->tableName);
        $queryBuilder = $connection->createQueryBuilder();
        $queryBuilder->select('artist', 'title', 'time', 'prev')
                     ->from($this->tableName);

        // If date was passed in search only in that date
        if ($date) {
            $start = new DateTime($date);
            $end   = new DateTime($date);

            $start->modify('midnight');
            $end->modify('tomorrow -1 minute');

            $queryBuilder->where(
                $queryBuilder->expr()->gte('time', $queryBuilder->createNamedParameter($start->getTimestamp())),
                $queryBuilder->expr()->lte('time', $queryBuilder->createNamedParameter($end->getTimestamp()))
            );
        }

        // If query was passed in add it to SQL query
        if ($query) {
            $queryBuilder->andWhere(
                $queryBuilder->expr()->comparison(
                    $connection->getDatabasePlatform()->getConcatExpression('artist, \' \', title'),
                    'LIKE',
                    $queryBuilder->createNamedParameter('%'.$queryBuilder->escapeLikeWildcards($query).'%')
                )
            );
        }

        // If query was passed in without date exclude all entries with 0 time
        if ($query and !$date) {
            $queryBuilder->andWhere("`time` > 0");
        }

        $queryBuilder->orderBy('time', 'DESC');

        return $queryBuilder->execute()->fetchAll();
    }

    /**
     * Get songs played on current day
     *
     * @return array
     */
    public function getTodaysSongs()
    {
        return $this->searchSongs('now');
    }

    /**
     * Get last played song
     *
     * @return mixed
     */
    public function getLastEntry()
    {
        return $this->take(1);
    }

    /**
     * Retrieve defined number of rows
     *
     * @param $limit
     *
     * @return mixed
     */
    public function take($limit)
    {
        $data = [];

        // Build query
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($this->tableName)->createQueryBuilder();
        $queryBuilder->select('*')->orderBy('uid', 'DESC')->from($this->tableName)->setMaxResults($limit);
        $statement = $queryBuilder->execute();

        // Build data array
        while ($row = $statement->fetch()) {
            // Return entry if requested only one
            if ($limit == 1) {
                return $row;
            } else {
                $data[] = $row;
            }
        }

        // Return array
        return $data;
    }

    /**
     * Fetches data from provided endpoint
     *
     * Notice: This should be called with care!
     *
     * @return array|int
     */
    private function fetchLiveEntry()
    {
        // Get url or fail
        $this->getConfig();
        $url = $this->conf['streamServer'];
        if (!$url) {
            return [];
        }
        $client = new Guzzle();

        // Fetch actual image content
        $result         = $client->get($url, ['verify' => false]);
        $songFromServer = $result->getBody()->getContents();

        // Fetch song response or fail
        $songArtistTitle = explode(';', trim($songFromServer, ';'));
        if (empty(trim($songArtistTitle[0])) or empty(trim($songArtistTitle[1]))) {
            return [];
        }
        // Build array and return
        $data = [
            'artist' => trim($songArtistTitle[0]),
            'title'  => trim($songArtistTitle[1]),
        ];

        return $data;
    }

    /**
     * Get config values
     */
    private function getConfig()
    {
        // Fetch config
        $this->conf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get('lu_nabamusic');
    }
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460


    /**
     * Add end time to last played song
     */
    private function addEndTime()
    {
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($this->tableName)->createQueryBuilder();

        // Get last song uid
        $queryBuilder->select('*')->orderBy('uid', 'DESC')->from($this->tableName)->setMaxResults(1);
        $statement = $queryBuilder->execute();

        $queryBuilder->update($this->tableName)
                     ->where(
                         $queryBuilder->expr()->eq('uid', $statement->fetch()['uid'])
                     )
                     ->andWhere(
                         $queryBuilder->expr()->eq('endtime', 0)
                     )
                     ->set('endtime', time())
                     ->execute();
    }
Dainis Abols's avatar
Dainis Abols committed
461
}