Passed
Push — shared-storage-experiments ( cbb9c9...a42f2e )
by Matias
06:53
created

Watcher   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 224
Duplicated Lines 0 %

Test Coverage

Coverage 20.21%

Importance

Changes 21
Bugs 5 Features 0
Metric Value
eloc 97
c 21
b 5
f 0
dl 0
loc 224
ccs 19
cts 94
cp 0.2021
rs 10
wmc 24

4 Methods

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