Passed
Push — develop ( a56058...ddfce4 )
by Nikolay
04:39
created

ConvertAudioFileAction::main()   B

Complexity

Conditions 10
Paths 11

Size

Total Lines 68
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 42
c 1
b 0
f 0
dl 0
loc 68
rs 7.6666
cc 10
nc 11
nop 1

How to fix   Long Method    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
 * MikoPBX - free phone system for small business
4
 * Copyright © 2017-2024 Alexey Portnov and Nikolay Beketov
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with this program.
17
 * If not, see <https://www.gnu.org/licenses/>.
18
 */
19
20
namespace MikoPBX\PBXCoreREST\Lib\System;
21
22
use MikoPBX\Core\System\Processes;
23
use MikoPBX\Core\System\Util;
24
use MikoPBX\PBXCoreREST\Lib\PBXApiResult;
25
/**
26
 *
27
 * @package MikoPBX\PBXCoreREST\Lib\System
28
 */
29
class ConvertAudioFileAction extends \Phalcon\Di\Injectable
30
{
31
    /**
32
     * Convert the audio file to various codecs using Asterisk.
33
     *
34
     * @param string $filename The path of the audio file to be converted.
35
     * @return PBXApiResult An object containing the result of the API call.
36
     */
37
    public static function main(string $filename): PBXApiResult
38
    {
39
        $res            = new PBXApiResult();
40
        $res->processor = __METHOD__;
41
        if ( ! file_exists($filename)) {
42
            $res->success    = false;
43
            $res->messages[] = "File '{$filename}' not found.";
44
45
            return $res;
46
        }
47
        $out          = [];
48
        $tmp_filename = '/tmp/' . time() . "_" . basename($filename);
49
        if (false === copy($filename, $tmp_filename)) {
50
            $res->success    = false;
51
            $res->messages[] = "Unable to create temporary file '{$tmp_filename}'.";
52
53
            return $res;
54
        }
55
56
        // Change extension to wav
57
        $trimmedFileName = Util::trimExtensionForFile($filename);
58
        $n_filename     = $trimmedFileName . ".wav";
59
        $n_filename_mp3 = $trimmedFileName . ".mp3";
60
61
        // Convert file to wav format
62
        $tmp_filename = escapeshellcmd($tmp_filename);
63
        $n_filename   = escapeshellcmd($n_filename);
64
        $soxPath      = Util::which('sox');
65
        Processes::mwExec("{$soxPath} -v 0.99 -G '{$tmp_filename}' -c 1 -r 8000 -b 16 '{$n_filename}'", $out);
66
        $result_str = implode('', $out);
67
68
        // Convert wav file to mp3 format
69
        $lamePath = Util::which('lame');
70
        Processes::mwExec("{$lamePath} -b 32 --silent '{$n_filename}' '{$n_filename_mp3}'", $out);
71
        $result_mp3 = implode('', $out);
72
73
        // Convert the file to various codecs using Asterisk
74
        $codecs = ['alaw', 'ulaw', 'gsm', 'g722', 'wav'];
75
        $rmPath       = Util::which('rm');
76
        $asteriskPath = Util::which('asterisk');
77
        foreach ($codecs as $codec){
78
            $result = shell_exec("$asteriskPath -rx 'file convert $tmp_filename $trimmedFileName.$codec'");
79
            if(strpos($result, 'Converted') !== 0){
80
                shell_exec("$rmPath -rf /root/test.{$codec}");
81
            }
82
        }
83
84
        // Remove temporary file
85
        unlink($tmp_filename);
86
        if ($result_str !== '' && $result_mp3 !== '') {
87
            // Conversion failed
88
            $res->success    = false;
89
            $res->messages[] = $result_str;
90
91
            return $res;
92
        }
93
94
        if (file_exists($filename)
95
            && $filename !== $n_filename
96
            && $filename !== $n_filename_mp3) {
97
            // Remove the original file if it's different from the converted files
98
            unlink($filename);
99
        }
100
101
        $res->success = true;
102
        $res->data[]  = $n_filename_mp3;
103
104
        return $res;
105
    }
106
}