TextProcessingApiController.php 7.6 KB

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