1
0

MigrateBackgroundImages.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Theming\Jobs;
  8. use OCA\Theming\AppInfo\Application;
  9. use OCP\AppFramework\Utility\ITimeFactory;
  10. use OCP\BackgroundJob\IJobList;
  11. use OCP\BackgroundJob\QueuedJob;
  12. use OCP\DB\QueryBuilder\IQueryBuilder;
  13. use OCP\Files\AppData\IAppDataFactory;
  14. use OCP\Files\IAppData;
  15. use OCP\Files\NotFoundException;
  16. use OCP\Files\NotPermittedException;
  17. use OCP\Files\SimpleFS\ISimpleFolder;
  18. use OCP\IDBConnection;
  19. use Psr\Log\LoggerInterface;
  20. class MigrateBackgroundImages extends QueuedJob {
  21. public const TIME_SENSITIVE = 0;
  22. public const STAGE_PREPARE = 'prepare';
  23. public const STAGE_EXECUTE = 'execute';
  24. // will be saved in appdata/theming/global/
  25. protected const STATE_FILE_NAME = '25_dashboard_to_theming_migration_users.json';
  26. public function __construct(
  27. ITimeFactory $time,
  28. private IAppDataFactory $appDataFactory,
  29. private IJobList $jobList,
  30. private IDBConnection $dbc,
  31. private IAppData $appData,
  32. private LoggerInterface $logger,
  33. ) {
  34. parent::__construct($time);
  35. }
  36. protected function run(mixed $argument): void {
  37. if (!is_array($argument) || !isset($argument['stage'])) {
  38. throw new \Exception('Job ' . self::class . ' called with wrong argument');
  39. }
  40. switch ($argument['stage']) {
  41. case self::STAGE_PREPARE:
  42. $this->runPreparation();
  43. break;
  44. case self::STAGE_EXECUTE:
  45. $this->runMigration();
  46. break;
  47. default:
  48. break;
  49. }
  50. }
  51. protected function runPreparation(): void {
  52. try {
  53. $selector = $this->dbc->getQueryBuilder();
  54. $result = $selector->select('userid')
  55. ->from('preferences')
  56. ->where($selector->expr()->eq('appid', $selector->createNamedParameter('theming')))
  57. ->andWhere($selector->expr()->eq('configkey', $selector->createNamedParameter('background')))
  58. ->andWhere($selector->expr()->eq('configvalue', $selector->createNamedParameter('custom', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
  59. ->executeQuery();
  60. $userIds = $result->fetchAll(\PDO::FETCH_COLUMN);
  61. $this->storeUserIdsToProcess($userIds);
  62. } catch (\Throwable $t) {
  63. $this->jobList->add(self::class, ['stage' => self::STAGE_PREPARE]);
  64. throw $t;
  65. }
  66. $this->jobList->add(self::class, ['stage' => self::STAGE_EXECUTE]);
  67. }
  68. /**
  69. * @throws NotPermittedException
  70. * @throws NotFoundException
  71. */
  72. protected function runMigration(): void {
  73. $allUserIds = $this->readUserIdsToProcess();
  74. $notSoFastMode = count($allUserIds) > 5000;
  75. $dashboardData = $this->appDataFactory->get('dashboard');
  76. $userIds = $notSoFastMode ? array_slice($allUserIds, 0, 5000) : $allUserIds;
  77. foreach ($userIds as $userId) {
  78. try {
  79. // migration
  80. $file = $dashboardData->getFolder($userId)->getFile('background.jpg');
  81. $targetDir = $this->getUserFolder($userId);
  82. if (!$targetDir->fileExists('background.jpg')) {
  83. $targetDir->newFile('background.jpg', $file->getContent());
  84. }
  85. $file->delete();
  86. } catch (NotFoundException|NotPermittedException $e) {
  87. }
  88. }
  89. if ($notSoFastMode) {
  90. $remainingUserIds = array_slice($allUserIds, 5000);
  91. $this->storeUserIdsToProcess($remainingUserIds);
  92. $this->jobList->add(self::class, ['stage' => self::STAGE_EXECUTE]);
  93. } else {
  94. $this->deleteStateFile();
  95. }
  96. }
  97. /**
  98. * @throws NotPermittedException
  99. * @throws NotFoundException
  100. */
  101. protected function readUserIdsToProcess(): array {
  102. $globalFolder = $this->appData->getFolder('global');
  103. if ($globalFolder->fileExists(self::STATE_FILE_NAME)) {
  104. $file = $globalFolder->getFile(self::STATE_FILE_NAME);
  105. try {
  106. $userIds = \json_decode($file->getContent(), true);
  107. } catch (NotFoundException $e) {
  108. $userIds = [];
  109. }
  110. if ($userIds === null) {
  111. $userIds = [];
  112. }
  113. } else {
  114. $userIds = [];
  115. }
  116. return $userIds;
  117. }
  118. /**
  119. * @throws NotFoundException
  120. */
  121. protected function storeUserIdsToProcess(array $userIds): void {
  122. $storableUserIds = \json_encode($userIds);
  123. $globalFolder = $this->appData->getFolder('global');
  124. try {
  125. if ($globalFolder->fileExists(self::STATE_FILE_NAME)) {
  126. $file = $globalFolder->getFile(self::STATE_FILE_NAME);
  127. } else {
  128. $file = $globalFolder->newFile(self::STATE_FILE_NAME);
  129. }
  130. $file->putContent($storableUserIds);
  131. } catch (NotFoundException $e) {
  132. } catch (NotPermittedException $e) {
  133. $this->logger->warning('Lacking permissions to create {file}',
  134. [
  135. 'app' => 'theming',
  136. 'file' => self::STATE_FILE_NAME,
  137. 'exception' => $e,
  138. ]
  139. );
  140. }
  141. }
  142. /**
  143. * @throws NotFoundException
  144. */
  145. protected function deleteStateFile(): void {
  146. $globalFolder = $this->appData->getFolder('global');
  147. if ($globalFolder->fileExists(self::STATE_FILE_NAME)) {
  148. $file = $globalFolder->getFile(self::STATE_FILE_NAME);
  149. try {
  150. $file->delete();
  151. } catch (NotPermittedException $e) {
  152. $this->logger->info('Could not delete {file} due to permissions. It is safe to delete manually inside data -> appdata -> theming -> global.',
  153. [
  154. 'app' => 'theming',
  155. 'file' => $file->getName(),
  156. 'exception' => $e,
  157. ]
  158. );
  159. }
  160. }
  161. }
  162. /**
  163. * Get the root location for users theming data
  164. */
  165. protected function getUserFolder(string $userId): ISimpleFolder {
  166. $themingData = $this->appDataFactory->get(Application::APP_ID);
  167. try {
  168. $rootFolder = $themingData->getFolder('users');
  169. } catch (NotFoundException $e) {
  170. $rootFolder = $themingData->newFolder('users');
  171. }
  172. try {
  173. return $rootFolder->getFolder($userId);
  174. } catch (NotFoundException $e) {
  175. return $rootFolder->newFolder($userId);
  176. }
  177. }
  178. }