Passed
Push — shared-storage-experiments ( 606554...2addb2 )
by Matias
08:21
created

Watcher::postDelete()   B

Complexity

Conditions 11
Paths 17

Size

Total Lines 62
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 5
Bugs 1 Features 0
Metric Value
cc 11
eloc 34
c 5
b 1
f 0
nc 17
nop 1
dl 0
loc 62
ccs 0
cts 34
cp 0
crap 132
rs 7.3166

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, 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\IHomeStorage;
29
use OCP\Files\Node;
30
use OCP\IConfig;
31
use OCP\ILogger;
32
use OCP\IUserManager;
33
use OCP\User;
34
35
use OCA\FaceRecognition\FaceManagementService;
36
use OCA\FaceRecognition\Service\FileService;
37
38
use OCA\FaceRecognition\BackgroundJob\Tasks\AddMissingImagesTask;
39
use OCA\FaceRecognition\BackgroundJob\Tasks\StaleImagesRemovalTask;
40
use OCA\FaceRecognition\Db\Face;
41
use OCA\FaceRecognition\Db\Image;
42
use OCA\FaceRecognition\Db\FaceMapper;
43
use OCA\FaceRecognition\Db\ImageMapper;
44
use OCA\FaceRecognition\Db\PersonMapper;
45
use OCA\FaceRecognition\Helper\Requirements;
46
use OCA\FaceRecognition\Migration\AddDefaultFaceModel;
47
48
class Watcher {
49
50
	/** @var IConfig Config */
51
	private $config;
52
53
	/** @var ILogger Logger */
54
	private $logger;
55
56
	/** @var IUserManager */
57
	private $userManager;
58
59
	/** @var FaceMapper */
60
	private $faceMapper;
61
62
	/** @var ImageMapper */
63
	private $imageMapper;
64
65
	/** @var PersonMapper */
66
	private $personMapper;
67
68
	/** @var FileService */
69
	private $fileService;
70
71
	/** @var FaceManagementService */
72
	private $faceManagementService;
73
74
	/**
75
	 * Watcher constructor.
76
	 *
77
	 * @param IConfig $config
78
	 * @param ILogger $logger
79
	 * @param IUserManager $userManager
80
	 * @param FaceMapper $faceMapper
81
	 * @param ImageMapper $imageMapper
82
	 * @param PersonMapper $personMapper
83
	 * @param FileService $fileService
84
	 * @param FaceManagementService $faceManagementService
85
	 */
86
	public function __construct(IConfig               $config,
87
	                            ILogger               $logger,
88
	                            IUserManager          $userManager,
89
	                            FaceMapper            $faceMapper,
90
	                            ImageMapper           $imageMapper,
91
	                            PersonMapper          $personMapper,
92
	                            FileService           $fileService,
93
	                            FaceManagementService $faceManagementService)
94
	{
95
		$this->config                = $config;
96
		$this->logger                = $logger;
97
		$this->userManager           = $userManager;
98
		$this->faceMapper            = $faceMapper;
99
		$this->imageMapper           = $imageMapper;
100
		$this->personMapper          = $personMapper;
101
		$this->fileService           = $fileService;
102
		$this->faceManagementService = $faceManagementService;
103
	}
104
105
	/**
106
	 * A node has been updated. We just store the file id
107
	 * with the current user in the DB
108
	 *
109
	 * @param Node $node
110
	 */
111 16
	public function postWrite(Node $node) {
112 16
		$model = intval($this->config->getAppValue('facerecognition', 'model', AddDefaultFaceModel::DEFAULT_FACE_MODEL_ID));
113 16
		$handleSharedFiles = $this->config->getAppValue('facerecognition', 'handle-shared-files', 'false');
114
115 16
		if ($this->fileService->isUserFile($node)) {
116 16
			$owner = $node->getOwner()->getUid();
117
		}
118 16
		else if ($handleSharedFiles === 'true' && $this->fileService->isSharedFile($node)) {
119
			// If we are going to analyze the shared files, we must 'appropriate' it.
120
			$owner = User::getUser();
0 ignored issues
show
Deprecated Code introduced by
The function OCP\User::getUser() has been deprecated: 8.0.0 Use \OC::$server->getUserSession()->getUser()->getUID() ( Ignorable by Annotation )

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

120
			$owner = /** @scrutinizer ignore-deprecated */ User::getUser();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
121
		}
122
		else {
123
			// Nextcloud also sends the Hooks when create thumbnails for example.
124 16
			return;
125
		}
126
127 16
		if ($node instanceof Folder) {
128 16
			return;
129
		}
130
131
		$enabled = $this->config->getUserValue($owner, 'facerecognition', 'enabled', 'false');
132
		if ($enabled !== 'true') {
133
			$this->logger->debug('The user ' . $owner . ' not have the analysis enabled. Skipping');
134
			return;
135
		}
136
137
		if ($node->getName() === '.nomedia') {
138
			// If user added this file, it means all images in this and all child directories should be removed.
139
			// Instead of doing that here, it's better to just add flag that image removal should be done.
140
			$this->config->setUserValue($owner, 'facerecognition', StaleImagesRemovalTask::STALE_IMAGES_REMOVAL_NEEDED_KEY, 'true');
141
			return;
142
		}
143
144
		if (!Requirements::isImageTypeSupported($node->getMimeType())) {
145
			return;
146
		}
147
148
		if (!$this->userManager->userExists($owner)) {
149
			$this->logger->debug(
150
				"Skipping inserting image " . $node->getName() . " because it seems that user  " . $owner . " doesn't exist");
151
			return;
152
		}
153
154
		if ($this->fileService->isUnderNoMedia($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($model);
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->removeFaces($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
	public function postDelete(Node $node) {
197
		$model = intval($this->config->getAppValue('facerecognition', 'model', AddDefaultFaceModel::DEFAULT_FACE_MODEL_ID));
198
		$handleSharedFiles = $this->config->getAppValue('facerecognition', 'handle-shared-files', 'false');
199
200
		if ($this->fileService->isUserFile($node)) {
201
			$owner = $node->getOwner()->getUid();
202
		}
203
		else if ($handleSharedFiles === 'true' && $this->fileService->isSharedFile($node)) {
204
			// If we are going to analyze the shared files, we must 'appropriate' it.
205
			$owner = User::getUser();
0 ignored issues
show
Deprecated Code introduced by
The function OCP\User::getUser() has been deprecated: 8.0.0 Use \OC::$server->getUserSession()->getUser()->getUID() ( Ignorable by Annotation )

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

205
			$owner = /** @scrutinizer ignore-deprecated */ User::getUser();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
206
		}
207
		else {
208
			// Nextcloud also sends the Hooks when create thumbnails for example.
209
			return;
210
		}
211
212
		if ($node instanceof Folder) {
213
			return;
214
		}
215
216
		$enabled = $this->config->getUserValue($owner, 'facerecognition', 'enabled', 'false');
217
		if ($enabled !== 'true') {
218
			$this->logger->debug('The user ' . $owner . ' not have the analysis enabled. Skipping');
219
			return;
220
		}
221
222
		if ($node->getName() === '.nomedia') {
223
			// If user deleted file named .nomedia, that means all images in this and all child directories should be added.
224
			// But, instead of doing that here, better option seem to be to just reset flag that image scan is not done.
225
			// This will trigger another round of image crawling in AddMissingImagesTask for this user and those images will be added.
226
			$this->config->setUserValue($owner, 'facerecognition', AddMissingImagesTask::FULL_IMAGE_SCAN_DONE_KEY, 'false');
227
			return;
228
		}
229
230
		if (!Requirements::isImageTypeSupported($node->getMimeType())) {
231
			return;
232
		}
233
234
		$this->logger->debug("Deleting image " . $node->getName() . " from face recognition");
235
236
		$image = new Image();
237
		$image->setUser($owner);
238
		$image->setFile($node->getId());
239
		$image->setModel($model);
240
241
		$imageId = $this->imageMapper->imageExists($image);
242
		if ($imageId !== null) {
243
			// note that invalidatePersons depends on existence of faces for a given image,
244
			// and we must invalidate before we delete faces!
245
			$this->personMapper->invalidatePersons($imageId);
246
247
			// Fetch all faces to be deleted before deleting them, and then delete them
248
			$facesToRemove = $this->faceMapper->findByImage($imageId);
249
			$this->faceMapper->removeFaces($imageId);
250
251
			$image->setId($imageId);
252
			$this->imageMapper->delete($image);
253
254
			// If any person is now without faces, remove those (empty) persons
255
			foreach ($facesToRemove as $faceToRemove) {
256
				if ($faceToRemove->getPerson() !== null) {
257
					$this->personMapper->removeIfEmpty($faceToRemove->getPerson());
258
				}
259
			}
260
		}
261
	}
262
263
	/**
264
	 * A user has been deleted. Cleanup everything from this user.
265
	 *
266
	 * @param \OC\User\User $user Deleted user
267
	 */
268 16
	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...
269 16
		$userId = $user->getUid();
270 16
		$this->faceManagementService->resetAllForUser($userId);
271 16
		$this->logger->info("Removed all face recognition data for deleted user " . $userId);
272 16
	}
273
}
274