Passed
Push — cleanup-after-deleted-users ( 2c4c8c...e14e55 )
by Branko
02:21
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 0
Metric Value
cc 1
eloc 8
nc 1
nop 8
dl 0
loc 17
ccs 9
cts 9
cp 1
crap 1
rs 10
c 0
b 0
f 0

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, 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\IDBConnection;
32
use OCP\ILogger;
33
use OCP\IUserManager;
34
35
use OCA\FaceRecognition\FaceManagementService;
36
37
use OCA\FaceRecognition\BackgroundJob\Tasks\AddMissingImagesTask;
38
use OCA\FaceRecognition\BackgroundJob\Tasks\StaleImagesRemovalTask;
39
use OCA\FaceRecognition\Db\Face;
40
use OCA\FaceRecognition\Db\Image;
41
use OCA\FaceRecognition\Db\FaceMapper;
42
use OCA\FaceRecognition\Db\ImageMapper;
43
use OCA\FaceRecognition\Db\PersonMapper;
44
use OCA\FaceRecognition\Helper\Requirements;
45
use OCA\FaceRecognition\Migration\AddDefaultFaceModel;
46
47
class Watcher {
48
49
	/** @var IConfig Config */
50
	private $config;
51
52
	/** @var ILogger Logger */
53
	private $logger;
54
55
	/** @var IDBConnection */
56
	private $connection;
57
58
	/** @var IUserManager */
59
	private $userManager;
60
61
	/** @var FaceMapper */
62
	private $faceMapper;
63
64
	/** @var ImageMapper */
65
	private $imageMapper;
66
67
	/** @var PersonMapper */
68
	private $personMapper;
69
70
	/** @var FaceManagementService */
71
	private $faceManagementService;
72
73
	/**
74
	 * Watcher constructor.
75
	 *
76
	 * @param IConfig $config
77
	 * @param ILogger $logger
78
	 * @param IDBConnection $connection
79
	 * @param IUserManager $userManager
80
	 * @param FaceMapper $faceMapper
81
	 * @param ImageMapper $imageMapper
82
	 * @param PersonMapper $personMapper
83
	 * @param FaceManagementService $faceManagementService
84
	 */
85 8
	public function __construct(IConfig               $config,
86
	                            ILogger               $logger,
87
	                            IDBConnection         $connection,
88
	                            IUserManager          $userManager,
89
	                            FaceMapper            $faceMapper,
90
	                            ImageMapper           $imageMapper,
91
	                            PersonMapper          $personMapper,
92
	                            FaceManagementService $faceManagementService)
93
	{
94 8
		$this->config = $config;
95 8
		$this->logger = $logger;
96 8
		$this->connection = $connection;
97 8
		$this->userManager = $userManager;
98 8
		$this->faceMapper = $faceMapper;
99 8
		$this->imageMapper = $imageMapper;
100 8
		$this->personMapper = $personMapper;
101 8
		$this->faceManagementService = $faceManagementService;
102 8
	}
103
104
	/**
105
	 * A node has been updated. We just store the file id
106
	 * with the current user in the DB
107
	 *
108
	 * @param Node $node
109
	 */
110 8
	public function postWrite(Node $node) {
111 8
		$model = intval($this->config->getAppValue('facerecognition', 'model', AddDefaultFaceModel::DEFAULT_FACE_MODEL_ID));
112
113
		// todo: should we also care about this too: instanceOfStorage(ISharedStorage::class);
114 8
		if ($node->getStorage()->instanceOfStorage(IHomeStorage::class) === false) {
115 8
			return;
116
		}
117
118 8
		if ($node instanceof Folder) {
119 8
			return;
120
		}
121
122
		$owner = $node->getOwner()->getUid();
123
124
		if ($node->getName() === '.nomedia') {
125
			// If user added this file, it means all images in this and all child directories should be removed.
126
			// Instead of doing that here, it's better to just add flag that image removal should be done.
127
			$this->config->setUserValue($owner, 'facerecognition', StaleImagesRemovalTask::STALE_IMAGES_REMOVAL_NEEDED_KEY, 'true');
128
			return;
129
		}
130
131
		if (!Requirements::isImageTypeSupported($node->getMimeType())) {
132
			return;
133
		}
134
135
		if (!$this->userManager->userExists($owner)) {
136
			$this->logger->debug(
137
				"Skipping inserting image " . $node->getName() . " because it seems that user  " . $owner . " doesn't exist");
138
			return;
139
		}
140
141
		// If we detect .nomedia file anywhere on the path to root folder (id===null), bail out
142
		$parentNode = $node->getParent();
143
		while (($parentNode instanceof Folder) && ($parentNode->getId() !== null)) {
144
			if ($parentNode->nodeExists('.nomedia')) {
145
				$this->logger->debug(
146
					"Skipping inserting image " . $node->getName() . " because directory " . $parentNode->getName() . " contains .nomedia file");
147
				return;
148
			}
149
150
			$parentNode = $parentNode->getParent();
151
		}
152
153
		$this->logger->debug("Inserting/updating image " . $node->getName() . " for face recognition");
154
155
		$image = new Image();
156
		$image->setUser($owner);
157
		$image->setFile($node->getId());
158
		$image->setModel($model);
159
160
		$imageId = $this->imageMapper->imageExists($image);
161
		if ($imageId === null) {
162
			// todo: can we have larger transaction with bulk insert?
163
			$this->imageMapper->insert($image);
164
		} else {
165
			$this->imageMapper->resetImage($image);
166
			// note that invalidatePersons depends on existence of faces for a given image,
167
			// and we must invalidate before we delete faces!
168
			$this->personMapper->invalidatePersons($imageId);
169
			$this->faceMapper->removeFaces($imageId);
170
		}
171
	}
172
173
	/**
174
	 * A node has been deleted. Remove faces with file id
175
	 * with the current user in the DB
176
	 *
177
	 * @param Node $node
178
	 */
179
	public function postDelete(Node $node) {
180
		$model = intval($this->config->getAppValue('facerecognition', 'model', AddDefaultFaceModel::DEFAULT_FACE_MODEL_ID));
181
182
		// todo: should we also care about this too: instanceOfStorage(ISharedStorage::class);
183
		if ($node->getStorage()->instanceOfStorage(IHomeStorage::class) === false) {
184
			return;
185
		}
186
187
		if ($node instanceof Folder) {
188
			return;
189
		}
190
191
		$owner = $node->getOwner()->getUid();
192
193
		if ($node->getName() === '.nomedia') {
194
			// If user deleted file named .nomedia, that means all images in this and all child directories should be added.
195
			// But, instead of doing that here, better option seem to be to just reset flag that image scan is not done.
196
			// This will trigger another round of image crawling in AddMissingImagesTask for this user and those images will be added.
197
			$this->config->setUserValue($owner, 'facerecognition', AddMissingImagesTask::FULL_IMAGE_SCAN_DONE_KEY, 'false');
198
			return;
199
		}
200
201
		if (!Requirements::isImageTypeSupported($node->getMimeType())) {
202
			return;
203
		}
204
205
		$this->logger->debug("Deleting image " . $node->getName() . " from face recognition");
206
207
		$image = new Image();
208
		$image->setUser($owner);
209
		$image->setFile($node->getId());
210
		$image->setModel($model);
211
212
		$imageId = $this->imageMapper->imageExists($image);
213
		if ($imageId !== null) {
214
			// note that invalidatePersons depends on existence of faces for a given image,
215
			// and we must invalidate before we delete faces!
216
			$this->personMapper->invalidatePersons($imageId);
217
			$this->faceMapper->removeFaces($imageId);
218
219
			$image->setId($imageId);
220
			$this->imageMapper->delete($image);
221
		}
222
	}
223
224
	/**
225
	 * A user has been deleted. Cleanup everything from this user.
226
	 *
227
	 * @param \OC\User\User $user Deleted user
228
	 */
229 8
	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...
230 8
		$userId = $user->getUid();
231 8
		$this->faceManagementService->resetAllForUser($userId);
232 8
		$this->logger->info("Removed all face recognition data for deleted user " . $userId);
233 8
	}
234
}
235