1
0

TaskProcessingApiController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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_values(array_map(function ($descriptor) {
  65. return $descriptor->jsonSerialize();
  66. }, $tt['inputShape']));
  67. $tt['outputShape'] = array_values(array_map(function ($descriptor) {
  68. return $descriptor->jsonSerialize();
  69. }, $tt['outputShape']));
  70. $tt['optionalInputShape'] = array_values(array_map(function ($descriptor) {
  71. return $descriptor->jsonSerialize();
  72. }, $tt['optionalInputShape']));
  73. $tt['optionalOutputShape'] = array_values(array_map(function ($descriptor) {
  74. return $descriptor->jsonSerialize();
  75. }, $tt['optionalOutputShape']));
  76. $tt['inputShapeEnumValues'] = array_values(array_map(function (array $enumValues) {
  77. return array_values(array_map(fn (ShapeEnumValue $enumValue) => $enumValue->jsonSerialize(), $enumValues));
  78. }, $tt['inputShapeEnumValues']));
  79. $tt['optionalInputShapeEnumValues'] = array_values(array_map(function (array $enumValues) {
  80. return array_values(array_map(fn (ShapeEnumValue $enumValue) => $enumValue->jsonSerialize(), $enumValues));
  81. }, $tt['optionalInputShapeEnumValues']));
  82. $tt['outputShapeEnumValues'] = array_values(array_map(function (array $enumValues) {
  83. return array_values(array_map(fn (ShapeEnumValue $enumValue) => $enumValue->jsonSerialize(), $enumValues));
  84. }, $tt['outputShapeEnumValues']));
  85. $tt['optionalOutputShapeEnumValues'] = array_values(array_map(function (array $enumValues) {
  86. return array_values(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: list<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. $json = array_map(static function (Task $task) {
  203. return $task->jsonSerialize();
  204. }, $tasks);
  205. return new DataResponse([
  206. 'tasks' => $json,
  207. ]);
  208. } catch (Exception) {
  209. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  210. }
  211. }
  212. /**
  213. * Returns tasks for the current user filtered by the optional taskType and optional customId
  214. *
  215. * @param string|null $taskType The task type to filter by
  216. * @param string|null $customId An arbitrary identifier for the task
  217. * @return DataResponse<Http::STATUS_OK, array{tasks: list<CoreTaskProcessingTask>}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  218. *
  219. * 200: Tasks returned
  220. */
  221. #[NoAdminRequired]
  222. #[ApiRoute(verb: 'GET', url: '/tasks', root: '/taskprocessing')]
  223. public function listTasks(?string $taskType, ?string $customId = null): DataResponse {
  224. try {
  225. $tasks = $this->taskProcessingManager->getUserTasks($this->userId, $taskType, $customId);
  226. $json = array_map(static function (Task $task) {
  227. return $task->jsonSerialize();
  228. }, $tasks);
  229. return new DataResponse([
  230. 'tasks' => $json,
  231. ]);
  232. } catch (Exception) {
  233. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  234. }
  235. }
  236. /**
  237. * Returns the contents of a file referenced in a task
  238. *
  239. * @param int $taskId The id of the task
  240. * @param int $fileId The file id of the file to retrieve
  241. * @return DataDownloadResponse<Http::STATUS_OK, string, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  242. *
  243. * 200: File content returned
  244. * 404: Task or file not found
  245. */
  246. #[NoAdminRequired]
  247. #[Http\Attribute\NoCSRFRequired]
  248. #[ApiRoute(verb: 'GET', url: '/tasks/{taskId}/file/{fileId}', root: '/taskprocessing')]
  249. public function getFileContents(int $taskId, int $fileId): Http\DataDownloadResponse|DataResponse {
  250. try {
  251. $task = $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  252. return $this->getFileContentsInternal($task, $fileId);
  253. } catch (NotFoundException) {
  254. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  255. } catch (Exception) {
  256. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  257. }
  258. }
  259. /**
  260. * Returns the contents of a file referenced in a task(ExApp route version)
  261. *
  262. * @param int $taskId The id of the task
  263. * @param int $fileId The file id of the file to retrieve
  264. * @return DataDownloadResponse<Http::STATUS_OK, string, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  265. *
  266. * 200: File content returned
  267. * 404: Task or file not found
  268. */
  269. #[ExAppRequired]
  270. #[ApiRoute(verb: 'GET', url: '/tasks_provider/{taskId}/file/{fileId}', root: '/taskprocessing')]
  271. public function getFileContentsExApp(int $taskId, int $fileId): Http\DataDownloadResponse|DataResponse {
  272. try {
  273. $task = $this->taskProcessingManager->getTask($taskId);
  274. return $this->getFileContentsInternal($task, $fileId);
  275. } catch (NotFoundException) {
  276. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  277. } catch (Exception) {
  278. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  279. }
  280. }
  281. /**
  282. * Upload a file so it can be referenced in a task result (ExApp route version)
  283. *
  284. * Use field 'file' for the file upload
  285. *
  286. * @param int $taskId The id of the task
  287. * @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{}>
  288. *
  289. * 201: File created
  290. * 400: File upload failed or no file was uploaded
  291. * 404: Task not found
  292. */
  293. #[ExAppRequired]
  294. #[ApiRoute(verb: 'POST', url: '/tasks_provider/{taskId}/file', root: '/taskprocessing')]
  295. public function setFileContentsExApp(int $taskId): DataResponse {
  296. try {
  297. $task = $this->taskProcessingManager->getTask($taskId);
  298. $file = $this->request->getUploadedFile('file');
  299. if (!isset($file['tmp_name'])) {
  300. return new DataResponse(['message' => $this->l->t('Bad request')], Http::STATUS_BAD_REQUEST);
  301. }
  302. $handle = fopen($file['tmp_name'], 'r');
  303. if (!$handle) {
  304. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  305. }
  306. $fileId = $this->setFileContentsInternal($handle);
  307. return new DataResponse(['fileId' => $fileId], Http::STATUS_CREATED);
  308. } catch (NotFoundException) {
  309. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  310. } catch (Exception) {
  311. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  312. }
  313. }
  314. /**
  315. * @throws NotPermittedException
  316. * @throws NotFoundException
  317. * @throws GenericFileException
  318. * @throws LockedException
  319. *
  320. * @return DataDownloadResponse<Http::STATUS_OK, string, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  321. */
  322. private function getFileContentsInternal(Task $task, int $fileId): Http\DataDownloadResponse|DataResponse {
  323. $ids = $this->extractFileIdsFromTask($task);
  324. if (!in_array($fileId, $ids)) {
  325. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  326. }
  327. $node = $this->rootFolder->getFirstNodeById($fileId);
  328. if ($node === null) {
  329. $node = $this->rootFolder->getFirstNodeByIdInPath($fileId, '/' . $this->rootFolder->getAppDataDirectoryName() . '/');
  330. if (!$node instanceof File) {
  331. throw new NotFoundException('Node is not a file');
  332. }
  333. } elseif (!$node instanceof File) {
  334. throw new NotFoundException('Node is not a file');
  335. }
  336. return new Http\DataDownloadResponse($node->getContent(), $node->getName(), $node->getMimeType());
  337. }
  338. /**
  339. * @param Task $task
  340. * @return list<int>
  341. * @throws NotFoundException
  342. */
  343. private function extractFileIdsFromTask(Task $task): array {
  344. $ids = [];
  345. $taskTypes = $this->taskProcessingManager->getAvailableTaskTypes();
  346. if (!isset($taskTypes[$task->getTaskTypeId()])) {
  347. throw new NotFoundException('Could not find task type');
  348. }
  349. $taskType = $taskTypes[$task->getTaskTypeId()];
  350. foreach ($taskType['inputShape'] + $taskType['optionalInputShape'] as $key => $descriptor) {
  351. if (in_array(EShapeType::getScalarType($descriptor->getShapeType()), [EShapeType::File, EShapeType::Image, EShapeType::Audio, EShapeType::Video], true)) {
  352. /** @var int|list<int> $inputSlot */
  353. $inputSlot = $task->getInput()[$key];
  354. if (is_array($inputSlot)) {
  355. $ids = array_merge($inputSlot, $ids);
  356. } else {
  357. $ids[] = $inputSlot;
  358. }
  359. }
  360. }
  361. if ($task->getOutput() !== null) {
  362. foreach ($taskType['outputShape'] + $taskType['optionalOutputShape'] as $key => $descriptor) {
  363. if (in_array(EShapeType::getScalarType($descriptor->getShapeType()), [EShapeType::File, EShapeType::Image, EShapeType::Audio, EShapeType::Video], true)) {
  364. /** @var int|list<int> $outputSlot */
  365. $outputSlot = $task->getOutput()[$key];
  366. if (is_array($outputSlot)) {
  367. $ids = array_merge($outputSlot, $ids);
  368. } else {
  369. $ids[] = $outputSlot;
  370. }
  371. }
  372. }
  373. }
  374. return $ids;
  375. }
  376. /**
  377. * Sets the task progress
  378. *
  379. * @param int $taskId The id of the task
  380. * @param float $progress The progress
  381. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  382. *
  383. * 200: Progress updated successfully
  384. * 404: Task not found
  385. */
  386. #[ExAppRequired]
  387. #[ApiRoute(verb: 'POST', url: '/tasks_provider/{taskId}/progress', root: '/taskprocessing')]
  388. public function setProgress(int $taskId, float $progress): DataResponse {
  389. try {
  390. $this->taskProcessingManager->setTaskProgress($taskId, $progress);
  391. $task = $this->taskProcessingManager->getTask($taskId);
  392. /** @var CoreTaskProcessingTask $json */
  393. $json = $task->jsonSerialize();
  394. return new DataResponse([
  395. 'task' => $json,
  396. ]);
  397. } catch (NotFoundException) {
  398. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  399. } catch (Exception) {
  400. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  401. }
  402. }
  403. /**
  404. * Sets the task result
  405. *
  406. * @param int $taskId The id of the task
  407. * @param array<string,mixed>|null $output The resulting task output, files are represented by their IDs
  408. * @param string|null $errorMessage An error message if the task failed
  409. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  410. *
  411. * 200: Result updated successfully
  412. * 404: Task not found
  413. */
  414. #[ExAppRequired]
  415. #[ApiRoute(verb: 'POST', url: '/tasks_provider/{taskId}/result', root: '/taskprocessing')]
  416. public function setResult(int $taskId, ?array $output = null, ?string $errorMessage = null): DataResponse {
  417. try {
  418. // set result
  419. $this->taskProcessingManager->setTaskResult($taskId, $errorMessage, $output, true);
  420. $task = $this->taskProcessingManager->getTask($taskId);
  421. /** @var CoreTaskProcessingTask $json */
  422. $json = $task->jsonSerialize();
  423. return new DataResponse([
  424. 'task' => $json,
  425. ]);
  426. } catch (NotFoundException) {
  427. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  428. } catch (Exception) {
  429. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  430. }
  431. }
  432. /**
  433. * Cancels a task
  434. *
  435. * @param int $taskId The id of the task
  436. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  437. *
  438. * 200: Task canceled successfully
  439. * 404: Task not found
  440. */
  441. #[NoAdminRequired]
  442. #[ApiRoute(verb: 'POST', url: '/tasks/{taskId}/cancel', root: '/taskprocessing')]
  443. public function cancelTask(int $taskId): DataResponse {
  444. try {
  445. // Check if the current user can access the task
  446. $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  447. // set result
  448. $this->taskProcessingManager->cancelTask($taskId);
  449. $task = $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  450. /** @var CoreTaskProcessingTask $json */
  451. $json = $task->jsonSerialize();
  452. return new DataResponse([
  453. 'task' => $json,
  454. ]);
  455. } catch (NotFoundException) {
  456. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  457. } catch (Exception) {
  458. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  459. }
  460. }
  461. /**
  462. * Returns the next scheduled task for the taskTypeId
  463. *
  464. * @param list<string> $providerIds The ids of the providers
  465. * @param list<string> $taskTypeIds The ids of the task types
  466. * @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{}>
  467. *
  468. * 200: Task returned
  469. * 204: No task found
  470. */
  471. #[ExAppRequired]
  472. #[ApiRoute(verb: 'GET', url: '/tasks_provider/next', root: '/taskprocessing')]
  473. public function getNextScheduledTask(array $providerIds, array $taskTypeIds): DataResponse {
  474. try {
  475. // restrict $providerIds to providers that are configured as preferred for the passed task types
  476. $providerIds = array_values(array_intersect(array_unique(array_map(fn ($taskTypeId) => $this->taskProcessingManager->getPreferredProvider($taskTypeId)->getId(), $taskTypeIds)), $providerIds));
  477. // restrict $taskTypeIds to task types that can actually be run by one of the now restricted providers
  478. $taskTypeIds = array_values(array_filter($taskTypeIds, fn ($taskTypeId) => in_array($this->taskProcessingManager->getPreferredProvider($taskTypeId)->getId(), $providerIds, true)));
  479. if (count($providerIds) === 0 || count($taskTypeIds) === 0) {
  480. throw new NotFoundException();
  481. }
  482. $taskIdsToIgnore = [];
  483. while (true) {
  484. $task = $this->taskProcessingManager->getNextScheduledTask($taskTypeIds, $taskIdsToIgnore);
  485. $provider = $this->taskProcessingManager->getPreferredProvider($task->getTaskTypeId());
  486. if (in_array($provider->getId(), $providerIds, true)) {
  487. if ($this->taskProcessingManager->lockTask($task)) {
  488. break;
  489. }
  490. }
  491. $taskIdsToIgnore[] = (int)$task->getId();
  492. }
  493. /** @var CoreTaskProcessingTask $json */
  494. $json = $task->jsonSerialize();
  495. return new DataResponse([
  496. 'task' => $json,
  497. 'provider' => [
  498. 'name' => $provider->getId(),
  499. ],
  500. ]);
  501. } catch (NotFoundException) {
  502. return new DataResponse(null, Http::STATUS_NO_CONTENT);
  503. } catch (Exception) {
  504. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  505. }
  506. }
  507. /**
  508. * @param resource $data
  509. * @return int
  510. * @throws NotPermittedException
  511. */
  512. private function setFileContentsInternal($data): int {
  513. try {
  514. $folder = $this->appData->getFolder('TaskProcessing');
  515. } catch (\OCP\Files\NotFoundException) {
  516. $folder = $this->appData->newFolder('TaskProcessing');
  517. }
  518. /** @var SimpleFile $file */
  519. $file = $folder->newFile(time() . '-' . rand(1, 100000), $data);
  520. return $file->getId();
  521. }
  522. }