1
0

TaskProcessingApiController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2024 Marcel Klehr <mklehr@gmx.net>
  5. *
  6. * @author Marcel Klehr <mklehr@gmx.net>
  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 <http://www.gnu.org/licenses/>.
  22. */
  23. namespace OC\Core\Controller;
  24. use OCA\Core\ResponseDefinitions;
  25. use OCP\AppFramework\Http;
  26. use OCP\AppFramework\Http\Attribute\AnonRateLimit;
  27. use OCP\AppFramework\Http\Attribute\ApiRoute;
  28. use OCP\AppFramework\Http\Attribute\NoAdminRequired;
  29. use OCP\AppFramework\Http\Attribute\PublicPage;
  30. use OCP\AppFramework\Http\Attribute\UserRateLimit;
  31. use OCP\AppFramework\Http\DataDownloadResponse;
  32. use OCP\AppFramework\Http\DataResponse;
  33. use OCP\Files\File;
  34. use OCP\Files\IRootFolder;
  35. use OCP\IL10N;
  36. use OCP\IRequest;
  37. use OCP\TaskProcessing\EShapeType;
  38. use OCP\TaskProcessing\Exception\Exception;
  39. use OCP\TaskProcessing\Exception\UnauthorizedException;
  40. use OCP\TaskProcessing\Exception\ValidationException;
  41. use OCP\TaskProcessing\ShapeDescriptor;
  42. use OCP\TaskProcessing\Task;
  43. /**
  44. * @psalm-import-type CoreTaskProcessingTask from ResponseDefinitions
  45. * @psalm-import-type CoreTaskProcessingTaskType from ResponseDefinitions
  46. */
  47. class TaskProcessingApiController extends \OCP\AppFramework\OCSController {
  48. public function __construct(
  49. string $appName,
  50. IRequest $request,
  51. private \OCP\TaskProcessing\IManager $taskProcessingManager,
  52. private IL10N $l,
  53. private ?string $userId,
  54. private IRootFolder $rootFolder,
  55. ) {
  56. parent::__construct($appName, $request);
  57. }
  58. /**
  59. * Returns all available TaskProcessing task types
  60. *
  61. * @return DataResponse<Http::STATUS_OK, array{types: array<string, CoreTaskProcessingTaskType>}, array{}>
  62. *
  63. * 200: Task types returned
  64. */
  65. #[PublicPage]
  66. #[ApiRoute(verb: 'GET', url: '/tasktypes', root: '/taskprocessing')]
  67. public function taskTypes(): DataResponse {
  68. $taskTypes = $this->taskProcessingManager->getAvailableTaskTypes();
  69. $serializedTaskTypes = [];
  70. foreach ($taskTypes as $key => $taskType) {
  71. $serializedTaskTypes[$key] = [
  72. 'name' => $taskType['name'],
  73. 'description' => $taskType['description'],
  74. 'inputShape' => array_map(fn (ShapeDescriptor $descriptor) =>
  75. $descriptor->jsonSerialize() + ['mandatory' => true], $taskType['inputShape'])
  76. + array_map(fn (ShapeDescriptor $descriptor) =>
  77. $descriptor->jsonSerialize() + ['mandatory' => false], $taskType['optionalInputShape']),
  78. 'outputShape' => array_map(fn (ShapeDescriptor $descriptor) =>
  79. $descriptor->jsonSerialize() + ['mandatory' => true], $taskType['outputShape'])
  80. + array_map(fn (ShapeDescriptor $descriptor) =>
  81. $descriptor->jsonSerialize() + ['mandatory' => false], $taskType['optionalOutputShape']),
  82. ];
  83. }
  84. return new DataResponse([
  85. 'types' => $serializedTaskTypes,
  86. ]);
  87. }
  88. /**
  89. * Schedules a task
  90. *
  91. * @param array<string, mixed> $input Task's input parameters
  92. * @param string $type Type of the task
  93. * @param string $appId ID of the app that will execute the task
  94. * @param string $customId An arbitrary identifier for the task
  95. *
  96. * @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{}>
  97. *
  98. * 200: Task scheduled successfully
  99. * 400: Scheduling task is not possible
  100. * 412: Scheduling task is not possible
  101. * 401: Cannot schedule task because it references files in its input that the user doesn't have access to
  102. */
  103. #[PublicPage]
  104. #[UserRateLimit(limit: 20, period: 120)]
  105. #[AnonRateLimit(limit: 5, period: 120)]
  106. #[ApiRoute(verb: 'POST', url: '/schedule', root: '/taskprocessing')]
  107. public function schedule(array $input, string $type, string $appId, string $customId = ''): DataResponse {
  108. $task = new Task($type, $input, $appId, $this->userId, $customId);
  109. try {
  110. $this->taskProcessingManager->scheduleTask($task);
  111. /** @var CoreTaskProcessingTask $json */
  112. $json = $task->jsonSerialize();
  113. return new DataResponse([
  114. 'task' => $json,
  115. ]);
  116. } catch (\OCP\TaskProcessing\Exception\PreConditionNotMetException) {
  117. return new DataResponse(['message' => $this->l->t('The given provider is not available')], Http::STATUS_PRECONDITION_FAILED);
  118. } catch (ValidationException $e) {
  119. return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
  120. } catch (UnauthorizedException $e) {
  121. return new DataResponse(['message' => 'User does not have access to the files mentioned in the task input'], Http::STATUS_UNAUTHORIZED);
  122. } catch (\OCP\TaskProcessing\Exception\Exception $e) {
  123. return new DataResponse(['message' => 'Internal server error'], Http::STATUS_INTERNAL_SERVER_ERROR);
  124. }
  125. }
  126. /**
  127. * Gets a task including status and result
  128. *
  129. * Tasks are removed 1 week after receiving their last update
  130. *
  131. * @param int $id The id of the task
  132. *
  133. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_NOT_FOUND|Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  134. *
  135. * 200: Task returned
  136. * 404: Task not found
  137. */
  138. #[PublicPage]
  139. #[ApiRoute(verb: 'GET', url: '/task/{id}', root: '/taskprocessing')]
  140. public function getTask(int $id): DataResponse {
  141. try {
  142. $task = $this->taskProcessingManager->getUserTask($id, $this->userId);
  143. /** @var CoreTaskProcessingTask $json */
  144. $json = $task->jsonSerialize();
  145. return new DataResponse([
  146. 'task' => $json,
  147. ]);
  148. } catch (\OCP\TaskProcessing\Exception\NotFoundException $e) {
  149. return new DataResponse(['message' => $this->l->t('Task not found')], Http::STATUS_NOT_FOUND);
  150. } catch (\RuntimeException $e) {
  151. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  152. }
  153. }
  154. /**
  155. * Deletes a task
  156. *
  157. * @param int $id The id of the task
  158. *
  159. * @return DataResponse<Http::STATUS_OK, null, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  160. *
  161. * 200: Task deleted
  162. */
  163. #[NoAdminRequired]
  164. #[ApiRoute(verb: 'DELETE', url: '/task/{id}', root: '/taskprocessing')]
  165. public function deleteTask(int $id): DataResponse {
  166. try {
  167. $task = $this->taskProcessingManager->getUserTask($id, $this->userId);
  168. $this->taskProcessingManager->deleteTask($task);
  169. return new DataResponse(null);
  170. } catch (\OCP\TaskProcessing\Exception\NotFoundException $e) {
  171. return new DataResponse(null);
  172. } catch (\OCP\TaskProcessing\Exception\Exception $e) {
  173. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  174. }
  175. }
  176. /**
  177. * Returns tasks for the current user filtered by the appId and optional customId
  178. *
  179. * @param string $appId ID of the app
  180. * @param string|null $customId An arbitrary identifier for the task
  181. * @return DataResponse<Http::STATUS_OK, array{tasks: CoreTaskProcessingTask[]}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  182. *
  183. * 200: Tasks returned
  184. */
  185. #[NoAdminRequired]
  186. #[ApiRoute(verb: 'GET', url: '/tasks/app/{appId}', root: '/taskprocessing')]
  187. public function listTasksByApp(string $appId, ?string $customId = null): DataResponse {
  188. try {
  189. $tasks = $this->taskProcessingManager->getUserTasksByApp($this->userId, $appId, $customId);
  190. /** @var CoreTaskProcessingTask[] $json */
  191. $json = array_map(static function (Task $task) {
  192. return $task->jsonSerialize();
  193. }, $tasks);
  194. return new DataResponse([
  195. 'tasks' => $json,
  196. ]);
  197. } catch (Exception $e) {
  198. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  199. }
  200. }
  201. /**
  202. * Returns tasks for the current user filtered by the optional taskType and optional customId
  203. *
  204. * @param string|null $taskType The task type to filter by
  205. * @param string|null $customId An arbitrary identifier for the task
  206. * @return DataResponse<Http::STATUS_OK, array{tasks: CoreTaskProcessingTask[]}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  207. *
  208. * 200: Tasks returned
  209. */
  210. #[NoAdminRequired]
  211. #[ApiRoute(verb: 'GET', url: '/tasks', root: '/taskprocessing')]
  212. public function listTasks(?string $taskType, ?string $customId = null): DataResponse {
  213. try {
  214. $tasks = $this->taskProcessingManager->getUserTasks($this->userId, $taskType, $customId);
  215. /** @var CoreTaskProcessingTask[] $json */
  216. $json = array_map(static function (Task $task) {
  217. return $task->jsonSerialize();
  218. }, $tasks);
  219. return new DataResponse([
  220. 'tasks' => $json,
  221. ]);
  222. } catch (Exception $e) {
  223. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  224. }
  225. }
  226. /**
  227. * Returns the contents of a file referenced in a task
  228. *
  229. * @param int $taskId The id of the task
  230. * @param int $fileId The file id of the file to retrieve
  231. * @return DataDownloadResponse<Http::STATUS_OK, string, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  232. *
  233. * 200: File content returned
  234. * 404: Task or file not found
  235. */
  236. #[NoAdminRequired]
  237. #[Http\Attribute\NoCSRFRequired]
  238. #[ApiRoute(verb: 'GET', url: '/tasks/{taskId}/file/{fileId}', root: '/taskprocessing')]
  239. public function getFileContents(int $taskId, int $fileId): Http\DataDownloadResponse|DataResponse {
  240. try {
  241. $task = $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  242. $ids = $this->extractFileIdsFromTask($task);
  243. if (!in_array($fileId, $ids)) {
  244. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  245. }
  246. $node = $this->rootFolder->getFirstNodeById($fileId);
  247. if ($node === null) {
  248. $node = $this->rootFolder->getFirstNodeByIdInPath($fileId, '/' . $this->rootFolder->getAppDataDirectoryName() . '/');
  249. if (!$node instanceof File) {
  250. throw new \OCP\TaskProcessing\Exception\NotFoundException('Node is not a file');
  251. }
  252. } elseif (!$node instanceof File) {
  253. throw new \OCP\TaskProcessing\Exception\NotFoundException('Node is not a file');
  254. }
  255. return new Http\DataDownloadResponse($node->getContent(), $node->getName(), $node->getMimeType());
  256. } catch (\OCP\TaskProcessing\Exception\NotFoundException $e) {
  257. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  258. } catch (Exception $e) {
  259. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  260. }
  261. }
  262. /**
  263. * @param Task $task
  264. * @return list<int>
  265. * @throws \OCP\TaskProcessing\Exception\NotFoundException
  266. */
  267. private function extractFileIdsFromTask(Task $task): array {
  268. $ids = [];
  269. $taskTypes = $this->taskProcessingManager->getAvailableTaskTypes();
  270. if (!isset($taskTypes[$task->getTaskTypeId()])) {
  271. throw new \OCP\TaskProcessing\Exception\NotFoundException('Could not find task type');
  272. }
  273. $taskType = $taskTypes[$task->getTaskTypeId()];
  274. foreach ($taskType['inputShape'] + $taskType['optionalInputShape'] as $key => $descriptor) {
  275. if (in_array(EShapeType::getScalarType($descriptor->getShapeType()), [EShapeType::File, EShapeType::Image, EShapeType::Audio, EShapeType::Video], true)) {
  276. /** @var int|list<int> $inputSlot */
  277. $inputSlot = $task->getInput()[$key];
  278. if (is_array($inputSlot)) {
  279. $ids += $inputSlot;
  280. } else {
  281. $ids[] = $inputSlot;
  282. }
  283. }
  284. }
  285. if ($task->getOutput() !== null) {
  286. foreach ($taskType['outputShape'] + $taskType['optionalOutputShape'] as $key => $descriptor) {
  287. if (in_array(EShapeType::getScalarType($descriptor->getShapeType()), [EShapeType::File, EShapeType::Image, EShapeType::Audio, EShapeType::Video], true)) {
  288. /** @var int|list<int> $outputSlot */
  289. $outputSlot = $task->getOutput()[$key];
  290. if (is_array($outputSlot)) {
  291. $ids += $outputSlot;
  292. } else {
  293. $ids[] = $outputSlot;
  294. }
  295. }
  296. }
  297. }
  298. return array_values($ids);
  299. }
  300. /**
  301. * Sets the task progress
  302. *
  303. * @param int $taskId The id of the task
  304. * @param float $progress The progress
  305. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  306. *
  307. * 200: Progress updated successfully
  308. * 404: Task not found
  309. */
  310. #[NoAdminRequired]
  311. #[ApiRoute(verb: 'POST', url: '/tasks/{taskId}/progress', root: '/taskprocessing')]
  312. public function setProgress(int $taskId, float $progress): DataResponse {
  313. try {
  314. $this->taskProcessingManager->setTaskProgress($taskId, $progress);
  315. $task = $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  316. /** @var CoreTaskProcessingTask $json */
  317. $json = $task->jsonSerialize();
  318. return new DataResponse([
  319. 'task' => $json,
  320. ]);
  321. } catch (\OCP\TaskProcessing\Exception\NotFoundException $e) {
  322. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  323. } catch (Exception $e) {
  324. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  325. }
  326. }
  327. /**
  328. * Sets the task result
  329. *
  330. * @param int $taskId The id of the task
  331. * @param array<string,mixed>|null $output The resulting task output
  332. * @param string|null $errorMessage An error message if the task failed
  333. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  334. *
  335. * 200: Result updated successfully
  336. * 404: Task not found
  337. */
  338. #[NoAdminRequired]
  339. #[ApiRoute(verb: 'POST', url: '/tasks/{taskId}/result', root: '/taskprocessing')]
  340. public function setResult(int $taskId, ?array $output = null, ?string $errorMessage = null): DataResponse {
  341. try {
  342. // Check if the current user can access the task
  343. $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  344. // set result
  345. $this->taskProcessingManager->setTaskResult($taskId, $errorMessage, $output);
  346. $task = $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  347. /** @var CoreTaskProcessingTask $json */
  348. $json = $task->jsonSerialize();
  349. return new DataResponse([
  350. 'task' => $json,
  351. ]);
  352. } catch (\OCP\TaskProcessing\Exception\NotFoundException $e) {
  353. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  354. } catch (Exception $e) {
  355. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  356. }
  357. }
  358. /**
  359. * Cancels a task
  360. *
  361. * @param int $taskId The id of the task
  362. * @return DataResponse<Http::STATUS_OK, array{task: CoreTaskProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_NOT_FOUND, array{message: string}, array{}>
  363. *
  364. * 200: Task canceled successfully
  365. * 404: Task not found
  366. */
  367. #[NoAdminRequired]
  368. #[ApiRoute(verb: 'POST', url: '/tasks/{taskId}/cancel', root: '/taskprocessing')]
  369. public function cancelTask(int $taskId): DataResponse {
  370. try {
  371. // Check if the current user can access the task
  372. $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  373. // set result
  374. $this->taskProcessingManager->cancelTask($taskId);
  375. $task = $this->taskProcessingManager->getUserTask($taskId, $this->userId);
  376. /** @var CoreTaskProcessingTask $json */
  377. $json = $task->jsonSerialize();
  378. return new DataResponse([
  379. 'task' => $json,
  380. ]);
  381. } catch (\OCP\TaskProcessing\Exception\NotFoundException $e) {
  382. return new DataResponse(['message' => $this->l->t('Not found')], Http::STATUS_NOT_FOUND);
  383. } catch (Exception $e) {
  384. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  385. }
  386. }
  387. }