Passed
Push — develop ( 3bb550...c283a9 )
by Nikolay
06:01 queued 11s
created

PostController   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 82
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 51
dl 0
loc 82
rs 10
c 1
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A callAction() 0 12 3
A uploadResumableAction() 0 31 4
A fileReadContent() 0 24 3
1
<?php
2
/**
3
 * Copyright (C) MIKO LLC - All Rights Reserved
4
 * Unauthorized copying of this file, via any medium is strictly prohibited
5
 * Proprietary and confidential
6
 * Written by Nikolay Beketov, 4 2020
7
 *
8
 */
9
10
namespace MikoPBX\PBXCoreREST\Controllers\Files;
11
12
use MikoPBX\Common\Models\SoundFiles;
13
use MikoPBX\Core\System\Util;
14
use MikoPBX\PBXCoreREST\Controllers\BaseController;
15
use Phalcon\Di;
16
17
/**
18
 * /pbxcore/api/files/{name}' Files management (POST).
19
 *
20
 * Get config file content
21
 *   curl -X POST -d '{"filename": "/etc/asterisk/asterisk.conf"}'
22
 *   http://172.16.156.212/pbxcore/api/files/fileReadContent;
23
 *
24
 * Answer example:
25
 *   {"result":"ERROR","message":"API action not found;","function":"fileReadContent"}
26
 *   {"result":"Success","data":"W2RpcmVj","function":"fileReadContent"}
27
 *
28
 * Convert audiofile:
29
 *   curl -X POST -d '{"filename": "/tmp/WelcomeMaleMusic.mp3"}'
30
 *   http://172.16.156.212/pbxcore/api/files/convertAudioFile;
31
 *
32
 *  Answer example:
33
 *   {
34
 *      "result": "Success",
35
 *      "filename": "/tmp/WelcomeMaleMusic.wav",
36
 *      "function": "convertAudioFile"
37
 *   }
38
 *
39
 *
40
 * Delete Audio file:
41
 *   curl -X POST -d '{"filename": "/storage/usbdisk1/mikopbx/tmp/2233333.wav"}'
42
 *   http://172.16.156.212/pbxcore/api/files/removeAudioFile;
43
 *
44
 *
45
 * Install new module with params by URL
46
 * curl -X POST -d '{"uniqid":"ModuleCTIClient", "md5":"fd9fbf38298dea83667a36d1d0464eae", "url":
47
 * "https://www.askozia.ru/upload/update/modules/ModuleCTIClient/ModuleCTIClientv01.zip"}'
48
 * http://172.16.156.223/pbxcore/api/files/uploadNewModule;
49
 *
50
 *
51
 * Receive uploading status
52
 * curl  -X POST -d '{"uniqid":"ModuleSmartIVR"} http://172.16.156.223/pbxcore/api/files/statusUploadingNewModule
53
 *
54
 * Install new module from ZIP archive:
55
 * curl -F "[email protected]" http://127.0.0.1/pbxcore/api/files/uploadNewModule;
56
 *
57
 * Uninstall module:
58
 * curl -X POST -d '{"uniqid":"ModuleSmartIVR"} http://172.16.156.223/pbxcore/api/files/uninstallModule
59
 *
60
 * Upload file:
61
 *   curl -X POST -d '{"id": "1531474060"}' http://127.0.0.1/pbxcore/api/files/statusUpload; -H 'Cookie:
62
 *
63
 *   XDEBUG_SESSION=PHPSTORM'
64
 */
65
class PostController extends BaseController
66
{
67
    public function callAction($actionName): void
68
    {
69
        switch ($actionName) {
70
            case 'fileReadContent':
71
                $this->fileReadContent();
72
                break;
73
            case 'uploadResumable':
74
                $this->uploadResumableAction();
75
                break;
76
            default:
77
                $data = $this->request->getPost();
78
                $this->sendRequestToBackendWorker('files', $actionName, $data);
79
        }
80
    }
81
82
    /**
83
     * Parses content of file and puts it to answer
84
     *
85
     */
86
    private function fileReadContent(): void
87
    {
88
        $requestMessage = json_encode(
89
            [
90
                'processor' => 'files',
91
                'data'      => $this->request->getPost(),
92
                'action'    => 'fileReadContent',
93
            ]
94
        );
95
        $connection     = $this->di->getShared('beanstalkConnection');
96
        $response       = $connection->request($requestMessage, 5, 0);
97
        if ($response !== false) {
98
            $response = json_decode($response, true);
99
            $filename = $response['data']['filename'] ?? '';
100
            if ( ! file_exists($filename)) {
101
                $response['messages'][] = 'Config file not found';
102
            } else {
103
                $response['data']['filename'] = $filename;
104
                $response['data']['content']  = mb_convert_encoding('' . file_get_contents($filename), 'UTF-8', 'UTF-8');
105
                unlink($filename);
106
            }
107
            $this->response->setPayloadSuccess($response);
108
        } else {
109
            $this->sendError(500);
110
        }
111
    }
112
113
    /**
114
     * Upload files by chunks
115
     */
116
    public function uploadResumableAction(): void
117
    {
118
        $data   = $this->request->getPost();
119
        $data['result'] = 'ERROR';
120
121
        if ($this->request->hasFiles() > 0) {
122
            $data = [
123
                'resumableFilename'    => $this->request->getPost('resumableFilename'),
124
                'resumableIdentifier'  => $this->request->getPost('resumableIdentifier'),
125
                'resumableChunkNumber' => $this->request->getPost('resumableChunkNumber'),
126
                'resumableTotalChunks' => $this->request->getPost('resumableTotalChunks'),
127
                'resumableTotalSize'   => $this->request->getPost('resumableTotalSize'),
128
            ];
129
            foreach ($this->request->getUploadedFiles() as $file) {
130
                $data['files'][]= [
131
                    'file_path' => $file->getTempName(),
132
                    'file_size' => $file->getSize(),
133
                    'file_error'=> $file->getError(),
134
                    'file_name' => $file->getName(),
135
                    'file_type' => $file->getType()
136
                ];
137
                if ($file->getError()) {
138
                    $data['data'] = 'error ' . $file->getError() . ' in file ' . $file->getTempName();
139
                    $this->sendError(400, $data['data']);
140
                    Util::sysLogMsg('UploadFile', 'error ' . $file->getError() . ' in file ' . $file->getTempName());
141
                    return;
142
                }
143
            }
144
        }
145
146
        $this->sendRequestToBackendWorker('files', 'uploadResumable', $data);
147
    }
148
149
}