Passed
Push — ignore-other-background-jobs ( 443190 )
by Matias
10:06
created

Watcher::postDelete()   C

Complexity

Conditions 12
Paths 12

Size

Total Lines 72
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 15
Bugs 1 Features 0
Metric Value
cc 12
eloc 40
c 15
b 1
f 0
nc 12
nop 1
dl 0
loc 72
ccs 0
cts 41
cp 0
crap 156
rs 6.9666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
		if (\OC::$server->getUserSession()->isLoggedIn()) {
123
			$this->logger->debug('Skipping since the file was not changed by a logged in user.');
124
			return;
125
		}
126
127
		$owner = \OC::$server->getUserSession()->getUser()->getUID();
128
		if (!$this->userManager->userExists($owner)) {
129
			$this->logger->debug(
130
				"Skipping inserting file " . $node->getName() . " because it seems that user  " . $owner . " doesn't exist");
131
			return;
132
		}
133
134
		$enabled = $this->settingsService->getUserEnabled($owner);
135
		if (!$enabled) {
136
			$this->logger->debug('The user ' . $owner . ' not have the analysis enabled. Skipping');
137
			return;
138
		}
139
140
		if ($node->getName() === FileService::NOMEDIA_FILE) {
141
			// If user added this file, it means all images in this and all child directories should be removed.
142
			// Instead of doing that here, it's better to just add flag that image removal should be done.
143
			$this->settingsService->setNeedRemoveStaleImages(true, $owner);
144
			return;
145
		}
146
147
		if ($node->getName() === FileService::FACERECOGNITION_SETTINGS_FILE) {
148
			// This file can enable or disable the analysis, so I have to look for new files and forget others.
149
			$this->settingsService->setNeedRemoveStaleImages(true, $owner);
150
			$this->settingsService->setUserFullScanDone(false, $owner);
151
			return;
152
		}
153
154
		if (!$this->settingsService->isAllowedMimetype($node->getMimeType())) {
155
			// The file is not an image or the model does not support it
156
			return;
157
		}
158
159
		if ($this->fileService->isUnderNoDetection($node)) {
160
			$this->logger->debug(
161
				"Skipping inserting image " . $node->getName() . " because is inside an folder that contains a .nomedia file");
162
			return;
163
		}
164
165
		$this->logger->debug("Inserting/updating image " . $node->getName() . " for face recognition");
166
167
		$image = new Image();
168
		$image->setUser($owner);
169
		$image->setFile($node->getId());
170
		$image->setModel($modelId);
171
172
		$imageId = $this->imageMapper->imageExists($image);
173
		if ($imageId === null) {
174
			// todo: can we have larger transaction with bulk insert?
175
			$this->imageMapper->insert($image);
176
		} else {
177
			$this->imageMapper->resetImage($image);
178
			// note that invalidatePersons depends on existence of faces for a given image,
179
			// and we must invalidate before we delete faces!
180
			$this->personMapper->invalidatePersons($imageId);
181
182
			// Fetch all faces to be deleted before deleting them, and then delete them
183
			$facesToRemove = $this->faceMapper->findByImage($imageId);
184
			$this->faceMapper->removeFromImage($imageId);
185
186
			// If any person is now without faces, remove those (empty) persons
187
			foreach ($facesToRemove as $faceToRemove) {
188
				if ($faceToRemove->getPerson() !== null) {
189
					$this->personMapper->removeIfEmpty($faceToRemove->getPerson());
190
				}
191
			}
192
		}
193
	}
194
195
	/**
196
	 * A node has been deleted. Remove faces with file id
197
	 * with the current user in the DB
198
	 *
199
	 * @param Node $node
200
	 */
201
	public function postDelete(Node $node) {
202
		if (!$this->fileService->isAllowedNode($node)) {
203
			// Nextcloud sends the Hooks when create thumbnails for example.
204
			return;
205
		}
206
207
		if ($node instanceof Folder) {
208
			return;
209
		}
210
211
		$modelId = $this->settingsService->getCurrentFaceModel();
212
		if ($modelId === SettingsService::FALLBACK_CURRENT_MODEL) {
213
			$this->logger->debug("Skipping deleting file since there are no configured model");
214
			return;
215
		}
216
217
		if (\OC::$server->getUserSession()->isLoggedIn()) {
218
			$this->logger->debug('Skipping since the file was not deleted by a logged in user.');
219
			return;
220
		}
221
222
		$owner = \OC::$server->getUserSession()->getUser()->getUID();
223
		$enabled = $this->settingsService->getUserEnabled($owner);
224
		if (!$enabled) {
225
			$this->logger->debug('The user ' . $owner . ' not have the analysis enabled. Skipping');
226
			return;
227
		}
228
229
		if ($node->getName() === FileService::NOMEDIA_FILE) {
230
			// If user deleted file named .nomedia, that means all images in this and all child directories should be added.
231
			// But, instead of doing that here, better option seem to be to just reset flag that image scan is not done.
232
			// This will trigger another round of image crawling in AddMissingImagesTask for this user and those images will be added.
233
			$this->settingsService->setUserFullScanDone(false, $owner);
234
			return;
235
		}
236
237
		if ($node->getName() === FileService::FACERECOGNITION_SETTINGS_FILE) {
238
			// This file can enable or disable the analysis, so I have to look for new files and forget others.
239
			$this->settingsService->setNeedRemoveStaleImages(true, $owner);
240
			$this->settingsService->setUserFullScanDone(false, $owner);
241
			return;
242
		}
243
244
		if (!$this->settingsService->isAllowedMimetype($node->getMimeType())) {
245
			// The file is not an image or the model does not support it
246
			return;
247
		}
248
249
		$this->logger->debug("Deleting image " . $node->getName() . " from face recognition");
250
251
		$image = new Image();
252
		$image->setUser($owner);
253
		$image->setFile($node->getId());
254
		$image->setModel($modelId);
255
256
		$imageId = $this->imageMapper->imageExists($image);
257
		if ($imageId !== null) {
258
			// note that invalidatePersons depends on existence of faces for a given image,
259
			// and we must invalidate before we delete faces!
260
			$this->personMapper->invalidatePersons($imageId);
261
262
			// Fetch all faces to be deleted before deleting them, and then delete them
263
			$facesToRemove = $this->faceMapper->findByImage($imageId);
264
			$this->faceMapper->removeFromImage($imageId);
265
266
			$image->setId($imageId);
267
			$this->imageMapper->delete($image);
268
269
			// If any person is now without faces, remove those (empty) persons
270
			foreach ($facesToRemove as $faceToRemove) {
271
				if ($faceToRemove->getPerson() !== null) {
272
					$this->personMapper->removeIfEmpty($faceToRemove->getPerson());
273
				}
274
			}
275
		}
276
	}
277
278
	/**
279
	 * A user has been deleted. Cleanup everything from this user.
280
	 *
281
	 * @param \OC\User\User $user Deleted user
282
	 */
283 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...
284 28
		$userId = $user->getUid();
285 28
		$this->faceManagementService->resetAllForUser($userId);
286 28
		$this->logger->info("Removed all face recognition data for deleted user " . $userId);
287 28
	}
288
}
289