| Total Complexity | 44 |
| Total Lines | 318 |
| Duplicated Lines | 0 % |
| Changes | 2 | ||
| Bugs | 0 | Features | 1 |
Complex classes like CoverHelper 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 CoverHelper, and based on these observations, apply Extract Interface, too.
| 1 | <?php declare(strict_types=1); |
||
| 30 | class CoverHelper { |
||
| 31 | private $extractor; |
||
| 32 | private $cache; |
||
| 33 | private $coverSize; |
||
| 34 | private $logger; |
||
| 35 | |||
| 36 | const MAX_SIZE_TO_CACHE = 102400; |
||
| 37 | const DO_NOT_CROP_OR_SCALE = -1; |
||
| 38 | |||
| 39 | public function __construct( |
||
| 40 | Extractor $extractor, |
||
| 41 | Cache $cache, |
||
| 42 | IConfig $config, |
||
| 43 | Logger $logger) { |
||
| 44 | $this->extractor = $extractor; |
||
| 45 | $this->cache = $cache; |
||
| 46 | $this->logger = $logger; |
||
| 47 | |||
| 48 | // Read the cover size to use from config.php or use the default |
||
| 49 | $this->coverSize = \intval($config->getSystemValue('music.cover_size')) ?: 380; |
||
| 50 | } |
||
| 51 | |||
| 52 | /** |
||
| 53 | * Get cover image of an album or and artist |
||
| 54 | * |
||
| 55 | * @param Album|Artist $entity |
||
| 56 | * @param string $userId |
||
| 57 | * @param Folder $rootFolder |
||
| 58 | * @param int|null $size Desired (max) image size, null to use the default. |
||
| 59 | * Special value DO_NOT_CROP_OR_SCALE can be used to opt out of |
||
| 60 | * scaling and cropping altogether. |
||
| 61 | * @return array|null Image data in format accepted by \OCA\Music\Http\FileResponse |
||
| 62 | */ |
||
| 63 | public function getCover($entity, string $userId, Folder $rootFolder, int $size=null) { |
||
| 64 | // Skip using cache in case the cover is requested in specific size |
||
| 65 | if ($size !== null) { |
||
| 66 | return $this->readCover($entity, $rootFolder, $size); |
||
| 67 | } else { |
||
| 68 | $dataAndHash = $this->getCoverAndHash($entity, $userId, $rootFolder); |
||
| 69 | return $dataAndHash['data']; |
||
| 70 | } |
||
| 71 | } |
||
| 72 | |||
| 73 | /** |
||
| 74 | * Get cover image of an album or and artist along with the image's hash |
||
| 75 | * |
||
| 76 | * The hash is non-null only in case the cover is/was cached. |
||
| 77 | * |
||
| 78 | * @param Album|Artist $entity |
||
| 79 | * @param string $userId |
||
| 80 | * @param Folder $rootFolder |
||
| 81 | * @return array Dictionary with keys 'data' and 'hash' |
||
| 82 | */ |
||
| 83 | public function getCoverAndHash($entity, string $userId, Folder $rootFolder) : array { |
||
| 84 | $hash = $this->cache->get($userId, self::getHashKey($entity)); |
||
| 85 | $data = null; |
||
| 86 | |||
| 87 | if ($hash !== null) { |
||
| 88 | $data = $this->getCoverFromCache($hash, $userId); |
||
| 89 | } |
||
| 90 | if ($data === null) { |
||
| 91 | $hash = null; |
||
| 92 | $data = $this->readCover($entity, $rootFolder, $this->coverSize); |
||
| 93 | if ($data !== null) { |
||
| 94 | $hash = $this->addCoverToCache($entity, $userId, $data); |
||
| 95 | } |
||
| 96 | } |
||
| 97 | |||
| 98 | return ['data' => $data, 'hash' => $hash]; |
||
| 99 | } |
||
| 100 | |||
| 101 | /** |
||
| 102 | * Get all album cover hashes for one user. |
||
| 103 | * @param string $userId |
||
| 104 | * @return array with album IDs as keys and hashes as values |
||
| 105 | */ |
||
| 106 | public function getAllCachedAlbumCoverHashes(string $userId) : array { |
||
| 107 | $rows = $this->cache->getAll($userId, 'album_cover_hash_'); |
||
| 108 | $hashes = []; |
||
| 109 | $prefixLen = \strlen('album_cover_hash_'); |
||
| 110 | foreach ($rows as $row) { |
||
| 111 | $albumId = \substr($row['key'], $prefixLen); |
||
| 112 | $hashes[$albumId] = $row['data']; |
||
| 113 | } |
||
| 114 | return $hashes; |
||
| 115 | } |
||
| 116 | |||
| 117 | /** |
||
| 118 | * Get cover image with given hash from the cache |
||
| 119 | * |
||
| 120 | * @param string $hash |
||
| 121 | * @param string $userId |
||
| 122 | * @param bool $asBase64 |
||
| 123 | * @return array|null Image data in format accepted by \OCA\Music\Http\FileResponse |
||
| 124 | */ |
||
| 125 | public function getCoverFromCache(string $hash, string $userId, bool $asBase64 = false) { |
||
| 137 | } |
||
| 138 | |||
| 139 | /** |
||
| 140 | * Cache the given cover image data |
||
| 141 | * @param Album|Artist $entity |
||
| 142 | * @param string $userId |
||
| 143 | * @param array $coverData |
||
| 144 | * @return string|null Hash of the cached cover |
||
| 145 | */ |
||
| 146 | private function addCoverToCache($entity, string $userId, array $coverData) { |
||
| 147 | $mime = $coverData['mimetype']; |
||
| 148 | $content = $coverData['content']; |
||
| 149 | $hash = null; |
||
| 150 | $hashKey = self::getHashKey($entity); |
||
| 151 | |||
| 152 | if ($mime && $content) { |
||
| 153 | $size = \strlen($content); |
||
| 154 | if ($size < self::MAX_SIZE_TO_CACHE) { |
||
| 155 | $hash = \hash('md5', $content); |
||
| 156 | // cache the data with hash as a key |
||
| 157 | try { |
||
| 158 | $this->cache->add($userId, 'cover_' . $hash, $mime . '|' . \base64_encode($content)); |
||
| 159 | } catch (UniqueConstraintViolationException $ex) { |
||
| 160 | $this->logger->log("Cover with hash $hash is already cached", 'debug'); |
||
| 161 | } |
||
| 162 | // cache the hash with hashKey as a key |
||
| 163 | try { |
||
| 164 | $this->cache->add($userId, $hashKey, $hash); |
||
| 165 | } catch (UniqueConstraintViolationException $ex) { |
||
| 166 | $this->logger->log("Cover hash with key $hashKey is already cached", 'debug'); |
||
| 167 | } |
||
| 168 | // collection.json needs to be regenrated the next time it's fetched |
||
| 169 | $this->cache->remove($userId, 'collection'); |
||
| 170 | } else { |
||
| 171 | $this->logger->log("Cover image of entity with key $hashKey is large ($size B), skip caching", 'debug'); |
||
| 172 | } |
||
| 173 | } |
||
| 174 | |||
| 175 | return $hash; |
||
| 176 | } |
||
| 177 | |||
| 178 | /** |
||
| 179 | * Remove album cover image from cache if it is there. Silently do nothing if there |
||
| 180 | * is no cached cover. All users are targeted if no $userId passed. |
||
| 181 | */ |
||
| 182 | public function removeAlbumCoverFromCache(int $albumId, string $userId=null) { |
||
| 183 | $this->cache->remove($userId, 'album_cover_hash_' . $albumId); |
||
| 184 | } |
||
| 185 | |||
| 186 | /** |
||
| 187 | * Remove artist cover image from cache if it is there. Silently do nothing if there |
||
| 188 | * is no cached cover. All users are targeted if no $userId passed. |
||
| 189 | */ |
||
| 190 | public function removeArtistCoverFromCache(int $artistId, string $userId=null) { |
||
| 191 | $this->cache->remove($userId, 'artist_cover_hash_' . $artistId); |
||
| 192 | } |
||
| 193 | |||
| 194 | /** |
||
| 195 | * Read cover image from the file system |
||
| 196 | * @param Album|Artist $entity |
||
| 197 | * @param Folder $rootFolder |
||
| 198 | * @param int $size Maximum size for the image to read, larger images are scaled down. |
||
| 199 | * Special value DO_NOT_CROP_OR_SCALE can be used to opt out of |
||
| 200 | * scaling and cropping altogether. |
||
| 201 | * @return array|null Image data in format accepted by \OCA\Music\Http\FileResponse |
||
| 202 | */ |
||
| 203 | private function readCover($entity, Folder $rootFolder, int $size) { |
||
| 235 | } |
||
| 236 | |||
| 237 | /** |
||
| 238 | * Scale down images to reduce size and crop to square shape |
||
| 239 | * |
||
| 240 | * If one of the dimensions of the image is smaller than the maximum, then just |
||
| 241 | * crop to square shape but do not scale. |
||
| 242 | * @param string $image The image to be scaled down as string |
||
| 243 | * @param integer $maxSize The maximum size in pixels for the square shaped output |
||
| 244 | * @return string The processed image as string |
||
| 245 | */ |
||
| 246 | public function scaleDownAndCrop($image, $maxSize) { |
||
| 298 | } |
||
| 299 | |||
| 300 | /** |
||
| 301 | * @param Album|Artist $entity |
||
| 302 | * @throws \InvalidArgumentException if entity is not one of the expected types |
||
| 303 | * @return string |
||
| 304 | */ |
||
| 305 | private static function getHashKey($entity) { |
||
| 312 | } |
||
| 313 | } |
||
| 314 | |||
| 315 | /** |
||
| 316 | * Create and store an access token which can be used to read cover images of a user. |
||
| 317 | * A user may have only one valid cover image access token at a time; the latest token |
||
| 318 | * always overwrites the previously obtained one. |
||
| 319 | * |
||
| 320 | * The reason this is needed is because the mediaSession in Firefox loads the cover images |
||
| 321 | * in a context where normal cookies and other standard request headers are not available. |
||
| 322 | * Hence, we need to provide the cover images as "public" resources, i.e. without requiring |
||
| 323 | * that the caller is logged in to the cloud. But still, we don't want to let just anyone |
||
| 324 | * load the user data. The solution is to use a temporary token which grants access just to |
||
| 325 | * the cover images. This token can be then sent as URL argument by the mediaSession. |
||
| 326 | */ |
||
| 327 | public function createAccessToken(string $userId) : string { |
||
| 333 | } |
||
| 334 | |||
| 335 | /** |
||
| 336 | * @see CoverHelper::createAccessToken |
||
| 337 | * @throws \OutOfBoundsException if the token is not valid |
||
| 338 | */ |
||
| 339 | public function getUserForAccessToken(?string $token) : string { |
||
| 350 |