MigrateBackgroundImages.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2022 Arthur Schiwon <blizzz@arthur-schiwon.de>
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OCA\Theming\Jobs;
  25. use OCA\Theming\AppInfo\Application;
  26. use OCP\AppFramework\Utility\ITimeFactory;
  27. use OCP\BackgroundJob\IJobList;
  28. use OCP\BackgroundJob\QueuedJob;
  29. use OCP\DB\QueryBuilder\IQueryBuilder;
  30. use OCP\Files\AppData\IAppDataFactory;
  31. use OCP\Files\IAppData;
  32. use OCP\Files\NotFoundException;
  33. use OCP\Files\NotPermittedException;
  34. use OCP\Files\SimpleFS\ISimpleFolder;
  35. use OCP\IDBConnection;
  36. use Psr\Log\LoggerInterface;
  37. class MigrateBackgroundImages extends QueuedJob {
  38. public const TIME_SENSITIVE = 0;
  39. public const STAGE_PREPARE = 'prepare';
  40. public const STAGE_EXECUTE = 'execute';
  41. // will be saved in appdata/theming/global/
  42. protected const STATE_FILE_NAME = '25_dashboard_to_theming_migration_users.json';
  43. private IAppDataFactory $appDataFactory;
  44. private IJobList $jobList;
  45. private IDBConnection $dbc;
  46. private IAppData $appData;
  47. private LoggerInterface $logger;
  48. public function __construct(
  49. ITimeFactory $time,
  50. IAppDataFactory $appDataFactory,
  51. IJobList $jobList,
  52. IDBConnection $dbc,
  53. IAppData $appData,
  54. LoggerInterface $logger
  55. ) {
  56. parent::__construct($time);
  57. $this->appDataFactory = $appDataFactory;
  58. $this->jobList = $jobList;
  59. $this->dbc = $dbc;
  60. $this->appData = $appData;
  61. $this->logger = $logger;
  62. }
  63. protected function run($argument): void {
  64. if (!is_array($argument) || !isset($argument['stage'])) {
  65. throw new \Exception('Job '.self::class.' called with wrong argument');
  66. }
  67. switch ($argument['stage']) {
  68. case self::STAGE_PREPARE:
  69. $this->runPreparation();
  70. break;
  71. case self::STAGE_EXECUTE:
  72. $this->runMigration();
  73. break;
  74. default:
  75. break;
  76. }
  77. }
  78. protected function runPreparation(): void {
  79. try {
  80. $selector = $this->dbc->getQueryBuilder();
  81. $result = $selector->select('userid')
  82. ->from('preferences')
  83. ->where($selector->expr()->eq('appid', $selector->createNamedParameter('theming')))
  84. ->andWhere($selector->expr()->eq('configkey', $selector->createNamedParameter('background')))
  85. ->andWhere($selector->expr()->eq('configvalue', $selector->createNamedParameter('custom', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
  86. ->executeQuery();
  87. $userIds = $result->fetchAll(\PDO::FETCH_COLUMN);
  88. $this->storeUserIdsToProcess($userIds);
  89. } catch (\Throwable $t) {
  90. $this->jobList->add(self::class, ['stage' => self::STAGE_PREPARE]);
  91. throw $t;
  92. }
  93. $this->jobList->add(self::class, ['stage' => self::STAGE_EXECUTE]);
  94. }
  95. /**
  96. * @throws NotPermittedException
  97. * @throws NotFoundException
  98. */
  99. protected function runMigration(): void {
  100. $allUserIds = $this->readUserIdsToProcess();
  101. $notSoFastMode = count($allUserIds) > 5000;
  102. $dashboardData = $this->appDataFactory->get('dashboard');
  103. $userIds = $notSoFastMode ? array_slice($allUserIds, 0, 5000) : $allUserIds;
  104. foreach ($userIds as $userId) {
  105. try {
  106. // migration
  107. $file = $dashboardData->getFolder($userId)->getFile('background.jpg');
  108. $targetDir = $this->getUserFolder($userId);
  109. if (!$targetDir->fileExists('background.jpg')) {
  110. $targetDir->newFile('background.jpg', $file->getContent());
  111. }
  112. $file->delete();
  113. } catch (NotFoundException|NotPermittedException $e) {
  114. }
  115. }
  116. if ($notSoFastMode) {
  117. $remainingUserIds = array_slice($allUserIds, 5000);
  118. $this->storeUserIdsToProcess($remainingUserIds);
  119. $this->jobList->add(self::class, ['stage' => self::STAGE_EXECUTE]);
  120. } else {
  121. $this->deleteStateFile();
  122. }
  123. }
  124. /**
  125. * @throws NotPermittedException
  126. * @throws NotFoundException
  127. */
  128. protected function readUserIdsToProcess(): array {
  129. $globalFolder = $this->appData->getFolder('global');
  130. if ($globalFolder->fileExists(self::STATE_FILE_NAME)) {
  131. $file = $globalFolder->getFile(self::STATE_FILE_NAME);
  132. try {
  133. $userIds = \json_decode($file->getContent(), true);
  134. } catch (NotFoundException $e) {
  135. $userIds = [];
  136. }
  137. if ($userIds === null) {
  138. $userIds = [];
  139. }
  140. } else {
  141. $userIds = [];
  142. }
  143. return $userIds;
  144. }
  145. /**
  146. * @throws NotFoundException
  147. */
  148. protected function storeUserIdsToProcess(array $userIds): void {
  149. $storableUserIds = \json_encode($userIds);
  150. $globalFolder = $this->appData->getFolder('global');
  151. try {
  152. if ($globalFolder->fileExists(self::STATE_FILE_NAME)) {
  153. $file = $globalFolder->getFile(self::STATE_FILE_NAME);
  154. } else {
  155. $file = $globalFolder->newFile(self::STATE_FILE_NAME);
  156. }
  157. $file->putContent($storableUserIds);
  158. } catch (NotFoundException $e) {
  159. } catch (NotPermittedException $e) {
  160. $this->logger->warning('Lacking permissions to create {file}',
  161. [
  162. 'app' => 'theming',
  163. 'file' => self::STATE_FILE_NAME,
  164. 'exception' => $e,
  165. ]
  166. );
  167. }
  168. }
  169. /**
  170. * @throws NotFoundException
  171. */
  172. protected function deleteStateFile(): void {
  173. $globalFolder = $this->appData->getFolder('global');
  174. if ($globalFolder->fileExists(self::STATE_FILE_NAME)) {
  175. $file = $globalFolder->getFile(self::STATE_FILE_NAME);
  176. try {
  177. $file->delete();
  178. } catch (NotPermittedException $e) {
  179. $this->logger->info('Could not delete {file} due to permissions. It is safe to delete manually inside data -> appdata -> theming -> global.',
  180. [
  181. 'app' => 'theming',
  182. 'file' => $file->getName(),
  183. 'exception' => $e,
  184. ]
  185. );
  186. }
  187. }
  188. }
  189. /**
  190. * Get the root location for users theming data
  191. */
  192. protected function getUserFolder(string $userId): ISimpleFolder {
  193. $themingData = $this->appDataFactory->get(Application::APP_ID);
  194. try {
  195. $rootFolder = $themingData->getFolder('users');
  196. } catch (NotFoundException $e) {
  197. $rootFolder = $themingData->newFolder('users');
  198. }
  199. try {
  200. return $rootFolder->getFolder($userId);
  201. } catch (NotFoundException $e) {
  202. return $rootFolder->newFolder($userId);
  203. }
  204. }
  205. }