You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

507 lines
14 KiB

<?php
namespace app\Providers;
use app\Interfaces\IApiMedia;
use app\Providers\RequestURL;
class Positus implements IApiMedia
{
private $token;
private $url;
private $metodo;
private $query;
private $requestType;
private $request;
private $params = array();
private $hook;
private $storage = CONF_PATH_FILES;
public $channel = CONF_WHATSAPP_CHANNEL;
public $timeout_client_resposta = CONF_WHATSAPP_TIMEOUT_CLIENT_RESPOSTA;
function __construct()
{
$this->token = CONF_WHATSAPP_AUTH_TOKEN;
$this->url = CONF_WHATSAPP_AUTH_URL;
$this->request = new RequestURL();
}
public function getchannel()
{
return CONF_WHATSAPP_CHANNEL;
}
public function convertToWebsocket($content, $matricula = '', $uniqueid, $type, $name, $number, $data, $idProvedor, $mimetype)
{
if ($number) {
$mensagem = [];
$mensagem["event"] = [
"type" => "mensagem",
"contact" => [
"name" => $name,
"number" => $number,
"matricula" => ''
],
"mensagem" => [
"type" => $type,
"content" => $content,
"id_provedor" => $idProvedor,
"dst" => $matricula,
"uniqueid" => $uniqueid,
"media" => $this->channel,
"file_name" => $this->retornaTituloDocument(),
"datetime" => $data,
"status" => "sent",
'mimetype' => $mimetype
]
];
return json_encode($mensagem);
}
return null;
}
function enviaImagem($whatsapp, $link, $titulo = null)
{
}
function enviaSticker($whatsapp, $link)
{
}
function enviaVideo($whatsapp, $link, $titulo = null)
{
}
function enviaAudio($whatsapp, $link)
{
}
function enviaDocumento($whatsapp, $link, $titulo = null)
{
}
function enviarMedia($whatsapp, $link, $type, $titulo = null)
{
$tipos = [];
$tipos['link'] = $link;
if (!empty($titulo)) {
$tipos['caption'] = $titulo;
}
$this->debug = debug_backtrace();
$this->params = [
"to" => "+$whatsapp",
"type" => "$type",
"$type" => $tipos
];
$this->requestType("POST");
$this->setMetodo('messages');
return $this->exec();
}
function enviarMsg($whatsapp, $mensagem, $encode = true)
{
if ($encode) {
$mensagem = utf8_encode($mensagem);
}
$this->debug = debug_backtrace();
$this->params = array(
"to" => "+$whatsapp",
"type" => "text",
"text" => array("body" => "$mensagem")
);
$this->requestType("POST");
$this->setMetodo('messages');
return $this->exec();
}
function enviarMsgIterativaLista($whatsapp, $mensagem, $nomeButton, $lista, $prex = '')
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"to" => "+$whatsapp",
"type" => "interactive",
"interactive" => array(
"type" => "list",
"body" => array(
"text" => utf8_encode($mensagem)
),
"action" => array(
"button" => utf8_encode($nomeButton),
"sections" => $this->montaSection($lista, $prex)
)
)
);
$this->requestType("POST");
$this->setMetodo('messages');
$ret = $this->exec();
return $ret;
}
return false;
}
function montaSection($lista, $prex = '')
{
$sections = [];
for ($i = 0; $i < count($lista); $i++) {
array_push(
$sections,
array(
"id" => "$prex$i",
"title" => utf8_encode("{$lista[$i]['title']}"),
"description" => utf8_encode("{$lista[$i]['sub']}")
)
);
}
return array(
array(
"title" => utf8_encode("Comandos"),
"rows" => $sections
),
);
}
function enviarMsgIterativaBotao($whatsapp, $mensagem, $buttons)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"to" => "+$whatsapp",
"type" => "interactive",
"recipient_type" => "individual",
"interactive" => array(
"type" => "button",
"body" => array(
"text" => utf8_encode($mensagem)
),
"action" => array(
"buttons" => $buttons
)
)
);
$this->requestType("POST");
$this->setMetodo('messages');
$ret = $this->exec();
return $ret;
}
return false;
}
function enviarContato($whatsapp, $nome, $contato)
{
$this->debug = debug_backtrace();
if ($whatsapp) {
$this->params = array(
"to" => "+$whatsapp",
"type" => "contacts",
"contacts" => array(
array(
"name" => array(
"first_name" => "$nome",
"formatted_name" => "$nome"
),
"phones" => array(
array(
"phone" => "+$contato",
"type" => "CELL",
"wa_id" => "$contato"
)
)
)
)
);
$this->requestType("POST");
$this->setMetodo('messages');
return $this->exec();
}
return false;
}
function enviarLocalizacao($whatsapp, $longitude, $latitude, $nome = null, $endereco = null)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"to" => "+$whatsapp",
"type" => "location",
"location" => array(
"longitude" => "$longitude",
"latitude" => "$latitude",
"name" => "$nome",
"address" => utf8_encode("$endereco")
)
);
$this->requestType("POST");
$this->setMetodo('messages');
return $this->exec();
}
return false;
}
function baixarMidia()
{
if (in_array($this->getType(), ['location', 'contacts', 'text'])) {
return true;
}
$name = $this->getId();
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->requestType("GET");
$this->setMetodo('media/' . $name);
$pathfile = $this->storage . $name;
$retorno = $this->exec();
file_put_contents($pathfile, $retorno);
if (file_exists($pathfile)) {
return true;
}
}
return false;
}
function ConvertWavToMp3($fileOrig)
{
try {
// ffmpeg -i 61f1a021ca8908.72216404_1643308267776 61f1a021ca8908.72216404_1643308267776
$cmd = "ffmpeg -y -i $fileOrig $fileOrig.mp3";
exec($cmd);
copy($fileOrig . ".mp3", $fileOrig);
} catch (\Exception $th) {
//throw $th;
}
}
function setStorage($storage)
{
$this->storage = $storage;
}
/**
* Profile WhatsApp
* @return string
*/
public function getProfile()
{
return $this->hook['contacts'][0]['profile']['name'];
}
/**
* Phone WhatsApp
* @return string
*/
public function getPhone()
{
return $this->hook['contacts'][0]['wa_id'];
}
/**
* Returns the type of the message
* @return string|boolean
*/
public function getType()
{
if ($this->hook) {
return $this->hook['messages'][0]['type'];
}
return false;
}
/**
* Returns the mime of the message
* @return string|boolean
*/
public function getMimetype()
{
if ($this->hook['messages'][0][$this->getType()]['mime_type']) {
return $this->hook['messages'][0][$this->getType()]['mime_type'];
}
return false;
}
/**
* Returns the id of the message
* @return string|boolean
*/
public function getId()
{
if ($this->hook && $this->getType()) {
if ($this->getType() == 'text') {
return $this->hook['messages'][0]['id'];
}
return $this->hook['messages'][0][$this->getType()]['id'];
}
return false;
}
/**
* Returns the (text, body) of the message
* @return string|boolean
*/
public function getIsValidMessage()
{
return $this->hook['contacts'];
}
/**
* Returns the (text, body) of the message
* @return string|boolean
*/
public function getMessage()
{
if ($this->hook['messages'][0]['interactive']) {
if ($this->hook['messages'][0]['interactive']['list_reply']) {
$id = $this->hook['messages'][0]['interactive']['list_reply']['id'];
if (strpos($id, 'P') === 0) {
return $this->hook['messages'][0]['interactive']['list_reply']['description'];
}
return $this->hook['messages'][0]['interactive']['list_reply']['title'];
} else {
return $this->hook['messages'][0]['interactive']['button_reply']['title'];
}
}
$message = $this->hook['messages'][0]['text']['body'];
return ($message ? $message : false);
}
/**
* Returns the name of the contact
* @return string|boolean
*/
public function getContactFormatted()
{
$formatted = $this->hook['messages'][0]['contacts'][0]['name']['formatted_name'];
if ($formatted) {
return $formatted;
}
return false;
}
/**
* Returns the phone of the contact
* @return string|boolean
*/
public function getContactPhone()
{
$contact = $this->hook['messages'][0]['contacts'][0]['phones'][0]['wa_id'];
if ($contact) {
return $contact;
}
return false;
}
/**
* Returns the latitude|longitude of the location
* @return string|boolean
*/
public function getGeolocation($type)
{
$geolocation = $this->hook['messages'][0]['location'][strtolower($type)];
if ($geolocation) {
return $geolocation;
}
return false;
}
function setHook($hook)
{
$this->hook = $hook;
}
function setMetodo($metodo)
{
$this->metodo = $metodo;
}
/**
* Escreve a query para ser passada para o curl
*
* @param string $query
*/
function setQuery($query)
{
return $this->query .= $query;
}
/**
* retorna a string pronta da query do curl e limpa a variavel.
*
* @return string $query
*/
function getQuery()
{
$query = $this->query;
unset($this->query);
return $query;
}
/**
* Verifica se todos os parametros passados foram completados.
*
* @param array $args
* @return true|false
*/
function getArgs($args)
{
foreach ($args as $value) {
if (!$value) {
return false;
}
}
return true;
}
/**
* Recebe o tipo de Requisi<EFBFBD><EFBFBD>o GET/POST
*
* @return boolean
*/
function requestType($req = null)
{
if (!$req) {
return $this->requestType;
}
if (strtoupper($req) == "GET") {
return $this->requestType = "GET";
} else if (strtoupper($req) == "POST") {
return $this->requestType = "POST";
}
}
function exec()
{
$this->setQuery(json_encode($this->params)); //SET QUERY
$this->request->setUrl($this->url . $this->metodo, false);
$header = array();
$header[] = "Authorization: Bearer {$this->token}";
if ($this->requestType == 'POST') {
$header[] = 'Content-Type: application/json';
$this->request->post_field($this->getQuery(), true);
}
// logger('core')->debug('header: ' . var_export($header, true), debug_backtrace());
// logger('core')->debug('body: ' . var_export($this->params, true), debug_backtrace());
$this->request->header($header);
$this->request->method_request($this->requestType);
return $this->request->exec_request();
//return $this->response($response);
}
function response($result)
{
if ($result) {
if (json_decode($result, true) !== null) {
return json_decode($result, true);
}
return $result;
} else {
return false;
}
}
/**
* Create file and download in browser
*/
public function getLinkDownload($host)
{
return $host . "whatsapp/download/{$this->getId()}/{$this->getMimetype()}";
}
public function retornaTituloDocument()
{
if ($this->hook['messages'][0]['document']) {
return $this->hook['messages'][0]['document']['filename'];
}
return null;
}
}