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

RedisService   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 170
Duplicated Lines 4.71 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 17.24%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
lcom 1
cbo 2
dl 8
loc 170
ccs 10
cts 58
cp 0.1724
rs 10
c 1
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
B sendJob() 0 24 3
A readingFinishedJobs() 0 16 2
A setupRedisInstance() 8 18 4
A handleException() 0 6 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * Nextcloud - OCR
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the COPYING file.
7
 * 
8
 * @author Janis Koehr <[email protected]>
9
 * @copyright Janis Koehr 2017
10
 */
11
namespace OCA\Ocr\Service;
12
13
use Exception;
14
use OCA\Ocr\Db\OcrJob;
15
use OCA\Ocr\Db\OcrJobMapper;
16
use OCP\IConfig;
17
use OCP\IL10N;
18
use OCP\ILogger;
19
use OCA\Ocr\Constants\OcrConstants;
20
21
22
/**
23
 * Class RedisService
24
 * 
25
 * @package OCA\Ocr\Service
26
 */
27
class RedisService {
28
29
    /**
30
     *
31
     * @var IConfig
32
     */
33
    private $config;
34
35
    /**
36
     *
37
     * @var OcrJobMapper
38
     */
39
    private $mapper;
40
41
    /**
42
     *
43
     * @var FileService
44
     */
45
    private $fileService;
46
47
    /**
48
     *
49
     * @var ILogger
50
     */
51
    private $logger;
52
53
    /**
54
     *
55
     * @var IL10N
56
     */
57
    private $l10n;
58
59
    /**
60
     *
61
     * @var string
62
     */
63
    private $redisHost;
64
65
    /**
66
     *
67
     * @var integer
68
     */
69
    private $redisPort;
70
71
    /**
72
     *
73
     * @var integer
74
     */
75
    private $redisDb;
76
77
    /**
78
     *
79
     * @var string
80
     */
81
    private $appName = 'ocr';
82
83
    /**
84
     * QueueService constructor.
85
     * 
86
     * @param OcrJobMapper $mapper            
87
     * @param FileService $fileService            
88
     * @param IConfig $config            
89
     * @param IL10N $l10n            
90
     * @param ILogger $logger            
91
     */
92 5
    public function __construct(OcrJobMapper $mapper, FileService $fileService, IConfig $config, IL10N $l10n, 
93
            ILogger $logger) {
94 5
        $this->mapper = $mapper;
95 5
        $this->fileService = $fileService;
96 5
        $this->logger = $logger;
97 5
        $this->l10n = $l10n;
98 5
        $this->config = $config;
99 5
        $this->redisHost = $this->config->getAppValue($this->appName, 'redisHost');
100 5
        $this->redisPort = intval($this->config->getAppValue($this->appName, 'redisPort'));
101 5
        $this->redisDb = intval($this->config->getAppValue($this->appName, 'redisDb'));
102 5
    }
103
104
    /**
105
     * Inits the client and sends the task to the background worker (async)
106
     * 
107
     * @param OcrJob $job            
108
     * @param string[] $languages            
109
     * @param string $occDir            
110
     */
111
    public function sendJob($job, $languages, $occDir) {
0 ignored issues
show
Unused Code introduced by
The parameter $occDir is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
112
        try {
113
            // check for messaging and put everything together
114
            $redis = $this->setupRedisInstance();
115
            $job = $this->mapper->insert($job);
116
            $msg = json_encode(
117
                    array(
118
                            'id' => $job->getId(),
119
                            'type' => $job->getType(),
120
                            'source' => $job->getSource(),
121
                            'tempFile' => $job->getTempFile(),
122
                            'languages' => $languages
123
                    ));
124
            if (!$redis->lPush(OcrConstants::REDIS_NEW_JOBS_QUEUE, $msg)) {
125
                throw new NotFoundException($this->l10n->t('Could not add files to the redis OCR processing queue.'));
126
            }
127
        } catch (Exception $e) {
128
            $this->fileService->execRemove($job->getTempFile());
129
            $job->setStatus('FAILED');
130
            $job->setErrorLog($this->l10n->t('Could not add files to the redis OCR processing queue.'));
131
            $this->mapper->update($job);
132
            $this->handleException($e);
133
        }
134
    }
135
136
    /**
137
     * Retrieves all finished jobs from redis and returns them.
138
     * 
139
     * @return string[]
140
     */
141
    public function readingFinishedJobs() {
142
        try {
143
            $redis = $this->setupRedisInstance();
144
            $result = $redis->multi()
145
                ->lRange(OcrConstants::REDIS_FINISHED_JOBS_QUEUE, 0, -1)
146
                ->delete(OcrConstants::REDIS_FINISHED_JOBS_QUEUE)
147
                ->exec();
148
            $this->logger->debug('Retrieved the following array from redis: {result}', 
149
                    [
150
                            'result' => $result[0]
151
                    ]);
152
            return $result[0];
153
        } catch (Exception $e) {
154
            $this->handleException($e);
155
        }
156
    }
157
158
    /**
159
     * Setup the Redis instance and return to whom ever it needs.
160
     * 
161
     * @throws NotFoundException
162
     * @return \Redis
163
     */
164
    private function setupRedisInstance() {
165 View Code Duplication
        if (!extension_loaded('redis')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
166
            $this->logger->debug(
167
                    'It seems that the message queueing capabilities are not available in your local php installation. Please install php-redis.');
168
            throw new NotFoundException($this->l10n->t('Message queueing capabilities are missing on the server.'));
169
        }
170
        $redis = new \Redis();
171
        if (!$redis->connect($this->redisHost, $this->redisPort, 2.5, NULL, 100)) {
172
            $this->logger->debug('Cannot connect to Redis.');
173
            throw new NotFoundException($this->l10n->t('Cannot connect to Redis.'));
174
        }
175 View Code Duplication
        if (!$redis->select($this->redisDb)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
176
            $this->logger->debug('Cannot connect to the right Redis database.');
177
            throw new NotFoundException($this->l10n->t('Cannot connect to the right Redis database.'));
178
        }
179
        $redis->setOption(\Redis::OPT_PREFIX, OcrConstants::REDIS_KEY_PREFIX);
180
        return $redis;
181
    }
182
183
    /**
184
     * Handle the possible thrown Exceptions from all methods of this class.
185
     * 
186
     * @param Exception $e            
187
     * @throws Exception
188
     * @throws NotFoundException
189
     */
190
    private function handleException($e) {
191
        $this->logger->logException($e, [
192
                'message' => 'Exception during message queue processing'
193
        ]);
194
        throw $e;
195
    }
196
}