File: /var/www/vhost/disk-apps/demo.sports-crowd.com/app/Http/Controllers/LiveScoreApiController.php
<?php
namespace App\Http\Controllers;
use App\LiveScoreCache;
use App\Parameter;
use Illuminate\Http\Request;
use GuzzleHttp;
class LiveScoreApiController extends Controller
{
private $BASE_URL = "https://livescore-api.com/api-client/";
private $api_key;
private $api_secret;
private $client;
private $isActive = false;
private $team_id;
private $team_name;
private $arrayEvents = [
"GOAL" => "⚽ @time' - Gol de @player",
"GOAL_TEAM" => "⚽ @time' - Gol @type para @team",
"GOAL_PENALTY" => "⚽ @time' - @player ha marcado un gol de penalti",
"MISSED_PENALTY" => "⚽ @time' - @player ha fallado un gol de penalti",
"OWN_GOAL" => "⚽ @time' Autogol de @player",
"YELLOW_CARD" => "🟨 @time' para @player",
"RED_CARD" => "🟥 @time' para @player",
"YELLOW_RED_CARD" => "🟨+🟨=🟥 @time' para @player",
"SUBSTITUTION" => "🔄 @time' cambio, ingresa @player y sale @playerOut",
"START_TIME" => "⏰ ¡Inicio Partido!",
"SECOND_TIME" => "⏰ ¡Inicio segundo tiempo!",
"HALFTIME" => "⌛ ¡Entretiempo!",
"FULL_TIME" => "🚩 ¡Fin Partido!",
];
public function __construct()
{
$this->client = new GuzzleHttp\Client();
$this->api_key = config("livescore.api_key");
$this->api_secret = config("livescore.api_secret");
// Validar si esta activo el desarrollo.
$p = Parameter::select('id', 'live_score_active', 'live_score_team_id', 'live_score_team_name')->first();
$this->isActive = $p->live_score_active;
$this->team_id = $p->live_score_team_id;
$this->team_name = $p->live_score_team_name;
}
public function getCountries()
{
$response = $this->client->get($this->BASE_URL . "countries/list.json?key=" . $this->api_key . "&secret=" . $this->api_secret . "&size=100");
$body = $response->getBody()->getContents();
return ($body);
}
public function getTeams($country_id)
{
$response = $this->client->get($this->BASE_URL . "teams/list.json?key=" . $this->api_key . "&secret=" . $this->api_secret . "&country_id=" . $country_id . "&size=100");
$body = $response->getBody()->getContents();
return ($body);
}
public function getFixturesByTeam($team_id)
{
$response = $this->client->get($this->BASE_URL . "fixtures/matches.json?key=" . $this->api_key . "&secret=" . $this->api_secret . "&team_id=" . $team_id);
$body = $response->getBody()->getContents();
return json_decode($body);
}
public function getLiveScore()
{
if (!$this->isActive) {
return;
}
$team_id = $this->team_id;
$response = $this->client->get($this->BASE_URL . "scores/live.json?key=" . $this->api_key . "&secret=" . $this->api_secret . "&team_id=" . $team_id);
$body = $response->getBody()->getContents();
$this->isNewEventAtMatch(json_decode($body));
}
public function isNewEventAtMatch($liveScoreEvents)
{
if (empty($liveScoreEvents->data->match)) {
$out = new \Symfony\Component\Console\Output\ConsoleOutput();
$out->writeln("No hay eventos");
return;
}
$response = $this->client->get($this->BASE_URL . "scores/events.json?key=" . $this->api_key . "&secret=" . $this->api_secret . "&id=" . $liveScoreEvents->data->match[0]->id);
$body = $response->getBody()->getContents();
$bodyJson = json_decode($body);
$score = $bodyJson->data->match->home_name . ' ' . $bodyJson->data->match->score . ' ' . $bodyJson->data->match->away_name;
$compareTo = LiveScoreCache::where("event_id", $bodyJson->data->match->id)->first();
$notifyGoal = false;
$type = '';
$team = '';
if ($compareTo) {
if ($compareTo->status == 'FINISHED')
return;
$compareToJson = json_decode($compareTo->json_events);
if ($compareToJson && $compareToJson->data->match->score != $bodyJson->data->match->score) {
$notifyGoal = true;
$previousResults = explode(' - ', $compareToJson->data->match->score);
$newResults = explode(' - ', $bodyJson->data->match->score);
if ($previousResults[0] > $newResults[0]) {
$type = 'anulado';
$team = $bodyJson->data->match->home_name;
} else if ($previousResults[0] < $newResults[0]) {
$type = 'anotado';
$team = $bodyJson->data->match->home_name;
} else if ($previousResults[1] > $newResults[1]) {
$type = 'anulado';
$team = $bodyJson->data->match->away_name;
} else if ($previousResults[1] < $newResults[1]) {
$type = 'anotado';
$team = $bodyJson->data->match->away_name;
}
}
}
// Notificación eventos de tiempo del partido (inicio, entretiempo y final)
$time = intval($bodyJson->data->match->time);
$status = $bodyJson->data->match->status;
if (in_array($time, [1, 45, 46]) || $status == 'FINISHED') {
if ($time == 1 && $status == 'IN PLAY' && !$compareTo) {
$score = 'Siga al ' . $bodyJson->data->match->home_name . ' contra ' . $bodyJson->data->match->away_name;
$this->sendMassiveNotification($this->arrayEvents["START_TIME"], $score);
$this->saveLiveScore($compareTo, $bodyJson, $body);
return;
} else if ($time == 45 && intval($compareToJson->data->match->time) != 45) {
$this->sendMassiveNotification($this->arrayEvents["HALFTIME"], $score);
$this->saveLiveScore($compareTo, $bodyJson, $body);
return;
} else if ($time == 46 && $status == 'IN PLAY') {
$this->sendMassiveNotification($this->arrayEvents["SECOND_TIME"], $score);
$this->saveLiveScore($compareTo, $bodyJson, $body);
return;
} else if ($status == 'FINISHED') {
$this->sendMassiveNotification($this->arrayEvents["FULL_TIME"], $score);
$this->saveLiveScore($compareTo, $bodyJson, $body);
return;
}
}
// Si no existe en cache, o si la cantidad de eventos varia, se debe notificar el nuevo evento ( por defecto es el último )
if (!$compareTo || (sizeof($compareToJson->data->event) != sizeof($bodyJson->data->event))) {
$lastEvent = end($bodyJson->data->event);
if (!$lastEvent || $lastEvent->time < $time) {
if ($notifyGoal) {
$this->sendMassiveNotification(strtr($this->arrayEvents["GOAL_TEAM"], ["@type" => $type, "@team" => $team, "@time" => $time]), $score);
$this->saveLiveScore($compareTo, $bodyJson, $body);
return;
}
$out = new \Symfony\Component\Console\Output\ConsoleOutput();
$out->writeln("No hay ningún evento en el partido hasta el momento...");
return;
}
// Se valida evento sin jugador lanzado al final del partido 17/ago/22, venía sin jugador y no existía el evento realmente.
if (!$lastEvent->player || !$lastEvent->time) {
$out = new \Symfony\Component\Console\Output\ConsoleOutput();
$out->writeln("Evento invalido...");
return;
}
// Se dejan separados por si se requiere manejar una logica aislada por caso
switch ($lastEvent->event) {
case 'GOAL':
$this->sendMassiveNotification(strtr($this->arrayEvents[$lastEvent->event], ["@player" => $lastEvent->player, "@time" => $lastEvent->time]), $score);
break;
case 'OWN_GOAL':
$this->sendMassiveNotification(strtr($this->arrayEvents[$lastEvent->event], ["@player" => $lastEvent->player, "@time" => $lastEvent->time]), $score);
break;
case 'GOAL_PENALTY':
$this->sendMassiveNotification(strtr($this->arrayEvents[$lastEvent->event], ["@player" => $lastEvent->player, "@time" => $lastEvent->time]), $score);
break;
/*
case 'YELLOW_CARD':
$this->sendMassiveNotification(strtr($this->arrayEvents[$lastEvent->event], ["@player" => $lastEvent->player, "@time" => $lastEvent->time]));
break;
case 'RED_CARD':
$this->sendMassiveNotification(strtr($this->arrayEvents[$lastEvent->event], ["@player" => $lastEvent->player, "@time" => $lastEvent->time]));
break;
case 'YELLOW_RED_CARD':
$this->sendMassiveNotification(strtr($this->arrayEvents[$lastEvent->event], ["@player" => $lastEvent->player, "@time" => $lastEvent->time]));
break;
case 'SUBSTITUTION':
$this->sendMassiveNotification(strtr($this->arrayEvents[$lastEvent->event], ["@player" => $lastEvent->player, "@time" => $lastEvent->time, "@playerOut" => $lastEvent->info]));
break;
*/
default:
$out = new \Symfony\Component\Console\Output\ConsoleOutput();
$out->writeln("No hay evento nuevo");
break;
}
$this->saveLiveScore($compareTo, $bodyJson, $body);
return;
} else {
if ($notifyGoal) {
$this->sendMassiveNotification(strtr($this->arrayEvents["GOAL_TEAM"], ["@type" => $type, "@team" => $team, "@time" => $time]), $score);
$this->saveLiveScore($compareTo, $bodyJson, $body);
return;
}
$out = new \Symfony\Component\Console\Output\ConsoleOutput();
$out->writeln("No hay evento nuevo");
}
}
public function saveLiveScore($compareTo, $bodyJson, $body)
{
// Si no existe la instancia se crea.
if (!$compareTo) {
$compareTo = new LiveScoreCache;
}
// Actualizar el ultimo evento.
$compareTo->event_id = $bodyJson->data->match->id;
$compareTo->json_events = $body;
$compareTo->status = $bodyJson->data->match->status;
$compareTo->save();
}
public function saveParametersLiveScore(Request $request)
{
$p = Parameter::first();
$p->live_score_active = false;
$p->live_score_team_name = $request->team_name;
$p->live_score_team_id = $request->team_id;
$p->save();
return array('status' => true, 'm' => 'Se ha actualizado correctamente');
}
public function sendMassiveNotification($event, $score = null)
{
$push = new PushNotificationController();
// Andres
// $push->sendToUser($event, "df9bb2aa-820c-11ec-938a-7248d0b51fa3", null, null, null, null, 'U');
// Francisco
// $push->sendToUser($event, "bf0bf992-82d8-11ec-8f51-9ebf1ea4cac0", null, null, null, null, 'U');
// Johan
// $push->sendToUser($event, "fd10ef58-9044-48c2-a179-25776d0ff6cd", null, null, null, null, 'U');
// Mauro Android
// $push->sendToUser($score, "60d5cae6-b033-11ec-ac5d-5efc774e9655", null, null, null, null, 'U', $event);
// Mauro iOS DIM
// $push->sendToUser($score, "f3e45391-2c05-46e2-a53f-6764a0258de3", null, null, null, null, 'U', $event);
// Mauro iOS ENVIGADO
// $push->sendToUser($score, "dcb15ac5-1d86-45ea-9d79-285bc6b3e9be", null, null, null, null, 'U', $event);
// Envio masivo por One Signal.
$push->sendToAll($score, null, null, null, null, 'U', $event);
// Envio por consola tinker
$out = new \Symfony\Component\Console\Output\ConsoleOutput();
$out->writeln("Evento: " . $event);
}
}