1
0

Manager.php 45 KB

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