Completed
Push — master ( 27e371...567171 )
by Matias
26s queued 13s
created

Imaginary   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 118
Duplicated Lines 0 %

Test Coverage

Coverage 9.85%

Importance

Changes 4
Bugs 1 Features 0
Metric Value
eloc 64
c 4
b 1
f 0
dl 0
loc 118
ccs 7
cts 71
cp 0.0985
rs 10
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A isEnabled() 0 3 1
A __construct() 0 4 1
A getInfo() 0 33 5
A getResized() 0 54 4
1
<?php
2
/**
3
 * @copyright Copyright (c) 2022-2023, Matias De lellis
4
 *
5
 * @author Matias De lellis <[email protected]>
6
 *
7
 * @license AGPL-3.0-or-later
8
 *
9
 * This code is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License, version 3,
11
 * as published by the Free Software Foundation.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
 * GNU Affero General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public License, version 3,
19
 * along with this program. If not, see <http://www.gnu.org/licenses/>
20
 *
21
 */
22
23
namespace OCA\FaceRecognition\Helper;
24
25
use OCP\Files\File;
26
use OCP\Http\Client\IClientService;
27
use OCP\IConfig;
28
use OCP\IImage;
29
30
use OC\StreamImage;
0 ignored issues
show
Bug introduced by
The type OC\StreamImage was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
31
use Psr\Log\LoggerInterface;
32
33
class Imaginary {
34
35
	/** @var IConfig */
36
	private $config;
37
38
	/** @var IClientService */
39
	private $service;
40
41
	/** @var LoggerInterface */
42
	private $logger;
43
44 5
	public function __construct() {
45 5
		$this->config = \OC::$server->get(IConfig::class);
46 5
		$this->service = \OC::$server->get(IClientService::class);
47 5
		$this->logger = \OC::$server->get(LoggerInterface::class);
48
	}
49
50 5
	public function isEnabled(): bool {
51 5
		$imaginaryUrl = $this->config->getSystemValueString('preview_imaginary_url', 'invalid');
52 5
		return ($imaginaryUrl !== 'invalid');
53
	}
54
55
	/**
56
	 * @return array Returns the array with the size of image.
57
	 */
58
	public function getInfo(string $filepath): array {
59
60
		$imaginaryUrl = $this->config->getSystemValueString('preview_imaginary_url', 'invalid');
61
		$imaginaryUrl = rtrim($imaginaryUrl, '/');
62
63
		$httpClient = $this->service->newClient();
64
65
		$options = [];
66
		$options['multipart'] = [[
67
			'name' => 'file',
68
			'contents' => file_get_contents($filepath),
69
			'filename' => basename($filepath),
70
		]];
71
72
		try {
73
			$response = $httpClient->post($imaginaryUrl . '/info', $options);
74
		} catch (\Exception $e) {
75
			$this->logger->error('Error getting image information in Imaginary: ' . $e->getMessage(), [
76
				'exception' => $e,
77
			]);
78
			return [];
79
		}
80
81
		if ($response->getStatusCode() !== 200) {
82
			$this->logger->error('Error getting image information in Imaginary: ' . json_decode($response->getBody())['message']);
0 ignored issues
show
Bug introduced by
It seems like $response->getBody() can also be of type resource; however, parameter $json of json_decode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

82
			$this->logger->error('Error getting image information in Imaginary: ' . json_decode(/** @scrutinizer ignore-type */ $response->getBody())['message']);
Loading history...
83
			return [];
84
		}
85
86
		// Rotates the size, since it is important and Imaginary do not do that.
87
		$info = json_decode($response->getBody(), true);
88
		return [
89
			'width'  => $info['orientation'] < 5 ? $info['width']  : $info['height'],
90
			'height' => $info['orientation'] < 5 ? $info['height'] : $info['width']
91
		];
92
	}
93
94
	/**
95
	 * @return false|resource|\GdImage Returns the resized image
96
	 */
97
	public function getResized(string $filepath, int $width, int $height, string $mimeType) {
98
99
		$imaginaryUrl = $this->config->getSystemValueString('preview_imaginary_url', 'invalid');
100
		$imaginaryUrl = rtrim($imaginaryUrl, '/');
101
102
		$httpClient = $this->service->newClient();
103
104
		switch ($mimeType) {
105
			case 'image/png':
106
				$type = 'png';
107
				break;
108
			default:
109
				$type = 'jpeg';
110
		}
111
112
		$operations = [
113
			[
114
				'operation' => 'autorotate',
115
			],
116
			[
117
				'operation' => 'resize',
118
				'params' => [
119
					'width' => $width,
120
					'height' => $height,
121
					'stripmeta' => 'true',
122
					'type' => $type,
123
					'norotation' => 'true',
124
					'force' => 'true'
125
				]
126
			]
127
		];
128
129
		try {
130
			$response = $httpClient->post(
131
				$imaginaryUrl . '/pipeline', [
132
					'query' => ['operations' => json_encode($operations)],
133
					'body' => file_get_contents($filepath),
134
					'nextcloud' => ['allow_local_address' => true],
135
				]);
136
		} catch (\Exception $e) {
137
			$this->logger->error('Error generating temporary image in Imaginary: ' . $e->getMessage(), [
138
				'exception' => $e,
139
			]);
140
			return false;
141
		}
142
143
		if ($response->getStatusCode() !== 200) {
144
			$this->logger->error('Error generating temporary image in Imaginary: ' . json_decode($response->getBody())['message']);
0 ignored issues
show
Bug introduced by
It seems like $response->getBody() can also be of type resource; however, parameter $json of json_decode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

144
			$this->logger->error('Error generating temporary image in Imaginary: ' . json_decode(/** @scrutinizer ignore-type */ $response->getBody())['message']);
Loading history...
145
			return false;
146
		}
147
148
		$body = $response->getBody();
149
150
		return $body;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $body also could return the type string which is incompatible with the documented return type GdImage|false|resource.
Loading history...
151
	}
152
153
}
154