Passed
Push — imaginary ( 116acd...de384a )
by Matias
04:29 queued 16s
created

Imaginary::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 4
ccs 4
cts 4
cp 1
crap 1
rs 10
1
<?php
2
/**
3
 * @copyright Copyright (c) 2022, 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
	public function getInfo(string $filepath): array {
56
57
		$imaginaryUrl = $this->config->getSystemValueString('preview_imaginary_url', 'invalid');
58
		$imaginaryUrl = rtrim($imaginaryUrl, '/');
59
60
		$httpClient = $this->service->newClient();
61
62
		$options['multipart'] = [[
0 ignored issues
show
Comprehensibility Best Practice introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = array(); before regardless.
Loading history...
63
			'name' => 'file',
64
			'contents' => file_get_contents($filepath),
65
			'filename' => basename($filepath),
66
		]];
67
68
		try {
69
			$response = $httpClient->post($imaginaryUrl . '/info', $options);
70
		} catch (\Exception $e) {
71
			$this->logger->error('Error getting image information in Imaginary: ' . $e->getMessage(), [
72
				'exception' => $e,
73
			]);
74
			return [];
75
		}
76
77
		if ($response->getStatusCode() !== 200) {
78
			$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

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

143
			$this->logger->error('Error generating temporary image in Imaginary: ' . json_decode(/** @scrutinizer ignore-type */ $response->getBody())['message']);
Loading history...
144
			return false;
145
		}
146
147
		$body = $response->getBody();
148
149
		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...
150
	}
151
152
}
153