aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/Files/Conversion/ConversionManager.php
blob: e6ec11b1cf4bf3f7ea370a11f2fe82e1e742855d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace OC\Files\Conversion;

use OC\AppFramework\Bootstrap\Coordinator;
use OC\SystemConfig;
use OCP\Files\Conversion\IConversionManager;
use OCP\Files\Conversion\IConversionProvider;
use OCP\Files\File;
use OCP\Files\GenericFileException;
use OCP\Files\IRootFolder;
use OCP\ITempManager;
use OCP\PreConditionNotMetException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Throwable;

class ConversionManager implements IConversionManager {
	/** @var string[] */
	private array $preferredApps = [
		'richdocuments',
	];

	/** @var list<IConversionProvider> */
	private array $preferredProviders = [];

	/** @var list<IConversionProvider> */
	private array $providers = [];

	public function __construct(
		private Coordinator $coordinator,
		private ContainerInterface $serverContainer,
		private IRootFolder $rootFolder,
		private ITempManager $tempManager,
		private LoggerInterface $logger,
		private SystemConfig $config,
	) {
	}

	public function hasProviders(): bool {
		$context = $this->coordinator->getRegistrationContext();
		return !empty($context->getFileConversionProviders());
	}

	public function getProviders(): array {
		$providers = [];
		foreach ($this->getRegisteredProviders() as $provider) {
			$providers = array_merge($providers, $provider->getSupportedMimeTypes());
		}
		return $providers;
	}

	public function convert(File $file, string $targetMimeType, ?string $destination = null): string {
		if (!$this->hasProviders()) {
			throw new PreConditionNotMetException('No file conversion providers available');
		}

		// Operate in mebibytes
		$fileSize = $file->getSize() / (1024 * 1024);
		$threshold = $this->config->getValue('max_file_conversion_filesize', 100);
		if ($fileSize > $threshold) {
			throw new GenericFileException('File is too large to convert');
		}

		$fileMimeType = $file->getMimetype();
		$validProvider = $this->getValidProvider($fileMimeType, $targetMimeType);

		if ($validProvider !== null) {
			$convertedFile = $validProvider->convertFile($file, $targetMimeType);
			
			$targetExtension = '';
			foreach ($validProvider->getSupportedMimeTypes() as $mimeProvider) {
				if ($mimeProvider->getTo() === $targetMimeType) {
					$targetExtension = $mimeProvider->getExtension();
					break;
				}
			}

			// If destination not provided, we use the same path
			// as the original file, but with the new extension
			if ($destination === null) {
				$basename = pathinfo($file->getPath(), PATHINFO_FILENAME);
				$parent = $file->getParent();
				$destination = $parent->getFullPath($basename . '.' . $targetExtension);
			}

			$convertedFile = $this->writeToDestination($destination, $convertedFile);
			return $convertedFile->getPath();
		}

		throw new RuntimeException('Could not convert file');
	}

	/**
	 * @return list<IConversionProvider>
	 */
	private function getRegisteredProviders(): array {
		$context = $this->coordinator->getRegistrationContext();
		foreach ($context->getFileConversionProviders() as $providerRegistration) {
			$class = $providerRegistration->getService();
			$appId = $providerRegistration->getAppId();

			try {
				if (in_array($appId, $this->preferredApps)) {
					$this->preferredProviders[$class] = $this->serverContainer->get($class);
					continue;
				}
				
				$this->providers[$class] = $this->serverContainer->get($class);
			} catch (NotFoundExceptionInterface|ContainerExceptionInterface|Throwable $e) {
				$this->logger->error('Failed to load file conversion provider ' . $class, [
					'exception' => $e,
				]);
			}
		}

		return array_values(array_merge([], $this->preferredProviders, $this->providers));
	}

	private function writeToDestination(string $destination, mixed $content): File {
		if ($this->rootFolder->nodeExists($destination)) {
			$file = $this->rootFolder->get($destination);
			$parent = $file->getParent();
			if (!$parent->isCreatable()) {
				throw new GenericFileException('Destination is not creatable');
			}

			$newName = $parent->getNonExistingName(basename($destination));
			$destination = $parent->getFullPath($newName);
		}

		return $this->rootFolder->newFile($destination, $content);
	}

	private function getValidProvider(string $fileMimeType, string $targetMimeType): ?IConversionProvider {
		foreach ($this->getRegisteredProviders() as $provider) {
			foreach ($provider->getSupportedMimeTypes() as $mimeProvider) {
				if ($mimeProvider->getFrom() === $fileMimeType && $mimeProvider->getTo() === $targetMimeType) {
					return $provider;
				}
			}
		}
		
		return null;
	}
}