Completed
Push — master ( 62184d...de56a6 )
by Matias
04:19 queued 04:16
created

Watcher::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 9
Bugs 1 Features 0
Metric Value
cc 1
eloc 8
c 9
b 1
f 0
nc 1
nop 8
dl 0
loc 17
ccs 9
cts 9
cp 1
crap 1
rs 10

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, Roeland Jago Douma <[email protected]>
4
 * @copyright Copyright (c) 2017-2020 Matias De lellis <[email protected]>
5
 *
6
 * @author Roeland Jago Douma <[email protected]>
7
 * @author Matias De lellis <[email protected]>
8
 *
9
 * @license GNU AGPL version 3 or any later version
10
 *
11
 * This program is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU Affero General Public License as
13
 * published by the Free Software Foundation, either version 3 of the
14
 * License, or (at your option) any later version.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU Affero General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Affero General Public License
22
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23
 *
24
 */
25
namespace OCA\FaceRecognition;
26
27
use OCP\Files\Folder;
28
use OCP\Files\Node;
29
use OCP\ILogger;
30
use OCP\IUserManager;
31
32
use OCA\FaceRecognition\Service\FaceManagementService;
33
use OCA\FaceRecognition\Service\FileService;
34
use OCA\FaceRecognition\Service\SettingsService;
35
36
use OCA\FaceRecognition\Db\Face;
37
use OCA\FaceRecognition\Db\Image;
38
39
use OCA\FaceRecognition\Db\FaceMapper;
40
use OCA\FaceRecognition\Db\ImageMapper;
41
use OCA\FaceRecognition\Db\PersonMapper;
42
43
class Watcher {
44
45
	/** @var ILogger Logger */
46
	private $logger;
47
48
	/** @var IUserManager */
49
	private $userManager;
50
51
	/** @var FaceMapper */
52
	private $faceMapper;
53
54
	/** @var ImageMapper */
55
	private $imageMapper;
56
57
	/** @var PersonMapper */
58
	private $personMapper;
59
60
	/** @var SettingsService */
61
	private $settingsService;
62
63
	/** @var FileService */
64
	private $fileService;
65
66
	/** @var FaceManagementService */
67
	private $faceManagementService;
68
69
	/**
70
	 * Watcher constructor.
71
	 *
72
	 * @param ILogger $logger
73
	 * @param IUserManager $userManager
74
	 * @param FaceMapper $faceMapper
75
	 * @param ImageMapper $imageMapper
76
	 * @param PersonMapper $personMapper
77
	 * @param SettingsService $settingsService
78
	 * @param FileService $fileService
79
	 * @param FaceManagementService $faceManagementService
80
	 */
81 1
	public function __construct(ILogger               $logger,
82
	                            IUserManager          $userManager,
83
	                            FaceMapper            $faceMapper,
84
	                            ImageMapper           $imageMapper,
85
	                            PersonMapper          $personMapper,
86
	                            SettingsService       $settingsService,
87
	                            FileService           $fileService,
88
	                            FaceManagementService $faceManagementService)
89
	{
90 1
		$this->logger                = $logger;
91 1
		$this->userManager           = $userManager;
92 1
		$this->faceMapper            = $faceMapper;
93 1
		$this->imageMapper           = $imageMapper;
94 1
		$this->personMapper          = $personMapper;
95 1
		$this->settingsService       = $settingsService;
96 1
		$this->fileService           = $fileService;
97 1
		$this->faceManagementService = $faceManagementService;
98 1
	}
99
100
	/**
101
	 * A node has been updated. We just store the file id
102
	 * with the current user in the DB
103
	 *
104
	 * @param Node $node
105
	 */
106 28
	public function postWrite(Node $node) {
107 28
		if (!$this->fileService->isAllowedNode($node)) {
108
			// Nextcloud sends the Hooks when create thumbnails for example.
109 28
			return;
110
		}
111
112 28
		if ($node instanceof Folder) {
113 28
			return;
114
		}
115
116
		$modelId = $this->settingsService->getCurrentFaceModel();
117
		if ($modelId === SettingsService::FALLBACK_CURRENT_MODEL) {
118
			$this->logger->debug("Skipping inserting file since there are no configured model");
119
			return;
120
		}
121
122
		$owner = \OC::$server->getUserSession()->getUser()->getUID();
123
		if (!$this->userManager->userExists($owner)) {
124
			$this->logger->debug(
125
				"Skipping inserting file " . $node->getName() . " because it seems that user  " . $owner . " doesn't exist");
126
			return;
127
		}
128
129
		$enabled = $this->settingsService->getUserEnabled($owner);
130
		if (!$enabled) {
131
			$this->logger->debug('The user ' . $owner . ' not have the analysis enabled. Skipping');
132
			return;
133
		}
134
135
		if ($node->getName() === FileService::NOMEDIA_FILE) {
136
			// If user added this file, it means all images in this and all child directories should be removed.
137
			// Instead of doing that here, it's better to just add flag that image removal should be done.
138
			$this->settingsService->setNeedRemoveStaleImages(true, $owner);
139
			return;
140
		}
141
142
		if ($node->getName() === FileService::FACERECOGNITION_SETTINGS_FILE) {
143
			// This file can enable or disable the analysis, so I have to look for new files and forget others.
144
			$this->settingsService->setNeedRemoveStaleImages(true, $owner);
145
			$this->settingsService->setUserFullScanDone(false, $owner);
146
			return;
147
		}
148
149
		if (!$this->settingsService->isAllowedMimetype($node->getMimeType())) {
150
			// The file is not an image or the model does not support it
151
			return;
152
		}
153
154
		if ($this->fileService->isUnderNoDetection($node)) {
155
			$this->logger->debug(
156
				"Skipping inserting image " . $node->getName() . " because is inside an folder that contains a .nomedia file");
157
			return;
158
		}
159
160
		$this->logger->debug("Inserting/updating image " . $node->getName() . " for face recognition");
161
162
		$image = new Image();
163
		$image->setUser($owner);
164
		$image->setFile($node->getId());
165
		$image->setModel($modelId);
166
167
		$imageId = $this->imageMapper->imageExists($image);
168
		if ($imageId === null) {
169
			// todo: can we have larger transaction with bulk insert?
170
			$this->imageMapper->insert($image);
171
		} else {
172
			$this->imageMapper->resetImage($image);
173
			// note that invalidatePersons depends on existence of faces for a given image,
174
			// and we must invalidate before we delete faces!
175
			$this->personMapper->invalidatePersons($imageId);
176
177
			// Fetch all faces to be deleted before deleting them, and then delete them
178
			$facesToRemove = $this->faceMapper->findByImage($imageId);
179
			$this->faceMapper->removeFromImage($imageId);
180
181
			// If any person is now without faces, remove those (empty) persons
182
			foreach ($facesToRemove as $faceToRemove) {
183
				if ($faceToRemove->getPerson() !== null) {
184
					$this->personMapper->removeIfEmpty($faceToRemove->getPerson());
185
				}
186
			}
187
		}
188
	}
189
190
	/**
191
	 * A node has been deleted. Remove faces with file id
192
	 * with the current user in the DB
193
	 *
194
	 * @param Node $node
195
	 */
196 28
	public function postDelete(Node $node) {
197 28
		if (!$this->fileService->isAllowedNode($node)) {
198
			// Nextcloud sends the Hooks when create thumbnails for example.
199 28
			return;
200
		}
201
202
		if ($node instanceof Folder) {
203
			return;
204
		}
205
206
		$modelId = $this->settingsService->getCurrentFaceModel();
207
		if ($modelId === SettingsService::FALLBACK_CURRENT_MODEL) {
208
			$this->logger->debug("Skipping deleting file since there are no configured model");
209
			return;
210
		}
211
212
		$owner = \OC::$server->getUserSession()->getUser()->getUID();
213
		$enabled = $this->settingsService->getUserEnabled($owner);
214
		if (!$enabled) {
215
			$this->logger->debug('The user ' . $owner . ' not have the analysis enabled. Skipping');
216
			return;
217
		}
218
219
		if ($node->getName() === FileService::NOMEDIA_FILE) {
220
			// If user deleted file named .nomedia, that means all images in this and all child directories should be added.
221
			// But, instead of doing that here, better option seem to be to just reset flag that image scan is not done.
222
			// This will trigger another round of image crawling in AddMissingImagesTask for this user and those images will be added.
223
			$this->settingsService->setUserFullScanDone(false, $owner);
224
			return;
225
		}
226
227
		if ($node->getName() === FileService::FACERECOGNITION_SETTINGS_FILE) {
228
			// This file can enable or disable the analysis, so I have to look for new files and forget others.
229
			$this->settingsService->setNeedRemoveStaleImages(true, $owner);
230
			$this->settingsService->setUserFullScanDone(false, $owner);
231
			return;
232
		}
233
234
		if (!$this->settingsService->isAllowedMimetype($node->getMimeType())) {
235
			// The file is not an image or the model does not support it
236
			return;
237
		}
238
239
		$this->logger->debug("Deleting image " . $node->getName() . " from face recognition");
240
241
		$image = new Image();
242
		$image->setUser($owner);
243
		$image->setFile($node->getId());
244
		$image->setModel($modelId);
245
246
		$imageId = $this->imageMapper->imageExists($image);
247
		if ($imageId !== null) {
248
			// note that invalidatePersons depends on existence of faces for a given image,
249
			// and we must invalidate before we delete faces!
250
			$this->personMapper->invalidatePersons($imageId);
251
252
			// Fetch all faces to be deleted before deleting them, and then delete them
253
			$facesToRemove = $this->faceMapper->findByImage($imageId);
254
			$this->faceMapper->removeFromImage($imageId);
255
256
			$image->setId($imageId);
257
			$this->imageMapper->delete($image);
258
259
			// If any person is now without faces, remove those (empty) persons
260
			foreach ($facesToRemove as $faceToRemove) {
261
				if ($faceToRemove->getPerson() !== null) {
262
					$this->personMapper->removeIfEmpty($faceToRemove->getPerson());
263
				}
264
			}
265
		}
266
	}
267
268
	/**
269
	 * A user has been deleted. Cleanup everything from this user.
270
	 *
271
	 * @param \OC\User\User $user Deleted user
272
	 */
273 28
	public function postUserDelete(\OC\User\User $user) {
0 ignored issues
show
Bug introduced by
The type OC\User\User 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...
274 28
		$userId = $user->getUid();
275 28
		$this->faceManagementService->resetAllForUser($userId);
276 28
		$this->logger->info("Removed all face recognition data for deleted user " . $userId);
277 28
	}
278
}
279