1
0

BackgroundService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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(): void {
  200. $this->config->deleteUserValue($this->userId, Application::APP_ID, 'background_image');
  201. $this->config->deleteUserValue($this->userId, Application::APP_ID, 'background_color');
  202. $this->config->deleteUserValue($this->userId, Application::APP_ID, 'primary_color');
  203. }
  204. /**
  205. * @param $path
  206. * @throws NotFoundException
  207. * @throws NotPermittedException
  208. * @throws LockedException
  209. * @throws PreConditionNotMetException
  210. * @throws NoUserException
  211. */
  212. public function setFileBackground($path): void {
  213. if ($this->userId === null) {
  214. throw new RuntimeException('No currently logged-in user');
  215. }
  216. $userFolder = $this->rootFolder->getUserFolder($this->userId);
  217. /** @var File $file */
  218. $file = $userFolder->get($path);
  219. $image = new \OCP\Image();
  220. if ($image->loadFromFileHandle($file->fopen('r')) === false) {
  221. throw new InvalidArgumentException('Invalid image file');
  222. }
  223. $meanColor = $this->calculateMeanColor($image);
  224. if ($meanColor !== false) {
  225. $this->setColorBackground($meanColor);
  226. }
  227. $this->getAppDataFolder()->newFile('background.jpg', $file->fopen('r'));
  228. $this->config->setUserValue($this->userId, Application::APP_ID, 'background_image', self::BACKGROUND_CUSTOM);
  229. }
  230. public function setShippedBackground($fileName): void {
  231. if ($this->userId === null) {
  232. throw new RuntimeException('No currently logged-in user');
  233. }
  234. if (!array_key_exists($fileName, self::SHIPPED_BACKGROUNDS)) {
  235. throw new InvalidArgumentException('The given file name is invalid');
  236. }
  237. $this->setColorBackground(self::SHIPPED_BACKGROUNDS[$fileName]['background_color']);
  238. $this->config->setUserValue($this->userId, Application::APP_ID, 'background_image', $fileName);
  239. $this->config->setUserValue($this->userId, Application::APP_ID, 'primary_color', self::SHIPPED_BACKGROUNDS[$fileName]['primary_color']);
  240. }
  241. /**
  242. * Set the background to color only
  243. */
  244. public function setColorBackground(string $color): void {
  245. if ($this->userId === null) {
  246. throw new RuntimeException('No currently logged-in user');
  247. }
  248. if (!preg_match('/^#([0-9a-f]{3}|[0-9a-f]{6})$/i', $color)) {
  249. throw new InvalidArgumentException('The given color is invalid');
  250. }
  251. $this->config->setUserValue($this->userId, Application::APP_ID, 'background_color', $color);
  252. $this->config->setUserValue($this->userId, Application::APP_ID, 'background_image', self::BACKGROUND_COLOR);
  253. }
  254. public function deleteBackgroundImage(): void {
  255. if ($this->userId === null) {
  256. throw new RuntimeException('No currently logged-in user');
  257. }
  258. $this->config->setUserValue($this->userId, Application::APP_ID, 'background_image', self::BACKGROUND_COLOR);
  259. }
  260. public function getBackground(): ?ISimpleFile {
  261. $background = $this->config->getUserValue($this->userId, Application::APP_ID, 'background_image', self::BACKGROUND_DEFAULT);
  262. if ($background === self::BACKGROUND_CUSTOM) {
  263. try {
  264. return $this->getAppDataFolder()->getFile('background.jpg');
  265. } catch (NotFoundException | NotPermittedException $e) {
  266. return null;
  267. }
  268. }
  269. return null;
  270. }
  271. /**
  272. * Called when a new global background (backgroundMime) is uploaded (admin setting)
  273. * This sets all necessary app config values
  274. * @param resource|string $path
  275. * @return string|null The fallback background color - if any
  276. */
  277. public function setGlobalBackground($path): string|null {
  278. $image = new \OCP\Image();
  279. $handle = is_resource($path) ? $path : fopen($path, 'rb');
  280. if ($handle && $image->loadFromFileHandle($handle) !== false) {
  281. $meanColor = $this->calculateMeanColor($image);
  282. if ($meanColor !== false) {
  283. $this->config->setAppValue(Application::APP_ID, 'background_color', $meanColor);
  284. return $meanColor;
  285. }
  286. }
  287. return null;
  288. }
  289. /**
  290. * Calculate mean color of an given image
  291. * It only takes the upper part into account so that a matching text color can be derived for the app menu
  292. */
  293. private function calculateMeanColor(\OCP\Image $image): false|string {
  294. /**
  295. * Small helper to ensure one channel is returned as 8byte hex
  296. */
  297. function toHex(int $channel): string {
  298. $hex = dechex($channel);
  299. return match (strlen($hex)) {
  300. 0 => '00',
  301. 1 => '0'.$hex,
  302. 2 => $hex,
  303. default => 'ff',
  304. };
  305. }
  306. $tempImage = new \OCP\Image();
  307. // Crop to only analyze top bar
  308. $resource = $image->cropNew(0, 0, $image->width(), min(max(50, (int)($image->height() * 0.125)), $image->height()));
  309. if ($resource === false) {
  310. return false;
  311. }
  312. $tempImage->setResource($resource);
  313. if (!$tempImage->preciseResize(100, 7)) {
  314. return false;
  315. }
  316. $resource = $tempImage->resource();
  317. if ($resource === false) {
  318. return false;
  319. }
  320. $reds = [];
  321. $greens = [];
  322. $blues = [];
  323. for ($y = 0; $y < 7; $y++) {
  324. for ($x = 0; $x < 100; $x++) {
  325. $value = imagecolorat($resource, $x, $y);
  326. if ($value === false) {
  327. continue;
  328. }
  329. $reds[] = ($value >> 16) & 0xFF;
  330. $greens[] = ($value >> 8) & 0xFF;
  331. $blues[] = $value & 0xFF;
  332. }
  333. }
  334. $meanColor = '#' . toHex((int)(array_sum($reds) / count($reds)));
  335. $meanColor .= toHex((int)(array_sum($greens) / count($greens)));
  336. $meanColor .= toHex((int)(array_sum($blues) / count($blues)));
  337. return $meanColor;
  338. }
  339. /**
  340. * Storing the data in appdata/theming/users/USERID
  341. *
  342. * @return ISimpleFolder
  343. * @throws NotPermittedException
  344. */
  345. private function getAppDataFolder(): ISimpleFolder {
  346. try {
  347. $rootFolder = $this->appData->getFolder('users');
  348. } catch (NotFoundException $e) {
  349. $rootFolder = $this->appData->newFolder('users');
  350. }
  351. try {
  352. return $rootFolder->getFolder($this->userId);
  353. } catch (NotFoundException $e) {
  354. return $rootFolder->newFolder($this->userId);
  355. }
  356. }
  357. }