BackgroundService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Theming\Service;
  8. use InvalidArgumentException;
  9. use OC\User\NoUserException;
  10. use OCA\Theming\AppInfo\Application;
  11. use OCP\Files\File;
  12. use OCP\Files\IAppData;
  13. use OCP\Files\IRootFolder;
  14. use OCP\Files\NotFoundException;
  15. use OCP\Files\NotPermittedException;
  16. use OCP\Files\SimpleFS\ISimpleFile;
  17. use OCP\Files\SimpleFS\ISimpleFolder;
  18. use OCP\IAppConfig;
  19. use OCP\IConfig;
  20. use OCP\Image;
  21. use OCP\Lock\LockedException;
  22. use OCP\PreConditionNotMetException;
  23. use RuntimeException;
  24. class BackgroundService {
  25. public const DEFAULT_COLOR = '#00679e';
  26. public const DEFAULT_BACKGROUND_COLOR = '#00679e';
  27. /**
  28. * One of our shipped background images is used
  29. */
  30. public const BACKGROUND_SHIPPED = 'shipped';
  31. /**
  32. * A custom background image is used
  33. */
  34. public const BACKGROUND_CUSTOM = 'custom';
  35. /**
  36. * The default background image is used
  37. */
  38. public const BACKGROUND_DEFAULT = 'default';
  39. /**
  40. * Just a background color is used
  41. */
  42. public const BACKGROUND_COLOR = 'color';
  43. public const DEFAULT_BACKGROUND_IMAGE = 'jenna-kim-the-globe.webp';
  44. /**
  45. * 'attribution': Name, artist and license
  46. * 'description': Alternative text
  47. * 'attribution_url': URL for attribution
  48. * 'background_color': Cached mean color of the top part to calculate app menu colors and use as fallback
  49. * 'primary_color': Recommended primary color for this theme / image
  50. */
  51. public const SHIPPED_BACKGROUNDS = [
  52. 'jenna-kim-the-globe.webp' => [
  53. 'attribution' => 'Globe (Jenna Kim - Nextcloud GmbH, CC-BY-SA-4.0)',
  54. 'description' => 'Background picture of white clouds on in front of a blue sky',
  55. 'attribution_url' => 'https://nextcloud.com/trademarks/',
  56. 'dark_variant' => 'jenna-kim-the-globe-dark.webp',
  57. 'background_color' => self::DEFAULT_BACKGROUND_COLOR,
  58. 'primary_color' => self::DEFAULT_COLOR,
  59. ],
  60. 'kamil-porembinski-clouds.jpg' => [
  61. 'attribution' => 'Clouds (Kamil Porembiński, CC BY-SA)',
  62. 'description' => 'Background picture of white clouds on in front of a blue sky',
  63. 'attribution_url' => 'https://www.flickr.com/photos/paszczak000/8715851521/',
  64. 'background_color' => self::DEFAULT_BACKGROUND_COLOR,
  65. 'primary_color' => self::DEFAULT_COLOR,
  66. ],
  67. 'hannah-maclean-soft-floral.jpg' => [
  68. 'attribution' => 'Soft floral (Hannah MacLean, CC0)',
  69. 'description' => 'Abstract background picture in yellow and white color whith a flower on it',
  70. 'attribution_url' => 'https://stocksnap.io/photo/soft-floral-XOYWCCW5PA',
  71. 'background_color' => '#e4d2c1',
  72. 'primary_color' => '#9f652f',
  73. ],
  74. 'ted-moravec-morning-fog.jpg' => [
  75. 'attribution' => 'Morning fog (Ted Moravec, Public Domain)',
  76. 'description' => 'Background picture of a forest shrouded in fog',
  77. 'attribution_url' => 'https://flickr.com/photos/tmoravec/52392410261',
  78. 'background_color' => '#f6f7f6',
  79. 'primary_color' => '#114c3b',
  80. ],
  81. 'stefanus-martanto-setyo-husodo-underwater-ocean.jpg' => [
  82. 'attribution' => 'Underwater ocean (Stefanus Martanto Setyo Husodo, CC0)',
  83. 'description' => 'Background picture of an underwater ocean',
  84. 'attribution_url' => 'https://stocksnap.io/photo/underwater-ocean-TJA9LBH4WS',
  85. 'background_color' => '#003351',
  86. 'primary_color' => '#04577e',
  87. ],
  88. 'zoltan-voros-rhythm-and-blues.jpg' => [
  89. 'attribution' => 'Rhythm and blues (Zoltán Vörös, CC BY)',
  90. 'description' => 'Abstract background picture of sand dunes during night',
  91. 'attribution_url' => 'https://flickr.com/photos/v923z/51634409289/',
  92. 'background_color' => '#1c2437',
  93. 'primary_color' => '#1c243c',
  94. ],
  95. 'anatoly-mikhaltsov-butterfly-wing-scale.jpg' => [
  96. 'attribution' => 'Butterfly wing scale (Anatoly Mikhaltsov, CC BY-SA)',
  97. 'description' => 'Background picture of a red-ish butterfly wing under microscope',
  98. 'attribution_url' => 'https://commons.wikimedia.org/wiki/File:%D0%A7%D0%B5%D1%88%D1%83%D0%B9%D0%BA%D0%B8_%D0%BA%D1%80%D1%8B%D0%BB%D0%B0_%D0%B1%D0%B0%D0%B1%D0%BE%D1%87%D0%BA%D0%B8.jpg',
  99. 'background_color' => '#652e11',
  100. 'primary_color' => '#a53c17',
  101. ],
  102. 'bernie-cetonia-aurata-take-off-composition.jpg' => [
  103. 'attribution' => 'Cetonia aurata take off composition (Bernie, Public Domain)',
  104. 'description' => 'Montage of a cetonia aurata bug that takes off with white background',
  105. 'attribution_url' => 'https://commons.wikimedia.org/wiki/File:Cetonia_aurata_take_off_composition_05172009.jpg',
  106. 'background_color' => '#dee0d3',
  107. 'primary_color' => '#56633d',
  108. ],
  109. 'dejan-krsmanovic-ribbed-red-metal.jpg' => [
  110. 'attribution' => 'Ribbed red metal (Dejan Krsmanovic, CC BY)',
  111. 'description' => 'Abstract background picture of red ribbed metal with two horizontal white elements on top of it',
  112. 'attribution_url' => 'https://www.flickr.com/photos/dejankrsmanovic/42971456774/',
  113. 'background_color' => '#9b171c',
  114. 'primary_color' => '#9c4236',
  115. ],
  116. 'eduardo-neves-pedra-azul.jpg' => [
  117. 'attribution' => 'Pedra azul milky way (Eduardo Neves, CC BY-SA)',
  118. 'description' => 'Background picture of the milky way during night with a mountain in front of it',
  119. 'attribution_url' => 'https://commons.wikimedia.org/wiki/File:Pedra_Azul_Milky_Way.jpg',
  120. 'background_color' => '#1d242d',
  121. 'primary_color' => '#4f6071',
  122. ],
  123. 'european-space-agency-barents-bloom.jpg' => [
  124. 'attribution' => 'Barents bloom (European Space Agency, CC BY-SA)',
  125. 'description' => 'Abstract background picture of blooming barents in blue and green colors',
  126. 'attribution_url' => 'https://www.esa.int/ESA_Multimedia/Images/2016/08/Barents_bloom',
  127. 'background_color' => '#1c383d',
  128. 'primary_color' => '#396475',
  129. ],
  130. 'hannes-fritz-flippity-floppity.jpg' => [
  131. 'attribution' => 'Flippity floppity (Hannes Fritz, CC BY-SA)',
  132. 'description' => 'Abstract background picture of many pairs of flip flops hanging on a wall in multiple colors',
  133. 'attribution_url' => 'http://hannes.photos/flippity-floppity',
  134. 'background_color' => '#5b2d53',
  135. 'primary_color' => '#98415a',
  136. ],
  137. 'hannes-fritz-roulette.jpg' => [
  138. 'attribution' => 'Roulette (Hannes Fritz, CC BY-SA)',
  139. 'description' => 'Background picture of a rotating giant wheel during night',
  140. 'attribution_url' => 'http://hannes.photos/roulette',
  141. 'background_color' => '#000000',
  142. 'primary_color' => '#845334',
  143. ],
  144. 'hannes-fritz-sea-spray.jpg' => [
  145. 'attribution' => 'Sea spray (Hannes Fritz, CC BY-SA)',
  146. 'description' => 'Background picture of a stone coast with fog and sea behind it',
  147. 'attribution_url' => 'http://hannes.photos/sea-spray',
  148. 'background_color' => '#333f47',
  149. 'primary_color' => '#4f6071',
  150. ],
  151. 'bernard-spragg-new-zealand-fern.jpg' => [
  152. 'attribution' => 'New zealand fern (Bernard Spragg, CC0)',
  153. 'description' => 'Abstract background picture of fern leafes',
  154. 'attribution_url' => 'https://commons.wikimedia.org/wiki/File:NZ_Fern.(Blechnum_chambersii)_(11263534936).jpg',
  155. 'background_color' => '#0c3c03',
  156. 'primary_color' => '#316b26',
  157. ],
  158. 'rawpixel-pink-tapioca-bubbles.jpg' => [
  159. 'attribution' => 'Pink tapioca bubbles (Rawpixel, CC BY)',
  160. 'description' => 'Abstract background picture of pink tapioca bubbles',
  161. 'attribution_url' => 'https://www.flickr.com/photos/byrawpixel/27665140298/in/photostream/',
  162. 'background_color' => '#c56e95',
  163. 'primary_color' => '#7b4e7e',
  164. ],
  165. 'nasa-waxing-crescent-moon.jpg' => [
  166. 'attribution' => 'Waxing crescent moon (NASA, Public Domain)',
  167. 'description' => 'Background picture of glowing earth in foreground and moon in the background',
  168. 'attribution_url' => 'https://www.nasa.gov/image-feature/a-waxing-crescent-moon',
  169. 'background_color' => '#000002',
  170. 'primary_color' => '#005ac1',
  171. ],
  172. 'tommy-chau-already.jpg' => [
  173. 'attribution' => 'Cityscape (Tommy Chau, CC BY)',
  174. 'description' => 'Background picture of a skyscraper city during night',
  175. 'attribution_url' => 'https://www.flickr.com/photos/90975693@N05/16910999368',
  176. 'background_color' => '#35229f',
  177. 'primary_color' => '#6a2af4',
  178. ],
  179. 'tommy-chau-lion-rock-hill.jpg' => [
  180. 'attribution' => 'Lion rock hill (Tommy Chau, CC BY)',
  181. 'description' => 'Background picture of mountains during sunset or sunrise',
  182. 'attribution_url' => 'https://www.flickr.com/photos/90975693@N05/17136440246',
  183. 'background_color' => '#cb92b7',
  184. 'primary_color' => '#7f4f70',
  185. ],
  186. 'lali-masriera-yellow-bricks.jpg' => [
  187. 'attribution' => 'Yellow bricks (Lali Masriera, CC BY)',
  188. 'description' => 'Background picture of yellow bricks with some yellow tubes',
  189. 'attribution_url' => 'https://www.flickr.com/photos/visualpanic/3982464447',
  190. 'background_color' => '#c78a19',
  191. 'primary_color' => '#7f5700',
  192. ],
  193. ];
  194. public function __construct(
  195. private IRootFolder $rootFolder,
  196. private IAppData $appData,
  197. private IAppConfig $appConfig,
  198. private IConfig $config,
  199. private ?string $userId,
  200. ) {
  201. }
  202. public function setDefaultBackground(?string $userId = null): void {
  203. $userId = $userId ?? $this->getUserId();
  204. $this->config->deleteUserValue($userId, Application::APP_ID, 'background_image');
  205. $this->config->deleteUserValue($userId, Application::APP_ID, 'background_color');
  206. $this->config->deleteUserValue($userId, Application::APP_ID, 'primary_color');
  207. }
  208. /**
  209. * @param $path
  210. * @throws NotFoundException
  211. * @throws NotPermittedException
  212. * @throws LockedException
  213. * @throws PreConditionNotMetException
  214. * @throws NoUserException
  215. */
  216. public function setFileBackground(string $path, ?string $userId = null): void {
  217. $userId = $userId ?? $this->getUserId();
  218. $userFolder = $this->rootFolder->getUserFolder($userId);
  219. /** @var File $file */
  220. $file = $userFolder->get($path);
  221. $handle = $file->fopen('r');
  222. if ($handle === false) {
  223. throw new InvalidArgumentException('Invalid image file');
  224. }
  225. $this->getAppDataFolder()->newFile('background.jpg', $handle);
  226. $this->recalculateMeanColor();
  227. }
  228. public function recalculateMeanColor(?string $userId = null): void {
  229. $userId = $userId ?? $this->getUserId();
  230. $image = new Image();
  231. $handle = $this->getAppDataFolder($userId)->getFile('background.jpg')->read();
  232. if ($handle === false || $image->loadFromFileHandle($handle) === false) {
  233. throw new InvalidArgumentException('Invalid image file');
  234. }
  235. $meanColor = $this->calculateMeanColor($image);
  236. if ($meanColor !== false) {
  237. $this->setColorBackground($meanColor);
  238. }
  239. $this->config->setUserValue($userId, Application::APP_ID, 'background_image', self::BACKGROUND_CUSTOM);
  240. }
  241. /**
  242. * Set background of user to a shipped background identified by the filename
  243. * @param string $filename The shipped background filename
  244. * @param null|string $userId The user to set - defaults to currently logged in user
  245. * @throws RuntimeException If neither $userId is specified nor a user is logged in
  246. * @throws InvalidArgumentException If the specified filename does not match any shipped background
  247. */
  248. public function setShippedBackground(string $filename, ?string $userId = null): void {
  249. $userId = $userId ?? $this->getUserId();
  250. if (!array_key_exists($filename, self::SHIPPED_BACKGROUNDS)) {
  251. throw new InvalidArgumentException('The given file name is invalid');
  252. }
  253. $this->setColorBackground(self::SHIPPED_BACKGROUNDS[$filename]['background_color'], $userId);
  254. $this->config->setUserValue($userId, Application::APP_ID, 'background_image', $filename);
  255. $this->config->setUserValue($userId, Application::APP_ID, 'primary_color', self::SHIPPED_BACKGROUNDS[$filename]['primary_color']);
  256. }
  257. /**
  258. * Set the background to color only
  259. * @param string|null $userId The user to set the color - default to current logged-in user
  260. */
  261. public function setColorBackground(string $color, ?string $userId = null): void {
  262. $userId = $userId ?? $this->getUserId();
  263. if (!preg_match('/^#([0-9a-f]{3}|[0-9a-f]{6})$/i', $color)) {
  264. throw new InvalidArgumentException('The given color is invalid');
  265. }
  266. $this->config->setUserValue($userId, Application::APP_ID, 'background_color', $color);
  267. $this->config->setUserValue($userId, Application::APP_ID, 'background_image', self::BACKGROUND_COLOR);
  268. }
  269. public function deleteBackgroundImage(?string $userId = null): void {
  270. $userId = $userId ?? $this->getUserId();
  271. $this->config->setUserValue($userId, Application::APP_ID, 'background_image', self::BACKGROUND_COLOR);
  272. }
  273. public function getBackground(?string $userId = null): ?ISimpleFile {
  274. $userId = $userId ?? $this->getUserId();
  275. $background = $this->config->getUserValue($userId, Application::APP_ID, 'background_image', self::BACKGROUND_DEFAULT);
  276. if ($background === self::BACKGROUND_CUSTOM) {
  277. try {
  278. return $this->getAppDataFolder()->getFile('background.jpg');
  279. } catch (NotFoundException|NotPermittedException $e) {
  280. return null;
  281. }
  282. }
  283. return null;
  284. }
  285. /**
  286. * Called when a new global background (backgroundMime) is uploaded (admin setting)
  287. * This sets all necessary app config values
  288. * @param resource|string $path
  289. * @return string|null The fallback background color - if any
  290. */
  291. public function setGlobalBackground($path): ?string {
  292. $image = new Image();
  293. $handle = is_resource($path) ? $path : fopen($path, 'rb');
  294. if ($handle && $image->loadFromFileHandle($handle) !== false) {
  295. $meanColor = $this->calculateMeanColor($image);
  296. if ($meanColor !== false) {
  297. $this->appConfig->setValueString(Application::APP_ID, 'background_color', $meanColor);
  298. return $meanColor;
  299. }
  300. }
  301. return null;
  302. }
  303. /**
  304. * Calculate mean color of an given image
  305. * It only takes the upper part into account so that a matching text color can be derived for the app menu
  306. */
  307. private function calculateMeanColor(Image $image): false|string {
  308. /**
  309. * Small helper to ensure one channel is returned as 8byte hex
  310. */
  311. function toHex(int $channel): string {
  312. $hex = dechex($channel);
  313. return match (strlen($hex)) {
  314. 0 => '00',
  315. 1 => '0' . $hex,
  316. 2 => $hex,
  317. default => 'ff',
  318. };
  319. }
  320. $tempImage = new Image();
  321. // Crop to only analyze top bar
  322. $resource = $image->cropNew(0, 0, $image->width(), min(max(50, (int)($image->height() * 0.125)), $image->height()));
  323. if ($resource === false) {
  324. return false;
  325. }
  326. $tempImage->setResource($resource);
  327. if (!$tempImage->preciseResize(100, 7)) {
  328. return false;
  329. }
  330. $resource = $tempImage->resource();
  331. if ($resource === false) {
  332. return false;
  333. }
  334. $reds = [];
  335. $greens = [];
  336. $blues = [];
  337. for ($y = 0; $y < 7; $y++) {
  338. for ($x = 0; $x < 100; $x++) {
  339. $value = imagecolorat($resource, $x, $y);
  340. if ($value === false) {
  341. continue;
  342. }
  343. $reds[] = ($value >> 16) & 0xFF;
  344. $greens[] = ($value >> 8) & 0xFF;
  345. $blues[] = $value & 0xFF;
  346. }
  347. }
  348. $meanColor = '#' . toHex((int)(array_sum($reds) / count($reds)));
  349. $meanColor .= toHex((int)(array_sum($greens) / count($greens)));
  350. $meanColor .= toHex((int)(array_sum($blues) / count($blues)));
  351. return $meanColor;
  352. }
  353. /**
  354. * Storing the data in appdata/theming/users/USERID
  355. *
  356. * @param string|null $userId The user to get the folder - default to current user
  357. * @throws NotPermittedException
  358. */
  359. private function getAppDataFolder(?string $userId = null): ISimpleFolder {
  360. $userId = $userId ?? $this->getUserId();
  361. try {
  362. $rootFolder = $this->appData->getFolder('users');
  363. } catch (NotFoundException) {
  364. $rootFolder = $this->appData->newFolder('users');
  365. }
  366. try {
  367. return $rootFolder->getFolder($userId);
  368. } catch (NotFoundException) {
  369. return $rootFolder->newFolder($userId);
  370. }
  371. }
  372. /**
  373. * @throws RuntimeException Thrown if a method that needs a user is called without any logged-in user
  374. */
  375. private function getUserId(): string {
  376. if ($this->userId === null) {
  377. throw new RuntimeException('No currently logged-in user');
  378. }
  379. return $this->userId;
  380. }
  381. }