Timur 5 lat temu
commit
01d7745122
8 zmienionych plików z 446 dodań i 0 usunięć
  1. 3 0
      .gitignore
  2. 21 0
      LICENSE
  3. 64 0
      README.md
  4. 23 0
      composer.json
  5. 5 0
      config/mangooffice.php
  6. 195 0
      src/Mango.php
  7. 114 0
      src/MangoApi.php
  8. 21 0
      src/MangoOfficeServiceProvider.php

+ 3 - 0
.gitignore

@@ -0,0 +1,3 @@
+/vendor
+.idea
+composer.lock

+ 21 - 0
LICENSE

@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2019 Ivan Alexandrov
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

+ 64 - 0
README.md

@@ -0,0 +1,64 @@
+# Класс для работы с IP-телефонией www.mango-office.ru
+
+## Установка
+```
+composer require timur-turdyev/laravel-mango-office
+```
+## Подключение
+В config/app.php в секции Package Service Providers <br />
+`TimurTurdyev\MangoOffice\ServiceProvider::class,` <br />
+
+## Конфигурация
+Выполняем команду <br />
+`php artisan vendor:publish` <br />
+
+Затем выбрыть провайдера 
+```
+TimurTurdyev\MangoOffice\MangoOfficeServiceProvider
+```
+Будет создан конфигурационный файл config/mangooffice.php, где:
+* api_key - Уникальный код АТС
+* api_salt - Ключ для создания подписи
+
+## Пример использования
+```php
+<?php
+
+namespace App\Http\Controllers;
+
+use Illuminate\Http\Request;
+use TimurTurdyev\MangoOffice\Mango;
+
+class TestController extends Controller
+{
+    public function test()
+    {
+        $mango = new Mango;
+
+        dd($mango->userList());
+    }
+}
+```
+## Доступные методы
+```
+// получить список всех пользователей<br>
+$mango->userList();
+
+// получить текущего пользователя<br>
+$mango->userList('добавочный номер пользователя');
+
+// получить статистику пользователя за указанный период<br>
+$mango->reportList('UNIX формат начальная дата', 'UNIX формат конечная дата', 'внутренний номер абонента');
+
+// получить статистику всех пользователей за указанный период<br>
+$mango->reportList('начальная дата', 'конечная дата');
+
+// скачать запись разговора<br>
+$mango->downloadAudio('уникальный идентификатор записи');
+
+// скачать запись разговора<br>
+$mango->downloadAudio('уникальный идентификатор записи');
+
+// воспроизвести запись разговора<br>
+$mango->downloadAudio('уникальный идентификатор записи', 'play');
+```

+ 23 - 0
composer.json

@@ -0,0 +1,23 @@
+{    
+    "name": "timur-turdyev/laravel-mango-office",
+    "description": "Mango-office API class",
+    "keywords": ["Mango-office", "Mango", "Mango-office API", "Mango class"],
+    "minimum-stability": "stable",
+    "type": "library",
+    "version":"1.0",
+    "repositories": [
+        {
+            "type": "composer",
+            "url": "https://github.com/TimurTurdyev/mango-office.git"
+        }
+    ],
+    "require": {
+        "php": "^7.2",
+        "guzzlehttp/guzzle": "^7"
+    },
+    "autoload": {
+        "psr-4": {
+           "TimurTurdyev\\MangoOffice\\": "src/"
+        }
+    }
+}

+ 5 - 0
config/mangooffice.php

@@ -0,0 +1,5 @@
+<?php
+return [
+    'api_key' => '',
+    'api_salt' => ''
+];

+ 195 - 0
src/Mango.php

@@ -0,0 +1,195 @@
+<?php
+namespace TimurTurdyev\MangoOffice;
+
+use TimurTurdyev\Mangooffice\MangoApi;
+use Illuminate\Support\Facades\Config;
+/**
+ * Список методов для работы с API mango-office
+ *
+ * @author Ivan Alexandrov <yahve1989@gmail.com>
+ */
+class Mango extends MangoApi
+{
+    /**
+     * Уникальный код АТС
+     *
+     * @var string $apiKey
+     */
+    private $apiKey = null;
+
+    /**
+     * Ключ для создания подписи
+     *
+     * @var string $apiSalt
+     */
+    private $apiSalt = null;
+
+    public function __construct()
+    {
+        $this->apiKey = config('mangooffice.api_key');
+        $this->apiSalt = config('mangooffice.api_salt');
+
+        if (empty($this->apiKey) or empty($this->apiSalt)) {
+            throw new Exception('bad request', 400, null);
+        }
+    }
+
+    /**
+     * Mетод авторизации для манго
+     * @param array $request данные запроса
+     * @param string $apiKey Уникальный код АТС
+     * @param string $apiSalt Ключ для создания подписи
+     * @return array
+     */
+    private function authParam($request)
+    {
+        $json = json_encode($request, JSON_UNESCAPED_SLASHES);
+        $sign = hash('sha256', $this->apiKey . $json . $this->apiSalt);
+        return ['vpbx_api_key' => $this->apiKey,
+            'sign' => $sign,
+            'json' => $json,
+        ];
+    }
+
+    /**
+     * метод конвертации данных
+     * @param string $csvData данные в формате CSV
+     * @return array
+     */
+    private function csvToArray($csvData)
+    {
+        $lines = str_getcsv($csvData, "\n");
+
+        foreach ($lines as $key => $line) {
+            $array = str_getcsv($line, ';');
+            $records = array_filter(explode(',', trim($array[0], '[]')));
+            $arResult[$key]['records'] = $records;
+            $arResult[$key]['start'] = $array[1];
+            $arResult[$key]['finish'] = $array[2];
+            $arResult[$key]['answer'] = $array[3];
+            $arResult[$key]['from_extension'] = $array[4];
+            $arResult[$key]['from_number'] = $array[5];
+            $arResult[$key]['to_extension'] = $array[6];
+            $arResult[$key]['to_number'] = $array[7];
+            $arResult[$key]['disconnect_reason'] = $array[8];
+            $arResult[$key]['location'] = $array[9];
+            $arResult[$key]['line_number'] = $array[10];
+            $arResult[$key]['entry_id'] = $array[11];
+        }
+
+        return $arResult;
+    }
+
+    /**
+     * получает список звонков за выбранный период
+     * @param string $dateFrom начальная дата
+     * @param string $dateTo конечная дата
+     * @param integer $extension внутренний номер абонента
+     * @return array || null
+     */
+    public function reportList($dateFrom, $dateTo, $extension = null)
+    {
+        $request = [];
+
+        if (empty($dateFrom) or empty($dateTo)) {
+            throw new Exception('bad request', 400, null);
+        }
+
+        if (!empty($extension)) {
+            $request['call_party'] = ['extension' => $extension];
+        }
+
+        $request['date_from'] = $dateFrom;
+        $request['date_to'] = $dateTo;
+        $request['fields'] = implode(',', [
+            'records',
+            'start',
+            'finish',
+            'answer',
+            'from_extension',
+            'from_number',
+            'to_extension',
+            'to_number',
+            'disconnect_reason',
+            'location',
+            'line_number',
+            'entry_id',
+        ]);
+
+        $init = MangoApi::init();
+        $data = $init->setBaseUri('https://app.mango-office.ru')
+            ->setPath('/vpbx/stats/request')
+            ->setMethod('POST')
+            ->setFormParams($this->authParam($request))
+            ->execute();
+        $response = $data->client->getBody()->getContents();
+        $data = $init->setBaseUri('https://app.mango-office.ru')
+            ->setPath('/vpbx/stats/result')
+            ->setMethod('POST')
+            ->setFormParams($this->authParam(json_decode($response)))
+            ->execute();
+        $csvData = $data->client->getBody()->getContents();
+
+        if ($ResponseJson = json_decode($csvData)) {
+            return $ResponseJson;
+        }
+
+        if (strlen($csvData) > 0) {
+            return $this->csvToArray($csvData);
+        }
+
+        return null;
+    }
+
+    /**
+     * получает запись разговора
+     * @param string $recordingId уникальный идентификатор записи
+     * @param string $action download | play
+     * @return mp3 file | array
+     */
+    public function downloadAudio($recordingId, $action = 'download')
+    {
+        if (empty($recordingId)) {
+            throw new Exception('bad request', 400, null);
+        }
+
+        $init = MangoApi::init();
+        $data = $init->setBaseUri('https://app.mango-office.ru')
+            ->setPath('/vpbx/queries/recording/post')
+            ->setMethod('POST')
+            ->setFormParams($this->authParam([
+                'recording_id' => $recordingId,
+                'action' => $action,
+            ]))->execute();
+        $recording = $data->client->getBody()->getContents();
+
+        if ($ResponseJson = json_decode($recording)) {
+            return $ResponseJson;
+        }
+
+        return $recording;
+    }
+
+    /**
+     * получает список пользовател
+     * @param integer $extension внутренний номер абонента
+     * @return array
+     */
+    public function userList($extension = null)
+    {
+        $param = [];
+
+        if (!empty($extension)) {
+            $param = ['extension' => $extension];
+        }
+
+        $init = MangoApi::init();
+        $data = $init->setBaseUri('https://app.mango-office.ru')
+            ->setPath('/vpbx/config/users/request')
+            ->setMethod('POST')
+            ->setFormParams($this->authParam($param))->execute();
+        $response = $data->client->getBody()->getContents();
+
+        return json_decode($response);
+    }
+}

+ 114 - 0
src/MangoApi.php

@@ -0,0 +1,114 @@
+<?php
+namespace TimurTurdyev\MangoOffice;
+
+use GuzzleHttp\Client;
+use GuzzleHttp\Cookie\CookieJar;
+use GuzzleHttp\Psr7\Request;
+
+/**
+ * класс для взаимодействия с API mango-office
+ *
+ * @author Ivan Alexandrov <yahve1989@gmail.com>
+ */
+class MangoApi
+{
+    public static $instance = null;
+    public $baseUri = null;
+    public $path = null;
+    public $method = null;
+    public $cookies = null;
+    public $client = null;
+    public $formParams = null;
+    public $headers = null;
+
+    /**
+     * @return type $instance
+     */
+    public static function init()
+    {
+
+        if (self::$instance === null) {
+            self::$instance = new self();
+        }
+
+        return self::$instance;
+    }
+
+    public function __construct()
+    {
+        $this->cookies = new CookieJar();
+    }
+
+    /**
+     * @param type $path
+     */
+    public function setPath($path)
+    {
+        $this->path = $path;
+        return $this;
+    }
+
+    /**
+     * @param type $formParams
+     */
+    public function setFormParams($formParams)
+    {
+        $this->formParams = $formParams;
+        return $this;
+    }
+
+    /**
+     * @param type $headers
+     */
+    public function setHeaders($headers)
+    {
+        $this->headers = $headers;
+        return $this;
+    }
+
+    /**
+     * @param type $baseUri
+     */
+    public function setBaseUri($baseUri)
+    {
+        $this->baseUri = $baseUri;
+        return $this;
+    }
+
+    /**
+     * @param type $method
+     */
+    public function setMethod($method)
+    {
+        $this->method = $method;
+        return $this;
+    }
+
+    /**
+     * @return type string
+     */
+    public function execute()
+    {
+        $client = new Client([
+            'cookies' => true,
+            'base_uri' => $this->baseUri,
+            'timeout' => 60,
+            'headers' => $this->headers,
+        ]);
+        $this->client = $client->request($this->method, $this->path, [
+            'debug' => false,
+            'verify' => false,
+            'cookies' => $this->cookies,
+            'http_errors' => false,
+            'allow_redirects' => [
+                'max' => 10,
+                'strict' => true,
+                'referer' => true,
+                'track_redirects' => true,
+            ],
+            'form_params' => $this->formParams,
+        ]);
+
+        return $this;
+    }
+}

+ 21 - 0
src/MangoOfficeServiceProvider.php

@@ -0,0 +1,21 @@
+<?php
+namespace TimurTurdyev\MangoOffice;
+
+
+class ServiceProvider extends \Illuminate\Support\ServiceProvider
+{
+    /**
+     * Bootstrap any application services.
+     *
+     * @return void
+     */
+    public function boot()
+    {
+        $this->publishes([__DIR__ . '/../config/mangooffice.php' => config_path('mangooffice.php')]);
+    }
+
+    public function register()
+    {
+    }
+
+}