1
0

TaskProcessingApiController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. if ($task->getUserId() !== null) {
  328. \OC_Util::setupFS($task->getUserId());
  329. }
  330. $node = $this->rootFolder->getFirstNodeById($fileId);
  331. if ($node === null) {
  332. $node = $this->rootFolder->getFirstNodeByIdInPath($fileId, '/' . $this->rootFolder->getAppDataDirectoryName() . '/');
  333. if (!$node instanceof File) {
  334. throw new NotFoundException('Node is not a file');
  335. }
  336. } elseif (!$node instanceof File) {
  337. throw new NotFoundException('Node is not a file');
  338. }
  339. return new Http\DataDownloadResponse($node->getContent(), $node->getName(), $node->getMimeType());
  340. }
  341. /**
  342. * @param Task $task
  343. * @return list<int>
  344. * @throws NotFoundException
  345. */
  346. private function extractFileIdsFromTask(Task $task): array {
  347. $ids = [];
  348. $taskTypes = $this->taskProcessingManager->getAvailableTaskTypes();
  349. if (!isset($taskTypes[$task->getTaskTypeId()])) {
  350. throw new NotFoundException('Could not find task type');
  351. }
  352. $taskType = $taskTypes[$task->getTaskTypeId()];
  353. foreach ($taskType['inputShape'] + $taskType['optionalInputShape'] as $key => $descriptor) {
  354. if (in_array(EShapeType::getScalarType($descriptor->getShapeType()), [EShapeType::File, EShapeType::Image, EShapeType::Audio, EShapeType::Video], true)) {
  355. /** @var int|list<int> $inputSlot */
  356. $inputSlot = $task->getInput()[$key];
  357. if (is_array($inputSlot)) {
  358. $ids = array_merge($inputSlot, $ids);
  359. } else {
  360. $ids[] = $inputSlot;
  361. }
  362. }
  363. }
  364. if ($task->getOutput() !== null) {
  365. foreach ($taskType['outputShape'] + $taskType['optionalOutputShape'] as $key => $descriptor) {
  366. if (in_array(EShapeType::getScalarType($descriptor->getShapeType()), [EShapeType::File, EShapeType::Image, EShapeType::Audio, EShapeType::Video], true)) {
  367. /** @var int|list<int> $outputSlot */
  368. $outputSlot = $task->getOutput()[$key];
  369. if (is_array($outputSlot)) {
  370. $ids = array_merge($outputSlot, $ids);
  371. } else {
  372. $ids[] = $outputSlot;
  373. }
  374. }
  375. }
  376. }
  377. return $ids;
  378. }
  379. /**
  380. * Sets the task progress
  381. *
  382. * @param int $taskId The id of the task
  383. * @param float $progress The progress
  384. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  385. *
  386. * 200: Progress updated successfully
  387. * 404: Task not found
  388. */
  389. #[ExAppRequired]
  390. #[ApiRoute(verb: 'POST', url: '/tasks_provider/{taskId}/progress', root: '/taskprocessing')]
  391. public function setProgress(int $taskId, float $progress): DataResponse {
  392. try {
  393. $this->taskProcessingManager->setTaskProgress($taskId, $progress);
  394. $task = $this->taskProcessingManager->getTask($taskId);
  395. /** @var CoreTaskProcessingTask $json */
  396. $json = $task->jsonSerialize();
  397. return new DataResponse([
  398. 'task' => $json,
  399. ]);
  400. } catch (NotFoundException) {
  401. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  402. } catch (Exception) {
  403. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  404. }
  405. }
  406. /**
  407. * Sets the task result
  408. *
  409. * @param int $taskId The id of the task
  410. * @param array<string,mixed>|null $output The resulting task output, files are represented by their IDs
  411. * @param string|null $errorMessage An error message if the task failed
  412. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  413. *
  414. * 200: Result updated successfully
  415. * 404: Task not found
  416. */
  417. #[ExAppRequired]
  418. #[ApiRoute(verb: 'POST', url: '/tasks_provider/{taskId}/result', root: '/taskprocessing')]
  419. public function setResult(int $taskId, ?array $output = null, ?string $errorMessage = null): DataResponse {
  420. try {
  421. // set result
  422. $this->taskProcessingManager->setTaskResult($taskId, $errorMessage, $output, true);
  423. $task = $this->taskProcessingManager->getTask($taskId);
  424. /** @var CoreTaskProcessingTask $json */
  425. $json = $task->jsonSerialize();
  426. return new DataResponse([
  427. 'task' => $json,
  428. ]);
  429. } catch (NotFoundException) {
  430. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  431. } catch (Exception) {
  432. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  433. }
  434. }
  435. /**
  436. * Cancels a task
  437. *
  438. * @param int $taskId The id of the task
  439. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  440. *
  441. * 200: Task canceled successfully
  442. * 404: Task not found
  443. */
  444. #[NoAdminRequired]
  445. #[ApiRoute(verb: 'POST', url: '/tasks/{taskId}/cancel', root: '/taskprocessing')]
  446. public function cancelTask(int $taskId): DataResponse {
  447. try {
  448. // Check if the current user can access the task
  449. $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  450. // set result
  451. $this->taskProcessingManager->cancelTask($taskId);
  452. $task = $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  453. /** @var CoreTaskProcessingTask $json */
  454. $json = $task->jsonSerialize();
  455. return new DataResponse([
  456. 'task' => $json,
  457. ]);
  458. } catch (NotFoundException) {
  459. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  460. } catch (Exception) {
  461. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  462. }
  463. }
  464. /**
  465. * Returns the next scheduled task for the taskTypeId
  466. *
  467. * @param list<string> $providerIds The ids of the providers
  468. * @param list<string> $taskTypeIds The ids of the task types
  469. * @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{}>
  470. *
  471. * 200: Task returned
  472. * 204: No task found
  473. */
  474. #[ExAppRequired]
  475. #[ApiRoute(verb: 'GET', url: '/tasks_provider/next', root: '/taskprocessing')]
  476. public function getNextScheduledTask(array $providerIds, array $taskTypeIds): DataResponse {
  477. try {
  478. // restrict $providerIds to providers that are configured as preferred for the passed task types
  479. $providerIds = array_values(array_intersect(array_unique(array_map(fn ($taskTypeId) => $this->taskProcessingManager->getPreferredProvider($taskTypeId)->getId(), $taskTypeIds)), $providerIds));
  480. // restrict $taskTypeIds to task types that can actually be run by one of the now restricted providers
  481. $taskTypeIds = array_values(array_filter($taskTypeIds, fn ($taskTypeId) => in_array($this->taskProcessingManager->getPreferredProvider($taskTypeId)->getId(), $providerIds, true)));
  482. if (count($providerIds) === 0 || count($taskTypeIds) === 0) {
  483. throw new NotFoundException();
  484. }
  485. $taskIdsToIgnore = [];
  486. while (true) {
  487. $task = $this->taskProcessingManager->getNextScheduledTask($taskTypeIds, $taskIdsToIgnore);
  488. $provider = $this->taskProcessingManager->getPreferredProvider($task->getTaskTypeId());
  489. if (in_array($provider->getId(), $providerIds, true)) {
  490. if ($this->taskProcessingManager->lockTask($task)) {
  491. break;
  492. }
  493. }
  494. $taskIdsToIgnore[] = (int)$task->getId();
  495. }
  496. /** @var CoreTaskProcessingTask $json */
  497. $json = $task->jsonSerialize();
  498. return new DataResponse([
  499. 'task' => $json,
  500. 'provider' => [
  501. 'name' => $provider->getId(),
  502. ],
  503. ]);
  504. } catch (NotFoundException) {
  505. return new DataResponse(null, Http::STATUS_NO_CONTENT);
  506. } catch (Exception) {
  507. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  508. }
  509. }
  510. /**
  511. * @param resource $data
  512. * @return int
  513. * @throws NotPermittedException
  514. */
  515. private function setFileContentsInternal($data): int {
  516. try {
  517. $folder = $this->appData->getFolder('TaskProcessing');
  518. } catch (\OCP\Files\NotFoundException) {
  519. $folder = $this->appData->newFolder('TaskProcessing');
  520. }
  521. /** @var SimpleFile $file */
  522. $file = $folder->newFile(time() . '-' . rand(1, 100000), $data);
  523. return $file->getId();
  524. }
  525. }