BackgroundService.php 14 KB

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