Issues (88)

lib/Controller/CategoryController.php (3 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-2021 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
                $this->db->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\PostgreSQL94Platform ||
358
                $this->db->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\PostgreSQL100Platform) {
359
                $order = 'ORDER BY random() Limit 50';
360
            } else {
361
                $order = 'ORDER BY RAND() Limit 50';
362
            }
363
            $SQL = $SQL_select . $SQL_from .
364
                "WHERE `AT`.`id` <> ? AND `AT`.`user_id` = ? " . $order;
365
            $categoryId = 0;
366
        } elseif ($category === 'Playlist') {
367
            $SQL = $SQL_select . ' , `AP`.`sortorder`' .
368
                'FROM `*PREFIX*audioplayer_playlist_tracks` `AP` 
369
					LEFT JOIN `*PREFIX*audioplayer_tracks` `AT` ON `AP`.`track_id` = `AT`.`id`
370
					LEFT JOIN `*PREFIX*audioplayer_artists` `AA` ON `AT`.`artist_id` = `AA`.`id`
371
					LEFT JOIN `*PREFIX*audioplayer_albums` `AB` ON `AT`.`album_id` = `AB`.`id`
372
			 		WHERE  `AP`.`playlist_id` = ?
373
					AND `AT`.`user_id` = ? 
374
			 		ORDER BY `AP`.`sortorder` ASC';
375
        } elseif ($category === 'Stream') {
376
            $aTracks = $this->StreamParser(intval(substr($categoryId, 1)));
377
            return $aTracks;
378
        } elseif ($category === 'Folder') {
379
            $SQL = $SQL_select . $SQL_from .
380
                'WHERE `AT`.`folder_id` = ? AND `AT`.`user_id` = ?' .
381
                $SQL_order;
382
        } elseif ($category === 'Album') {
383
            $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`';
384
            $SQL = $SQL_select . $SQL_from .
385
                'WHERE `AB`.`id` = ? AND `AB`.`user_id` = ?' .
386
                ' ORDER BY `AT`.`disc` ASC, `AT`.`number` ASC';
387
        } elseif ($category === 'Album Artist') {
388
            $SQL = $SQL_select . $SQL_from .
389
                'WHERE  `AB`.`artist_id` = ? AND `AT`.`user_id` = ?' .
390
                $SQL_order;
391
        } elseif ($category === 'Tags') {
392
            $results = $this->categoriesTag->getTracksDetails($categoryId);
393
            $SQL = null;
394
        }
395
396
        if (isset($SQL)) {
397
            $stmt = $this->db->prepare($SQL);
398
            $stmt->execute(array($categoryId, $this->userId));
399
            $results = $stmt->fetchAll();
400
        }
401
402
        $this->tagger = $this->tagManager->load('files');
403
        $favorites = $this->tagger->getFavorites();
404
405
406
        if ($category === 'Album') {
407
            $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...
408
        }
409
410
        foreach ($results as $row) {
411
            if ($category === 'Album') {
412
                if ($row['dsc'] !== $discNum) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $discNum does not seem to be defined for all execution paths leading up to this point.
Loading history...
413
                    $row['cl3'] = $row['dsc'] . '-' . $row['num'];
414
                } else {
415
                    $row['cl3'] = $row['num'];
416
                }
417
            }
418
            array_splice($row, 8, 1);
419
            $nodes = $this->rootFolder->getUserFolder($this->userId)->getById($row['fid']);
420
            $file = array_shift($nodes);
421
422
            if ($file === null) {
423
                $this->logger->debug('removed/unshared file found => remove '.$row['fid'], array('app' => 'audioplayer'));
424
                $this->DBController->deleteFromDB($row['fid'], $this->userId);
425
                continue;
426
            }
427
            if (is_array($favorites) AND in_array($row['fid'], $favorites)) {
428
                $row['fav'] = 't';
429
            }
430
431
            if ($favorite AND is_array($favorites) AND !in_array($row['fid'], $favorites)) {
432
                //special handling for Favorites smart playlist;
433
                //do not display anything that is NOT a fav
434
            } else {
435
                array_splice($row, 5, 1);
436
                $aTracks[] = $row;
437
            }
438
        }
439
        return $aTracks;
440
    }
441
442
    /**
443
     * Extract steam urls from playlist files
444
     *
445
     * @param integer $fileId
446
     * @return array
447
     * @throws InvalidPathException
448
     */
449
    private function StreamParser($fileId)
450
    {
451
        $tracks = array();
452
        $x = 0;
453
        $title = null;
454
        $userView = $this->rootFolder->getUserFolder($this->userId);
455
        //$this->logger->debug('removed/unshared file found => remove '.$row['fid'], array('app' => 'audioplayer'));
456
457
        $streamfile = $userView->getById($fileId);
458
        $file_type = $streamfile[0]->getMimetype();
459
        $file_content = $streamfile[0]->getContent();
460
461
        if ($file_type === 'audio/x-scpls') {
462
            $stream_data = parse_ini_string($file_content, true, INI_SCANNER_RAW);
463
            $stream_rows = isset($stream_data['playlist']['NumberOfEntries']) ? $stream_data['playlist']['NumberOfEntries'] : $stream_data['playlist']['numberofentries'];
464
            for ($i = 1; $i <= $stream_rows; $i++) {
465
                $title = $stream_data['playlist']['Title' . $i];
466
                $file = $stream_data['playlist']['File' . $i];
467
                preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $file, $matches);
468
469
                if ($matches[0]) {
470
                    $row = array();
471
                    $row['id'] = $fileId . $i;
472
                    $row['cl1'] = $matches[0][0];
473
                    $row['cl2'] = '';
474
                    $row['cl3'] = '';
475
                    $row['len'] = '';
476
                    $row['mim'] = $file_type;
477
                    $row['cid'] = '';
478
                    $row['lin'] = $matches[0][0];
479
                    if ($title) $row['cl1'] = $title;
480
                    $tracks[] = $row;
481
                }
482
            }
483
        } else {
484
            // get the path of the playlist file as reference
485
            $playlistFilePath = explode('/', ltrim($streamfile[0]->getPath(), '/'));
486
            // remove leading username
487
            array_shift($playlistFilePath);
488
            // remove leading "files/"
489
            array_shift($playlistFilePath);
490
            // remove the filename itself
491
            array_pop($playlistFilePath);
492
493
            // read each line of the playlist
494
            foreach (preg_split("/((\r?\n)|(\r\n?))/", $file_content) as $line) {
495
                $title = null;
496
                $artist = null;
497
                if (empty($line) || $line === '#EXTM3U') continue;
498
                if (substr($line, 0, 8) === '#EXTINF:') {
499
                    $extinf = explode(',', substr($line, 8));
500
                    $extNoDuration = $extinf[1];
501
                    $extinf = explode(' - ', $extNoDuration);
502
                    $title = $extinf[1];
503
                    $artist = $extinf[0];
504
                    $line = $extinf[2];
505
                }
506
507
                preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $line, $matches);
508
                if ($matches[0]) {
509
                    // playlist item is a web stream url
510
                    $x++;
511
                    $row = array();
512
                    $row['id'] = $fileId . $x;
513
                    $row['cl1'] = $matches[0][0];
514
                    $row['cl2'] = '';
515
                    $row['cl3'] = '';
516
                    $row['len'] = '';
517
                    $row['mim'] = $file_type;
518
                    $row['cid'] = '';
519
                    $row['lin'] = $matches[0][0];
520
                    if ($title) $row['cl1'] = $title;
521
                    if ($artist) $row['cl2'] = $artist;
522
                    $tracks[] = $row;
523
                } elseif (preg_match('/^[^"<>|:]*$/',$line)) {
524
                    // playlist item is an internal file
525
                    if ($line[0] === '/') {
526
                        // Absolut path
527
                        $path = $line;
528
                    } elseif (substr($line, 0, 3) === '../') {
529
                        // relative one level up => remove the parent folder of the playlist file
530
                        $path = $playlistFilePath;
531
                        do {
532
                            $line = substr($line, 3);
533
                            array_pop($path);
534
                        } while (substr($line, 0, 3) === '../');
535
536
                        array_push($path, $line);
537
                        $path = implode('/', $path);
538
                    } else {
539
                        // normal relative path
540
                        $path = $playlistFilePath;
541
542
                        array_push($path, $line);
543
                        $path = implode('/', $path);
544
                    }
545
                    $x++;
546
                    $this->logger->debug('Final path of playlist track: '.$path);
547
548
                    try {
549
                        $fileId = $this->rootFolder->getUserFolder($this->userId)->get($path)->getId();
550
                        $track = $this->DBController->getTrackInfo(null,$fileId);
551
                        if (!isset($track['id'])) continue;
552
553
                        $row = array();
554
                        $row['id'] = $track['id'];
555
                        $row['cl1'] = $track['Title'];
556
                        $row['cl2'] = $track['Artist'];
557
                        $row['cl3'] = $track['Album'];
558
                        $row['len'] = $track['Length'];
559
                        $row['mim'] = $track['MIME type'];
560
                        $row['cid'] = '';
561
                        $row['lin'] = $track['id'];
562
                        $row['fav'] = $track['fav'];
563
                        if ($title) $row['cl1'] = $title;
564
                        if ($artist) $row['cl2'] = $artist;
565
                        $tracks[] = $row;
566
                    } catch (NotFoundException $e) {
567
                        $this->logger->debug('Path is not a valid file: '.$path);
568
                        // File is not known in the filecache and will be ignored;
569
                    }
570
                }
571
            }
572
        }
573
        return $tracks;
574
    }
575
576
    /**
577
     * Get selection dependend headers for the list view
578
     *
579
     * @param string $category
580
     * @return array
581
     */
582
    private function getListViewHeaders($category)
583
    {
584
        if ($category === 'Artist') {
585
            return ['col1' => $this->l10n->t('Title'), 'col2' => $this->l10n->t('Album'), 'col3' => $this->l10n->t('Year'), 'col4' => $this->l10n->t('Length')];
586
        } elseif ($category === 'Album') {
587
            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')];
588
        } elseif ($category === 'x_Stream') { //temporary disabled; need to separate streams and playlists
589
            return ['col1' => $this->l10n->t('URL'), 'col2' => $this->l10n->t(''), 'col3' => $this->l10n->t(''), 'col4' => $this->l10n->t('')];
590
        } else {
591
            return ['col1' => $this->l10n->t('Title'), 'col2' => $this->l10n->t('Artist'), 'col3' => $this->l10n->t('Album'), 'col4' => $this->l10n->t('Length')];
592
        }
593
    }
594
}
595