BackgroundService.php 16 KB

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