Manager.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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\TextProcessing;
  24. use OC\AppFramework\Bootstrap\Coordinator;
  25. use OC\TextProcessing\Db\Task as DbTask;
  26. use OCP\IConfig;
  27. use OCP\TextProcessing\Task;
  28. use OCP\TextProcessing\Task as OCPTask;
  29. use OC\TextProcessing\Db\TaskMapper;
  30. use OCP\AppFramework\Db\DoesNotExistException;
  31. use OCP\AppFramework\Db\MultipleObjectsReturnedException;
  32. use OCP\BackgroundJob\IJobList;
  33. use OCP\Common\Exception\NotFoundException;
  34. use OCP\DB\Exception;
  35. use OCP\IServerContainer;
  36. use OCP\TextProcessing\IManager;
  37. use OCP\TextProcessing\IProvider;
  38. use OCP\PreConditionNotMetException;
  39. use Psr\Log\LoggerInterface;
  40. use RuntimeException;
  41. use Throwable;
  42. class Manager implements IManager {
  43. /** @var ?IProvider[] */
  44. private ?array $providers = null;
  45. public function __construct(
  46. private IServerContainer $serverContainer,
  47. private Coordinator $coordinator,
  48. private LoggerInterface $logger,
  49. private IJobList $jobList,
  50. private TaskMapper $taskMapper,
  51. private IConfig $config,
  52. ) {
  53. }
  54. public function getProviders(): array {
  55. $context = $this->coordinator->getRegistrationContext();
  56. if ($context === null) {
  57. return [];
  58. }
  59. if ($this->providers !== null) {
  60. return $this->providers;
  61. }
  62. $this->providers = [];
  63. foreach ($context->getTextProcessingProviders() as $providerServiceRegistration) {
  64. $class = $providerServiceRegistration->getService();
  65. try {
  66. $this->providers[$class] = $this->serverContainer->get($class);
  67. } catch (Throwable $e) {
  68. $this->logger->error('Failed to load Text processing provider ' . $class, [
  69. 'exception' => $e,
  70. ]);
  71. }
  72. }
  73. return $this->providers;
  74. }
  75. public function hasProviders(): bool {
  76. $context = $this->coordinator->getRegistrationContext();
  77. if ($context === null) {
  78. return false;
  79. }
  80. return count($context->getTextProcessingProviders()) > 0;
  81. }
  82. /**
  83. * @inheritDoc
  84. */
  85. public function getAvailableTaskTypes(): array {
  86. $tasks = [];
  87. foreach ($this->getProviders() as $provider) {
  88. $tasks[$provider->getTaskType()] = true;
  89. }
  90. return array_keys($tasks);
  91. }
  92. public function canHandleTask(OCPTask $task): bool {
  93. return in_array($task->getType(), $this->getAvailableTaskTypes());
  94. }
  95. /**
  96. * @inheritDoc
  97. */
  98. public function runTask(OCPTask $task): string {
  99. if (!$this->canHandleTask($task)) {
  100. throw new PreConditionNotMetException('No text processing provider is installed that can handle this task');
  101. }
  102. $providers = $this->getProviders();
  103. $json = $this->config->getAppValue('core', 'ai.textprocessing_provider_preferences', '');
  104. if ($json !== '') {
  105. $preferences = json_decode($json, true);
  106. if (isset($preferences[$task->getType()])) {
  107. // If a preference for this task type is set, move the preferred provider to the start
  108. $provider = current(array_filter($providers, fn ($provider) => $provider::class === $preferences[$task->getType()]));
  109. if ($provider !== false) {
  110. $providers = array_filter($providers, fn ($p) => $p !== $provider);
  111. array_unshift($providers, $provider);
  112. }
  113. }
  114. }
  115. foreach ($providers as $provider) {
  116. if (!$task->canUseProvider($provider)) {
  117. continue;
  118. }
  119. try {
  120. $task->setStatus(OCPTask::STATUS_RUNNING);
  121. if ($task->getId() === null) {
  122. $taskEntity = $this->taskMapper->insert(DbTask::fromPublicTask($task));
  123. $task->setId($taskEntity->getId());
  124. } else {
  125. $this->taskMapper->update(DbTask::fromPublicTask($task));
  126. }
  127. $output = $task->visitProvider($provider);
  128. $task->setOutput($output);
  129. $task->setStatus(OCPTask::STATUS_SUCCESSFUL);
  130. $this->taskMapper->update(DbTask::fromPublicTask($task));
  131. return $output;
  132. } catch (\RuntimeException $e) {
  133. $this->logger->info('LanguageModel call using provider ' . $provider->getName() . ' failed', ['exception' => $e]);
  134. $task->setStatus(OCPTask::STATUS_FAILED);
  135. $this->taskMapper->update(DbTask::fromPublicTask($task));
  136. throw $e;
  137. } catch (\Throwable $e) {
  138. $this->logger->info('LanguageModel call using provider ' . $provider->getName() . ' failed', ['exception' => $e]);
  139. $task->setStatus(OCPTask::STATUS_FAILED);
  140. $this->taskMapper->update(DbTask::fromPublicTask($task));
  141. throw new RuntimeException('LanguageModel call using provider ' . $provider->getName() . ' failed: ' . $e->getMessage(), 0, $e);
  142. }
  143. }
  144. throw new RuntimeException('Could not run task');
  145. }
  146. /**
  147. * @inheritDoc
  148. * @throws Exception
  149. */
  150. public function scheduleTask(OCPTask $task): void {
  151. if (!$this->canHandleTask($task)) {
  152. throw new PreConditionNotMetException('No LanguageModel provider is installed that can handle this task');
  153. }
  154. $task->setStatus(OCPTask::STATUS_SCHEDULED);
  155. $taskEntity = DbTask::fromPublicTask($task);
  156. $this->taskMapper->insert($taskEntity);
  157. $task->setId($taskEntity->getId());
  158. $this->jobList->add(TaskBackgroundJob::class, [
  159. 'taskId' => $task->getId()
  160. ]);
  161. }
  162. /**
  163. * @inheritDoc
  164. */
  165. public function deleteTask(Task $task): void {
  166. $taskEntity = DbTask::fromPublicTask($task);
  167. $this->taskMapper->delete($taskEntity);
  168. $this->jobList->remove(TaskBackgroundJob::class, [
  169. 'taskId' => $task->getId()
  170. ]);
  171. }
  172. /**
  173. * Get a task from its id
  174. *
  175. * @param int $id The id of the task
  176. * @return OCPTask
  177. * @throws RuntimeException If the query failed
  178. * @throws NotFoundException If the task could not be found
  179. */
  180. public function getTask(int $id): OCPTask {
  181. try {
  182. $taskEntity = $this->taskMapper->find($id);
  183. return $taskEntity->toPublicTask();
  184. } catch (DoesNotExistException $e) {
  185. throw new NotFoundException('Could not find task with the provided id');
  186. } catch (MultipleObjectsReturnedException $e) {
  187. throw new RuntimeException('Could not uniquely identify task with given id', 0, $e);
  188. } catch (Exception $e) {
  189. throw new RuntimeException('Failure while trying to find task by id: ' . $e->getMessage(), 0, $e);
  190. }
  191. }
  192. /**
  193. * Get a task from its user id and task id
  194. * If userId is null, this can only get a task that was scheduled anonymously
  195. *
  196. * @param int $id The id of the task
  197. * @param string|null $userId The user id that scheduled the task
  198. * @return OCPTask
  199. * @throws RuntimeException If the query failed
  200. * @throws NotFoundException If the task could not be found
  201. */
  202. public function getUserTask(int $id, ?string $userId): OCPTask {
  203. try {
  204. $taskEntity = $this->taskMapper->findByIdAndUser($id, $userId);
  205. return $taskEntity->toPublicTask();
  206. } catch (DoesNotExistException $e) {
  207. throw new NotFoundException('Could not find task with the provided id and user id');
  208. } catch (MultipleObjectsReturnedException $e) {
  209. throw new RuntimeException('Could not uniquely identify task with given id and user id', 0, $e);
  210. } catch (Exception $e) {
  211. throw new RuntimeException('Failure while trying to find task by id and user id: ' . $e->getMessage(), 0, $e);
  212. }
  213. }
  214. /**
  215. * Get a list of tasks scheduled by a specific user for a specific app
  216. * and optionally with a specific identifier.
  217. * This cannot be used to get anonymously scheduled tasks
  218. *
  219. * @param string $userId
  220. * @param string $appId
  221. * @param string|null $identifier
  222. * @return array
  223. */
  224. public function getUserTasksByApp(string $userId, string $appId, ?string $identifier = null): array {
  225. try {
  226. $taskEntities = $this->taskMapper->findUserTasksByApp($userId, $appId, $identifier);
  227. return array_map(static function (DbTask $taskEntity) {
  228. return $taskEntity->toPublicTask();
  229. }, $taskEntities);
  230. } catch (Exception $e) {
  231. throw new RuntimeException('Failure while trying to find tasks by appId and identifier: ' . $e->getMessage(), 0, $e);
  232. }
  233. }
  234. }