Passed
Pull Request — master (#752)
by
unknown
02:07
created

PlaylistBusinessLayer::createPlayQueueWithTracks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 2
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * ownCloud - Music app
5
 *
6
 * This file is licensed under the Affero General Public License version 3 or
7
 * later. See the COPYING file.
8
 *
9
 * @author Pauli Järvinen <[email protected]>
10
 * @copyright Pauli Järvinen 2016 - 2019
11
 */
12
13
namespace OCA\Music\BusinessLayer;
14
15
use \OCA\Music\AppFramework\BusinessLayer\BusinessLayer;
16
use \OCA\Music\AppFramework\BusinessLayer\BusinessLayerException;
17
use \OCA\Music\AppFramework\Core\Logger;
18
19
use \OCA\Music\Db\PlaylistMapper;
20
use \OCA\Music\Db\Playlist;
21
use \OCA\Music\Db\SortBy;
22
23
use \OCA\Music\Utility\Util;
24
25
class PlaylistBusinessLayer extends BusinessLayer {
26
        const PLAYQUEUE_PLAYLIST_NAME = '{playqueue}';
27
28
	private $logger;
29
	private $trackBusinessLayer;
30
31
	public function __construct(
32
			PlaylistMapper $playlistMapper,
33
			TrackBusinessLayer $trackBusinessLayer,
34
			Logger $logger) {
35
		parent::__construct($playlistMapper);
36
		$this->logger = $logger;
37
		$this->trackBusinessLayer = $trackBusinessLayer;
38
	}
39
40
	public function addTracks($trackIds, $playlistId, $userId) {
41
		$playlist = $this->find($playlistId, $userId);
42
		$prevTrackIds = $playlist->getTrackIdsAsArray();
43
		$playlist->setTrackIdsFromArray(\array_merge($prevTrackIds, $trackIds));
44
		$this->mapper->update($playlist);
45
		return $playlist;
46
	}
47
48
	public function removeTracks($trackIndices, $playlistId, $userId) {
49
		$playlist = $this->find($playlistId, $userId);
50
		$trackIds = $playlist->getTrackIdsAsArray();
51
		$trackIds = \array_diff_key($trackIds, \array_flip($trackIndices));
52
		$playlist->setTrackIdsFromArray($trackIds);
53
		$this->mapper->update($playlist);
54
		return $playlist;
55
	}
56
57
	public function moveTrack($fromIndex, $toIndex, $playlistId, $userId) {
58
		$playlist = $this->find($playlistId, $userId);
59
		$trackIds = $playlist->getTrackIdsAsArray();
60
		$movedTrack = \array_splice($trackIds, $fromIndex, 1);
61
		\array_splice($trackIds, $toIndex, 0, $movedTrack);
62
		$playlist->setTrackIdsFromArray($trackIds);
63
		$this->mapper->update($playlist);
64
		return $playlist;
65
	}
66
67
	public function create($name, $userId) {
68
    // if playlist with given name already exists, don't re-create it (return record will include existing tracks)
69
    $existingPlaylists = $this->findAllByName($name, $userId);
70
    if (count($existingPlaylists) > 0)
71
      return $existingPlaylists[0];
72
73
		$playlist = new Playlist();
74
		$playlist->setName(Util::truncate($name, 256)); // some DB setups can't truncate automatically to column max size
75
		$playlist->setUserId($userId);
76
77
		return $this->mapper->insert($playlist);
78
	}
79
80
        public function createWithTracks($userId, $name, $trackIds) {
81
          // if playlist with given name already exists, don't re-create it (return record will include existing tracks)
82
          $existingPlaylists = $this->findAllByName($name, $userId);
83
          if (count($existingPlaylists) > 0)
84
          {
85
            $existingPlaylists[0]->setTrackIdsFromArray($trackIds);
86
            return $this->mapper->update($existingPlaylists[0]);
87
          }
88
89
          $playlist = new Playlist();
90
          $playlist->setName(Util::truncate($name, 256)); // some DB setups can't truncate automatically to column max size
91
          $playlist->setUserId($userId);
92
          $playlist->setTrackIdsFromArray($trackIds);
93
94
          return $this->mapper->insert($playlist);
95
        }
96
97
	public function rename($name, $playlistId, $userId) {
98
		$playlist = $this->find($playlistId, $userId);
99
		$playlist->setName(Util::truncate($name, 256)); // some DB setups can't truncate automatically to column max size
100
		$this->mapper->update($playlist);
101
		return $playlist;
102
	}
103
104
	/**
105
	 * removes tracks from all available playlists
106
	 * @param int[] $trackIds array of all track IDs to remove
107
	 */
108
	public function removeTracksFromAllLists($trackIds) {
109
		foreach ($trackIds as $trackId) {
110
			$affectedLists = $this->mapper->findListsContainingTrack($trackId);
111
112
			foreach ($affectedLists as $playlist) {
113
				$prevTrackIds = $playlist->getTrackIdsAsArray();
114
				$playlist->setTrackIdsFromArray(\array_diff($prevTrackIds, [$trackId]));
115
				$this->mapper->update($playlist);
116
			}
117
		}
118
	}
119
120
	/**
121
	 * get list of Track objects belonging to a given playlist
122
	 * @param int $playlistId
123
	 * @param string $userId
124
	 * @param int|null $limit
125
	 * @param int|null $offset
126
	 * @return Track[]
127
	 */
128
	public function getPlaylistTracks($playlistId, $userId, $limit=null, $offset=null) {
129
		$playlist = $this->find($playlistId, $userId);
130
		$trackIds = $playlist->getTrackIdsAsArray();
131
132
		$trackIds = \array_slice($trackIds, \intval($offset), $limit);
133
134
		$tracks = empty($trackIds) ? [] : $this->trackBusinessLayer->findById($trackIds, $userId);
135
136
		// The $tracks contains the songs in unspecified order and with no duplicates.
137
		// Build a new array where the tracks are in the same order as in $trackIds.
138
		// First create an index as a middle-step.
139
		$tracksById = [];
140
		foreach ($tracks as $track) {
141
			$tracksById[$track->getId()] = $track;
142
		}
143
		$playlistTracks = [];
144
		foreach ($trackIds as $trackId) {
145
			$track = $tracksById[$trackId];
146
			$track->setNumber(\count($playlistTracks) + 1); // override track # with the ordinal on the list
147
			$playlistTracks[] = $track;
148
		}
149
150
		return $playlistTracks;
151
	}
152
153
	/**
154
	 * @param string $name
155
	 * @param string $userId
156
	 * @param bool $fuzzy
157
	 * @param integer $limit
158
	 * @param integer $offset
159
	 * @return Playlist[]
160
	 */
161
        public function findAllByName($name, $userId, $fuzzy = false, $limit=null, $offset=null) {
162
          return $this->mapper->findAllByName($name, $userId, $fuzzy, $limit, $offset);
163
        }
164
165
	/**
166
	 * Finds all entities
167
	 * @param string $userId the name of the user
168
	 * @param integer $sortBy sort order of the result set
169
	 * @param integer $limit
170
	 * @param integer $offset
171
	 * @return Entity[]
172
	 */
173
        public function findAll($userId, $sortBy=SortBy::None, $limit=null, $offset=null) {
174
          $playlists = $this->mapper->findAll($userId, $sortBy, $limit, $offset);
175
176
          // remove playqueue if it exists in results
177
          foreach ($playlists as $key => $playlist) {
178
            if ($playlist->getName() == self::PLAYQUEUE_PLAYLIST_NAME) {
179
              unset($playlists[$key]);
180
              break;
181
            }
182
          }
183
184
          return $playlists;
185
        }
186
187
	/**
188
	 * Finds all entities
189
	 * @param string $userId the name of the user
190
	 * @return Entity[] or null
191
	 */
192
        public function findPlayQueue($userId) {
193
          return array_shift($this->findAllByName(self::PLAYQUEUE_PLAYLIST_NAME, $userId));
0 ignored issues
show
Bug introduced by
$this->findAllByName(sel...PLAYLIST_NAME, $userId) cannot be passed to array_shift() as the parameter $array expects a reference. ( Ignorable by Annotation )

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

193
          return array_shift(/** @scrutinizer ignore-type */ $this->findAllByName(self::PLAYQUEUE_PLAYLIST_NAME, $userId));
Loading history...
194
        }
195
196
	/**
197
	 * Finds all entities
198
	 * @param string $userId the name of the user
199
	 * @return Entity[] or null
200
	 */
201
        public function createPlayQueueWithTracks($userId, $trackIds) {
202
          return $this->createWithTracks($userId, self::PLAYQUEUE_PLAYLIST_NAME, $trackIds);
203
        }
204
}
205