1
0

TextProcessingApiController.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Core\Controller;
  8. use InvalidArgumentException;
  9. use OC\Core\ResponseDefinitions;
  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\NoAdminRequired;
  14. use OCP\AppFramework\Http\Attribute\PublicPage;
  15. use OCP\AppFramework\Http\Attribute\UserRateLimit;
  16. use OCP\AppFramework\Http\DataResponse;
  17. use OCP\Common\Exception\NotFoundException;
  18. use OCP\DB\Exception;
  19. use OCP\IL10N;
  20. use OCP\IRequest;
  21. use OCP\PreConditionNotMetException;
  22. use OCP\TextProcessing\Exception\TaskFailureException;
  23. use OCP\TextProcessing\IManager;
  24. use OCP\TextProcessing\ITaskType;
  25. use OCP\TextProcessing\Task;
  26. use Psr\Container\ContainerExceptionInterface;
  27. use Psr\Container\ContainerInterface;
  28. use Psr\Container\NotFoundExceptionInterface;
  29. use Psr\Log\LoggerInterface;
  30. /**
  31. * @psalm-import-type CoreTextProcessingTask from ResponseDefinitions
  32. */
  33. class TextProcessingApiController extends \OCP\AppFramework\OCSController {
  34. public function __construct(
  35. string $appName,
  36. IRequest $request,
  37. private IManager $textProcessingManager,
  38. private IL10N $l,
  39. private ?string $userId,
  40. private ContainerInterface $container,
  41. private LoggerInterface $logger,
  42. ) {
  43. parent::__construct($appName, $request);
  44. }
  45. /**
  46. * This endpoint returns all available LanguageModel task types
  47. *
  48. * @return DataResponse<Http::STATUS_OK, array{types: array{id: string, name: string, description: string}[]}, array{}>
  49. *
  50. * 200: Task types returned
  51. */
  52. #[PublicPage]
  53. #[ApiRoute(verb: 'GET', url: '/tasktypes', root: '/textprocessing')]
  54. public function taskTypes(): DataResponse {
  55. $typeClasses = $this->textProcessingManager->getAvailableTaskTypes();
  56. $types = [];
  57. /** @var string $typeClass */
  58. foreach ($typeClasses as $typeClass) {
  59. try {
  60. /** @var ITaskType $object */
  61. $object = $this->container->get($typeClass);
  62. } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) {
  63. $this->logger->warning('Could not find ' . $typeClass, ['exception' => $e]);
  64. continue;
  65. }
  66. $types[] = [
  67. 'id' => $typeClass,
  68. 'name' => $object->getName(),
  69. 'description' => $object->getDescription(),
  70. ];
  71. }
  72. return new DataResponse([
  73. 'types' => $types,
  74. ]);
  75. }
  76. /**
  77. * This endpoint allows scheduling a language model task
  78. *
  79. * @param string $input Input text
  80. * @param string $type Type of the task
  81. * @param string $appId ID of the app that will execute the task
  82. * @param string $identifier An arbitrary identifier for the task
  83. *
  84. * @return DataResponse<Http::STATUS_OK, array{task: CoreTextProcessingTask}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_BAD_REQUEST|Http::STATUS_PRECONDITION_FAILED, array{message: string}, array{}>
  85. *
  86. * 200: Task scheduled successfully
  87. * 400: Scheduling task is not possible
  88. * 412: Scheduling task is not possible
  89. */
  90. #[PublicPage]
  91. #[UserRateLimit(limit: 20, period: 120)]
  92. #[AnonRateLimit(limit: 5, period: 120)]
  93. #[ApiRoute(verb: 'POST', url: '/schedule', root: '/textprocessing')]
  94. public function schedule(string $input, string $type, string $appId, string $identifier = ''): DataResponse {
  95. try {
  96. $task = new Task($type, $input, $appId, $this->userId, $identifier);
  97. } catch (InvalidArgumentException) {
  98. return new DataResponse(['message' => $this->l->t('Requested task type does not exist')], Http::STATUS_BAD_REQUEST);
  99. }
  100. try {
  101. try {
  102. $this->textProcessingManager->runOrScheduleTask($task);
  103. } catch(TaskFailureException) {
  104. // noop, because the task object has the failure status set already, we just return the task json
  105. }
  106. $json = $task->jsonSerialize();
  107. return new DataResponse([
  108. 'task' => $json,
  109. ]);
  110. } catch (PreConditionNotMetException) {
  111. return new DataResponse(['message' => $this->l->t('Necessary language model provider is not available')], Http::STATUS_PRECONDITION_FAILED);
  112. } catch (Exception) {
  113. return new DataResponse(['message' => 'Internal server error'], Http::STATUS_INTERNAL_SERVER_ERROR);
  114. }
  115. }
  116. /**
  117. * This endpoint allows checking the status and results of a task.
  118. * Tasks are removed 1 week after receiving their last update.
  119. *
  120. * @param int $id The id of the task
  121. *
  122. * @return DataResponse<Http::STATUS_OK, array{task: CoreTextProcessingTask}, array{}>|DataResponse<Http::STATUS_NOT_FOUND|Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  123. *
  124. * 200: Task returned
  125. * 404: Task not found
  126. */
  127. #[PublicPage]
  128. #[ApiRoute(verb: 'GET', url: '/task/{id}', root: '/textprocessing')]
  129. public function getTask(int $id): DataResponse {
  130. try {
  131. $task = $this->textProcessingManager->getUserTask($id, $this->userId);
  132. $json = $task->jsonSerialize();
  133. return new DataResponse([
  134. 'task' => $json,
  135. ]);
  136. } catch (NotFoundException $e) {
  137. return new DataResponse(['message' => $this->l->t('Task not found')], Http::STATUS_NOT_FOUND);
  138. } catch (\RuntimeException $e) {
  139. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  140. }
  141. }
  142. /**
  143. * This endpoint allows to delete a scheduled task for a user
  144. *
  145. * @param int $id The id of the task
  146. *
  147. * @return DataResponse<Http::STATUS_OK, array{task: CoreTextProcessingTask}, array{}>|DataResponse<Http::STATUS_NOT_FOUND|Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  148. *
  149. * 200: Task returned
  150. * 404: Task not found
  151. */
  152. #[NoAdminRequired]
  153. #[ApiRoute(verb: 'DELETE', url: '/task/{id}', root: '/textprocessing')]
  154. public function deleteTask(int $id): DataResponse {
  155. try {
  156. $task = $this->textProcessingManager->getUserTask($id, $this->userId);
  157. $this->textProcessingManager->deleteTask($task);
  158. $json = $task->jsonSerialize();
  159. return new DataResponse([
  160. 'task' => $json,
  161. ]);
  162. } catch (NotFoundException $e) {
  163. return new DataResponse(['message' => $this->l->t('Task not found')], Http::STATUS_NOT_FOUND);
  164. } catch (\RuntimeException $e) {
  165. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  166. }
  167. }
  168. /**
  169. * This endpoint returns a list of tasks of a user that are related
  170. * with a specific appId and optionally with an identifier
  171. *
  172. * @param string $appId ID of the app
  173. * @param string|null $identifier An arbitrary identifier for the task
  174. * @return DataResponse<Http::STATUS_OK, array{tasks: CoreTextProcessingTask[]}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  175. *
  176. * 200: Task list returned
  177. */
  178. #[NoAdminRequired]
  179. #[ApiRoute(verb: 'GET', url: '/tasks/app/{appId}', root: '/textprocessing')]
  180. public function listTasksByApp(string $appId, ?string $identifier = null): DataResponse {
  181. try {
  182. $tasks = $this->textProcessingManager->getUserTasksByApp($this->userId, $appId, $identifier);
  183. /** @var CoreTextProcessingTask[] $json */
  184. $json = array_map(static function (Task $task) {
  185. return $task->jsonSerialize();
  186. }, $tasks);
  187. return new DataResponse([
  188. 'tasks' => $json,
  189. ]);
  190. } catch (\RuntimeException $e) {
  191. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  192. }
  193. }
  194. }