Manager.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\TaskProcessing;
  8. use GuzzleHttp\Exception\ClientException;
  9. use GuzzleHttp\Exception\ServerException;
  10. use OC\AppFramework\Bootstrap\Coordinator;
  11. use OC\Files\SimpleFS\SimpleFile;
  12. use OC\TaskProcessing\Db\TaskMapper;
  13. use OCP\App\IAppManager;
  14. use OCP\AppFramework\Db\DoesNotExistException;
  15. use OCP\AppFramework\Db\MultipleObjectsReturnedException;
  16. use OCP\BackgroundJob\IJobList;
  17. use OCP\DB\Exception;
  18. use OCP\EventDispatcher\IEventDispatcher;
  19. use OCP\Files\AppData\IAppDataFactory;
  20. use OCP\Files\Config\IUserMountCache;
  21. use OCP\Files\File;
  22. use OCP\Files\GenericFileException;
  23. use OCP\Files\IAppData;
  24. use OCP\Files\InvalidPathException;
  25. use OCP\Files\IRootFolder;
  26. use OCP\Files\Node;
  27. use OCP\Files\NotPermittedException;
  28. use OCP\Files\SimpleFS\ISimpleFile;
  29. use OCP\Http\Client\IClientService;
  30. use OCP\IConfig;
  31. use OCP\IL10N;
  32. use OCP\IServerContainer;
  33. use OCP\L10N\IFactory;
  34. use OCP\Lock\LockedException;
  35. use OCP\SpeechToText\ISpeechToTextProvider;
  36. use OCP\SpeechToText\ISpeechToTextProviderWithId;
  37. use OCP\TaskProcessing\EShapeType;
  38. use OCP\TaskProcessing\Events\TaskFailedEvent;
  39. use OCP\TaskProcessing\Events\TaskSuccessfulEvent;
  40. use OCP\TaskProcessing\Exception\NotFoundException;
  41. use OCP\TaskProcessing\Exception\ProcessingException;
  42. use OCP\TaskProcessing\Exception\UnauthorizedException;
  43. use OCP\TaskProcessing\Exception\ValidationException;
  44. use OCP\TaskProcessing\IManager;
  45. use OCP\TaskProcessing\IProvider;
  46. use OCP\TaskProcessing\ISynchronousProvider;
  47. use OCP\TaskProcessing\ITaskType;
  48. use OCP\TaskProcessing\ShapeDescriptor;
  49. use OCP\TaskProcessing\ShapeEnumValue;
  50. use OCP\TaskProcessing\Task;
  51. use OCP\TaskProcessing\TaskTypes\AudioToText;
  52. use OCP\TaskProcessing\TaskTypes\TextToImage;
  53. use OCP\TaskProcessing\TaskTypes\TextToText;
  54. use OCP\TaskProcessing\TaskTypes\TextToTextHeadline;
  55. use OCP\TaskProcessing\TaskTypes\TextToTextSummary;
  56. use OCP\TaskProcessing\TaskTypes\TextToTextTopics;
  57. use Psr\Container\ContainerExceptionInterface;
  58. use Psr\Container\NotFoundExceptionInterface;
  59. use Psr\Log\LoggerInterface;
  60. class Manager implements IManager {
  61. public const LEGACY_PREFIX_TEXTPROCESSING = 'legacy:TextProcessing:';
  62. public const LEGACY_PREFIX_TEXTTOIMAGE = 'legacy:TextToImage:';
  63. public const LEGACY_PREFIX_SPEECHTOTEXT = 'legacy:SpeechToText:';
  64. /** @var list<IProvider>|null */
  65. private ?array $providers = null;
  66. /**
  67. * @var array<array-key,array{name: string, description: string, inputShape: ShapeDescriptor[], inputShapeEnumValues: ShapeEnumValue[][], inputShapeDefaults: array<array-key, numeric|string>, optionalInputShape: ShapeDescriptor[], optionalInputShapeEnumValues: ShapeEnumValue[][], optionalInputShapeDefaults: array<array-key, numeric|string>, outputShape: ShapeDescriptor[], outputShapeEnumValues: ShapeEnumValue[][], optionalOutputShape: ShapeDescriptor[], optionalOutputShapeEnumValues: ShapeEnumValue[][]}>
  68. */
  69. private ?array $availableTaskTypes = null;
  70. private IAppData $appData;
  71. public function __construct(
  72. private IConfig $config,
  73. private Coordinator $coordinator,
  74. private IServerContainer $serverContainer,
  75. private LoggerInterface $logger,
  76. private TaskMapper $taskMapper,
  77. private IJobList $jobList,
  78. private IEventDispatcher $dispatcher,
  79. IAppDataFactory $appDataFactory,
  80. private IRootFolder $rootFolder,
  81. private \OCP\TextToImage\IManager $textToImageManager,
  82. private IUserMountCache $userMountCache,
  83. private IClientService $clientService,
  84. private IAppManager $appManager,
  85. ) {
  86. $this->appData = $appDataFactory->get('core');
  87. }
  88. /**
  89. * This is almost a copy of textProcessingManager->getProviders
  90. * to avoid a dependency cycle between TextProcessingManager and TaskProcessingManager
  91. */
  92. private function _getRawTextProcessingProviders(): array {
  93. $context = $this->coordinator->getRegistrationContext();
  94. if ($context === null) {
  95. return [];
  96. }
  97. $providers = [];
  98. foreach ($context->getTextProcessingProviders() as $providerServiceRegistration) {
  99. $class = $providerServiceRegistration->getService();
  100. try {
  101. $providers[$class] = $this->serverContainer->get($class);
  102. } catch (\Throwable $e) {
  103. $this->logger->error('Failed to load Text processing provider ' . $class, [
  104. 'exception' => $e,
  105. ]);
  106. }
  107. }
  108. return $providers;
  109. }
  110. private function _getTextProcessingProviders(): array {
  111. $oldProviders = $this->_getRawTextProcessingProviders();
  112. $newProviders = [];
  113. foreach ($oldProviders as $oldProvider) {
  114. $provider = new class($oldProvider) implements IProvider, ISynchronousProvider {
  115. private \OCP\TextProcessing\IProvider $provider;
  116. public function __construct(\OCP\TextProcessing\IProvider $provider) {
  117. $this->provider = $provider;
  118. }
  119. public function getId(): string {
  120. if ($this->provider instanceof \OCP\TextProcessing\IProviderWithId) {
  121. return $this->provider->getId();
  122. }
  123. return Manager::LEGACY_PREFIX_TEXTPROCESSING . $this->provider::class;
  124. }
  125. public function getName(): string {
  126. return $this->provider->getName();
  127. }
  128. public function getTaskTypeId(): string {
  129. return match ($this->provider->getTaskType()) {
  130. \OCP\TextProcessing\FreePromptTaskType::class => TextToText::ID,
  131. \OCP\TextProcessing\HeadlineTaskType::class => TextToTextHeadline::ID,
  132. \OCP\TextProcessing\TopicsTaskType::class => TextToTextTopics::ID,
  133. \OCP\TextProcessing\SummaryTaskType::class => TextToTextSummary::ID,
  134. default => Manager::LEGACY_PREFIX_TEXTPROCESSING . $this->provider->getTaskType(),
  135. };
  136. }
  137. public function getExpectedRuntime(): int {
  138. if ($this->provider instanceof \OCP\TextProcessing\IProviderWithExpectedRuntime) {
  139. return $this->provider->getExpectedRuntime();
  140. }
  141. return 60;
  142. }
  143. public function getOptionalInputShape(): array {
  144. return [];
  145. }
  146. public function getOptionalOutputShape(): array {
  147. return [];
  148. }
  149. public function process(?string $userId, array $input, callable $reportProgress): array {
  150. if ($this->provider instanceof \OCP\TextProcessing\IProviderWithUserId) {
  151. $this->provider->setUserId($userId);
  152. }
  153. try {
  154. return ['output' => $this->provider->process($input['input'])];
  155. } catch (\RuntimeException $e) {
  156. throw new ProcessingException($e->getMessage(), 0, $e);
  157. }
  158. }
  159. public function getInputShapeEnumValues(): array {
  160. return [];
  161. }
  162. public function getInputShapeDefaults(): array {
  163. return [];
  164. }
  165. public function getOptionalInputShapeEnumValues(): array {
  166. return [];
  167. }
  168. public function getOptionalInputShapeDefaults(): array {
  169. return [];
  170. }
  171. public function getOutputShapeEnumValues(): array {
  172. return [];
  173. }
  174. public function getOptionalOutputShapeEnumValues(): array {
  175. return [];
  176. }
  177. };
  178. $newProviders[$provider->getId()] = $provider;
  179. }
  180. return $newProviders;
  181. }
  182. /**
  183. * @return ITaskType[]
  184. */
  185. private function _getTextProcessingTaskTypes(): array {
  186. $oldProviders = $this->_getRawTextProcessingProviders();
  187. $newTaskTypes = [];
  188. foreach ($oldProviders as $oldProvider) {
  189. // These are already implemented in the TaskProcessing realm
  190. if (in_array($oldProvider->getTaskType(), [
  191. \OCP\TextProcessing\FreePromptTaskType::class,
  192. \OCP\TextProcessing\HeadlineTaskType::class,
  193. \OCP\TextProcessing\TopicsTaskType::class,
  194. \OCP\TextProcessing\SummaryTaskType::class
  195. ], true)) {
  196. continue;
  197. }
  198. $taskType = new class($oldProvider->getTaskType()) implements ITaskType {
  199. private string $oldTaskTypeClass;
  200. private \OCP\TextProcessing\ITaskType $oldTaskType;
  201. private IL10N $l;
  202. public function __construct(string $oldTaskTypeClass) {
  203. $this->oldTaskTypeClass = $oldTaskTypeClass;
  204. $this->oldTaskType = \OCP\Server::get($oldTaskTypeClass);
  205. $this->l = \OCP\Server::get(IFactory::class)->get('core');
  206. }
  207. public function getId(): string {
  208. return Manager::LEGACY_PREFIX_TEXTPROCESSING . $this->oldTaskTypeClass;
  209. }
  210. public function getName(): string {
  211. return $this->oldTaskType->getName();
  212. }
  213. public function getDescription(): string {
  214. return $this->oldTaskType->getDescription();
  215. }
  216. public function getInputShape(): array {
  217. return ['input' => new ShapeDescriptor($this->l->t('Input text'), $this->l->t('The input text'), EShapeType::Text)];
  218. }
  219. public function getOutputShape(): array {
  220. return ['output' => new ShapeDescriptor($this->l->t('Input text'), $this->l->t('The input text'), EShapeType::Text)];
  221. }
  222. };
  223. $newTaskTypes[$taskType->getId()] = $taskType;
  224. }
  225. return $newTaskTypes;
  226. }
  227. /**
  228. * @return IProvider[]
  229. */
  230. private function _getTextToImageProviders(): array {
  231. $oldProviders = $this->textToImageManager->getProviders();
  232. $newProviders = [];
  233. foreach ($oldProviders as $oldProvider) {
  234. $newProvider = new class($oldProvider, $this->appData) implements IProvider, ISynchronousProvider {
  235. private \OCP\TextToImage\IProvider $provider;
  236. private IAppData $appData;
  237. public function __construct(\OCP\TextToImage\IProvider $provider, IAppData $appData) {
  238. $this->provider = $provider;
  239. $this->appData = $appData;
  240. }
  241. public function getId(): string {
  242. return Manager::LEGACY_PREFIX_TEXTTOIMAGE . $this->provider->getId();
  243. }
  244. public function getName(): string {
  245. return $this->provider->getName();
  246. }
  247. public function getTaskTypeId(): string {
  248. return TextToImage::ID;
  249. }
  250. public function getExpectedRuntime(): int {
  251. return $this->provider->getExpectedRuntime();
  252. }
  253. public function getOptionalInputShape(): array {
  254. return [];
  255. }
  256. public function getOptionalOutputShape(): array {
  257. return [];
  258. }
  259. public function process(?string $userId, array $input, callable $reportProgress): array {
  260. try {
  261. $folder = $this->appData->getFolder('text2image');
  262. } catch (\OCP\Files\NotFoundException) {
  263. $folder = $this->appData->newFolder('text2image');
  264. }
  265. $resources = [];
  266. $files = [];
  267. for ($i = 0; $i < $input['numberOfImages']; $i++) {
  268. $file = $folder->newFile(time() . '-' . rand(1, 100000) . '-' . $i);
  269. $files[] = $file;
  270. $resource = $file->write();
  271. if ($resource !== false && $resource !== true && is_resource($resource)) {
  272. $resources[] = $resource;
  273. } else {
  274. throw new ProcessingException('Text2Image generation using provider "' . $this->getName() . '" failed: Couldn\'t open file to write.');
  275. }
  276. }
  277. if ($this->provider instanceof \OCP\TextToImage\IProviderWithUserId) {
  278. $this->provider->setUserId($userId);
  279. }
  280. try {
  281. $this->provider->generate($input['input'], $resources);
  282. } catch (\RuntimeException $e) {
  283. throw new ProcessingException($e->getMessage(), 0, $e);
  284. }
  285. for ($i = 0; $i < $input['numberOfImages']; $i++) {
  286. if (is_resource($resources[$i])) {
  287. // If $resource hasn't been closed yet, we'll do that here
  288. fclose($resources[$i]);
  289. }
  290. }
  291. return ['images' => array_map(fn (ISimpleFile $file) => $file->getContent(), $files)];
  292. }
  293. public function getInputShapeEnumValues(): array {
  294. return [];
  295. }
  296. public function getInputShapeDefaults(): array {
  297. return [];
  298. }
  299. public function getOptionalInputShapeEnumValues(): array {
  300. return [];
  301. }
  302. public function getOptionalInputShapeDefaults(): array {
  303. return [];
  304. }
  305. public function getOutputShapeEnumValues(): array {
  306. return [];
  307. }
  308. public function getOptionalOutputShapeEnumValues(): array {
  309. return [];
  310. }
  311. };
  312. $newProviders[$newProvider->getId()] = $newProvider;
  313. }
  314. return $newProviders;
  315. }
  316. /**
  317. * This is almost a copy of SpeechToTextManager->getProviders
  318. * to avoid a dependency cycle between SpeechToTextManager and TaskProcessingManager
  319. */
  320. private function _getRawSpeechToTextProviders(): array {
  321. $context = $this->coordinator->getRegistrationContext();
  322. if ($context === null) {
  323. return [];
  324. }
  325. $providers = [];
  326. foreach ($context->getSpeechToTextProviders() as $providerServiceRegistration) {
  327. $class = $providerServiceRegistration->getService();
  328. try {
  329. $providers[$class] = $this->serverContainer->get($class);
  330. } catch (NotFoundExceptionInterface|ContainerExceptionInterface|\Throwable $e) {
  331. $this->logger->error('Failed to load SpeechToText provider ' . $class, [
  332. 'exception' => $e,
  333. ]);
  334. }
  335. }
  336. return $providers;
  337. }
  338. /**
  339. * @return IProvider[]
  340. */
  341. private function _getSpeechToTextProviders(): array {
  342. $oldProviders = $this->_getRawSpeechToTextProviders();
  343. $newProviders = [];
  344. foreach ($oldProviders as $oldProvider) {
  345. $newProvider = new class($oldProvider, $this->rootFolder, $this->appData) implements IProvider, ISynchronousProvider {
  346. private ISpeechToTextProvider $provider;
  347. private IAppData $appData;
  348. private IRootFolder $rootFolder;
  349. public function __construct(ISpeechToTextProvider $provider, IRootFolder $rootFolder, IAppData $appData) {
  350. $this->provider = $provider;
  351. $this->rootFolder = $rootFolder;
  352. $this->appData = $appData;
  353. }
  354. public function getId(): string {
  355. if ($this->provider instanceof ISpeechToTextProviderWithId) {
  356. return Manager::LEGACY_PREFIX_SPEECHTOTEXT . $this->provider->getId();
  357. }
  358. return Manager::LEGACY_PREFIX_SPEECHTOTEXT . $this->provider::class;
  359. }
  360. public function getName(): string {
  361. return $this->provider->getName();
  362. }
  363. public function getTaskTypeId(): string {
  364. return AudioToText::ID;
  365. }
  366. public function getExpectedRuntime(): int {
  367. return 60;
  368. }
  369. public function getOptionalInputShape(): array {
  370. return [];
  371. }
  372. public function getOptionalOutputShape(): array {
  373. return [];
  374. }
  375. public function process(?string $userId, array $input, callable $reportProgress): array {
  376. if ($this->provider instanceof \OCP\SpeechToText\ISpeechToTextProviderWithUserId) {
  377. $this->provider->setUserId($userId);
  378. }
  379. try {
  380. $result = $this->provider->transcribeFile($input['input']);
  381. } catch (\RuntimeException $e) {
  382. throw new ProcessingException($e->getMessage(), 0, $e);
  383. }
  384. return ['output' => $result];
  385. }
  386. public function getInputShapeEnumValues(): array {
  387. return [];
  388. }
  389. public function getInputShapeDefaults(): array {
  390. return [];
  391. }
  392. public function getOptionalInputShapeEnumValues(): array {
  393. return [];
  394. }
  395. public function getOptionalInputShapeDefaults(): array {
  396. return [];
  397. }
  398. public function getOutputShapeEnumValues(): array {
  399. return [];
  400. }
  401. public function getOptionalOutputShapeEnumValues(): array {
  402. return [];
  403. }
  404. };
  405. $newProviders[$newProvider->getId()] = $newProvider;
  406. }
  407. return $newProviders;
  408. }
  409. /**
  410. * @return IProvider[]
  411. */
  412. private function _getProviders(): array {
  413. $context = $this->coordinator->getRegistrationContext();
  414. if ($context === null) {
  415. return [];
  416. }
  417. $providers = [];
  418. foreach ($context->getTaskProcessingProviders() as $providerServiceRegistration) {
  419. $class = $providerServiceRegistration->getService();
  420. try {
  421. /** @var IProvider $provider */
  422. $provider = $this->serverContainer->get($class);
  423. if (isset($providers[$provider->getId()])) {
  424. $this->logger->warning('Task processing provider ' . $class . ' is using ID ' . $provider->getId() . ' which is already used by ' . $providers[$provider->getId()]::class);
  425. }
  426. $providers[$provider->getId()] = $provider;
  427. } catch (\Throwable $e) {
  428. $this->logger->error('Failed to load task processing provider ' . $class, [
  429. 'exception' => $e,
  430. ]);
  431. }
  432. }
  433. $providers += $this->_getTextProcessingProviders() + $this->_getTextToImageProviders() + $this->_getSpeechToTextProviders();
  434. return $providers;
  435. }
  436. /**
  437. * @return ITaskType[]
  438. */
  439. private function _getTaskTypes(): array {
  440. $context = $this->coordinator->getRegistrationContext();
  441. if ($context === null) {
  442. return [];
  443. }
  444. // Default task types
  445. $taskTypes = [
  446. \OCP\TaskProcessing\TaskTypes\TextToText::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToText::class),
  447. \OCP\TaskProcessing\TaskTypes\TextToTextTopics::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextTopics::class),
  448. \OCP\TaskProcessing\TaskTypes\TextToTextHeadline::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextHeadline::class),
  449. \OCP\TaskProcessing\TaskTypes\TextToTextSummary::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextSummary::class),
  450. \OCP\TaskProcessing\TaskTypes\TextToTextFormalization::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextFormalization::class),
  451. \OCP\TaskProcessing\TaskTypes\TextToTextSimplification::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextSimplification::class),
  452. \OCP\TaskProcessing\TaskTypes\TextToTextChat::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextChat::class),
  453. \OCP\TaskProcessing\TaskTypes\TextToTextTranslate::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextTranslate::class),
  454. \OCP\TaskProcessing\TaskTypes\TextToTextReformulation::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextReformulation::class),
  455. \OCP\TaskProcessing\TaskTypes\TextToImage::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToImage::class),
  456. \OCP\TaskProcessing\TaskTypes\AudioToText::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\AudioToText::class),
  457. \OCP\TaskProcessing\TaskTypes\ContextWrite::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\ContextWrite::class),
  458. \OCP\TaskProcessing\TaskTypes\GenerateEmoji::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\GenerateEmoji::class),
  459. ];
  460. foreach ($context->getTaskProcessingTaskTypes() as $providerServiceRegistration) {
  461. $class = $providerServiceRegistration->getService();
  462. try {
  463. /** @var ITaskType $provider */
  464. $taskType = $this->serverContainer->get($class);
  465. if (isset($taskTypes[$taskType->getId()])) {
  466. $this->logger->warning('Task processing task type ' . $class . ' is using ID ' . $taskType->getId() . ' which is already used by ' . $taskTypes[$taskType->getId()]::class);
  467. }
  468. $taskTypes[$taskType->getId()] = $taskType;
  469. } catch (\Throwable $e) {
  470. $this->logger->error('Failed to load task processing task type ' . $class, [
  471. 'exception' => $e,
  472. ]);
  473. }
  474. }
  475. $taskTypes += $this->_getTextProcessingTaskTypes();
  476. return $taskTypes;
  477. }
  478. /**
  479. * @param ShapeDescriptor[] $spec
  480. * @param array<array-key, string|numeric> $defaults
  481. * @param array<array-key, ShapeEnumValue[]> $enumValues
  482. * @param array $io
  483. * @param bool $optional
  484. * @return void
  485. * @throws ValidationException
  486. */
  487. private static function validateInput(array $spec, array $defaults, array $enumValues, array $io, bool $optional = false): void {
  488. foreach ($spec as $key => $descriptor) {
  489. $type = $descriptor->getShapeType();
  490. if (!isset($io[$key])) {
  491. if ($optional) {
  492. continue;
  493. }
  494. if (isset($defaults[$key])) {
  495. if (EShapeType::getScalarType($type) !== $type) {
  496. throw new ValidationException('Provider tried to set a default value for a non-scalar slot');
  497. }
  498. if (EShapeType::isFileType($type)) {
  499. throw new ValidationException('Provider tried to set a default value for a slot that is not text or number');
  500. }
  501. $type->validateInput($defaults[$key]);
  502. continue;
  503. }
  504. throw new ValidationException('Missing key: "' . $key . '"');
  505. }
  506. try {
  507. $type->validateInput($io[$key]);
  508. if ($type === EShapeType::Enum) {
  509. if (!isset($enumValues[$key])) {
  510. throw new ValidationException('Provider did not provide enum values for an enum slot: "' . $key . '"');
  511. }
  512. $type->validateEnum($io[$key], $enumValues[$key]);
  513. }
  514. } catch (ValidationException $e) {
  515. throw new ValidationException('Failed to validate input key "' . $key . '": ' . $e->getMessage());
  516. }
  517. }
  518. }
  519. /**
  520. * Takes task input data and replaces fileIds with File objects
  521. *
  522. * @param array<array-key, list<numeric|string>|numeric|string> $input
  523. * @param array<array-key, numeric|string> ...$defaultSpecs the specs
  524. * @return array<array-key, list<numeric|string>|numeric|string>
  525. */
  526. public function fillInputDefaults(array $input, ...$defaultSpecs): array {
  527. $spec = array_reduce($defaultSpecs, fn ($carry, $spec) => array_merge($carry, $spec), []);
  528. return array_merge($spec, $input);
  529. }
  530. /**
  531. * @param ShapeDescriptor[] $spec
  532. * @param array<array-key, ShapeEnumValue[]> $enumValues
  533. * @param array $io
  534. * @param bool $optional
  535. * @return void
  536. * @throws ValidationException
  537. */
  538. private static function validateOutputWithFileIds(array $spec, array $enumValues, array $io, bool $optional = false): void {
  539. foreach ($spec as $key => $descriptor) {
  540. $type = $descriptor->getShapeType();
  541. if (!isset($io[$key])) {
  542. if ($optional) {
  543. continue;
  544. }
  545. throw new ValidationException('Missing key: "' . $key . '"');
  546. }
  547. try {
  548. $type->validateOutputWithFileIds($io[$key]);
  549. if (isset($enumValues[$key])) {
  550. $type->validateEnum($io[$key], $enumValues[$key]);
  551. }
  552. } catch (ValidationException $e) {
  553. throw new ValidationException('Failed to validate output key "' . $key . '": ' . $e->getMessage());
  554. }
  555. }
  556. }
  557. /**
  558. * @param ShapeDescriptor[] $spec
  559. * @param array<array-key, ShapeEnumValue[]> $enumValues
  560. * @param array $io
  561. * @param bool $optional
  562. * @return void
  563. * @throws ValidationException
  564. */
  565. private static function validateOutputWithFileData(array $spec, array $enumValues, array $io, bool $optional = false): void {
  566. foreach ($spec as $key => $descriptor) {
  567. $type = $descriptor->getShapeType();
  568. if (!isset($io[$key])) {
  569. if ($optional) {
  570. continue;
  571. }
  572. throw new ValidationException('Missing key: "' . $key . '"');
  573. }
  574. try {
  575. $type->validateOutputWithFileData($io[$key]);
  576. if (isset($enumValues[$key])) {
  577. $type->validateEnum($io[$key], $enumValues[$key]);
  578. }
  579. } catch (ValidationException $e) {
  580. throw new ValidationException('Failed to validate output key "' . $key . '": ' . $e->getMessage());
  581. }
  582. }
  583. }
  584. /**
  585. * @param array<array-key, T> $array The array to filter
  586. * @param ShapeDescriptor[] ...$specs the specs that define which keys to keep
  587. * @return array<array-key, T>
  588. * @psalm-template T
  589. */
  590. private function removeSuperfluousArrayKeys(array $array, ...$specs): array {
  591. $keys = array_unique(array_reduce($specs, fn ($carry, $spec) => array_merge($carry, array_keys($spec)), []));
  592. $keys = array_filter($keys, fn ($key) => array_key_exists($key, $array));
  593. $values = array_map(fn (string $key) => $array[$key], $keys);
  594. return array_combine($keys, $values);
  595. }
  596. public function hasProviders(): bool {
  597. return count($this->getProviders()) !== 0;
  598. }
  599. public function getProviders(): array {
  600. if ($this->providers === null) {
  601. $this->providers = $this->_getProviders();
  602. }
  603. return $this->providers;
  604. }
  605. public function getPreferredProvider(string $taskTypeId) {
  606. try {
  607. $preferences = json_decode($this->config->getAppValue('core', 'ai.taskprocessing_provider_preferences', 'null'), associative: true, flags: JSON_THROW_ON_ERROR);
  608. $providers = $this->getProviders();
  609. if (isset($preferences[$taskTypeId])) {
  610. $provider = current(array_values(array_filter($providers, fn ($provider) => $provider->getId() === $preferences[$taskTypeId])));
  611. if ($provider !== false) {
  612. return $provider;
  613. }
  614. }
  615. // By default, use the first available provider
  616. foreach ($providers as $provider) {
  617. if ($provider->getTaskTypeId() === $taskTypeId) {
  618. return $provider;
  619. }
  620. }
  621. } catch (\JsonException $e) {
  622. $this->logger->warning('Failed to parse provider preferences while getting preferred provider for task type ' . $taskTypeId, ['exception' => $e]);
  623. }
  624. throw new \OCP\TaskProcessing\Exception\Exception('No matching provider found');
  625. }
  626. public function getAvailableTaskTypes(): array {
  627. if ($this->availableTaskTypes === null) {
  628. $taskTypes = $this->_getTaskTypes();
  629. $availableTaskTypes = [];
  630. foreach ($taskTypes as $taskType) {
  631. try {
  632. $provider = $this->getPreferredProvider($taskType->getId());
  633. } catch (\OCP\TaskProcessing\Exception\Exception $e) {
  634. continue;
  635. }
  636. try {
  637. $availableTaskTypes[$provider->getTaskTypeId()] = [
  638. 'name' => $taskType->getName(),
  639. 'description' => $taskType->getDescription(),
  640. 'optionalInputShape' => $provider->getOptionalInputShape(),
  641. 'inputShapeEnumValues' => $provider->getInputShapeEnumValues(),
  642. 'inputShapeDefaults' => $provider->getInputShapeDefaults(),
  643. 'inputShape' => $taskType->getInputShape(),
  644. 'optionalInputShapeEnumValues' => $provider->getOptionalInputShapeEnumValues(),
  645. 'optionalInputShapeDefaults' => $provider->getOptionalInputShapeDefaults(),
  646. 'outputShape' => $taskType->getOutputShape(),
  647. 'outputShapeEnumValues' => $provider->getOutputShapeEnumValues(),
  648. 'optionalOutputShape' => $provider->getOptionalOutputShape(),
  649. 'optionalOutputShapeEnumValues' => $provider->getOptionalOutputShapeEnumValues(),
  650. ];
  651. } catch (\Throwable $e) {
  652. $this->logger->error('Failed to set up TaskProcessing provider ' . $provider::class, ['exception' => $e]);
  653. }
  654. }
  655. $this->availableTaskTypes = $availableTaskTypes;
  656. }
  657. return $this->availableTaskTypes;
  658. }
  659. public function canHandleTask(Task $task): bool {
  660. return isset($this->getAvailableTaskTypes()[$task->getTaskTypeId()]);
  661. }
  662. public function scheduleTask(Task $task): void {
  663. if (!$this->canHandleTask($task)) {
  664. throw new \OCP\TaskProcessing\Exception\PreConditionNotMetException('No task processing provider is installed that can handle this task type: ' . $task->getTaskTypeId());
  665. }
  666. $this->prepareTask($task);
  667. $task->setStatus(Task::STATUS_SCHEDULED);
  668. $this->storeTask($task);
  669. // schedule synchronous job if the provider is synchronous
  670. $provider = $this->getPreferredProvider($task->getTaskTypeId());
  671. if ($provider instanceof ISynchronousProvider) {
  672. $this->jobList->add(SynchronousBackgroundJob::class, null);
  673. }
  674. }
  675. public function runTask(Task $task): Task {
  676. if (!$this->canHandleTask($task)) {
  677. throw new \OCP\TaskProcessing\Exception\PreConditionNotMetException('No task processing provider is installed that can handle this task type: ' . $task->getTaskTypeId());
  678. }
  679. $provider = $this->getPreferredProvider($task->getTaskTypeId());
  680. if ($provider instanceof ISynchronousProvider) {
  681. $this->prepareTask($task);
  682. $task->setStatus(Task::STATUS_SCHEDULED);
  683. $this->storeTask($task);
  684. $this->processTask($task, $provider);
  685. $task = $this->getTask($task->getId());
  686. } else {
  687. $this->scheduleTask($task);
  688. // poll task
  689. while ($task->getStatus() === Task::STATUS_SCHEDULED || $task->getStatus() === Task::STATUS_RUNNING) {
  690. sleep(1);
  691. $task = $this->getTask($task->getId());
  692. }
  693. }
  694. return $task;
  695. }
  696. public function processTask(Task $task, ISynchronousProvider $provider): bool {
  697. try {
  698. try {
  699. $input = $this->prepareInputData($task);
  700. } catch (GenericFileException|NotPermittedException|LockedException|ValidationException|UnauthorizedException $e) {
  701. $this->logger->warning('Failed to prepare input data for a TaskProcessing task with synchronous provider ' . $provider->getId(), ['exception' => $e]);
  702. $this->setTaskResult($task->getId(), $e->getMessage(), null);
  703. return false;
  704. }
  705. try {
  706. $this->setTaskStatus($task, Task::STATUS_RUNNING);
  707. $output = $provider->process($task->getUserId(), $input, fn (float $progress) => $this->setTaskProgress($task->getId(), $progress));
  708. } catch (ProcessingException $e) {
  709. $this->logger->warning('Failed to process a TaskProcessing task with synchronous provider ' . $provider->getId(), ['exception' => $e]);
  710. $this->setTaskResult($task->getId(), $e->getMessage(), null);
  711. return false;
  712. } catch (\Throwable $e) {
  713. $this->logger->error('Unknown error while processing TaskProcessing task', ['exception' => $e]);
  714. $this->setTaskResult($task->getId(), $e->getMessage(), null);
  715. return false;
  716. }
  717. $this->setTaskResult($task->getId(), null, $output);
  718. } catch (NotFoundException $e) {
  719. $this->logger->info('Could not find task anymore after execution. Moving on.', ['exception' => $e]);
  720. } catch (Exception $e) {
  721. $this->logger->error('Failed to report result of TaskProcessing task', ['exception' => $e]);
  722. }
  723. return true;
  724. }
  725. public function deleteTask(Task $task): void {
  726. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  727. $this->taskMapper->delete($taskEntity);
  728. }
  729. public function getTask(int $id): Task {
  730. try {
  731. $taskEntity = $this->taskMapper->find($id);
  732. return $taskEntity->toPublicTask();
  733. } catch (DoesNotExistException $e) {
  734. throw new NotFoundException('Couldn\'t find task with id ' . $id, 0, $e);
  735. } catch (MultipleObjectsReturnedException|\OCP\DB\Exception $e) {
  736. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  737. } catch (\JsonException $e) {
  738. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the task', 0, $e);
  739. }
  740. }
  741. public function cancelTask(int $id): void {
  742. $task = $this->getTask($id);
  743. if ($task->getStatus() !== Task::STATUS_SCHEDULED && $task->getStatus() !== Task::STATUS_RUNNING) {
  744. return;
  745. }
  746. $task->setStatus(Task::STATUS_CANCELLED);
  747. $task->setEndedAt(time());
  748. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  749. try {
  750. $this->taskMapper->update($taskEntity);
  751. $this->runWebhook($task);
  752. } catch (\OCP\DB\Exception $e) {
  753. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  754. }
  755. }
  756. public function setTaskProgress(int $id, float $progress): bool {
  757. // TODO: Not sure if we should rather catch the exceptions of getTask here and fail silently
  758. $task = $this->getTask($id);
  759. if ($task->getStatus() === Task::STATUS_CANCELLED) {
  760. return false;
  761. }
  762. // only set the start time if the task is going from scheduled to running
  763. if ($task->getstatus() === Task::STATUS_SCHEDULED) {
  764. $task->setStartedAt(time());
  765. }
  766. $task->setStatus(Task::STATUS_RUNNING);
  767. $task->setProgress($progress);
  768. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  769. try {
  770. $this->taskMapper->update($taskEntity);
  771. } catch (\OCP\DB\Exception $e) {
  772. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  773. }
  774. return true;
  775. }
  776. public function setTaskResult(int $id, ?string $error, ?array $result, bool $isUsingFileIds = false): void {
  777. // TODO: Not sure if we should rather catch the exceptions of getTask here and fail silently
  778. $task = $this->getTask($id);
  779. if ($task->getStatus() === Task::STATUS_CANCELLED) {
  780. $this->logger->info('A TaskProcessing ' . $task->getTaskTypeId() . ' task with id ' . $id . ' finished but was cancelled in the mean time. Moving on without storing result.');
  781. return;
  782. }
  783. if ($error !== null) {
  784. $task->setStatus(Task::STATUS_FAILED);
  785. $task->setEndedAt(time());
  786. // truncate error message to 1000 characters
  787. $task->setErrorMessage(mb_substr($error, 0, 1000));
  788. $this->logger->warning('A TaskProcessing ' . $task->getTaskTypeId() . ' task with id ' . $id . ' failed with the following message: ' . $error);
  789. } elseif ($result !== null) {
  790. $taskTypes = $this->getAvailableTaskTypes();
  791. $outputShape = $taskTypes[$task->getTaskTypeId()]['outputShape'];
  792. $outputShapeEnumValues = $taskTypes[$task->getTaskTypeId()]['outputShapeEnumValues'];
  793. $optionalOutputShape = $taskTypes[$task->getTaskTypeId()]['optionalOutputShape'];
  794. $optionalOutputShapeEnumValues = $taskTypes[$task->getTaskTypeId()]['optionalOutputShapeEnumValues'];
  795. try {
  796. // validate output
  797. if (!$isUsingFileIds) {
  798. $this->validateOutputWithFileData($outputShape, $outputShapeEnumValues, $result);
  799. $this->validateOutputWithFileData($optionalOutputShape, $optionalOutputShapeEnumValues, $result, true);
  800. } else {
  801. $this->validateOutputWithFileIds($outputShape, $outputShapeEnumValues, $result);
  802. $this->validateOutputWithFileIds($optionalOutputShape, $optionalOutputShapeEnumValues, $result, true);
  803. }
  804. $output = $this->removeSuperfluousArrayKeys($result, $outputShape, $optionalOutputShape);
  805. // extract raw data and put it in files, replace it with file ids
  806. if (!$isUsingFileIds) {
  807. $output = $this->encapsulateOutputFileData($output, $outputShape, $optionalOutputShape);
  808. } else {
  809. $this->validateOutputFileIds($output, $outputShape, $optionalOutputShape);
  810. }
  811. // Turn file objects into IDs
  812. foreach ($output as $key => $value) {
  813. if ($value instanceof Node) {
  814. $output[$key] = $value->getId();
  815. }
  816. if (is_array($value) && $value[0] instanceof Node) {
  817. $output[$key] = array_map(fn ($node) => $node->getId(), $value);
  818. }
  819. }
  820. $task->setOutput($output);
  821. $task->setProgress(1);
  822. $task->setStatus(Task::STATUS_SUCCESSFUL);
  823. $task->setEndedAt(time());
  824. } catch (ValidationException $e) {
  825. $task->setProgress(1);
  826. $task->setStatus(Task::STATUS_FAILED);
  827. $task->setEndedAt(time());
  828. $error = 'The task was processed successfully but the provider\'s output doesn\'t pass validation against the task type\'s outputShape spec and/or the provider\'s own optionalOutputShape spec';
  829. $task->setErrorMessage($error);
  830. $this->logger->error($error, ['exception' => $e]);
  831. } catch (NotPermittedException $e) {
  832. $task->setProgress(1);
  833. $task->setStatus(Task::STATUS_FAILED);
  834. $task->setEndedAt(time());
  835. $error = 'The task was processed successfully but storing the output in a file failed';
  836. $task->setErrorMessage($error);
  837. $this->logger->error($error, ['exception' => $e]);
  838. } catch (InvalidPathException|\OCP\Files\NotFoundException $e) {
  839. $task->setProgress(1);
  840. $task->setStatus(Task::STATUS_FAILED);
  841. $task->setEndedAt(time());
  842. $error = 'The task was processed successfully but the result file could not be found';
  843. $task->setErrorMessage($error);
  844. $this->logger->error($error, ['exception' => $e]);
  845. }
  846. }
  847. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  848. try {
  849. $this->taskMapper->update($taskEntity);
  850. $this->runWebhook($task);
  851. } catch (\OCP\DB\Exception $e) {
  852. throw new \OCP\TaskProcessing\Exception\Exception($e->getMessage());
  853. }
  854. if ($task->getStatus() === Task::STATUS_SUCCESSFUL) {
  855. $event = new TaskSuccessfulEvent($task);
  856. } else {
  857. $event = new TaskFailedEvent($task, $error);
  858. }
  859. $this->dispatcher->dispatchTyped($event);
  860. }
  861. public function getNextScheduledTask(array $taskTypeIds = [], array $taskIdsToIgnore = []): Task {
  862. try {
  863. $taskEntity = $this->taskMapper->findOldestScheduledByType($taskTypeIds, $taskIdsToIgnore);
  864. return $taskEntity->toPublicTask();
  865. } catch (DoesNotExistException $e) {
  866. throw new \OCP\TaskProcessing\Exception\NotFoundException('Could not find the task', 0, $e);
  867. } catch (\OCP\DB\Exception $e) {
  868. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  869. } catch (\JsonException $e) {
  870. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the task', 0, $e);
  871. }
  872. }
  873. /**
  874. * Takes task input data and replaces fileIds with File objects
  875. *
  876. * @param string|null $userId
  877. * @param array<array-key, list<numeric|string>|numeric|string> $input
  878. * @param ShapeDescriptor[] ...$specs the specs
  879. * @return array<array-key, list<File|numeric|string>|numeric|string|File>
  880. * @throws GenericFileException|LockedException|NotPermittedException|ValidationException|UnauthorizedException
  881. */
  882. public function fillInputFileData(?string $userId, array $input, ...$specs): array {
  883. if ($userId !== null) {
  884. \OC_Util::setupFS($userId);
  885. }
  886. $newInputOutput = [];
  887. $spec = array_reduce($specs, fn ($carry, $spec) => $carry + $spec, []);
  888. foreach ($spec as $key => $descriptor) {
  889. $type = $descriptor->getShapeType();
  890. if (!isset($input[$key])) {
  891. continue;
  892. }
  893. if (!in_array(EShapeType::getScalarType($type), [EShapeType::Image, EShapeType::Audio, EShapeType::Video, EShapeType::File], true)) {
  894. $newInputOutput[$key] = $input[$key];
  895. continue;
  896. }
  897. if (EShapeType::getScalarType($type) === $type) {
  898. // is scalar
  899. $node = $this->validateFileId((int)$input[$key]);
  900. $this->validateUserAccessToFile($input[$key], $userId);
  901. $newInputOutput[$key] = $node;
  902. } else {
  903. // is list
  904. $newInputOutput[$key] = [];
  905. foreach ($input[$key] as $item) {
  906. $node = $this->validateFileId((int)$item);
  907. $this->validateUserAccessToFile($item, $userId);
  908. $newInputOutput[$key][] = $node;
  909. }
  910. }
  911. }
  912. return $newInputOutput;
  913. }
  914. public function getUserTask(int $id, ?string $userId): Task {
  915. try {
  916. $taskEntity = $this->taskMapper->findByIdAndUser($id, $userId);
  917. return $taskEntity->toPublicTask();
  918. } catch (DoesNotExistException $e) {
  919. throw new \OCP\TaskProcessing\Exception\NotFoundException('Could not find the task', 0, $e);
  920. } catch (MultipleObjectsReturnedException|\OCP\DB\Exception $e) {
  921. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  922. } catch (\JsonException $e) {
  923. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the task', 0, $e);
  924. }
  925. }
  926. public function getUserTasks(?string $userId, ?string $taskTypeId = null, ?string $customId = null): array {
  927. try {
  928. $taskEntities = $this->taskMapper->findByUserAndTaskType($userId, $taskTypeId, $customId);
  929. return array_map(fn ($taskEntity): Task => $taskEntity->toPublicTask(), $taskEntities);
  930. } catch (\OCP\DB\Exception $e) {
  931. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the tasks', 0, $e);
  932. } catch (\JsonException $e) {
  933. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the tasks', 0, $e);
  934. }
  935. }
  936. public function getTasks(
  937. ?string $userId, ?string $taskTypeId = null, ?string $appId = null, ?string $customId = null,
  938. ?int $status = null, ?int $scheduleAfter = null, ?int $endedBefore = null,
  939. ): array {
  940. try {
  941. $taskEntities = $this->taskMapper->findTasks($userId, $taskTypeId, $appId, $customId, $status, $scheduleAfter, $endedBefore);
  942. return array_map(fn ($taskEntity): Task => $taskEntity->toPublicTask(), $taskEntities);
  943. } catch (\OCP\DB\Exception $e) {
  944. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the tasks', 0, $e);
  945. } catch (\JsonException $e) {
  946. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the tasks', 0, $e);
  947. }
  948. }
  949. public function getUserTasksByApp(?string $userId, string $appId, ?string $customId = null): array {
  950. try {
  951. $taskEntities = $this->taskMapper->findUserTasksByApp($userId, $appId, $customId);
  952. return array_map(fn ($taskEntity): Task => $taskEntity->toPublicTask(), $taskEntities);
  953. } catch (\OCP\DB\Exception $e) {
  954. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding a task', 0, $e);
  955. } catch (\JsonException $e) {
  956. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding a task', 0, $e);
  957. }
  958. }
  959. /**
  960. *Takes task input or output and replaces base64 data with file ids
  961. *
  962. * @param array $output
  963. * @param ShapeDescriptor[] ...$specs the specs that define which keys to keep
  964. * @return array
  965. * @throws NotPermittedException
  966. */
  967. public function encapsulateOutputFileData(array $output, ...$specs): array {
  968. $newOutput = [];
  969. try {
  970. $folder = $this->appData->getFolder('TaskProcessing');
  971. } catch (\OCP\Files\NotFoundException) {
  972. $folder = $this->appData->newFolder('TaskProcessing');
  973. }
  974. $spec = array_reduce($specs, fn ($carry, $spec) => $carry + $spec, []);
  975. foreach ($spec as $key => $descriptor) {
  976. $type = $descriptor->getShapeType();
  977. if (!isset($output[$key])) {
  978. continue;
  979. }
  980. if (!in_array(EShapeType::getScalarType($type), [EShapeType::Image, EShapeType::Audio, EShapeType::Video, EShapeType::File], true)) {
  981. $newOutput[$key] = $output[$key];
  982. continue;
  983. }
  984. if (EShapeType::getScalarType($type) === $type) {
  985. /** @var SimpleFile $file */
  986. $file = $folder->newFile(time() . '-' . rand(1, 100000), $output[$key]);
  987. $newOutput[$key] = $file->getId(); // polymorphic call to SimpleFile
  988. } else {
  989. $newOutput = [];
  990. foreach ($output[$key] as $item) {
  991. /** @var SimpleFile $file */
  992. $file = $folder->newFile(time() . '-' . rand(1, 100000), $item);
  993. $newOutput[$key][] = $file->getId();
  994. }
  995. }
  996. }
  997. return $newOutput;
  998. }
  999. /**
  1000. * @param Task $task
  1001. * @return array<array-key, list<numeric|string|File>|numeric|string|File>
  1002. * @throws GenericFileException
  1003. * @throws LockedException
  1004. * @throws NotPermittedException
  1005. * @throws ValidationException|UnauthorizedException
  1006. */
  1007. public function prepareInputData(Task $task): array {
  1008. $taskTypes = $this->getAvailableTaskTypes();
  1009. $inputShape = $taskTypes[$task->getTaskTypeId()]['inputShape'];
  1010. $optionalInputShape = $taskTypes[$task->getTaskTypeId()]['optionalInputShape'];
  1011. $input = $task->getInput();
  1012. $input = $this->removeSuperfluousArrayKeys($input, $inputShape, $optionalInputShape);
  1013. $input = $this->fillInputFileData($task->getUserId(), $input, $inputShape, $optionalInputShape);
  1014. return $input;
  1015. }
  1016. public function lockTask(Task $task): bool {
  1017. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  1018. if ($this->taskMapper->lockTask($taskEntity) === 0) {
  1019. return false;
  1020. }
  1021. $task->setStatus(Task::STATUS_RUNNING);
  1022. return true;
  1023. }
  1024. /**
  1025. * @throws \JsonException
  1026. * @throws Exception
  1027. */
  1028. public function setTaskStatus(Task $task, int $status): void {
  1029. $currentTaskStatus = $task->getStatus();
  1030. if ($currentTaskStatus === Task::STATUS_SCHEDULED && $status === Task::STATUS_RUNNING) {
  1031. $task->setStartedAt(time());
  1032. } elseif ($currentTaskStatus === Task::STATUS_RUNNING && ($status === Task::STATUS_FAILED || $status === Task::STATUS_CANCELLED)) {
  1033. $task->setEndedAt(time());
  1034. } elseif ($currentTaskStatus === Task::STATUS_UNKNOWN && $status === Task::STATUS_SCHEDULED) {
  1035. $task->setScheduledAt(time());
  1036. }
  1037. $task->setStatus($status);
  1038. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  1039. $this->taskMapper->update($taskEntity);
  1040. }
  1041. /**
  1042. * Validate input, fill input default values, set completionExpectedAt, set scheduledAt
  1043. *
  1044. * @param Task $task
  1045. * @return void
  1046. * @throws UnauthorizedException
  1047. * @throws ValidationException
  1048. * @throws \OCP\TaskProcessing\Exception\Exception
  1049. */
  1050. private function prepareTask(Task $task): void {
  1051. $taskTypes = $this->getAvailableTaskTypes();
  1052. $taskType = $taskTypes[$task->getTaskTypeId()];
  1053. $inputShape = $taskType['inputShape'];
  1054. $inputShapeDefaults = $taskType['inputShapeDefaults'];
  1055. $inputShapeEnumValues = $taskType['inputShapeEnumValues'];
  1056. $optionalInputShape = $taskType['optionalInputShape'];
  1057. $optionalInputShapeEnumValues = $taskType['optionalInputShapeEnumValues'];
  1058. $optionalInputShapeDefaults = $taskType['optionalInputShapeDefaults'];
  1059. // validate input
  1060. $this->validateInput($inputShape, $inputShapeDefaults, $inputShapeEnumValues, $task->getInput());
  1061. $this->validateInput($optionalInputShape, $optionalInputShapeDefaults, $optionalInputShapeEnumValues, $task->getInput(), true);
  1062. // authenticate access to mentioned files
  1063. $ids = [];
  1064. foreach ($inputShape + $optionalInputShape as $key => $descriptor) {
  1065. if (in_array(EShapeType::getScalarType($descriptor->getShapeType()), [EShapeType::File, EShapeType::Image, EShapeType::Audio, EShapeType::Video], true)) {
  1066. /** @var list<int>|int $inputSlot */
  1067. $inputSlot = $task->getInput()[$key];
  1068. if (is_array($inputSlot)) {
  1069. $ids += $inputSlot;
  1070. } else {
  1071. $ids[] = $inputSlot;
  1072. }
  1073. }
  1074. }
  1075. foreach ($ids as $fileId) {
  1076. $this->validateFileId($fileId);
  1077. $this->validateUserAccessToFile($fileId, $task->getUserId());
  1078. }
  1079. // remove superfluous keys and set input
  1080. $input = $this->removeSuperfluousArrayKeys($task->getInput(), $inputShape, $optionalInputShape);
  1081. $inputWithDefaults = $this->fillInputDefaults($input, $inputShapeDefaults, $optionalInputShapeDefaults);
  1082. $task->setInput($inputWithDefaults);
  1083. $task->setScheduledAt(time());
  1084. $provider = $this->getPreferredProvider($task->getTaskTypeId());
  1085. // calculate expected completion time
  1086. $completionExpectedAt = new \DateTime('now');
  1087. $completionExpectedAt->add(new \DateInterval('PT' . $provider->getExpectedRuntime() . 'S'));
  1088. $task->setCompletionExpectedAt($completionExpectedAt);
  1089. }
  1090. /**
  1091. * Store the task in the DB and set its ID in the \OCP\TaskProcessing\Task input param
  1092. *
  1093. * @param Task $task
  1094. * @return void
  1095. * @throws Exception
  1096. * @throws \JsonException
  1097. */
  1098. private function storeTask(Task $task): void {
  1099. // create a db entity and insert into db table
  1100. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  1101. $this->taskMapper->insert($taskEntity);
  1102. // make sure the scheduler knows the id
  1103. $task->setId($taskEntity->getId());
  1104. }
  1105. /**
  1106. * @param array $output
  1107. * @param ShapeDescriptor[] ...$specs the specs that define which keys to keep
  1108. * @return array
  1109. * @throws NotPermittedException
  1110. */
  1111. private function validateOutputFileIds(array $output, ...$specs): array {
  1112. $newOutput = [];
  1113. $spec = array_reduce($specs, fn ($carry, $spec) => $carry + $spec, []);
  1114. foreach ($spec as $key => $descriptor) {
  1115. $type = $descriptor->getShapeType();
  1116. if (!isset($output[$key])) {
  1117. continue;
  1118. }
  1119. if (!in_array(EShapeType::getScalarType($type), [EShapeType::Image, EShapeType::Audio, EShapeType::Video, EShapeType::File], true)) {
  1120. $newOutput[$key] = $output[$key];
  1121. continue;
  1122. }
  1123. if (EShapeType::getScalarType($type) === $type) {
  1124. // Is scalar file ID
  1125. $newOutput[$key] = $this->validateFileId($output[$key]);
  1126. } else {
  1127. // Is list of file IDs
  1128. $newOutput = [];
  1129. foreach ($output[$key] as $item) {
  1130. $newOutput[$key][] = $this->validateFileId($item);
  1131. }
  1132. }
  1133. }
  1134. return $newOutput;
  1135. }
  1136. /**
  1137. * @param mixed $id
  1138. * @return File
  1139. * @throws ValidationException
  1140. */
  1141. private function validateFileId(mixed $id): File {
  1142. $node = $this->rootFolder->getFirstNodeById($id);
  1143. if ($node === null) {
  1144. $node = $this->rootFolder->getFirstNodeByIdInPath($id, '/' . $this->rootFolder->getAppDataDirectoryName() . '/');
  1145. if ($node === null) {
  1146. throw new ValidationException('Could not find file ' . $id);
  1147. } elseif (!$node instanceof File) {
  1148. throw new ValidationException('File with id "' . $id . '" is not a file');
  1149. }
  1150. } elseif (!$node instanceof File) {
  1151. throw new ValidationException('File with id "' . $id . '" is not a file');
  1152. }
  1153. return $node;
  1154. }
  1155. /**
  1156. * @param mixed $fileId
  1157. * @param string|null $userId
  1158. * @return void
  1159. * @throws UnauthorizedException
  1160. */
  1161. private function validateUserAccessToFile(mixed $fileId, ?string $userId): void {
  1162. if ($userId === null) {
  1163. throw new UnauthorizedException('User does not have access to file ' . $fileId);
  1164. }
  1165. $mounts = $this->userMountCache->getMountsForFileId($fileId);
  1166. $userIds = array_map(fn ($mount) => $mount->getUser()->getUID(), $mounts);
  1167. if (!in_array($userId, $userIds)) {
  1168. throw new UnauthorizedException('User ' . $userId . ' does not have access to file ' . $fileId);
  1169. }
  1170. }
  1171. /**
  1172. * Make a request to the task's webhookUri if necessary
  1173. *
  1174. * @param Task $task
  1175. */
  1176. private function runWebhook(Task $task): void {
  1177. $uri = $task->getWebhookUri();
  1178. $method = $task->getWebhookMethod();
  1179. if (!$uri || !$method) {
  1180. return;
  1181. }
  1182. if (in_array($method, ['HTTP:GET', 'HTTP:POST', 'HTTP:PUT', 'HTTP:DELETE'], true)) {
  1183. $client = $this->clientService->newClient();
  1184. $httpMethod = preg_replace('/^HTTP:/', '', $method);
  1185. $options = [
  1186. 'timeout' => 30,
  1187. 'body' => json_encode([
  1188. 'task' => $task->jsonSerialize(),
  1189. ]),
  1190. 'headers' => ['Content-Type' => 'application/json'],
  1191. ];
  1192. try {
  1193. $client->request($httpMethod, $uri, $options);
  1194. } catch (ClientException|ServerException $e) {
  1195. $this->logger->warning('Task processing HTTP webhook failed for task ' . $task->getId() . '. Request failed', ['exception' => $e]);
  1196. } catch (\Exception|\Throwable $e) {
  1197. $this->logger->warning('Task processing HTTP webhook failed for task ' . $task->getId() . '. Unknown error', ['exception' => $e]);
  1198. }
  1199. } elseif (str_starts_with($method, 'AppAPI:') && str_starts_with($uri, '/')) {
  1200. $parsedMethod = explode(':', $method, 4);
  1201. if (count($parsedMethod) < 3) {
  1202. $this->logger->warning('Task processing AppAPI webhook failed for task ' . $task->getId() . '. Invalid method: ' . $method);
  1203. }
  1204. [, $exAppId, $httpMethod] = $parsedMethod;
  1205. if (!$this->appManager->isInstalled('app_api')) {
  1206. $this->logger->warning('Task processing AppAPI webhook failed for task ' . $task->getId() . '. AppAPI is disabled or not installed.');
  1207. return;
  1208. }
  1209. try {
  1210. $appApiFunctions = \OCP\Server::get(\OCA\AppAPI\PublicFunctions::class);
  1211. } catch (ContainerExceptionInterface|NotFoundExceptionInterface) {
  1212. $this->logger->warning('Task processing AppAPI webhook failed for task ' . $task->getId() . '. Could not get AppAPI public functions.');
  1213. return;
  1214. }
  1215. $exApp = $appApiFunctions->getExApp($exAppId);
  1216. if ($exApp === null) {
  1217. $this->logger->warning('Task processing AppAPI webhook failed for task ' . $task->getId() . '. ExApp ' . $exAppId . ' is missing.');
  1218. return;
  1219. } elseif (!$exApp['enabled']) {
  1220. $this->logger->warning('Task processing AppAPI webhook failed for task ' . $task->getId() . '. ExApp ' . $exAppId . ' is disabled.');
  1221. return;
  1222. }
  1223. $requestParams = [
  1224. 'task' => $task->jsonSerialize(),
  1225. ];
  1226. $requestOptions = [
  1227. 'timeout' => 30,
  1228. ];
  1229. $response = $appApiFunctions->exAppRequest($exAppId, $uri, $task->getUserId(), $httpMethod, $requestParams, $requestOptions);
  1230. if (is_array($response) && isset($response['error'])) {
  1231. $this->logger->warning('Task processing AppAPI webhook failed for task ' . $task->getId() . '. Error during request to ExApp(' . $exAppId . '): ', $response['error']);
  1232. }
  1233. }
  1234. }
  1235. }