You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1229 lines
45 KiB

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