1
0

TextToImageApiController.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 OC\Files\AppData\AppData;
  25. use OCA\Core\ResponseDefinitions;
  26. use OCP\AppFramework\Http;
  27. use OCP\AppFramework\Http\Attribute\AnonRateLimit;
  28. use OCP\AppFramework\Http\Attribute\BruteForceProtection;
  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\AppFramework\Http\FileDisplayResponse;
  34. use OCP\DB\Exception;
  35. use OCP\Files\NotFoundException;
  36. use OCP\IL10N;
  37. use OCP\IRequest;
  38. use OCP\PreConditionNotMetException;
  39. use OCP\TextToImage\Exception\TaskFailureException;
  40. use OCP\TextToImage\Exception\TaskNotFoundException;
  41. use OCP\TextToImage\IManager;
  42. use OCP\TextToImage\Task;
  43. /**
  44. * @psalm-import-type CoreTextToImageTask from ResponseDefinitions
  45. */
  46. class TextToImageApiController extends \OCP\AppFramework\OCSController {
  47. public function __construct(
  48. string $appName,
  49. IRequest $request,
  50. private IManager $textToImageManager,
  51. private IL10N $l,
  52. private ?string $userId,
  53. private AppData $appData,
  54. ) {
  55. parent::__construct($appName, $request);
  56. }
  57. /**
  58. * Check whether this feature is available
  59. *
  60. * @return DataResponse<Http::STATUS_OK, array{isAvailable: bool}, array{}>
  61. *
  62. * 200: Returns availability status
  63. */
  64. #[PublicPage]
  65. public function isAvailable(): DataResponse {
  66. return new DataResponse([
  67. 'isAvailable' => $this->textToImageManager->hasProviders(),
  68. ]);
  69. }
  70. /**
  71. * This endpoint allows scheduling a text to image task
  72. *
  73. * @param string $input Input text
  74. * @param string $appId ID of the app that will execute the task
  75. * @param string $identifier An arbitrary identifier for the task
  76. * @param int $numberOfImages The number of images to generate
  77. *
  78. * @return DataResponse<Http::STATUS_OK, array{task: CoreTextToImageTask}, array{}>|DataResponse<Http::STATUS_PRECONDITION_FAILED|Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  79. *
  80. * 200: Task scheduled successfully
  81. * 412: Scheduling task is not possible
  82. */
  83. #[PublicPage]
  84. #[UserRateLimit(limit: 20, period: 120)]
  85. #[AnonRateLimit(limit: 5, period: 120)]
  86. public function schedule(string $input, string $appId, string $identifier = '', int $numberOfImages = 8): DataResponse {
  87. $task = new Task($input, $appId, $numberOfImages, $this->userId, $identifier);
  88. try {
  89. try {
  90. $this->textToImageManager->runOrScheduleTask($task);
  91. } catch (TaskFailureException) {
  92. // Task status was already updated by the manager, nothing to do here
  93. }
  94. $json = $task->jsonSerialize();
  95. return new DataResponse([
  96. 'task' => $json,
  97. ]);
  98. } catch (PreConditionNotMetException) {
  99. return new DataResponse(['message' => $this->l->t('No text to image provider is available')], Http::STATUS_PRECONDITION_FAILED);
  100. } catch (Exception) {
  101. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  102. }
  103. }
  104. /**
  105. * This endpoint allows checking the status and results of a task.
  106. * Tasks are removed 1 week after receiving their last update.
  107. *
  108. * @param int $id The id of the task
  109. *
  110. * @return DataResponse<Http::STATUS_OK, array{task: CoreTextToImageTask}, array{}>|DataResponse<Http::STATUS_NOT_FOUND|Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  111. *
  112. * 200: Task returned
  113. * 404: Task not found
  114. */
  115. #[PublicPage]
  116. #[BruteForceProtection(action: 'text2image')]
  117. public function getTask(int $id): DataResponse {
  118. try {
  119. $task = $this->textToImageManager->getUserTask($id, $this->userId);
  120. $json = $task->jsonSerialize();
  121. return new DataResponse([
  122. 'task' => $json,
  123. ]);
  124. } catch (TaskNotFoundException) {
  125. $res = new DataResponse(['message' => $this->l->t('Task not found')], Http::STATUS_NOT_FOUND);
  126. $res->throttle(['action' => 'text2image']);
  127. return $res;
  128. } catch (\RuntimeException) {
  129. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  130. }
  131. }
  132. /**
  133. * This endpoint allows downloading the resulting image of a task
  134. *
  135. * @param int $id The id of the task
  136. * @param int $index The index of the image to retrieve
  137. *
  138. * @return FileDisplayResponse<Http::STATUS_OK, array{'Content-Type': string}>|DataResponse<Http::STATUS_NOT_FOUND|Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  139. *
  140. * 200: Image returned
  141. * 404: Task or image not found
  142. */
  143. #[PublicPage]
  144. #[BruteForceProtection(action: 'text2image')]
  145. public function getImage(int $id, int $index): DataResponse|FileDisplayResponse {
  146. try {
  147. $task = $this->textToImageManager->getUserTask($id, $this->userId);
  148. try {
  149. $folder = $this->appData->getFolder('text2image');
  150. } catch(NotFoundException) {
  151. $res = new DataResponse(['message' => $this->l->t('Image not found')], Http::STATUS_NOT_FOUND);
  152. $res->throttle(['action' => 'text2image']);
  153. return $res;
  154. }
  155. $file = $folder->getFolder((string) $task->getId())->getFile((string) $index);
  156. $info = getimagesizefromstring($file->getContent());
  157. return new FileDisplayResponse($file, Http::STATUS_OK, ['Content-Type' => image_type_to_mime_type($info[2])]);
  158. } catch (TaskNotFoundException) {
  159. $res = new DataResponse(['message' => $this->l->t('Task not found')], Http::STATUS_NOT_FOUND);
  160. $res->throttle(['action' => 'text2image']);
  161. return $res;
  162. } catch (\RuntimeException) {
  163. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  164. } catch (NotFoundException) {
  165. $res = new DataResponse(['message' => $this->l->t('Image not found')], Http::STATUS_NOT_FOUND);
  166. $res->throttle(['action' => 'text2image']);
  167. return $res;
  168. }
  169. }
  170. /**
  171. * This endpoint allows to delete a scheduled task for a user
  172. *
  173. * @param int $id The id of the task
  174. *
  175. * @return DataResponse<Http::STATUS_OK, array{task: CoreTextToImageTask}, array{}>|DataResponse<Http::STATUS_NOT_FOUND|Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  176. *
  177. * 200: Task returned
  178. * 404: Task not found
  179. */
  180. #[NoAdminRequired]
  181. #[BruteForceProtection(action: 'text2image')]
  182. public function deleteTask(int $id): DataResponse {
  183. try {
  184. $task = $this->textToImageManager->getUserTask($id, $this->userId);
  185. $this->textToImageManager->deleteTask($task);
  186. $json = $task->jsonSerialize();
  187. return new DataResponse([
  188. 'task' => $json,
  189. ]);
  190. } catch (TaskNotFoundException) {
  191. $res = new DataResponse(['message' => $this->l->t('Task not found')], Http::STATUS_NOT_FOUND);
  192. $res->throttle(['action' => 'text2image']);
  193. return $res;
  194. } catch (\RuntimeException) {
  195. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  196. }
  197. }
  198. /**
  199. * This endpoint returns a list of tasks of a user that are related
  200. * with a specific appId and optionally with an identifier
  201. *
  202. * @param string $appId ID of the app
  203. * @param string|null $identifier An arbitrary identifier for the task
  204. * @return DataResponse<Http::STATUS_OK, array{tasks: CoreTextToImageTask[]}, array{}>|DataResponse<Http::STATUS_INTERNAL_SERVER_ERROR, array{message: string}, array{}>
  205. *
  206. * 200: Task list returned
  207. */
  208. #[NoAdminRequired]
  209. #[AnonRateLimit(limit: 5, period: 120)]
  210. public function listTasksByApp(string $appId, ?string $identifier = null): DataResponse {
  211. try {
  212. $tasks = $this->textToImageManager->getUserTasksByApp($this->userId, $appId, $identifier);
  213. /** @var CoreTextToImageTask[] $json */
  214. $json = array_map(static function (Task $task) {
  215. return $task->jsonSerialize();
  216. }, $tasks);
  217. return new DataResponse([
  218. 'tasks' => $json,
  219. ]);
  220. } catch (\RuntimeException) {
  221. return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
  222. }
  223. }
  224. }