Passed
Push — master ( d9d99b...742760 )
by Marcel
04:55 queued 02:45
created

DbController::commit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 3
rs 10
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 as JSONResponseAlias;
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|JSONResponseAlias
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
            $response = new JSONResponseAlias();
201
            $response->setData($result);
202
            return $response;
203
        } elseif ($hook === null) {
204
            $output->writeln("Reset finished");
205
        } else {
206
            $this->logger->info('Library of "' . $userId . '" reset due to user deletion', array('app' => 'audioplayer'));
207
        }
208
        return true;
209
    }
210
211
    /**
212
     * Delete single title from audio player tables
213
     * @NoAdminRequired
214
     * @param int $file_id
215
     * @param int $userId
216
     * @return bool
217
     */
218
    public function deleteFromDB($file_id, $userId = null)
219
    {
220
        // check if scanner is started from web or occ
221
        if ($userId !== null) {
222
            $this->userId = $userId;
223
        }
224
        $this->logger->debug('deleteFromDB: ' . $file_id, array('app' => 'audioplayer'));
225
226
        $stmt = $this->db->prepare('SELECT `album_id`, `id` FROM `*PREFIX*audioplayer_tracks` WHERE `file_id` = ?  AND `user_id` = ?');
227
        $stmt->execute(array($file_id, $this->userId));
228
        $row = $stmt->fetch();
229
        $AlbumId = $row['album_id'];
230
        $TrackId = $row['id'];
231
232
        $stmt = $this->db->prepare('SELECT COUNT(`album_id`) AS `ALBUMCOUNT`  FROM `*PREFIX*audioplayer_tracks` WHERE `album_id` = ? ');
233
        $stmt->execute(array($AlbumId));
234
        $row = $stmt->fetch();
235
        if ((int)$row['ALBUMCOUNT'] === 1) {
236
            $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_albums` WHERE `id` = ? AND `user_id` = ?');
237
            $stmt->execute(array($AlbumId, $this->userId));
238
        }
239
240
        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_tracks` WHERE  `file_id` = ? AND `user_id` = ?');
241
        $stmt->execute(array($file_id, $this->userId));
242
243
        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*audioplayer_streams` WHERE  `file_id` = ? AND `user_id` = ?');
244
        $stmt->execute(array($file_id, $this->userId));
245
246
        $stmt = $this->db->prepare('SELECT `playlist_id` FROM `*PREFIX*audioplayer_playlist_tracks` WHERE `track_id` = ?');
247
        $stmt->execute(array($TrackId));
248
        $row = $stmt->fetch();
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
        return true;
262
    }
263
264
    /**
265
     * write cover image data to album
266
     * @param int $userId
267
     * @param integer $iAlbumId
268
     * @param string $sImage
269
     * @return true
270
     */
271
    public function writeCoverToAlbum($userId, $iAlbumId, $sImage)
272
    {
273
        $stmt = $this->db->prepare('UPDATE `*PREFIX*audioplayer_albums` SET `cover`= ?, `bgcolor`= ? WHERE `id` = ? AND `user_id` = ?');
274
        $stmt->execute(array($sImage, '', $iAlbumId, $userId));
275
        return true;
276
    }
277
278
    /**
279
     * Add album to db if not exist
280
     * @param int $userId
281
     * @param string $sAlbum
282
     * @param string $sYear
283
     * @param int $iArtistId
284
     * @param int $parentId
285
     * @return array
286
     * @throws \Doctrine\DBAL\DBALException
287
     */
288
    public function writeAlbumToDB($userId, $sAlbum, $sYear, $iArtistId, $parentId)
289
    {
290
        $sAlbum = $this->truncate($sAlbum, '256');
291
        $sYear = $this->normalizeInteger($sYear);
292
        $AlbumCount = 0;
293
294
        $stmt = $this->db->prepare('SELECT `id`, `artist_id` FROM `*PREFIX*audioplayer_albums` WHERE `user_id` = ? AND `name` = ? AND `folder_id` = ?');
295
        $stmt->execute(array($userId, $sAlbum, $parentId));
296
        $row = $stmt->fetch();
297
        if ($row) {
298
            if ((int)$row['artist_id'] !== (int)$iArtistId) {
299
                $various_id = $this->writeArtistToDB($userId, $this->l10n->t('Various Artists'));
300
                $stmt = $this->db->prepare('UPDATE `*PREFIX*audioplayer_albums` SET `artist_id`= ? WHERE `id` = ? AND `user_id` = ?');
301
                $stmt->execute(array($various_id, $row['id'], $userId));
302
            }
303
            $insertid = $row['id'];
304
        } else {
305
            $stmt = $this->db->prepare('INSERT INTO `*PREFIX*audioplayer_albums` (`user_id`,`name`,`folder_id`) VALUES(?,?,?)');
306
            $stmt->execute(array($userId, $sAlbum, $parentId));
307
            $insertid = $this->db->lastInsertId('*PREFIX*audioplayer_albums');
308
            if ($iArtistId) {
309
                $stmt = $this->db->prepare('UPDATE `*PREFIX*audioplayer_albums` SET `year`= ?, `artist_id`= ? WHERE `id` = ? AND `user_id` = ?');
310
                $stmt->execute(array((int)$sYear, $iArtistId, $insertid, $userId));
311
            } else {
312
                $stmt = $this->db->prepare('UPDATE `*PREFIX*audioplayer_albums` SET `year`= ? WHERE `id` = ? AND `user_id` = ?');
313
                $stmt->execute(array((int)$sYear, $insertid, $userId));
314
            }
315
            $AlbumCount = 1;
316
        }
317
318
        $return = [
319
            'id' => $insertid,
320
            'state' => true,
321
            'albumcount' => $AlbumCount,
322
        ];
323
        return $return;
324
    }
325
326
    /**
327
     * truncates fiels do DB-field size
328
     *
329
     * @param $string
330
     * @param $length
331
     * @param $dots
332
     * @return string
333
     */
334
    private function truncate($string, $length, $dots = "...")
335
    {
336
        return (strlen($string) > $length) ? mb_strcut($string, 0, $length - strlen($dots)) . $dots : $string;
337
    }
338
339
    /**
340
     * validate unsigned int values
341
     *
342
     * @param string $value
343
     * @return int value
344
     */
345
    private function normalizeInteger($value)
346
    {
347
        // convert format '1/10' to '1' and '-1' to null
348
        $tmp = explode('/', $value);
349
        $tmp = explode('-', $tmp[0]);
350
        $value = $tmp[0];
351
        if (is_numeric($value) && ((int)$value) > 0) {
352
            $value = (int)$value;
353
        } else {
354
            $value = 0;
355
        }
356
        return $value;
357
    }
358
359
    /**
360
     * Add artist to db if not exist
361
     * @param int $userId
362
     * @param string $sArtist
363
     * @return int
364
     */
365
    public function writeArtistToDB($userId, $sArtist)
366
    {
367
        $sArtist = $this->truncate($sArtist, '256');
368
369
        $stmt = $this->db->prepare('SELECT `id` FROM `*PREFIX*audioplayer_artists` WHERE `user_id` = ? AND `name` = ?');
370
        $stmt->execute(array($userId, $sArtist));
371
        $row = $stmt->fetch();
372
        if ($row) {
373
            return $row['id'];
374
        } else {
375
            $stmt = $this->db->prepare('INSERT INTO `*PREFIX*audioplayer_artists` (`user_id`,`name`) VALUES(?,?)');
376
            $stmt->execute(array($userId, $sArtist));
377
            $insertid = $this->db->lastInsertId('*PREFIX*audioplayer_artists');
378
            return $insertid;
379
        }
380
    }
381
382
    public function beginTransaction()
383
    {
384
        $this->db->beginTransaction();
385
    }
386
387
    public function commit()
388
    {
389
        $this->db->commit();
390
    }
391
392
    public function rollBack()
393
    {
394
        $this->db->rollBack();
395
    }
396
397
    /**
398
     * Add genre to db if not exist
399
     * @param int $userId
400
     * @param string $sGenre
401
     * @return int
402
     */
403
    public function writeGenreToDB($userId, $sGenre)
404
    {
405
        $sGenre = $this->truncate($sGenre, '256');
406
407
        $stmt = $this->db->prepare('SELECT `id` FROM `*PREFIX*audioplayer_genre` WHERE `user_id` = ? AND `name` = ?');
408
        $stmt->execute(array($userId, $sGenre));
409
        $row = $stmt->fetch();
410
        if ($row) {
411
            return $row['id'];
412
        } else {
413
            $stmt = $this->db->prepare('INSERT INTO `*PREFIX*audioplayer_genre` (`user_id`,`name`) VALUES(?,?)');
414
            $stmt->execute(array($userId, $sGenre));
415
            $insertid = $this->db->lastInsertId('*PREFIX*audioplayer_genre');
416
            return $insertid;
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
491
        $SQL = "SELECT `AT`.`title` AS `Title`,
492
                      `AT`.`subtitle` AS `Subtitle`,
493
                      `AA`.`name` AS `Artist`,
494
                      `AB`.`artist_id` AS `Album Artist`,
495
                      `AT`.`composer` AS `Composer`,
496
                      `AB`.`name` AS `Album`,
497
                      `AG`.`name` AS `Genre`,
498
					  `AT`.`year` AS `Year`,
499
                      `AT`.`disc` AS `Disc`,
500
                      `AT`.`number` AS `Track`,
501
					  `AT`.`length` AS `Length`,
502
                      ROUND((`AT`.`bitrate` / 1000 ),0) AS `Bitrate`,
503
                      `AT`.`mimetype` AS `MIME type`,
504
                      `AT`.`isrc` AS `ISRC`,
505
                      `AT`.`copyright` AS `Copyright`,
506
					  `AT`.`file_id`, 
507
					  `AB`.`id` AS `album_id`,
508
                      `AT`.`id`
509
						FROM `*PREFIX*audioplayer_tracks` `AT`
510
						LEFT JOIN `*PREFIX*audioplayer_artists` `AA` ON `AT`.`artist_id` = `AA`.`id`
511
						LEFT JOIN `*PREFIX*audioplayer_genre` `AG` ON `AT`.`genre_id` = `AG`.`id`
512
						LEFT JOIN `*PREFIX*audioplayer_albums` `AB` ON `AT`.`album_id` = `AB`.`id`";
513
514
        if ($trackId !== null) {
515
            $SQL .= " WHERE  `AT`.`user_id` = ? AND `AT`.`id` = ?
516
			 		ORDER BY `AT`.`album_id` ASC,`AT`.`number` ASC ";
517
            $selectId = $trackId;
518
        } else {
519
            $SQL .= " WHERE  `AT`.`user_id` = ? AND `AT`.`file_id` = ?
520
			 		ORDER BY `AT`.`album_id` ASC,`AT`.`number` ASC ";
521
            $selectId = $fileId;
522
        }
523
524
        $stmt = $this->db->prepare($SQL);
525
        $stmt->execute(array($this->userId, $selectId));
526
        $row = $stmt->fetch();
527
528
        $favorites = $this->tagManager->load('files')->getFavorites();
529
        if (in_array($row['file_id'], $favorites)) {
0 ignored issues
show
Bug introduced by
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

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