TextProcessingApiController.php 8.0 KB

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