Manager.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  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 OC\AppFramework\Bootstrap\Coordinator;
  9. use OC\Files\SimpleFS\SimpleFile;
  10. use OC\TaskProcessing\Db\TaskMapper;
  11. use OCP\AppFramework\Db\DoesNotExistException;
  12. use OCP\AppFramework\Db\MultipleObjectsReturnedException;
  13. use OCP\BackgroundJob\IJobList;
  14. use OCP\EventDispatcher\IEventDispatcher;
  15. use OCP\Files\AppData\IAppDataFactory;
  16. use OCP\Files\File;
  17. use OCP\Files\GenericFileException;
  18. use OCP\Files\IAppData;
  19. use OCP\Files\IRootFolder;
  20. use OCP\Files\NotPermittedException;
  21. use OCP\Files\SimpleFS\ISimpleFile;
  22. use OCP\IL10N;
  23. use OCP\IServerContainer;
  24. use OCP\L10N\IFactory;
  25. use OCP\Lock\LockedException;
  26. use OCP\SpeechToText\ISpeechToTextProvider;
  27. use OCP\SpeechToText\ISpeechToTextProviderWithId;
  28. use OCP\TaskProcessing\EShapeType;
  29. use OCP\TaskProcessing\Events\TaskFailedEvent;
  30. use OCP\TaskProcessing\Events\TaskSuccessfulEvent;
  31. use OCP\TaskProcessing\Exception\NotFoundException;
  32. use OCP\TaskProcessing\Exception\ProcessingException;
  33. use OCP\TaskProcessing\Exception\UnauthorizedException;
  34. use OCP\TaskProcessing\Exception\ValidationException;
  35. use OCP\TaskProcessing\IManager;
  36. use OCP\TaskProcessing\IProvider;
  37. use OCP\TaskProcessing\ISynchronousProvider;
  38. use OCP\TaskProcessing\ITaskType;
  39. use OCP\TaskProcessing\ShapeDescriptor;
  40. use OCP\TaskProcessing\Task;
  41. use OCP\TaskProcessing\TaskTypes\AudioToText;
  42. use OCP\TaskProcessing\TaskTypes\TextToImage;
  43. use OCP\TaskProcessing\TaskTypes\TextToText;
  44. use OCP\TaskProcessing\TaskTypes\TextToTextHeadline;
  45. use OCP\TaskProcessing\TaskTypes\TextToTextSummary;
  46. use OCP\TaskProcessing\TaskTypes\TextToTextTopics;
  47. use Psr\Log\LoggerInterface;
  48. class Manager implements IManager {
  49. public const LEGACY_PREFIX_TEXTPROCESSING = 'legacy:TextProcessing:';
  50. public const LEGACY_PREFIX_TEXTTOIMAGE = 'legacy:TextToImage:';
  51. public const LEGACY_PREFIX_SPEECHTOTEXT = 'legacy:SpeechToText:';
  52. /** @var list<IProvider>|null */
  53. private ?array $providers = null;
  54. /** @var array<string,array{name: string, description: string, inputShape: array<string, ShapeDescriptor>, optionalInputShape: array<string, ShapeDescriptor>, outputShape: array<string, ShapeDescriptor>, optionalOutputShape: array<string, ShapeDescriptor>}>|null */
  55. private ?array $availableTaskTypes = null;
  56. private IAppData $appData;
  57. public function __construct(
  58. private Coordinator $coordinator,
  59. private IServerContainer $serverContainer,
  60. private LoggerInterface $logger,
  61. private TaskMapper $taskMapper,
  62. private IJobList $jobList,
  63. private IEventDispatcher $dispatcher,
  64. IAppDataFactory $appDataFactory,
  65. private IRootFolder $rootFolder,
  66. private \OCP\TextProcessing\IManager $textProcessingManager,
  67. private \OCP\TextToImage\IManager $textToImageManager,
  68. private \OCP\SpeechToText\ISpeechToTextManager $speechToTextManager,
  69. private \OCP\Share\IManager $shareManager,
  70. ) {
  71. $this->appData = $appDataFactory->get('core');
  72. }
  73. /**
  74. * @return IProvider[]
  75. */
  76. private function _getTextProcessingProviders(): array {
  77. $oldProviders = $this->textProcessingManager->getProviders();
  78. $newProviders = [];
  79. foreach ($oldProviders as $oldProvider) {
  80. $provider = new class($oldProvider) implements IProvider, ISynchronousProvider {
  81. private \OCP\TextProcessing\IProvider $provider;
  82. public function __construct(\OCP\TextProcessing\IProvider $provider) {
  83. $this->provider = $provider;
  84. }
  85. public function getId(): string {
  86. if ($this->provider instanceof \OCP\TextProcessing\IProviderWithId) {
  87. return $this->provider->getId();
  88. }
  89. return Manager::LEGACY_PREFIX_TEXTPROCESSING . $this->provider::class;
  90. }
  91. public function getName(): string {
  92. return $this->provider->getName();
  93. }
  94. public function getTaskTypeId(): string {
  95. return match ($this->provider->getTaskType()) {
  96. \OCP\TextProcessing\FreePromptTaskType::class => TextToText::ID,
  97. \OCP\TextProcessing\HeadlineTaskType::class => TextToTextHeadline::ID,
  98. \OCP\TextProcessing\TopicsTaskType::class => TextToTextTopics::ID,
  99. \OCP\TextProcessing\SummaryTaskType::class => TextToTextSummary::ID,
  100. default => Manager::LEGACY_PREFIX_TEXTPROCESSING . $this->provider->getTaskType(),
  101. };
  102. }
  103. public function getExpectedRuntime(): int {
  104. if ($this->provider instanceof \OCP\TextProcessing\IProviderWithExpectedRuntime) {
  105. return $this->provider->getExpectedRuntime();
  106. }
  107. return 60;
  108. }
  109. public function getOptionalInputShape(): array {
  110. return [];
  111. }
  112. public function getOptionalOutputShape(): array {
  113. return [];
  114. }
  115. public function process(?string $userId, array $input, callable $reportProgress): array {
  116. if ($this->provider instanceof \OCP\TextProcessing\IProviderWithUserId) {
  117. $this->provider->setUserId($userId);
  118. }
  119. try {
  120. return ['output' => $this->provider->process($input['input'])];
  121. } catch(\RuntimeException $e) {
  122. throw new ProcessingException($e->getMessage(), 0, $e);
  123. }
  124. }
  125. };
  126. $newProviders[$provider->getId()] = $provider;
  127. }
  128. return $newProviders;
  129. }
  130. /**
  131. * @return ITaskType[]
  132. */
  133. private function _getTextProcessingTaskTypes(): array {
  134. $oldProviders = $this->textProcessingManager->getProviders();
  135. $newTaskTypes = [];
  136. foreach ($oldProviders as $oldProvider) {
  137. // These are already implemented in the TaskProcessing realm
  138. if (in_array($oldProvider->getTaskType(), [
  139. \OCP\TextProcessing\FreePromptTaskType::class,
  140. \OCP\TextProcessing\HeadlineTaskType::class,
  141. \OCP\TextProcessing\TopicsTaskType::class,
  142. \OCP\TextProcessing\SummaryTaskType::class
  143. ], true)) {
  144. continue;
  145. }
  146. $taskType = new class($oldProvider->getTaskType()) implements ITaskType {
  147. private string $oldTaskTypeClass;
  148. private \OCP\TextProcessing\ITaskType $oldTaskType;
  149. private IL10N $l;
  150. public function __construct(string $oldTaskTypeClass) {
  151. $this->oldTaskTypeClass = $oldTaskTypeClass;
  152. $this->oldTaskType = \OCP\Server::get($oldTaskTypeClass);
  153. $this->l = \OCP\Server::get(IFactory::class)->get('core');
  154. }
  155. public function getId(): string {
  156. return Manager::LEGACY_PREFIX_TEXTPROCESSING . $this->oldTaskTypeClass;
  157. }
  158. public function getName(): string {
  159. return $this->oldTaskType->getName();
  160. }
  161. public function getDescription(): string {
  162. return $this->oldTaskType->getDescription();
  163. }
  164. public function getInputShape(): array {
  165. return ['input' => new ShapeDescriptor($this->l->t('Input text'), $this->l->t('The input text'), EShapeType::Text)];
  166. }
  167. public function getOutputShape(): array {
  168. return ['output' => new ShapeDescriptor($this->l->t('Input text'), $this->l->t('The input text'), EShapeType::Text)];
  169. }
  170. };
  171. $newTaskTypes[$taskType->getId()] = $taskType;
  172. }
  173. return $newTaskTypes;
  174. }
  175. /**
  176. * @return IProvider[]
  177. */
  178. private function _getTextToImageProviders(): array {
  179. $oldProviders = $this->textToImageManager->getProviders();
  180. $newProviders = [];
  181. foreach ($oldProviders as $oldProvider) {
  182. $newProvider = new class($oldProvider, $this->appData) implements IProvider, ISynchronousProvider {
  183. private \OCP\TextToImage\IProvider $provider;
  184. private IAppData $appData;
  185. public function __construct(\OCP\TextToImage\IProvider $provider, IAppData $appData) {
  186. $this->provider = $provider;
  187. $this->appData = $appData;
  188. }
  189. public function getId(): string {
  190. return Manager::LEGACY_PREFIX_TEXTTOIMAGE . $this->provider->getId();
  191. }
  192. public function getName(): string {
  193. return $this->provider->getName();
  194. }
  195. public function getTaskTypeId(): string {
  196. return TextToImage::ID;
  197. }
  198. public function getExpectedRuntime(): int {
  199. return $this->provider->getExpectedRuntime();
  200. }
  201. public function getOptionalInputShape(): array {
  202. return [];
  203. }
  204. public function getOptionalOutputShape(): array {
  205. return [];
  206. }
  207. public function process(?string $userId, array $input, callable $reportProgress): array {
  208. try {
  209. $folder = $this->appData->getFolder('text2image');
  210. } catch(\OCP\Files\NotFoundException) {
  211. $folder = $this->appData->newFolder('text2image');
  212. }
  213. $resources = [];
  214. $files = [];
  215. for ($i = 0; $i < $input['numberOfImages']; $i++) {
  216. $file = $folder->newFile(time() . '-' . rand(1, 100000) . '-' . $i);
  217. $files[] = $file;
  218. $resource = $file->write();
  219. if ($resource !== false && $resource !== true && is_resource($resource)) {
  220. $resources[] = $resource;
  221. } else {
  222. throw new ProcessingException('Text2Image generation using provider "' . $this->getName() . '" failed: Couldn\'t open file to write.');
  223. }
  224. }
  225. if ($this->provider instanceof \OCP\TextToImage\IProviderWithUserId) {
  226. $this->provider->setUserId($userId);
  227. }
  228. try {
  229. $this->provider->generate($input['input'], $resources);
  230. } catch (\RuntimeException $e) {
  231. throw new ProcessingException($e->getMessage(), 0, $e);
  232. }
  233. for ($i = 0; $i < $input['numberOfImages']; $i++) {
  234. if (is_resource($resources[$i])) {
  235. // If $resource hasn't been closed yet, we'll do that here
  236. fclose($resources[$i]);
  237. }
  238. }
  239. return ['images' => array_map(fn (ISimpleFile $file) => $file->getContent(), $files)];
  240. }
  241. };
  242. $newProviders[$newProvider->getId()] = $newProvider;
  243. }
  244. return $newProviders;
  245. }
  246. /**
  247. * @return IProvider[]
  248. */
  249. private function _getSpeechToTextProviders(): array {
  250. $oldProviders = $this->speechToTextManager->getProviders();
  251. $newProviders = [];
  252. foreach ($oldProviders as $oldProvider) {
  253. $newProvider = new class($oldProvider, $this->rootFolder, $this->appData) implements IProvider, ISynchronousProvider {
  254. private ISpeechToTextProvider $provider;
  255. private IAppData $appData;
  256. private IRootFolder $rootFolder;
  257. public function __construct(ISpeechToTextProvider $provider, IRootFolder $rootFolder, IAppData $appData) {
  258. $this->provider = $provider;
  259. $this->rootFolder = $rootFolder;
  260. $this->appData = $appData;
  261. }
  262. public function getId(): string {
  263. if ($this->provider instanceof ISpeechToTextProviderWithId) {
  264. return Manager::LEGACY_PREFIX_SPEECHTOTEXT . $this->provider->getId();
  265. }
  266. return Manager::LEGACY_PREFIX_SPEECHTOTEXT . $this->provider::class;
  267. }
  268. public function getName(): string {
  269. return $this->provider->getName();
  270. }
  271. public function getTaskTypeId(): string {
  272. return AudioToText::ID;
  273. }
  274. public function getExpectedRuntime(): int {
  275. return 60;
  276. }
  277. public function getOptionalInputShape(): array {
  278. return [];
  279. }
  280. public function getOptionalOutputShape(): array {
  281. return [];
  282. }
  283. public function process(?string $userId, array $input, callable $reportProgress): array {
  284. try {
  285. $result = $this->provider->transcribeFile($input['input']);
  286. } catch (\RuntimeException $e) {
  287. throw new ProcessingException($e->getMessage(), 0, $e);
  288. }
  289. return ['output' => $result];
  290. }
  291. };
  292. $newProviders[$newProvider->getId()] = $newProvider;
  293. }
  294. return $newProviders;
  295. }
  296. /**
  297. * @return IProvider[]
  298. */
  299. private function _getProviders(): array {
  300. $context = $this->coordinator->getRegistrationContext();
  301. if ($context === null) {
  302. return [];
  303. }
  304. $providers = [];
  305. foreach ($context->getTaskProcessingProviders() as $providerServiceRegistration) {
  306. $class = $providerServiceRegistration->getService();
  307. try {
  308. /** @var IProvider $provider */
  309. $provider = $this->serverContainer->get($class);
  310. if (isset($providers[$provider->getId()])) {
  311. $this->logger->warning('Task processing provider ' . $class . ' is using ID ' . $provider->getId() . ' which is already used by ' . $providers[$provider->getId()]::class);
  312. }
  313. $providers[$provider->getId()] = $provider;
  314. } catch (\Throwable $e) {
  315. $this->logger->error('Failed to load task processing provider ' . $class, [
  316. 'exception' => $e,
  317. ]);
  318. }
  319. }
  320. $providers += $this->_getTextProcessingProviders() + $this->_getTextToImageProviders() + $this->_getSpeechToTextProviders();
  321. return $providers;
  322. }
  323. /**
  324. * @return ITaskType[]
  325. */
  326. private function _getTaskTypes(): array {
  327. $context = $this->coordinator->getRegistrationContext();
  328. if ($context === null) {
  329. return [];
  330. }
  331. // Default task types
  332. $taskTypes = [
  333. \OCP\TaskProcessing\TaskTypes\TextToText::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToText::class),
  334. \OCP\TaskProcessing\TaskTypes\TextToTextTopics::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextTopics::class),
  335. \OCP\TaskProcessing\TaskTypes\TextToTextHeadline::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextHeadline::class),
  336. \OCP\TaskProcessing\TaskTypes\TextToTextSummary::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToTextSummary::class),
  337. \OCP\TaskProcessing\TaskTypes\TextToImage::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\TextToImage::class),
  338. \OCP\TaskProcessing\TaskTypes\AudioToText::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\AudioToText::class),
  339. \OCP\TaskProcessing\TaskTypes\ContextWrite::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\ContextWrite::class),
  340. \OCP\TaskProcessing\TaskTypes\GenerateEmoji::ID => \OCP\Server::get(\OCP\TaskProcessing\TaskTypes\GenerateEmoji::class),
  341. ];
  342. foreach ($context->getTaskProcessingTaskTypes() as $providerServiceRegistration) {
  343. $class = $providerServiceRegistration->getService();
  344. try {
  345. /** @var ITaskType $provider */
  346. $taskType = $this->serverContainer->get($class);
  347. if (isset($taskTypes[$taskType->getId()])) {
  348. $this->logger->warning('Task processing task type ' . $class . ' is using ID ' . $taskType->getId() . ' which is already used by ' . $taskTypes[$taskType->getId()]::class);
  349. }
  350. $taskTypes[$taskType->getId()] = $taskType;
  351. } catch (\Throwable $e) {
  352. $this->logger->error('Failed to load task processing task type ' . $class, [
  353. 'exception' => $e,
  354. ]);
  355. }
  356. }
  357. $taskTypes += $this->_getTextProcessingTaskTypes();
  358. return $taskTypes;
  359. }
  360. /**
  361. * @param string $taskType
  362. * @return IProvider
  363. * @throws \OCP\TaskProcessing\Exception\Exception
  364. */
  365. private function _getPreferredProvider(string $taskType) {
  366. $providers = $this->getProviders();
  367. foreach ($providers as $provider) {
  368. if ($provider->getTaskTypeId() === $taskType) {
  369. return $provider;
  370. }
  371. }
  372. throw new \OCP\TaskProcessing\Exception\Exception('No matching provider found');
  373. }
  374. /**
  375. * @param ShapeDescriptor[] $spec
  376. * @param array $io
  377. * @return void
  378. * @throws ValidationException
  379. */
  380. private function validateInput(array $spec, array $io, bool $optional = false): void {
  381. foreach ($spec as $key => $descriptor) {
  382. $type = $descriptor->getShapeType();
  383. if (!isset($io[$key])) {
  384. if ($optional) {
  385. continue;
  386. }
  387. throw new ValidationException('Missing key: "' . $key . '"');
  388. }
  389. try {
  390. $type->validateInput($io[$key]);
  391. } catch (ValidationException $e) {
  392. throw new ValidationException('Failed to validate input key "' . $key . '": ' . $e->getMessage());
  393. }
  394. }
  395. }
  396. /**
  397. * @param ShapeDescriptor[] $spec
  398. * @param array $io
  399. * @param bool $optional
  400. * @return void
  401. * @throws ValidationException
  402. */
  403. private function validateOutput(array $spec, array $io, bool $optional = false): void {
  404. foreach ($spec as $key => $descriptor) {
  405. $type = $descriptor->getShapeType();
  406. if (!isset($io[$key])) {
  407. if ($optional) {
  408. continue;
  409. }
  410. throw new ValidationException('Missing key: "' . $key . '"');
  411. }
  412. try {
  413. $type->validateOutput($io[$key]);
  414. } catch (ValidationException $e) {
  415. throw new ValidationException('Failed to validate output key "' . $key . '": ' . $e->getMessage());
  416. }
  417. }
  418. }
  419. /**
  420. * @param array<array-key, T> $array The array to filter
  421. * @param ShapeDescriptor[] ...$specs the specs that define which keys to keep
  422. * @return array<array-key, T>
  423. * @psalm-template T
  424. */
  425. private function removeSuperfluousArrayKeys(array $array, ...$specs): array {
  426. $keys = array_unique(array_reduce($specs, fn ($carry, $spec) => $carry + array_keys($spec), []));
  427. $values = array_map(fn (string $key) => $array[$key], $keys);
  428. return array_combine($keys, $values);
  429. }
  430. public function hasProviders(): bool {
  431. return count($this->getProviders()) !== 0;
  432. }
  433. public function getProviders(): array {
  434. if ($this->providers === null) {
  435. $this->providers = $this->_getProviders();
  436. }
  437. return $this->providers;
  438. }
  439. public function getAvailableTaskTypes(): array {
  440. if ($this->availableTaskTypes === null) {
  441. $taskTypes = $this->_getTaskTypes();
  442. $providers = $this->getProviders();
  443. $availableTaskTypes = [];
  444. foreach ($providers as $provider) {
  445. if (!isset($taskTypes[$provider->getTaskTypeId()])) {
  446. continue;
  447. }
  448. $taskType = $taskTypes[$provider->getTaskTypeId()];
  449. $availableTaskTypes[$provider->getTaskTypeId()] = [
  450. 'name' => $taskType->getName(),
  451. 'description' => $taskType->getDescription(),
  452. 'inputShape' => $taskType->getInputShape(),
  453. 'optionalInputShape' => $provider->getOptionalInputShape(),
  454. 'outputShape' => $taskType->getOutputShape(),
  455. 'optionalOutputShape' => $provider->getOptionalOutputShape(),
  456. ];
  457. }
  458. $this->availableTaskTypes = $availableTaskTypes;
  459. }
  460. return $this->availableTaskTypes;
  461. }
  462. public function canHandleTask(Task $task): bool {
  463. return isset($this->getAvailableTaskTypes()[$task->getTaskTypeId()]);
  464. }
  465. public function scheduleTask(Task $task): void {
  466. if (!$this->canHandleTask($task)) {
  467. throw new \OCP\TaskProcessing\Exception\PreConditionNotMetException('No task processing provider is installed that can handle this task type: ' . $task->getTaskTypeId());
  468. }
  469. $taskTypes = $this->getAvailableTaskTypes();
  470. $inputShape = $taskTypes[$task->getTaskTypeId()]['inputShape'];
  471. $optionalInputShape = $taskTypes[$task->getTaskTypeId()]['optionalInputShape'];
  472. // validate input
  473. $this->validateInput($inputShape, $task->getInput());
  474. $this->validateInput($optionalInputShape, $task->getInput(), true);
  475. // authenticate access to mentioned files
  476. $ids = [];
  477. foreach ($inputShape + $optionalInputShape as $key => $descriptor) {
  478. if (in_array(EShapeType::getScalarType($descriptor->getShapeType()), [EShapeType::File, EShapeType::Image, EShapeType::Audio, EShapeType::Video], true)) {
  479. /** @var list<int>|int $inputSlot */
  480. $inputSlot = $task->getInput()[$key];
  481. if (is_array($inputSlot)) {
  482. $ids += $inputSlot;
  483. } else {
  484. $ids[] = $inputSlot;
  485. }
  486. }
  487. }
  488. foreach ($ids as $fileId) {
  489. $node = $this->rootFolder->getFirstNodeById($fileId);
  490. if ($node === null) {
  491. $node = $this->rootFolder->getFirstNodeByIdInPath($fileId, '/' . $this->rootFolder->getAppDataDirectoryName() . '/');
  492. if ($node === null) {
  493. throw new ValidationException('Could not find file ' . $fileId);
  494. }
  495. }
  496. /** @var array{users:array<string,array{node_id:int, node_path: string}>, remote: array<string,array{node_id:int, node_path: string}>, mail: array<string,array{node_id:int, node_path: string}>} $accessList */
  497. $accessList = $this->shareManager->getAccessList($node, true, true);
  498. $userIds = array_map(fn ($id) => strval($id), array_keys($accessList['users']));
  499. if (!in_array($task->getUserId(), $userIds)) {
  500. throw new UnauthorizedException('User ' . $task->getUserId() . ' does not have access to file ' . $fileId);
  501. }
  502. }
  503. // remove superfluous keys and set input
  504. $task->setInput($this->removeSuperfluousArrayKeys($task->getInput(), $inputShape, $optionalInputShape));
  505. $task->setStatus(Task::STATUS_SCHEDULED);
  506. $provider = $this->_getPreferredProvider($task->getTaskTypeId());
  507. // calculate expected completion time
  508. $completionExpectedAt = new \DateTime('now');
  509. $completionExpectedAt->add(new \DateInterval('PT'.$provider->getExpectedRuntime().'S'));
  510. $task->setCompletionExpectedAt($completionExpectedAt);
  511. // create a db entity and insert into db table
  512. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  513. $this->taskMapper->insert($taskEntity);
  514. // make sure the scheduler knows the id
  515. $task->setId($taskEntity->getId());
  516. // schedule synchronous job if the provider is synchronous
  517. if ($provider instanceof ISynchronousProvider) {
  518. $this->jobList->add(SynchronousBackgroundJob::class, null);
  519. }
  520. }
  521. public function deleteTask(Task $task): void {
  522. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  523. $this->taskMapper->delete($taskEntity);
  524. }
  525. public function getTask(int $id): Task {
  526. try {
  527. $taskEntity = $this->taskMapper->find($id);
  528. return $taskEntity->toPublicTask();
  529. } catch (DoesNotExistException $e) {
  530. throw new NotFoundException('Couldn\'t find task with id ' . $id, 0, $e);
  531. } catch (MultipleObjectsReturnedException|\OCP\DB\Exception $e) {
  532. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  533. } catch (\JsonException $e) {
  534. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the task', 0, $e);
  535. }
  536. }
  537. public function cancelTask(int $id): void {
  538. $task = $this->getTask($id);
  539. if ($task->getStatus() !== Task::STATUS_SCHEDULED && $task->getStatus() !== Task::STATUS_RUNNING) {
  540. return;
  541. }
  542. $task->setStatus(Task::STATUS_CANCELLED);
  543. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  544. try {
  545. $this->taskMapper->update($taskEntity);
  546. } catch (\OCP\DB\Exception $e) {
  547. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  548. }
  549. }
  550. public function setTaskProgress(int $id, float $progress): bool {
  551. // TODO: Not sure if we should rather catch the exceptions of getTask here and fail silently
  552. $task = $this->getTask($id);
  553. if ($task->getStatus() === Task::STATUS_CANCELLED) {
  554. return false;
  555. }
  556. $task->setStatus(Task::STATUS_RUNNING);
  557. $task->setProgress($progress);
  558. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  559. try {
  560. $this->taskMapper->update($taskEntity);
  561. } catch (\OCP\DB\Exception $e) {
  562. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  563. }
  564. return true;
  565. }
  566. public function setTaskResult(int $id, ?string $error, ?array $result): void {
  567. // TODO: Not sure if we should rather catch the exceptions of getTask here and fail silently
  568. $task = $this->getTask($id);
  569. if ($task->getStatus() === Task::STATUS_CANCELLED) {
  570. $this->logger->info('A TaskProcessing ' . $task->getTaskTypeId() . ' task with id ' . $id . ' finished but was cancelled in the mean time. Moving on without storing result.');
  571. return;
  572. }
  573. if ($error !== null) {
  574. $task->setStatus(Task::STATUS_FAILED);
  575. $task->setErrorMessage($error);
  576. $this->logger->warning('A TaskProcessing ' . $task->getTaskTypeId() . ' task with id ' . $id . ' failed with the following message: ' . $error);
  577. } elseif ($result !== null) {
  578. $taskTypes = $this->getAvailableTaskTypes();
  579. $outputShape = $taskTypes[$task->getTaskTypeId()]['outputShape'];
  580. $optionalOutputShape = $taskTypes[$task->getTaskTypeId()]['optionalOutputShape'];
  581. try {
  582. // validate output
  583. $this->validateOutput($outputShape, $result);
  584. $this->validateOutput($optionalOutputShape, $result, true);
  585. $output = $this->removeSuperfluousArrayKeys($result, $outputShape, $optionalOutputShape);
  586. // extract raw data and put it in files, replace it with file ids
  587. $output = $this->encapsulateOutputFileData($output, $outputShape, $optionalOutputShape);
  588. $task->setOutput($output);
  589. $task->setProgress(1);
  590. $task->setStatus(Task::STATUS_SUCCESSFUL);
  591. } catch (ValidationException $e) {
  592. $task->setProgress(1);
  593. $task->setStatus(Task::STATUS_FAILED);
  594. $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';
  595. $task->setErrorMessage($error);
  596. $this->logger->error($error, ['exception' => $e]);
  597. } catch (NotPermittedException $e) {
  598. $task->setProgress(1);
  599. $task->setStatus(Task::STATUS_FAILED);
  600. $error = 'The task was processed successfully but storing the output in a file failed';
  601. $task->setErrorMessage($error);
  602. $this->logger->error($error, ['exception' => $e]);
  603. }
  604. }
  605. $taskEntity = \OC\TaskProcessing\Db\Task::fromPublicTask($task);
  606. try {
  607. $this->taskMapper->update($taskEntity);
  608. } catch (\OCP\DB\Exception $e) {
  609. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  610. }
  611. if ($task->getStatus() === Task::STATUS_SUCCESSFUL) {
  612. $event = new TaskSuccessfulEvent($task);
  613. } else {
  614. $event = new TaskFailedEvent($task, $error);
  615. }
  616. $this->dispatcher->dispatchTyped($event);
  617. }
  618. public function getNextScheduledTask(?string $taskTypeId = null): Task {
  619. try {
  620. $taskEntity = $this->taskMapper->findOldestScheduledByType($taskTypeId);
  621. return $taskEntity->toPublicTask();
  622. } catch (DoesNotExistException $e) {
  623. throw new \OCP\TaskProcessing\Exception\NotFoundException('Could not find the task', 0, $e);
  624. } catch (\OCP\DB\Exception $e) {
  625. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  626. } catch (\JsonException $e) {
  627. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the task', 0, $e);
  628. }
  629. }
  630. /**
  631. * Takes task input or output data and replaces fileIds with base64 data
  632. *
  633. * @param string|null $userId
  634. * @param array<array-key, list<numeric|string>|numeric|string> $input
  635. * @param ShapeDescriptor[] ...$specs the specs
  636. * @return array<array-key, list<File|numeric|string>|numeric|string|File>
  637. * @throws GenericFileException
  638. * @throws LockedException
  639. * @throws NotPermittedException
  640. * @throws ValidationException
  641. */
  642. public function fillInputFileData(?string $userId, array $input, ...$specs): array {
  643. if ($userId !== null) {
  644. \OC_Util::setupFS($userId);
  645. }
  646. $newInputOutput = [];
  647. $spec = array_reduce($specs, fn ($carry, $spec) => $carry + $spec, []);
  648. foreach($spec as $key => $descriptor) {
  649. $type = $descriptor->getShapeType();
  650. if (!isset($input[$key])) {
  651. continue;
  652. }
  653. if (!in_array(EShapeType::getScalarType($type), [EShapeType::Image, EShapeType::Audio, EShapeType::Video, EShapeType::File], true)) {
  654. $newInputOutput[$key] = $input[$key];
  655. continue;
  656. }
  657. if ($type->value < 10) {
  658. $node = $this->rootFolder->getFirstNodeById((int)$input[$key]);
  659. if ($node === null) {
  660. $node = $this->rootFolder->getFirstNodeByIdInPath((int)$input[$key], '/' . $this->rootFolder->getAppDataDirectoryName() . '/');
  661. if (!$node instanceof File) {
  662. throw new ValidationException('File id given for key "' . $key . '" is not a file');
  663. }
  664. } elseif (!$node instanceof File) {
  665. throw new ValidationException('File id given for key "' . $key . '" is not a file');
  666. }
  667. // TODO: Validate if userId has access to this file
  668. $newInputOutput[$key] = $node;
  669. } else {
  670. $newInputOutput[$key] = [];
  671. foreach ($input[$key] as $item) {
  672. $node = $this->rootFolder->getFirstNodeById((int)$item);
  673. if ($node === null) {
  674. $node = $this->rootFolder->getFirstNodeByIdInPath((int)$item, '/' . $this->rootFolder->getAppDataDirectoryName() . '/');
  675. if (!$node instanceof File) {
  676. throw new ValidationException('File id given for key "' . $key . '" is not a file');
  677. }
  678. } elseif (!$node instanceof File) {
  679. throw new ValidationException('File id given for key "' . $key . '" is not a file');
  680. }
  681. // TODO: Validate if userId has access to this file
  682. $newInputOutput[$key][] = $node;
  683. }
  684. }
  685. }
  686. return $newInputOutput;
  687. }
  688. public function getUserTask(int $id, ?string $userId): Task {
  689. try {
  690. $taskEntity = $this->taskMapper->findByIdAndUser($id, $userId);
  691. return $taskEntity->toPublicTask();
  692. } catch (DoesNotExistException $e) {
  693. throw new \OCP\TaskProcessing\Exception\NotFoundException('Could not find the task', 0, $e);
  694. } catch (MultipleObjectsReturnedException|\OCP\DB\Exception $e) {
  695. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the task', 0, $e);
  696. } catch (\JsonException $e) {
  697. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the task', 0, $e);
  698. }
  699. }
  700. public function getUserTasks(?string $userId, ?string $taskTypeId = null, ?string $customId = null): array {
  701. try {
  702. $taskEntities = $this->taskMapper->findByUserAndTaskType($userId, $taskTypeId, $customId);
  703. return array_map(fn ($taskEntity): Task => $taskEntity->toPublicTask(), $taskEntities);
  704. } catch (\OCP\DB\Exception $e) {
  705. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the tasks', 0, $e);
  706. } catch (\JsonException $e) {
  707. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the tasks', 0, $e);
  708. }
  709. }
  710. public function getUserTasksByApp(?string $userId, string $appId, ?string $customId = null): array {
  711. try {
  712. $taskEntities = $this->taskMapper->findUserTasksByApp($userId, $appId, $customId);
  713. return array_map(fn ($taskEntity): Task => $taskEntity->toPublicTask(), $taskEntities);
  714. } catch (\OCP\DB\Exception $e) {
  715. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding a task', 0, $e);
  716. } catch (\JsonException $e) {
  717. throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding a task', 0, $e);
  718. }
  719. }
  720. /**
  721. *Takes task input or output and replaces base64 data with file ids
  722. *
  723. * @param array $output
  724. * @param ShapeDescriptor[] ...$specs the specs that define which keys to keep
  725. * @return array
  726. * @throws NotPermittedException
  727. */
  728. public function encapsulateOutputFileData(array $output, ...$specs): array {
  729. $newOutput = [];
  730. try {
  731. $folder = $this->appData->getFolder('TaskProcessing');
  732. } catch (\OCP\Files\NotFoundException) {
  733. $folder = $this->appData->newFolder('TaskProcessing');
  734. }
  735. $spec = array_reduce($specs, fn ($carry, $spec) => $carry + $spec, []);
  736. foreach($spec as $key => $descriptor) {
  737. $type = $descriptor->getShapeType();
  738. if (!isset($output[$key])) {
  739. continue;
  740. }
  741. if (!in_array(EShapeType::getScalarType($type), [EShapeType::Image, EShapeType::Audio, EShapeType::Video, EShapeType::File], true)) {
  742. $newOutput[$key] = $output[$key];
  743. continue;
  744. }
  745. if ($type->value < 10) {
  746. /** @var SimpleFile $file */
  747. $file = $folder->newFile((string) rand(0, 10000000), $output[$key]);
  748. $newOutput[$key] = $file->getId(); // polymorphic call to SimpleFile
  749. } else {
  750. $newOutput = [];
  751. foreach ($output[$key] as $item) {
  752. /** @var SimpleFile $file */
  753. $file = $folder->newFile((string) rand(0, 10000000), $item);
  754. $newOutput[$key][] = $file->getId();
  755. }
  756. }
  757. }
  758. return $newOutput;
  759. }
  760. /**
  761. * @param Task $task
  762. * @return array<array-key, list<numeric|string|File>|numeric|string|File>
  763. * @throws GenericFileException
  764. * @throws LockedException
  765. * @throws NotPermittedException
  766. * @throws ValidationException
  767. */
  768. public function prepareInputData(Task $task): array {
  769. $taskTypes = $this->getAvailableTaskTypes();
  770. $inputShape = $taskTypes[$task->getTaskTypeId()]['inputShape'];
  771. $optionalInputShape = $taskTypes[$task->getTaskTypeId()]['optionalInputShape'];
  772. $input = $task->getInput();
  773. // validate input, again for good measure (should have been validated in scheduleTask)
  774. $this->validateInput($inputShape, $input);
  775. $this->validateInput($optionalInputShape, $input, true);
  776. $input = $this->removeSuperfluousArrayKeys($input, $inputShape, $optionalInputShape);
  777. $input = $this->fillInputFileData($task->getUserId(), $input, $inputShape, $optionalInputShape);
  778. return $input;
  779. }
  780. }