BackgroundService.php 15 KB

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