Completed
Push — improveTravis ( 69f7a5 )
by Matias
05:57
created

AddMissingImagesTask::parseUserFolder()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 12
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 19
ccs 13
cts 13
cp 1
crap 3
rs 9.8666
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
use OCP\Files\IHomeStorage;
32
33
use OCA\FaceRecognition\BackgroundJob\FaceRecognitionBackgroundTask;
34
use OCA\FaceRecognition\BackgroundJob\FaceRecognitionContext;
35
use OCA\FaceRecognition\Db\Image;
36
use OCA\FaceRecognition\Db\ImageMapper;
37
use OCA\FaceRecognition\Helper\Requirements;
38
use OCA\FaceRecognition\Migration\AddDefaultFaceModel;
39
40
/**
41
 * Task that, for each user, crawls for all images in filesystem and insert them in database.
42
 * This is job that normally does file watcher, but this should be done at least once,
43
 * after app is installed (or re-enabled).
44
 */
45
class AddMissingImagesTask extends FaceRecognitionBackgroundTask {
46
	const FULL_IMAGE_SCAN_DONE_KEY = "full_image_scan_done";
47
48
	/** @var IConfig Config */
49
	private $config;
50
51
	/** @var ImageMapper Image mapper */
52
	private $imageMapper;
53
54
	/**
55
	 * @param IConfig $config Config
56
	 * @param ImageMapper $imageMapper Image mapper
57
	 */
58 10
	public function __construct(IConfig $config, ImageMapper $imageMapper) {
59 10
		parent::__construct();
60 10
		$this->config = $config;
61 10
		$this->imageMapper = $imageMapper;
62 10
	}
63
64
	/**
65
	 * @inheritdoc
66
	 */
67 4
	public function description() {
68 4
		return "Crawl for missing images for each user and insert them in DB";
69
	}
70
71
	/**
72
	 * @inheritdoc
73
	 */
74 10
	public function execute(FaceRecognitionContext $context) {
75 10
		$this->setContext($context);
76
77 10
		$model = intval($this->config->getAppValue('facerecognition', 'model', AddDefaultFaceModel::DEFAULT_FACE_MODEL_ID));
78
79
		// Check if we are called for one user only, or for all user in instance.
80 10
		$insertedImages = 0;
81 10
		$eligable_users = array();
82 10
		if (is_null($this->context->user)) {
83 2
			$this->context->userManager->callForSeenUsers(function (IUser $user) use (&$eligable_users) {
84 2
				$eligable_users[] = $user->getUID();
85 2
			});
86
		} else {
87 8
			$eligable_users[] = $this->context->user->getUID();
88
		}
89
90 10
		foreach($eligable_users as $user) {
91 10
			$userEnabled = $this->config->getUserValue($user, 'facerecognition', 'enabled', 'false');
92 10
			if ($userEnabled === 'false') {
93
				// Completely skip this task for this user, seems that disable analysis
94 2
				$this->logInfo('Skipping image scan for user ' . $user . ' that has disabled the analysis');
95 2
				continue;
96
			}
97
98 10
			$fullImageScanDone = $this->config->getUserValue($user, 'facerecognition', AddMissingImagesTask::FULL_IMAGE_SCAN_DONE_KEY, 'false');
99 10
			if ($fullImageScanDone === 'true') {
100
				// Completely skip this task for this user, seems that we already did full scan for him
101
				$this->logDebug('Skipping full image scan for user ' . $user);
102
				continue;
103
			}
104
105 10
			$insertedImages += $this->addMissingImagesForUser($user, $model);
106 10
			$this->config->setUserValue($user, 'facerecognition', AddMissingImagesTask::FULL_IMAGE_SCAN_DONE_KEY, 'true');
107 10
			yield;
108
		}
109
110 10
		$this->context->propertyBag['AddMissingImagesTask_insertedImages'] = $insertedImages;
111 10
		return true;
112
	}
113
114
	/**
115
	 * Crawl filesystem for a given user
116
	 *
117
	 * @param string $userId ID of the user for which to crawl images for
118
	 * @param int $model Used model
119
	 * @return int Number of missing images found
120
	 */
121 10
	private function addMissingImagesForUser(string $userId, int $model): int {
122 10
		$this->logInfo(sprintf('Finding missing images for user %s', $userId));
123 10
		\OC_Util::tearDownFS();
0 ignored issues
show
Bug introduced by
The type OC_Util 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...
124 10
		\OC_Util::setupFS($userId);
125
126 10
		$userFolder = $this->context->rootFolder->getUserFolder($userId);
127 10
		return $this->parseUserFolder($model, $userFolder);
128
	}
129
130
	/**
131
	 * Recursively crawls given folder for a given user
132
	 *
133
	 * @param int $model Used model
134
	 * @param Folder $folder Folder to recursively search images in
135
	 * @return int Number of missing images found
136
	 */
137 10
	private function parseUserFolder(int $model, Folder $folder): int {
138 10
		$insertedImages = 0;
139 10
		$nodes = $this->getPicturesFromFolder($folder);
140 10
		foreach ($nodes as $file) {
141 7
			$this->logDebug('Found ' . $file->getPath());
142
143 7
			$image = new Image();
144 7
			$image->setUser($file->getOwner()->getUid());
145 7
			$image->setFile($file->getId());
146 7
			$image->setModel($model);
147
			// todo: this check/insert logic for each image is so inefficient it hurts my mind
148 7
			if ($this->imageMapper->imageExists($image) === null) {
149
				// todo: can we have larger transaction with bulk insert?
150 7
				$this->imageMapper->insert($image);
151 7
				$insertedImages++;
152
			}
153
		}
154
155 10
		return $insertedImages;
156
	}
157
158
	/**
159
	 * Return all images from a given folder.
160
	 *
161
	 * TODO: It is inefficient since it copies the array recursively.
162
	 *
163
	 * @param Folder $folder Folder to get images from
164
	 * @return array List of all images and folders to continue recursive crawling
165
	 */
166 10
	private function getPicturesFromFolder(Folder $folder, $results = array()) {
167
		// todo: should we also care about this too: instanceOfStorage(ISharedStorage::class);
168 10
		if ($folder->getStorage()->instanceOfStorage(IHomeStorage::class) === false) {
169
			return $results;
170
		}
171
172 10
		$nodes = $folder->getDirectoryListing();
173
174 10
		foreach ($nodes as $node) {
175 8
			if ($node instanceof Folder and !$node->nodeExists('.nomedia')) {
176 3
				$results = $this->getPicturesFromFolder($node, $results);
177 8
			} else if ($node instanceof File) {
178 8
				if (Requirements::isImageTypeSupported($node->getMimeType())) {
179 8
					$results[] = $node;
180
				}
181
			}
182
		}
183
184 10
		return $results;
185
	}
186
}
187