| Total Complexity | 72 |
| Total Lines | 445 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Complex classes like CoverService 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 CoverService, and based on these observations, apply Extract Interface, too.
| 1 | <?php declare(strict_types=1); |
||
| 37 | class CoverService { |
||
| 38 | private Extractor $extractor; |
||
| 39 | private Cache $cache; |
||
| 40 | private AlbumBusinessLayer $albumBusinessLayer; |
||
| 41 | private int $coverSize; |
||
| 42 | private IL10N $l10n; |
||
| 43 | private Logger $logger; |
||
| 44 | |||
| 45 | const MAX_SIZE_TO_CACHE = 102400; |
||
| 46 | const DO_NOT_CROP_OR_SCALE = -1; |
||
| 47 | |||
| 48 | public function __construct( |
||
| 63 | } |
||
| 64 | |||
| 65 | /** |
||
| 66 | * Get cover image of an album, an artist, a podcast, or a playlist. |
||
| 67 | * Returns a generated placeholder in case there's no art set. |
||
| 68 | * |
||
| 69 | * @param int|null $size Desired (max) image size, null to use the default. |
||
| 70 | * Special value DO_NOT_CROP_OR_SCALE can be used to opt out of |
||
| 71 | * scaling and cropping altogether. |
||
| 72 | * @return array|null Image data in format accepted by \OCA\Music\Http\FileResponse |
||
| 73 | */ |
||
| 74 | public function getCover(Entity $entity, string $userId, Folder $rootFolder, ?int $size=null, bool $allowPlaceholder=true) : ?array { |
||
| 75 | if ($entity instanceof Playlist) { |
||
| 76 | $trackIds = $entity->getTrackIdsAsArray(); |
||
| 77 | $albums = $this->albumBusinessLayer->findAlbumsWithCoversForTracks($trackIds, $userId, 4); |
||
| 78 | $result = $this->getCoverMosaic($albums, $userId, $rootFolder, $size); |
||
| 79 | } elseif ($entity instanceof RadioStation) { |
||
| 80 | $result = null; // only placeholders supported for radio |
||
| 81 | } elseif ($entity instanceof Album || $entity instanceof Artist || $entity instanceof PodcastChannel) { |
||
| 82 | if ($size !== null) { |
||
| 83 | // Skip using cache in case the cover is requested in specific size |
||
| 84 | $result = $this->readCover($entity, $rootFolder, $size); |
||
| 85 | } else { |
||
| 86 | $dataAndHash = $this->getCoverAndHash($entity, $userId, $rootFolder); |
||
| 87 | $result = $dataAndHash['data']; |
||
| 88 | } |
||
| 89 | } else { |
||
| 90 | // only placeholder is supported for any other Entity type |
||
| 91 | $result = null; |
||
| 92 | } |
||
| 93 | |||
| 94 | if ($result === null && $allowPlaceholder) { |
||
| 95 | $result = $this->getPlaceholder($entity, $size); |
||
| 96 | } |
||
| 97 | |||
| 98 | return $result; |
||
| 99 | } |
||
| 100 | |||
| 101 | public function getCoverMosaic(array $entities, string $userId, Folder $rootFolder, ?int $size=null) : ?array { |
||
| 102 | if (\count($entities) === 0) { |
||
| 103 | return null; |
||
| 104 | } elseif (\count($entities) === 1) { |
||
| 105 | return $this->getCover($entities[0], $userId, $rootFolder, $size); |
||
| 106 | } else { |
||
| 107 | $covers = \array_map(fn($entity) => $this->getCover($entity, $userId, $rootFolder), $entities); |
||
| 108 | return $this->createMosaic($covers, $size); |
||
| 109 | } |
||
| 110 | } |
||
| 111 | |||
| 112 | /** |
||
| 113 | * Get cover image of an album or and artist along with the image's hash |
||
| 114 | * |
||
| 115 | * The hash is non-null only in case the cover is/was cached. |
||
| 116 | * |
||
| 117 | * @param Album|Artist|PodcastChannel $entity |
||
| 118 | * @param string $userId |
||
| 119 | * @param Folder $rootFolder |
||
| 120 | * @return array Dictionary with keys 'data' and 'hash' |
||
| 121 | */ |
||
| 122 | public function getCoverAndHash($entity, string $userId, Folder $rootFolder) : array { |
||
| 123 | $hash = $this->cache->get($userId, self::getHashKey($entity)); |
||
| 124 | $data = null; |
||
| 125 | |||
| 126 | if ($hash !== null) { |
||
| 127 | $data = $this->getCoverFromCache($hash, $userId); |
||
| 128 | } |
||
| 129 | if ($data === null) { |
||
| 130 | $hash = null; |
||
| 131 | $data = $this->readCover($entity, $rootFolder, $this->coverSize); |
||
| 132 | if ($data !== null) { |
||
| 133 | $hash = $this->addCoverToCache($entity, $userId, $data); |
||
| 134 | } |
||
| 135 | } |
||
| 136 | |||
| 137 | return ['data' => $data, 'hash' => $hash]; |
||
| 138 | } |
||
| 139 | |||
| 140 | /** |
||
| 141 | * Get all album cover hashes for one user. |
||
| 142 | * @param string $userId |
||
| 143 | * @return array with album IDs as keys and hashes as values |
||
| 144 | */ |
||
| 145 | public function getAllCachedAlbumCoverHashes(string $userId) : array { |
||
| 146 | $rows = $this->cache->getAll($userId, 'album_cover_hash_'); |
||
| 147 | $hashes = []; |
||
| 148 | $prefixLen = \strlen('album_cover_hash_'); |
||
| 149 | foreach ($rows as $row) { |
||
| 150 | $albumId = \substr($row['key'], $prefixLen); |
||
| 151 | $hashes[$albumId] = $row['data']; |
||
| 152 | } |
||
| 153 | return $hashes; |
||
| 154 | } |
||
| 155 | |||
| 156 | /** |
||
| 157 | * Get cover image with given hash from the cache |
||
| 158 | * |
||
| 159 | * @param string $hash |
||
| 160 | * @param string $userId |
||
| 161 | * @param bool $asBase64 |
||
| 162 | * @return array|null Image data in format accepted by \OCA\Music\Http\FileResponse |
||
| 163 | */ |
||
| 164 | public function getCoverFromCache(string $hash, string $userId, bool $asBase64 = false) : ?array { |
||
| 165 | $cached = $this->cache->get($userId, 'cover_' . $hash); |
||
| 166 | if ($cached !== null) { |
||
| 167 | $delimPos = \strpos($cached, '|'); |
||
| 168 | $mime = \substr($cached, 0, $delimPos); |
||
| 169 | $content = \substr($cached, $delimPos + 1); |
||
| 170 | if (!$asBase64) { |
||
| 171 | $content = \base64_decode($content); |
||
| 172 | } |
||
| 173 | return ['mimetype' => $mime, 'content' => $content]; |
||
| 174 | } |
||
| 175 | return null; |
||
| 176 | } |
||
| 177 | |||
| 178 | private function getPlaceholder(Entity $entity, ?int $size) : array { |
||
| 187 | } |
||
| 188 | |||
| 189 | /** |
||
| 190 | * Cache the given cover image data |
||
| 191 | * @param Album|Artist|PodcastChannel $entity |
||
| 192 | * @param string $userId |
||
| 193 | * @param array $coverData |
||
| 194 | * @return string|null Hash of the cached cover |
||
| 195 | */ |
||
| 196 | private function addCoverToCache(Entity $entity, string $userId, array $coverData) : ?string { |
||
| 197 | $mime = $coverData['mimetype']; |
||
| 198 | $content = $coverData['content']; |
||
| 199 | $hash = null; |
||
| 200 | $hashKey = self::getHashKey($entity); |
||
| 201 | |||
| 202 | if ($mime && $content) { |
||
| 203 | $size = \strlen($content); |
||
| 204 | if ($size < self::MAX_SIZE_TO_CACHE) { |
||
| 205 | $hash = \hash('md5', $content); |
||
| 206 | // cache the data with hash as a key |
||
| 207 | try { |
||
| 208 | $this->cache->add($userId, 'cover_' . $hash, $mime . '|' . \base64_encode($content)); |
||
| 209 | } catch (UniqueConstraintViolationException $ex) { |
||
| 210 | $this->logger->debug("Cover with hash $hash is already cached"); |
||
| 211 | } |
||
| 212 | // cache the hash with hashKey as a key |
||
| 213 | try { |
||
| 214 | $this->cache->add($userId, $hashKey, $hash); |
||
| 215 | } catch (UniqueConstraintViolationException $ex) { |
||
| 216 | $this->logger->debug("Cover hash with key $hashKey is already cached"); |
||
| 217 | } |
||
| 218 | // collection.json needs to be regenerated the next time it's fetched |
||
| 219 | $this->cache->remove($userId, 'collection'); |
||
| 220 | } else { |
||
| 221 | $this->logger->debug("Cover image of entity with key $hashKey is large ($size B), skip caching"); |
||
| 222 | } |
||
| 223 | } |
||
| 224 | |||
| 225 | return $hash; |
||
| 226 | } |
||
| 227 | |||
| 228 | /** |
||
| 229 | * Remove album cover image from cache if it is there. Silently do nothing if there |
||
| 230 | * is no cached cover. All users are targeted if no $userId passed. |
||
| 231 | */ |
||
| 232 | public function removeAlbumCoverFromCache(int $albumId, ?string $userId=null) : void { |
||
| 234 | } |
||
| 235 | |||
| 236 | /** |
||
| 237 | * Remove artist cover image from cache if it is there. Silently do nothing if there |
||
| 238 | * is no cached cover. All users are targeted if no $userId passed. |
||
| 239 | */ |
||
| 240 | public function removeArtistCoverFromCache(int $artistId, ?string $userId=null) : void { |
||
| 242 | } |
||
| 243 | |||
| 244 | /** |
||
| 245 | * Read cover image from the entity-specific file or URL and scale it unless the caller opts out of it |
||
| 246 | * @param Album|Artist|PodcastChannel $entity |
||
| 247 | * @param Folder $rootFolder |
||
| 248 | * @param int $size Maximum size for the image to read, larger images are scaled down. |
||
| 249 | * Special value DO_NOT_CROP_OR_SCALE can be used to opt out of |
||
| 250 | * scaling and cropping altogether. |
||
| 251 | * @return array|null Image data in format accepted by \OCA\Music\Http\FileResponse |
||
| 252 | */ |
||
| 253 | private function readCover($entity, Folder $rootFolder, int $size) : ?array { |
||
| 254 | $response = null; |
||
| 255 | |||
| 256 | if ($entity instanceof PodcastChannel) { |
||
| 257 | if ($entity->getImageUrl() !== null) { |
||
| 258 | list('content' => $image, 'content_type' => $mime) = HttpUtil::loadFromUrl($entity->getImageUrl()); |
||
| 259 | if ($image !== false) { |
||
| 260 | $response = ['mimetype' => $mime, 'content' => $image]; |
||
| 261 | } |
||
| 262 | } |
||
| 263 | } else { |
||
| 264 | $response = $this->readCoverFromLocalFile($entity, $rootFolder); |
||
| 265 | } |
||
| 266 | |||
| 267 | if ($response !== null) { |
||
| 268 | if ($size !== self::DO_NOT_CROP_OR_SCALE) { |
||
| 269 | $response = $this->scaleDownAndCrop($response, $size); |
||
| 270 | } elseif ($response['mimetype'] === null) { |
||
| 271 | $response['mimetype'] = self::autoDetectMime($response['content']); |
||
| 272 | } |
||
| 273 | } |
||
| 274 | |||
| 275 | return $response; |
||
| 276 | } |
||
| 277 | |||
| 278 | /** |
||
| 279 | * Read cover image from the file system |
||
| 280 | * @param Album|Artist $entity |
||
| 281 | * @param Folder $rootFolder |
||
| 282 | * @return array|null Image data in format accepted by \OCA\Music\Http\FileResponse |
||
| 283 | */ |
||
| 284 | private function readCoverFromLocalFile($entity, Folder $rootFolder) : ?array { |
||
| 285 | $response = null; |
||
| 286 | |||
| 287 | $coverId = $entity->getCoverFileId(); |
||
| 288 | if ($coverId > 0) { |
||
| 289 | $node = $rootFolder->getById($coverId)[0] ?? null; |
||
| 290 | if ($node instanceof File) { |
||
| 291 | $mime = $node->getMimeType(); |
||
| 292 | |||
| 293 | if (\strpos($mime, 'audio') === 0) { // embedded cover image |
||
| 294 | $cover = $this->extractor->parseEmbeddedCoverArt($node); // TODO: currently only album cover supported |
||
| 295 | |||
| 296 | if ($cover !== null) { |
||
| 297 | $response = ['mimetype' => $cover['image_mime'], 'content' => $cover['data']]; |
||
| 298 | } |
||
| 299 | } else { // separate image file |
||
| 300 | $response = ['mimetype' => $mime, 'content' => $node->getContent()]; |
||
| 301 | } |
||
| 302 | } |
||
| 303 | |||
| 304 | if ($response === null) { |
||
| 305 | $class = \get_class($entity); |
||
| 306 | $this->logger->error("Requested cover not found for $class entity {$entity->getId()}, coverId=$coverId"); |
||
| 307 | } |
||
| 308 | } |
||
| 309 | |||
| 310 | return $response; |
||
| 311 | } |
||
| 312 | |||
| 313 | /** |
||
| 314 | * Scale down images to reduce size and crop to square shape |
||
| 315 | * |
||
| 316 | * If one of the dimensions of the image is smaller than the maximum, then just |
||
| 317 | * crop to square shape but do not scale. |
||
| 318 | * @param array $image The image to be scaled down in format accepted by \OCA\Music\Http\FileResponse |
||
| 319 | * @param integer $maxSize The maximum size in pixels for the square shaped output |
||
| 320 | * @return array The processed image in format accepted by \OCA\Music\Http\FileResponse |
||
| 321 | */ |
||
| 322 | public function scaleDownAndCrop(array $image, int $maxSize) : array { |
||
| 323 | $meta = \getimagesizefromstring($image['content']); |
||
| 324 | |||
| 325 | if ($meta !== false) { |
||
| 326 | $srcWidth = $meta[0]; |
||
| 327 | $srcHeight = $meta[1]; |
||
| 328 | } else { |
||
| 329 | $srcWidth = $srcHeight = 0; |
||
| 330 | $this->logger->warning('Failed to extract size of the image, skip downscaling'); |
||
| 331 | } |
||
| 332 | |||
| 333 | // only process picture if it's larger than target size or not perfect square |
||
| 334 | if ($srcWidth > $maxSize || $srcHeight > $maxSize || $srcWidth != $srcHeight) { |
||
| 335 | $img = \imagecreatefromstring($image['content']); |
||
| 336 | |||
| 337 | if ($img === false) { |
||
| 338 | $this->logger->warning('Failed to open cover image for downscaling'); |
||
| 339 | } else { |
||
| 340 | $srcCropSize = \min($srcWidth, $srcHeight); |
||
| 341 | $srcX = (int)(($srcWidth - $srcCropSize) / 2); |
||
| 342 | $srcY = (int)(($srcHeight - $srcCropSize) / 2); |
||
| 343 | |||
| 344 | $dstSize = \min($maxSize, $srcCropSize); |
||
| 345 | $scaledImg = \imagecreatetruecolor($dstSize, $dstSize); |
||
| 346 | |||
| 347 | if ($scaledImg === false) { |
||
| 348 | $this->logger->warning("Failed to create scaled image of size $dstSize x $dstSize"); |
||
| 349 | \imagedestroy($img); |
||
| 350 | } else { |
||
| 351 | \imagecopyresampled($scaledImg, $img, 0, 0, $srcX, $srcY, $dstSize, $dstSize, $srcCropSize, $srcCropSize); |
||
| 352 | \imagedestroy($img); |
||
| 353 | |||
| 354 | \ob_start(); |
||
| 355 | \ob_clean(); |
||
| 356 | $image['mimetype'] = $meta['mime']; // override the supplied mime with the auto-detected one |
||
| 357 | switch ($image['mimetype']) { |
||
| 358 | case 'image/jpeg': |
||
| 359 | imagejpeg($scaledImg, null, 75); |
||
| 360 | $image['content'] = \ob_get_contents(); |
||
| 361 | break; |
||
| 362 | case 'image/png': |
||
| 363 | imagepng($scaledImg, null, 7, PNG_ALL_FILTERS); |
||
| 364 | $image['content'] = \ob_get_contents(); |
||
| 365 | break; |
||
| 366 | case 'image/gif': |
||
| 367 | imagegif($scaledImg, null); |
||
| 368 | $image['content'] = \ob_get_contents(); |
||
| 369 | break; |
||
| 370 | default: |
||
| 371 | $this->logger->warning("Cover image type {$image['mimetype']} not supported for downscaling"); |
||
| 372 | break; |
||
| 373 | } |
||
| 374 | \ob_end_clean(); |
||
| 375 | \imagedestroy($scaledImg); |
||
| 376 | } |
||
| 377 | } |
||
| 378 | } |
||
| 379 | return $image; |
||
| 380 | } |
||
| 381 | |||
| 382 | private function createMosaic(array $covers, ?int $size) : array { |
||
| 383 | $size = ($size > 0) ? $size : $this->coverSize; // DO_NOT_CROP_OR_SCALE handled here the same as null, i.e. default size |
||
| 384 | $pieceSize = $size/2; |
||
| 385 | $mosaicImg = \imagecreatetruecolor($size, $size); |
||
| 386 | if ($mosaicImg === false) { |
||
| 387 | $this->logger->warning("Failed to create mosaic image of size $size x $size"); |
||
| 388 | } |
||
| 389 | else { |
||
| 390 | $scaleAndCopyPiece = function($pieceData, $dstImage, $dstX, $dstY, $dstSize) { |
||
| 391 | $meta = \getimagesizefromstring($pieceData['content']); |
||
| 392 | $srcWidth = $meta[0]; |
||
| 393 | $srcHeight = $meta[1]; |
||
| 394 | |||
| 395 | $piece = imagecreatefromstring($pieceData['content']); |
||
| 396 | |||
| 397 | if ($piece === false) { |
||
| 398 | $this->logger->warning('Failed to open cover image to create a mosaic'); |
||
| 399 | } else { |
||
| 400 | \imagecopyresampled($dstImage, $piece, $dstX, $dstY, 0, 0, $dstSize, $dstSize, $srcWidth, $srcHeight); |
||
| 401 | \imagedestroy($piece); |
||
| 402 | } |
||
| 403 | }; |
||
| 404 | |||
| 405 | $coordinates = [ |
||
| 406 | ['x' => 0, 'y' => 0], // top-left |
||
| 407 | ['x' => $pieceSize, 'y' => $pieceSize], // bottom-right |
||
| 408 | ['x' => $pieceSize, 'y' => 0], // top-right |
||
| 409 | ['x' => 0, 'y' => $pieceSize], // bottom-left |
||
| 410 | ]; |
||
| 411 | |||
| 412 | $covers = \array_slice($covers, 0, 4); |
||
| 413 | foreach ($covers as $i => $cover) { |
||
| 414 | $scaleAndCopyPiece($cover, $mosaicImg, $coordinates[$i]['x'], $coordinates[$i]['y'], $pieceSize); |
||
| 415 | } |
||
| 416 | } |
||
| 417 | |||
| 418 | $image = ['mimetype' => 'image/png']; |
||
| 419 | \ob_start(); |
||
| 420 | \ob_clean(); |
||
| 421 | imagepng($mosaicImg, null, 7, PNG_ALL_FILTERS); |
||
| 422 | $image['content'] = \ob_get_contents(); |
||
| 423 | \ob_end_clean(); |
||
| 424 | \imagedestroy($mosaicImg); |
||
| 425 | |||
| 426 | return $image; |
||
| 427 | } |
||
| 428 | |||
| 429 | private static function autoDetectMime(string $imageContent) : ?string { |
||
| 432 | } |
||
| 433 | |||
| 434 | /** |
||
| 435 | * @throws \InvalidArgumentException if entity is not one of the expected types |
||
| 436 | */ |
||
| 437 | private static function getHashKey(Entity $entity) : string { |
||
| 446 | } |
||
| 447 | } |
||
| 448 | |||
| 449 | /** |
||
| 450 | * Create and store an access token which can be used to read cover images of a user. |
||
| 451 | * A user may have only one valid cover image access token at a time; the latest token |
||
| 452 | * always overwrites the previously obtained one. |
||
| 453 | * |
||
| 454 | * The reason this is needed is because the mediaSession in Firefox loads the cover images |
||
| 455 | * in a context where normal cookies and other standard request headers are not available. |
||
| 456 | * Hence, we need to provide the cover images as "public" resources, i.e. without requiring |
||
| 457 | * that the caller is logged in to the cloud. But still, we don't want to let just anyone |
||
| 458 | * load the user data. The solution is to use a temporary token which grants access just to |
||
| 459 | * the cover images. This token can be then sent as URL argument by the mediaSession. |
||
| 460 | */ |
||
| 461 | public function createAccessToken(string $userId) : string { |
||
| 462 | $token = Random::secure(32); |
||
| 463 | // It might be neater to use a dedicated DB table for this, but the generic cache table |
||
| 464 | // will do, at least for now. |
||
| 465 | $this->cache->set($userId, 'cover_access_token', $token); |
||
| 466 | return $token; |
||
| 467 | } |
||
| 468 | |||
| 469 | /** |
||
| 470 | * @see CoverService::createAccessToken |
||
| 471 | * @throws \OutOfBoundsException if the token is not valid |
||
| 472 | */ |
||
| 473 | public function getUserForAccessToken(?string $token) : string { |
||
| 482 | } |
||
| 483 | } |
||
| 484 |