1
0

TextToImageApiController.php 9.0 KB

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