TranscodeAssetActivity   B
last analyzed

Complexity

Total Complexity 38

Size/Duplication

Total Lines 243
Duplicated Lines 1.65 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 4
loc 243
rs 8.3999
c 0
b 0
f 0
wmc 38
lcom 1
cbo 5

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
C process() 0 50 7
B transcodeImage() 0 25 2
B transcodeVideo() 0 36 4
C uploadResultFiles() 0 51 9
B getOutputPath() 4 28 4
C validateInput() 0 28 11

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
#!/usr/bin/php
2
3
<?php
4
5
/*
6
 *   This class handles the transcoding activity
7
 *   Based on the input file type we lunch the proper transcoder
8
 *
9
 *   Copyright (C) 2016  BFan Sports - Sport Archive Inc.
10
 *
11
 *   This program is free software; you can redistribute it and/or modify
12
 *   it under the terms of the GNU General Public License as published by
13
 *   the Free Software Foundation; either version 2 of the License, or
14
 *   (at your option) any later version.
15
 *
16
 *   This program is distributed in the hope that it will be useful,
17
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 *   GNU General Public License for more details.
20
 *
21
 *   You should have received a copy of the GNU General Public License along
22
 *   with this program; if not, write to the Free Software Foundation, Inc.,
23
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24
 */
25
26
require_once __DIR__.'/BasicActivity.php';
27
28
use SA\CpeSdk;
29
30
class TranscodeAssetActivity extends BasicActivity
31
{
32
    const CONVERSION_TYPE_ERROR = "CONVERSION_TYPE_ERROR";
33
    const TMP_PATH_OPEN_FAIL    = "TMP_PATH_OPEN_FAIL";
34
35
    private $output;
0 ignored issues
show
Unused Code introduced by
The property $output is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
36
    private $outputFilesPath;
37
38
    public function __construct($client = null, $params, $debug, $cpeLogger)
39
    {
40
        parent::__construct($client, $params, $debug, $cpeLogger);
41
    }
42
43
    // Perform the activity
44
    public function process($task)
45
    {
46
        // Call parent do_activity:
47
        // It download the input file we will process.
48
        parent::process($task);
49
50
        // Save output object
51
        $this->outputs = $this->input->{'output_assets'};
52
53
        $this->cpeLogger->logOut(
54
            "INFO",
55
            basename(__FILE__),
56
            "Preparing Asset transcoding ...",
57
            $this->logKey
58
        );
59
60
        foreach ($this->outputs as $output)
0 ignored issues
show
Bug introduced by
The property outputs does not seem to exist. Did you mean output?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
61
        {
62
            $this->validateInput($output);
63
            
64
            // Set output path to store result files
65
            $this->outputFilesPath = $this->getOutputPath($output);
66
            
67
            // Load the right transcoder base on input_type
68
            // Get asset detailed info
69
            switch ($this->input->{'input_asset'}->{'type'})
70
            {
71
            case self::VIDEO:
72
                $result = $this->transcodeVideo($task, $output);
73
                break;
74
            case self::IMAGE:
75
                $result = $this->transcodeImage($task, $output);
76
                break;
77
            case self::AUDIO:
78
            case self::DOC:
79
                break;
80
            default:
81
                throw new CpeSdk\CpeException("Unknown input asset 'type'! Abording ...",
82
                                              self::UNKOWN_INPUT_TYPE);
83
            }
84
85
            // Upload resulting file
86
            $this->uploadResultFiles($task, $output);
87
88
            if ($this->client)
89
                $this->client->onTranscodeDone($this->token, $result);
0 ignored issues
show
Bug introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
90
        }
91
92
        return json_encode($result);
93
    }
94
95
    // Process INPUT IMAGE
96
    private function transcodeImage($task, $output)
97
    {
98
        require_once __DIR__.'/transcoders/ImageTranscoder.php';
99
        
100
        // Instanciate transcoder to output Images
101
        $imageTranscoder = new ImageTranscoder($this, $task);
102
        
103
        # If we have metadata, we expect the output of ffprobe
104
        $metadata = null;
105
        if (isset($this->input->{'input_metadata'}))
106
            $metadata = $this->input->{'input_metadata'};
107
        
108
        // Perform transcoding
109
        $result = $imageTranscoder->transcode_asset(
110
            $this->tmpInputPath,
111
            $this->inputFilePath,
112
            $this->outputFilesPath,
113
            $metadata,
114
            $output
115
        );
116
        
117
        unset($imageTranscoder);
118
119
        return ($result);
120
    }
121
    
122
    // Process INPUT VIDEO
123
    private function transcodeVideo($task, $output)
124
    {
125
        require_once __DIR__.'/transcoders/VideoTranscoder.php';
126
        
127
        // Instanciate transcoder to output Videos
128
        $videoTranscoder = new VideoTranscoder($this, $task);
129
130
        // Check preset file, read its content and add its data to output object
131
        if ($output->{'type'} == self::VIDEO &&
132
            isset($output->{'preset'}))
133
        {
134
            // Validate output preset
135
            $videoTranscoder->validate_preset($output);
136
137
            // Set preset value
138
            $output->{'preset_values'} = $videoTranscoder->get_preset_values($output);
139
        }
140
141
        # If we have metadata, we expect the output of ffprobe
142
        $metadata = null;
143
        if (isset($this->input->{'input_metadata'}))
144
            $metadata = $this->input->{'input_metadata'};
145
146
        // Perform transcoding
147
        $result = $videoTranscoder->transcode_asset(
148
            $this->tmpInputPath,
149
            $this->inputFilePath,
150
            $this->outputFilesPath,
151
            $metadata,
152
            $output
153
        );
154
        
155
        unset($videoTranscoder);
156
157
        return ($result);
158
    }
159
160
    // Upload all output files to destination S3 bucket
161
    private function uploadResultFiles($task, $output)
0 ignored issues
show
Unused Code introduced by
The parameter $task 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...
162
    {
163
        // Sanitize output bucket and file path "/"
164
        $s3Bucket = str_replace("//", "/",
165
                                $output->{"bucket"});
166
167
        // Set S3 options
168
        $options = array("rrs" => false, "encrypt" => false);
169
        if (isset($output->{'s3_rrs'}) &&
170
            $output->{'s3_rrs'} == true) {
171
            $options['rrs'] = true;
172
        }
173
        if (isset($output->{'s3_encrypt'}) &&
174
            $output->{'s3_encrypt'} == true) {
175
            $options['encrypt'] = true;
176
        }
177
178
        // Open '$outputFilesPath' to read it and send all files to S3 bucket
179
        if (!$handle = opendir($this->outputFilesPath)) {
180
            throw new CpeSdk\CpeException("Can't open tmp path '$this->outputFilesPath'!",
181
                                          self::TMP_PATH_OPEN_FAIL);
182
        }
183
184
        // Upload all resulting files sitting in $outputFilesPath to S3
185
        while ($entry = readdir($handle)) {
186
            if ($entry == "." || $entry == "..") {
187
                continue;
188
            }
189
190
            // Destination path on S3. Sanitizing
191
            $s3Location = $output->{'output_file_info'}['dirname']."/$entry";
192
            $s3Location = str_replace("//", "/", $s3Location);
193
194
            // Send to S3. We reference the callback s3_put_processing_callback
195
            // The callback ping back SWF so we stay alive
196
            $s3Output = $this->s3Utils->put_file_into_s3(
197
                $s3Bucket,
198
                $s3Location,
199
                "$this->outputFilesPath/$entry",
200
                $options,
201
                array($this, "activityHeartbeat"),
202
                null
203
            );
204
            // We delete the TMP file once uploaded
205
            unlink("$this->outputFilesPath/$entry");
206
207
            $this->cpeLogger->logOut("INFO", basename(__FILE__),
208
                                     $s3Output['msg'],
209
                                     $this->logKey);
210
        }
211
    }
212
213
    private function getOutputPath($output)
214
    {
215
        $outputFilesPath = self::TMP_FOLDER
216
                         . $this->name."/".$this->logKey;
217
218
        $output->{'key'} = $output->{'path'}."/".$output->{'file'};
219
220
        // Create TMP folder for output files
221
        $outputFileInfo = pathinfo($output->{'key'});
222
        $output->{'output_file_info'} = $outputFileInfo;
223
        $outputFilesPath .= $outputFileInfo['dirname'];
224
225
        if (!file_exists($outputFilesPath))
226
        {
227 View Code Duplication
            if ($this->debug)
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...
228
                $this->cpeLogger->logOut("INFO", basename(__FILE__),
229
                                         "Creating TMP output folder '".$outputFilesPath."'",
230
                                         $this->logKey);
231
232
            if (!mkdir($outputFilesPath, 0750, true))
233
                throw new CpeSdk\CpeException(
234
                    "Unable to create temporary folder '$outputFilesPath' !",
235
                    self::TMP_FOLDER_FAIL
236
                );
237
        }
238
239
        return ($outputFilesPath);
240
    }
241
242
    // Perform custom validation on JSON input
243
    // Callback function used in $this->do_input_validation
244
    private function validateInput($output)
245
    {
246
        if ((
247
            $this->input->{'input_asset'}->{'type'} == self::VIDEO &&
248
            $output->{'type'} != self::VIDEO &&
249
            $output->{'type'} != self::THUMB &&
250
            $output->{'type'} != self::AUDIO
251
        )
252
            ||
253
            (
254
                $this->input->{'input_asset'}->{'type'} == self::IMAGE &&
255
                $output->{'type'} != self::IMAGE
256
            )
257
            ||
258
            (
259
                $this->input->{'input_asset'}->{'type'} == self::AUDIO &&
260
                $output->{'type'} != self::AUDIO
261
            )
262
            ||
263
            (
264
                $this->input->{'input_asset'}->{'type'} == self::DOC &&
265
                $output->{'type'} != self::DOC
266
            ))
267
        {
268
            throw new CpeSdk\CpeException("Can't convert that input asset 'type' (".$this->input->{'input_asset'}->{'type'}.") into this output asset 'type' (".$output->{'type'}.")! Abording.",
269
                                          self::CONVERSION_TYPE_ERROR);
270
        }
271
    }
272
}
273
274
275
/*
276
***************************
277
* Activity Startup SCRIPT
278
***************************
279
*/
280
281
// Usage
282 View Code Duplication
function usage()
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in 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...
283
{
284
    echo("Usage: php ". basename(__FILE__) . " -A <Snf ARN> [-C <client class path>] [-N <activity name>] [-h] [-d] [-l <log path>]\n");
285
    echo("-h: Print this help\n");
286
    echo("-d: Debug mode\n");
287
    echo("-l <log_path>: Location where logs will be dumped in (folder).\n");
288
    echo("-A <activity_name>: Activity name this Poller can process. Or use 'SNF_ACTIVITY_ARN' environment variable. Command line arguments have precedence\n");
289
    echo("-C <client class path>: Path to the PHP file that contains the class that implements your Client Interface\n");
290
    echo("-N <activity name>: Override the default activity name. Useful if you want to have different client interfaces for the same activity type.\n");
291
    exit(0);
292
}
293
294
// Check command line input parameters
295 View Code Duplication
function check_activity_arguments()
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in 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...
296
{
297
    // Filling the globals with input
298
    global $arn;
299
    global $logPath;
300
    global $debug;
301
    global $clientClassPath;
302
    global $name;
303
304
    // Handle input parameters
305
    if (!($options = getopt("N:A:l:C:hd")))
306
        usage();
307
308
    if (isset($options['h']))
309
        usage();
310
311
    // Debug
312
    if (isset($options['d']))
313
        $debug = true;
314
315
    if (isset($options['A']) && $options['A']) {
316
        $arn = $options['A'];
317
    } else if (getenv('SNF_ACTIVITY_ARN')) {
318
        $arn = getenv('SNF_ACTIVITY_ARN');
319
    } else {
320
        echo "ERROR: You must provide the ARN of your activity (Sfn ARN). Use option [-A <ARN>] or environment variable: 'SNF_ACTIVITY_ARN'\n";
321
        usage();
322
    }
323
324
    if (isset($options['C']) && $options['C']) {
325
        $clientClassPath = $options['C'];
326
    }
327
328
    if (isset($options['N']) && $options['N']) {
329
        $name = $options['N'];
330
    }
331
332
    if (isset($options['l']))
333
        $logPath = $options['l'];
334
}
335
336
337
338
/*
339
 * START THE SCRIPT ACTITIVY
340
 */
341
342
// Globals
343
$debug = false;
344
$logPath = null;
345
$arn;
346
$name = 'TranscodeAsset';
347
$clientClassPath = null;
348
349
check_activity_arguments();
350
351
$cpeLogger = new SA\CpeSdk\CpeLogger($name, $logPath);
352
$cpeLogger->logOut("INFO", basename(__FILE__),
353
                   "\033[1mStarting activity\033[0m: $name");
354
355
// We instanciate the Activity 'ValidateAsset' and give it a name for Snf
356
$activityPoller = new TranscodeAssetActivity(
357
    $clientClassPath,
358
    [
359
        'arn'  => $arn,
360
        'name' => $name
361
    ],
362
    $debug,
363
    $cpeLogger);
364
365
// Initiate the polling loop and will call your `process` function upon trigger
366
$activityPoller->doActivity();
367