1
0

TaskProcessingApiController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Core\Controller;
  8. use OC\Core\ResponseDefinitions;
  9. use OC\Files\SimpleFS\SimpleFile;
  10. use OCP\AppFramework\Http;
  11. use OCP\AppFramework\Http\Attribute\AnonRateLimit;
  12. use OCP\AppFramework\Http\Attribute\ApiRoute;
  13. use OCP\AppFramework\Http\Attribute\ExAppRequired;
  14. use OCP\AppFramework\Http\Attribute\NoAdminRequired;
  15. use OCP\AppFramework\Http\Attribute\PublicPage;
  16. use OCP\AppFramework\Http\Attribute\UserRateLimit;
  17. use OCP\AppFramework\Http\DataDownloadResponse;
  18. use OCP\AppFramework\Http\DataResponse;
  19. use OCP\Files\File;
  20. use OCP\Files\GenericFileException;
  21. use OCP\Files\IAppData;
  22. use OCP\Files\IRootFolder;
  23. use OCP\Files\NotPermittedException;
  24. use OCP\IL10N;
  25. use OCP\IRequest;
  26. use OCP\Lock\LockedException;
  27. use OCP\TaskProcessing\EShapeType;
  28. use OCP\TaskProcessing\Exception\Exception;
  29. use OCP\TaskProcessing\Exception\NotFoundException;
  30. use OCP\TaskProcessing\Exception\PreConditionNotMetException;
  31. use OCP\TaskProcessing\Exception\UnauthorizedException;
  32. use OCP\TaskProcessing\Exception\ValidationException;
  33. use OCP\TaskProcessing\IManager;
  34. use OCP\TaskProcessing\ShapeEnumValue;
  35. use OCP\TaskProcessing\Task;
  36. use RuntimeException;
  37. /**
  38. * @psalm-import-type CoreTaskProcessingTask from ResponseDefinitions
  39. * @psalm-import-type CoreTaskProcessingTaskType from ResponseDefinitions
  40. */
  41. class TaskProcessingApiController extends \OCP\AppFramework\OCSController {
  42. public function __construct(
  43. string $appName,
  44. IRequest $request,
  45. private IManager $taskProcessingManager,
  46. private IL10N $l,
  47. private ?string $userId,
  48. private IRootFolder $rootFolder,
  49. private IAppData $appData,
  50. ) {
  51. parent::__construct($appName, $request);
  52. }
  53. /**
  54. * Returns all available TaskProcessing task types
  55. *
  56. * @return DataResponse<Http::STATUS_OK, array{types: array<string, CoreTaskProcessingTaskType>}, array{}>
  57. *
  58. * 200: Task types returned
  59. */
  60. #[PublicPage]
  61. #[ApiRoute(verb: 'GET', url: '/tasktypes', root: '/taskprocessing')]
  62. public function taskTypes(): DataResponse {
  63. $taskTypes = array_map(function (array $tt) {
  64. $tt['inputShape'] = array_map(function ($descriptor) {
  65. return $descriptor->jsonSerialize();
  66. }, $tt['inputShape']);
  67. $tt['outputShape'] = array_map(function ($descriptor) {
  68. return $descriptor->jsonSerialize();
  69. }, $tt['outputShape']);
  70. $tt['optionalInputShape'] = array_map(function ($descriptor) {
  71. return $descriptor->jsonSerialize();
  72. }, $tt['optionalInputShape']);
  73. $tt['optionalOutputShape'] = array_map(function ($descriptor) {
  74. return $descriptor->jsonSerialize();
  75. }, $tt['optionalOutputShape']);
  76. $tt['inputShapeEnumValues'] = array_map(function (array $enumValues) {
  77. return array_map(fn (ShapeEnumValue $enumValue) => $enumValue->jsonSerialize(), $enumValues);
  78. }, $tt['inputShapeEnumValues']);
  79. $tt['optionalInputShapeEnumValues'] = array_map(function (array $enumValues) {
  80. return array_map(fn (ShapeEnumValue $enumValue) => $enumValue->jsonSerialize(), $enumValues);
  81. }, $tt['optionalInputShapeEnumValues']);
  82. $tt['outputShapeEnumValues'] = array_map(function (array $enumValues) {
  83. return array_map(fn (ShapeEnumValue $enumValue) => $enumValue->jsonSerialize(), $enumValues);
  84. }, $tt['outputShapeEnumValues']);
  85. $tt['optionalOutputShapeEnumValues'] = array_map(function (array $enumValues) {
  86. return array_map(fn (ShapeEnumValue $enumValue) => $enumValue->jsonSerialize(), $enumValues);
  87. }, $tt['optionalOutputShapeEnumValues']);
  88. return $tt;
  89. }, $this->taskProcessingManager->getAvailableTaskTypes());
  90. return new DataResponse([
  91. 'types' => $taskTypes,
  92. ]);
  93. }
  94. /**
  95. * Schedules a task
  96. *
  97. * @param array<string, mixed> $input Task's input parameters
  98. * @param string $type Type of the task
  99. * @param string $appId ID of the app that will execute the task
  100. * @param string $customId An arbitrary identifier for the task
  101. * @param string|null $webhookUri URI to be requested when the task finishes
  102. * @param string|null $webhookMethod Method used for the webhook request (HTTP:GET, HTTP:POST, HTTP:PUT, HTTP:DELETE or AppAPI:APP_ID:GET, AppAPI:APP_ID:POST...)
  103. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_BAD_REQUEST|Http::STATUS_PRECONDITION_FAILED|Http::STATUS_UNAUTHORIZED, array{message: string}, array{}>
  104. *
  105. * 200: Task scheduled successfully
  106. * 400: Scheduling task is not possible
  107. * 412: Scheduling task is not possible
  108. * 401: Cannot schedule task because it references files in its input that the user doesn't have access to
  109. */
  110. #[PublicPage]
  111. #[UserRateLimit(limit: 20, period: 120)]
  112. #[AnonRateLimit(limit: 5, period: 120)]
  113. #[ApiRoute(verb: 'POST', url: '/schedule', root: '/taskprocessing')]
  114. public function schedule(
  115. array $input, string $type, string $appId, string $customId = '',
  116. ?string $webhookUri = null, ?string $webhookMethod = null,
  117. ): DataResponse {
  118. $task = new Task($type, $input, $appId, $this->userId, $customId);
  119. $task->setWebhookUri($webhookUri);
  120. $task->setWebhookMethod($webhookMethod);
  121. try {
  122. $this->taskProcessingManager->scheduleTask($task);
  123. /** @var CoreTaskProcessingTask $json */
  124. $json = $task->jsonSerialize();
  125. return new DataResponse([
  126. 'task' => $json,
  127. ]);
  128. } catch (PreConditionNotMetException) {
  129. return new DataResponse(['message' => $this->l->t('The given provider is not available')], Http::STATUS_PRECONDITION_FAILED);
  130. } catch (ValidationException $e) {
  131. return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
  132. } catch (UnauthorizedException) {
  133. return new DataResponse(['message' => 'User does not have access to the files mentioned in the task input'], Http::STATUS_UNAUTHORIZED);
  134. } catch (Exception) {
  135. return new DataResponse(['message' => 'Internal server error'], Http::STATUS_INTERNAL_SERVER_ERROR);
  136. }
  137. }
  138. /**
  139. * Gets a task including status and result
  140. *
  141. * Tasks are removed 1 week after receiving their last update
  142. *
  143. * @param int $id The id of the task
  144. *
  145. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_NOT_FOUND|Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  146. *
  147. * 200: Task returned
  148. * 404: Task not found
  149. */
  150. #[PublicPage]
  151. #[ApiRoute(verb: 'GET', url: '/task/{id}', root: '/taskprocessing')]
  152. public function getTask(int $id): DataResponse {
  153. try {
  154. $task = $this->taskProcessingManager->getUserTask($id, $this->userId);
  155. /** @var CoreTaskProcessingTask $json */
  156. $json = $task->jsonSerialize();
  157. return new DataResponse([
  158. 'task' => $json,
  159. ]);
  160. } catch (NotFoundException) {
  161. return new DataResponse(['message' => $this->l->t('Task not found')], Http::STATUS_NOT_FOUND);
  162. } catch (RuntimeException) {
  163. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  164. }
  165. }
  166. /**
  167. * Deletes a task
  168. *
  169. * @param int $id The id of the task
  170. *
  171. * @return DataResponse<Http::STATUS_OK, null, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  172. *
  173. * 200: Task deleted
  174. */
  175. #[NoAdminRequired]
  176. #[ApiRoute(verb: 'DELETE', url: '/task/{id}', root: '/taskprocessing')]
  177. public function deleteTask(int $id): DataResponse {
  178. try {
  179. $task = $this->taskProcessingManager->getUserTask($id, $this->userId);
  180. $this->taskProcessingManager->deleteTask($task);
  181. return new DataResponse(null);
  182. } catch (NotFoundException) {
  183. return new DataResponse(null);
  184. } catch (Exception) {
  185. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  186. }
  187. }
  188. /**
  189. * Returns tasks for the current user filtered by the appId and optional customId
  190. *
  191. * @param string $appId ID of the app
  192. * @param string|null $customId An arbitrary identifier for the task
  193. * @return DataResponse<Http::STATUS_OK, array{tasks: CoreTaskProcessingTask[]}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  194. *
  195. * 200: Tasks returned
  196. */
  197. #[NoAdminRequired]
  198. #[ApiRoute(verb: 'GET', url: '/tasks/app/{appId}', root: '/taskprocessing')]
  199. public function listTasksByApp(string $appId, ?string $customId = null): DataResponse {
  200. try {
  201. $tasks = $this->taskProcessingManager->getUserTasksByApp($this->userId, $appId, $customId);
  202. /** @var CoreTaskProcessingTask[] $json */
  203. $json = array_map(static function (Task $task) {
  204. return $task->jsonSerialize();
  205. }, $tasks);
  206. return new DataResponse([
  207. 'tasks' => $json,
  208. ]);
  209. } catch (Exception) {
  210. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  211. }
  212. }
  213. /**
  214. * Returns tasks for the current user filtered by the optional taskType and optional customId
  215. *
  216. * @param string|null $taskType The task type to filter by
  217. * @param string|null $customId An arbitrary identifier for the task
  218. * @return DataResponse<Http::STATUS_OK, array{tasks: CoreTaskProcessingTask[]}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  219. *
  220. * 200: Tasks returned
  221. */
  222. #[NoAdminRequired]
  223. #[ApiRoute(verb: 'GET', url: '/tasks', root: '/taskprocessing')]
  224. public function listTasks(?string $taskType, ?string $customId = null): DataResponse {
  225. try {
  226. $tasks = $this->taskProcessingManager->getUserTasks($this->userId, $taskType, $customId);
  227. /** @var CoreTaskProcessingTask[] $json */
  228. $json = array_map(static function (Task $task) {
  229. return $task->jsonSerialize();
  230. }, $tasks);
  231. return new DataResponse([
  232. 'tasks' => $json,
  233. ]);
  234. } catch (Exception) {
  235. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  236. }
  237. }
  238. /**
  239. * Returns the contents of a file referenced in a task
  240. *
  241. * @param int $taskId The id of the task
  242. * @param int $fileId The file id of the file to retrieve
  243. * @return DataDownloadResponse<Http::STATUS_OK, string, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  244. *
  245. * 200: File content returned
  246. * 404: Task or file not found
  247. */
  248. #[NoAdminRequired]
  249. #[Http\Attribute\NoCSRFRequired]
  250. #[ApiRoute(verb: 'GET', url: '/tasks/{taskId}/file/{fileId}', root: '/taskprocessing')]
  251. public function getFileContents(int $taskId, int $fileId): Http\DataDownloadResponse|DataResponse {
  252. try {
  253. $task = $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  254. return $this->getFileContentsInternal($task, $fileId);
  255. } catch (NotFoundException) {
  256. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  257. } catch (Exception) {
  258. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  259. }
  260. }
  261. /**
  262. * Returns the contents of a file referenced in a task(ExApp route version)
  263. *
  264. * @param int $taskId The id of the task
  265. * @param int $fileId The file id of the file to retrieve
  266. * @return DataDownloadResponse<Http::STATUS_OK, string, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  267. *
  268. * 200: File content returned
  269. * 404: Task or file not found
  270. */
  271. #[ExAppRequired]
  272. #[ApiRoute(verb: 'GET', url: '/tasks_provider/{taskId}/file/{fileId}', root: '/taskprocessing')]
  273. public function getFileContentsExApp(int $taskId, int $fileId): Http\DataDownloadResponse|DataResponse {
  274. try {
  275. $task = $this->taskProcessingManager->getTask($taskId);
  276. return $this->getFileContentsInternal($task, $fileId);
  277. } catch (NotFoundException) {
  278. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  279. } catch (Exception) {
  280. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  281. }
  282. }
  283. /**
  284. * Upload a file so it can be referenced in a task result (ExApp route version)
  285. *
  286. * Use field 'file' for the file upload
  287. *
  288. * @param int $taskId The id of the task
  289. * @return DataResponse<Http::STATUS_CREATED, array{fileId: int}, array{}>|DataResponse<Http::STATUS_BAD_REQUEST|Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  290. *
  291. * 201: File created
  292. * 400: File upload failed or no file was uploaded
  293. * 404: Task not found
  294. */
  295. #[ExAppRequired]
  296. #[ApiRoute(verb: 'POST', url: '/tasks_provider/{taskId}/file', root: '/taskprocessing')]
  297. public function setFileContentsExApp(int $taskId): DataResponse {
  298. try {
  299. $task = $this->taskProcessingManager->getTask($taskId);
  300. $file = $this->request->getUploadedFile('file');
  301. if (!isset($file['tmp_name'])) {
  302. return new DataResponse(['message' => $this->l->t('Bad request')], Http::STATUS_BAD_REQUEST);
  303. }
  304. $handle = fopen($file['tmp_name'], 'r');
  305. if (!$handle) {
  306. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  307. }
  308. $fileId = $this->setFileContentsInternal($handle);
  309. return new DataResponse(['fileId' => $fileId], Http::STATUS_CREATED);
  310. } catch (NotFoundException) {
  311. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  312. } catch (Exception) {
  313. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  314. }
  315. }
  316. /**
  317. * @throws NotPermittedException
  318. * @throws NotFoundException
  319. * @throws GenericFileException
  320. * @throws LockedException
  321. *
  322. * @return DataDownloadResponse<Http::STATUS_OK, string, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  323. */
  324. private function getFileContentsInternal(Task $task, int $fileId): Http\DataDownloadResponse|DataResponse {
  325. $ids = $this->extractFileIdsFromTask($task);
  326. if (!in_array($fileId, $ids)) {
  327. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  328. }
  329. $node = $this->rootFolder->getFirstNodeById($fileId);
  330. if ($node === null) {
  331. $node = $this->rootFolder->getFirstNodeByIdInPath($fileId, '/' . $this->rootFolder->getAppDataDirectoryName() . '/');
  332. if (!$node instanceof File) {
  333. throw new NotFoundException('Node is not a file');
  334. }
  335. } elseif (!$node instanceof File) {
  336. throw new NotFoundException('Node is not a file');
  337. }
  338. return new Http\DataDownloadResponse($node->getContent(), $node->getName(), $node->getMimeType());
  339. }
  340. /**
  341. * @param Task $task
  342. * @return list<int>
  343. * @throws NotFoundException
  344. */
  345. private function extractFileIdsFromTask(Task $task): array {
  346. $ids = [];
  347. $taskTypes = $this->taskProcessingManager->getAvailableTaskTypes();
  348. if (!isset($taskTypes[$task->getTaskTypeId()])) {
  349. throw new NotFoundException('Could not find task type');
  350. }
  351. $taskType = $taskTypes[$task->getTaskTypeId()];
  352. foreach ($taskType['inputShape'] + $taskType['optionalInputShape'] as $key => $descriptor) {
  353. if (in_array(EShapeType::getScalarType($descriptor->getShapeType()), [EShapeType::File, EShapeType::Image, EShapeType::Audio, EShapeType::Video], true)) {
  354. /** @var int|list<int> $inputSlot */
  355. $inputSlot = $task->getInput()[$key];
  356. if (is_array($inputSlot)) {
  357. $ids += $inputSlot;
  358. } else {
  359. $ids[] = $inputSlot;
  360. }
  361. }
  362. }
  363. if ($task->getOutput() !== null) {
  364. foreach ($taskType['outputShape'] + $taskType['optionalOutputShape'] as $key => $descriptor) {
  365. if (in_array(EShapeType::getScalarType($descriptor->getShapeType()), [EShapeType::File, EShapeType::Image, EShapeType::Audio, EShapeType::Video], true)) {
  366. /** @var int|list<int> $outputSlot */
  367. $outputSlot = $task->getOutput()[$key];
  368. if (is_array($outputSlot)) {
  369. $ids += $outputSlot;
  370. } else {
  371. $ids[] = $outputSlot;
  372. }
  373. }
  374. }
  375. }
  376. return array_values($ids);
  377. }
  378. /**
  379. * Sets the task progress
  380. *
  381. * @param int $taskId The id of the task
  382. * @param float $progress The progress
  383. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  384. *
  385. * 200: Progress updated successfully
  386. * 404: Task not found
  387. */
  388. #[ExAppRequired]
  389. #[ApiRoute(verb: 'POST', url: '/tasks_provider/{taskId}/progress', root: '/taskprocessing')]
  390. public function setProgress(int $taskId, float $progress): DataResponse {
  391. try {
  392. $this->taskProcessingManager->setTaskProgress($taskId, $progress);
  393. $task = $this->taskProcessingManager->getTask($taskId);
  394. /** @var CoreTaskProcessingTask $json */
  395. $json = $task->jsonSerialize();
  396. return new DataResponse([
  397. 'task' => $json,
  398. ]);
  399. } catch (NotFoundException) {
  400. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  401. } catch (Exception) {
  402. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  403. }
  404. }
  405. /**
  406. * Sets the task result
  407. *
  408. * @param int $taskId The id of the task
  409. * @param array<string,mixed>|null $output The resulting task output, files are represented by their IDs
  410. * @param string|null $errorMessage An error message if the task failed
  411. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  412. *
  413. * 200: Result updated successfully
  414. * 404: Task not found
  415. */
  416. #[ExAppRequired]
  417. #[ApiRoute(verb: 'POST', url: '/tasks_provider/{taskId}/result', root: '/taskprocessing')]
  418. public function setResult(int $taskId, ?array $output = null, ?string $errorMessage = null): DataResponse {
  419. try {
  420. // set result
  421. $this->taskProcessingManager->setTaskResult($taskId, $errorMessage, $output, true);
  422. $task = $this->taskProcessingManager->getTask($taskId);
  423. /** @var CoreTaskProcessingTask $json */
  424. $json = $task->jsonSerialize();
  425. return new DataResponse([
  426. 'task' => $json,
  427. ]);
  428. } catch (NotFoundException) {
  429. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  430. } catch (Exception) {
  431. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  432. }
  433. }
  434. /**
  435. * Cancels a task
  436. *
  437. * @param int $taskId The id of the task
  438. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  439. *
  440. * 200: Task canceled successfully
  441. * 404: Task not found
  442. */
  443. #[NoAdminRequired]
  444. #[ApiRoute(verb: 'POST', url: '/tasks/{taskId}/cancel', root: '/taskprocessing')]
  445. public function cancelTask(int $taskId): DataResponse {
  446. try {
  447. // Check if the current user can access the task
  448. $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  449. // set result
  450. $this->taskProcessingManager->cancelTask($taskId);
  451. $task = $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  452. /** @var CoreTaskProcessingTask $json */
  453. $json = $task->jsonSerialize();
  454. return new DataResponse([
  455. 'task' => $json,
  456. ]);
  457. } catch (NotFoundException) {
  458. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  459. } catch (Exception) {
  460. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  461. }
  462. }
  463. /**
  464. * Returns the next scheduled task for the taskTypeId
  465. *
  466. * @param list<string> $providerIds The ids of the providers
  467. * @param list<string> $taskTypeIds The ids of the task types
  468. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask, provider: array{name: string}}, array{}>|DataResponse<Http::STATUS_NO_CONTENT, null, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  469. *
  470. * 200: Task returned
  471. * 204: No task found
  472. */
  473. #[ExAppRequired]
  474. #[ApiRoute(verb: 'GET', url: '/tasks_provider/next', root: '/taskprocessing')]
  475. public function getNextScheduledTask(array $providerIds, array $taskTypeIds): DataResponse {
  476. try {
  477. // restrict $providerIds to providers that are configured as preferred for the passed task types
  478. $providerIds = array_values(array_intersect(array_unique(array_map(fn ($taskTypeId) => $this->taskProcessingManager->getPreferredProvider($taskTypeId)->getId(), $taskTypeIds)), $providerIds));
  479. // restrict $taskTypeIds to task types that can actually be run by one of the now restricted providers
  480. $taskTypeIds = array_values(array_filter($taskTypeIds, fn ($taskTypeId) => in_array($this->taskProcessingManager->getPreferredProvider($taskTypeId)->getId(), $providerIds, true)));
  481. if (count($providerIds) === 0 || count($taskTypeIds) === 0) {
  482. throw new NotFoundException();
  483. }
  484. $taskIdsToIgnore = [];
  485. while (true) {
  486. $task = $this->taskProcessingManager->getNextScheduledTask($taskTypeIds, $taskIdsToIgnore);
  487. $provider = $this->taskProcessingManager->getPreferredProvider($task->getTaskTypeId());
  488. if (in_array($provider->getId(), $providerIds, true)) {
  489. if ($this->taskProcessingManager->lockTask($task)) {
  490. break;
  491. }
  492. }
  493. $taskIdsToIgnore[] = (int)$task->getId();
  494. }
  495. /** @var CoreTaskProcessingTask $json */
  496. $json = $task->jsonSerialize();
  497. return new DataResponse([
  498. 'task' => $json,
  499. 'provider' => [
  500. 'name' => $provider->getId(),
  501. ],
  502. ]);
  503. } catch (NotFoundException) {
  504. return new DataResponse(null, Http::STATUS_NO_CONTENT);
  505. } catch (Exception) {
  506. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  507. }
  508. }
  509. /**
  510. * @param resource $data
  511. * @return int
  512. * @throws NotPermittedException
  513. */
  514. private function setFileContentsInternal($data): int {
  515. try {
  516. $folder = $this->appData->getFolder('TaskProcessing');
  517. } catch (\OCP\Files\NotFoundException) {
  518. $folder = $this->appData->newFolder('TaskProcessing');
  519. }
  520. /** @var SimpleFile $file */
  521. $file = $folder->newFile(time() . '-' . rand(1, 100000), $data);
  522. return $file->getId();
  523. }
  524. }