Passed
Push — shared-storage-experiments ( ffc80d...075dcd )
by Matias
16:44
created

AddMissingImagesTask::getPicturesFromFolder()   B

Complexity

Conditions 9
Paths 6

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 9
eloc 13
c 3
b 0
f 0
nc 6
nop 2
dl 0
loc 20
ccs 0
cts 14
cp 0
crap 90
rs 8.0555
1
<?php
2
/**
3
 * @copyright Copyright (c) 2017, 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\IConfig;
27
use OCP\IUser;
28
29
use OCP\Files\File;
30
use OCP\Files\Folder;
31
32
use OCA\FaceRecognition\BackgroundJob\FaceRecognitionBackgroundTask;
33
use OCA\FaceRecognition\BackgroundJob\FaceRecognitionContext;
34
use OCA\FaceRecognition\Db\Image;
35
use OCA\FaceRecognition\Db\ImageMapper;
36
use OCA\FaceRecognition\Migration\AddDefaultFaceModel;
37
use OCA\FaceRecognition\Service\FileService;
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 IConfig Config */
48
	private $config;
49
50
	/** @var ImageMapper Image mapper */
51
	private $imageMapper;
52
53
	/** @var FileService */
54
	private $fileService;
55
56
	/**
57
	 * @param IConfig $config Config
58
	 * @param ImageMapper $imageMapper Image mapper
59
	 * @param FileService $fileService File Service
60
	 */
61
	public function __construct(IConfig     $config,
62
	                            ImageMapper $imageMapper,
63
	                            FileService $fileService) {
64
		parent::__construct();
65
		$this->config      = $config;
66
		$this->imageMapper = $imageMapper;
67
		$this->fileService = $fileService;
68
	}
69
70
	/**
71
	 * @inheritdoc
72
	 */
73
	public function description() {
74
		return "Crawl for missing images for each user and insert them in DB";
75
	}
76
77
	/**
78
	 * @inheritdoc
79
	 */
80
	public function execute(FaceRecognitionContext $context) {
81
		$this->setContext($context);
82
83
		$model = intval($this->config->getAppValue('facerecognition', 'model', AddDefaultFaceModel::DEFAULT_FACE_MODEL_ID));
84
85
		// Check if we are called for one user only, or for all user in instance.
86
		$insertedImages = 0;
87
		$eligable_users = array();
88
		if (is_null($this->context->user)) {
89
			$this->context->userManager->callForSeenUsers(function (IUser $user) use (&$eligable_users) {
90
				$eligable_users[] = $user->getUID();
91
			});
92
		} else {
93
			$eligable_users[] = $this->context->user->getUID();
94
		}
95
96
		foreach($eligable_users as $user) {
97
			$userEnabled = $this->config->getUserValue($user, 'facerecognition', 'enabled', 'false');
98
			if ($userEnabled === 'false') {
99
				// Completely skip this task for this user, seems that disable analysis
100
				$this->logInfo('Skipping image scan for user ' . $user . ' that has disabled the analysis');
101
				continue;
102
			}
103
104
			$fullImageScanDone = $this->config->getUserValue($user, 'facerecognition', AddMissingImagesTask::FULL_IMAGE_SCAN_DONE_KEY, 'false');
105
			if ($fullImageScanDone === 'true') {
106
				// Completely skip this task for this user, seems that we already did full scan for him
107
				$this->logDebug('Skipping full image scan for user ' . $user);
108
				continue;
109
			}
110
111
			$insertedImages += $this->addMissingImagesForUser($user, $model);
112
			$this->config->setUserValue($user, 'facerecognition', AddMissingImagesTask::FULL_IMAGE_SCAN_DONE_KEY, 'true');
113
			yield;
114
		}
115
116
		$this->context->propertyBag['AddMissingImagesTask_insertedImages'] = $insertedImages;
117
		return true;
118
	}
119
120
	/**
121
	 * Crawl filesystem for a given user
122
	 *
123
	 * @param string $userId ID of the user for which to crawl images for
124
	 * @param int $model Used model
125
	 * @return int Number of missing images found
126
	 */
127
	private function addMissingImagesForUser(string $userId, int $model): int {
128
		$this->logInfo(sprintf('Finding missing images for user %s', $userId));
129
		$this->fileService->setupFS($userId);
130
131
		$userFolder = $this->context->rootFolder->getUserFolder($userId);
132
		return $this->parseUserFolder($userId, $model, $userFolder);
133
	}
134
135
	/**
136
	 * Recursively crawls given folder for a given user
137
	 *
138
	 * @param int $model Used model
139
	 * @param Folder $folder Folder to recursively search images in
140
	 * @return int Number of missing images found
141
	 */
142
	private function parseUserFolder(string $userId, int $model, Folder $folder): int {
143
		$insertedImages = 0;
144
		$nodes = $this->fileService->getPicturesFromFolder($folder);
145
		foreach ($nodes as $file) {
146
			$this->logDebug('Found ' . $file->getPath());
147
148
			$image = new Image();
149
			$image->setUser($userId);
150
			$image->setFile($file->getId());
151
			$image->setModel($model);
152
			// todo: this check/insert logic for each image is so inefficient it hurts my mind
153
			if ($this->imageMapper->imageExists($image) === null) {
154
				// todo: can we have larger transaction with bulk insert?
155
				$this->imageMapper->insert($image);
156
				$insertedImages++;
157
			}
158
		}
159
160
		return $insertedImages;
161
	}
162
163
}
164