Passed
Push — master ( b5cc7d...f2f8fd )
by Marcel
02:32
created

lib/Controller/CategoryController.php (2 issues)

1
<?php
2
/**
3
 * Audio Player
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the LICENSE.md file.
7
 *
8
 * @author Marcel Scherello <[email protected]>
9
 * @copyright 2016-2020 Marcel Scherello
10
 */
11
12
namespace OCA\audioplayer\Controller;
13
14
use OCP\AppFramework\Controller;
15
use OCP\AppFramework\Http\JSONResponse;
16
use OCP\Files\InvalidPathException;
17
use OCP\IRequest;
18
use OCP\IL10N;
19
use OCP\IDBConnection;
20
use OCP\ITagManager;
21
use OCP\Files\IRootFolder;
22
use Psr\Log\LoggerInterface;
23
use \OCP\Files\NotFoundException;
24
use OCA\audioplayer\Categories\Tag;
25
26
/**
27
 * Controller class for main page.
28
 */
29
class CategoryController extends Controller
30
{
31
32
    private $userId;
33
    private $l10n;
34
    private $db;
35
    private $tagger;
36
    private $tagManager;
37
    private $rootFolder;
38
    private $logger;
39
    private $DBController;
40
    private $categoriesTag;
41
42
    public function __construct(
43
        $appName,
44
        IRequest $request,
45
        $userId,
46
        IL10N $l10n,
47
        IDBConnection $db,
48
        ITagManager $tagManager,
49
        IRootFolder $rootFolder,
50
        LoggerInterface $logger,
51
        DbController $DBController,
52
        Tag $categoriesTag
53
    )
54
    {
55
        parent::__construct($appName, $request);
56
        $this->userId = $userId;
57
        $this->l10n = $l10n;
58
        $this->db = $db;
59
        $this->tagManager = $tagManager;
60
        $this->tagger = null;
61
        $this->rootFolder = $rootFolder;
62
        $this->logger = $logger;
63
        $this->DBController = $DBController;
64
        $this->categoriesTag = $categoriesTag;
65
    }
66
67
    /**
68
     * Get the items for the selected category
69
     *
70
     * @NoAdminRequired
71
     * @param $category
72
     * @return JSONResponse
73
     */
74
    public function getCategoryItems($category)
75
    {
76
        $SQL = null;
77
        $aPlaylists = array();
78
        if ($category === 'Artist') {
79
            $SQL = 'SELECT  DISTINCT(`AT`.`artist_id`) AS `id`, `AA`.`name`, LOWER(`AA`.`name`) AS `lower` 
80
						FROM `*PREFIX*audioplayer_tracks` `AT`
81
						JOIN `*PREFIX*audioplayer_artists` `AA`
82
						ON `AA`.`id` = `AT`.`artist_id`
83
			 			WHERE  `AT`.`user_id` = ?
84
			 			ORDER BY LOWER(`AA`.`name`) ASC
85
			 			';
86
        } elseif ($category === 'Genre') {
87
            $SQL = 'SELECT  `id`, `name`, LOWER(`name`) AS `lower` 
88
						FROM `*PREFIX*audioplayer_genre`
89
			 			WHERE  `user_id` = ?
90
			 			ORDER BY LOWER(`name`) ASC
91
			 			';
92
        } elseif ($category === 'Year') {
93
            $SQL = 'SELECT DISTINCT(`year`) AS `id` ,`year` AS `name`  
94
						FROM `*PREFIX*audioplayer_tracks`
95
			 			WHERE  `user_id` = ?
96
			 			ORDER BY `id` ASC
97
			 			';
98
        } elseif ($category === 'Title') {
99
            $SQL = "SELECT distinct('0') as `id` ,'" . $this->l10n->t('All Titles') . "' as `name`  
100
						FROM `*PREFIX*audioplayer_tracks`
101
			 			WHERE  `user_id` = ?
102
			 			";
103
        } elseif ($category === 'Playlist') {
104
            $aPlaylists[] = array('id' => 'X1', 'name' => $this->l10n->t('Favorites'));
105
            $aPlaylists[] = array('id' => 'X2', 'name' => $this->l10n->t('Recently Added'));
106
            $aPlaylists[] = array('id' => 'X3', 'name' => $this->l10n->t('Recently Played'));
107
            $aPlaylists[] = array('id' => 'X4', 'name' => $this->l10n->t('Most Played'));
108
            //https://github.com/Rello/audioplayer/issues/442
109
            $aPlaylists[] = array('id' => 'X5', 'name' => $this->l10n->t('50 Random Tracks'));
110
            $aPlaylists[] = array('id' => '', 'name' => '');
111
112
            // Stream files are shown directly
113
            $SQL = 'SELECT  `file_id` AS `id`, `title` AS `name`, LOWER(`title`) AS `lower` 
114
						FROM `*PREFIX*audioplayer_streams`
115
			 			WHERE  `user_id` = ?
116
			 			ORDER BY LOWER(`title`) ASC
117
			 			';
118
            $stmt = $this->db->prepare($SQL);
119
            $stmt->execute(array($this->userId));
120
            $results = $stmt->fetchAll();
121
            foreach ($results as $row) {
122
                array_splice($row, 2, 1);
123
                $row['id'] = 'S' . $row['id'];
124
                $aPlaylists[] = $row;
125
            }
126
            $aPlaylists[] = array('id' => '', 'name' => '');
127
128
            // regular playlists are selected
129
            $SQL = 'SELECT  `id`,`name`, LOWER(`name`) AS `lower` 
130
						FROM `*PREFIX*audioplayer_playlists`
131
			 			WHERE  `user_id` = ?
132
			 			ORDER BY LOWER(`name`) ASC
133
			 			';
134
135
        } elseif ($category === 'Folder') {
136
            $SQL = 'SELECT  DISTINCT(`FC`.`fileid`) AS `id`, `FC`.`name`, LOWER(`FC`.`name`) AS `lower` 
137
						FROM `*PREFIX*audioplayer_tracks` `AT`
138
						JOIN `*PREFIX*filecache` `FC`
139
						ON `FC`.`fileid` = `AT`.`folder_id`
140
			 			WHERE `AT`.`user_id` = ?
141
			 			ORDER BY LOWER(`FC`.`name`) ASC
142
			 			';
143
        } elseif ($category === 'Album') {
144
            $SQL = 'SELECT  `AB`.`id` , `AB`.`name`, LOWER(`AB`.`name`) AS `lower`
145
						FROM `*PREFIX*audioplayer_albums` `AB`
146
						LEFT JOIN `*PREFIX*audioplayer_artists` `AA` 
147
						ON `AB`.`artist_id` = `AA`.`id`
148
			 			WHERE `AB`.`user_id` = ?
149
			 			ORDER BY LOWER(`AB`.`name`) ASC
150
			 			';
151
        } elseif ($category === 'Album Artist') {
152
            $SQL = 'SELECT  DISTINCT(`AB`.`artist_id`) AS `id`, `AA`.`name`, LOWER(`AA`.`name`) AS `lower` 
153
						FROM `*PREFIX*audioplayer_albums` `AB`
154
						JOIN `*PREFIX*audioplayer_artists` `AA`
155
						ON `AB`.`artist_id` = `AA`.`id`
156
			 			WHERE `AB`.`user_id` = ?
157
			 			ORDER BY LOWER(`AA`.`name`) ASC
158
			 			';
159
        } elseif ($category === 'Tags') {
160
            $aPlaylists = $this->categoriesTag->getCategoryItems();
161
        }
162
163
        if (isset($SQL)) {
164
            $stmt = $this->db->prepare($SQL);
165
            $stmt->execute(array($this->userId));
166
            $results = $stmt->fetchAll();
167
            foreach ($results as $row) {
168
                array_splice($row, 2, 1);
169
                if ($row['name'] === '0' OR $row['name'] === '') $row['name'] = $this->l10n->t('Unknown');
170
                $row['cnt'] = $this->getTrackCount($category, $row['id']);
171
                $aPlaylists[] = $row;
172
            }
173
        }
174
175
        $result = empty($aPlaylists) ? [
176
            'status' => 'nodata'
177
        ] : [
178
            'status' => 'success',
179
            'data' => $aPlaylists
180
        ];
181
        return new JSONResponse($result);
182
    }
183
184
    /**
185
     * Get the covers for the "Album Covers" view
186
     *
187
     * @NoAdminRequired
188
     * @param $category
189
     * @param $categoryId
190
     * @return JSONResponse
191
     */
192
    public function getCategoryItemCovers($category, $categoryId)
193
    {
194
        $whereMatching = array('Artist' => '`AT`.`artist_id`', 'Genre' => '`AT`.`genre_id`', 'Album' => '`AB`.`id`', 'Album Artist' => '`AB`.`artist_id`', 'Year' => '`AT`.`year`', 'Folder' => '`AT`.`folder_id`', 'Tags' => '`AT`.`file_id`');
195
196
        $aPlaylists = array();
197
        $SQL = 'SELECT  `AB`.`id` , `AB`.`name`, LOWER(`AB`.`name`) AS `lower` , `AA`.`id` AS `art`, (CASE  WHEN `AB`.`cover` IS NOT NULL THEN `AB`.`id` ELSE NULL END) AS `cid`';
198
        $SQL .= ' FROM `*PREFIX*audioplayer_tracks` `AT`';
199
        $SQL .= ' LEFT JOIN `*PREFIX*audioplayer_albums` `AB` ON `AB`.`id` = `AT`.`album_id`';
200
        $SQL .= ' LEFT JOIN `*PREFIX*audioplayer_artists` `AA` ON `AA`.`id` = `AB`.`artist_id`';
201
        $SQL .= ' WHERE `AT`.`user_id` = ? ';
202
        if ($categoryId) $SQL .= 'AND ' . $whereMatching[$category] . '= ?';
203
        $SQL .= ' GROUP BY `AB`.`id`, `AA`.`id`, `AB`.`name` ORDER BY LOWER(`AB`.`name`) ASC';
204
205
        if ($category === 'Tags') {
206
            $results = $this->categoriesTag->getCategoryItemCovers($categoryId);
207
            $SQL = null;
208
        }
209
210
        if (isset($SQL)) {
211
            $stmt = $this->db->prepare($SQL);
212
            if ($categoryId) {
213
                $stmt->execute(array($this->userId, $categoryId));
214
            } else {
215
                $stmt->execute(array($this->userId));
216
            }
217
            $results = $stmt->fetchAll();
218
        }
219
220
        foreach ($results as $row) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $results does not seem to be defined for all execution paths leading up to this point.
Loading history...
221
            $row['art'] = $this->DBController->loadArtistsToAlbum($row['id'], $row['art']);
222
            array_splice($row, 2, 1);
223
            if ($row['name'] === '0' OR $row['name'] === '') $row['name'] = $this->l10n->t('Unknown');
224
            $aPlaylists[] = $row;
225
        }
226
227
        $result = empty($aPlaylists) ? [
228
            'status' => 'nodata'
229
        ] : [
230
            'status' => 'success',
231
            'data' => $aPlaylists
232
        ];
233
        return new JSONResponse($result);
234
    }
235
236
    /**
237
     * Get the number of tracks for a category item
238
     *
239
     * @param string $category
240
     * @param integer $categoryId
241
     * @return integer
242
     */
243
    private function getTrackCount($category, $categoryId)
244
    {
245
        $SQL = array();
246
        $SQL['Artist'] = 'SELECT COUNT(`AT`.`id`) AS `count` FROM `*PREFIX*audioplayer_tracks` `AT` LEFT JOIN `*PREFIX*audioplayer_artists` `AA` ON `AT`.`artist_id` = `AA`.`id` WHERE  `AT`.`artist_id` = ? AND `AT`.`user_id` = ?';
247
        $SQL['Genre'] = 'SELECT COUNT(`AT`.`id`) AS `count` FROM `*PREFIX*audioplayer_tracks` `AT` WHERE  `AT`.`genre_id` = ? AND `AT`.`user_id` = ?';
248
        $SQL['Year'] = 'SELECT COUNT(`AT`.`id`) AS `count` FROM `*PREFIX*audioplayer_tracks` `AT` WHERE  `AT`.`year` = ? AND `AT`.`user_id` = ?';
249
        $SQL['Title'] = 'SELECT COUNT(`AT`.`id`) AS `count` FROM `*PREFIX*audioplayer_tracks` `AT` WHERE  `AT`.`id` > ? AND `AT`.`user_id` = ?';
250
        $SQL['Playlist'] = 'SELECT COUNT(`AP`.`track_id`) AS `count` FROM `*PREFIX*audioplayer_playlist_tracks` `AP` WHERE  `AP`.`playlist_id` = ?';
251
        $SQL['Folder'] = 'SELECT COUNT(`AT`.`id`) AS `count` FROM `*PREFIX*audioplayer_tracks` `AT` WHERE  `AT`.`folder_id` = ? AND `AT`.`user_id` = ?';
252
        $SQL['Album'] = 'SELECT COUNT(`AT`.`id`) AS `count` FROM `*PREFIX*audioplayer_tracks` `AT` WHERE  `AT`.`album_id` = ? AND `AT`.`user_id` = ?';
253
        $SQL['Album Artist'] = 'SELECT COUNT(`AT`.`id`) AS `count` FROM `*PREFIX*audioplayer_albums` `AB` JOIN `*PREFIX*audioplayer_tracks` `AT` ON `AB`.`id` = `AT`.`album_id` WHERE  `AB`.`artist_id` = ? AND `AB`.`user_id` = ?';
254
255
        $stmt = $this->db->prepare($SQL[$category]);
256
        if ($category === 'Playlist') {
257
            $stmt->execute(array($categoryId));
258
        } else {
259
            $stmt->execute(array($categoryId, $this->userId));
260
        }
261
        $results = $stmt->fetch();
262
        return $results['count'];
263
    }
264
265
        /**
266
     * get the tracks for a selected category or album
267
     *
268
     * @NoAdminRequired
269
     * @param string $category
270
     * @param string $categoryId
271
     * @return JSONResponse
272
     * @throws InvalidPathException
273
     * @throws NotFoundException
274
     */
275
    public function getTracks($category, $categoryId)
276
    {
277
        if ($categoryId[0] === 'S') $category = 'Stream';
278
        if ($categoryId[0] === 'P') $category = 'Playlist';
279
        $items = $this->getTracksDetails($category, $categoryId);
280
        $headers = $this->getListViewHeaders($category);
281
282
        $result = !empty($items) ? [
283
            'status' => 'success',
284
            'data' => $items,
285
            'header' => $headers,
286
        ] : [
287
            'status' => 'nodata',
288
        ];
289
        return new JSONResponse($result);
290
    }
291
292
    /**
293
     * Get the tracks for a selected category or album
294
     *
295
     * @param string $category
296
     * @param string $categoryId
297
     * @return array
298
     * @throws InvalidPathException
299
     */
300
    private function getTracksDetails($category, $categoryId)
301
    {
302
        $SQL = null;
303
        $favorite = false;
304
        $aTracks = array();
305
        $SQL_select = 'SELECT  `AT`.`id`, `AT`.`title`  AS `cl1`, `AA`.`name` AS `cl2`, `AB`.`name` AS `cl3`, `AT`.`length` AS `len`, `AT`.`file_id` AS `fid`, `AT`.`mimetype` AS `mim`, (CASE  WHEN `AB`.`cover` IS NOT NULL THEN `AB`.`id` ELSE NULL END) AS `cid`, LOWER(`AB`.`name`) AS `lower`';
306
        $SQL_from = ' FROM `*PREFIX*audioplayer_tracks` `AT`
307
					LEFT JOIN `*PREFIX*audioplayer_artists` `AA` ON `AT`.`artist_id` = `AA`.`id`
308
					LEFT JOIN `*PREFIX*audioplayer_albums` `AB` ON `AT`.`album_id` = `AB`.`id`';
309
        $SQL_order = ' ORDER BY LOWER(`AB`.`name`) ASC, `AT`.`disc` ASC, `AT`.`number` ASC';
310
311
        if ($category === 'Artist') {
312
            $SQL_select = 'SELECT  `AT`.`id`, `AT`.`title`  AS `cl1`, `AB`.`name` AS `cl2`, `AT`.`year` AS `cl3`, `AT`.`length` AS `len`, `AT`.`file_id` AS `fid`, `AT`.`mimetype` AS `mim`, (CASE  WHEN `AB`.`cover` IS NOT NULL THEN `AB`.`id` ELSE NULL END) AS `cid`, LOWER(`AB`.`name`) AS `lower`';
313
            $SQL = $SQL_select . $SQL_from .
314
                'WHERE  `AT`.`artist_id` = ? AND `AT`.`user_id` = ?' .
315
                $SQL_order;
316
        } elseif ($category === 'Genre') {
317
            $SQL = $SQL_select . $SQL_from .
318
                'WHERE `AT`.`genre_id` = ? AND `AT`.`user_id` = ?' .
319
                $SQL_order;
320
        } elseif ($category === 'Year') {
321
            $SQL = $SQL_select . $SQL_from .
322
                'WHERE `AT`.`year` = ? AND `AT`.`user_id` = ?' .
323
                $SQL_order;
324
        } elseif ($category === 'Title') {
325
            $SQL = $SQL_select . $SQL_from .
326
                'WHERE `AT`.`id` > ? AND `AT`.`user_id` = ?' .
327
                $SQL_order;
328
        } elseif ($category === 'Playlist' AND $categoryId === 'X1') { // Favorites
329
            $SQL = 'SELECT  `AT`.`id` , `AT`.`title`  AS `cl1`,`AA`.`name` AS `cl2`, `AB`.`name` AS `cl3`,`AT`.`length` AS `len`, `AT`.`file_id` AS `fid`, `AT`.`mimetype` AS `mim`, (CASE  WHEN `AB`.`cover` IS NOT NULL THEN `AB`.`id` ELSE NULL END) AS `cid`, LOWER(`AT`.`title`) AS `lower`' .
330
                $SQL_from .
331
                'WHERE `AT`.`id` <> ? AND `AT`.`user_id` = ?' .
332
                ' ORDER BY LOWER(`AT`.`title`) ASC';
333
            $categoryId = 0; //overwrite to integer for PostgreSQL
334
            $favorite = true;
335
        } elseif ($category === 'Playlist' AND $categoryId === 'X2') { // Recently Added
336
            $SQL = $SQL_select . $SQL_from .
337
                'WHERE `AT`.`id` <> ? AND `AT`.`user_id` = ? 
338
			 		ORDER BY `AT`.`file_id` DESC
339
			 		Limit 100';
340
            $categoryId = 0;
341
        } elseif ($category === 'Playlist' AND $categoryId === 'X3') { // Recently Played
342
            $SQL = $SQL_select . $SQL_from .
343
                'LEFT JOIN `*PREFIX*audioplayer_stats` `AS` ON `AT`.`id` = `AS`.`track_id`
344
			 		WHERE `AS`.`id` <> ? AND `AT`.`user_id` = ? 
345
			 		ORDER BY `AS`.`playtime` DESC
346
			 		Limit 50';
347
            $categoryId = 0;
348
        } elseif ($category === 'Playlist' AND $categoryId === 'X4') { // Most Played
349
            $SQL = $SQL_select . $SQL_from .
350
                'LEFT JOIN `*PREFIX*audioplayer_stats` `AS` ON `AT`.`id` = `AS`.`track_id`
351
			 		WHERE `AS`.`id` <> ? AND `AT`.`user_id` = ? 
352
			 		ORDER BY `AS`.`playcount` DESC
353
			 		Limit 25';
354
            $categoryId = 0;
355
        } elseif ($category === 'Playlist' AND $categoryId === "X5") { // 50 Random Tracks
356
            if ($this->db->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\PostgreSqlPlatform) {
357
                $order = 'ORDER BY random() Limit 50';
358
            } else {
359
                $order = 'ORDER BY RAND() Limit 50';
360
            }
361
            $SQL = $SQL_select . $SQL_from .
362
                "WHERE `AT`.`id` <> ? AND `AT`.`user_id` = ? " . $order;
363
            $categoryId = 0;
364
        } elseif ($category === 'Playlist') {
365
            $SQL = $SQL_select . ' , `AP`.`sortorder`' .
366
                'FROM `*PREFIX*audioplayer_playlist_tracks` `AP` 
367
					LEFT JOIN `*PREFIX*audioplayer_tracks` `AT` ON `AP`.`track_id` = `AT`.`id`
368
					LEFT JOIN `*PREFIX*audioplayer_artists` `AA` ON `AT`.`artist_id` = `AA`.`id`
369
					LEFT JOIN `*PREFIX*audioplayer_albums` `AB` ON `AT`.`album_id` = `AB`.`id`
370
			 		WHERE  `AP`.`playlist_id` = ?
371
					AND `AT`.`user_id` = ? 
372
			 		ORDER BY `AP`.`sortorder` ASC';
373
        } elseif ($category === 'Stream') {
374
            $aTracks = $this->StreamParser(intval(substr($categoryId, 1)));
375
            return $aTracks;
376
        } elseif ($category === 'Folder') {
377
            $SQL = $SQL_select . $SQL_from .
378
                'WHERE `AT`.`folder_id` = ? AND `AT`.`user_id` = ?' .
379
                $SQL_order;
380
        } elseif ($category === 'Album') {
381
            $SQL_select = 'SELECT  `AT`.`id`, `AT`.`title` AS `cl1`, `AA`.`name` AS `cl2`, `AT`.`length` AS `len`, `AT`.`disc` AS `dsc`, `AT`.`file_id` AS `fid`, `AT`.`mimetype` AS `mim`, (CASE  WHEN `AB`.`cover` IS NOT NULL THEN `AB`.`id` ELSE NULL END) AS `cid`, LOWER(`AT`.`title`) AS `lower`,`AT`.`number`  AS `num`';
382
            $SQL = $SQL_select . $SQL_from .
383
                'WHERE `AB`.`id` = ? AND `AB`.`user_id` = ?' .
384
                ' ORDER BY `AT`.`disc` ASC, `AT`.`number` ASC';
385
        } elseif ($category === 'Album Artist') {
386
            $SQL = $SQL_select . $SQL_from .
387
                'WHERE  `AB`.`artist_id` = ? AND `AT`.`user_id` = ?' .
388
                $SQL_order;
389
        } elseif ($category === 'Tags') {
390
            $results = $this->categoriesTag->getTracksDetails($categoryId);
391
            $SQL = null;
392
        }
393
394
        if (isset($SQL)) {
395
            $stmt = $this->db->prepare($SQL);
396
            $stmt->execute(array($categoryId, $this->userId));
397
            $results = $stmt->fetchAll();
398
        }
399
400
        $this->tagger = $this->tagManager->load('files');
401
        $favorites = $this->tagger->getFavorites();
402
403
404
        if ($category === 'Album') {
405
            $discNum = array_sum(array_column($results, 'dsc')) / count($results);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $results does not seem to be defined for all execution paths leading up to this point.
Loading history...
406
        }
407
408
        foreach ($results as $row) {
409
            if ($category === 'Album') {
410
                if ($row['dsc'] !== $discNum) {
411
                    $row['cl3'] = $row['dsc'] . '-' . $row['num'];
412
                } else {
413
                    $row['cl3'] = $row['num'];
414
                }
415
            }
416
            array_splice($row, 8, 1);
417
            $nodes = $this->rootFolder->getUserFolder($this->userId)->getById($row['fid']);
418
            $file = array_shift($nodes);
419
420
            if ($file === null) {
421
                $this->logger->debug('removed/unshared file found => remove '.$row['fid'], array('app' => 'audioplayer'));
422
                $this->DBController->deleteFromDB($row['fid'], $this->userId);
423
                continue;
424
            }
425
            if (is_array($favorites) AND in_array($row['fid'], $favorites)) {
426
                $row['fav'] = 't';
427
            }
428
429
            if ($favorite AND is_array($favorites) AND !in_array($row['fid'], $favorites)) {
430
                //special handling for Favorites smart playlist;
431
                //do not display anything that is NOT a fav
432
            } else {
433
                array_splice($row, 5, 1);
434
                $aTracks[] = $row;
435
            }
436
        }
437
        return $aTracks;
438
    }
439
440
    /**
441
     * Extract steam urls from playlist files
442
     *
443
     * @param integer $fileId
444
     * @return array
445
     * @throws InvalidPathException
446
     */
447
    private function StreamParser($fileId)
448
    {
449
        $tracks = array();
450
        $x = 0;
451
        $title = null;
452
        $userView = $this->rootFolder->getUserFolder($this->userId);
453
        //$this->logger->debug('removed/unshared file found => remove '.$row['fid'], array('app' => 'audioplayer'));
454
455
        $streamfile = $userView->getById($fileId);
456
        $file_type = $streamfile[0]->getMimetype();
457
        $file_content = $streamfile[0]->getContent();
458
459
        if ($file_type === 'audio/x-scpls') {
460
            $stream_data = parse_ini_string($file_content, true, INI_SCANNER_RAW);
461
            $stream_rows = isset($stream_data['playlist']['NumberOfEntries']) ? $stream_data['playlist']['NumberOfEntries'] : $stream_data['playlist']['numberofentries'];
462
            for ($i = 1; $i <= $stream_rows; $i++) {
463
                $title = $stream_data['playlist']['Title' . $i];
464
                $file = $stream_data['playlist']['File' . $i];
465
                preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $file, $matches);
466
467
                if ($matches[0]) {
468
                    $row = array();
469
                    $row['id'] = $fileId . $i;
470
                    $row['cl1'] = $matches[0][0];
471
                    $row['cl2'] = '';
472
                    $row['cl3'] = '';
473
                    $row['len'] = '';
474
                    $row['mim'] = $file_type;
475
                    $row['cid'] = '';
476
                    $row['lin'] = $matches[0][0];
477
                    if ($title) $row['cl1'] = $title;
478
                    $tracks[] = $row;
479
                }
480
            }
481
        } else {
482
            // get the path of the playlist file as reference
483
            $playlistFilePath = explode('/', ltrim($streamfile[0]->getPath(), '/'));
484
            // remove leading username
485
            array_shift($playlistFilePath);
486
            // remove leading "files/"
487
            array_shift($playlistFilePath);
488
            // remove the filename itself
489
            array_pop($playlistFilePath);
490
491
            // read each line of the playlist
492
            foreach (preg_split("/((\r?\n)|(\r\n?))/", $file_content) as $line) {
493
                $title = null;
494
                $artist = null;
495
                if (empty($line) || $line === '#EXTM3U') continue;
496
                if (substr($line, 0, 8) === '#EXTINF:') {
497
                    $extinf = explode(',', substr($line, 8));
498
                    $extNoDuration = $extinf[1];
499
                    $extinf = explode(' - ', $extNoDuration);
500
                    $title = $extinf[1];
501
                    $artist = $extinf[0];
502
                    $line = $extinf[2];
503
                }
504
505
                preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $line, $matches);
506
                if ($matches[0]) {
507
                    // playlist item is a web stream url
508
                    $x++;
509
                    $row = array();
510
                    $row['id'] = $fileId . $x;
511
                    $row['cl1'] = $matches[0][0];
512
                    $row['cl2'] = '';
513
                    $row['cl3'] = '';
514
                    $row['len'] = '';
515
                    $row['mim'] = $file_type;
516
                    $row['cid'] = '';
517
                    $row['lin'] = $matches[0][0];
518
                    if ($title) $row['cl1'] = $title;
519
                    if ($artist) $row['cl2'] = $artist;
520
                    $tracks[] = $row;
521
                } elseif (preg_match('/^[^"<>|:]*$/',$line)) {
522
                    // playlist item is an internal file
523
                    if ($line[0] === '/') {
524
                        // Absolut path
525
                        $path = $line;
526
                    } elseif (substr($line, 0, 3) === '../') {
527
                        // relative one level up => remove the parent folder of the playlist file
528
                        $path = $playlistFilePath;
529
                        do {
530
                            $line = substr($line, 3);
531
                            array_pop($path);
532
                        } while (substr($line, 0, 3) === '../');
533
534
                        array_push($path, $line);
535
                        $path = implode('/', $path);
536
                    } else {
537
                        // normal relative path
538
                        $path = $playlistFilePath;
539
540
                        array_push($path, $line);
541
                        $path = implode('/', $path);
542
                    }
543
                    $x++;
544
                    $this->logger->debug('Final path of playlist track: '.$path);
545
546
                    try {
547
                        $fileId = $this->rootFolder->getUserFolder($this->userId)->get($path)->getId();
548
                        $track = $this->DBController->getTrackInfo(null,$fileId);
549
                        if (!isset($track['id'])) continue;
550
551
                        $row = array();
552
                        $row['id'] = $track['id'];
553
                        $row['cl1'] = $track['Title'];
554
                        $row['cl2'] = $track['Artist'];
555
                        $row['cl3'] = $track['Album'];
556
                        $row['len'] = $track['Length'];
557
                        $row['mim'] = $track['MIME type'];
558
                        $row['cid'] = '';
559
                        $row['lin'] = $track['id'];
560
                        $row['fav'] = $track['fav'];
561
                        if ($title) $row['cl1'] = $title;
562
                        if ($artist) $row['cl2'] = $artist;
563
                        $tracks[] = $row;
564
                    } catch (NotFoundException $e) {
565
                        $this->logger->debug('Path is not a valid file: '.$path);
566
                        // File is not known in the filecache and will be ignored;
567
                    }
568
                }
569
            }
570
        }
571
        return $tracks;
572
    }
573
574
    /**
575
     * Get selection dependend headers for the list view
576
     *
577
     * @param string $category
578
     * @return array
579
     */
580
    private function getListViewHeaders($category)
581
    {
582
        if ($category === 'Artist') {
583
            return ['col1' => $this->l10n->t('Title'), 'col2' => $this->l10n->t('Album'), 'col3' => $this->l10n->t('Year'), 'col4' => $this->l10n->t('Length')];
584
        } elseif ($category === 'Album') {
585
            return ['col1' => $this->l10n->t('Title'), 'col2' => $this->l10n->t('Artist'), 'col3' => $this->l10n->t('Disc') . '-' . $this->l10n->t('Track'), 'col4' => $this->l10n->t('Length')];
586
        } elseif ($category === 'x_Stream') { //temporary disabled; need to separate streams and playlists
587
            return ['col1' => $this->l10n->t('URL'), 'col2' => $this->l10n->t(''), 'col3' => $this->l10n->t(''), 'col4' => $this->l10n->t('')];
588
        } else {
589
            return ['col1' => $this->l10n->t('Title'), 'col2' => $this->l10n->t('Artist'), 'col3' => $this->l10n->t('Album'), 'col4' => $this->l10n->t('Length')];
590
        }
591
    }
592
}
593