Passed
Push — master ( de702b...3e9331 )
by Pauli
02:18
created

CoverHelper   A

Complexity

Total Complexity 38

Size/Duplication

Total Lines 276
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 124
dl 0
loc 276
ccs 0
cts 122
cp 0
rs 9.36
c 4
b 0
f 0
wmc 38

11 Methods

Rating   Name   Duplication   Size   Complexity  
A getCoverFromCache() 0 12 3
A readCover() 0 32 6
B addCoverToCache() 0 30 6
A removeAlbumCoverFromCache() 0 2 1
B scaleDownAndCrop() 0 47 8
A getCover() 0 7 2
A getHashKey() 0 7 3
A getAllCachedAlbumCoverHashes() 0 8 2
A getCoverAndHash() 0 16 4
A __construct() 0 11 2
A removeArtistCoverFromCache() 0 2 1
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 2017 - 2020
11
 */
12
13
namespace OCA\Music\Utility;
14
15
use \OCA\Music\AppFramework\Core\Logger;
16
use \OCA\Music\Db\Album;
17
use \OCA\Music\Db\Artist;
18
use \OCA\Music\Db\Cache;
19
20
use \OCP\Files\Folder;
0 ignored issues
show
Bug introduced by
The type OCP\Files\Folder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
21
use \OCP\Files\File;
0 ignored issues
show
Bug introduced by
The type OCP\Files\File was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
22
23
use \OCP\IConfig;
0 ignored issues
show
Bug introduced by
The type OCP\IConfig was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
24
25
use \Doctrine\DBAL\Exception\UniqueConstraintViolationException;
0 ignored issues
show
Bug introduced by
The type Doctrine\DBAL\Exception\...raintViolationException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
26
use Doctrine\Instantiator\Exception\InvalidArgumentException;
27
28
/**
29
 * utility to get cover image for album
30
 */
31
class CoverHelper {
32
	private $extractor;
33
	private $cache;
34
	private $coverSize;
35
	private $logger;
36
37
	const MAX_SIZE_TO_CACHE = 102400;
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 Entity $entity Album or Artist
0 ignored issues
show
Bug introduced by
The type OCA\Music\Utility\Entity was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
56
	 * @param string $userId
57
	 * @param Folder $rootFolder
58
	 * @param int|null $size
59
	 * @return array|null Image data in format accepted by \OCA\Music\Http\FileResponse
60
	 */
61
	public function getCover($entity, $userId, $rootFolder, $size=null) {
62
		// Skip using cache in case the cover is requested in specific size
63
		if ($size) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $size of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
64
			return $this->readCover($entity, $userId, $rootFolder, $size);
65
		} else {
66
			$dataAndHash = $this->getCoverAndHash($entity, $userId, $rootFolder);
67
			return $dataAndHash['data'];
68
		}
69
	}
70
71
	/**
72
	 * Get cover image of an album or and artist along with the image's hash
73
	 * 
74
	 * The hash is non-null only in case the cover is/was cached.
75
	 *
76
	 * @param Entity $entity Album or Artist
77
	 * @param string $userId
78
	 * @param Folder $rootFolder
79
	 * @return array Dictionary with keys 'data' and 'hash'
80
	 */
81
	public function getCoverAndHash($entity, $userId, $rootFolder) {
82
		$hash = $this->cache->get($userId, self::getHashKey($entity));
83
		$data = null;
84
85
		if ($hash !== null) {
86
			$data = $this->getCoverFromCache($hash, $userId);
87
		}
88
		if ($data === null) {
89
			$hash = null;
90
			$data = $this->readCover($entity, $userId, $rootFolder, $this->coverSize);
91
			if ($data !== null) {
92
				$hash = $this->addCoverToCache($entity, $userId, $data);
93
			}
94
		}
95
96
		return ['data' => $data, 'hash' => $hash];
97
	}
98
99
	/**
100
	 * Get all album cover hashes for one user.
101
	 * @param string $userId
102
	 * @return array with album IDs as keys and hashes as values
103
	 */
104
	public function getAllCachedAlbumCoverHashes($userId) {
105
		$rows = $this->cache->getAll($userId, 'album_cover_hash_');
106
		$hashes = [];
107
		foreach ($rows as $row) {
108
			$albumId = \explode('_', $row['key'])[1];
109
			$hashes[$albumId] = $row['data'];
110
		}
111
		return $hashes;
112
	}
113
114
	/**
115
	 * Get cover image with given hash from the cache
116
	 *
117
	 * @param string $hash
118
	 * @param string $userId
119
	 * @param bool $asBase64
120
	 * @return array|null Image data in format accepted by \OCA\Music\Http\FileResponse
121
	 */
122
	public function getCoverFromCache($hash, $userId, $asBase64 = false) {
123
		$cached = $this->cache->get($userId, 'cover_' . $hash);
124
		if ($cached !== null) {
125
			$delimPos = \strpos($cached, '|');
126
			$mime = \substr($cached, 0, $delimPos);
127
			$content = \substr($cached, $delimPos + 1);
128
			if (!$asBase64) {
129
				$content = \base64_decode($content);
130
			}
131
			return ['mimetype' => $mime, 'content' => $content];
132
		}
133
		return null;
134
	}
135
136
	/**
137
	 * Cache the given cover image data
138
	 * @param Entity $entity Album or Artist
139
	 * @param string $userId
140
	 * @param array $coverData
141
	 * @return string|null Hash of the cached cover
142
	 */
143
	private function addCoverToCache($entity, $userId, $coverData) {
144
		$mime = $coverData['mimetype'];
145
		$content = $coverData['content'];
146
		$hash = null;
147
		$hashKey = self::getHashKey($entity);
148
149
		if ($mime && $content) {
150
			$size = \strlen($content);
151
			if ($size < self::MAX_SIZE_TO_CACHE) {
152
				$hash = \hash('md5', $content);
153
				// cache the data with hash as a key
154
				try {
155
					$this->cache->add($userId, 'cover_' . $hash, $mime . '|' . \base64_encode($content));
156
				} catch (UniqueConstraintViolationException $ex) {
157
					$this->logger->log("Cover with hash $hash is already cached", 'debug');
158
				}
159
				// cache the hash with hashKey as a key
160
				try {
161
					$this->cache->add($userId, $hashKey, $hash);
162
				} catch (UniqueConstraintViolationException $ex) {
163
					$this->logger->log("Cover hash with key $hashKey is already cached", 'debug');
164
				}
165
				// collection.json needs to be regenrated the next time it's fetched
166
				$this->cache->remove($userId, 'collection');
167
			} else {
168
				$this->logger->log("Cover image of entity with key $hashKey is large ($size B), skip caching", 'debug');
169
			}
170
		}
171
172
		return $hash;
173
	}
174
175
	/**
176
	 * Remove album cover image from cache if it is there. Silently do nothing if there
177
	 * is no cached cover.
178
	 * @param int $albumId
179
	 * @param string $userId
180
	 */
181
	public function removeAlbumCoverFromCache($albumId, $userId) {
182
		$this->cache->remove($userId, 'album_cover_hash_' . $albumId);
183
	}
184
185
	/**
186
	 * Remove artist cover image from cache if it is there. Silently do nothing if there
187
	 * is no cached cover.
188
	 * @param int $artistId
189
	 * @param string $userId
190
	 */
191
	public function removeArtistCoverFromCache($artistId, $userId) {
192
		$this->cache->remove($userId, 'artist_cover_hash_' . $artistId);
193
	}
194
195
	/**
196
	 * Read cover image from the file system
197
	 * @param Enity $entity Album or Artist entity
0 ignored issues
show
Bug introduced by
The type OCA\Music\Utility\Enity was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
198
	 * @param string $userId
199
	 * @param Folder $rootFolder
200
	 * @param int $size Maximum size for the image to read, larger images are scaled down
201
	 * @return array|null Image data in format accepted by \OCA\Music\Http\FileResponse
202
	 */
203
	private function readCover($entity, $userId, $rootFolder, $size) {
0 ignored issues
show
Unused Code introduced by
The parameter $userId is not used and could be removed. ( Ignorable by Annotation )

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

203
	private function readCover($entity, /** @scrutinizer ignore-unused */ $userId, $rootFolder, $size) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
204
		$response = null;
205
		$coverId = $entity->getCoverFileId();
206
207
		if ($coverId > 0) {
208
			$nodes = $rootFolder->getById($coverId);
209
			if (\count($nodes) > 0) {
210
				// get the first valid node (there shouldn't be more than one node anyway)
211
				/* @var $node File */
212
				$node = $nodes[0];
213
				$mime = $node->getMimeType();
214
215
				if (\strpos($mime, 'audio') === 0) { // embedded cover image
216
					$cover = $this->extractor->parseEmbeddedCoverArt($node); // TODO: currently only album cover supported
217
218
					if ($cover !== null) {
0 ignored issues
show
introduced by
The condition $cover !== null is always true.
Loading history...
219
						$response = ['mimetype' => $cover['image_mime'], 'content' => $cover['data']];
220
					}
221
				} else { // separate image file
222
					$response = ['mimetype' => $mime, 'content' => $node->getContent()];
223
				}
224
			}
225
226
			if ($response === null) {
227
				$class = \get_class($entity);
228
				$this->logger->log("Requested cover not found for $class entity {$entity->getId()}, coverId=$coverId", 'error');
229
			} else {
230
				$response['content'] = $this->scaleDownAndCrop($response['content'], $size);
231
			}
232
		}
233
234
		return $response;
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) {
247
		$meta = \getimagesizefromstring($image);
248
		$srcWidth = $meta[0];
249
		$srcHeight = $meta[1];
250
251
		// only process picture if it's larger than target size or not perfect square
252
		if ($srcWidth > $maxSize || $srcHeight > $maxSize || $srcWidth != $srcHeight) {
253
			$img = imagecreatefromstring($image);
254
255
			if ($img === false) {
256
				$this->logger->log('Failed to open cover image for downscaling', 'warning');
257
			}
258
			else {
259
				$srcCropSize = \min($srcWidth, $srcHeight);
260
				$srcX = ($srcWidth - $srcCropSize) / 2;
261
				$srcY = ($srcHeight - $srcCropSize) / 2;
262
263
				$dstSize = \min($maxSize, $srcCropSize);
264
				$scaledImg = \imagecreatetruecolor($dstSize, $dstSize);
265
				\imagecopyresampled($scaledImg, $img, 0, 0, $srcX, $srcY, $dstSize, $dstSize, $srcCropSize, $srcCropSize);
0 ignored issues
show
Bug introduced by
It seems like $scaledImg can also be of type false; however, parameter $dst_image of imagecopyresampled() does only seem to accept resource, 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

265
				\imagecopyresampled(/** @scrutinizer ignore-type */ $scaledImg, $img, 0, 0, $srcX, $srcY, $dstSize, $dstSize, $srcCropSize, $srcCropSize);
Loading history...
266
				\imagedestroy($img);
267
268
				\ob_start();
269
				\ob_clean();
270
				$mime = $meta['mime'];
271
				switch ($mime) {
272
					case 'image/jpeg':
273
						imagejpeg($scaledImg, null, 75);
0 ignored issues
show
Bug introduced by
It seems like $scaledImg can also be of type false; however, parameter $image of imagejpeg() does only seem to accept resource, 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

273
						imagejpeg(/** @scrutinizer ignore-type */ $scaledImg, null, 75);
Loading history...
274
						$image = \ob_get_contents();
275
						break;
276
					case 'image/png':
277
						imagepng($scaledImg, null, 7, PNG_ALL_FILTERS);
0 ignored issues
show
Bug introduced by
It seems like $scaledImg can also be of type false; however, parameter $image of imagepng() does only seem to accept resource, 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

277
						imagepng(/** @scrutinizer ignore-type */ $scaledImg, null, 7, PNG_ALL_FILTERS);
Loading history...
278
						$image = \ob_get_contents();
279
						break;
280
					case 'image/gif':
281
						imagegif($scaledImg, null);
0 ignored issues
show
Bug introduced by
It seems like $scaledImg can also be of type false; however, parameter $image of imagegif() does only seem to accept resource, 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

281
						imagegif(/** @scrutinizer ignore-type */ $scaledImg, null);
Loading history...
282
						$image = \ob_get_contents();
283
						break;
284
					default:
285
						$this->logger->log("Cover image type $mime not supported for downscaling", 'warning');
286
						break;
287
				}
288
				\ob_end_clean();
289
				\imagedestroy($scaledImg);
0 ignored issues
show
Bug introduced by
It seems like $scaledImg can also be of type false; however, parameter $image of imagedestroy() does only seem to accept resource, 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

289
				\imagedestroy(/** @scrutinizer ignore-type */ $scaledImg);
Loading history...
290
			}
291
		}
292
		return $image;
293
	}
294
295
	/**
296
	 * @param Entity $entity An Album or Artist entity
297
	 * @throws InvalidArgumentException if entity is not one of the expected types
298
	 * @return string
299
	 */
300
	private static function getHashKey($entity) {
301
		if ($entity instanceof Album) {
302
			return 'album_cover_hash_' . $entity->getId();
303
		} elseif ($entity instanceof Artist) {
304
			return 'artist_cover_hash_' . $entity->getId();
305
		} else {
306
			throw new \InvalidArgumentException('Unexpected entity type');
307
		}
308
	}
309
}
310