DbController   C
last analyzed

Complexity

Total Complexity 55

Size/Duplication

Total Lines 643
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 1
Metric Value
eloc 314
c 4
b 0
f 1
dl 0
loc 643
rs 6
wmc 55

22 Methods

Rating   Name   Duplication   Size   Complexity  
A writeTrackToDB() 0 54 2
A getTrackInfo() 0 47 3
A __construct() 0 18 1
A writeCoverToAlbum() 0 5 1
A updateTrack() 0 9 1
A getFileId() 0 7 1
A loadArtistsToAlbum() 0 24 3
A rollBack() 0 3 1
A writeAlbumToDB() 0 36 4
A getPlaylistsForTrack() 0 20 2
B deleteFromDB() 0 50 6
A truncate() 0 3 2
A writeStreamToDB() 0 24 2
A normalizeInteger() 0 12 3
A getSessionValue() 0 8 1
B resetMediaLibrary() 0 58 6
A writeArtistToDB() 0 13 2
A setSessionValue() 0 18 3
A writeGenreToDB() 0 13 2
B search() 0 46 7
A beginTransaction() 0 3 1
A commit() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like DbController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DbController, and based on these observations, apply Extract Interface, too.

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
 * @author Sebastian Doell <[email protected]>
10
 * @copyright 2016-2020 Marcel Scherello
11
 * @copyright 2015 Sebastian Doell
12
 */
13
14
namespace OCA\audioplayer\Controller;
15
16
use OCP\AppFramework\Controller;
17
use OCP\AppFramework\Http\JSONResponse;
18
use OCP\IRequest;
19
use OCP\IL10N;
20
use OCP\IDbConnection;
21
use OCP\Share\IManager;
22
use OCP\ILogger;
23
use OCP\ITagManager;
24
25
/**
26
 * Controller class for main page.
27
 */
28
class DbController extends Controller
29
{
30
    private $userId;
31
    private $l10n;
32
    private $db;
33
    private $occ_job;
34
    private $shareManager;
35
    private $tagManager;
36
    private $logger;
37
38
    public function __construct(
39
        $appName,
40
        IRequest $request,
41
        $userId,
42
        IL10N $l10n,
43
        IDbConnection $db,
44
        ITagManager $tagManager,
45
        IManager $shareManager,
46
        ILogger $logger
47
    )
48
    {
49
        parent::__construct($appName, $request);
50
        $this->userId = $userId;
51
        $this->l10n = $l10n;
52
        $this->db = $db;
53
        $this->shareManager = $shareManager;
54
        $this->tagManager = $tagManager;
55
        $this->logger = $logger;
56
    }
57
58
    public function loadArtistsToAlbum($iAlbumId, $ARtistID)
59
    {
60
        # load albumartist if available
61
        # if no albumartist, we will load all artists from the tracks
62
        # if all the same - display it as album artist
63
        # if different track-artists, display "various"
64
        if ((int)$ARtistID !== 0) {
65
            $stmt = $this->db->prepare('SELECT `name`  FROM `*PREFIX*audioplayer_artists` WHERE  `id` = ?');
66
            $stmt->execute(array($ARtistID));
67
            $row = $stmt->fetch();
68
            return $row['name'];
69
        } else {
70
            $stmt = $this->db->prepare('SELECT DISTINCT(`artist_id`) FROM `*PREFIX*audioplayer_tracks` WHERE  `album_id` = ?');
71
            $stmt->execute(array($iAlbumId));
72
            $TArtist = $stmt->fetch();
73
            $rowCount = $stmt->rowCount();
74
75
            if ($rowCount === 1) {
76
                $stmt = $this->db->prepare('SELECT `name`  FROM `*PREFIX*audioplayer_artists` WHERE  `id` = ?');
77
                $stmt->execute(array($TArtist['artist_id']));
78
                $row = $stmt->fetch();
79
                return $row['name'];
80
            } else {
81
                return (string)$this->l10n->t('Various Artists');
82
            }
83
        }
84
    }
85
86
    /**
87
     * @NoAdminRequired
88
     * @param $searchquery
89
     * @return array
90
     */
91
    public function search($searchquery)
92
    {
93
        $searchresult = array();
94
        $SQL = "SELECT `id`,`name` FROM `*PREFIX*audioplayer_albums` WHERE (LOWER(`name`) LIKE LOWER(?)) AND `user_id` = ?";
95
        $stmt = $this->db->prepare($SQL);
96
        $stmt->execute(array('%' . addslashes($searchquery) . '%', $this->userId));
97
        $results = $stmt->fetchAll();
98
        if (!is_null($results)) {
99
            foreach ($results as $row) {
100
                $searchresult[] = [
101
                    'id' => 'Album-' . $row['id'],
102
                    'name' => $this->l10n->t('Album') . ': ' . $row['name'],
103
                ];
104
            }
105
        }
106
107
        $SQL = "SELECT `AA`.`id`, `AA`.`name` 
108
                FROM `*PREFIX*audioplayer_artists` `AA`
109
                JOIN `*PREFIX*audioplayer_tracks` `AT`
110
				ON `AA`.`id` = `AT`.`artist_id`
111
                WHERE (LOWER(`AA`.`name`) LIKE LOWER(?)) AND `AA`.`user_id` = ?";
112
        $stmt = $this->db->prepare($SQL);
113
        $stmt->execute(array('%' . addslashes($searchquery) . '%', $this->userId));
114
        $results = $stmt->fetchAll();
115
        if (!is_null($results)) {
116
            foreach ($results as $row) {
117
                $searchresult[] = [
118
                    'id' => 'Artist-' . $row['id'],
119
                    'name' => $this->l10n->t('Artist') . ': ' . $row['name'],
120
                ];
121
            }
122
        }
123
124
        $SQL = "SELECT `album_id`, `title` FROM `*PREFIX*audioplayer_tracks` WHERE (LOWER(`title`) LIKE LOWER(?)) AND `user_id` = ?";
125
        $stmt = $this->db->prepare($SQL);
126
        $stmt->execute(array('%' . addslashes($searchquery) . '%', $this->userId));
127
        $results = $stmt->fetchAll();
128
        if (!is_null($results)) {
129
            foreach ($results as $row) {
130
                $searchresult[] = [
131
                    'id' => 'Album-' . $row['album_id'],
132
                    'name' => $this->l10n->t('Title') . ': ' . $row['title'],
133
                ];
134
            }
135
        }
136
        return $searchresult;
137
    }
138
139
    /**
140
     * @NoAdminRequired
141
     * @param string $userId
142
     * @param $output
143
     * @param $hook
144
     *
145
     * @return bool|JSONResponse
146
     */
147
    public function resetMediaLibrary($userId = null, $output = null, $hook = null)
148
    {
149
        if ($userId !== null) {
150
            $this->occ_job = true;
151
            $this->userId = $userId;
152
        } else {
153
            $this->occ_job = false;
154
        }
155
156
        $this->db->beginTransaction();
157
        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_tracks` WHERE `user_id` = ?');
158
        $stmt->execute(array($this->userId));
159
160
        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_artists` WHERE `user_id` = ?');
161
        $stmt->execute(array($this->userId));
162
163
        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_genre` WHERE `user_id` = ?');
164
        $stmt->execute(array($this->userId));
165
166
        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_albums` WHERE `user_id` = ?');
167
        $stmt->execute(array($this->userId));
168
169
        $stmt = $this->db->prepare('SELECT `id` FROM `*PREFIX*audioplayer_playlists` WHERE `user_id` = ?');
170
171
        $stmt->execute(array($this->userId));
172
        $results = $stmt->fetchAll();
173
        if (!is_null($results)) {
174
            foreach ($results as $row) {
175
                $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_playlist_tracks` WHERE `playlist_id` = ?');
176
                $stmt->execute(array($row['id']));
177
            }
178
        }
179
180
        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_playlists` WHERE `user_id` = ?');
181
        $stmt->execute(array($this->userId));
182
183
        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_stats` WHERE `user_id` = ?');
184
        $stmt->execute(array($this->userId));
185
186
        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_streams` WHERE `user_id` = ?');
187
        $stmt->execute(array($this->userId));
188
189
        $this->db->commit();
190
191
        $result = [
192
            'status' => 'success',
193
            'msg' => 'all good'
194
        ];
195
196
        // applies if scanner is not started via occ
197
        if (!$this->occ_job) {
198
            return new JSONResponse($result);
199
        } elseif ($hook === null) {
200
            $output->writeln("Reset finished");
201
        } else {
202
            $this->logger->info('Library of "' . $userId . '" reset due to user deletion', array('app' => 'audioplayer'));
203
        }
204
        return true;
205
    }
206
207
    /**
208
     * Delete single title from audio player tables
209
     * @NoAdminRequired
210
     * @param int $file_id
211
     * @param int $userId
212
     * @return bool
213
     */
214
    public function deleteFromDB($file_id, $userId = null)
215
    {
216
        // check if scanner is started from web or occ
217
        if ($userId !== null) {
218
            $this->userId = $userId;
219
        }
220
        $this->logger->debug('deleteFromDB: ' . $file_id, array('app' => 'audioplayer'));
221
222
        $stmt = $this->db->prepare('SELECT `album_id`, `id` FROM `*PREFIX*audioplayer_tracks` WHERE `file_id` = ?  AND `user_id` = ?');
223
        $stmt->execute(array($file_id, $this->userId));
224
        $row = $stmt->fetch();
225
226
        if (isset($row['id'])) {
227
            $AlbumId = $row['album_id'];
228
            $TrackId = $row['id'];
229
230
            $stmt = $this->db->prepare('SELECT COUNT(`album_id`) AS `ALBUMCOUNT`  FROM `*PREFIX*audioplayer_tracks` WHERE `album_id` = ? ');
231
            $stmt->execute(array($AlbumId));
232
            $row = $stmt->fetch();
233
            if ((int)$row['ALBUMCOUNT'] === 1) {
234
                $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_albums` WHERE `id` = ? AND `user_id` = ?');
235
                $stmt->execute(array($AlbumId, $this->userId));
236
            }
237
238
            $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_tracks` WHERE  `file_id` = ? AND `user_id` = ?');
239
            $stmt->execute(array($file_id, $this->userId));
240
241
            $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_streams` WHERE  `file_id` = ? AND `user_id` = ?');
242
            $stmt->execute(array($file_id, $this->userId));
243
244
            $stmt = $this->db->prepare('SELECT `playlist_id` FROM `*PREFIX*audioplayer_playlist_tracks` WHERE `track_id` = ?');
245
            $stmt->execute(array($TrackId));
246
            $row = $stmt->fetch();
247
248
            if ($row['playlist_id']) {
249
                $PlaylistId = $row['playlist_id'];
250
251
                $stmt = $this->db->prepare('SELECT COUNT(`playlist_id`) AS `PLAYLISTCOUNT` FROM `*PREFIX*audioplayer_playlist_tracks` WHERE `playlist_id` = ? ');
252
                $stmt->execute(array($PlaylistId));
253
                $row = $stmt->fetch();
254
                if ((int)$row['PLAYLISTCOUNT'] === 1) {
255
                    $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_playlists` WHERE `id` = ? AND `user_id` = ?');
256
                    $stmt->execute(array($PlaylistId, $this->userId));
257
                }
258
            }
259
            $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_playlist_tracks` WHERE  `track_id` = ?');
260
            $stmt->execute(array($TrackId));
261
        }
262
263
        return true;
264
    }
265
266
    /**
267
     * write cover image data to album
268
     * @param int $userId
269
     * @param integer $iAlbumId
270
     * @param string $sImage
271
     * @return true
272
     */
273
    public function writeCoverToAlbum($userId, $iAlbumId, $sImage)
274
    {
275
        $stmt = $this->db->prepare('UPDATE `*PREFIX*audioplayer_albums` SET `cover`= ?, `bgcolor`= ? WHERE `id` = ? AND `user_id` = ?');
276
        $stmt->execute(array($sImage, '', $iAlbumId, $userId));
277
        return true;
278
    }
279
280
    /**
281
     * Add album to db if not exist
282
     * @param int $userId
283
     * @param string $sAlbum
284
     * @param string $sYear
285
     * @param int $iArtistId
286
     * @param int $parentId
287
     * @return array
288
     * @throws \Doctrine\DBAL\DBALException
289
     */
290
    public function writeAlbumToDB($userId, $sAlbum, $sYear, $iArtistId, $parentId)
291
    {
292
        $sAlbum = $this->truncate($sAlbum, '256');
293
        $sYear = $this->normalizeInteger($sYear);
294
        $AlbumCount = 0;
295
296
        $stmt = $this->db->prepare('SELECT `id`, `artist_id` FROM `*PREFIX*audioplayer_albums` WHERE `user_id` = ? AND `name` = ? AND `folder_id` = ?');
297
        $stmt->execute(array($userId, $sAlbum, $parentId));
298
        $row = $stmt->fetch();
299
        if ($row) {
300
            if ((int)$row['artist_id'] !== (int)$iArtistId) {
301
                $various_id = $this->writeArtistToDB($userId, $this->l10n->t('Various Artists'));
302
                $stmt = $this->db->prepare('UPDATE `*PREFIX*audioplayer_albums` SET `artist_id`= ? WHERE `id` = ? AND `user_id` = ?');
303
                $stmt->execute(array($various_id, $row['id'], $userId));
304
            }
305
            $insertid = $row['id'];
306
        } else {
307
            $stmt = $this->db->prepare('INSERT INTO `*PREFIX*audioplayer_albums` (`user_id`,`name`,`folder_id`) VALUES(?,?,?)');
308
            $stmt->execute(array($userId, $sAlbum, $parentId));
309
            $insertid = $this->db->lastInsertId('*PREFIX*audioplayer_albums');
310
            if ($iArtistId) {
311
                $stmt = $this->db->prepare('UPDATE `*PREFIX*audioplayer_albums` SET `year`= ?, `artist_id`= ? WHERE `id` = ? AND `user_id` = ?');
312
                $stmt->execute(array((int)$sYear, $iArtistId, $insertid, $userId));
313
            } else {
314
                $stmt = $this->db->prepare('UPDATE `*PREFIX*audioplayer_albums` SET `year`= ? WHERE `id` = ? AND `user_id` = ?');
315
                $stmt->execute(array((int)$sYear, $insertid, $userId));
316
            }
317
            $AlbumCount = 1;
318
        }
319
320
        $return = [
321
            'id' => $insertid,
322
            'state' => true,
323
            'albumcount' => $AlbumCount,
324
        ];
325
        return $return;
326
    }
327
328
    /**
329
     * truncates fiels do DB-field size
330
     *
331
     * @param $string
332
     * @param $length
333
     * @param $dots
334
     * @return string
335
     */
336
    private function truncate($string, $length, $dots = "...")
337
    {
338
        return (strlen($string) > $length) ? mb_strcut($string, 0, $length - strlen($dots)) . $dots : $string;
339
    }
340
341
    /**
342
     * validate unsigned int values
343
     *
344
     * @param string $value
345
     * @return int value
346
     */
347
    private function normalizeInteger($value)
348
    {
349
        // convert format '1/10' to '1' and '-1' to null
350
        $tmp = explode('/', $value);
351
        $tmp = explode('-', $tmp[0]);
352
        $value = $tmp[0];
353
        if (is_numeric($value) && ((int)$value) > 0) {
354
            $value = (int)$value;
355
        } else {
356
            $value = 0;
357
        }
358
        return $value;
359
    }
360
361
    /**
362
     * Add artist to db if not exist
363
     * @param int $userId
364
     * @param string $sArtist
365
     * @return int
366
     */
367
    public function writeArtistToDB($userId, $sArtist)
368
    {
369
        $sArtist = $this->truncate($sArtist, '256');
370
371
        $stmt = $this->db->prepare('SELECT `id` FROM `*PREFIX*audioplayer_artists` WHERE `user_id` = ? AND `name` = ?');
372
        $stmt->execute(array($userId, $sArtist));
373
        $row = $stmt->fetch();
374
        if ($row) {
375
            return $row['id'];
376
        } else {
377
            $stmt = $this->db->prepare('INSERT INTO `*PREFIX*audioplayer_artists` (`user_id`,`name`) VALUES(?,?)');
378
            $stmt->execute(array($userId, $sArtist));
379
            return $this->db->lastInsertId('*PREFIX*audioplayer_artists');
380
        }
381
    }
382
383
    public function beginTransaction()
384
    {
385
        $this->db->beginTransaction();
386
    }
387
388
    public function commit()
389
    {
390
        $this->db->commit();
391
    }
392
393
    public function rollBack()
394
    {
395
        $this->db->rollBack();
396
    }
397
398
    /**
399
     * Add genre to db if not exist
400
     * @param int $userId
401
     * @param string $sGenre
402
     * @return int
403
     */
404
    public function writeGenreToDB($userId, $sGenre)
405
    {
406
        $sGenre = $this->truncate($sGenre, '256');
407
408
        $stmt = $this->db->prepare('SELECT `id` FROM `*PREFIX*audioplayer_genre` WHERE `user_id` = ? AND `name` = ?');
409
        $stmt->execute(array($userId, $sGenre));
410
        $row = $stmt->fetch();
411
        if ($row) {
412
            return $row['id'];
413
        } else {
414
            $stmt = $this->db->prepare('INSERT INTO `*PREFIX*audioplayer_genre` (`user_id`,`name`) VALUES(?,?)');
415
            $stmt->execute(array($userId, $sGenre));
416
            return $this->db->lastInsertId('*PREFIX*audioplayer_genre');
417
        }
418
    }
419
420
    /**
421
     * Add track to db if not exist
422
     * @param int $userId
423
     * @param array $aTrack
424
     * @return array
425
     */
426
    public function writeTrackToDB($userId, $aTrack)
427
    {
428
        $dublicate = 0;
429
        $insertid = 0;
430
        $SQL = 'SELECT `id` FROM `*PREFIX*audioplayer_tracks` WHERE `user_id`= ? AND `title`= ? AND `number`= ? 
431
				AND `artist_id`= ? AND `album_id`= ? AND `length`= ? AND `bitrate`= ? 
432
				AND `mimetype`= ? AND `genre_id`= ? AND `year`= ?
433
				AND `disc`= ? AND `composer`= ? AND `subtitle`= ?';
434
        $stmt = $this->db->prepare($SQL);
435
        $stmt->execute(array($userId,
436
            $aTrack['title'],
437
            $aTrack['number'],
438
            $aTrack['artist_id'],
439
            $aTrack['album_id'],
440
            $aTrack['length'],
441
            $aTrack['bitrate'],
442
            $aTrack['mimetype'],
443
            $aTrack['genre'],
444
            $aTrack['year'],
445
            $aTrack['disc'],
446
            $aTrack['composer'],
447
            $aTrack['subtitle'],
448
        ));
449
        $row = $stmt->fetch();
450
        if (isset($row['id'])) {
451
            $dublicate = 1;
452
        } else {
453
            $stmt = $this->db->prepare('INSERT INTO `*PREFIX*audioplayer_tracks` (`user_id`,`title`,`number`,`artist_id`,`album_id`,`length`,`file_id`,`bitrate`,`mimetype`,`genre_id`,`year`,`folder_id`,`disc`,`composer`,`subtitle`,`isrc`,`copyright`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
454
            $stmt->execute(array($userId,
455
                $aTrack['title'],
456
                $aTrack['number'],
457
                $aTrack['artist_id'],
458
                $aTrack['album_id'],
459
                $aTrack['length'],
460
                $aTrack['file_id'],
461
                $aTrack['bitrate'],
462
                $aTrack['mimetype'],
463
                $aTrack['genre'],
464
                $aTrack['year'],
465
                $aTrack['folder_id'],
466
                $aTrack['disc'],
467
                $aTrack['composer'],
468
                $aTrack['subtitle'],
469
                $aTrack['isrc'],
470
                $aTrack['copyright'],
471
            ));
472
            $insertid = $this->db->lastInsertId('*PREFIX*audioplayer_tracks');
473
        }
474
        $return = [
475
            'id' => $insertid,
476
            'state' => true,
477
            'dublicate' => $dublicate,
478
        ];
479
        return $return;
480
    }
481
482
    /**
483
     * Get audio info for single track
484
     * @param int $trackId
485
     * @param int $fileId
486
     * @return array
487
     */
488
    public function getTrackInfo($trackId = null, $fileId = null)
489
    {
490
        $SQL = "SELECT `AT`.`title` AS `Title`,
491
                      `AT`.`subtitle` AS `Subtitle`,
492
                      `AA`.`name` AS `Artist`,
493
                      `AB`.`artist_id` AS `Album Artist`,
494
                      `AT`.`composer` AS `Composer`,
495
                      `AB`.`name` AS `Album`,
496
                      `AG`.`name` AS `Genre`,
497
					  `AT`.`year` AS `Year`,
498
                      `AT`.`disc` AS `Disc`,
499
                      `AT`.`number` AS `Track`,
500
					  `AT`.`length` AS `Length`,
501
                      ROUND((`AT`.`bitrate` / 1000 ),0) AS `Bitrate`,
502
                      `AT`.`mimetype` AS `MIME type`,
503
                      `AT`.`isrc` AS `ISRC`,
504
                      `AT`.`copyright` AS `Copyright`,
505
					  `AT`.`file_id`, 
506
					  `AB`.`id` AS `album_id`,
507
                      `AT`.`id`
508
						FROM `*PREFIX*audioplayer_tracks` `AT`
509
						LEFT JOIN `*PREFIX*audioplayer_artists` `AA` ON `AT`.`artist_id` = `AA`.`id`
510
						LEFT JOIN `*PREFIX*audioplayer_genre` `AG` ON `AT`.`genre_id` = `AG`.`id`
511
						LEFT JOIN `*PREFIX*audioplayer_albums` `AB` ON `AT`.`album_id` = `AB`.`id`";
512
513
        if ($trackId !== null) {
514
            $SQL .= " WHERE  `AT`.`user_id` = ? AND `AT`.`id` = ?
515
			 		ORDER BY `AT`.`album_id` ASC,`AT`.`number` ASC ";
516
            $selectId = $trackId;
517
        } else {
518
            $SQL .= " WHERE  `AT`.`user_id` = ? AND `AT`.`file_id` = ?
519
			 		ORDER BY `AT`.`album_id` ASC,`AT`.`number` ASC ";
520
            $selectId = $fileId;
521
        }
522
523
        $stmt = $this->db->prepare($SQL);
524
        $stmt->execute(array($this->userId, $selectId));
525
        $row = $stmt->fetch();
526
527
        $favorites = $this->tagManager->load('files')->getFavorites();
528
        if (in_array($row['file_id'], $favorites)) {
0 ignored issues
show
Bug introduced by Rello
It seems like $favorites can also be of type false; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

528
        if (in_array($row['file_id'], /** @scrutinizer ignore-type */ $favorites)) {
Loading history...
529
            $row['fav'] = "t";
530
        } else {
531
            $row['fav'] = "f";
532
        }
533
534
        return $row;
535
    }
536
537
    /**
538
     * Get file id for single track
539
     * @param int $trackId
540
     * @return int
541
     */
542
    public function getFileId($trackId)
543
    {
544
        $SQL = "SELECT `file_id` FROM `*PREFIX*audioplayer_tracks` WHERE  `user_id` = ? AND `id` = ?";
545
        $stmt = $this->db->prepare($SQL);
546
        $stmt->execute(array($this->userId, $trackId));
547
        $row = $stmt->fetch();
548
        return $row['file_id'];
549
    }
550
551
    /**
552
     * Add track to db if not exist
553
     * @param int $userId
554
     * @param int $track_id
555
     * @param string $editKey
556
     * @param string $editValue
557
     * @return bool
558
     */
559
    public function updateTrack($userId, $track_id, $editKey, $editValue)
560
    {
561
        $SQL = 'UPDATE `*PREFIX*audioplayer_tracks` SET `' . $editKey . '` = ? WHERE `user_id` = ? AND `id` = ?';
562
        $stmt = $this->db->prepare($SQL);
563
        $stmt->execute(array($editValue,
564
            $userId,
565
            $track_id
566
        ));
567
        return true;
568
    }
569
570
    /**
571
     * Add stream to db if not exist
572
     * @param int $userId
573
     * @param array $aStream
574
     * @return array
575
     */
576
    public function writeStreamToDB($userId, $aStream)
577
    {
578
        $stmt = $this->db->prepare('SELECT `id` FROM `*PREFIX*audioplayer_streams` WHERE `user_id` = ? AND `file_id` = ? ');
579
        $stmt->execute(array($userId, $aStream['file_id']));
580
        $row = $stmt->fetch();
581
        $dublicate = 0;
582
        $insertid = 0;
583
        if (isset($row['id'])) {
584
            $dublicate = 1;
585
        } else {
586
            $stmt = $this->db->prepare('INSERT INTO `*PREFIX*audioplayer_streams` (`user_id`,`title`,`file_id`,`mimetype`) VALUES(?,?,?,?)');
587
            $stmt->execute(array($userId,
588
                $aStream['title'],
589
                $aStream['file_id'],
590
                $aStream['mimetype'],
591
            ));
592
            $insertid = $this->db->lastInsertId('*PREFIX*audioplayer_streams');
593
        }
594
        $return = [
595
            'id' => $insertid,
596
            'state' => true,
597
            'dublicate' => $dublicate,
598
        ];
599
        return $return;
600
    }
601
602
    /**
603
     * Get all playlists were track is added
604
     * @param int $userId
605
     * @param int $trackId
606
     * @return array
607
     */
608
    public function getPlaylistsForTrack($userId, $trackId)
609
    {
610
        $playlists = array();
611
        $SQL = "SELECT  `AP`.`playlist_id` , `AN`.`name`, LOWER(`AN`.`name`) AS `lower`
612
						FROM `*PREFIX*audioplayer_playlist_tracks` `AP`
613
						LEFT JOIN `*PREFIX*audioplayer_playlists` `AN` 
614
						ON `AP`.`playlist_id` = `AN`.`id`
615
			 			WHERE  `AN`.`user_id` = ?
616
			 			AND `AP`.`track_id` = ?
617
			 			ORDER BY LOWER(`AN`.`name`) ASC
618
			 			";
619
        $stmt = $this->db->prepare($SQL);
620
        $stmt->execute(array($userId, $trackId));
621
        $results = $stmt->fetchAll();
622
        foreach ($results as $row) {
623
            array_splice($row, 2, 1);
624
            $playlists[] = $row;
625
        }
626
627
        return $playlists;
628
    }
629
630
    /**
631
     * @NoAdminRequired
632
     * @param $type
633
     * @param $value
634
     * @param $userId
635
     * @return string
636
     */
637
    public function setSessionValue($type, $value, $userId)
638
    {
639
        if ($userId) {
640
            $this->userId = $userId;
641
        }
642
        //$this->session->set($type, $value);
643
        $SQL = 'SELECT `configvalue` FROM `*PREFIX*preferences` WHERE `userid`= ? AND `appid`= ? AND `configkey`= ?';
644
        $stmt = $this->db->prepare($SQL);
645
        $stmt->execute(array($this->userId, 'audioplayer', $type));
646
        $row = $stmt->fetch();
647
        if (isset($row['configvalue'])) {
648
            $stmt = $this->db->prepare('UPDATE `*PREFIX*preferences` SET `configvalue`= ? WHERE `userid`= ? AND `appid`= ? AND `configkey`= ?');
649
            $stmt->execute(array($value, $this->userId, 'audioplayer', $type));
650
            return 'update';
651
        } else {
652
            $stmt = $this->db->prepare('INSERT INTO `*PREFIX*preferences` (`userid`,`appid`,`configkey`,`configvalue`) VALUES(?,?,?,?)');
653
            $stmt->execute(array($this->userId, 'audioplayer', $type, $value));
654
            return 'insert';
655
        }
656
    }
657
658
    /**
659
     * @NoAdminRequired
660
     * @param $type
661
     * @return string
662
     */
663
    public function getSessionValue($type)
664
    {
665
        //return $this->session->get($type);
666
        $SQL = 'SELECT `configvalue` FROM `*PREFIX*preferences` WHERE `userid`= ? AND `appid`= ? AND `configkey`= ?';
667
        $stmt = $this->db->prepare($SQL);
668
        $stmt->execute(array($this->userId, 'audioplayer', $type));
669
        $row = $stmt->fetch();
670
        return $row['configvalue'];
671
    }
672
}
673