Passed
Pull Request — master (#269)
by Matias
06:58 queued 05:22
created

AddMissingImagesTask::execute()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 5.025

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 20
c 1
b 0
f 0
nc 8
nop 1
dl 0
loc 34
ccs 18
cts 20
cp 0.9
crap 5.025
rs 9.2888
1
<?php
2
/**
3
 * @copyright Copyright (c) 2017-2020 Matias De lellis <[email protected]>
4
 * @copyright Copyright (c) 2018, Branko Kokanovic <[email protected]>
5
 *
6
 * @author Branko Kokanovic <[email protected]>
7
 *
8
 * @license GNU AGPL version 3 or any later version
9
 *
10
 * This program is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License as
12
 * published by the Free Software Foundation, either version 3 of the
13
 * License, or (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU Affero General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Affero General Public License
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
 *
23
 */
24
namespace OCA\FaceRecognition\BackgroundJob\Tasks;
25
26
use OCP\IUser;
27
28
use OCP\Files\File;
29
use OCP\Files\Folder;
30
31
use OCA\FaceRecognition\BackgroundJob\FaceRecognitionBackgroundTask;
32
use OCA\FaceRecognition\BackgroundJob\FaceRecognitionContext;
33
use OCA\FaceRecognition\Db\Image;
34
use OCA\FaceRecognition\Db\ImageMapper;
35
36
use OCA\FaceRecognition\Service\FileService;
37
use OCA\FaceRecognition\Service\SettingsService;
38
39
/**
40
 * Task that, for each user, crawls for all images in filesystem and insert them in database.
41
 * This is job that normally does file watcher, but this should be done at least once,
42
 * after app is installed (or re-enabled).
43
 */
44
class AddMissingImagesTask extends FaceRecognitionBackgroundTask {
45
	const FULL_IMAGE_SCAN_DONE_KEY = "full_image_scan_done";
46
47
	/** @var ImageMapper Image mapper */
48
	private $imageMapper;
49
50
	/** @var FileService */
51
	private $fileService;
52
53
	/** @var SettingsService Settings service */
54
	private $settingsService;
55
56
	/**
57
	 * @param ImageMapper $imageMapper Image mapper
58
	 * @param FileService $fileService File Service
59
	 * @param SettingsService $settingsService Settings Service
60
	 */
61 10
	public function __construct(ImageMapper     $imageMapper,
62
	                            FileService     $fileService,
63
	                            SettingsService $settingsService)
64
	{
65 10
		parent::__construct();
66
67 10
		$this->imageMapper     = $imageMapper;
68 10
		$this->fileService     = $fileService;
69 10
		$this->settingsService = $settingsService;
70 10
	}
71
72
	/**
73
	 * @inheritdoc
74
	 */
75 4
	public function description() {
76 4
		return "Crawl for missing images for each user and insert them in DB";
77
	}
78
79
	/**
80
	 * @inheritdoc
81
	 */
82 10
	public function execute(FaceRecognitionContext $context) {
83 10
		$this->setContext($context);
84
85
		// Check if we are called for one user only, or for all user in instance.
86 10
		$insertedImages = 0;
87 10
		$eligable_users = array();
88 10
		if (is_null($this->context->user)) {
89
			$this->context->userManager->callForSeenUsers(function (IUser $user) use (&$eligable_users) {
90 2
				$eligable_users[] = $user->getUID();
91 2
			});
92
		} else {
93 8
			$eligable_users[] = $this->context->user->getUID();
94
		}
95
96 10
		foreach($eligable_users as $user) {
97 10
			if (!$this->settingsService->getUserEnabled($user)) {
98
				// Completely skip this task for this user, seems that disable analysis
99 2
				$this->logInfo('Skipping image scan for user ' . $user . ' that has disabled the analysis');
100 2
				continue;
101
			}
102
103 10
			if ($this->settingsService->getUserFullScanDone($user)) {
104
				// Completely skip this task for this user, seems that we already did full scan for him
105
				$this->logDebug('Skipping full image scan for user ' . $user);
106
				continue;
107
			}
108
109 10
			$insertedImages += $this->addMissingImagesForUser($user, $this->settingsService->getCurrentFaceModel());
110 10
			$this->settingsService->setUserFullScanDone(true, $user);
111 10
			yield;
112
		}
113
114 10
		$this->context->propertyBag['AddMissingImagesTask_insertedImages'] = $insertedImages;
115 10
		return true;
116
	}
117
118
	/**
119
	 * Crawl filesystem for a given user
120
	 *
121
	 * @param string $userId ID of the user for which to crawl images for
122
	 * @param int $model Used model
123
	 * @return int Number of missing images found
124
	 */
125 10
	private function addMissingImagesForUser(string $userId, int $model): int {
126 10
		$this->logInfo(sprintf('Finding missing images for user %s', $userId));
127 10
		$this->fileService->setupFS($userId);
128
129 10
		$userFolder = $this->fileService->getUserFolder($userId);
130 10
		return $this->parseUserFolder($userId, $model, $userFolder);
131
	}
132
133
	/**
134
	 * Recursively crawls given folder for a given user
135
	 *
136
	 * @param int $model Used model
137
	 * @param Folder $folder Folder to recursively search images in
138
	 * @return int Number of missing images found
139
	 */
140 10
	private function parseUserFolder(string $userId, int $model, Folder $folder): int {
141 10
		$insertedImages = 0;
142 10
		$nodes = $this->fileService->getPicturesFromFolder($folder);
143 10
		foreach ($nodes as $file) {
144 7
			$this->logDebug('Found ' . $file->getPath());
145
146 7
			$image = new Image();
147 7
			$image->setUser($userId);
148 7
			$image->setFile($file->getId());
149 7
			$image->setModel($model);
150
			// todo: this check/insert logic for each image is so inefficient it hurts my mind
151 7
			if ($this->imageMapper->imageExists($image) === null) {
152
				// todo: can we have larger transaction with bulk insert?
153 7
				$this->imageMapper->insert($image);
154 7
				$insertedImages++;
155
			}
156
		}
157
158 10
		return $insertedImages;
159
	}
160
161
}
162