Passed
Push — master ( 7b8fea...bb5769 )
by Pauli
10:49
created

CoverHelper::getUserForAccessToken()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 6
nc 3
nop 1
dl 0
loc 9
rs 10
c 1
b 0
f 1
1
<?php declare(strict_types=1);
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;
21
use \OCP\Files\File;
22
23
use \OCP\IConfig;
24
25
use \Doctrine\DBAL\Exception\UniqueConstraintViolationException;
26
27
/**
28
 * utility to get cover image for album
29
 */
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) {
126
		$cached = $this->cache->get($userId, 'cover_' . $hash);
127
		if ($cached !== null) {
128
			$delimPos = \strpos($cached, '|');
129
			$mime = \substr($cached, 0, $delimPos);
130
			$content = \substr($cached, $delimPos + 1);
131
			if (!$asBase64) {
132
				$content = \base64_decode($content);
133
			}
134
			return ['mimetype' => $mime, 'content' => $content];
135
		}
136
		return null;
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) {
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) {
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
			} elseif ($size !== self::DO_NOT_CROP_OR_SCALE) {
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
			} else {
258
				$srcCropSize = \min($srcWidth, $srcHeight);
259
				$srcX = (int)(($srcWidth - $srcCropSize) / 2);
260
				$srcY = (int)(($srcHeight - $srcCropSize) / 2);
261
262
				$dstSize = \min($maxSize, $srcCropSize);
263
				$scaledImg = \imagecreatetruecolor($dstSize, $dstSize);
264
265
				if ($scaledImg === false) {
266
					$this->logger->log("Failed to create scaled image of size $dstSize x $dstSize", 'warning');
267
					\imagedestroy($img);
268
				} else {
269
					\imagecopyresampled($scaledImg, $img, 0, 0, $srcX, $srcY, $dstSize, $dstSize, $srcCropSize, $srcCropSize);
270
					\imagedestroy($img);
271
272
					\ob_start();
273
					\ob_clean();
274
					$mime = $meta['mime'];
275
					switch ($mime) {
276
						case 'image/jpeg':
277
							imagejpeg($scaledImg, null, 75);
278
							$image = \ob_get_contents();
279
							break;
280
						case 'image/png':
281
							imagepng($scaledImg, null, 7, PNG_ALL_FILTERS);
282
							$image = \ob_get_contents();
283
							break;
284
						case 'image/gif':
285
							imagegif($scaledImg, null);
286
							$image = \ob_get_contents();
287
							break;
288
						default:
289
							$this->logger->log("Cover image type $mime not supported for downscaling", 'warning');
290
							break;
291
					}
292
					\ob_end_clean();
293
					\imagedestroy($scaledImg);
294
				}
295
			}
296
		}
297
		return $image;
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) {
306
		if ($entity instanceof Album) {
307
			return 'album_cover_hash_' . $entity->getId();
308
		} elseif ($entity instanceof Artist) {
0 ignored issues
show
introduced by
$entity is always a sub-type of OCA\Music\Db\Artist.
Loading history...
309
			return 'artist_cover_hash_' . $entity->getId();
310
		} else {
311
			throw new \InvalidArgumentException('Unexpected entity type');
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 {
328
		$token = Random::secure(32);
329
		// It might be neater to use a dedicated DB table for this, but the generic cache table
330
		// will do, at least for now.
331
		$this->cache->set($userId, 'cover_access_token', $token);
332
		return $token;
333
	}
334
335
	/**
336
	 * @see CoverHelper::createAccessToken
337
	 * @throws \OutOfBoundsException if the token is not valid
338
	 */
339
	public function getUserForAccessToken(?string $token) : string {
340
		if ($token === null) {
341
			throw new \OutOfBoundsException('Cannot get user for a null token');
342
		}
343
		$userId = $this->cache->getOwner('cover_access_token', $token);
344
		if ($userId === null) {
345
			throw new \OutOfBoundsException('No userId found for the given token');
346
		}
347
		return $userId;
348
	}
349
}
350