Completed
Pull Request — master (#93)
by Janis
04:19
created

JobService::process()   C

Complexity

Conditions 7
Paths 26

Size

Total Lines 40
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 7.004

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 40
ccs 22
cts 23
cp 0.9565
rs 6.7272
c 1
b 0
f 0
cc 7
eloc 24
nc 26
nop 2
crap 7.004
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 22
    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 22
        $this->logger = $logger;
118 22
        $this->redisService = $queueService;
119 22
        $this->jobMapper = $mapper;
120 22
        $this->view = $view;
121 22
        $this->userId = $userId;
122 22
        $this->l10n = $l10n;
123 22
        $this->fileService = $fileService;
124 22
        $this->tempM = $tempManager;
125 22
        $this->appConfigService = $appConfigService;
126 22
        $this->phpUtil = $phpUtil;
127 22
        $this->fileUtil = $fileUtil;
128 22
    }
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
     * @return string
137
     */
138 9
    public function process($languages, $files) {
139
        try {
140 9
            $this->logger->debug('Will now process files: {files} with languages: {languages}', 
141
                    [
142 9
                            'files' => json_encode($files),
143 9
                            'languages' => json_encode($languages)
144
                    ]);
145
            // Check if files and language not empty
146 9
            $noLang = $this->noLanguage($languages);
147 9
            if (!empty($files) && ($this->checkForAcceptedLanguages($languages) || $noLang)) {
148
                // language part:
149 6
                if ($noLang) {
150 5
                    $languages = [];
151
                }
152
                // file part:
153 6
                $fileInfo = $this->fileService->buildFileInfo($files);
154 6
                foreach ($fileInfo as $fInfo) {
155
                    // Check Shared
156 6
                    $shared = $this->fileService->checkSharedWithInitiator($fInfo);
157 6
                    $target = $this->fileService->buildTarget($fInfo, $shared);
158 6
                    $source = $this->fileService->buildSource($fInfo, $shared);
159
                    // set the running type
160 6
                    $fType = $this->fileService->getCorrectType($fInfo);
161
                    // create a temp file for ocr processing purposes
162 6
                    $tempFile = $this->getTempFile($fType);
163
                    // Create job object
164 2
                    $job = new OcrJob(OcrConstants::STATUS_PENDING, $source, $target, $tempFile, $fType, $this->userId, 
165 2
                            false, $fInfo->getName(), null);
1 ignored issue
show
Bug introduced by
Consider using $fInfo->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
166
                    // Init client and send task / job
167
                    // Feed the worker
168 2
                    $this->redisService->sendJob($job, $languages);
169
                }
170 2
                return 'PROCESSING';
171
            } else {
172 3
                throw new NotFoundException($this->l10n->t('Empty parameters passed.'));
173
            }
174 7
        } catch (Exception $e) {
175 7
            $this->handleException($e);
176
        }
177
    }
178
179
    /**
180
     * Delete an ocr job for a given id and userId.
181
     * 
182
     * @param
183
     *            $jobId
184
     * @param string $userId            
185
     * @return OcrJob
186
     */
187 3
    public function deleteJob($jobId, $userId) {
188
        try {
189 3
            $job = $this->jobMapper->find($jobId);
190 2
            if ($job->getUserId() !== $userId) {
191 1
                throw new NotFoundException($this->l10n->t('Cannot delete because of wrong owner.'));
192
            } else {
193 1
                $job = $this->jobMapper->delete($job);
194
            }
195 1
            $job->setTarget(null);
196 1
            $job->setSource(null);
197 1
            $job->setStatus(null);
198 1
            $job->setTempFile(null);
199 1
            $job->setType(null);
200 1
            $job->setUserId(null);
201 1
            $job->setErrorDisplayed(null);
202 1
            $job->setErrorLog(null);
203 1
            return $job;
204 2
        } catch (Exception $e) {
205 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...
206 1
                $ex = new NotFoundException($this->l10n->t('Cannot delete because of wrong ID.'));
207 1
                $this->handleException($ex);
208
            } else {
209 1
                $this->handleException($e);
210
            }
211
        }
212
    }
213
214
    /**
215
     * Gets all job objects for a specific user.
216
     * 
217
     * @param string $userId            
218
     * @return OcrJob[]
219
     */
220 1
    public function getAllJobsForUser($userId) {
221
        try {
222 1
            $jobs = $this->jobMapper->findAll($userId);
223 1
            $jobsNew = array();
224 1
            foreach ($jobs as $job) {
225 1
                $job->setTarget(null);
226 1
                $job->setSource(null);
227 1
                $job->setTempFile(null);
228 1
                $job->setType(null);
229 1
                $job->setUserId(null);
230 1
                $job->setErrorDisplayed(null);
231 1
                array_push($jobsNew, $job);
232
            }
233 1
            return $jobsNew;
234
        } catch (Exception $e) {
235
            $this->handleException($e);
236
        }
237
    }
238
239
    /**
240
     * The function checks if there are finished jobs to process finally.
241
     * 
242
     * @throws NotFoundException
243
     */
244 2
    public function checkForFinishedJobs() {
245
        try {
246 2
            $finishedJobs = $this->redisService->readingFinishedJobs();
247 2
            foreach ($finishedJobs as $finishedJob) {
248 1
                $fJob = $this->transformJob($finishedJob);
249 1
                $this->logger->debug('The following job finished: {job}', 
250
                        [
251 1
                                'job' => $fJob
252
                        ]);
253 1
                $this->jobFinished($fJob->id, $fJob->error, $fJob->log);
254
            }
255 1
        } catch (Exception $e) {
256 1
            throw new NotFoundException($this->l10n->t('Reading the finished jobs from redis went wrong.'));
257
        }
258 1
    }
259
260
    /**
261
     * Finishes all Processed files by copying them to the right path and deleteing the temp files.
262
     * Returns the number of processed files.
263
     * 
264
     * @return array
265
     */
266 2
    public function handleProcessed() {
267
        try {
268 2
            $this->logger->debug('Check if files were processed by ocr and if so, put them to the right dirs.');
269 2
            $processed = $this->jobMapper->findAllProcessed($this->userId);
270 2
            foreach ($processed as $job) {
271 2
                if ($this->fileUtil->fileExists($job->getTempFile())) {
272
                    // Save the tmp file with newname
273 1
                    $this->view->file_put_contents($job->getTarget(), 
274 1
                            $this->fileUtil->getFileContents($job->getTempFile()));
275 1
                    $this->jobMapper->delete($job);
276 1
                    $this->fileUtil->execRemove($job->getTempFile());
277
                } else {
278 1
                    $job->setStatus(OcrConstants::STATUS_FAILED);
279 1
                    $job->setErrorLog('Temp file does not exist.');
280 1
                    $this->jobMapper->update($job);
281 2
                    throw new NotFoundException($this->l10n->t('Temp file does not exist.'));
282
                }
283
            }
284 1
            return $processed;
285 1
        } catch (Exception $e) {
286 1
            $this->handleException($e);
287
        }
288
    }
289
290
    /**
291
     * Handles all failed orders of ocr processing queue and returns the job objects.
292
     * 
293
     * @return array
294
     */
295 1
    public function handleFailed() {
296
        try {
297 1
            $failed = $this->jobMapper->findAllFailed($this->userId);
298 1
            foreach ($failed as $job) {
299
                // clean the tempfile
300 1
                $this->fileUtil->execRemove($job->getTempFile());
301
                // set error displayed
302 1
                $job->setErrorDisplayed(true);
303 1
                $this->jobMapper->update($job);
304
            }
305 1
            $this->logger->debug('Following jobs failed: {failed}', 
306
                    [
307 1
                            'failed' => json_encode($failed)
308
                    ]);
309 1
            return $failed;
310
        } catch (Exception $e) {
311
            $this->handleException($e);
312
        }
313
    }
314
315
    /**
316
     * The function the worker will call in order to set the jobs status.
317
     * The worker should call it automatically after each processing step.
318
     * 
319
     * @param integer $jobId            
320
     * @param boolean $error            
321
     * @param string $log            
322
     */
323 1
    private function jobFinished($jobId, $error, $log) {
324
        try {
325 1
            $job = $this->jobMapper->find($jobId);
326 1
            if (!$error) {
327 1
                $job->setStatus(OcrConstants::STATUS_PROCESSED);
328 1
                $this->jobMapper->update($job);
329
            } else {
330 1
                $job->setStatus(OcrConstants::STATUS_FAILED);
331 1
                $job->setErrorLog($log);
332 1
                $this->jobMapper->update($job);
333 1
                $this->logger->error($log);
334
            }
335
        } catch (Exception $e) {
336
            $this->handleException($e);
337
        }
338 1
    }
339
340
    /**
341
     * Gives a temp file name back depending on the type of the OCR.
342
     * Later in the worker this file is used as an output.
343
     * 
344
     * @param integer $type            
345
     * @return string
346
     */
347 6
    private function getTempFile($type) {
348 6
        if ($type === OcrConstants::TESSERACT) {
349 5
            $fileName = $this->phpUtil->tempnamWrapper($this->tempM->getTempBaseDir(), OcrConstants::TEMPFILE_PREFIX);
350 5
            $this->phpUtil->unlinkWrapper($fileName);
351 4
            $fileNameWithPostfix = $fileName . '.txt';
352 4
            $this->phpUtil->touchWrapper($fileNameWithPostfix);
353 3
            $this->phpUtil->chmodWrapper($fileNameWithPostfix, 0600);
354 2
            return $fileNameWithPostfix;
355
        } else {
356 3
            return $this->phpUtil->tempnamWrapper($this->tempM->getTempBaseDir(), OcrConstants::TEMPFILE_PREFIX);
357
        }
358
    }
359
360
    /**
361
     * Takes care of transforming an incoming finished job into a php readable object.
362
     * 
363
     * @param string $job            
364
     * @throws NotFoundException
365
     * @return mixed
366
     */
367 1
    private function transformJob($job) {
368 1
        $decoded = json_decode($job);
369 1
        if ($decoded !== null && isset($decoded->id)) {
370 1
            return $decoded;
371
        } else {
372
            $this->logger->debug('The finished job retrieved by Redis was corrupt.');
373
            throw new NotFoundException('The finished job retrieved by Redis was corrupt.');
374
        }
375
    }
376
377
    /**
378
     * Checks if the given languages are supported or not.
379
     * 
380
     * @param string[] $languages            
381
     * @return boolean
382
     */
383 8
    private function checkForAcceptedLanguages($languages) {
384 8
        $installedLanguages = explode(';', $this->appConfigService->getAppValue('languages'));
385 8
        if (count(array_diff($languages, $installedLanguages)) === 0) {
386 1
            return true;
387
        } else {
388 7
            return false;
389
        }
390
    }
391
392
    /**
393
     * Checks if the process should be initiated without any language specified.
394
     * 
395
     * @param string[] $languages            
396
     * @return boolean
397
     */
398 9
    private function noLanguage($languages) {
399 9
        if (in_array('any', $languages)) {
400 6
            return true;
401
        } else {
402 3
            return false;
403
        }
404
    }
405
406
    /**
407
     * Handle the possible thrown Exceptions from all methods of this class.
408
     * 
409
     * @param Exception $e            
410
     * @throws Exception
411
     * @throws NotFoundException
412
     */
413 10
    private function handleException($e) {
414 10
        $this->logger->logException($e, 
415
                [
416
                        'message' => 'Exception during job service function processing'
417 10
                ]);
418 10
        throw $e;
419
    }
420
}