DbController   C
last analyzed

Complexity

Total Complexity 53

Size/Duplication

Total Lines 638
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
eloc 311
c 3
b 0
f 1
dl 0
loc 638
rs 6.96
wmc 53

22 Methods

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

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