Completed
Pull Request — master (#116)
by Janis
09:43
created

JobService::process()   D

Complexity

Conditions 10
Paths 28

Size

Total Lines 44
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 10.0056

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 44
ccs 25
cts 26
cp 0.9615
rs 4.8196
c 1
b 0
f 0
cc 10
eloc 27
nc 28
nop 3
crap 10.0056

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Nextcloud - OCR
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later.
7
 * See the COPYING file.
8
 * 
9
 * @author Janis Koehr <[email protected]>
10
 * @copyright Janis Koehr 2017
11
 */
12
namespace OCA\Ocr\Service;
13
14
use OCA\Ocr\Db\OcrJobMapper;
15
use OC\Files\View;
16
use OCP\ILogger;
17
use OCP\IL10N;
18
use OCP\ITempManager;
19
use OCA\Ocr\Db\OcrJob;
20
use OCA\Ocr\Constants\OcrConstants;
21
use OCA\Ocr\Util\PHPUtil;
22
use Exception;
23
use OCP\AppFramework\Db\DoesNotExistException;
24
use OCA\Ocr\Util\FileUtil;
25
26
27
/**
28
 * Class JobService
29
 * 
30
 * @package OCA\Ocr\Service
31
 */
32
class JobService {
33
34
    /**
35
     *
36
     * @var ILogger
37
     */
38
    private $logger;
39
40
    /**
41
     *
42
     * @var RedisService
43
     */
44
    private $redisService;
45
46
    /**
47
     *
48
     * @var OcrJobMapper
49
     */
50
    private $jobMapper;
51
52
    /**
53
     *
54
     * @var View
55
     */
56
    private $view;
57
58
    /**
59
     *
60
     * @var String
61
     */
62
    private $userId;
63
64
    /**
65
     *
66
     * @var IL10N
67
     */
68
    private $l10n;
69
70
    /**
71
     *
72
     * @var FileService
73
     */
74
    private $fileService;
75
76
    /**
77
     *
78
     * @var ITempManager
79
     */
80
    private $tempM;
81
82
    /**
83
     *
84
     * @var AppConfigService
85
     */
86
    private $appConfigService;
87
88
    /**
89
     *
90
     * @var PHPUtil
91
     */
92
    private $phpUtil;
93
94
    /**
95
     *
96
     * @var FileUtil
97
     */
98
    private $fileUtil;
99
100
    /**
101
     * JobService constructor.
102
     * 
103
     * @param IL10N $l10n            
104
     * @param ILogger $logger            
105
     * @param string $userId            
106
     * @param View $view            
107
     * @param RedisService $queueService            
108
     * @param OcrJobMapper $mapper            
109
     * @param FileService $fileService            
110
     * @param AppConfigService $appConfigService            
111
     * @param PHPUtil $phpUtil            
112
     * @param FileUtil $fileUtil            
113
     */
114 24
    public function __construct(IL10N $l10n, ILogger $logger, $userId, View $view, ITempManager $tempManager, 
115
            RedisService $queueService, OcrJobMapper $mapper, FileService $fileService, 
116
            AppConfigService $appConfigService, PHPUtil $phpUtil, FileUtil $fileUtil) {
117 24
        $this->logger = $logger;
118 24
        $this->redisService = $queueService;
119 24
        $this->jobMapper = $mapper;
120 24
        $this->view = $view;
121 24
        $this->userId = $userId;
122 24
        $this->l10n = $l10n;
123 24
        $this->fileService = $fileService;
124 24
        $this->tempM = $tempManager;
125 24
        $this->appConfigService = $appConfigService;
126 24
        $this->phpUtil = $phpUtil;
127 24
        $this->fileUtil = $fileUtil;
128 24
    }
129
130
    /**
131
     * Processes and prepares the files for OCR.
132
     * Sends the stuff to the client in order to OCR async.
133
     * 
134
     * @param string[] $languages            
135
     * @param array $files            
136
     * @param boolean $replace            
137
     * @return string
138
     */
139 11
    public function process($languages, $files, $replace) {
140
        try {
141 11
            $this->logger->debug('Will now process files: {files} with languages: {languages} and replace: {replace}', 
142
                    [
143 11
                            'files' => json_encode($files),
144 11
                            'languages' => json_encode($languages),
145 11
                            'replace' => json_encode($replace)
146
                    ]);
147
            // Check if files and language not empty
148 11
            $noLang = $this->noLanguage($languages);
149 11
            if (!empty($files) && ($this->checkForAcceptedLanguages($languages) || $noLang) && is_bool($replace)) {
150
                // language part:
151 7
                if ($noLang) {
152 5
                    $languages = [];
153
                }
154
                // file part:
155 7
                $fileInfo = $this->fileService->buildFileInfo($files);
156 7
                foreach ($fileInfo as $fInfo) {
157
                    // Check Shared
158 7
                    $shared = $this->fileService->checkSharedWithInitiator($fInfo);
159 7
                    if($shared && $replace) {
160 1
                        throw new NotFoundException($this->l10n->t('Cannot replace shared files.'));
161
                    }
162 6
                    $target = $this->fileService->buildTarget($fInfo, $shared, $replace);
163 6
                    $source = $this->fileService->buildSource($fInfo, $shared);
164
                    // set the running type
165 6
                    $fType = $this->fileService->getCorrectType($fInfo);
166
                    // create a temp file for ocr processing purposes
167 6
                    $tempFile = $this->getTempFile($fType);
168
                    // Create job object
169 2
                    $job = new OcrJob(OcrConstants::STATUS_PENDING, $source, $target, $tempFile, $fType, $this->userId, 
170 2
                            false, $fInfo->getName(), null, $replace);
171
                    // Init client and send task / job
172
                    // Feed the worker
173 2
                    $this->redisService->sendJob($job, $languages);
174
                }
175 2
                return 'PROCESSING';
176
            } else {
177 4
                throw new NotFoundException($this->l10n->t('Empty parameters passed.'));
178
            }
179 9
        } catch (Exception $e) {
180 9
            $this->handleException($e);
181
        }
182
    }
183
184
    /**
185
     * Delete an ocr job for a given id and userId.
186
     * 
187
     * @param
188
     *            $jobId
189
     * @param string $userId            
190
     * @return OcrJob
191
     */
192 3
    public function deleteJob($jobId, $userId) {
193
        try {
194 3
            $job = $this->jobMapper->find($jobId);
195 2
            if ($job->getUserId() !== $userId) {
196 1
                throw new NotFoundException($this->l10n->t('Cannot delete because of wrong owner.'));
197
            } else {
198 1
                $job = $this->jobMapper->delete($job);
199
            }
200 1
            $job->setTarget(null);
201 1
            $job->setSource(null);
202 1
            $job->setStatus(null);
203 1
            $job->setTempFile(null);
204 1
            $job->setType(null);
205 1
            $job->setUserId(null);
206 1
            $job->setErrorDisplayed(null);
207 1
            $job->setErrorLog(null);
208 1
            $job->setReplace(null);
209 1
            return $job;
210 2
        } catch (Exception $e) {
211 2
            if ($e instanceof DoesNotExistException) {
0 ignored issues
show
Bug introduced by
The class OCP\AppFramework\Db\DoesNotExistException does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
212 1
                $ex = new NotFoundException($this->l10n->t('Cannot delete because of wrong ID.'));
213 1
                $this->handleException($ex);
214
            } else {
215 1
                $this->handleException($e);
216
            }
217
        }
218
    }
219
220
    /**
221
     * Gets all job objects for a specific user.
222
     * 
223
     * @param string $userId            
224
     * @return OcrJob[]
225
     */
226 1
    public function getAllJobsForUser($userId) {
227
        try {
228 1
            $jobs = $this->jobMapper->findAll($userId);
229 1
            $jobsNew = array();
230 1
            foreach ($jobs as $job) {
231 1
                $job->setTarget(null);
232 1
                $job->setSource(null);
233 1
                $job->setTempFile(null);
234 1
                $job->setType(null);
235 1
                $job->setUserId(null);
236 1
                $job->setErrorDisplayed(null);
237 1
                array_push($jobsNew, $job);
238
            }
239 1
            return $jobsNew;
240
        } catch (Exception $e) {
241
            $this->handleException($e);
242
        }
243
    }
244
245
    /**
246
     * The function checks if there are finished jobs to process finally.
247
     * 
248
     * @throws NotFoundException
249
     */
250 2
    public function checkForFinishedJobs() {
251
        try {
252 2
            $finishedJobs = $this->redisService->readingFinishedJobs();
253 2
            foreach ($finishedJobs as $finishedJob) {
254 1
                $fJob = $this->transformJob($finishedJob);
255 1
                $this->logger->debug('The following job finished: {job}', 
256
                        [
257 1
                                'job' => $fJob
258
                        ]);
259 1
                $this->jobFinished($fJob->id, $fJob->error, $fJob->log);
260
            }
261 1
        } catch (Exception $e) {
262 1
            throw new NotFoundException($this->l10n->t('Reading the finished jobs from Redis went wrong.'));
263
        }
264 1
    }
265
266
    /**
267
     * Finishes all Processed files by copying them to the right path and deleteing the temp files.
268
     * Returns the number of processed files.
269
     * 
270
     * @return array
271
     */
272 2
    public function handleProcessed() {
273
        try {
274 2
            $this->logger->debug('Check if files were processed by ocr and if so, put them to the right dirs.');
275 2
            $processed = $this->jobMapper->findAllProcessed($this->userId);
276 2
            foreach ($processed as $job) {
277 2
                if ($this->fileUtil->fileExists($job->getTempFile())) {
278
                    // Save the tmp file with newname
279 1
                    $this->pullResult($job);
280 1
                    $this->jobMapper->delete($job);
281 1
                    $this->fileUtil->execRemove($job->getTempFile());
282
                } else {
283 1
                    $job->setStatus(OcrConstants::STATUS_FAILED);
284 1
                    $job->setErrorLog('Temp file does not exist.');
285 1
                    $this->jobMapper->update($job);
286 2
                    throw new NotFoundException($this->l10n->t('Temp file does not exist.'));
287
                }
288
            }
289 1
            return $processed;
290 1
        } catch (Exception $e) {
291 1
            $this->handleException($e);
292
        }
293
    }
294
295
    /**
296
     * Handles all failed orders of ocr processing queue and returns the job objects.
297
     * 
298
     * @return array
299
     */
300 1
    public function handleFailed() {
301
        try {
302 1
            $failed = $this->jobMapper->findAllFailed($this->userId);
303 1
            foreach ($failed as $job) {
304
                // clean the tempfile
305 1
                $this->fileUtil->execRemove($job->getTempFile());
306
                // set error displayed
307 1
                $job->setErrorDisplayed(true);
308 1
                $this->jobMapper->update($job);
309
            }
310 1
            $this->logger->debug('Following jobs failed: {failed}', 
311
                    [
312 1
                            'failed' => json_encode($failed)
313
                    ]);
314 1
            return $failed;
315
        } catch (Exception $e) {
316
            $this->handleException($e);
317
        }
318
    }
319
320
    /**
321
     * Gets the OCR result and puts it to Nextcloud.
322
     * 
323
     * @param OcrJob $job            
324
     */
325 1
    private function pullResult($job) {
326 1
        if ($job->getReplace()) {
327 1
            $this->view->unlink(str_replace($this->userId . '/files', '', $job->getSource()));
328
        }
329 1
        $result = $this->view->file_put_contents($job->getTarget(), $this->fileUtil->getFileContents($job->getTempFile()));
330 1
        if (!$result) {
331
            throw new NotFoundException($this->l10n->t('OCR could not put processed file to the right target folder. If you selected the replace option, you can restore the file by using the trash bin.'));
332
        }
333 1
    }
334
335
    /**
336
     * The function the worker will call in order to set the jobs status.
337
     * The worker should call it automatically after each processing step.
338
     * 
339
     * @param integer $jobId            
340
     * @param boolean $error            
341
     * @param string $log            
342
     */
343 1
    private function jobFinished($jobId, $error, $log) {
344
        try {
345 1
            $job = $this->jobMapper->find($jobId);
346 1
            if (!$error) {
347 1
                $job->setStatus(OcrConstants::STATUS_PROCESSED);
348 1
                $this->jobMapper->update($job);
349
            } else {
350 1
                $job->setStatus(OcrConstants::STATUS_FAILED);
351 1
                $job->setErrorLog($log);
352 1
                $this->jobMapper->update($job);
353 1
                $this->logger->error($log);
354
            }
355
        } catch (Exception $e) {
356
            $this->handleException($e);
357
        }
358 1
    }
359
360
    /**
361
     * Gives a temp file name back depending on the type of the OCR.
362
     * Later in the worker this file is used as an output.
363
     * 
364
     * @param integer $type            
365
     * @return string
366
     */
367 6
    private function getTempFile($type) {
368 6
        if ($type === OcrConstants::TESSERACT) {
369 5
            $fileName = $this->phpUtil->tempnamWrapper($this->tempM->getTempBaseDir(), OcrConstants::TEMPFILE_PREFIX);
370 5
            $this->phpUtil->unlinkWrapper($fileName);
371 4
            $fileNameWithPostfix = $fileName . '.txt';
372 4
            $this->phpUtil->touchWrapper($fileNameWithPostfix);
373 3
            $this->phpUtil->chmodWrapper($fileNameWithPostfix, 0600);
374 2
            return $fileNameWithPostfix;
375
        } else {
376 3
            return $this->phpUtil->tempnamWrapper($this->tempM->getTempBaseDir(), OcrConstants::TEMPFILE_PREFIX);
377
        }
378
    }
379
380
    /**
381
     * Takes care of transforming an incoming finished job into a php readable object.
382
     * 
383
     * @param string $job            
384
     * @throws NotFoundException
385
     * @return mixed
386
     */
387 1
    private function transformJob($job) {
388 1
        $decoded = json_decode($job);
389 1
        if ($decoded !== null && isset($decoded->id)) {
390 1
            return $decoded;
391
        } else {
392
            $this->logger->debug('The finished job retrieved by Redis was corrupt.');
393
            throw new NotFoundException('The finished job retrieved by Redis was corrupt.');
394
        }
395
    }
396
397
    /**
398
     * Checks if the given languages are supported or not.
399
     * 
400
     * @param string[] $languages            
401
     * @return boolean
402
     */
403 10
    private function checkForAcceptedLanguages($languages) {
404 10
        $installedLanguages = explode(';', $this->appConfigService->getAppValue('languages'));
405 10
        if (count(array_diff($languages, $installedLanguages)) === 0) {
406 3
            return true;
407
        } else {
408 7
            return false;
409
        }
410
    }
411
412
    /**
413
     * Checks if the process should be initiated without any language specified.
414
     * 
415
     * @param string[] $languages            
416
     * @return boolean
417
     */
418 11
    private function noLanguage($languages) {
419 11
        if (in_array('any', $languages)) {
420 6
            return true;
421
        } else {
422 5
            return false;
423
        }
424
    }
425
426
    /**
427
     * Handle the possible thrown Exceptions from all methods of this class.
428
     * 
429
     * @param Exception $e            
430
     * @throws Exception
431
     * @throws NotFoundException
432
     */
433 12
    private function handleException($e) {
434 12
        $this->logger->logException($e, 
435
                [
436 12
                        'message' => 'Exception during job service function processing'
437
                ]);
438 12
        throw $e;
439
    }
440
}