BackgroundService.php 16 KB

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