Manager.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  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. \OCP\TaskProcessing\TaskTypes\TextToTextChangeTone::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextChangeTone::class),
  460. \OCP\TaskProcessing\TaskTypes\TextToTextChatWithTools::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextChatWithTools::class),
  461. \OCP\TaskProcessing\TaskTypes\ContextAgentInteraction::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\ContextAgentInteraction::class),
  462. ];
  463. foreach ($context->getTaskProcessingTaskTypes() as $providerServiceRegistration) {
  464. $class = $providerServiceRegistration->getService();
  465. try {
  466. /** @var ITaskType $provider */
  467. $taskType = $this->serverContainer->get($class);
  468. if (isset($taskTypes[$taskType->getId()])) {
  469. $this->logger->warning('Task processing task type ' . $class . ' is using ID ' . $taskType->getId() . ' which is already used by ' . $taskTypes[$taskType->getId()]::class);
  470. }
  471. $taskTypes[$taskType->getId()] = $taskType;
  472. } catch (\Throwable $e) {
  473. $this->logger->error('Failed to load task processing task type ' . $class, [
  474. 'exception' => $e,
  475. ]);
  476. }
  477. }
  478. $taskTypes += $this->_getTextProcessingTaskTypes();
  479. return $taskTypes;
  480. }
  481. /**
  482. * @param ShapeDescriptor[] $spec
  483. * @param array<array-key, string|numeric> $defaults
  484. * @param array<array-key, ShapeEnumValue[]> $enumValues
  485. * @param array $io
  486. * @param bool $optional
  487. * @return void
  488. * @throws ValidationException
  489. */
  490. private static function validateInput(array $spec, array $defaults, array $enumValues, array $io, bool $optional = false): void {
  491. foreach ($spec as $key => $descriptor) {
  492. $type = $descriptor->getShapeType();
  493. if (!isset($io[$key])) {
  494. if ($optional) {
  495. continue;
  496. }
  497. if (isset($defaults[$key])) {
  498. if (EShapeType::getScalarType($type) !== $type) {
  499. throw new ValidationException('Provider tried to set a default value for a non-scalar slot');
  500. }
  501. if (EShapeType::isFileType($type)) {
  502. throw new ValidationException('Provider tried to set a default value for a slot that is not text or number');
  503. }
  504. $type->validateInput($defaults[$key]);
  505. continue;
  506. }
  507. throw new ValidationException('Missing key: "' . $key . '"');
  508. }
  509. try {
  510. $type->validateInput($io[$key]);
  511. if ($type === EShapeType::Enum) {
  512. if (!isset($enumValues[$key])) {
  513. throw new ValidationException('Provider did not provide enum values for an enum slot: "' . $key . '"');
  514. }
  515. $type->validateEnum($io[$key], $enumValues[$key]);
  516. }
  517. } catch (ValidationException $e) {
  518. throw new ValidationException('Failed to validate input key "' . $key . '": ' . $e->getMessage());
  519. }
  520. }
  521. }
  522. /**
  523. * Takes task input data and replaces fileIds with File objects
  524. *
  525. * @param array<array-key, list<numeric|string>|numeric|string> $input
  526. * @param array<array-key, numeric|string> ...$defaultSpecs the specs
  527. * @return array<array-key, list<numeric|string>|numeric|string>
  528. */
  529. public function fillInputDefaults(array $input, ...$defaultSpecs): array {
  530. $spec = array_reduce($defaultSpecs, fn ($carry, $spec) => array_merge($carry, $spec), []);
  531. return array_merge($spec, $input);
  532. }
  533. /**
  534. * @param ShapeDescriptor[] $spec
  535. * @param array<array-key, ShapeEnumValue[]> $enumValues
  536. * @param array $io
  537. * @param bool $optional
  538. * @return void
  539. * @throws ValidationException
  540. */
  541. private static function validateOutputWithFileIds(array $spec, array $enumValues, array $io, bool $optional = false): void {
  542. foreach ($spec as $key => $descriptor) {
  543. $type = $descriptor->getShapeType();
  544. if (!isset($io[$key])) {
  545. if ($optional) {
  546. continue;
  547. }
  548. throw new ValidationException('Missing key: "' . $key . '"');
  549. }
  550. try {
  551. $type->validateOutputWithFileIds($io[$key]);
  552. if (isset($enumValues[$key])) {
  553. $type->validateEnum($io[$key], $enumValues[$key]);
  554. }
  555. } catch (ValidationException $e) {
  556. throw new ValidationException('Failed to validate output key "' . $key . '": ' . $e->getMessage());
  557. }
  558. }
  559. }
  560. /**
  561. * @param ShapeDescriptor[] $spec
  562. * @param array<array-key, ShapeEnumValue[]> $enumValues
  563. * @param array $io
  564. * @param bool $optional
  565. * @return void
  566. * @throws ValidationException
  567. */
  568. private static function validateOutputWithFileData(array $spec, array $enumValues, array $io, bool $optional = false): void {
  569. foreach ($spec as $key => $descriptor) {
  570. $type = $descriptor->getShapeType();
  571. if (!isset($io[$key])) {
  572. if ($optional) {
  573. continue;
  574. }
  575. throw new ValidationException('Missing key: "' . $key . '"');
  576. }
  577. try {
  578. $type->validateOutputWithFileData($io[$key]);
  579. if (isset($enumValues[$key])) {
  580. $type->validateEnum($io[$key], $enumValues[$key]);
  581. }
  582. } catch (ValidationException $e) {
  583. throw new ValidationException('Failed to validate output key "' . $key . '": ' . $e->getMessage());
  584. }
  585. }
  586. }
  587. /**
  588. * @param array<array-key, T> $array The array to filter
  589. * @param ShapeDescriptor[] ...$specs the specs that define which keys to keep
  590. * @return array<array-key, T>
  591. * @psalm-template T
  592. */
  593. private function removeSuperfluousArrayKeys(array $array, ...$specs): array {
  594. $keys = array_unique(array_reduce($specs, fn ($carry, $spec) => array_merge($carry, array_keys($spec)), []));
  595. $keys = array_filter($keys, fn ($key) => array_key_exists($key, $array));
  596. $values = array_map(fn (string $key) => $array[$key], $keys);
  597. return array_combine($keys, $values);
  598. }
  599. public function hasProviders(): bool {
  600. return count($this->getProviders()) !== 0;
  601. }
  602. public function getProviders(): array {
  603. if ($this->providers === null) {
  604. $this->providers = $this->_getProviders();
  605. }
  606. return $this->providers;
  607. }
  608. public function getPreferredProvider(string $taskTypeId) {
  609. try {
  610. $preferences = json_decode($this->config->getAppValue('core', 'ai.taskprocessing_provider_preferences', 'null'), associative: true, flags: JSON_THROW_ON_ERROR);
  611. $providers = $this->getProviders();
  612. if (isset($preferences[$taskTypeId])) {
  613. $provider = current(array_values(array_filter($providers, fn ($provider) => $provider->getId() === $preferences[$taskTypeId])));
  614. if ($provider !== false) {
  615. return $provider;
  616. }
  617. }
  618. // By default, use the first available provider
  619. foreach ($providers as $provider) {
  620. if ($provider->getTaskTypeId() === $taskTypeId) {
  621. return $provider;
  622. }
  623. }
  624. } catch (\JsonException $e) {
  625. $this->logger->warning('Failed to parse provider preferences while getting preferred provider for task type ' . $taskTypeId, ['exception' => $e]);
  626. }
  627. throw new \OCP\TaskProcessing\Exception\Exception('No matching provider found');
  628. }
  629. public function getAvailableTaskTypes(): array {
  630. if ($this->availableTaskTypes === null) {
  631. $taskTypes = $this->_getTaskTypes();
  632. $availableTaskTypes = [];
  633. foreach ($taskTypes as $taskType) {
  634. try {
  635. $provider = $this->getPreferredProvider($taskType->getId());
  636. } catch (\OCP\TaskProcessing\Exception\Exception $e) {
  637. continue;
  638. }
  639. try {
  640. $availableTaskTypes[$provider->getTaskTypeId()] = [
  641. 'name' => $taskType->getName(),
  642. 'description' => $taskType->getDescription(),
  643. 'optionalInputShape' => $provider->getOptionalInputShape(),
  644. 'inputShapeEnumValues' => $provider->getInputShapeEnumValues(),
  645. 'inputShapeDefaults' => $provider->getInputShapeDefaults(),
  646. 'inputShape' => $taskType->getInputShape(),
  647. 'optionalInputShapeEnumValues' => $provider->getOptionalInputShapeEnumValues(),
  648. 'optionalInputShapeDefaults' => $provider->getOptionalInputShapeDefaults(),
  649. 'outputShape' => $taskType->getOutputShape(),
  650. 'outputShapeEnumValues' => $provider->getOutputShapeEnumValues(),
  651. 'optionalOutputShape' => $provider->getOptionalOutputShape(),
  652. 'optionalOutputShapeEnumValues' => $provider->getOptionalOutputShapeEnumValues(),
  653. ];
  654. } catch (\Throwable $e) {
  655. $this->logger->error('Failed to set up TaskProcessing provider ' . $provider::class, ['exception' => $e]);
  656. }
  657. }
  658. $this->availableTaskTypes = $availableTaskTypes;
  659. }
  660. return $this->availableTaskTypes;
  661. }
  662. public function canHandleTask(Task $task): bool {
  663. return isset($this->getAvailableTaskTypes()[$task->getTaskTypeId()]);
  664. }
  665. public function scheduleTask(Task $task): void {
  666. if (!$this->canHandleTask($task)) {
  667. throw new \OCP\TaskProcessing\Exception\PreConditionNotMetException('No task processing provider is installed that can handle this task type: ' . $task->getTaskTypeId());
  668. }
  669. $this->prepareTask($task);
  670. $task->setStatus(Task::STATUS_SCHEDULED);
  671. $this->storeTask($task);
  672. // schedule synchronous job if the provider is synchronous
  673. $provider = $this->getPreferredProvider($task->getTaskTypeId());
  674. if ($provider instanceof ISynchronousProvider) {
  675. $this->jobList->add(SynchronousBackgroundJob::class, null);
  676. }
  677. }
  678. public function runTask(Task $task): Task {
  679. if (!$this->canHandleTask($task)) {
  680. throw new \OCP\TaskProcessing\Exception\PreConditionNotMetException('No task processing provider is installed that can handle this task type: ' . $task->getTaskTypeId());
  681. }
  682. $provider = $this->getPreferredProvider($task->getTaskTypeId());
  683. if ($provider instanceof ISynchronousProvider) {
  684. $this->prepareTask($task);
  685. $task->setStatus(Task::STATUS_SCHEDULED);
  686. $this->storeTask($task);
  687. $this->processTask($task, $provider);
  688. $task = $this->getTask($task->getId());
  689. } else {
  690. $this->scheduleTask($task);
  691. // poll task
  692. while ($task->getStatus() === Task::STATUS_SCHEDULED || $task->getStatus() === Task::STATUS_RUNNING) {
  693. sleep(1);
  694. $task = $this->getTask($task->getId());
  695. }
  696. }
  697. return $task;
  698. }
  699. public function processTask(Task $task, ISynchronousProvider $provider): bool {
  700. try {
  701. try {
  702. $input = $this->prepareInputData($task);
  703. } catch (GenericFileException|NotPermittedException|LockedException|ValidationException|UnauthorizedException $e) {
  704. $this->logger->warning('Failed to prepare input data for a TaskProcessing task with synchronous provider ' . $provider->getId(), ['exception' => $e]);
  705. $this->setTaskResult($task->getId(), $e->getMessage(), null);
  706. return false;
  707. }
  708. try {
  709. $this->setTaskStatus($task, Task::STATUS_RUNNING);
  710. $output = $provider->process($task->getUserId(), $input, fn (float $progress) => $this->setTaskProgress($task->getId(), $progress));
  711. } catch (ProcessingException $e) {
  712. $this->logger->warning('Failed to process a TaskProcessing task with synchronous provider ' . $provider->getId(), ['exception' => $e]);
  713. $this->setTaskResult($task->getId(), $e->getMessage(), null);
  714. return false;
  715. } catch (\Throwable $e) {
  716. $this->logger->error('Unknown error while processing TaskProcessing task', ['exception' => $e]);
  717. $this->setTaskResult($task->getId(), $e->getMessage(), null);
  718. return false;
  719. }
  720. $this->setTaskResult($task->getId(), null, $output);
  721. } catch (NotFoundException $e) {
  722. $this->logger->info('Could not find task anymore after execution. Moving on.', ['exception' => $e]);
  723. } catch (Exception $e) {
  724. $this->logger->error('Failed to report result of TaskProcessing task', ['exception' => $e]);
  725. }
  726. return true;
  727. }
  728. public function deleteTask(Task $task): void {
  729. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  730. $this->taskMapper->delete($taskEntity);
  731. }
  732. public function getTask(int $id): Task {
  733. try {
  734. $taskEntity = $this->taskMapper->find($id);
  735. return $taskEntity->toPublicTask();
  736. } catch (DoesNotExistException $e) {
  737. throw new NotFoundException('Couldn\'t find task with id ' . $id, 0, $e);
  738. } catch (MultipleObjectsReturnedException|\OCP\DB\Exception $e) {
  739. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  740. } catch (\JsonException $e) {
  741. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the task', 0, $e);
  742. }
  743. }
  744. public function cancelTask(int $id): void {
  745. $task = $this->getTask($id);
  746. if ($task->getStatus() !== Task::STATUS_SCHEDULED && $task->getStatus() !== Task::STATUS_RUNNING) {
  747. return;
  748. }
  749. $task->setStatus(Task::STATUS_CANCELLED);
  750. $task->setEndedAt(time());
  751. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  752. try {
  753. $this->taskMapper->update($taskEntity);
  754. $this->runWebhook($task);
  755. } catch (\OCP\DB\Exception $e) {
  756. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  757. }
  758. }
  759. public function setTaskProgress(int $id, float $progress): bool {
  760. // TODO: Not sure if we should rather catch the exceptions of getTask here and fail silently
  761. $task = $this->getTask($id);
  762. if ($task->getStatus() === Task::STATUS_CANCELLED) {
  763. return false;
  764. }
  765. // only set the start time if the task is going from scheduled to running
  766. if ($task->getstatus() === Task::STATUS_SCHEDULED) {
  767. $task->setStartedAt(time());
  768. }
  769. $task->setStatus(Task::STATUS_RUNNING);
  770. $task->setProgress($progress);
  771. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  772. try {
  773. $this->taskMapper->update($taskEntity);
  774. } catch (\OCP\DB\Exception $e) {
  775. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  776. }
  777. return true;
  778. }
  779. public function setTaskResult(int $id, ?string $error, ?array $result, bool $isUsingFileIds = false): void {
  780. // TODO: Not sure if we should rather catch the exceptions of getTask here and fail silently
  781. $task = $this->getTask($id);
  782. if ($task->getStatus() === Task::STATUS_CANCELLED) {
  783. $this->logger->info('A TaskProcessing ' . $task->getTaskTypeId() . ' task with id ' . $id . ' finished but was cancelled in the mean time. Moving on without storing result.');
  784. return;
  785. }
  786. if ($error !== null) {
  787. $task->setStatus(Task::STATUS_FAILED);
  788. $task->setEndedAt(time());
  789. // truncate error message to 1000 characters
  790. $task->setErrorMessage(mb_substr($error, 0, 1000));
  791. $this->logger->warning('A TaskProcessing ' . $task->getTaskTypeId() . ' task with id ' . $id . ' failed with the following message: ' . $error);
  792. } elseif ($result !== null) {
  793. $taskTypes = $this->getAvailableTaskTypes();
  794. $outputShape = $taskTypes[$task->getTaskTypeId()]['outputShape'];
  795. $outputShapeEnumValues = $taskTypes[$task->getTaskTypeId()]['outputShapeEnumValues'];
  796. $optionalOutputShape = $taskTypes[$task->getTaskTypeId()]['optionalOutputShape'];
  797. $optionalOutputShapeEnumValues = $taskTypes[$task->getTaskTypeId()]['optionalOutputShapeEnumValues'];
  798. try {
  799. // validate output
  800. if (!$isUsingFileIds) {
  801. $this->validateOutputWithFileData($outputShape, $outputShapeEnumValues, $result);
  802. $this->validateOutputWithFileData($optionalOutputShape, $optionalOutputShapeEnumValues, $result, true);
  803. } else {
  804. $this->validateOutputWithFileIds($outputShape, $outputShapeEnumValues, $result);
  805. $this->validateOutputWithFileIds($optionalOutputShape, $optionalOutputShapeEnumValues, $result, true);
  806. }
  807. $output = $this->removeSuperfluousArrayKeys($result, $outputShape, $optionalOutputShape);
  808. // extract raw data and put it in files, replace it with file ids
  809. if (!$isUsingFileIds) {
  810. $output = $this->encapsulateOutputFileData($output, $outputShape, $optionalOutputShape);
  811. } else {
  812. $this->validateOutputFileIds($output, $outputShape, $optionalOutputShape);
  813. }
  814. // Turn file objects into IDs
  815. foreach ($output as $key => $value) {
  816. if ($value instanceof Node) {
  817. $output[$key] = $value->getId();
  818. }
  819. if (is_array($value) && isset($value[0]) && $value[0] instanceof Node) {
  820. $output[$key] = array_map(fn ($node) => $node->getId(), $value);
  821. }
  822. }
  823. $task->setOutput($output);
  824. $task->setProgress(1);
  825. $task->setStatus(Task::STATUS_SUCCESSFUL);
  826. $task->setEndedAt(time());
  827. } catch (ValidationException $e) {
  828. $task->setProgress(1);
  829. $task->setStatus(Task::STATUS_FAILED);
  830. $task->setEndedAt(time());
  831. $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';
  832. $task->setErrorMessage($error);
  833. $this->logger->error($error, ['exception' => $e]);
  834. } catch (NotPermittedException $e) {
  835. $task->setProgress(1);
  836. $task->setStatus(Task::STATUS_FAILED);
  837. $task->setEndedAt(time());
  838. $error = 'The task was processed successfully but storing the output in a file failed';
  839. $task->setErrorMessage($error);
  840. $this->logger->error($error, ['exception' => $e]);
  841. } catch (InvalidPathException|\OCP\Files\NotFoundException $e) {
  842. $task->setProgress(1);
  843. $task->setStatus(Task::STATUS_FAILED);
  844. $task->setEndedAt(time());
  845. $error = 'The task was processed successfully but the result file could not be found';
  846. $task->setErrorMessage($error);
  847. $this->logger->error($error, ['exception' => $e]);
  848. }
  849. }
  850. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  851. try {
  852. $this->taskMapper->update($taskEntity);
  853. $this->runWebhook($task);
  854. } catch (\OCP\DB\Exception $e) {
  855. throw new \OCP\TaskProcessing\Exception\Exception($e->getMessage());
  856. }
  857. if ($task->getStatus() === Task::STATUS_SUCCESSFUL) {
  858. $event = new TaskSuccessfulEvent($task);
  859. } else {
  860. $event = new TaskFailedEvent($task, $error);
  861. }
  862. $this->dispatcher->dispatchTyped($event);
  863. }
  864. public function getNextScheduledTask(array $taskTypeIds = [], array $taskIdsToIgnore = []): Task {
  865. try {
  866. $taskEntity = $this->taskMapper->findOldestScheduledByType($taskTypeIds, $taskIdsToIgnore);
  867. return $taskEntity->toPublicTask();
  868. } catch (DoesNotExistException $e) {
  869. throw new \OCP\TaskProcessing\Exception\NotFoundException('Could not find the task', 0, $e);
  870. } catch (\OCP\DB\Exception $e) {
  871. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  872. } catch (\JsonException $e) {
  873. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the task', 0, $e);
  874. }
  875. }
  876. /**
  877. * Takes task input data and replaces fileIds with File objects
  878. *
  879. * @param string|null $userId
  880. * @param array<array-key, list<numeric|string>|numeric|string> $input
  881. * @param ShapeDescriptor[] ...$specs the specs
  882. * @return array<array-key, list<File|numeric|string>|numeric|string|File>
  883. * @throws GenericFileException|LockedException|NotPermittedException|ValidationException|UnauthorizedException
  884. */
  885. public function fillInputFileData(?string $userId, array $input, ...$specs): array {
  886. if ($userId !== null) {
  887. \OC_Util::setupFS($userId);
  888. }
  889. $newInputOutput = [];
  890. $spec = array_reduce($specs, fn ($carry, $spec) => $carry + $spec, []);
  891. foreach ($spec as $key => $descriptor) {
  892. $type = $descriptor->getShapeType();
  893. if (!isset($input[$key])) {
  894. continue;
  895. }
  896. if (!in_array(EShapeType::getScalarType($type), [EShapeType::Image, EShapeType::Audio, EShapeType::Video, EShapeType::File], true)) {
  897. $newInputOutput[$key] = $input[$key];
  898. continue;
  899. }
  900. if (EShapeType::getScalarType($type) === $type) {
  901. // is scalar
  902. $node = $this->validateFileId((int)$input[$key]);
  903. $this->validateUserAccessToFile($input[$key], $userId);
  904. $newInputOutput[$key] = $node;
  905. } else {
  906. // is list
  907. $newInputOutput[$key] = [];
  908. foreach ($input[$key] as $item) {
  909. $node = $this->validateFileId((int)$item);
  910. $this->validateUserAccessToFile($item, $userId);
  911. $newInputOutput[$key][] = $node;
  912. }
  913. }
  914. }
  915. return $newInputOutput;
  916. }
  917. public function getUserTask(int $id, ?string $userId): Task {
  918. try {
  919. $taskEntity = $this->taskMapper->findByIdAndUser($id, $userId);
  920. return $taskEntity->toPublicTask();
  921. } catch (DoesNotExistException $e) {
  922. throw new \OCP\TaskProcessing\Exception\NotFoundException('Could not find the task', 0, $e);
  923. } catch (MultipleObjectsReturnedException|\OCP\DB\Exception $e) {
  924. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  925. } catch (\JsonException $e) {
  926. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the task', 0, $e);
  927. }
  928. }
  929. public function getUserTasks(?string $userId, ?string $taskTypeId = null, ?string $customId = null): array {
  930. try {
  931. $taskEntities = $this->taskMapper->findByUserAndTaskType($userId, $taskTypeId, $customId);
  932. return array_map(fn ($taskEntity): Task => $taskEntity->toPublicTask(), $taskEntities);
  933. } catch (\OCP\DB\Exception $e) {
  934. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the tasks', 0, $e);
  935. } catch (\JsonException $e) {
  936. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the tasks', 0, $e);
  937. }
  938. }
  939. public function getTasks(
  940. ?string $userId, ?string $taskTypeId = null, ?string $appId = null, ?string $customId = null,
  941. ?int $status = null, ?int $scheduleAfter = null, ?int $endedBefore = null,
  942. ): array {
  943. try {
  944. $taskEntities = $this->taskMapper->findTasks($userId, $taskTypeId, $appId, $customId, $status, $scheduleAfter, $endedBefore);
  945. return array_map(fn ($taskEntity): Task => $taskEntity->toPublicTask(), $taskEntities);
  946. } catch (\OCP\DB\Exception $e) {
  947. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the tasks', 0, $e);
  948. } catch (\JsonException $e) {
  949. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the tasks', 0, $e);
  950. }
  951. }
  952. public function getUserTasksByApp(?string $userId, string $appId, ?string $customId = null): array {
  953. try {
  954. $taskEntities = $this->taskMapper->findUserTasksByApp($userId, $appId, $customId);
  955. return array_map(fn ($taskEntity): Task => $taskEntity->toPublicTask(), $taskEntities);
  956. } catch (\OCP\DB\Exception $e) {
  957. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding a task', 0, $e);
  958. } catch (\JsonException $e) {
  959. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding a task', 0, $e);
  960. }
  961. }
  962. /**
  963. *Takes task input or output and replaces base64 data with file ids
  964. *
  965. * @param array $output
  966. * @param ShapeDescriptor[] ...$specs the specs that define which keys to keep
  967. * @return array
  968. * @throws NotPermittedException
  969. */
  970. public function encapsulateOutputFileData(array $output, ...$specs): array {
  971. $newOutput = [];
  972. try {
  973. $folder = $this->appData->getFolder('TaskProcessing');
  974. } catch (\OCP\Files\NotFoundException) {
  975. $folder = $this->appData->newFolder('TaskProcessing');
  976. }
  977. $spec = array_reduce($specs, fn ($carry, $spec) => $carry + $spec, []);
  978. foreach ($spec as $key => $descriptor) {
  979. $type = $descriptor->getShapeType();
  980. if (!isset($output[$key])) {
  981. continue;
  982. }
  983. if (!in_array(EShapeType::getScalarType($type), [EShapeType::Image, EShapeType::Audio, EShapeType::Video, EShapeType::File], true)) {
  984. $newOutput[$key] = $output[$key];
  985. continue;
  986. }
  987. if (EShapeType::getScalarType($type) === $type) {
  988. /** @var SimpleFile $file */
  989. $file = $folder->newFile(time() . '-' . rand(1, 100000), $output[$key]);
  990. $newOutput[$key] = $file->getId(); // polymorphic call to SimpleFile
  991. } else {
  992. $newOutput = [];
  993. foreach ($output[$key] as $item) {
  994. /** @var SimpleFile $file */
  995. $file = $folder->newFile(time() . '-' . rand(1, 100000), $item);
  996. $newOutput[$key][] = $file->getId();
  997. }
  998. }
  999. }
  1000. return $newOutput;
  1001. }
  1002. /**
  1003. * @param Task $task
  1004. * @return array<array-key, list<numeric|string|File>|numeric|string|File>
  1005. * @throws GenericFileException
  1006. * @throws LockedException
  1007. * @throws NotPermittedException
  1008. * @throws ValidationException|UnauthorizedException
  1009. */
  1010. public function prepareInputData(Task $task): array {
  1011. $taskTypes = $this->getAvailableTaskTypes();
  1012. $inputShape = $taskTypes[$task->getTaskTypeId()]['inputShape'];
  1013. $optionalInputShape = $taskTypes[$task->getTaskTypeId()]['optionalInputShape'];
  1014. $input = $task->getInput();
  1015. $input = $this->removeSuperfluousArrayKeys($input, $inputShape, $optionalInputShape);
  1016. $input = $this->fillInputFileData($task->getUserId(), $input, $inputShape, $optionalInputShape);
  1017. return $input;
  1018. }
  1019. public function lockTask(Task $task): bool {
  1020. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  1021. if ($this->taskMapper->lockTask($taskEntity) === 0) {
  1022. return false;
  1023. }
  1024. $task->setStatus(Task::STATUS_RUNNING);
  1025. return true;
  1026. }
  1027. /**
  1028. * @throws \JsonException
  1029. * @throws Exception
  1030. */
  1031. public function setTaskStatus(Task $task, int $status): void {
  1032. $currentTaskStatus = $task->getStatus();
  1033. if ($currentTaskStatus === Task::STATUS_SCHEDULED && $status === Task::STATUS_RUNNING) {
  1034. $task->setStartedAt(time());
  1035. } elseif ($currentTaskStatus === Task::STATUS_RUNNING && ($status === Task::STATUS_FAILED || $status === Task::STATUS_CANCELLED)) {
  1036. $task->setEndedAt(time());
  1037. } elseif ($currentTaskStatus === Task::STATUS_UNKNOWN && $status === Task::STATUS_SCHEDULED) {
  1038. $task->setScheduledAt(time());
  1039. }
  1040. $task->setStatus($status);
  1041. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  1042. $this->taskMapper->update($taskEntity);
  1043. }
  1044. /**
  1045. * Validate input, fill input default values, set completionExpectedAt, set scheduledAt
  1046. *
  1047. * @param Task $task
  1048. * @return void
  1049. * @throws UnauthorizedException
  1050. * @throws ValidationException
  1051. * @throws \OCP\TaskProcessing\Exception\Exception
  1052. */
  1053. private function prepareTask(Task $task): void {
  1054. $taskTypes = $this->getAvailableTaskTypes();
  1055. $taskType = $taskTypes[$task->getTaskTypeId()];
  1056. $inputShape = $taskType['inputShape'];
  1057. $inputShapeDefaults = $taskType['inputShapeDefaults'];
  1058. $inputShapeEnumValues = $taskType['inputShapeEnumValues'];
  1059. $optionalInputShape = $taskType['optionalInputShape'];
  1060. $optionalInputShapeEnumValues = $taskType['optionalInputShapeEnumValues'];
  1061. $optionalInputShapeDefaults = $taskType['optionalInputShapeDefaults'];
  1062. // validate input
  1063. $this->validateInput($inputShape, $inputShapeDefaults, $inputShapeEnumValues, $task->getInput());
  1064. $this->validateInput($optionalInputShape, $optionalInputShapeDefaults, $optionalInputShapeEnumValues, $task->getInput(), true);
  1065. // authenticate access to mentioned files
  1066. $ids = [];
  1067. foreach ($inputShape + $optionalInputShape as $key => $descriptor) {
  1068. if (in_array(EShapeType::getScalarType($descriptor->getShapeType()), [EShapeType::File, EShapeType::Image, EShapeType::Audio, EShapeType::Video], true)) {
  1069. /** @var list<int>|int $inputSlot */
  1070. $inputSlot = $task->getInput()[$key];
  1071. if (is_array($inputSlot)) {
  1072. $ids += $inputSlot;
  1073. } else {
  1074. $ids[] = $inputSlot;
  1075. }
  1076. }
  1077. }
  1078. foreach ($ids as $fileId) {
  1079. $this->validateFileId($fileId);
  1080. $this->validateUserAccessToFile($fileId, $task->getUserId());
  1081. }
  1082. // remove superfluous keys and set input
  1083. $input = $this->removeSuperfluousArrayKeys($task->getInput(), $inputShape, $optionalInputShape);
  1084. $inputWithDefaults = $this->fillInputDefaults($input, $inputShapeDefaults, $optionalInputShapeDefaults);
  1085. $task->setInput($inputWithDefaults);
  1086. $task->setScheduledAt(time());
  1087. $provider = $this->getPreferredProvider($task->getTaskTypeId());
  1088. // calculate expected completion time
  1089. $completionExpectedAt = new \DateTime('now');
  1090. $completionExpectedAt->add(new \DateInterval('PT' . $provider->getExpectedRuntime() . 'S'));
  1091. $task->setCompletionExpectedAt($completionExpectedAt);
  1092. }
  1093. /**
  1094. * Store the task in the DB and set its ID in the \OCP\TaskProcessing\Task input param
  1095. *
  1096. * @param Task $task
  1097. * @return void
  1098. * @throws Exception
  1099. * @throws \JsonException
  1100. */
  1101. private function storeTask(Task $task): void {
  1102. // create a db entity and insert into db table
  1103. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  1104. $this->taskMapper->insert($taskEntity);
  1105. // make sure the scheduler knows the id
  1106. $task->setId($taskEntity->getId());
  1107. }
  1108. /**
  1109. * @param array $output
  1110. * @param ShapeDescriptor[] ...$specs the specs that define which keys to keep
  1111. * @return array
  1112. * @throws NotPermittedException
  1113. */
  1114. private function validateOutputFileIds(array $output, ...$specs): array {
  1115. $newOutput = [];
  1116. $spec = array_reduce($specs, fn ($carry, $spec) => $carry + $spec, []);
  1117. foreach ($spec as $key => $descriptor) {
  1118. $type = $descriptor->getShapeType();
  1119. if (!isset($output[$key])) {
  1120. continue;
  1121. }
  1122. if (!in_array(EShapeType::getScalarType($type), [EShapeType::Image, EShapeType::Audio, EShapeType::Video, EShapeType::File], true)) {
  1123. $newOutput[$key] = $output[$key];
  1124. continue;
  1125. }
  1126. if (EShapeType::getScalarType($type) === $type) {
  1127. // Is scalar file ID
  1128. $newOutput[$key] = $this->validateFileId($output[$key]);
  1129. } else {
  1130. // Is list of file IDs
  1131. $newOutput = [];
  1132. foreach ($output[$key] as $item) {
  1133. $newOutput[$key][] = $this->validateFileId($item);
  1134. }
  1135. }
  1136. }
  1137. return $newOutput;
  1138. }
  1139. /**
  1140. * @param mixed $id
  1141. * @return File
  1142. * @throws ValidationException
  1143. */
  1144. private function validateFileId(mixed $id): File {
  1145. $node = $this->rootFolder->getFirstNodeById($id);
  1146. if ($node === null) {
  1147. $node = $this->rootFolder->getFirstNodeByIdInPath($id, '/' . $this->rootFolder->getAppDataDirectoryName() . '/');
  1148. if ($node === null) {
  1149. throw new ValidationException('Could not find file ' . $id);
  1150. } elseif (!$node instanceof File) {
  1151. throw new ValidationException('File with id "' . $id . '" is not a file');
  1152. }
  1153. } elseif (!$node instanceof File) {
  1154. throw new ValidationException('File with id "' . $id . '" is not a file');
  1155. }
  1156. return $node;
  1157. }
  1158. /**
  1159. * @param mixed $fileId
  1160. * @param string|null $userId
  1161. * @return void
  1162. * @throws UnauthorizedException
  1163. */
  1164. private function validateUserAccessToFile(mixed $fileId, ?string $userId): void {
  1165. if ($userId === null) {
  1166. throw new UnauthorizedException('User does not have access to file ' . $fileId);
  1167. }
  1168. $mounts = $this->userMountCache->getMountsForFileId($fileId);
  1169. $userIds = array_map(fn ($mount) => $mount->getUser()->getUID(), $mounts);
  1170. if (!in_array($userId, $userIds)) {
  1171. throw new UnauthorizedException('User ' . $userId . ' does not have access to file ' . $fileId);
  1172. }
  1173. }
  1174. /**
  1175. * Make a request to the task's webhookUri if necessary
  1176. *
  1177. * @param Task $task
  1178. */
  1179. private function runWebhook(Task $task): void {
  1180. $uri = $task->getWebhookUri();
  1181. $method = $task->getWebhookMethod();
  1182. if (!$uri || !$method) {
  1183. return;
  1184. }
  1185. if (in_array($method, ['HTTP:GET', 'HTTP:POST', 'HTTP:PUT', 'HTTP:DELETE'], true)) {
  1186. $client = $this->clientService->newClient();
  1187. $httpMethod = preg_replace('/^HTTP:/', '', $method);
  1188. $options = [
  1189. 'timeout' => 30,
  1190. 'body' => json_encode([
  1191. 'task' => $task->jsonSerialize(),
  1192. ]),
  1193. 'headers' => ['Content-Type' => 'application/json'],
  1194. ];
  1195. try {
  1196. $client->request($httpMethod, $uri, $options);
  1197. } catch (ClientException|ServerException $e) {
  1198. $this->logger->warning('Task processing HTTP webhook failed for task ' . $task->getId() . '. Request failed', ['exception' => $e]);
  1199. } catch (\Exception|\Throwable $e) {
  1200. $this->logger->warning('Task processing HTTP webhook failed for task ' . $task->getId() . '. Unknown error', ['exception' => $e]);
  1201. }
  1202. } elseif (str_starts_with($method, 'AppAPI:') && str_starts_with($uri, '/')) {
  1203. $parsedMethod = explode(':', $method, 4);
  1204. if (count($parsedMethod) < 3) {
  1205. $this->logger->warning('Task processing AppAPI webhook failed for task ' . $task->getId() . '. Invalid method: ' . $method);
  1206. }
  1207. [, $exAppId, $httpMethod] = $parsedMethod;
  1208. if (!$this->appManager->isInstalled('app_api')) {
  1209. $this->logger->warning('Task processing AppAPI webhook failed for task ' . $task->getId() . '. AppAPI is disabled or not installed.');
  1210. return;
  1211. }
  1212. try {
  1213. $appApiFunctions = \OCP\Server::get(\OCA\AppAPI\PublicFunctions::class);
  1214. } catch (ContainerExceptionInterface|NotFoundExceptionInterface) {
  1215. $this->logger->warning('Task processing AppAPI webhook failed for task ' . $task->getId() . '. Could not get AppAPI public functions.');
  1216. return;
  1217. }
  1218. $exApp = $appApiFunctions->getExApp($exAppId);
  1219. if ($exApp === null) {
  1220. $this->logger->warning('Task processing AppAPI webhook failed for task ' . $task->getId() . '. ExApp ' . $exAppId . ' is missing.');
  1221. return;
  1222. } elseif (!$exApp['enabled']) {
  1223. $this->logger->warning('Task processing AppAPI webhook failed for task ' . $task->getId() . '. ExApp ' . $exAppId . ' is disabled.');
  1224. return;
  1225. }
  1226. $requestParams = [
  1227. 'task' => $task->jsonSerialize(),
  1228. ];
  1229. $requestOptions = [
  1230. 'timeout' => 30,
  1231. ];
  1232. $response = $appApiFunctions->exAppRequest($exAppId, $uri, $task->getUserId(), $httpMethod, $requestParams, $requestOptions);
  1233. if (is_array($response) && isset($response['error'])) {
  1234. $this->logger->warning('Task processing AppAPI webhook failed for task ' . $task->getId() . '. Error during request to ExApp(' . $exAppId . '): ', $response['error']);
  1235. }
  1236. }
  1237. }
  1238. }