Passed
Push — settings-service ( 7803f5...566350 )
by Matias
04:05
created

Watcher::postDelete()   B

Complexity

Conditions 10
Paths 10

Size

Total Lines 60
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 10
Bugs 1 Features 0
Metric Value
cc 10
eloc 33
nc 10
nop 1
dl 0
loc 60
ccs 0
cts 34
cp 0
crap 110
rs 7.6666
c 10
b 1
f 0

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-2019 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
use OCA\FaceRecognition\Helper\Requirements;
44
45
class Watcher {
46
47
	/** @var ILogger Logger */
48
	private $logger;
49
50
	/** @var IUserManager */
51
	private $userManager;
52
53
	/** @var FaceMapper */
54
	private $faceMapper;
55
56
	/** @var ImageMapper */
57
	private $imageMapper;
58
59
	/** @var PersonMapper */
60
	private $personMapper;
61
62
	/** @var SettingsService */
63
	private $settingsService;
64
65
	/** @var FileService */
66
	private $fileService;
67
68
	/** @var FaceManagementService */
69
	private $faceManagementService;
70
71
	/**
72
	 * Watcher constructor.
73
	 *
74
	 * @param ILogger $logger
75
	 * @param IUserManager $userManager
76
	 * @param FaceMapper $faceMapper
77
	 * @param ImageMapper $imageMapper
78
	 * @param PersonMapper $personMapper
79
	 * @param SettingsService $settingsService
80
	 * @param FileService $fileService
81
	 * @param FaceManagementService $faceManagementService
82
	 */
83
	public function __construct(ILogger               $logger,
84
	                            IUserManager          $userManager,
85
	                            FaceMapper            $faceMapper,
86
	                            ImageMapper           $imageMapper,
87
	                            PersonMapper          $personMapper,
88
	                            SettingsService       $settingsService,
89
	                            FileService           $fileService,
90
	                            FaceManagementService $faceManagementService)
91
	{
92
		$this->logger                = $logger;
93
		$this->userManager           = $userManager;
94
		$this->faceMapper            = $faceMapper;
95
		$this->imageMapper           = $imageMapper;
96
		$this->personMapper          = $personMapper;
97
		$this->settingsService       = $settingsService;
98
		$this->fileService           = $fileService;
99
		$this->faceManagementService = $faceManagementService;
100
	}
101
102
	/**
103
	 * A node has been updated. We just store the file id
104
	 * with the current user in the DB
105
	 *
106
	 * @param Node $node
107
	 */
108 17
	public function postWrite(Node $node) {
109 17
		if (!$this->fileService->isAllowedNode($node)) {
110
			// Nextcloud sends the Hooks when create thumbnails for example.
111
			return;
112
		}
113
114 17
		if ($node instanceof Folder) {
115 17
			return;
116
		}
117
118
		$owner = \OC::$server->getUserSession()->getUser()->getUID();
119
		if (!$this->userManager->userExists($owner)) {
120
			$this->logger->debug(
121
				"Skipping inserting image " . $node->getName() . " because it seems that user  " . $owner . " doesn't exist");
122
			return;
123
		}
124
125
		$enabled = $this->settingsService->getUserEnabled($owner);
126
		if (!$enabled) {
127
			$this->logger->debug('The user ' . $owner . ' not have the analysis enabled. Skipping');
128
			return;
129
		}
130
131
		if ($node->getName() === FileService::NOMEDIA_FILE) {
132
			// If user added this file, it means all images in this and all child directories should be removed.
133
			// Instead of doing that here, it's better to just add flag that image removal should be done.
134
			$this->settingsService->setNeedRemoveStaleImages(true, $owner);
135
			return;
136
		}
137
138
		if ($node->getName() === FileService::FACERECOGNITION_SETTINGS_FILE) {
139
			// This file can enable or disable the analysis, so I have to look for new files and forget others.
140
			$this->settingsService->setNeedRemoveStaleImages(true, $owner);
141
			$this->settingsService->setUserFullScanDone(false, $owner);
142
			return;
143
		}
144
145
		if (!Requirements::isImageTypeSupported($node->getMimeType())) {
146
			return;
147
		}
148
149
		if ($this->fileService->isUnderNoDetection($node)) {
150
			$this->logger->debug(
151
				"Skipping inserting image " . $node->getName() . " because is inside an folder that contains a .nomedia file");
152
			return;
153
		}
154
155
		$this->logger->debug("Inserting/updating image " . $node->getName() . " for face recognition");
156
157
		$image = new Image();
158
		$image->setUser($owner);
159
		$image->setFile($node->getId());
160
		$image->setModel($this->settingsService->getCurrentFaceModel());
161
162
		$imageId = $this->imageMapper->imageExists($image);
163
		if ($imageId === null) {
164
			// todo: can we have larger transaction with bulk insert?
165
			$this->imageMapper->insert($image);
166
		} else {
167
			$this->imageMapper->resetImage($image);
168
			// note that invalidatePersons depends on existence of faces for a given image,
169
			// and we must invalidate before we delete faces!
170
			$this->personMapper->invalidatePersons($imageId);
171
172
			// Fetch all faces to be deleted before deleting them, and then delete them
173
			$facesToRemove = $this->faceMapper->findByImage($imageId);
174
			$this->faceMapper->removeFaces($imageId);
175
176
			// If any person is now without faces, remove those (empty) persons
177
			foreach ($facesToRemove as $faceToRemove) {
178
				if ($faceToRemove->getPerson() !== null) {
179
					$this->personMapper->removeIfEmpty($faceToRemove->getPerson());
180
				}
181
			}
182
		}
183
	}
184
185
	/**
186
	 * A node has been deleted. Remove faces with file id
187
	 * with the current user in the DB
188
	 *
189
	 * @param Node $node
190
	 */
191
	public function postDelete(Node $node) {
192
		if (!$this->fileService->isAllowedNode($node)) {
193
			// Nextcloud sends the Hooks when create thumbnails for example.
194
			return;
195
		}
196
197
		if ($node instanceof Folder) {
198
			return;
199
		}
200
201
		$owner = \OC::$server->getUserSession()->getUser()->getUID();
202
		$enabled = $this->settingsService->getUserEnabled($owner);
203
		if (!$enabled) {
204
			$this->logger->debug('The user ' . $owner . ' not have the analysis enabled. Skipping');
205
			return;
206
		}
207
208
		if ($node->getName() === FileService::NOMEDIA_FILE) {
209
			// If user deleted file named .nomedia, that means all images in this and all child directories should be added.
210
			// But, instead of doing that here, better option seem to be to just reset flag that image scan is not done.
211
			// This will trigger another round of image crawling in AddMissingImagesTask for this user and those images will be added.
212
			$this->settingsService->setNeedRemoveStaleImages(true, $owner);
213
			return;
214
		}
215
216
		if ($node->getName() === FileService::FACERECOGNITION_SETTINGS_FILE) {
217
			// This file can enable or disable the analysis, so I have to look for new files and forget others.
218
			$this->settingsService->setNeedRemoveStaleImages(true, $owner);
219
			$this->settingsService->setUserFullScanDone(false, $owner);
220
			return;
221
		}
222
223
		if (!Requirements::isImageTypeSupported($node->getMimeType())) {
224
			return;
225
		}
226
227
		$this->logger->debug("Deleting image " . $node->getName() . " from face recognition");
228
229
		$image = new Image();
230
		$image->setUser($owner);
231
		$image->setFile($node->getId());
232
		$image->setModel($this->settingsService->getCurrentFaceModel());
233
234
		$imageId = $this->imageMapper->imageExists($image);
235
		if ($imageId !== null) {
236
			// note that invalidatePersons depends on existence of faces for a given image,
237
			// and we must invalidate before we delete faces!
238
			$this->personMapper->invalidatePersons($imageId);
239
240
			// Fetch all faces to be deleted before deleting them, and then delete them
241
			$facesToRemove = $this->faceMapper->findByImage($imageId);
242
			$this->faceMapper->removeFaces($imageId);
243
244
			$image->setId($imageId);
245
			$this->imageMapper->delete($image);
246
247
			// If any person is now without faces, remove those (empty) persons
248
			foreach ($facesToRemove as $faceToRemove) {
249
				if ($faceToRemove->getPerson() !== null) {
250
					$this->personMapper->removeIfEmpty($faceToRemove->getPerson());
251
				}
252
			}
253
		}
254
	}
255
256
	/**
257
	 * A user has been deleted. Cleanup everything from this user.
258
	 *
259
	 * @param \OC\User\User $user Deleted user
260
	 */
261
	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...
262
		$userId = $user->getUid();
263
		$this->faceManagementService->resetAllForUser($userId);
264
		$this->logger->info("Removed all face recognition data for deleted user " . $userId);
265
	}
266
}
267