Passed
Push — restore-progress ( cb701c )
by Matias
02:15
created

ImageMapper::avgProcessingDuration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 12
nc 1
nop 1
dl 0
loc 14
rs 9.8666
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2017, Matias De lellis <[email protected]>
4
 * @copyright Copyright (c) 2018, Branko Kokanovic <[email protected]>
5
 *
6
 * @author Branko Kokanovic <[email protected]>
7
 *
8
 * @license GNU AGPL version 3 or any later version
9
 *
10
 * This program is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License as
12
 * published by the Free Software Foundation, either version 3 of the
13
 * License, or (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU Affero General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Affero General Public License
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
 *
23
 */
24
namespace OCA\FaceRecognition\Db;
25
26
use OCP\IDBConnection;
27
use OCP\IUser;
28
29
use OCP\AppFramework\Db\Mapper;
30
use OCP\AppFramework\Db\DoesNotExistException;
31
use OCP\DB\QueryBuilder\IQueryBuilder;
32
33
class ImageMapper extends Mapper {
34
35
	public function __construct(IDBConnection $db) {
36
		parent::__construct($db, 'face_recognition_images', '\OCA\FaceRecognition\Db\Image');
37
	}
38
39
	public function find (string $userId, int $imageId): Image {
40
		$qb = $this->db->getQueryBuilder();
41
		$qb->select('id', 'file')
0 ignored issues
show
Unused Code introduced by
The call to OCP\DB\QueryBuilder\IQueryBuilder::select() has too many arguments starting with 'file'. ( Ignorable by Annotation )

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

41
		$qb->/** @scrutinizer ignore-call */ 
42
       select('id', 'file')

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
42
			->from('face_recognition_images', 'i')
43
			->where($qb->expr()->eq('user', $qb->createParameter('user_id')))
44
			->andWhere($qb->expr()->eq('id', $qb->createParameter('image_id')));
45
		$params = array();
46
		$params['user_id'] = $userId;
47
		$params['image_id'] = $imageId;
48
		$image = $this->findEntity($qb->getSQL(), $params);
49
		return $image;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $image returns the type OCP\AppFramework\Db\Entity which includes types incompatible with the type-hinted return OCA\FaceRecognition\Db\Image.
Loading history...
50
	}
51
52
	public function imageExists(Image $image) {
53
		$qb = $this->db->getQueryBuilder();
54
		$query = $qb
55
			->select(['id'])
56
			->from('face_recognition_images')
57
			->where($qb->expr()->eq('user', $qb->createParameter('user')))
58
			->andWhere($qb->expr()->eq('file', $qb->createParameter('file')))
59
			->andWhere($qb->expr()->eq('model', $qb->createParameter('model')))
60
			->setParameter('user', $image->getUser())
61
			->setParameter('file', $image->getFile())
62
			->setParameter('model', $image->getModel());
63
		$resultStatement = $query->execute();
64
		$row = $resultStatement->fetch();
65
		$resultStatement->closeCursor();
66
		return $row ? (int)$row['id'] : null;
67
	}
68
69
	public function countImages(int $model): int {
70
		$qb = $this->db->getQueryBuilder();
71
		$query = $qb
72
			->select($qb->createFunction('COUNT(' . $qb->getColumnName('id') . ')'))
73
			->from('face_recognition_images')
74
			->where($qb->expr()->eq('model', $qb->createParameter('model')))
75
			->setParameter('model', $model);
76
		$resultStatement = $query->execute();
77
		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
78
		$resultStatement->closeCursor();
79
80
		return (int)$data[0];
81
	}
82
83
	public function countProcessedImages(int $model): int {
84
		$qb = $this->db->getQueryBuilder();
85
		$query = $qb
86
			->select($qb->createFunction('COUNT(' . $qb->getColumnName('id') . ')'))
87
			->from('face_recognition_images')
88
			->where($qb->expr()->eq('model', $qb->createParameter('model')))
89
			->andWhere($qb->expr()->eq('is_processed', $qb->createParameter('is_processed')))
90
			->setParameter('model', $model)
91
			->setParameter('is_processed', True);
92
		$resultStatement = $query->execute();
93
		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
94
		$resultStatement->closeCursor();
95
96
		return (int)$data[0];
97
	}
98
99
	public function avgProcessingDuration(int $model): int {
100
		$qb = $this->db->getQueryBuilder();
101
		$query = $qb
102
			->select($qb->createFunction('AVG(' . $qb->getColumnName('processing_duration') . ')'))
103
			->from('face_recognition_images')
104
			->where($qb->expr()->eq('model', $qb->createParameter('model')))
105
			->andWhere($qb->expr()->eq('is_processed', $qb->createParameter('is_processed')))
106
			->setParameter('model', $model)
107
			->setParameter('is_processed', True);
108
		$resultStatement = $query->execute();
109
		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
110
		$resultStatement->closeCursor();
111
112
		return (int)$data[0];
113
	}
114
115
	public function countUserImages(string $userId, $model): int {
116
		$qb = $this->db->getQueryBuilder();
117
		$query = $qb
118
			->select($qb->createFunction('COUNT(' . $qb->getColumnName('id') . ')'))
119
			->from('face_recognition_images')
120
			->where($qb->expr()->eq('user', $qb->createParameter('user')))
121
			->andWhere($qb->expr()->eq('model', $qb->createParameter('model')))
122
			->setParameter('user', $userId)
123
			->setParameter('model', $model);
124
		$resultStatement = $query->execute();
125
		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
126
		$resultStatement->closeCursor();
127
128
		return (int)$data[0];
129
	}
130
131
	public function countUserProcessedImages(string $userId, $model): int {
132
		$qb = $this->db->getQueryBuilder();
133
		$query = $qb
134
			->select($qb->createFunction('COUNT(' . $qb->getColumnName('id') . ')'))
135
			->from('face_recognition_images')
136
			->where($qb->expr()->eq('user', $qb->createParameter('user')))
137
			->andWhere($qb->expr()->eq('model', $qb->createParameter('model')))
138
			->andWhere($qb->expr()->eq('is_processed', $qb->createParameter('is_processed')))
139
			->setParameter('user', $userId)
140
			->setParameter('model', $model)
141
			->setParameter('is_processed', True);
142
		$resultStatement = $query->execute();
143
		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
144
		$resultStatement->closeCursor();
145
146
		return (int)$data[0];
147
	}
148
149
	/**
150
	 * @param IUser|null $user User for which to get images for. If not given, all images from instance are returned.
151
	 */
152
	public function findImagesWithoutFaces(IUser $user = null) {
153
		$qb = $this->db->getQueryBuilder();
154
		$params = array();
155
156
		$query = $qb
157
			->select(['id', 'user', 'file', 'model'])
158
			->from('face_recognition_images')
159
			->where($qb->expr()->eq('is_processed',  $qb->createParameter('is_processed')));
160
			$params['is_processed'] = False;
161
		if (!is_null($user)) {
162
			$query->andWhere($qb->expr()->eq('user', $qb->createParameter('user')));
163
			$params['user'] = $user->getUID();
164
		}
165
166
		$images = $this->findEntities($qb->getSQL(), $params);
167
		return $images;
168
	}
169
170
171
	public function findImagesFromPerson(string $userId, string $name, int $model): array {
172
		$qb = $this->db->getQueryBuilder();
173
		$qb->select('i.id', 'i.file')
0 ignored issues
show
Unused Code introduced by
The call to OCP\DB\QueryBuilder\IQueryBuilder::select() has too many arguments starting with 'i.file'. ( Ignorable by Annotation )

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

173
		$qb->/** @scrutinizer ignore-call */ 
174
       select('i.id', 'i.file')

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
174
			->from('face_recognition_images', 'i')
175
			->innerJoin('i', 'face_recognition_faces', 'f', $qb->expr()->eq('f.image', 'i.id'))
176
			->innerJoin('i', 'face_recognition_persons', 'p', $qb->expr()->eq('f.person', 'p.id'))
177
			->where($qb->expr()->eq('p.user', $qb->createParameter('user')))
178
			->andWhere($qb->expr()->eq('model', $qb->createParameter('model')))
179
			->andWhere($qb->expr()->eq('is_processed', $qb->createParameter('is_processed')))
180
			->andWhere($qb->expr()->like($qb->func()->lower('p.name'), $qb->createParameter('query')));
0 ignored issues
show
Bug introduced by
The method lower() does not exist on OCP\DB\QueryBuilder\IFunctionBuilder. ( Ignorable by Annotation )

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

180
			->andWhere($qb->expr()->like($qb->func()->/** @scrutinizer ignore-call */ lower('p.name'), $qb->createParameter('query')));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
181
182
		$params = array();
183
		$params['user'] = $userId;
184
		$params['model'] = $model;
185
		$params['is_processed'] = True;
186
		$params['query'] = '%' . $this->db->escapeLikeParameter(strtolower($name)) . '%';
187
		$images = $this->findEntities($qb->getSQL(), $params);
188
		return $images;
189
	}
190
191
	/**
192
	 * Writes to DB that image has been processed. Previously found faces are deleted and new ones are inserted.
193
	 * If there is exception, its stack trace is also updated.
194
	 *
195
	 * @param Image $image Image to be updated
196
	 * @param Face[] $faces Faces to insert
197
	 * @param int $duration Processing time, in milliseconds
198
	 * @param \Exception|null $e Any exception that happened during image processing
199
	 */
200
	public function imageProcessed(Image $image, array $faces, int $duration, \Exception $e = null) {
201
		$this->db->beginTransaction();
202
		try {
203
			// Update image itself
204
			//
205
			$error = null;
206
			if ($e !== null) {
207
				$error = substr($e->getMessage(), 0, 1024);
208
			}
209
210
			$qb = $this->db->getQueryBuilder();
211
			$qb->update('face_recognition_images')
212
				->set("is_processed", $qb->createNamedParameter(true, IQueryBuilder::PARAM_BOOL))
213
				->set("error", $qb->createNamedParameter($error))
214
				->set("last_processed_time", $qb->createNamedParameter(new \DateTime(), IQueryBuilder::PARAM_DATE))
215
				->set("processing_duration", $qb->createNamedParameter($duration))
216
				->where($qb->expr()->eq('id', $qb->createNamedParameter($image->id)))
217
				->execute();
218
219
			// Delete all previous faces
220
			//
221
			$qb = $this->db->getQueryBuilder();
222
			$qb->delete('face_recognition_faces')
223
				->where($qb->expr()->eq('image', $qb->createNamedParameter($image->id)))
224
				->execute();
225
226
			// Insert all faces
227
			//
228
			foreach ($faces as $face) {
229
				// Simple INSERT will close cursor and we want to be in transaction, so use hard way
230
				// todo: should we move this to FaceMapper (don't forget to hand over connection though)
231
				$qb = $this->db->getQueryBuilder();
232
				$qb->insert('face_recognition_faces')
233
					->values([
234
						'image' => $qb->createNamedParameter($image->id),
235
						'person' => $qb->createNamedParameter(null),
236
						'left' => $qb->createNamedParameter($face->left),
237
						'right' => $qb->createNamedParameter($face->right),
238
						'top' => $qb->createNamedParameter($face->top),
239
						'bottom' => $qb->createNamedParameter($face->bottom),
240
						'descriptor' => $qb->createNamedParameter(json_encode($face->descriptor)),
241
						'creation_time' => $qb->createNamedParameter($face->creationTime, IQueryBuilder::PARAM_DATE),
242
					])
243
					->execute();
244
			}
245
246
			$this->db->commit();
247
		} catch (\Exception $e) {
248
			$this->db->rollBack();
249
			throw $e;
250
		}
251
	}
252
253
	/**
254
	 * Resets image by deleting all associated faces and prepares it to be processed again
255
	 *
256
	 * @param Image $image Image to reset
257
	 */
258
	public function resetImage(Image $image) {
259
		$qb = $this->db->getQueryBuilder();
260
		$qb->update($this->getTableName())
261
			->set("is_processed", $qb->createNamedParameter(false, IQueryBuilder::PARAM_BOOL))
262
			->set("error", $qb->createNamedParameter(null))
263
			->set("last_processed_time", $qb->createNamedParameter(null))
264
			->where($qb->expr()->eq('user', $qb->createNamedParameter($image->getUser())))
265
			->andWhere($qb->expr()->eq('file', $qb->createNamedParameter($image->getFile())))
266
			->andWhere($qb->expr()->eq('model', $qb->createNamedParameter($image->getModel())))
267
			->execute();
268
	}
269
}
270