<?php
namespace App\Controller\WS;
use App\Websocket\PusherManager;
use Symfony\Component\Process\Process;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use App\Util\WS\Util;
use App\Util\NewUtil;
use App\Util\Util as Utilx;
use App\Util\UUIDGeneratorUtil;
use App\Util\WS\ForcedAsynchronousCommandsUtil;
use stdClass;
use App\Structure\Usuario;
use App\Structure\RegistActions;
use App\Entity\User;
use App\Entity\PushSent;
use App\Entity\GiftCard;
use App\Entity\MasterSync;
use App\Entity\WebService;
use App\Entity\ReadFilesData;
use App\Entity\AccountLicense;
use App\Entity\ReadFilesDataWeb;
use App\Entity\SyncReportedError;
use App\Entity\LogAndroidEmailSent;
use App\Entity\GiftCardTransaction;
use App\Entity\ThirdPartyAPIRecords;
use App\Entity\AndroidErrorsHistory;
use App\Entity\SyncAllCallStatus;
use App\Entity\ErrorAndroidEmailSent;
use App\Entity\NotificationInLicensorBell;
use App\Transformer\SyncWebTransformer;
use App\Transformer\DemoForLoginTransformer;
use App\Transformer\SublicensesListTransformer;
use App\Transformer\LicensorGenericTransformer;
use App\Transformer\UpdateAndroidCommandTransformer;
use App\Transformer\UploadSyncJsonNotifyTransformer;
use App\Transformer\UpdateMobileInsertJsonTransformer;
use App\Transformer\RespondedNotificationPushTransformer;
use App\Controller\Application\Service\ArmorService;
use App\Controller\Application\Service\Log\Log;
use App\Controller\Application\Service\Util\Encryptor;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use DateTime;
use App\SynchronizationUtil\SyncWebUtil;
use Exception;
use App\Command\Websocket\SyncAllWebsocketVersionCommand;
use App\Consumer\WS\SyncFullCallConsumer;
use App\Entity\ActionHistory;
use App\Util\UtilSync;
/**
* Description of ReadFilesDataController
* @author
*/
class ReadFilesDataController extends ApiController {
/**
* Esta funcion permite validar el acceso a la aplicacion web de level
* validando codigo de usuario y contraseña y generando el apiKey
* necesario para toda la aplicacion movil
* @author Aealan Z <lrobledo@kijho.com> 08/10/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function loginMobil(Request $request) {
if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
if (!(0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT))) {
return $this->errorWrongArgs('Wrong Content.', WebService::CODE_WRONG_ARGUMENTS);
}
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'InitialAndroidLoginWS', 'InitialAndroidLoginWS0.txt');
$this->createFileJson($path, "\r" . 'Login Mobile: ' . $request->getContent() . "\r");
try {
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['alLicenseUsername']) || !isset($data['password']) || !isset($data['username']) || !isset($data['uid'])) {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$licenseUserName = ['alLicenseUsername' => $data['alLicenseUsername']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
$countResult = count($accountLicenseData);
if ($countResult <= 0) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Inactive Account', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Inactive License', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_PENDING) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Pending License', WebService::CODE_ACCOUNT_SUSPENDED);
}
$oldUID = $accountLicenseData[0]->getDeviceUid();
$oldLoguedDeviceKind = $accountLicenseData[0]->getLastloguedDeviceKind();
$alreadyUsingLastVersion = false;
$deviceUIDWasSetted = false;
$arrayGoodWayUpdate = [];
$arrayWrongWayUpdate = [];
$theVersionArrayForOldUsers = [];
$accountLicenseData[0]->setHasAndroid(true);
$country = $accountLicenseData[0]->getCity()->getCiState()->getStCountry()->getCoVal();
$isCallCenter = $accountLicenseData[0]->getIsCallCenter();
$language = Util::getLanguageCodeByCountryCode($country);
$theRespArray['language'] = $language;
$pathXD = $this->realContainer->getParameter('level_directory_logs') . 'ip_man.json';
$this->createFileJson($pathXD, $this->realContainer->get('request_stack')->getCurrentRequest()->getClientIp() . ' -> ' . $data['alLicenseUsername'] . ' |L| ');
if (isset($data['isLiteDevice'])) {
$accountLicenseByUID = $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $data['uid']]);
if (empty($accountLicenseByUID) && $accountLicenseData[0]->getLastloguedDeviceKind() == AccountLicense::DEVICE_LITE_TYPE) {
$deviceUIDWasSetted = true;
$accountLicenseData[0]->setHasAndroid(true);
$accountLicenseData[0]->setDeviceUid($data['uid']);
} else {
// dump('Hola chingo!');
$accountLicenseData[0]->setHasAndroid(true);
if (!($accountLicenseData[0]->getDeviceUid() && $accountLicenseData[0]->getLastloguedDeviceKind() != AccountLicense::DEVICE_LITE_TYPE)) {
// dump('Jumm!');
if (isset($accountLicenseByUID[0]) && isset($accountLicenseData[0]) && ($accountLicenseData[0]->getId() == $accountLicenseByUID[0]->getId()) && $accountLicenseByUID[0]->getLastloguedDeviceKind() == AccountLicense::DEVICE_LITE_TYPE) {
// dump('Jumm x2!');
$accountLicenseByUID[0]->setDeviceUid(null);
$accountLicenseByUID[0]->setWsResourceIdVerifiedAfterLogin(0);
$em->persist($accountLicenseByUID[0]);
$em->flush();
$accountLicenseData[0]->setDeviceUid($data['uid']);
} elseif (isset($accountLicenseByUID[0]) && (!$accountLicenseData[0]->getDeviceUid() || $accountLicenseData[0]->getDeviceUid() == '')) {
$auxLicenseFoundCounter = 1;
$auxLicenseUID = $accountLicenseByUID[0]->getDeviceUid() . '_aux_lite_' . $accountLicenseByUID[0]->getAlLicenseUsername() . '_' . $auxLicenseFoundCounter;
$deviceSplitAux = explode("_aux_lite_", $auxLicenseUID);
do {
$auxLicenseUID = $deviceSplitAux[0] . '_aux_lite_' . $accountLicenseByUID[0]->getAlLicenseUsername() . '_' . $auxLicenseFoundCounter;
$accountLicenseByUID = $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $auxLicenseUID]);
++$auxLicenseFoundCounter;
} while (isset($accountLicenseByUID[0]));
$accountLicenseData[0]->setDeviceUid($auxLicenseUID);
$accountLicenseData[0]->setHasAndroid(true);
} else if (!isset($accountLicenseByUID[0]) && (!$accountLicenseData[0]->getDeviceUid() || $accountLicenseData[0]->getDeviceUid() == '')) {
$accountLicenseData[0]->setDeviceUid($data['uid']);
$accountLicenseData[0]->setHasAndroid(true);
}
$accountLicenseData[0]->setLastloguedDeviceKind(AccountLicense::DEVICE_LITE_TYPE);
}
}
// dump('Casillo!?');
// die;
$em->persist($accountLicenseData[0]);
$em->flush();
} else {
// dump(isset($data['uid']), $data['uid']);
// dump($accountLicenseData[0]->getDeviceUid() == '');
// dump(null == $accountLicenseData[0]->getDeviceUid());
// die;
if (isset($data['uid']) && ($accountLicenseData[0]->getDeviceUid() == '' || null == $accountLicenseData[0]->getDeviceUid())) {
$accountLicenseByUID = $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $data['uid']]);
// dump($accountLicenseByUID);
if (!empty($accountLicenseByUID)) {
$alreadyWithTheSameUIDLicense = $accountLicenseByUID[0];
if ($accountLicenseData[0]->getAlLicenseUsername() != $accountLicenseByUID[0]->getAlLicenseUsername() && $accountLicenseByUID[0]->getLastloguedDeviceKind() != AccountLicense::DEVICE_LITE_TYPE) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError("Device UID '" . $data['uid'] . "' already registed with '" . $accountLicenseByUID[0] . "' license using a non lite app", WebService::CODE_COULD_NOT_AUTHENTICATE);
} elseif ($accountLicenseData[0]->getAlLicenseUsername() != $accountLicenseByUID[0]->getAlLicenseUsername()) {
$auxLicenseFoundCounter = 1;
$auxLicenseUID = $accountLicenseByUID[0]->getDeviceUid() . '_aux_lite_' . $accountLicenseByUID[0]->getAlLicenseUsername() . '_' . $auxLicenseFoundCounter;
$deviceSplitAux = explode("_aux_lite_", $auxLicenseUID);
do {
$auxLicenseUID = $deviceSplitAux[0] . '_aux_lite_' . $accountLicenseByUID[0]->getAlLicenseUsername() . '_' . $auxLicenseFoundCounter;
$accountLicenseByUID = $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $auxLicenseUID]);
++$auxLicenseFoundCounter;
} while (isset($accountLicenseByUID[0]));
$alreadyWithTheSameUIDLicense->setDeviceUid($auxLicenseUID);
$alreadyWithTheSameUIDLicense->setHasAndroid(true);
$em->persist($alreadyWithTheSameUIDLicense);
$em->flush();
$auxLevEm = Util::emLicenseConnection($this->realContainer, $em, $alreadyWithTheSameUIDLicense);
$configuracionForAll = $auxLevEm->getRepository('App\Structure\Configuracion')->findAll();
if (!empty($configuracionForAll)) {
$configuracion = $configuracionForAll[0];
}
if ($configuracion) {
$configuracion->setConfHasAndriod(true);
$configuracion->setConfDeviceUid($alreadyWithTheSameUIDLicense->getDeviceUid());
$this->createFileJson($path, "\r" . '1 SETEO DE LEVEL UUID CONFIG: ' . $alreadyWithTheSameUIDLicense->getDeviceUid() . ' HAS ANDROID : TRUE' . "\r");
$auxLevEm->persist($configuracion);
$auxLevEm->flush();
$auxLevEm->close();
}
}
}
$deviceUIDWasSetted = true;
$accountLicenseData[0]->setHasAndroid(true);
$accountLicenseData[0]->setDeviceUid($data['uid']);
} else {
if (isset($data['uid']) && $accountLicenseData[0]->getDeviceUid() != $data['uid'] && $accountLicenseData[0]->getLastloguedDeviceKind() != AccountLicense::DEVICE_LITE_TYPE) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError("There is another server device with the UID '" . $accountLicenseData[0]->getDeviceUid() . "' registered with this license", WebService::CODE_INVALID_UID);
} else {
$accountLicenseByUID = $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $data['uid']]);
if (!empty($accountLicenseByUID)) {
if ($accountLicenseData[0]->getAlLicenseUsername() != $accountLicenseByUID[0]->getAlLicenseUsername() && ($accountLicenseData[0]->getLastloguedDeviceKind() != AccountLicense::DEVICE_LITE_TYPE || $accountLicenseByUID[0]->getLastloguedDeviceKind() != AccountLicense::DEVICE_LITE_TYPE)) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError("Device UID '" . $data['uid'] . "' already registed with '" . $accountLicenseByUID[0] . "' license", WebService::CODE_COULD_NOT_AUTHENTICATE);
} else {
$accountLicenseByUID[0]->setDeviceUid(null);
$accountLicenseByUID[0]->setHasAndroid(null);
$accountLicenseByUID[0]->setWsResourceIdVerifiedAfterLogin(0);
$em->persist($accountLicenseByUID[0]);
$em->flush();
}
}
$deviceUIDWasSetted = true;
$accountLicenseData[0]->setHasAndroid(true);
$accountLicenseData[0]->setDeviceUid($data['uid']);
}
}
$accountLicenseData[0]->setLastloguedDeviceKind(AccountLicense::DEVICE_ANDROID_TYPE);
}
$liteUsername = '';
$responseArrOmt = [];
/**
* Allows to add the apikey to the user of lite level this exported in OMT
*/
if ($accountLicenseData[0]->getHasLogedOMT() == true || $accountLicenseData[0]->getIsLevelLight() == true || (isset($data['isLiteDevice']) && $data['isLiteDevice']) ) {
$this->createFileJson($path, 'Util::doOMTDashboardLoginToGetToken 1!' . "\r");
$levelLiteUser = $accountLicenseData[0]->getLevelLightUser();
// $apikey = Util::doOMTDashboardLoginToGetToken($this->realContainer, $levelLiteUser, $path, $accountLicenseData[0]->getLoginType());
if (!empty($apikey)) {
$levelLiteUser['apikey'] = $apikey;
$responseArrOmt['userToOmt']['apikey'] = $apikey;
}
if (!empty($apikey)) {
$levelLiteUser['apikey'] = $apikey;
$accountLicenseData[0]->setLevelLightUser($levelLiteUser);
}
$liteUsername = $levelLiteUser['username'];
$responseArrOmt['userToOmt']['username'] = $liteUsername;
$responseArrOmt['userToOmt']['password'] = $levelLiteUser['realPass'];
}
if (isset($data['version'])) {
$data['version'] = trim($data['version']);
}
if (isset($data['version']) && !isset($data['isLiteDevice'])) {
if (strpos($data['version'], '-')) {
$this->createFileJson($path, 'Is a testing version...? ' . $data['version'] . "\r");
$data['version'] = explode('-', $data['version'])[0];
}
if (!preg_match('/^(\d+\.)(\d+\.)(\d+)$/', $data['version'])) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid version format', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$accountLicenseData[0]->setAndroidVersionName($data['version']);
$accountLicenseData[0]->setVersionUpdatedDate(Util::getCurrentDate());
$theRespArray = Util::getLastVersionByDirNow($this->realContainer, false, $path);
$theRespArray['bigbag'] = true;
$theRespArray['language'] = $language;
if (isset($theRespArray['updateAppError']) && $theRespArray['updateAppError']) {
return $this->setStatusCode(WebService::HTTP_CODE_SERVICE_UNAVAILABLE)
->respondWithError('Error finding last version', WebService::CODE_OBJECT_NOT_FOUND);
}
if (isset($theRespArray['newVersion'])) {
$newVersionString = Util::validateNewerVersion($data['version'], $theRespArray['newVersion']);
if ($newVersionString != $data['version']) {
$theRespArray['success'] = WebService::CODE_SUCCESS;
$theRespArray['country'] = $country;
$theRespArray['iscallcenter'] = (int) $isCallCenter;
$theUrlTrSt = new UpdateAndroidCommandTransformer($this->realContainer, $theRespArray);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
$arrayWrongWayUpdate['case'] = 'Android client is already updated!';
$alreadyUsingLastVersion = true;
}
} else {
$arrayWrongWayUpdate['case'] = 'Android client is already updated!';
$alreadyUsingLastVersion = true;
}
} elseif (!isset($data['isLiteDevice'])) {
$userOldVersion = $accountLicenseData[0]->getAndroidVersionName();
if (null != $userOldVersion && $userOldVersion != '') {
$theVersionArrayForOldUsers = Util::getLastVersionByDirAvailableVersions($this->realContainer, $userOldVersion, true, $path);
} else {
$theVersionArrayForOldUsers = Util::getLastVersionByDirAvailableVersions($this->realContainer, '1.0.0', true, $path);
}
if (isset($theVersionArrayForOldUsers['updateAppIsNeeded']) && $theVersionArrayForOldUsers['updateAppIsNeeded'] === true) {
$arrayGoodWayUpdate['apkurl'] = $theVersionArrayForOldUsers['updateRequestApk'];
$arrayGoodWayUpdate['lastversion'] = $theVersionArrayForOldUsers['newVersion'];
} else {
$arrayGoodWayUpdate['apkurl'] = '';
$arrayGoodWayUpdate['lastversion'] = '';
}
}
$unsetDownUrl = false;
$em->persist($accountLicenseData[0]);
$em->flush();
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
// Verifica si es un usuario de leveLite y si este pertenece a la licencia a la cual se esta accediendo
if(isset($levelLiteUser) && isset($levelLiteUser["username"]) && isset($data['isLiteDevice']) ){
if (strtolower($data['username']) === strtolower($levelLiteUser["username"]) && $data['isLiteDevice'] == '1'){
// Limpia lista de usuarios levelLite
// Revisar se estalla al borrar usuarios
// $emLev->getRepository('App\Structure\Usuario')->cleanWrongUsers($levelLiteUser["username"]);
}
}
$configuracionForAll = $emLev->getRepository('App\Structure\Configuracion')->findAll();
if (!empty($configuracionForAll)) {
$configuracion = $configuracionForAll[0];
}
if (($configuracion && $deviceUIDWasSetted) || !$configuracion->getConfDeviceUid() || $configuracion->getConfDeviceUid() == '' || $configuracion->getConfDeviceUid() == "") {
$configuracion->setConfHasAndriod(true);
$configuracion->setConfDeviceUid($data['uid']);
$this->createFileJson($path, "\r" . '2 SETEO DE LEVEL UUID IN CONFIG: ' . $data['uid'] . ' HAS ANDROID : TRUE' . "\r");
$emLev->persist($configuracion);
$emLev->flush();
$maxUIDPollingCounter = 0;
do {
++$maxUIDPollingCounter;
$configuracionForAll = $emLev->getRepository('App\Structure\Configuracion')->findAll();
if (!empty($configuracionForAll)) {
$configuracion = $configuracionForAll[0];
} else {
return $this->setStatusCode(WebService::HTTP_CODE_SERVICE_UNAVAILABLE)
->respondWithError('Error finding configuration LEVEL database record', WebService::CODE_OBJECT_NOT_FOUND);
}
$configuracion->setConfHasAndriod(true);
$configuracion->setConfDeviceUid($data['uid']);
$emLev->persist($configuracion);
$emLev->flush();
$emLev->clear();
sleep(1);
$configuracionForAllCheck = $emLev->getRepository('App\Structure\Configuracion')->findBy(['confDeviceUid' => $data['uid']]);
} while (!isset($configuracionForAllCheck[0]) && $maxUIDPollingCounter < 7);
$this->createFileJson($path, "\r" . '2 SETEO DE LEVEL UUID IN CONFIG CHECKEADO Y FULL PARA: ' . $data['uid'] . ' HAS ANDROID : TRUE' . "\r");
}
$cliente = $emLev->getRepository('App\Structure\Usuario')->validateUser($data);
$emLev->clear();
$emLev->close();
// dump($data);
// dump($cliente);
// die;
if (!empty($cliente)) {
if (isset($data['isLiteDevice']) && strtolower($data['username']) != $liteUsername) {
$this->createFileJson($path, "Error: Invalid username for LEVELLite");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid username for LEVELLite', WebService::CODE_UNAUTHORIZED);
}
if (strtolower($data['username']) != 'admin') {
$isDirectoryReady = Util::createLicenseDirectory($this->realContainer, $accountLicenseData[0], $data['alLicenseUsername']);
$theAccountLicenseDirector = $isDirectoryReady['directory'];
if (!isset($isDirectoryReady['result']) || $isDirectoryReady['result'] == '__KO__') {
$msnError = 'An error occurred while creating your directory in server ';
$this->createFileJson($path, $msnError);
return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
->respondWithError($msnError, WebService::CODE_INTERNAL_ERROR);
}
$em = $this->getDoctrine()->getManager();
$licenseDB = $em->getRepository("App\Entity\LicenseDataBase")->findBy(['license' => $accountLicenseData[0]->getId()]);
$splitedLogin = isset($data['splitedLogin']) ? $data['splitedLogin'] : 0;
if (!empty($licenseDB)) {
if (!isset($data['isLiteDevice'])) {
$useMetadataCacheInLogin = false;
if (isset($data['useMetadataCache'])) {
$useMetadataCacheInLogin = true;
}
if (isset($data['splitedLogin'])) {
$this->createFileJson($path, "Notice: pre fileJsonFromSelectEntities with 'splitedLogin' -> " . $data['splitedLogin']);
$auxResponseArray = Util::fileJsonFromSelectEntities($this->realContainer, $em, $theAccountLicenseDirector, $licenseDB[0], null, true, false, true, $data['splitedLogin'], $useMetadataCacheInLogin);
} else {
$this->createFileJson($path, "Notice: pre fileJsonFromSelectEntities ");
$auxResponseArray = Util::fileJsonFromSelectEntities($this->realContainer, $em, $theAccountLicenseDirector, $licenseDB[0], null, true, false, true, null, $useMetadataCacheInLogin);
}
$responseArr = $auxResponseArray[0];
$responseArr['bigbag'] = true;
$responseArr['language'] = $language;
$newSetWebRecordToSync = $auxResponseArray[1]['entity'];
if (isset($responseArrOmt) && isset($responseArrOmt['userToOmt'])) {
$responseArr['userToOmt'] = $responseArrOmt['userToOmt'];
}
$actualDate = Util::getCurrentDate();
$accountLicenseData[0]->setLastLoginWasOk(false);
$accountLicenseData[0]->setLastLoginDate($actualDate);
$newNotificationSeed = new NotificationInLicensorBell();
$newNotificationSeed->setDateCreated($actualDate);
$newNotificationSeed->setIterativeNotification(true);
$newNotificationSeed->setLicense($accountLicenseData[0]);
$newNotificationSeed->setTypeRoleToNotify(NotificationInLicensorBell::ROLE_LICENSE_MANAGER);
$newNotificationSeed->setContext(NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_LOGIN);
$em->persist($newNotificationSeed);
$em->persist($accountLicenseData[0]);
$em->flush();
if ($newSetWebRecordToSync) {
Util::updateWebSyncUploadResponseFile($em, $newSetWebRecordToSync);
} else {
$unsetDownUrl = true;
unset($data['splitedLogin']);
unset($responseArr['splitedLogin']);
Utilx::closeAllStuckedWebSync($em, $accountLicenseData[0]);
}
}
} else {
$this->createFileJson($path, "Error: No DB conection data found!");
return $this->setStatusCode(WebService::HTTP_CODE_SERVICE_UNAVAILABLE)
->respondWithError('No DB conection data found!', WebService::CODE_OBJECT_NOT_FOUND);
}
$userLite = $accountLicenseData[0]->getLevelLightUser();
// dump($responseArr, strtolower($data['username']), $userLite["username"]);die;
if (isset($responseArr['status']) && $responseArr['status']==200 && strtolower($data['username']) !== $userLite["username"]) {
if ($accountLicenseData[0]->getHasLogedOMT() && !isset($data['isLiteDevice'])) {
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
// Util::createSyncRecordsToOmtByUpdate($emLev, $accountLicenseData[0]);
$curlResponse = Util::makeOwnSyncWebCurl($this->realContainer, ['nickname' => $data['alLicenseUsername']], $path);
$data['rwid'] = $curlResponse;
ForcedAsynchronousCommandsUtil::consumeUpDownSyncCommand($this->realContainer, $data, true);
$emLev->clear();
$emLev->close();
}
$responseArr['urlBase'] = $this->realContainer->getParameter('level_directory_data_base_url') . $accountLicenseData[0]->getAlAccountLicense() . '/' . $data['alLicenseUsername'] . $responseArr['urlBase'];
$responseArr['urlBase'] = str_replace(' ', '_', $responseArr['urlBase']);
if (isset($arrayWrongWayUpdate['case'])) {
$responseArr['case'] = $arrayWrongWayUpdate['case'];
} else {
$responseArr['case'] = '';
}
if (!$alreadyUsingLastVersion && !isset($data['isLiteDevice'])) {
$theVersionArrayForOldUsers = Util::getLastVersionByDirNow($this->realContainer, true, $path);
if (isset($theVersionArrayForOldUsers['updateAppIsNeeded']) && $theVersionArrayForOldUsers['updateAppIsNeeded'] === true) {
$responseArr['apkurl'] = $theVersionArrayForOldUsers['updateRequestApk'];
$responseArr['lastversion'] = $theVersionArrayForOldUsers['newVersion'];
} else {
$responseArr['apkurl'] = '';
$responseArr['lastversion'] = '';
}
} else {
$responseArr['apkurl'] = '';
$responseArr['lastversion'] = '';
}
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
$clienteForWebAndroidLogin = $emLev->getRepository('App\Structure\Usuario')->findBy(['usuLogin' => 'admin']);
$emLev->clear();
$emLev->close();
$auxArrayUserAndroidWebLogin = [];
if (isset($clienteForWebAndroidLogin[0])) {
$auxArrayUserAndroidWebLogin['user'] = 'admin';
$auxArrayUserAndroidWebLogin['pass'] = $clienteForWebAndroidLogin[0]->getUsuPass();
}
$pushServicesKeysArray = Util::buildTheServicesKeysArray($this->realContainer, $accountLicenseData[0], $auxArrayUserAndroidWebLogin);
if ($accountLicenseData[0]->getAwsTopicARN() && $accountLicenseData[0]->getAwsTopicARN() != '' && $accountLicenseData[0]->getAwsTopicARN() != "" ) {
if (isset($pushServicesKeysArray['awsPush'])) {
$pushServicesKeysArray['awsPush']['TopicArn'] = $accountLicenseData[0]->getAwsTopicARN();
}
}
$responseArr['country'] = $country;
$responseArr['iscallcenter'] = (int) $isCallCenter;
$isSplitedAgain = false;
if (isset($data['splitedLogin'])) {
$responseArr['splitedLogin'] = $data['splitedLogin'];
$isSplitedAgain = true;
}
$responseArr['push_services'] = $pushServicesKeysArray;
// $responseArr['uploadurl'] = $this->generateUrl('level_web_service_respond_sync_web', [], UrlGeneratorInterface::ABSOLUTE_URL);
$responseArr['uploadurl'] = $this->realContainer->getParameter('level_scheme') . '://' . $this->realContainer->getParameter('level_host') . $this->generateUrl('level_web_service_respond_sync_web');
$responseArr['downloadurl'] = $this->realContainer->getParameter('level_directory_data_base_url') . $accountLicenseData[0]->getAlAccountLicense() . '/' . $data['alLicenseUsername'] . '/' . $auxResponseArray[1]['fileConfigName'];
$responseArr['downloadurl'] = str_replace(' ', '_', $responseArr['downloadurl']);
if (isset($auxResponseArray[1]['fileExpectedName'])) {
$responseArr['expected'] = $this->realContainer->getParameter('level_directory_data_base_url') . $accountLicenseData[0]->getAlAccountLicense() . '/' . $data['alLicenseUsername'] . '/' . $auxResponseArray[1]['fileExpectedName'];
$responseArr['expected'] = str_replace(' ', '_', $responseArr['expected']);
} else {
$responseArr['expected'] = '';
}
if ($accountLicenseData[0]->getLevelLightUser() && isset($data['isLiteDevice']) && $accountLicenseData[0]->getHasLogedOMT() == true) {
$this->createFileJson($path, 'Util::doOMTDashboardLoginToGetToken 2!' . "\r");
$userData = $accountLicenseData[0]->getLevelLightUser();
$apikey = Util::doOMTDashboardLoginToGetToken($this->realContainer, $userData, $path, $accountLicenseData[0]->getLoginType());
if (!empty($apikey)) {
$responseArr['userToOmt']['apikey'] = $apikey;
}
$responseArr['userToOmt']['username'] = $userData['username'];
$responseArr['userToOmt']['password'] = $userData['realPass'];
}
if ($unsetDownUrl) {
$responseArr['downloadurl'] = '';
}
$theUrlTrSt = new UpdateMobileInsertJsonTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_OUT) {
$accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_ANDROID);
} else if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_LITE) {
$accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_LITE_AND_ANDROID);
}
$em->persist($accountLicenseData[0]);
$em->flush();
if ($accountLicenseData[0]->getLevelLightUser() && isset($data['isLiteDevice'])) {
$this->createFileJson($path, 'Util::doOMTDashboardLoginToGetToken 3!' . "\r");
$userData = $accountLicenseData[0]->getLevelLightUser();
$apykey = Util::doOMTDashboardLoginToGetToken($this->realContainer, $userData, $path, $accountLicenseData[0]->getLoginType());
if (!empty($apykey)) {
$xxArray['userToOmt']['apykey'] = $apykey;
}
$xxArray['userToOmt']['username'] = $userData['username'];
if (isset($userData['password'])) {
$xxArray['userToOmt']['password'] = $userData['password'];
}
}
$jsonContent = json_encode($xxArray);
// $splitedLogin = json_decode($jsonContent)->splitedLogin ?? null;
// dump($splitedLogin);
// dump(Util::definitionInitialMultipartLogin(0, true));
// die;
if ($splitedLogin === (Util::definitionInitialMultipartLogin(0, true) - 1)) {
// dump("Holaa!");
// die;
$freeLicnesesToPairWithStations = $em->getRepository('App\Entity\LicenseDevice')->getLicenseDeviceServerRecordForInitialLogin($accountLicenseData[0]->getId());
$historyResponse = [];
$historyResponse["status"] = 200;
if (isset($freeLicnesesToPairWithStations[0])) {
$licenseSold = $freeLicnesesToPairWithStations[0];
$this->createFileJson($path, "Updating old license device record with '" . $licenseSold->getId() . "' id..." . "\r");
$licenseSold->setLdUpdateDate($actualDate);
$licenseSold->setLdStationUID($data['uid']);
$em->persist($licenseSold);
$em->flush();
$historyResponse["actions"] = "Server station updated by initial login";
Util::logAction(
$em, 'LicenseDevice',
$licenseSold->getId(), ActionHistory::ACTION_STATION_UPDATE, 'System', [
'data' => $historyResponse
]);
}
///// Limpiado de los otros dispositivos autorizados para el inicio de registro de estaciones de parte de una licencia
$this->createFileJson($path, "Limpiado de dispositivos para que se permita el registro de nuevas estaciones segun dispositivos autorizados en '" . $accountLicenseData[0] . "'" . "\r");
$em->getRepository('App\Entity\LicenseDevice')->clearLicenseDeviceNonServerRecordsForInitialLogin($accountLicenseData[0]->getId());
Util::logAction(
$em, 'AccountLicense',
$accountLicenseData[0]->getId(), ActionHistory::INITIAL_LOGIN, 'System', [
'data' => "Login completed successfully for license: " . $accountLicenseData[0]->getAlLicenseUsername()
]);
}
$this->createFileJson($pathXD, "splitedLogin => " . $splitedLogin . "\r");
$data['license'] = $accountLicenseData[0]->getId();
$data['isForSync'] = 1;
$data['unactiveActiveZipcodes'] = 1;
$data['validationByEdition'] = 0;
$pushSendRepository = $em->getRepository('App\Entity\PushSent');
$pushSendRepository->respondOldPushesForLicense(PushSent::PUSH_TYPE_LICENSE_RESET_UID, $accountLicenseData[0]->getId());
$this->createFileJson($pathXD, "Has Loged OMT" . ' => ' . $accountLicenseData[0]->getHasLogedOMT());
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
$configuracion = $emLev->getRepository('App\Structure\Configuracion')->findAll();
if (isset($configuracion[0])) {
$configuracion[0]->setConfDeviceUid($accountLicenseData[0]->getDeviceUid());
$emLev->persist($configuracion[0]);
$emLev->flush();
}
if ($accountLicenseData[0]->getHasLogedOMT()) {
$this->createFileJson($pathXD, "For call => makeSyncCleanseBecauseNewLogin");
Util::makeSyncCleanseBecauseNewLogin($this->realContainer, $em, $path, $accountLicenseData[0]);
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
// Util::createSyncRecordsToOmtByUpdate($emLev, $accountLicenseData[0]);
$emLev->clear();
$emLev->close();
Util::makeOwnSyncWebCurl($this->realContainer, ['nickname' => $data['alLicenseUsername']], $path);
}
if ($accountLicenseData[0]->getNeedZipcodes() && !$isSplitedAgain) {
ForcedAsynchronousCommandsUtil::validateZipcodesToSyncAfterLogin($this->realContainer, $data, true);
}
$this->createFileJson($path, 'Login response -> ' . $jsonContent . "\r");
$accountLicenseData[0]->setLastLoginDate(Util::getCurrentDate());
$isThisLicenseVersion = Util::validateNewerVersion($accountLicenseData[0]->getAndroidVersionName(), $this->realContainer->getParameter('default_break_android_with_pusher'));
if ($isThisLicenseVersion === $accountLicenseData[0]->getAndroidVersionName()) {
$newPusherTokenCallResult = NewUtil::generateNewPusherVerificationToken($this->realContainer, $em, $accountLicenseData[0], $path);
if (is_string($newPusherTokenCallResult)) {
$this->createFileJson($path, 'Error creating new pusher token -> ' . $newPusherTokenCallResult . "\r");
} else {
$this->createFileJson($path, 'New pusher token created!'. "\r");
}
}
if (!isset(json_decode($jsonContent)->splitedLogin)) {
$accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_ANDROID);
$accountLicenseData[0]->setHasAndroid(true);
}
// if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_OUT) {
// $accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_ANDROID);
// } else if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_LITE) {
// $accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_LITE_AND_ANDROID);
// }
$em->persist($accountLicenseData[0]);
$em->flush();
// Se valida que el parametro timeZone exista para guardarlo en las Tablas Configuracion y AccountLicense
if (isset($data['timeZone']) && trim($data['timeZone']) !== '') {
$timeZone = trim($data['timeZone']);
$configuracion = $emLev->getRepository('App\Structure\Configuracion')->findAll();
if (isset($configuracion[0])) {
$configuracion[0]->setTimeZoneRes($timeZone);
$emLev->persist($configuracion[0]);
$emLev->flush();
}
$accountLicenseData[0]->setTimeZoneRes($timeZone);
$em->persist($accountLicenseData[0]);
$em->flush();
}
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
$deleteRegistActionPauseOrder = $emLev->getRepository('App\Structure\RegistActions')->deleteRegistActionPauseOrder($emLev);
$emLev->clear();
$emLev->close();
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} elseif ($accountLicenseData[0]->getLevelLightUser() && isset($data["isLiteDevice"])) {
/** Flujo de un login correcto para level lite */
/** dump('Joder!'); */
if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_OUT) {
$accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_LITE);
} else if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_ANDROID) {
$accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_LITE_AND_ANDROID);
}
$em->persist($accountLicenseData[0]);
$em->flush();
$userData = $accountLicenseData[0]->getLevelLightUser();
$this->createFileJson($path, 'Util::doOMTDashboardLoginToGetToken 4!' . "\r");
$apikey = Util::doOMTDashboardLoginToGetToken($this->realContainer, $userData, $path, $accountLicenseData[0]->getLoginType());
if (!empty($apikey)) {
$responseArr['userToOmt']['apikey'] = $apikey;
}
$responseArr['userToOmt']['username'] = $userData['username'];
$responseArr['userToOmt']['password'] = $userData['realPass'];
if (!isset($userData['realPass'])) {
if ($accountLicenseData[0]->getHasLogedOMT() || $accountLicenseData[0]->getIsLevelLight() == true) {
$msnError = "The default OMT dashboard user doesn't have a password, please check the OMT database...";
$this->createFileJson($path, "\r" . 'LevelLite Error: ' . $msnError . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_FORBIDDEN)
->respondWithError($msnError, WebService::CODE_COULD_NOT_AUTHENTICATE);
} else {
if ($accountLicenseData[0]->getLastloguedDeviceKind() == AccountLicense::DEVICE_LITE_TYPE && $accountLicenseData[0]->getDeviceUid()) {
$accountLicenseData[0]->setDeviceUid(null);
$accountLicenseData[0]->setHasAndroid(null);
$accountLicenseData[0]->setWsResourceIdVerifiedAfterLogin(0);
$em->persist($accountLicenseData[0]);
$em->flush();
}
$msnError = $accountLicenseData[0] . " restaurant needs to be exported to OMT first!";
$this->createFileJson($path, "\r" . 'LevelLite Error: ' . $msnError . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_FORBIDDEN)
->respondWithError($msnError, WebService::CODE_COULD_NOT_AUTHENTICATE);
}
}
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
//// If para asegurarse de la coincidencia de uids entre el license account y la configuracion para permitir la coreecta syn desde level web
if ($accountLicenseData[0]->getLastloguedDeviceKind() == AccountLicense::DEVICE_LITE_TYPE) {
$this->createFileJson($path, 'Setting of UID in configuration! :' . $accountLicenseData[0]->getDeviceUid() . "\r");
$configuracion = $emLev->getRepository('App\Structure\Configuracion')->findAll();
if (isset($configuracion[0])) {
$configuracion[0]->setConfDeviceUid($accountLicenseData[0]->getDeviceUid());
$emLev->persist($configuracion[0]);
$emLev->flush();
}
}
//dump(':O');
//die;
$responseArr['status'] = WebService::HTTP_CODE_SUCCESS;
$responseArr['msg'] = 'Valid level lite license!';
$responseArr['bigbag'] = true;
$responseArr['language'] = $language;
if ($accountLicenseData[0]->getHasLogedOMT()) {
// Util::createSyncRecordsToOmtByUpdate($emLev, $accountLicenseData[0]);
$curlResponse = Util::makeOwnSyncWebCurl($this->realContainer, ['nickname' => $data['alLicenseUsername']], $path);
$data['rwid'] = $curlResponse;
ForcedAsynchronousCommandsUtil::consumeUpDownSyncCommand($this->realContainer, $data, true);
}
$emLev->clear();
$emLev->close();
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
$splitedLogin = json_decode($jsonContent)->splitedLogin ?? null;
if ($splitedLogin === (Util::definitionInitialMultipartLogin(0, true) - 1)) {
Util::logAction(
$em, 'AccountLicense',
$accountLicenseData[0]->getId(), ActionHistory::LEVELLITE_INITIAL_LOGIN, 'System', [
'data' => "Level Lite Login completed successfully for license: " . $accountLicenseData[0]->getAlLicenseUsername()
]);
}
$this->createFileJson($pathXD, "level lite splitedLogin => " . $splitedLogin . "\r");
$accountLicenseData[0]->setLastLoginDate(Util::getCurrentDate());
$em->persist($accountLicenseData[0]);
$em->flush();
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else if (!isset($data["isLiteDevice"]) && strtolower($data['username']) == $userLite["username"]) {
$accountLicenseData[0]->setLastloguedDeviceKind($oldLoguedDeviceKind);
$em->persist($accountLicenseData[0]);
$em->flush();
// dump(isset($data["isLiteDevice"]),$data, $userLite);die;
$this->createFileJson($path, "Error: User not valid for this platform");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError('User not valid for this platform', WebService::CODE_INTERNAL_ERROR);
} else {
$accountLicenseData[0]->setLastloguedDeviceKind($oldLoguedDeviceKind);
$em->persist($accountLicenseData[0]);
$em->flush();
$this->createFileJson($path, "Error: Error creating json file");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError('Error creating json file', WebService::CODE_INTERNAL_ERROR);
}
} else {
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
$configuracion = $emLev->getRepository('App\Structure\Configuracion')->find(1);
if (null == $oldUID || $oldUID == '') {
$accountLicenseData[0]->setDeviceUid(null);
$accountLicenseData[0]->setWsResourceIdVerifiedAfterLogin(0);
$configuracion->setConfDeviceUid(null);
$this->createFileJson($path, "\r" . '3 SETEO DE LEVEL UUID IN CONFIG: IS NULL AND HAS ANDROID : NULL' . "\r");
} else {
$this->createFileJson($path, "\r" . '4 SETEO DE LEVEL UUID IN CONFIG: ' . $oldUID . ' AND HAS ANDROID : NULL' . "\r");
$accountLicenseData[0]->setDeviceUid($oldUID);
$configuracion->setConfDeviceUid($oldUID);
}
$emLev->persist($configuracion);
$emLev->flush();
$em->persist($accountLicenseData[0]);
$em->flush();
$emLev->clear();
$emLev->close();
$this->createFileJson($path, "Error: Username not found");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Username not found', WebService::CODE_UNAUTHORIZED);
}
} else {
if (null == $oldUID || $oldUID == '') {
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
$configuracion = $emLev->getRepository('App\Structure\Configuracion')->find(1);
$accountLicenseData[0]->setDeviceUid(null);
$accountLicenseData[0]->setWsResourceIdVerifiedAfterLogin(0);
$configuracion->setConfDeviceUid(null);
$this->createFileJson($path, "\r" . '5 SETEO DE LEVEL UUID IN CONFIG: IS OLDUID IS EMPTY AND HAS ANDROID : NULL' . "\r");
$accountLicenseData[0]->setHasAndroid(false);
$configuracion->setConfHasAndriod(false);
$emLev->persist($configuracion);
$emLev->flush();
$em->persist($accountLicenseData[0]);
$em->flush();
$emLev->clear();
$emLev->close();
} else {
$accountLicenseData[0]->setDeviceUid($oldUID);
$configuracion->setConfDeviceUid($oldUID);
$this->createFileJson($path, "\r" . '6 SETEO DE LEVEL UUID IN CONFIG: IS OLDUID ' . $oldUID . ' AND HAS ANDROID : NULL' . "\r");
}
$this->createFileJson($path, "Error: Invalid login data please try again");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Invalid login data please try again', WebService::CODE_UNAUTHORIZED);
}
} catch (\Exception $th) {
$errorCode = uniqid();
$err = [
'Error Message' => $th->getMessage(), 'Error Line' => $th->getLine(),
'Error File' => $th->getFile(), 'Error Trace' => $th->getTrace()
];
$this->createFileJson($path, "\r" . "Error Code => ". $errorCode . "\r");
$this->createFileJson($path, "\r" . json_encode($err) . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)->respondWithError('Internal Server Error, Please, Contact Team Licensor, Error Code: '. $errorCode, WebService::HTTP_CODE_INTERNAL_ERROR);
}
}
/**
* Esta funcion permite al cliente adroid notificar que termino de
* subir el archivo de sincronizacion
* @author Aealan Z <lrobledo@kijho.com> 30/04/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function uploadSyncServiceUrl(Request $request) {
// dump('Die');
// die;
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
$arrayRequestEncripted = [];
$arrayRequestEncripted['nickname'] = $request->request->get('nickname');
$arrayRequestEncripted['uid'] = $request->request->get('uid');
$arrayRequestEncripted['numberOfSyncDataRecords'] = $request->request->get('numberOfSyncDataRecords');
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'syncDownUpWS', 'syncDownUpWS0.txt');
$this->createFileJson($path, "\r" . 'The request ' . json_encode($arrayRequestEncripted) . "\r");
try {
$parameters = $request->request->all();
$this->createFileJson($path, 'All parameters in request -> ' . json_encode($parameters) . "\r");
$data = [];
$arrayEncryptResult = Util::decryptDataForUploadsFiles($this->realContainer, $request->request->get('nickname'));
$data['nickname'] = $arrayEncryptResult['data'];
$arrayEncryptResult = Util::decryptDataForUploadsFiles($this->realContainer, $request->request->get('uid'));
$data['uid'] = $arrayEncryptResult['data'];
$arrayEncryptResult = Util::decryptDataForUploadsFiles($this->realContainer, $request->request->get('numberOfSyncDataRecords'));
$data['numberOfSyncDataRecords'] = $arrayEncryptResult['data'];
$arrayEncryptResult = Util::decryptDataForUploadsFiles($this->realContainer, $request->request->get('prioritySMSOrderSync'));
$data['prioritySMSOrderSync'] = $arrayEncryptResult['data'];
$this->createFileJson($path, 'Decripted ' . json_encode($data) . "\r");
$theTrueNameFile = $request->files->get('file')->getClientOriginalName();
$this->createFileJson($path, 'The Client IP -> ' . $request->getClientIp() . "\r");
$this->createFileJson($path, 'The File -> ' . $theTrueNameFile . "\r");
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($licenseUserName);
$forcedValidationPassed = false;
if (empty($accountLicenseData) && (null == $data['nickname'] ||
empty($data['nickname']) || $data['nickname'] == 'null') &&
(int) $this->realContainer->getParameter('device_recognition_by_ip_enabled') &&
!empty($theTrueNameFile) && $theTrueNameFile != '') {
$this->createFileJson($path, 'Forcing server android autentication... ' . "\r");
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy(['androidIP' => $request->getClientIp()]);
if (empty($accountLicenseData) || (int) $accountLicenseData[0]->getTimesCheckedIP() < (int) $this->realContainer->getParameter('ip_recognition_times_to_valid_check')) {
$accountLicenseData = [];
} else {
$forcedValidationPassed = true;
$this->createFileJson($path, 'Forced autentication succeeded! ' . "\r");
}
}
$countResult = count($accountLicenseData);
$this->createFileJson($path, 'Number of license found -> ' . $countResult . "\r");
if ($countResult > 0) {
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
$this->createFileJson($path, 'Salio 1! ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if (!$forcedValidationPassed && $accountLicenseData[0]->getDeviceUid() != $data['uid']) {
$this->createFileJson($path, 'Salio 2! ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_ACTIVE) {
$this->notifyLastSyncByLicense($em, $accountLicenseData[0]);
$this->createFileJson($path, 'License active! ' . "\r");
if (isset($data['numberOfSyncDataRecords'])) {
$accountLicenseData[0]->setNumberOfSyncDataRecords((int) $data['numberOfSyncDataRecords']);
$em->persist($accountLicenseData[0]);
$em->flush();
$licenseDataBaseEntity = $em->getRepository('App\Entity\LicenseDataBase')->findOneBy(['license' => $accountLicenseData[0]->getId()]);
if (!is_null($licenseDataBaseEntity)) {
$this->createFileJson($path, 'Creating license database connection for => '. $data['nickname'] . "\r");
$dataOptionsRoot = [
'dbname' => $licenseDataBaseEntity->getDbname(),
'user' => $licenseDataBaseEntity->getDbuser(),
'password' => $licenseDataBaseEntity->getDbpass(),
'host' => $licenseDataBaseEntity->getDbhost(),
'driver' => 'pdo_mysql',
];
$emLev = Util::emCreateConfiguration($this->realContainer, $dataOptionsRoot);
$configuracion = $emLev->getRepository('App\Structure\Configuracion')->find(1);
$configuracion->setNumberOfSyncDataRecords((int) $data['numberOfSyncDataRecords']);
$configuracion->setMaxRecordsSyncUpDown((int) $this->realContainer->getParameter('max_records_sync_up_down'));
$configuracion->setMaxRecordsSyncDownUp((int) $this->realContainer->getParameter('max_records_sync_down_up'));
$emLev->persist($configuracion);
$emLev->flush();
}else{
$this->createFileJson($path, 'License database configuration not found from => '. $data['nickname'] . "\r");
}
}
$masterBlockingByDBUpdate = $em->getRepository('App\Entity\MasterSync')->findBy(['msLicense' => $accountLicenseData[0]->getId(), 'msType' => MasterSync::MASTER_SYNC_TYPE_DB_UPDATE, 'msStatus' => MasterSync::MASTER_STATUS_INITIALIZATED]);
if (!empty($masterBlockingByDBUpdate)) {
$this->createFileJson($path, 'Se Fue DB blocked!' . "\r");
return $this->setStatusCode(WebService::CODE_OBJECT_NOT_FOUND)
->respondWithError('Synchronization blocked by DB update, please wait...', WebService::NOTHING_TO_WEB_SYNCHRONIZE);
}
$masterSyncRecords = $em->getRepository('App\Entity\MasterSync')->findMastersSyncsDownUpInProcessToBlockNewSyncs($accountLicenseData[0]->getId());
$statusArryMsg = [];
$statusArryMsg['status'] = WebService::CODE_SUCCESS;
$statusArryMsg['msg'] = '';
if (!empty($masterSyncRecords)) {
$auxArrayResponse = Utilx::validateAndUnblockSyncsWithErrors($this->realContainer, $masterSyncRecords, $em, $accountLicenseData[0], $path);
if (isset($auxArrayResponse['continue']) && isset($auxArrayResponse['msg']) && !$auxArrayResponse['continue']) {
$statusArryMsg['msg'] = $auxArrayResponse['msg'];
$theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer, $statusArryMsg);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
$readFilesDataEntity = $em->getRepository('App\Entity\ReadFilesData')->findBy(['rfStatus' => ReadFilesData::STATUS_UPLOADED, 'rfLicenseId' => $accountLicenseData[0]->getId(), 'hasPersistentError' => false]);
if (!empty($readFilesDataEntity)) {
$this->createFileJson($path, 'There is another sync petition in process, please wait until is finished' . "\r");
$statusArryMsg['msg'] = 'There is another sync petition in process, please wait until is finished';
$theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer, $statusArryMsg);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
$readFilesDataEntity = $em->getRepository('App\Entity\ReadFilesData')->findBy(['rfStatus' => ReadFilesData::STATUS_UPLOADED, 'rfLicenseId' => $accountLicenseData[0]->getId(), 'hasPersistentError' => true]);
if (!empty($readFilesDataEntity)) {
$this->createFileJson($path, 'There is another sync petition for this license with a problem in the sever, please contact your system supplier for more information' . "\r");
$statusArryMsg['msg'] = 'There is another sync petition for this license with a problem in the sever, please contact your system supplier for more information';
$theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer, $statusArryMsg);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
$numberOfOtherSyncsInProccess = $em->getRepository('App\Entity\ReadFilesData')->findMaxAmountOfIncomingAndroidSyncs();
if ($numberOfOtherSyncsInProccess >= (int) $this->realContainer->getParameter('max_concurret_down_up_sync')) {
$this->createFileJson($path, "There are '$numberOfOtherSyncsInProccess' another sync proccess in server, please try it later" . "\r");
$statusArryMsg['msg'] = "There are '$numberOfOtherSyncsInProccess' another sync proccess in server, please try it later";
$theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer, $statusArryMsg);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
$isDirectoryReady = Util::createLicenseDirectory($this->realContainer, $accountLicenseData[0], $accountLicenseData[0]->getAlLicenseUsername());
$theAccountLicenseDirector = $isDirectoryReady['directory'];
if (!isset($isDirectoryReady['result']) || $isDirectoryReady['result'] == '__KO__') {
$msnError = 'An error occurred while creating your directory in server ';
return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
->respondWithError($msnError, WebService::CODE_INTERNAL_ERROR);
}
$this->createFileJson($path, 'The license dir ' . $theAccountLicenseDirector . "\r");
$uploadFileResponse = Utilx::uploadFileTo($request, $theAccountLicenseDirector, $path);
if (!isset($uploadFileResponse['result']) || !isset($uploadFileResponse['msg'])) {
$this->createFileJson($path, 'Unknown error uploading file ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError('Unknown error uploading file', WebService::CODE_INTERNAL_ERROR);
}
if (isset($uploadFileResponse['result']) && isset($uploadFileResponse['msg']) && $uploadFileResponse['result'] == '__KO__') {
$this->createFileJson($path, $uploadFileResponse['msg'] . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError($uploadFileResponse['msg'], WebService::CODE_INTERNAL_ERROR);
}
$readFilesDataEntityByLicense = $em->getRepository('App\Entity\ReadFilesData')->findBy(['rfLicenseId' => $accountLicenseData[0]->getId(), 'rfStatus' => ReadFilesData::STATUS_STANDBY], ['rfDateSincAsk' => 'DESC']);
$this->createFileJson($path, 'The ReadFilesData count 1 -> ' . count($readFilesDataEntityByLicense) . "\r");
if (empty($readFilesDataEntityByLicense)) {
$readFilesDataEntityByLicense[0] = $this->setRegistNewFile($accountLicenseData[0]);
}
///////////////// por aca iria la lectura del archivo subido para la prueba del NO_DATA
// dump($uploadFileResponse['fileDir']);
// dump(file_get_contents($uploadFileResponse['fileDir']));
// die;
$auxNoDataStringFromFile = file_get_contents($uploadFileResponse['fileDir']);
if (strpos($auxNoDataStringFromFile, "NO_DATA") && strlen($auxNoDataStringFromFile) < 40) {
$this->createFileJson($path, "No data file detected, closing opened sync... \r");
$masterSyncRecordToClose = $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncRecord' => $readFilesDataEntityByLicense[0]->getId()]);
if (isset($masterSyncRecordToClose[0])) {
$masterSyncRecordToClose[0]->setMsStatus(MasterSync::MASTER_STATUS_RESPONDED);
$this->createFileJson($path, "Closing MasterSync with '" . $masterSyncRecordToClose[0]->getId() . "' id \r");
$em->persist($masterSyncRecordToClose[0]);
} else {
$this->createFileJson($path, 'Dafuq! o.O! ' . "\r");
}
$readFilesDataEntityByLicense[0]->setRfStatus(ReadFilesData::STATUS_DELIVERED);
$this->createFileJson($path, "Closing ReadFilesData with '" . $readFilesDataEntityByLicense[0]->getId() . "' id \r");
$accountLicenseData[0]->setNoDataFileDetected(1);
$em->persist($accountLicenseData[0]);
$em->persist($readFilesDataEntityByLicense[0]);
$em->flush();
$statusArryMsg['msg'] = 'No data file detected, closing opened sync...';
$theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer, $statusArryMsg);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
$this->createFileJson($path, 'Track X! ' . "\r");
$this->createFileJson($path, 'WS Response: ' . $jsonContent . "\r");
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
$this->createFileJson($path, "Restoring NoDatFileDetectedFlag for '" . $accountLicenseData[0] . "' restaurant \r");
$accountLicenseData[0]->setNoDataFileDetected(0);
$em->persist($accountLicenseData[0]);
$em->flush();
}
$bucketFileLocation = Util::uploadSyncFileToS3Service($this->realContainer, $accountLicenseData[0], $uploadFileResponse['fileName'], $uploadFileResponse['fileDir'], $path);
$syncFileS3URI = 'https://' . $this->realContainer->getParameter('s3_bucket_name') . '.' . $this->realContainer->getParameter('s3_default_bucket_domain') . '/' . $bucketFileLocation;
$registerStatus = $this->updateRegistUploadFile($readFilesDataEntityByLicense[0], $uploadFileResponse['fileName'], $syncFileS3URI);
if ($registerStatus) {
$statusArryMsg['msg'] = 'File has been uploaded and the record updated';
$this->createFileJson($path, 'File has been uploaded and the record updated' . "\r");
} else {
$this->createFileJson($path, 'Salio 9! ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_NOT_FOUND)
->respondWithError('Error updating syncronization control record', WebService::CODE_OBJECT_NOT_FOUND);
}
$licenseDataBaseEntity = $em->getRepository('App\Entity\LicenseDataBase')->findBy(['license' => $accountLicenseData[0]->getId()]);
if (!empty($licenseDataBaseEntity)) {
$pushSendRepository = $em->getRepository('App\Entity\PushSent');
$pushSendRepository->respondOldPushesForLicense(PushSent::PUSH_TYPE_SYNC_DOWNUP, $accountLicenseData[0]->getId());
$usernameByNickname = $licenseDataBaseEntity[0]->getLicense();
$theAccountPath = $this->realContainer->getParameter('level_directory_data_android') . $usernameByNickname->getAlAccountLicense()->getAcName() . '/' . $usernameByNickname->getAlLicenseUsername();
$theAccountPath = str_replace(' ', '_', $theAccountPath);
$dataOptionsRoot = [
'dbname' => $licenseDataBaseEntity[0]->getDbname(),
'user' => $licenseDataBaseEntity[0]->getDbuser(),
'password' => $licenseDataBaseEntity[0]->getDbpass(),
'host' => $licenseDataBaseEntity[0]->getDbhost(),
'driver' => 'pdo_mysql',
];
$msg = [
'id' => $readFilesDataEntityByLicense[0]->getId(),
'dataOptionsRoot' => $dataOptionsRoot,
'path' => $theAccountPath,
'fileName' => $readFilesDataEntityByLicense[0]->getRfNameFile(),
'AccountLicense' => $usernameByNickname->getAlAccountLicense()->getAcName(),
'pushchanel' => $usernameByNickname->getAlLicenseUsername()
];
$readFilesDataEntityByLicense[0]->setIsReadedByServer(true);
$em->persist($readFilesDataEntityByLicense[0]);
$em->flush();
if (isset($data['prioritySMSOrderSync']) && $data['prioritySMSOrderSync']) {
$this->get('priority_android_sync_producer')->setContentType('application/json');
$this->get('priority_android_sync_producer')->setDeliveryMode(2);
$this->get('priority_android_sync_producer')->publish(json_encode($msg));
} else {
$this->get('incoming_android_sync_producer')->setContentType('application/json');
$this->get('incoming_android_sync_producer')->setDeliveryMode(2);
$this->get('incoming_android_sync_producer')->publish(json_encode($msg));
}
if (!$request->request->get('hold')) {
$statusArryMsg['msg'] = 'File has been uploaded and the sync process triggered';
$this->createFileJson($path, 'File has been uploaded and the sync process triggered' . "\r");
$data['readFilesDataId'] = $readFilesDataEntityByLicense[0]->getId();
ForcedAsynchronousCommandsUtil::consumeDownUpSyncCommand($this->realContainer, $data, true);
} else {
$statusArryMsg['msg'] = 'File has been uploaded and the sync process is ready to start';
$this->createFileJson($path, 'File has been uploaded and the sync process is ready to start' . "\r");
}
}
$this->createFileJson($path, 'Track 7! ' . "\r");
$theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer, $statusArryMsg);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
$this->createFileJson($path, 'Track 8! ' . "\r");
$this->createFileJson($path, 'UploadSyncJsonNotifyTransformer json to respond' . $jsonContent . "\r");
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
$this->createFileJson($path, 'Salio 3! ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Inactive License', WebService::CODE_ACCOUNT_SUSPENDED);
}
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} catch (\Exception $th) {
$this->createFileJson($path, 'Error Message => '. $th->getMessage() . ' Error Line => '. $th->getLine() . ' Error Trace => '. $th->getTraceAsString() . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError($th->getMessage(), WebService::HTTP_CODE_INTERNAL_ERROR);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* Esta funcion permite validar el acceso a la aplicacion web de level
* validando codigo de usuario y contraseña y generando el apiKey
* necesario para toda la aplicacion movil
* @author Aealan Z <lrobledo@kijho.com> 28/03/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function syncFromWeb(Request $request) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'requestFromWeb', 'requestFromWeb0.txt');
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT) && 0 !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
$this->createFileJson($path, 'Se Fue 6' . "\r");
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$params = json_decode($request->getContent(), true);
$this->createFileJson($path, "\r" . 'Coming Content New Age: ' . json_encode($params) . "\r");
$decodeInfo = Util::decodeInfo($params['nickname']);
$this->createFileJson($path, 'Decode info: ' . $decodeInfo . "\r");
$data = ['alLicenseUsername' => $decodeInfo];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
$countResult = count($accountLicenseData);
$this->createFileJson($path, 'Count found: ' . $countResult . "\r");
if ($countResult <= 0) {
$this->createFileJson($path, 'Se Fue 5' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$this->createFileJson($path, 'Entro coño! ' . $accountLicenseData[0]->getAlAccountLicense()->getDeleted() . "\r");
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted() === true) {
$this->createFileJson($path, 'Se Fue 1: Account is inactive' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
$this->createFileJson($path, 'Se Fue 4' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Inactive License', WebService::CODE_ACCOUNT_SUSPENDED);
}
$priorityFlag = null;
if (isset($params['priorityFlag'])) {
$priorityFlag = (int) $params['priorityFlag'];
}
$this->createFileJson($path, 'pre notifyLastSyncByLicense ' . "\r");
$this->notifyLastSyncByLicense($em, $accountLicenseData[0]);
$masterBlockingByDBUpdate = $em->getRepository('App\Entity\MasterSync')->findBy(['msLicense' => $accountLicenseData[0]->getId(), 'msType' => MasterSync::MASTER_SYNC_TYPE_DB_UPDATE, 'msStatus' => MasterSync::MASTER_STATUS_INITIALIZATED]);
if (!empty($masterBlockingByDBUpdate)) {
$this->createFileJson($path, 'Se Fue DB blocked!' . "\r");
return $this->setStatusCode(WebService::CODE_OBJECT_NOT_FOUND)
->respondWithError('Synchronization blocked by DB update, please wait...', WebService::NOTHING_TO_WEB_SYNCHRONIZE);
}
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
$registActionRepository = $emLev->getRepository('App\Structure\RegistActions');
$this->createFileJson($path, 'pre existCategoryRegistActionRecordToSync ' . "\r");
$hasCategoryToSync = $registActionRepository->existCategoryRegistActionRecordToSync($this->realContainer->getParameter('max_records_sync_up_down'));
if ($accountLicenseData[0]->getHasLogedOMT() && (int) $hasCategoryToSync) {
$this->createFileJson($path, 'pre validateMenuCategoryForOutgoingOMTSyncs ' . "\r");
Util::validateMenuCategoryForOutgoingOMTSyncs($emLev, $path, false);
}
$this->createFileJson($path, 'pre validateIfRestaurantCaDoAndroidDatabaseCleanse ' . "\r");
$canSyncCleanseRecords = Util::validateIfRestaurantCaDoAndroidDatabaseCleanse($accountLicenseData[0], $emLev, $path);
if (is_string($canSyncCleanseRecords)) {
$recordType = RegistActions::TYPE_GENERAL;
$this->createFileJson($path, 'Full sync with cleanse if there is one' . "\r");
$pendingToSyncDownRecord = $registActionRepository->alternateSmartGetRegistActionForUpDownSync($this->realContainer, RegistActions::STATUS_NOTREADED, RegistActions::TYPE_GENERAL, $this->realContainer->getParameter('max_records_sync_up_down'), $priorityFlag, $path);
// $pendingToSyncDownRecord = $registActionRepository->findBy(['reacStatus' => RegistActions::STATUS_NOTREADED, 'reacType' => RegistActions::TYPE_GENERAL], ['reacRegistFk' => 'DESC'], $this->realContainer->getParameter('max_records_sync_up_down'));
} else {
$recordType = null;
$this->createFileJson($path, 'Without cleanse' . "\r");
$pendingToSyncDownRecord = $registActionRepository->alternateSmartGetRegistActionForUpDownSync($this->realContainer, RegistActions::STATUS_NOTREADED, null, $this->realContainer->getParameter('max_records_sync_up_down'), $priorityFlag, $path);
// $pendingToSyncDownRecord = $registActionRepository->findBy(['reacStatus' => RegistActions::STATUS_NOTREADED], ['reacRegistFk' => 'DESC'], $this->realContainer->getParameter('max_records_sync_up_down'));
}
// dump($pendingToSyncDownRecord);
$recordsCount = count($pendingToSyncDownRecord);
$auxRecordCount = $this->realContainer->getParameter('max_records_sync_up_down') - count($pendingToSyncDownRecord);
if ($auxRecordCount > 0 && $priorityFlag !== false) {
$this->createFileJson($path, 'Completing max regist action records for sync ;) ' . "\r");
if (!empty($path)) {
$this->createFileJson($path, "'$recordsCount' total priority records were found... filling with normal records XD " . "\r");
}
$otherComplementingRegistActionRecords = $registActionRepository->alternateSmartGetRegistActionForUpDownSync($this->realContainer, RegistActions::STATUS_NOTREADED, $recordType, $auxRecordCount, false, $path);
$pendingToSyncDownRecord = array_merge($pendingToSyncDownRecord, $otherComplementingRegistActionRecords);
}
// dump($pendingToSyncDownRecord);
$this->createFileJson($path, 'pre countPendigRecordsToPickupAndSync ' . "\r");
$totalSyncRecords = $registActionRepository->countPendigRecordsToPickupAndSync();
$countTotalSyncRecords = (int) $totalSyncRecords;
$hasMoreRecordsToSync = false;
$syncsToPerform = 1;
if ($countTotalSyncRecords > $this->realContainer->getParameter('max_records_sync_up_down')) {
$hasMoreRecordsToSync = true;
$syncsToPerform = (int) ceil($countTotalSyncRecords / $this->realContainer->getParameter('max_records_sync_up_down'));
}
$responseArray = [];
$responseArray['status'] = WebService::CODE_SUCCESS;
$responseArray['result'] = '__OK__';
$responseArray['wait'] = '__NO__';
$responseArray['bigbag'] = true;
$responseArray['hasMoreRecords'] = $hasMoreRecordsToSync;
$responseArray['syncsToPerform'] = $syncsToPerform;
$this->createFileJson($path, 'Count records to notify x2: ' . count($pendingToSyncDownRecord) . "\r");
if (!empty($pendingToSyncDownRecord)) {
$this->createFileJson($path, 'The syncFK: ' . $pendingToSyncDownRecord[0]->getReacRegistFk() . "\r");
if (null == $pendingToSyncDownRecord[0]->getReacRegistFk() || $pendingToSyncDownRecord[0]->getReacRegistFk() == 0) {
$this->createFileJson($path, 'Records not picked yet! ' . "\r");
$auxResponseArray = Utilx::setRegistNewSyncWeb($this->realContainer, $em, $accountLicenseData[0], null, null, null, $syncsToPerform, $priorityFlag);
$responseArray['result'] = $auxResponseArray['result'];
$responseArray['rid'] = $auxResponseArray['rid'];
$this->createFileJson($path, 'The new record sync id to handle! ' . $responseArray['rid'] . "\r");
} else {
// $pendignMasterSyncRecord = $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncWebRecord' => $pendingToSyncDownRecord[0]->getReacRegistFk(), 'msStatus' => MasterSync::MASTER_STATUS_INITIALIZATED]);
$pendignMasterSyncRecord = $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncWebRecord' => $pendingToSyncDownRecord[0]->getReacRegistFk()]);
// $responseArray['hasMoreRecords'] = $hasMoreRecordsToSync;
//////
if (!empty($pendignMasterSyncRecord)) {
if ($pendignMasterSyncRecord[0]->getMsType() == MasterSync::MASTER_SYNC_TYPE_UPDOWN && $pendignMasterSyncRecord[0]->getMsStatus() == MasterSync::MASTER_STATUS_CLOSED && $pendignMasterSyncRecord[0]->getMsOMTStatus() == MasterSync::MASTER_STATUS_CLOSED) {
$this->createFileJson($path, 'Records about to be picked by validation, generating another web sync record! ' . "\r");
$auxResponseArray = Utilx::setRegistNewSyncWeb($this->realContainer, $em, $accountLicenseData[0], null, null, null, $syncsToPerform, $priorityFlag);
$responseArray['result'] = $auxResponseArray['result'];
$responseArray['rid'] = $auxResponseArray['rid'];
$this->createFileJson($path, 'The new records to sync with! ' . $responseArray['rid'] . "\r");
} else {
$responseArray['rid'] = $pendingToSyncDownRecord[0]->getReacRegistFk();
$this->createFileJson($path, 'Records picked by: ' . $responseArray['rid'] . "\r");
}
} else {
$this->createFileJson($path, 'Records about to be picked, generating another web sync record! ' . "\r");
$auxResponseArray = Utilx::setRegistNewSyncWeb($this->realContainer, $em, $accountLicenseData[0], null, null, null, $syncsToPerform, $priorityFlag);
$responseArray['result'] = $auxResponseArray['result'];
$responseArray['rid'] = $auxResponseArray['rid'];
$this->createFileJson($path, 'The new records to sync with! ' . $responseArray['rid'] . "\r");
}
}
// dump($pendingToSyncDownRecord);
// die;
$recordsJustForOMT = true;
$arrRegistActionsToDeleteAlready = [];
$arrAlreadyCheckedRegistActionRecord = [];
$auxArrayForRealRegistActionsRecordsToSync = [];
foreach ($pendingToSyncDownRecord as $registActionRecord) {
if (array_search($registActionRecord->getId(), $arrAlreadyCheckedRegistActionRecord) === false) {
$registActionRecord->setReacRegistFk($responseArray['rid']);
if (!$registActionRecord->getReacType() && !$registActionRecord->getReacOMTRegistFk()) {
$registActionRecord->setReacOMTRegistFk($responseArray['rid']);
}
$androidtname = Util::getAndroidTableName($registActionRecord->getReacTableName());
if ($recordsJustForOMT && (Util::getRepoServerNameByAndroidTableName($androidtname) || Util::getStructureEntityDirForForLicensorCorrespondigTable($androidtname))) {
$this->createFileJson($path, 'Has Android records to sync!!' . "\r");
$recordsJustForOMT = false;
}
array_push($arrRegistActionsToDeleteAlready, $registActionRecord->getId());
array_push($arrAlreadyCheckedRegistActionRecord, $registActionRecord->getId());
array_push($auxArrayForRealRegistActionsRecordsToSync, $registActionRecord);
$emLev->persist($registActionRecord);
}
}
$pendingToSyncDownRecord = $auxArrayForRealRegistActionsRecordsToSync;
// dump($pendingToSyncDownRecord);
if ($recordsJustForOMT) {
$this->createFileJson($path, 'Direct sync for OMT detected, moving forward with validations.... -_- ' . "\r");
}
// die;
$emLev->flush();
$this->createFileJson($path, 'New sync web fk?? -> ' . $responseArray['rid'] . "\r");
$masterSyncRecords = $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncWebRecord' => $responseArray['rid']]);
if (!empty($masterSyncRecords) && !$recordsJustForOMT) {
$responseArray['msg'] = 'Processing new data..';
$responseArray['wait'] = '__NO__';
$responseArray['master_sync'] = $masterSyncRecords[0]->getId();
$responseArray['response_code'] = WebService::PROCESSING_UNNOTIFIED_WEB_DATA;
$webSyncWaiting = $masterSyncRecords[0]->getMsSyncWebRecord();
$this->createFileJson($path, 'Master sync record: ' . $masterSyncRecords[0]->getId() . "\r");
$this->createFileJson($path, 'One IF Status: ' . $webSyncWaiting->getRfwStatus() . ' Error: ' . !(boolean) $webSyncWaiting->getHasPersistentError() . "\r");
if ($webSyncWaiting->getRfwStatus() == ReadFilesDataWeb::STATUS_NOTIFIED && !(boolean) $webSyncWaiting->getHasPersistentError()) {
$isDirectoryReady = Util::createLicenseDirectory($this->realContainer, $accountLicenseData[0], $decodeInfo);
if (isset($isDirectoryReady['result']) && $isDirectoryReady['result'] == '__KO__') {
$this->createFileJson($path, 'Se Fue 1 ' . "\r");
$msnError = 'An error occurred while creating license directory in server ';
return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
->respondWithError($msnError, WebService::CODE_INTERNAL_ERROR);
}
$this->createFileJson($path, 'Web ready sync: ' . $webSyncWaiting->getId() . "\r");
if ($webSyncWaiting->getIsReadedByServer()) {
$this->createFileJson($path, 'Web already picked by rabbit: TRUE' . "\r");
$responseArray['msg'] = 'Server is already synchronizing the new data to the android device, please wait.';
$responseArray['wait'] = '__YES__';
$responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
$theUrlTrSt = new SyncWebTransformer($responseArray);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
return $this->respondWithURLWithoutEncriptControl($jsonContent, $theUrlTrSt);
}
$em->clear();
if (isset($params['waitTime']) && !(boolean) $params['waitTime'] && isset($responseArray['rid']) && $responseArray['rid'] != 0) {
ForcedAsynchronousCommandsUtil::produceUpDownSyncCommand($this->realContainer, $responseArray, true);
$this->createFileJson($path, 'No wait request triggered...' . "\r");
}
$theUrlTrSt = new SyncWebTransformer($responseArray);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
$this->createFileJson($path, 'WS Response: ' . $jsonContent . "\r");
return $this->respondWithURLWithoutEncriptControl($jsonContent, $theUrlTrSt);
} else {
$pushRelatedRecord = $masterSyncRecords[0]->getMsPushRecord();
$responseArray['rid'] = 0;
$responseArray['response_code'] = 0;
$responseArray['master_sync'] = $masterSyncRecords[0]->getId();
if (!$pushRelatedRecord) {
$this->createFileJson($path, 'No push related to the master sync record' . "\r");
$responseArray['msg'] = 'Processing unnotified data..';
$responseArray['rid'] = $webSyncWaiting->getId();
$responseArray['response_code'] = WebService::PROCESSING_UNNOTIFIED_WEB_DATA;
if (isset($pendingToSyncDownRecord[0]) && $pendingToSyncDownRecord[0]->getReacStatus() == RegistActions::STATUS_NOTREADED && ReadFilesDataWeb::STATUS_RESPONSE_READED == $webSyncWaiting->getRfwStatus()) {
///// analizar si la licencia tiene OMT logueado y verificar si dichos registros son para OMT, si si, entonces enviarla desde aca directamente a OMT, si no, borrar los registros del regist action y asi evitar la inconsistencia
if ($recordsJustForOMT && !$accountLicenseData[0]->getHasLogedOMT()) {
$this->createFileJson($path, 'Deleting OMT RegistAction records to for non OMT license ;) ' . "\r");
SyncWebUtil::deleteValidatedRegistAction($arrRegistActionsToDeleteAlready, [], $registActionRepository, false, true, $path);
$this->createFileJson($path, 'Closing the related sync records ;) ' . "\r");
$masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
$webSyncWaiting->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
$webSyncWaiting->setIsReadedByServer(true);
$em->persist($masterSyncRecords[0]);
$em->persist($webSyncWaiting);
$em->flush();
$this->createFileJson($path, 'Preparing a propper ws response for this case ;) ' . "\r");
$responseArray['msg'] = 'Cleaning web sync records, please try again in a few seconds...';
$responseArray['wait'] = '__NO__';
$responseArray['askAgain'] = 1;
$responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
} elseif ($recordsJustForOMT && $accountLicenseData[0]->getHasLogedOMT()) {
//// amerita en elseif en donde se mande directo a OMT si la licencia si tiene OMT y estos registros andan asi como raros o mal cerrados
$this->createFileJson($path, 'Sending forced sync direct to OMT!' . "\r");
$data['rid'] = $webSyncWaiting->getId();
$data['masterSyncId'] = $masterSyncRecords[0]->getId();
$data['restaurantNickname'] = $data['alLicenseUsername'];
$masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
if ($webSyncWaiting) {
$webSyncWaiting->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
$webSyncWaiting->setIsReadedByServer(true);
$em->persist($webSyncWaiting);
}
$em->persist($masterSyncRecords[0]);
$em->flush();
$typeSync = UtilSync::hybridSync2OMT($this->realContainer, $em, $path, $data['alLicenseUsername']);
// se valida el tipo de sync que se va a realizar
if($typeSync){
ForcedAsynchronousCommandsUtil::produceUpDownOMTSyncCommand($this->realContainer, $data, true);
}else{
// comando de cola para sync masiva
ForcedAsynchronousCommandsUtil::produceUpDownOMTSyncMassiveCommand($this->realContainer, $data, $path, true);
}
$responseArray['msg'] = 'Direct sync to OMT';
$responseArray['wait'] = '__NO__';
$responseArray['askAgain'] = 1;
$responseArray['master_sync'] = $masterSyncRecords[0]->getId();
$responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
} else {
$this->createFileJson($path, 'Records bad closed by support, generating another web sync record! ' . "\r");
// $auxResponseArray = Utilx::setRegistNewSyncWeb($this->realContainer, $em, $accountLicenseData[0], null, null, null, $syncsToPerform);
$responseArray['result'] = $auxResponseArray['result'];
$responseArray['rid'] = $auxResponseArray['rid'];
$responseArray['master_sync'] = $masterSyncRecords[0]->getId();
$responseArray['msg'] = 'Scheduling unprocessed sync records, please try to sync again in a few seconds';
$this->createFileJson($path, 'The new records to sync with! ' . $responseArray['rid'] . " second chance \r");
foreach ($pendingToSyncDownRecord as $registActionRecord) {
$registActionRecord->setReacRegistFk($responseArray['rid']);
if (!$registActionRecord->getReacType() && !$registActionRecord->getReacOMTRegistFk()) {
$registActionRecord->setReacOMTRegistFk($responseArray['rid']);
}
$emLev->persist($registActionRecord);
}
$emLev->flush();
$this->createFileJson($path, 'New sync web fk second chance?? -> ' . $responseArray['rid'] . "\r");
}
} else {
////mandar a la cola de rabbit para que recoja los registros aun no procesados
ForcedAsynchronousCommandsUtil::produceUpDownSyncCommand($this->realContainer, $responseArray, true);
$this->createFileJson($path, 'No wait request triggered alternate 1 ...' . "\r");
}
} else {
if ($pushRelatedRecord->getPushStatus() == PushSent::STATUS_PUSH_PENDING) {
$this->createFileJson($path, 'Pending for response push: ' . $pushRelatedRecord->getId() . "\r");
$responseArray['msg'] = 'Push notification unconfirmed by android device, forwarding push to complete the synchronization process... ';
$responseArray['wait'] = '__NO__';
$responseArray['response_code'] = WebService::FORWARDING_UNNOTIFIED_WEB_PUSH;
$responseArray['master_sync'] = $masterSyncRecords[0]->getId();
$actualDate = Util::getCurrentDate();
$actualDate->modify($this->realContainer->getParameter('maximum_minutes_to_validate_push_sending') . ' minutes');
if ($pushRelatedRecord->getResendDate() < $actualDate) {
$data['pushId'] = $pushRelatedRecord->getId();
ForcedAsynchronousCommandsUtil::resendPushCommand($this->realContainer, $data, true);
}
} else {
if (isset($pendingToSyncDownRecord[0]) && $pendingToSyncDownRecord[0]->getReacStatus() == RegistActions::STATUS_NOTREADED && ReadFilesDataWeb::STATUS_RESPONSE_READED == $webSyncWaiting->getRfwStatus()) {
if ($recordsJustForOMT && !$accountLicenseData[0]->getHasLogedOMT()) {
$this->createFileJson($path, 'Deleting OMT RegistAction records to for non OMT license ;)) ' . "\r");
SyncWebUtil::deleteValidatedRegistAction($arrRegistActionsToDeleteAlready, [], $registActionRepository, false, true, $path);
$this->createFileJson($path, 'Closing the related sync records ;)) ' . "\r");
$masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
$masterSyncRecords[0]->setMsOMTStatus(MasterSync::MASTER_STATUS_CLOSED);
$webSyncWaiting->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
$webSyncWaiting->setIsReadedByServer(true);
$em->persist($masterSyncRecords[0]);
$em->persist($webSyncWaiting);
$em->flush();
$this->createFileJson($path, 'Preparing a propper ws response for this case ;)) ' . "\r");
$responseArray['msg'] = 'Cleaning web sync records, please try again in a few seconds...';
$responseArray['wait'] = '__NO__';
$responseArray['askAgain'] = 1;
$responseArray['master_sync'] = $masterSyncRecords[0]->getId();
$responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
} elseif ($recordsJustForOMT && $accountLicenseData[0]->getHasLogedOMT()) {
$this->createFileJson($path, 'Sending forced sync direct to OMT!!' . "\r");
$data['rid'] = $webSyncWaiting->getId();
$data['masterSyncId'] = $masterSyncRecords[0]->getId();
$data['restaurantNickname'] = $data['alLicenseUsername'];
$masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
$webSyncWaiting->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
$webSyncWaiting->setIsReadedByServer(true);
$em->persist($masterSyncRecords[0]);
$em->persist($webSyncWaiting);
$em->flush();
$typeSync = UtilSync::hybridSync2OMT($this->container, $em, $path, $data['alLicenseUsername']);
// se valida el tipo de sync que se va a realizar
if($typeSync){
$this->createFileJson($path, 'Sending standard sync direct to OMT 1 !!' . "\r");
ForcedAsynchronousCommandsUtil::produceUpDownOMTSyncCommand($this->container, $data, true);
}else{
// comando de cola para sync masiva
$this->createFileJson($path, 'Sending hybrid sync direct to OMT 1 !!' . "\r");
ForcedAsynchronousCommandsUtil::produceUpDownOMTSyncMassiveCommand($this->container, $data, $path, true);
}
$responseArray['msg'] = 'Direct sync to OMT';
$responseArray['wait'] = '__NO__';
$responseArray['askAgain'] = 1;
$responseArray['master_sync'] = $masterSyncRecords[0]->getId();
$responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
} else {
$this->createFileJson($path, 'Records bad closed by support, generating another web sync record! ' . "\r");
// $auxResponseArray = Utilx::setRegistNewSyncWeb($this->realContainer, $em, $accountLicenseData[0], null, null, null, $syncsToPerform);
$responseArray['result'] = $auxResponseArray['result'];
$responseArray['rid'] = $auxResponseArray['rid'];
$responseArray['msg'] = 'Scheduling unprocessed sync records, please try to sync again in a few seconds';
$responseArray['master_sync'] = $masterSyncRecords[0]->getId();
$this->createFileJson($path, 'The new records to sync with! ' . $responseArray['rid'] . " second chance \r");
foreach ($pendingToSyncDownRecord as $registActionRecord) {
$registActionRecord->setReacRegistFk($responseArray['rid']);
if (!$registActionRecord->getReacType() && !$registActionRecord->getReacOMTRegistFk()) {
$registActionRecord->setReacOMTRegistFk($responseArray['rid']);
}
$emLev->persist($registActionRecord);
}
$emLev->flush();
$this->createFileJson($path, 'New sync web fk second chance?? -> ' . $responseArray['rid'] . "\r");
}
} else {
$this->createFileJson($path, 'Sync unresponded by android device: ' . $pushRelatedRecord->getId() . "\r");
$responseArray['msg'] = 'Forwarding push with new code to complete the synchronization process...';
$responseArray['wait'] = '__YES__';
$responseArray['response_code'] = WebService::FORWARDING_UNNOTIFIED_WEB_PUSH;
$actualDate = Util::getCurrentDate();
$actualDate->modify($this->realContainer->getParameter('maximum_minutes_to_validate_push_sending') . ' minutes');
if ($pushRelatedRecord->getResendDate() < $actualDate) {
$data['pushId'] = $pushRelatedRecord->getId();
$data['forcePushNewCode'] = true;
ForcedAsynchronousCommandsUtil::resendPushCommand($this->realContainer, $data, true);
}
}
}
}
}
$theUrlTrSt = new SyncWebTransformer($responseArray);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
$this->createFileJson($path, 'WS Response: ' . $jsonContent . "\r");
return $this->respondWithURLWithoutEncriptControl($jsonContent, $theUrlTrSt);
} elseif (!empty($masterSyncRecords) && $recordsJustForOMT) {
$responseArray['master_sync'] = $masterSyncRecords[0]->getId();
$webSyncWaiting = $masterSyncRecords[0]->getMsSyncWebRecord();
if (!$accountLicenseData[0]->getHasLogedOMT()) {
$this->createFileJson($path, 'Deleting OMT RegistAction records to for non OMT license ;)) ' . "\r");
SyncWebUtil::deleteValidatedRegistAction($arrRegistActionsToDeleteAlready, [], $registActionRepository, false, true, $path);
$this->createFileJson($path, 'Closing the related sync records ;)) ' . "\r");
$masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
$masterSyncRecords[0]->setMsOMTStatus(MasterSync::MASTER_STATUS_CLOSED);
if ($webSyncWaiting) {
$webSyncWaiting->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
$webSyncWaiting->setIsReadedByServer(true);
$em->persist($webSyncWaiting);
}
$em->persist($masterSyncRecords[0]);
$em->flush();
$this->createFileJson($path, 'Preparing a propper ws response for this case ;)) ' . "\r");
$responseArray['msg'] = 'Cleaning web sync records, please try again in a few seconds...';
$responseArray['wait'] = '__NO__';
$responseArray['askAgain'] = 1;
$responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
} else {
$this->createFileJson($path, 'Sending forced sync direct to OMT!!' . "\r");
$data['rid'] = $webSyncWaiting->getId();
$data['masterSyncId'] = $masterSyncRecords[0]->getId();
$data['restaurantNickname'] = $data['alLicenseUsername'];
$masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
if ($webSyncWaiting) {
$webSyncWaiting->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
$webSyncWaiting->setIsReadedByServer(true);
$em->persist($webSyncWaiting);
}
$em->persist($masterSyncRecords[0]);
$em->flush();
$typeSync = UtilSync::hybridSync2OMT($this->realContainer, $em, $path, $data['alLicenseUsername']);
// se valida el tipo de sync que se va a realizar
if($typeSync){
$this->createFileJson($path, 'Sending standard sync direct to OMT 2 !!' . "\r");
ForcedAsynchronousCommandsUtil::produceUpDownOMTSyncCommand($this->realContainer, $data, true);
}else{
// comando de cola para sync masiva
$this->createFileJson($path, 'Sending hybrid sync direct to OMT 2 !!' . "\r");
ForcedAsynchronousCommandsUtil::produceUpDownOMTSyncMassiveCommand($this->realContainer, $data, $path, true);
}
$responseArray['msg'] = 'Direct sync to OMT';
$responseArray['wait'] = '__NO__';
$responseArray['askAgain'] = 1;
$responseArray['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
}
} else {
$this->createFileJson($path, 'Se Fue 2' . "\r");
$msnError = 'Nothing to synchronize! ';
return $this->setStatusCode(WebService::CODE_OBJECT_NOT_FOUND)
->respondWithError($msnError, WebService::NOTHING_TO_WEB_SYNCHRONIZE);
}
$theUrlTrSt = new SyncWebTransformer($responseArray);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
$this->createFileJson($path, 'WS Response: ' . $jsonContent . "\r");
return $this->respondWithURLWithoutEncriptControl($jsonContent, $theUrlTrSt);
} else {
$masterSyncRecords = $em->getRepository('App\Entity\MasterSync')->findBy(['msLicense' => $accountLicenseData[0]->getId(), 'msType' => MasterSync::MASTER_SYNC_TYPE_UPDOWN, 'msStatus' => MasterSync::MASTER_STATUS_PROCESSED], ['id' => 'ASC']);
if (!empty($masterSyncRecords)) {
$this->createFileJson($path, 'Uncomplet master record found -> ' . $masterSyncRecords[0]->getId() . "\r");
$webSyncWaiting = $masterSyncRecords[0]->getMsSyncWebRecord();
$pushRelatedRecord = $masterSyncRecords[0]->getMsPushRecord();
$responseArray['rid'] = 0;
$responseArray['master_sync'] = $masterSyncRecords[0]->getId();
if (!$pushRelatedRecord) {
$this->createFileJson($path, 'No push related to the master sync record' . "\r");
$responseArray['msg'] = 'Processing unnotified data..';
$responseArray['rid'] = $webSyncWaiting->getId();
$responseArray['response_code'] = WebService::PROCESSING_UNNOTIFIED_WEB_DATA;
} else {
if ($pushRelatedRecord->getPushStatus() == PushSent::STATUS_PUSH_PENDING) {
$this->createFileJson($path, 'Pending for response push: ' . $pushRelatedRecord->getId() . "\r");
$responseArray['msg'] = 'Push notification unconfirmed by android device, forwarding push to complete the synchronization process... ';
$responseArray['wait'] = '__NO__';
$responseArray['response_code'] = WebService::FORWARDING_UNNOTIFIED_WEB_PUSH;
$actualDate = Util::getCurrentDate();
$actualDate->modify($this->realContainer->getParameter('maximum_minutes_to_validate_push_sending') . ' minutes');
if ($pushRelatedRecord->getResendDate() < $actualDate) {
$data['pushId'] = $pushRelatedRecord->getId();
ForcedAsynchronousCommandsUtil::resendPushCommand($this->realContainer, $data, true);
}
} else {
$this->createFileJson($path, 'Sync unresponded by android device: ' . $pushRelatedRecord->getId() . "\r");
$responseArray['msg'] = 'Forwarding push with new code to complete the synchronization process...';
$responseArray['wait'] = '__YES__';
$responseArray['response_code'] = WebService::FORWARDING_UNNOTIFIED_WEB_PUSH;
$actualDate = Util::getCurrentDate();
$actualDate->modify($this->realContainer->getParameter('maximum_minutes_to_validate_push_sending') . ' minutes');
if ($pushRelatedRecord->getResendDate() < $actualDate) {
$data['pushId'] = $pushRelatedRecord->getId();
$data['forcePushNewCode'] = true;
ForcedAsynchronousCommandsUtil::resendPushCommand($this->realContainer, $data, true);
}
}
}
} else {
$masterBlockingByFalseSync = $em->getRepository('App\Entity\MasterSync')->findBy(['msLicense' => $accountLicenseData[0]->getId(), 'msType' => MasterSync::MASTER_SYNC_TYPE_UPDOWN, 'msStatus' => MasterSync::MASTER_STATUS_INITIALIZATED]);
foreach ($masterBlockingByFalseSync as $falseMasterSync) {
Utilx::updateRegistCloseByEmptySyncFile($em, $falseMasterSync, $path);
}
$this->createFileJson($path, 'Se Fue 3' . "\r");
$msnError = 'Nothing to synchronize! ';
return $this->setStatusCode(WebService::CODE_OBJECT_NOT_FOUND)
->respondWithError($msnError, WebService::NOTHING_TO_WEB_SYNCHRONIZE);
}
$theUrlTrSt = new SyncWebTransformer($responseArray);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
$this->createFileJson($path, 'WS Response: ' . $jsonContent . "\r");
return $this->respondWithURLWithoutEncriptControl($jsonContent, $theUrlTrSt);
}
} else {
$this->createFileJson($path, 'Se Fue 7' . "\r");
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* Funcion tipo polling para activar el consumidor de una sincronizacion de
* arriba a abajo ya encolada por medio de la solicitud de un ajax
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param Request $request peticion realizada por medio de un ajax
* @param type $id id del registro de sincronizacion web de esa licencia
* @return type repuesta de la sincronizacion para el ajax en formato json
*/
public function activateWebConsumerByAjax(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'requestFromWebYYY', 'requestFromWebYYY0.txt');
$paramNick = $request->request->get('nickname');
if ($paramNick == null) {
$paramNick = $request->query->get('nickname');
}
$this->createFileJson($path, 'Searching sync with id: ' . $id . "\r");
$syncWebRecord = $em->getRepository('App\Entity\ReadFilesDataWeb')->find($id);
$this->createFileJson($path, 'Instant Request Auch -> Llego Llego!' . "\r");
if ($syncWebRecord) {
for ($i = 0; $i <= 4; $i++) {
if ($paramNick != $syncWebRecord->getRfwLicenseId()->getAlLicenseUsername()) {
$responseToAjax['msg'] = 'License Not Found!';
$responseToAjax['result'] = '__KO__';
return $this->respondJsonAjax($responseToAjax);
}
$responseToAjax['result'] = '__OK__';
sleep(4);
$this->createFileJson($path, 'Instant Request Auch -> ' . $syncWebRecord->getIsReadedByServer() . ' | ' . $syncWebRecord->getRfwStatus() . "\r");
$statusReadFileWeb = $em->getRepository('App\Entity\ReadFilesDataWeb')->find($id);
$statusSyncMaster = $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncWebRecord' => $id]);
if ($statusSyncMaster[0]->getMsType() == MasterSync::MASTER_SYNC_TYPE_UPDOWN &&
$statusSyncMaster[0]->getMsStatus() == MasterSync::MASTER_STATUS_PROCESSED &&
$statusSyncMaster[0]->getMsPushRecord() !== null &&
ReadFilesDataWeb::STATUS_READED_DELIVERED == $statusReadFileWeb->getRfwStatus()) {
$em->clear();
$this->createFileJson($path, 'Instant Request Processed!' . "\r");
$responseToAjax['msg'] = 'Data for the Android server send, please check for the new data!';
$responseToAjax['response_code'] = WebService::WEB_DATA_SENDED_TO_ANDROID;
break;
} else if ($syncWebRecord->getIsReadedByServer() && ReadFilesDataWeb::STATUS_NOTIFIED == $syncWebRecord->getRfwStatus()) {
$em->clear();
$data['rwid'] = $syncWebRecord->getId();
ForcedAsynchronousCommandsUtil::consumeUpDownSyncCommand($this->realContainer, $data, true);
$this->createFileJson($path, 'Instant Request Processed!' . "\r");
$responseToAjax['msg'] = 'The data is being processed, please verify the changes in a few seconds...';
$responseToAjax['response_code'] = WebService::WEB_DATA_SENDED_TO_ANDROID;
break;
} else {
$responseToAjax['msg'] = 'Server is working... Please try 20 seconds latter!';
$responseToAjax['response_code'] = WebService::SERVER_ALREADY_WORKING_WEB_SYNC;
}
}
} else {
if ($id == 0) {
$this->createFileJson($path, 'Instant Request Push Resend -> XD' . "\r");
sleep(4);
$responseToAjax['msg'] = 'Push forwarded, please check the Android server!';
$responseToAjax['result'] = '__KO__';
$responseToAjax['response_code'] = WebService::FORWARDING_UNNOTIFIED_WEB_PUSH;
} else {
$this->createFileJson($path, 'Instant Request Auch -> License sync web record not found!' . "\r");
$responseToAjax['msg'] = 'License sync web record not found!';
$responseToAjax['result'] = '__KO__';
}
return $this->respondJsonAjax($responseToAjax);
}
return $this->respondJsonAjax($responseToAjax);
}
/**
* Funcion que solicitar una sincronizacion de arriba a abajo a un servidor
* android por medio de un push
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param Request $request solicitud que llega por ajax pidiendo una sincronizacion de abajo a arriba
* @param type $id id de la licencia a la cual se le solicita la sincronizacion
* @return type respuesta del envio del push que solicita la sincronizacion de tipo json para un ajax
*/
public function activateAndroidSyncManually(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'requestForManuallySync', 'requestForManuallySync0.txt');
$paramNick = $request->request->get('nickname');
if ($paramNick == null) {
$paramNick = $request->query->get('nickname');
}
$this->createFileJson($path, "\r" . 'Sync Android Up Manually: ' . $paramNick . "\r");
$licenseToSync = $em->getRepository('App\Entity\AccountLicense')->find($id);
if ($licenseToSync) {
if ($paramNick != $licenseToSync->getAlLicenseUsername()) {
$this->createFileJson($path, 'Bad nickname!' . "\r");
$responseToAjax['msg'] = 'License not found!';
$responseToAjax['result'] = '__KO__';
return $this->respondJsonAjax($responseToAjax);
}
$this->createFileJson($path, 'Sync Android Up Manually: License Found!' . "\r");
$masterBlockingByDBUpdate = $em->getRepository('App\Entity\MasterSync')->findBy(['msLicense' => $licenseToSync->getId(), 'msType' => MasterSync::MASTER_SYNC_TYPE_DB_UPDATE, 'msStatus' => MasterSync::MASTER_STATUS_INITIALIZATED]);
if (!empty($masterBlockingByDBUpdate)) {
$this->createFileJson($path, 'Synchronization blocked by DB update, please wait...' . "\r");
$responseToAjax['msg'] = 'Synchronization blocked by DB update, please wait...';
$responseToAjax['result'] = '__KO__';
$responseToAjax['response_code'] = WebService::SYNC_BLOQUED_DB;
return $this->respondJsonAjax($responseToAjax);
}
$this->createFileJson($path, 'No blocked synchronization by DB update, moving forward...' . "\r");
$infiniteSyncIdentified = false;
if ($licenseToSync->getAlLockedByInfiniteSync() == false && $licenseToSync->getLastLoginDate() != null) {
$resultCheck = Utilx::validateAndLockLicenseWithInfiniteSync($em, $this->realContainer, $licenseToSync);
$infiniteSyncIdentified = !$resultCheck["continue"] ;
}
if ($infiniteSyncIdentified == true || $licenseToSync->getAlLockedByInfiniteSync() == true) {
$this->createFileJson($path, 'Sync blocked by infinite loop problems issues' . "\r");
$responseToAjax['msg'] = 'Sync blocked by infinite loop problems issues';
$responseToAjax['result'] = '__KO__';
$responseToAjax['response_code'] = WebService::SYNC_LOCKED_BY_INFINITE_LOOP;
return $this->respondJsonAjax($responseToAjax);
}
$this->createFileJson($path, 'No blocked synchronization by by infinite loop issues, moving forward...' . "\r");
$masterSyncRecords = $em->getRepository('App\Entity\MasterSync')->findMastersSyncsDownUpInProcessToBlockNewSyncs($licenseToSync->getId());
if (!empty($masterSyncRecords)) {
$auxArrayResponse = Utilx::validateAndUnblockSyncsWithErrors($this->realContainer, $masterSyncRecords, $em, $licenseToSync, $path);
if (isset($auxArrayResponse['continue']) && isset($auxArrayResponse['msg']) && !$auxArrayResponse['continue']) {
$this->createFileJson($path, $auxArrayResponse['msg'] . "\r");
$responseToAjax['msg'] = $auxArrayResponse['msg'];
$responseToAjax['result'] = '__KO__';
$responseToAjax['response_code'] = WebService::ANOTHER_SYNC_IN_PROCESS;
return $this->respondJsonAjax($responseToAjax);
}
}
$lastReadDataForLicense = $em->getRepository('App\Entity\ReadFilesData')->findLastSyncPetitionIdByLicense($id);
$responseToAjax['result'] = '__OK__';
$responseToAjax['lastId'] = (int) $lastReadDataForLicense;
$isInProssesASync = $em->getRepository('App\Entity\ReadFilesData')->findBy(['id' => $lastReadDataForLicense, 'isReadedByServer' => true, 'hasPersistentError' => false, 'rfStatus' => ReadFilesData::STATUS_UPLOADED]);
if (!empty($isInProssesASync)) {
$responseToAjax['result'] = '__KO__';
$this->createFileJson($path, 'An Android server synchronization is already in process.. Please check if the new data has been uploaded in one minute!' . "\r");
$responseToAjax['msg'] = 'An Android server synchronization is already in process.. Please check if the new data has been uploaded in one minute!';
$responseToAjax['response_code'] = WebService::SYNC_ALREADY_IN_PROCESS;
}
$this->createFileJson($path, 'Ready to send push asking for down up synchronization!' . "\r");
$dataResponse = [];
$dataResponse["status"] = WebService::CODE_SUCCESS;
$dataResponse["actions"] = "updatedb";
$dataResponse['uploadurl'] = $this->realContainer->getParameter('level_scheme') . '://' . $this->realContainer->getParameter('level_host') . $this->generateUrl('level_web_service_sync_upload_data_android');
$typePush = PushSent::PUSH_TYPE_SYNC_DOWNUP;
Util::sendSuperPush($this->realContainer, $em, $dataResponse, $typePush, $licenseToSync, $path);
} else {
$responseToAjax['msg'] = 'License not found!';
$responseToAjax['result'] = '__KO__';
return $this->respondJsonAjax($responseToAjax);
}
return $this->respondJsonAjax($responseToAjax);
}
/**
* Funcion para hacer el polling para un ajax verificando si la peticion
* de sincronizacion manual de abajo a arriba fue completada con exito
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param Request $request peticion recivida por ajax
* @param type $id id de la licencia a la que se le solicito la sincronizacion
* @return type json con la respuesta del polling formateada para el ajax
*/
public function checkAndroidSyncManuallyCompleted(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'requestForManuallySyncXXX', 'requestForManuallySyncXXX0.txt');
$this->createFileJson($path, 'Sync Android Up Manually: Llego al check! ' . "\r");
$paramNick = $request->request->get('nickname');
if ($paramNick == null) {
$paramNick = $request->query->get('nickname');
}
$paramLastId = $request->request->get('lastId');
if ($paramLastId == null) {
$paramLastId = $request->query->get('lastId');
}
$this->createFileJson($path, 'Sync Android Up Manually: nickname' . $paramNick . "\r");
$this->createFileJson($path, 'Sync Android Up Manually: lastId' . $paramLastId . "\r");
if (null != $paramLastId && (int) $paramLastId >= 0) {
$licenseToSync = $em->getRepository('App\Entity\AccountLicense')->find($id);
$this->createFileJson($path, 'Sync Android Up Manually: Entro 1' . $paramLastId . "\r");
if ($licenseToSync) {
$this->createFileJson($path, 'Sync Android Up Manually: Entro 2' . $paramLastId . "\r");
if ($paramNick != $licenseToSync->getAlLicenseUsername()) {
$responseToAjax['msg'] = 'License not found!';
$responseToAjax['result'] = '__KO__';
return $this->respondJsonAjax($responseToAjax);
}
$responseToAjax['result'] = '__OK__';
$pollingResultArray = $this->checkForDownUpPolling($id, $paramLastId, $path);
$responseToAjax['msg'] = $pollingResultArray['msg'];
$responseToAjax['response_code'] = $pollingResultArray['response_code'];
$this->createFileJson($path, 'Sync Android Up Manually: Super!' . $paramLastId . "\r");
} else {
$responseToAjax['msg'] = 'License not found!';
$responseToAjax['result'] = '__KO__';
$this->createFileJson($path, 'Sync Android Up Manually: Chango1 ' . $paramLastId . "\r");
return $this->respondJsonAjax($responseToAjax);
}
} else {
$this->createFileJson($path, 'Sync Android Up Manually: Chango2 ' . $paramLastId . "\r");
$responseToAjax['msg'] = 'License not found!';
$responseToAjax['result'] = '__KO__';
return $this->respondJsonAjax($responseToAjax);
}
return $this->respondJsonAjax($responseToAjax);
}
/**
* Esta funcion permite al cliente adroid notificar que termino de
* subir el archivo de sincronizacion
* @author Aealan Z <lrobledo@kijho.com> 30/04/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function uploadAndoridSyncWebResponse(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'requestRespondForWebSyncFromAndroid', 'requestRespondForWebSyncFromAndroid0.txt');
try {
$this->createFileJson($path, "\r" . 'Upload Sync Up-Down Andorid Response File: Llego? ' . "\r");
$this->createFileJson($path, 'Whole request -> ' . $request . "\r");
$this->createFileJson($path, 'Maybe some content here...? -> ' . $request->getContent() . "\r");
$parameters = $request->request->all();
$this->createFileJson($path, 'All parameters in request -> ' . json_encode($parameters) . "\r");
$this->createFileJson($path, 'Nickname -> ' . $request->request->get('nickname') . "\r");
$this->createFileJson($path, 'UID -> ' . $request->request->get('uid') . "\r");
$data = [];
$dataForTrack = [];
$arrayEncryptResult = Util::decryptDataForUploadsFiles($this->realContainer, $request->request->get('nickname'));
$data['nickname'] = $arrayEncryptResult['data'];
$dataForTrack['nick_encrypt'] = $request->request->get('nickname');
$dataForTrack['nick_decrypt'] = $arrayEncryptResult['data'];
$arrayEncryptResult = Util::decryptDataForUploadsFiles($this->realContainer, $request->request->get('uid'));
$data['uid'] = $arrayEncryptResult['data'];
$dataForTrack['uid_encrypt'] = $request->request->get('uid');
$dataForTrack['uid_decrypt'] = $arrayEncryptResult['data'];
$arrayEncryptResult = Util::decryptDataForUploadsFiles($this->realContainer, $request->request->get('NO_DATA'));
$data['NO_DATA'] = $arrayEncryptResult['data'];
$dataForTrack['uid_encrypt'] = $request->request->get('NO_DATA');
$dataForTrack['uid_decrypt'] = $arrayEncryptResult['data'];
$this->createFileJson($path, 'Full -> ' . json_encode($dataForTrack) . "\r");
$this->createFileJson($path, 'The Client IP -> ' . $request->getClientIp() . "\r");
$hasFile = false;
if ($request->files->get('file')) {
$hasFile = true;
$this->createFileJson($path, 'The File -> ' . $request->files->get('file')->getClientOriginalName() . "\r");
} else {
$this->createFileJson($path, 'No file uploaded, returning ' . "\r");
}
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
$countResult = count($accountLicenseData);
if ($countResult > 0 && $hasFile) {
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
$this->createFileJson($path, 'Licensia borrada! o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
$this->createFileJson($path, 'UID diferente! o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::CODE_ACCOUNT_SUSPENDED);
}
$statusArryMsg = [];
$statusArryMsg['status'] = WebService::CODE_SUCCESS;
$statusArryMsg['msg'] = '';
if (isset($data['NO_DATA'])) {
$statusArryMsg['msg'] = 'Empty file delivered for Android!!!! ...closing sync...';
$this->createFileJson($path, 'Empty file delivered for Android!!!! ...closing sync...' . " O.o! \r");
// $registerStatus = Util::updateWebSyncUploadResponseFile($em, $readFilesDataEntityByLicense[0], $data['NO_DATA']);
$theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer, $statusArryMsg);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_ACTIVE) {
$pushSentArray = [];
$readFilesDataEntityByLicense = $em->getRepository('App\Entity\ReadFilesDataWeb')->findBy(['rfwLicenseId' => $accountLicenseData[0]->getId(), 'rfwStatus' => ReadFilesDataWeb::STATUS_READED_DELIVERED], ['rfwDateSincAsk' => 'ASC'], 2);
if (isset($readFilesDataEntityByLicense[0]) && $readFilesDataEntityByLicense[0]->getRfwStatus() == ReadFilesDataWeb::STATUS_READED_DELIVERED) {
$this->createFileJson($path, 'Encontrada la ' . $readFilesDataEntityByLicense[0]->getId() . " :) \r");
$masterSyncForWebResponse = $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncWebRecord' => $readFilesDataEntityByLicense[0]->getId()]);
if (isset($masterSyncForWebResponse[0])) {
$this->createFileJson($path, 'Into push validation response ' . $masterSyncForWebResponse[0]->getId() . " :) \r");
$pushWebPushSend = $masterSyncForWebResponse[0]->getMsPushRecord();
if ($pushWebPushSend) {
if ($pushWebPushSend->getPushStatus() == PushSent::STATUS_PUSH_PENDING) {
$pushWebPushSend->setPushStatus(PushSent::STATUS_PUSH_READED);
$actualDate = Util::getCurrentDate();
$pushWebPushSend->setRespondDate($actualDate);
$em->persist($pushWebPushSend);
$em->flush();
$this->createFileJson($path, 'Updated push status by sync response for ' . $pushWebPushSend->getId() . " ;) \r");
} else {
$this->createFileJson($path, 'Already responded by Android server XD' . "\r");
}
} else {
$this->createFileJson($path, 'Not related push, it may be an initial login... ' . "\r");
}
}
$isDirectoryReady = Util::createLicenseDirectory($this->realContainer, $accountLicenseData[0], $data['nickname']);
$theAccountLicenseDirector = $isDirectoryReady['directory'];
if (!isset($isDirectoryReady['result']) || $isDirectoryReady['result'] == '__KO__') {
$this->createFileJson($path, 'No existe el directorio de la licensia coño! o.O' . "\r");
$msnError = 'An error occurred while creating your directory in server ';
return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
->respondWithError($msnError, WebService::CODE_INTERNAL_ERROR);
}
$uploadFileResponse = Utilx::uploadFileTo($request, $theAccountLicenseDirector, $path);
if (!isset($uploadFileResponse['result']) || !isset($uploadFileResponse['msg'])) {
$this->createFileJson($path, 'Unknown error uploading file ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError('Unknown error uploading file', WebService::CODE_INTERNAL_ERROR);
}
if (isset($uploadFileResponse['result']) && isset($uploadFileResponse['msg']) && $uploadFileResponse['result'] == '__KO__') {
$this->createFileJson($path, $uploadFileResponse['msg'] . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError($uploadFileResponse['msg'], WebService::CODE_INTERNAL_ERROR);
}
$bucketFileLocation = Util::uploadSyncFileToS3Service($this->realContainer, $accountLicenseData[0], $uploadFileResponse['fileName'], $uploadFileResponse['fileDir'], $path);
$syncResponseFileS3URI = 'https://' . $this->realContainer->getParameter('s3_bucket_name') . '.' . $this->realContainer->getParameter('s3_default_bucket_domain') . '/' . $bucketFileLocation;
$registerStatus = Util::updateWebSyncUploadResponseFile($em, $readFilesDataEntityByLicense[0], $uploadFileResponse['fileName'], $syncResponseFileS3URI);
//////////// validacion para determinar si se puede marcar la licencia con login inicial exitoso
$theProcessedUploadedFile = $readFilesDataEntityByLicense[0]->getRfwNameProcessedFile();
if (($readFilesDataEntityByLicense[0]->getSplitLoginIndex() == 0 && count(explode('_', $theProcessedUploadedFile)) == 2 && strpos($theProcessedUploadedFile, 'heInitialData') === 1) ||
($readFilesDataEntityByLicense[0]->getSplitLoginIndex() == 4 && count(explode('_', $theProcessedUploadedFile)) == 4 && strpos($theProcessedUploadedFile, 'heInitialData_user') === 1)) {
$accountLicenseData[0]->setLastLoginWasOk(true);
$em->persist($accountLicenseData[0]);
$em->flush();
}
if ($registerStatus) {
$statusArryMsg['msg'] = 'File has been uploaded and the record updated';
$this->createFileJson($path, ':D 6' . "\r");
} else {
$this->createFileJson($path, 'Error actualizando el MasterSync coño! o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_NOT_FOUND)
->respondWithError('Error updating syncronization control record', WebService::CODE_OBJECT_NOT_FOUND);
}
$this->createFileJson($path, 'Hay Chingada!?' . "\r");
$licenseDataBaseEntity = $em->getRepository('App\Entity\LicenseDataBase')->findBy(['license' => $accountLicenseData[0]->getId()]);
$this->createFileJson($path, 'O No Hay!?' . "\r");
if (!empty($licenseDataBaseEntity)) {
$this->createFileJson($path, 'Entro Trigger' . "\r");
$usernameByNickname = $licenseDataBaseEntity[0]->getLicense();
$theAccountPath = $this->realContainer->getParameter('level_directory_data_android') . $usernameByNickname->getAlAccountLicense()->getAcName() . '/' . $usernameByNickname->getAlLicenseUsername();
$theAccountPath = str_replace(' ', '_', $theAccountPath);
$dataOptionsRoot = [
'dbname' => $licenseDataBaseEntity[0]->getDbname(),
'user' => $licenseDataBaseEntity[0]->getDbuser(),
'password' => $licenseDataBaseEntity[0]->getDbpass(),
'host' => $licenseDataBaseEntity[0]->getDbhost(),
'driver' => 'pdo_mysql',
];
$msg = [
'id' => $readFilesDataEntityByLicense[0]->getId(),
'dataOptionsRoot' => $dataOptionsRoot,
'path' => $theAccountPath,
'filename' => $readFilesDataEntityByLicense[0]->getRfwClientResponseFile(),
'AccountLicense' => $usernameByNickname->getAlAccountLicense()->getAcName()
];
$this->get('incoming_web_android_sync_response_producer')->setContentType('application/json');
$this->get('incoming_web_android_sync_response_producer')->setDeliveryMode(2);
$this->get('incoming_web_android_sync_response_producer')->publish(json_encode($msg));
$statusArryMsg['msg'] = 'File has been uploaded and the sync web response process is ready to consume';
$holdTheComsume = $request->request->get('hold');
if (null == $holdTheComsume) {
$statusArryMsg['msg'] = 'File has been uploaded and the sync web response process triggered';
sleep(5);
$this->createFileJson($path, 'Instant parameter sended to consumer command -> ' . $readFilesDataEntityByLicense[0]->getId() . "\r");
$data['syncRecord'] = $readFilesDataEntityByLicense[0]->getId();
ForcedAsynchronousCommandsUtil::consumeUpDownSyncResponseCommand($this->realContainer, $data, true);
$this->createFileJson($path, 'Corrio Trigger? ' . "\r");
}
}
$this->createFileJson($path, ':D 7' . "\r");
if (null != $request->request->get('code')) {
$arrayEncryptResult = Util::decryptDataForUploadsFiles($this->realContainer, $request->request->get('code'));
$data['code'] = $arrayEncryptResult['data'];
$pushSendRecords = $em->getRepository('App\Entity\PushSent')->findBy(['verificationCode' => $data['code'], 'pushStatus' => PushSent::STATUS_PUSH_PENDING]);
if (!empty($pushSendRecords)) {
$this->updateRegistPushSend($pushSendRecords[0]);
}
}
$this->createFileJson($path, ':D 8' . "\r");
$theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer, $statusArryMsg);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
$this->createFileJson($path, 'No encontro el registro de la sincronizacion web coño! o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_NOT_FOUND)
->respondWithError('No syncronization data registered', WebService::CODE_OBJECT_NOT_FOUND);
}
} else {
$this->createFileJson($path, 'Licensia inactiva! o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Inactive License', WebService::CODE_ACCOUNT_SUSPENDED);
}
} else {
$this->createFileJson($path, 'No encontro la licencia! o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname or file not uploaded properly', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} catch (\Exception $ex) {
$this->createFileJson($path, 'Error on request: -> ' . $ex->getMessage() . "\r");
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS generico para que el cliente andorid responda todos los push enviados a los clientes
* @author Aealan Z <lrobledo@kijho.com> 18/06/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function respondedReadedPush(Request $request) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'pushResponseFromAndroid', 'pushResponseFromAndroid0.txt');
$this->createFileJson($path, 'Push Responded: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$params = json_decode($arrayEncryptResult['data'], true);
$this->createFileJson($path, 'Push Responded decode params: ' . $arrayEncryptResult['data'] . "\r");
if (!isset($params['code'])) {
$this->createFileJson($path, 'No code argument send' . "\r");
return $this->errorWrongArgs('No code argument send', WebService::CODE_WRONG_ARGUMENTS);
}
$em = $this->realContainer->get('doctrine')->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->validateRestauratAndAccountActive($params['nickname']);
$pushSendRepository = $em->getRepository('App\Entity\PushSent');
$firstBy = null;
if (isset($params['pushProvider']) && $params['pushProvider'] == 'Pushy') {
$firstBy = PushSent::SENDED_FIRST_BY_PUSHY;
} elseif (isset($params['pushProvider']) && $params['pushProvider'] == 'Pubnub') {
$firstBy = PushSent::SENDED_FIRST_BY_PUBNUB;
} elseif (isset($params['pushProvider']) && $params['pushProvider'] == 'Level') {
$firstBy = PushSent::SENDED_FIRST_BY_LICENSOR;
}
$this->createFileJson($path, "step 1 \r");
$response = null;
if (isset($params['response'])) {
$response = (int) $params['response'];
}
$responsePushType = $pushSendRepository->selectPushTypeByCode($params['code']);
$this->createFileJson($path, "step 2 \r");
if (!$responsePushType) {
$msnError = 'Push record not found! ';
$this->createFileJson($path, "$msnError \r");
return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
->respondWithError($msnError, WebService::CODE_INTERNAL_ERROR);
}
$responseUpdate = $pushSendRepository->updateReadedPush($params['code'], $firstBy, $response);
if (PushSent::PUSH_TYPE_UPLOAD_S3_BACKUP == $responsePushType) {
$pushSendRepository->updateLicenseRecordByPush($params['code']);
}
$pushSendRepository->respondOldPushesForLicense($responsePushType, $accountLicenseData);
$pushSendRepository->closeUnansweredS3Pushes($accountLicenseData);
$this->createFileJson($path, "step 3 \r");
if (!$responseUpdate) {
$msnError = 'An error occurred while updatin the push send record or push already answered.';
$this->createFileJson($path, "$msnError \r");
return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
->respondWithError($msnError, WebService::CODE_INTERNAL_ERROR);
}
$responseArray['status'] = WebService::CODE_SUCCESS;
$responseArray['msg'] = 'Server notified';
$this->createFileJson($path, "step 4 \r");
$theUrlTrSt = new RespondedNotificationPushTransformer($responseArray);
$jsonTransform = $theUrlTrSt->transform();
$this->createFileJson($path, "step 5 \r");
$jsonContent = json_encode($jsonTransform);
$this->createFileJson($path, "$jsonContent \r");
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
/**
* WS generico para que el servidor andorid responda una pregunta realizada en un push
* @author Aealan Z <lrobledo@kijho.com> 15/06/16
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function respondedAskInPush(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'requestEncriptedFromAndroid', 'requestEncriptedFromAndroid0.txt');
$this->createFileJson($path, "\r" . 'Push Ask: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$params = json_decode($arrayEncryptResult['data'], true);
$this->createFileJson($path, 'Push Responded decode params: ' . $arrayEncryptResult['data'] . "\r");
if (!isset($params['nickname']) || !isset($params['code'])) {
return $this->errorWrongArgs('Wrong Arguments', WebService::CODE_WRONG_ARGUMENTS);
}
$em = $this->getDoctrine()->getManager();
$data = ['alLicenseUsername' => $params['nickname']];
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
$data = ['channelName' => $params['nickname']];
$subLicenseData = $em->getRepository('App\Entity\SubLicense')->findBy($data);
$countResult = count($accountLicenseData) + count($subLicenseData);
if ($countResult > 0) {
if (!empty($accountLicenseData)) {
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Inactive License', WebService::CODE_ACCOUNT_SUSPENDED);
}
}
$pushSendRecords = $em->getRepository('App\Entity\PushSent')->searchPushSendRecords($params['code']);
$responseArray = [];
$responseUpdate = false;
if (!empty($pushSendRecords)) {
if (isset($params['response'])) {
$pushSendRecords[0]->setAskedResponse((boolean) $params['response']);
}
$responseUpdate = $this->updateRegistPushSend($pushSendRecords[0]);
} else {
$msnError = 'Push send record not found ';
return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
->respondWithError($msnError, WebService::CODE_INTERNAL_ERROR);
}
if (!$responseUpdate) {
$msnError = 'An error occurred while updatin the push send record..';
return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
->respondWithError($msnError, WebService::CODE_INTERNAL_ERROR);
}
$responseArray['status'] = WebService::CODE_SUCCESS;
$responseArray['msg'] = 'Push ask response notified';
$theUrlTrSt = new RespondedNotificationPushTransformer($responseArray);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname or channelname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} else {
return $this->errorWrongArgs('Wrong Arguments', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS generico para que los dispositivos android notifique de un error por correo
* @author Aealan Z <lrobledo@kijho.com> 13/07/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function notifyAndroidError(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
/////////////////////// Otra sospecha de caida del servidor de licensor prod
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'notifyErrorAndroid', 'notifyErrorAndroid0.txt');
$this->createFileJson($path, "\r" . 'The content: ' . $request->getContent() . "\r");
$responseArray['status'] = WebService::CODE_SUCCESS;
$responseArray['msg'] = 'Server notified';
$theUrlTrSt = new RespondedNotificationPushTransformer($responseArray);
$jsonTransform = $theUrlTrSt->transform();
$this->createFileJson($path, 'The encoded ws response: ' . json_encode($responseArray) . "\r");
$jsonContent = json_encode($jsonTransform);
$this->createFileJson($path, 'The transform: ' . $jsonContent . "\r");
return $this->respondWithItem($jsonContent, $theUrlTrSt);
///////////////////
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$this->createFileJson($path, 'The decrypted content: ' . $request->getContent() . "\r");
$params = json_decode($arrayEncryptResult['data'], true);
$this->createFileJson($path, 'The request array: ' . $arrayEncryptResult['data'] . "\r");
if (!isset($params['nickname']) || !isset($params['msg']) || !isset($params['uid'])) {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$data = ['alLicenseUsername' => $params['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
$data = ['channelName' => $params['nickname']];
$subLicenseData = $em->getRepository('App\Entity\SubLicense')->findBy($data);
$countResult = count($accountLicenseData) + count($subLicenseData);
if ($countResult > 0) {
if (!empty($accountLicenseData)) {
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Inactive License', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getDeviceUid() != $params['uid']) {
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
$subLicenseData = $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $params['uid']]);
if (empty($subLicenseData)) {
$emLev->close();
$this->createFileJson($path, 'Error: Unknown device' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::CODE_UNAUTHORIZED);
} else {
$emLev->close();
}
}
}
$sendEmail = $this->realContainer->getParameter('level_emails_syncs_errors');
if (isset($params['msg']) && $params['msg'] == '') {
return $this->setStatusCode(WebService::CODE_WRONG_ARGUMENTS)
->respondWithError('Empty error message', WebService::CODE_ACCOUNT_SUSPENDED);
}
$errors = $em->getRepository('App\Entity\ErrorAndroidEmailSent')->getAllErrorMsg();
list($errorMsg) = explode("->", $params['msg']);
$theErrorEmailEntity=null;
$countErrors = count($errors);
for ($i=0; $i < $countErrors ; ++$i) {
$error=$errors[$i]["errorMsg"];
$pos = strpos($errorMsg, $error);
if ($pos !== false) {
$theErrorEmailEntity = $em->getRepository('App\Entity\ErrorAndroidEmailSent')->findBy(['errorMsg' => $error]);
$theErrorEmailEntity = $theErrorEmailEntity[0];
break;
}
}
$body = "<p><label>Server: <strong>http://" . $this->realContainer->getParameter("licensor_base_url") . "/licensor/login</strong></label><br></p>";
$body .= "<p><label>" . $params['nickname'] . "</label></p><br>";
$body .= "<p><label><strong>Error: </strong></label><br></p><p><label>" . nl2br($params['msg']) . "</label></p><br>";
$actualDate = Utilx::getCurrentDate();
if(!empty($theErrorEmailEntity)){
$theErrorEmailEntity->setDateErrorLastReport($actualDate);
$theErrorEmailEntity->setErrorCounter(1 + (int) $theErrorEmailEntity->getErrorCounter());
$em->persist($theErrorEmailEntity);
$em->flush();
} else {
$androidErrorCode = $em->getRepository('App\Entity\ErrorAndroidEmailSent')->findRegisteredErrorCodeLicense();
++$androidErrorCode;
if (!empty($accountLicenseData)) {
$theErrorEmailEntity = $this->setRegistErrorEmail($accountLicenseData[0], $sendEmail[0], $errorMsg, $params['uid'], $androidErrorCode);
} else {
$theErrorEmailEntity = $this->setRegistErrorEmail(null, $sendEmail[0], $errorMsg, $params['uid'], $androidErrorCode, $subLicenseData[0]);
}
$body .= "<p><label><strong>Error Code: </strong></label><br></p><p><label>" . $theErrorEmailEntity->getErrorCode() . "</label></p>";
if ($accountLicenseData[0]) {
$respArray['subject'] = 'Error In ' . $params['nickname'] . ' ' . $theErrorEmailEntity->getErrorCode();
} else {
$respArray['subject'] = 'Error ' . $theErrorEmailEntity->getErrorCode();
}
$respArray['message'] = "";
$this->createFileJson($path, "Mail to -> " . $sendEmail[0] . "\r");
$respArray['to'] = $sendEmail[0];
Utilx::sendMailInfo($this->realContainer, $respArray, $path, $body);
$theErrorEmailEntity->setDateErrorEmailSent($actualDate);
$em->persist($theErrorEmailEntity);
$em->flush();
}
if (!empty($accountLicenseData)) {
$theAndroidErrorEntity = $this->setRegistAndroidError($theErrorEmailEntity,$accountLicenseData[0], $sendEmail[0], $params['msg'], $params['uid']);
} else {
$theAndroidErrorEntity = $this->setRegistAndroidError($theErrorEmailEntity,null, $sendEmail[0], $params['msg'], $params['uid'], $subLicenseData[0]);
}
if(!is_null($theErrorEmailEntity->getErrorQualifier())){
if($theErrorEmailEntity->getErrorQualifier() >= ErrorAndroidEmailSent::ERROR_QUALIFIER_COMPARISON ){
if ($accountLicenseData[0]) {
$respArray['subject'] = 'Error In ' . $params['nickname'] . ' ' . $theErrorEmailEntity->getErrorCode();
} else {
$respArray['subject'] = 'Error ' . $theErrorEmailEntity->getErrorCode();
}
$body .= "<p><label><strong>Error Code: </strong></label><br></p><p><label>" . $theErrorEmailEntity->getErrorCode() . "</label></p>";
$respArray['message'] = "";
$this->createFileJson($path, "Mail to -> " . $sendEmail[0] . "\r");
$respArray['to'] = $sendEmail[0];
Utilx::sendMailInfo($this->realContainer, $respArray, $path, $body);
$theAndroidErrorEntity->setDateErrorEmailSent($actualDate);
$em->persist($theAndroidErrorEntity);
$em->flush();
}
}
$responseArray['status'] = WebService::CODE_SUCCESS;
$responseArray['msg'] = 'Server notified';
$theUrlTrSt = new RespondedNotificationPushTransformer($responseArray);
$jsonTransform = $theUrlTrSt->transform();
$this->createFileJson($path, 'The encoded ws response: ' . json_encode($responseArray) . "\r");
$jsonContent = json_encode($jsonTransform);
$this->createFileJson($path, 'The transform: ' . $jsonContent . "\r");
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} else {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS generico para que los dispositivos android envien su
* log por correo a los administradores del sistema
* @author Aealan Z <lrobledo@kijho.com> 13/07/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function notifyAndroidLog(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'notifyAndroidLog', 'notifyAndroidLog0.txt');
$this->createFileJson($path, 'Notify Android Log: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$this->createFileJson($path, 'The decrypted content: ' . $request->getContent() . "\r");
$params = json_decode($arrayEncryptResult['data'], true);
$this->createFileJson($path, 'The request array: ' . $arrayEncryptResult['data'] . "\r");
if (!isset($params['nickname']) || !isset($params['log']) || !isset($params['uid'])) {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$data = ['alLicenseUsername' => $params['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($data);
$data = ['channelName' => $params['nickname']];
$subLicenseData = $em->getRepository('App\Entity\SubLicense')->findBy($data);
$countResult = count($accountLicenseData) + count($subLicenseData);
if ($countResult > 0) {
if (!empty($accountLicenseData)) {
$theLicenses = $accountLicenseData[0];
$theUID = $accountLicenseData[0]->getDeviceUid();
} elseif (!empty($subLicenseData)) {
$theLicenses = $subLicenseData[0]->getLicense();
$theUID = $subLicenseData[0]->getDeviceUid();
}
if ($theLicenses->getAlAccountLicense()->getDeleted()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($theLicenses->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Inactive License', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($theUID != $params['uid']) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($params['log'] == '') {
return $this->setStatusCode(WebService::CODE_WRONG_ARGUMENTS)
->respondWithError('Empty log content', WebService::CODE_WRONG_ARGUMENTS);
}
$sendEmail = $this->realContainer->getParameter('level_emails_syncs_errors');
$isSameLog = false;
$sameLogs = $em->getRepository('App\Entity\LogAndroidEmailSent')->findBy(['logMsg' => $params['log']]);
if (!empty($sameLogs)) {
$isSameLog = true;
$theLogEmailEntity = $sameLogs[0];
} else {
$androidLogCode = $em->getRepository('App\Entity\LogAndroidEmailSent')->findRegisteredLogCodeLicense();
++$androidLogCode;
$numEmails = count($sendEmail);
for ($i = 0; $i < $numEmails; ++$i) {
if (!empty($accountLicenseData)) {
$theLogEmailEntity = $this->setRegistLogEmail($accountLicenseData[0], $sendEmail[$i], $params['log'], $params['uid'], $androidLogCode);
} else {
$theLogEmailEntity = $this->setRegistLogEmail(null, $sendEmail[$i], $params['log'], $params['uid'], $androidLogCode, $subLicenseData[0]);
}
}
}
$body = "<p><label>Server: <strong>http://" . $this->realContainer->getParameter("licensor_base_url") . "/login</strong></label><br></p>";
$body .= "<p><label>" . $params['nickname'] . "</label></p><br>";
$body .= "<p><label><strong>Log: </strong></label><br></p><p><label>" . nl2br($params['log']) . "</label></p><br>";
$respArray['subject'] = 'Android device log ' . $params['nickname'];
$respArray['message'] = "";
foreach ($sendEmail as $mailTo) {
$this->createFileJson($path, "Mail to -> " . $mailTo . "\r");
$respArray['to'] = $mailTo;
Utilx::sendMailInfo($this->realContainer, $respArray, $path, $body);
}
$responseArray['status'] = WebService::CODE_SUCCESS;
$responseArray['msg'] = 'Android log notified';
$theUrlTrSt = new RespondedNotificationPushTransformer($responseArray);
$jsonTransform = $theUrlTrSt->transform();
$this->createFileJson($path, 'The encoded ws response: ' . json_encode($responseArray) . "\r");
$jsonContent = json_encode($jsonTransform);
$this->createFileJson($path, 'The transform: ' . $jsonContent . "\r");
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} else {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS Para validar el logue de dispositivos tanto de licencias como de sublicencias,
* dado el caso de que sea necesario actualizar el dispositivo logueado,
* este sera notificado mediante la validacion de su logueo en este ws
* necesario para toda la aplicacion movil
* @author Aealan Z <lrobledo@kijho.com> 20/12/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function validateLogin(Request $request) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'validateLogin', 'validateLogin0.txt');
$this->createFileJson($path, "\r" . 'Validate Login: ' . $request->getContent() . "\r");
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$this->createFileJson($path, "\r" . 'arrayEncryptResult: ' . json_encode($arrayEncryptResult) . "\r");
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['version']) || !isset($data['uid'])) {
return $this->errorWrongArgs('Wrong Arguments!', WebService::CODE_WRONG_ARGUMENTS);
}
$this->createFileJson($path, 'The Client IP -> ' . $request->getClientIp() . "\r");
$dataToSearch = ['deviceUid' => $data['uid']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($dataToSearch);
if (empty($accountLicenseData)) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid UID', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if (isset($data['channelname'])) {
$dataToSearch = ['deviceUid' => $data['uid']];
$subLicenseData = $em->getRepository('App\Entity\SubLicense')->findBy($dataToSearch);
$countResult = count($accountLicenseData) + count($subLicenseData);
} else {
$countResult = count($accountLicenseData);
}
if ($countResult > 0) {
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('License is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if (isset($data['channelname']) && !empty($subLicenseData)) {
$licenseOrSublicenseToValidate = $subLicenseData[0];
} elseif (empty($subLicenseData) && isset($data['channelname'])) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid channelname', WebService::CODE_COULD_NOT_AUTHENTICATE);
} else {
$licenseOrSublicenseToValidate = $accountLicenseData[0];
}
if ((int) $this->realContainer->getParameter('device_recognition_by_ip_enabled') && $licenseOrSublicenseToValidate->getAndroidIP() == $request->getClientIp()) {
$licenseOrSublicenseToValidate->setTimesCheckedIP($licenseOrSublicenseToValidate->getTimesCheckedIP() + 1);
} else {
$licenseOrSublicenseToValidate->setAndroidIP($request->getClientIp());
$licenseOrSublicenseToValidate->setTimesCheckedIP(0);
}
if (isset($data['databaseSize'])) {
$licenseOrSublicenseToValidate->setAndroidDatabaseSize((int) $data['databaseSize']);
$licenseOrSublicenseToValidate->setLastUpdateOfDatabaseSize(new DateTime("now"));
if ((int) $data['databaseSize'] > (int) $this->realContainer->getParameter('max_android_database_size_to_consider_cleanse')) {
// $body = "<p><label>Server: <strong>http://" . $this->realContainer->getParameter("licensor_base_url") . "/licensor/login</strong></label><br></p>";
// $body .= "<p><label>License: <strong>" . $accountLicenseData[0] . "</strong></label></p>";
// $body .= "<p><label>Message: Database has a size of <strong>'" . Util::humanFilesize($data['databaseSize']) . "' </strong> and the Android server could be having an slow performance for this reason</label><br></p>";
// $respArray['subject'] = "Android database cleanse is needed for '" . $accountLicenseData[0]->getAlLicenseUsername() . "' license";
// $respArray['message'] = "";
// $sendEmail = $this->realContainer->getParameter('level_emails_support_warnings');
// foreach ($sendEmail as $mailTo) {
// $this->createFileJson($path, "Mail to -> " . $mailTo . "\r");
// $respArray['to'] = $mailTo;
// Utilx::sendMailInfo($this->realContainer, $respArray, $path, $body);
// }
// Inicio de lógica, validación de notificación.
$currentDate = Utilx::getCurrentDate();
$seed = $em->getRepository("App\Entity\NotificationInLicensorBell")->findOneBy(["context"=>NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_DATABASE_CLEANSE_NEEDED, "license"=>$accountLicenseData[0]]);
if(!is_null($seed)){
$dateMinusOneWeek = clone $currentDate;
$dateMinusOneWeek->modify('-1 week');
if ($dateMinusOneWeek>=$seed->getPickedtByValidatingCronDate()) {
$seed->setDateCreated($currentDate);
$seed->setPickedtByValidatingCronDate(null);
$seed->setNotificationMsg("License:" . $accountLicenseData[0] . "Database has a size of " . Util::humanFilesize($data['databaseSize']) . " and the Android server could be having an slow performance for this reason");
$em->persist($seed);
$em->flush();
}
}else{
$currentDate = Utilx::getCurrentDate();
$seed = new NotificationInLicensorBell();
$seed->setNotificationTitle('Android database cleanse is needed for ' . $accountLicenseData[0]->getAlLicenseUsername() . ' license');
$seed->setNotificationLabel(NotificationInLicensorBell::NOTIFICATION_TYPE_WARNING);
$seed->setNotificationMsg("License:" . $accountLicenseData[0] . "Database has a size of " . Util::humanFilesize($data['databaseSize']) . " and the Android server could be having an slow performance for this reason");
$seed->setDateCreated($currentDate);
$seed->setContext(NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_DATABASE_CLEANSE_NEEDED);
$seed->setLicense($accountLicenseData[0]);
$seed->setTypeRoleToNotify(NotificationInLicensorBell::ROLE_ADMINISTRATOR);
$em->persist($seed);
$em->flush();
}
// Fin de lógica, validación de notificación.
}
}
if(isset($data['numberOfSyncDataRecords']) || (isset($data["validateLogin"]) && $data["validateLogin"] == true)){
$licenseDataBaseEntity = $em->getRepository('App\Entity\LicenseDataBase')->findOneBy(['license' => $licenseOrSublicenseToValidate->getId()]);
$dataOptionsRoot = [
'dbname' => $licenseDataBaseEntity->getDbname(),
'user' => $licenseDataBaseEntity->getDbuser(),
'password' => $licenseDataBaseEntity->getDbpass(),
'host' => $licenseDataBaseEntity->getDbhost(),
'driver' => 'pdo_mysql',
];
$emLev = Util::emCreateConfiguration($this->realContainer, $dataOptionsRoot);
if (isset($data['numberOfSyncDataRecords'])) {
$licenseOrSublicenseToValidate->setNumberOfSyncDataRecords((int) $data['numberOfSyncDataRecords']);
// $licenseDataBaseEntity = $em->getRepository('App\Entity\LicenseDataBase')->findOneBy(['license' => $licenseOrSublicenseToValidate->getId()]);
// $dataOptionsRoot = [
// 'dbname' => $licenseDataBaseEntity->getDbname(),
// 'user' => $licenseDataBaseEntity->getDbuser(),
// 'password' => $licenseDataBaseEntity->getDbpass(),
// 'host' => $licenseDataBaseEntity->getDbhost(),
// 'driver' => 'pdo_mysql',
// ];
// $emLev = Util::emCreateConfiguration($this->realContainer, $dataOptionsRoot);
$configuracion = $emLev->getRepository('App\Structure\Configuracion')->find(1);
$configuracion->setNumberOfSyncDataRecords((int) $data['numberOfSyncDataRecords']);
$configuracion->setMaxRecordsSyncUpDown((int) $this->realContainer->getParameter('max_records_sync_up_down'));
$configuracion->setMaxRecordsSyncDownUp((int) $this->realContainer->getParameter('max_records_sync_down_up'));
$emLev->persist($configuracion);
$emLev->flush();
}
}
$em->persist($licenseOrSublicenseToValidate);
$em->flush();
try {
$theRespArray = Util::getLastVersionByJsonVersionFile($this->realContainer, $data['version'], true, $path);
} catch (\Exception $ex) {
$theRespArray['updateAppError'] = true;
}
try {
$theRespArrayTwo = Util::getLastVersionByDirAvailableVersions($this->realContainer, $data['version'], true, $path);
} catch (\Exception $ex) {
$theRespArrayTwo['updateAppError'] = true;
}
if (isset($theRespArray['updateAppError']) && $theRespArray['updateAppError'] && isset($theRespArrayTwo['updateAppError']) && $theRespArrayTwo['updateAppError']) {
return $this->setStatusCode(WebService::HTTP_CODE_SERVICE_UNAVAILABLE)
->respondWithError('Error finding last version', WebService::CODE_OBJECT_NOT_FOUND);
}
if (isset($theRespArray["newVersion"]) && isset($theRespArrayTwo["newVersion"])) {
if ($theRespArray["newVersion"] < $theRespArrayTwo["newVersion"]) {
$theRespArray = $theRespArrayTwo;
}
} elseif (!isset($theRespArray["newVersion"]) && isset($theRespArrayTwo["newVersion"])) {
$theRespArray = $theRespArrayTwo;
}
if (isset($data['version'])) {
if (strpos($data['version'], '-')) {
$this->createFileJson($path, 'Is a testing version...? ' . $data['version'] . "\r");
$data['version'] = explode('-', $data['version'])[0];
}
}
ForcedAsynchronousCommandsUtil::recoveryInformationInProyects($this->realContainer, ['licenseId' => $accountLicenseData[0]->getId(), 'mode' => 0]);
if (isset($theRespArray['newVersion'])) {
$newVersionString = Util::validateNewerVersion($data['version'], $theRespArray['newVersion']);
if ($newVersionString == $theRespArray['newVersion'] && $newVersionString != $data['version']) {
$country = $accountLicenseData[0]->getCity()->getCiState()->getStCountry()->getCoVal();
$isCallCenter = $accountLicenseData[0]->getIsCallCenter();
$theRespArray['success'] = WebService::CODE_SUCCESS;
$theRespArray['country'] = $country;
$theRespArray['iscallcenter'] = (int) $isCallCenter;
$theUrlTrSt = new UpdateAndroidCommandTransformer($this->realContainer, $theRespArray);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
$newVersionString = Util::validateNewerVersion($accountLicenseData[0]->getAndroidVersionName(), $data['version']);
if (!isset($theRespArray["newVersion"]) && $newVersionString != $accountLicenseData[0]->getAndroidVersionName() && preg_match('/^(\d+\.)(\d+\.)(\d+)$/', $data['version'])) {
$body = "<p><label>Server: <strong>http://" . $this->realContainer->getParameter("licensor_base_url") . "/licensor/login</strong></label><br></p>";
$body .= "<p><label><strong>" . $accountLicenseData[0]->getAlLicenseUsername() . "</strong></label></p>";
$body .= "<p><label>The server has been updated from version: <strong>" . $accountLicenseData[0]->getAndroidVersionName() . "</strong> to version: <strong>" . $data['version'] . "</strong></label><br></p>";
$respArray['subject'] = 'Android APK version updated ' . $accountLicenseData[0]->getAlLicenseUsername();
$respArray['message'] = "";
$accountLicenseData[0]->setAndroidVersionName($data['version']);
$accountLicenseData[0]->setVersionUpdatedDate(Util::getCurrentDate());
$em->persist($accountLicenseData[0]);
$em->flush();
$sendEmail = $this->realContainer->getParameter('level_emails_syncs_errors');
foreach ($sendEmail as $mailTo) {
$this->createFileJson($path, "Mail to -> " . $mailTo . "\r");
$respArray['to'] = $mailTo;
Utilx::sendMailInfo($this->realContainer, $respArray, $path, $body);
}
$pushSendRepository = $em->getRepository('App\Entity\PushSent');
$pushSendRepository->respondOldPushesForLicense(PushSent::PUSH_TYPE_APK_UPDATE, $accountLicenseData[0]->getId());
}
if ($data['version']) {
$connectionRecord = $em->getRepository('App\Entity\AccountLicense')->getTheLastesVersionRegisteredInDataBaseByWorkingAPKs();
$newVersionString = Util::getDifferenceBetweenVersion($this->realContainer->getParameter('max_difference_in_APK_server_version_allowed'), $data['version'], $connectionRecord['androidVersionName']);
if (is_array($newVersionString) && isset($newVersionString['needsEmail']) && $newVersionString['needsEmail']) {
// $body = "<p><label>Server: <strong>http://" . $this->realContainer->getParameter("licensor_base_url") . "/licensor/login</strong></label><br></p>";
// $body .= "<p><label>License: <strong>" . $accountLicenseData[0] . "</strong></label></p>";
// $body .= "<p><label>License Version: <strong>" . $data['version'] . "</strong></label></p>";
// $body .= "<p><label>Newer Version In Use: <strong>" . $connectionRecord['androidVersionName'] . "</strong></label></p>";
// $body .= "<p><label>Message: <strong>" . sprintf($newVersionString['versionResult'], "'" . $accountLicenseData[0] . "'") . "</strong></label><br></p>";
// $respArray['subject'] = "Android APK needs an immediate update for '" . $accountLicenseData[0]->getAlLicenseUsername() . "' license";
// $respArray['message'] = "";
// $sendEmail = $this->realContainer->getParameter('level_emails_support_warnings');
// foreach ($sendEmail as $mailTo) {
// $this->createFileJson($path, "Mail to -> " . $mailTo . "\r");
// $respArray['to'] = $mailTo;
// Utilx::sendMailInfo($this->realContainer, $respArray, $path, $body);
// }
// Inicio de lógica, validación de notificación.
if(!$accountLicenseData[0]->getIsTesting()){
$currentDate = Utilx::getCurrentDate();
$seed = $em->getRepository("App\Entity\NotificationInLicensorBell")->findOneBy(["context" => NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_UPDATE_NEEDED, "license" => $accountLicenseData[0]]);
if(!is_null($seed)){
$dateMinusOneWeek = clone $currentDate;
$dateMinusOneWeek->modify('-1 week');
if ($dateMinusOneWeek >= $seed->getPickedtByValidatingCronDate()) {
$seed->setDateCreated($currentDate);
$seed->setPickedtByValidatingCronDate(null);
$seed->setNotificationMsg("License:" . $accountLicenseData[0] . "License Version:".$data['version'] ."Newer Version In Use:" .$connectionRecord['androidVersionName'] ."Message:" . sprintf($newVersionString['versionResult'], "'" . $accountLicenseData[0] . "'"));
$em->persist($seed);
$em->flush();
}
}else{
$seed = new NotificationInLicensorBell();
$seed->setNotificationTitle('Android APK needs update for ' . $accountLicenseData[0]->getAlLicenseUsername() . ' license');
$seed->setNotificationLabel(NotificationInLicensorBell::NOTIFICATION_TYPE_WARNING);
$seed->setNotificationMsg("License:" . $accountLicenseData[0] . "License Version:".$data['version'] ."Newer Version In Use:" .$connectionRecord['androidVersionName'] ."Message:" . sprintf($newVersionString['versionResult'], "'" . $accountLicenseData[0] . "'"));
$seed->setDateCreated($currentDate);
$seed->setContext(NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_UPDATE_NEEDED);
$seed->setLicense($accountLicenseData[0]);
$seed->setTypeRoleToNotify(NotificationInLicensorBell::ROLE_ADMINISTRATOR);
$em->persist($seed);
$em->flush();
}
}
}
// Fin de lógica, validación de notificación por una semana.
}
if(isset($data["debug"]) && $data["debug"]){
dump((isset($emLev) && !empty($emLev)));
dump(isset($emLev) && $emLev);
dump($emLev, isset($emLev), !empty($emLev));
}
if (isset($emLev) && !empty($emLev)) {
$clienteForWebAndroidLogin = $emLev->getRepository('App\Structure\Usuario')->findBy(['usuLogin' => 'admin']);
$auxArrayUserAndroidWebLogin = [];
if (isset($clienteForWebAndroidLogin[0])) {
$auxArrayUserAndroidWebLogin['user'] = 'admin';
$auxArrayUserAndroidWebLogin['pass'] = $clienteForWebAndroidLogin[0]->getUsuPass();
$auxArrayUserAndroidWebLogin['nickname'] = $accountLicenseData[0]->getAlLicenseUsername();
}
$pushServicesKeysArray = Util::buildTheServicesKeysArray($this->realContainer, $accountLicenseData[0], $auxArrayUserAndroidWebLogin);
} else {
$pushServicesKeysArray = Util::buildTheServicesKeysArray($this->realContainer, $accountLicenseData[0]);
}
if ($accountLicenseData[0]->getLevelLightUser()) {
$userData = $accountLicenseData[0]->getLevelLightUser();
/**
* Allows to add the apikey to the user of lite level this exported in OMT
*/
if ($accountLicenseData[0]->getHasLogedOMT() == true) {
$apikey = Util::doOMTDashboardLoginToGetToken($this->realContainer, $userData, $path, $accountLicenseData[0]->getLoginType());
if (!empty($apikey)) {
$userData['apikey'] = $apikey;
$responseArr['userToOmt']['apikey'] = $apikey;
} else {
$responseArr['userToOmt']['apikey'] = '';
}
$accountLicenseData[0]->setLevelLightUser($userData);
$em->persist($accountLicenseData[0]);
$em->flush();
} else {
$responseArr['userToOmt']['apikey'] = '';
}
$responseArr['userToOmt']['username'] = $userData['username'];
$responseArr['userToOmt']['password'] = $userData['realPass'];
}
if ($accountLicenseData[0]->getAwsTopicARN() && $accountLicenseData[0]->getAwsTopicARN() != '' && $accountLicenseData[0]->getAwsTopicARN() != "" ) {
if (isset($pushServicesKeysArray['awsPush'])) {
$pushServicesKeysArray['awsPush']['TopicArn'] = $accountLicenseData[0]->getAwsTopicARN();
}
}
///////
if ($accountLicenseData[0]->getNeedsOneUpdaownSync()) {
ForcedAsynchronousCommandsUtil::callPriorityUpDownSync($this->realContainer, ['license' => $accountLicenseData[0]->getId()], true);
//// podria ser el llamdo con prioridad que se haga desde aca, toca verificar la prioridad en cuanto al funcionamiento general de sync
}
///////
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['push_services'] = $pushServicesKeysArray;
$responseArr['msg'] = 'Valid login and actual apk version installed!';
$responseArr['url'] = '';
$responseArr['directoryOmtS3'] = [
'directoryImageProduct' => $this->realContainer->getParameter('AWS_ENVIRONMENT_FOLDER') . 'images/product',
'directoryImageRestaurant' => $this->realContainer->getParameter('AWS_ENVIRONMENT_FOLDER') . 'images/restaurant'
];
$accountLicenseData[0]->setLastValidatedLoginDate(Util::getCurrentDate());
if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_OUT) {
$accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_ANDROID);
} else if ($accountLicenseData[0]->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_LITE) {
$accountLicenseData[0]->setLoginType(AccountLicense::LOGGED_BY_LEVEL_LITE_AND_ANDROID);
}
$em->persist($accountLicenseData[0]);
$em->flush();
// Se valida que el parametro timeZone exista para guardarlo en las Tablas Configuracion y AccountLicense
if (isset($data['timeZone']) && trim($data['timeZone']) !== '') {
$timeZone = trim($data['timeZone']);
$configuracion = $emLev->getRepository('App\Structure\Configuracion')->findAll();
if (isset($configuracion[0])) {
$configuracion[0]->setTimeZoneRes($timeZone);
$emLev->persist($configuracion[0]);
$emLev->flush();
}
$accountLicenseData[0]->setTimeZoneRes($timeZone);
$em->persist($accountLicenseData[0]);
$em->flush();
}
$theUrlTrSt = new DemoForLoginTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid UID', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} else {
$this->createFileJson($path, "\r" . 'Wrong Content.', WebService::CODE_WRONG_ARGUMENTS . "\r");
return $this->errorWrongArgs('Wrong Content.', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
$this->createFileJson($path, "\r" . 'Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method" . "\r");
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS Para validar giftcards segun la licencia, el estado de esta y el
* saldo registrado en licensor
* @author Aealan Z <lrobledo@kijho.com> 02/02/16
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function giftCardTransaction(Request $request, ArmorService $armor, Log $log) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'GiftCardTransaction', 'GiftCardTransaction0.txt');
// validacion del metodo de peticion POST
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
// Validacion de tamaño en contenido, validacion de datos nulos - vacios
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
$this->createFileJson($path, "\r" . 'Validate GiftCard: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
// Datos desencriptados
$data = json_decode($arrayEncryptResult['data'], true);
$em = $this->getDoctrine()->getManager();
$worksWithArmor = false;
//////
/*
*
{
"nickname": "noonansb_206",
"uid": "5ad093af8070f25f",
"type": 1,
"order_id": "720b4297-90df-4c2a-b06b-d9c0815390f5",
"amount": 25,
"gift_code": "8814"
}
{
"nickname":"blackdoc_28",
"uid":"coquitoXX",
"token":"ElTokenCochinoEse"
}
*
*
{
"gift_card_id":"3b02add2-e376-11e8-853e-0242ac130004", // primaria en la bd de licensor
"issuing": "406b63b7-9ad6-4327-9af9-bdbca33ee637", // usuario al que pertenece la giftCard
"number": "6",
"balance": "4800",
"activation_date": "1409175049",
"deactivation_date": "1509175049",
"identifier": "b07b77b7-7ad7-7777-7af7-bdbca77ee77", // no se sabe para que putas, me la invento y ya
"status": "1"
}
*
*/
if (isset($data['token']) && base64_encode(base64_decode($data['token'])) === $data['token']) {
$decodeJWT = json_decode(Encryptor::decodeInfo($data['token'], 5), true);
$armorGiftCodeToSearch = $decodeJWT['number'];
$data['amount'] = Encryptor::decodeInfo($decodeJWT['balance'], 5);
$data['gift_code'] = Encryptor::decodeInfo($decodeJWT['number'], 5);
$data['order_id'] = $decodeJWT['order_id'];
$data['type'] = $decodeJWT['type'];
$data['identifier'] = $decodeJWT['identifier'];
$data['activation_date'] = $decodeJWT['activation_date'];
$client = $em->getRepository('App\Entity\OmtClient')->find($decodeJWT['issuing']);
if (!$client) {
return $this->errorWrongArgs('Customer not found!', WebService::CODE_OBJECT_NOT_FOUND);
}
$worksWithArmor = true;
}
if (((!isset($data['nickname']) || !isset($data['uid']) || !isset($data['type'])
|| !isset($data['amount']) || !isset($data['gift_code'])) && !$worksWithArmor)
|| ($worksWithArmor && !isset($data['token']))) {
$this->createFileJson($path, 'Error: Wrong Arguments!' . "\r");
return $this->errorWrongArgs('Wrong Arguments!', WebService::CODE_WRONG_ARGUMENTS);
}
if (!is_numeric($data['amount']) || !is_numeric($data['type']) || $data['gift_code'] == '') {
$this->createFileJson($path, 'Error: Wrong Type Arguments!' . "\r");
return $this->errorWrongArgs('Wrong Type Arguments!', WebService::CODE_WRONG_ARGUMENTS);
}
$dataToSearch = ['alLicenseUsername' => $data['nickname']];
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($dataToSearch);
if (empty($accountLicenseData)) {
$this->createFileJson($path, 'Error: Invalid nickname' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
} else {
$gcStatus = $accountLicenseData[0]->getGiftCardStatus();
if (!$gcStatus) {
$this->createFileJson($path, "The restaurant has no active gift card payments \r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('The restaurant has no active gift card payments', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
$this->createFileJson($path, 'Error: Account is inactive' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
$this->createFileJson($path, 'Error: License is inactive' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('License is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
$licenseToValidate = $accountLicenseData[0];
if ($licenseToValidate->getDeviceUid() != $data['uid']) {
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
$registeredClientsByUID = $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $data['uid']]);
if (empty($registeredClientsByUID)) {
$emLev->close();
$this->createFileJson($path, 'Error: Unknown device' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Unknown device', WebService::CODE_UNAUTHORIZED);
} else {
$emLev->close();
}
}
$actualDate = Util::getCurrentDate();
$responseArr['bigbag'] = true;
if (isset($data['transaction_id']) && $data['transaction_id'] != ''
&& (GiftCardTransaction::TRANSACTION_TYPE_BUY_WITH_GIFTCARD == (int) $data['type']
|| GiftCardTransaction::TRANSACTION_TYPE_REFUND_GIFTCARD == (int) $data['type'])) {
$giftCardTransaction = $em->getRepository('App\Entity\GiftCardTransaction')->find($data['transaction_id']);
} else {
$giftCardTransaction = new GiftCardTransaction();
}
if (!$giftCardTransaction) {
$this->createFileJson($path, 'GiftCard transaction not found in licensor!' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('GiftCard transaction not found!', WebService::GIFTCARD_WS_STATUS_GIFTCARD_TRANSACTION_NOT_FOUND_ERROR);
}
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
$theTransactionType = $data['type'];
$levelWebGiftCardRepo = $emLev->getRepository('App\Structure\GiftCard');
$doGiftCardLogRecord = true;
if ($worksWithArmor && GiftCardTransaction::TRANSACTION_TYPE_NEW_GIFTCARD != (int) $data['type']) {
$log->createChannel('gift_card');
$url = $this->getParameter('armor_host') . "gift/gift-cards/" . $decodeJWT['number'] . "/number";
$dataResponse = $armor->armorGet($request, $url, $log);
if (!isset($dataResponse['id'])) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Giftcard not found in Armor!', WebService::GIFTCARD_WS_STATUS_GIFTCARDNOTFOUND_ERROR);
}
$giftCardRecord = $em->getRepository('App\Entity\GiftCard')->findBy(['gcVerificationCode' => $dataResponse['id']]);
if (empty($giftCardRecord)) {
$giftCardRecord = $em->getRepository('App\Entity\GiftCard')->findBy(['gcVerificationCode' => $data['nickname'] .'-'. $dataResponse['id']]);
}
$amountInArmor = Encryptor::decodeInfo($dataResponse['balance'], 5);
if (isset($giftCardRecord[0]) && $amountInArmor != $giftCardRecord[0]->getGcAmount()) {
$this->createFileJson($path, 'Different GT amount error!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' . "\r");
$this->createFileJson($path, 'Armor amount -> ' . $amountInArmor . "\r");
$this->createFileJson($path, 'Licensor amount -> ' . $giftCardRecord[0]->getGcAmount() . "\r");
$giftCardRecord[0]->setGcAmount($amountInArmor);
$em->persist($giftCardRecord[0]);
$em->flush();
} elseif (!isset($giftCardRecord[0])) {
$this->createFileJson($path, 'GiftCard not found in Licensor A!!!' . $giftCardRecord[0]->getGcAmount() . "\r");
return $this->errorWrongArgs('GiftCard not found!', WebService::CODE_OBJECT_NOT_FOUND);
}
$data['gift_code'] = $dataResponse['id'];
} else {
$otherAuxGiftcardCode = $data['nickname'] .'-'. $data['gift_code'];
$giftCardRecord = $em->getRepository('App\Entity\GiftCard')->findBy(['gcVerificationCode' => $otherAuxGiftcardCode]);
if (empty($giftCardRecord)) {
$giftCardRecord = $em->getRepository('App\Entity\GiftCard')->findOneBy(['gcVerificationCode' => $data['gift_code']]);
if ($giftCardRecord && $giftCardRecord->getGcCreatorLicense()->getId() != $accountLicenseData[0]->getId()) {
$giftCardRecord = null;
$this->createFileJson($path, 'New giftcard with same base code as other licence ' . $data['gift_code'] . "\r");
} else {
$this->createFileJson($path, 'Redy for a very new giftcard with base code ' . $data['gift_code'] . "\r");
}
}
if (isset($data['debug'])) {
dump($giftCardRecord);
}
}
if (GiftCardTransaction::TRANSACTION_TYPE_NEW_GIFTCARD == (int) $data['type'] && empty($giftCardRecord)) {
$this->createFileJson($path, 'New GiftCard to licensor ' . "\r");
$theGiftCard = new GiftCard();
$theGiftCard->setGcAmount($data['amount']);
$theGiftCard->setGcVerificationCode($data['nickname'] .'-'. $data['gift_code']);
$theGiftCard->setGcReleaseDate($actualDate);
if (isset($data['activation_date'])) {
try {
$theGiftCard->setGcActivateDate(new DateTime($data['activation_date']));
} catch (\Exception $ex) {
$theGiftCard->setGcActivateDate(new DateTime('now'));
}
} else {
$theGiftCard->setGcActivateDate(new DateTime('now'));
}
if (isset($data['status'])) {
$theGiftCard->setGcStatus(GiftCard::STATUS_DEACTIVATE);
} else {
$theGiftCard->setGcStatus(GiftCard::STATUS_ACTIVE);
}
$theGiftCard->setGcCreatorLicense($licenseToValidate);
$theGiftCard->setGcAccount($licenseToValidate->getAlAccountLicense());
$em->persist($theGiftCard);
$em->flush();
if ($worksWithArmor) {
$decodeJWT['gift_card_id'] = $theGiftCard->getId();
$decodeJWT['identifier'] = $theGiftCard->getId();
$decodeJWT['balance'] = Encryptor::encodeInfo($data['amount'], 5);
$token = Encryptor::encodeInfo(json_encode($decodeJWT));
$request = $armor->duplicateRequestWithOverwritedContentForArmorServer($request, ['token' => $token]);
$log->createChannel('gift_card');
$url = $this->getParameter('armor_host') . "gift/add-gift-card";
$dataResponse = $armor->armorPost($request, $url, $log);
if ($dataResponse instanceof Response) {
$jsonResponse = $dataResponse->getContent();
$decodedResponse = json_decode($jsonResponse, true);
$neededArmorId = $data['nickname'] .'-'. $decodedResponse['data']['gift_card_id'];
$data['gift_code'] = $neededArmorId;
$theGiftCard->setGcVerificationCode($neededArmorId);
$em->persist($theGiftCard);
$em->flush();
}
}
$giftCardWebData = new stdClass();
$giftCardWebData->gift_status = $data['type'];
$giftCardWebData->gift_price = $data['amount'];
$giftCardWebData->gift_code = $data['gift_code'];
$giftCardWebData->gift_date = $actualDate->format('Y-m-d H:i:s');
$giftCardWebData->licId = $theGiftCard->getId();
$giftCardWebData->id = UUIDGeneratorUtil::getUUIDv4();
$this->createFileJson($path, 'Ready to insert GiftCard into license database -> ' . json_encode($giftCardWebData) . "\r");
$emLevCreatorGiftCard = $emLev;
$queryResponse = $levelWebGiftCardRepo->setDataUploadOne($this->realContainer, $giftCardWebData, $path);
if (is_array($queryResponse)) {
$responseArr['msg'] = 'GiftCard registed and activated successfully!!';
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_NEW_GIFTCARD_SUCCESS;
$this->createFileJson($path, 'New GiftCard registed successfully!' . "\r");
} else {
if (strpos($queryResponse, '1062 Duplicate entry') && strpos($queryResponse, $data['nickname'] .'-'. $data['gift_code'])) {
$responseArr['msg'] = "GiftCard with '" . $data['gift_code'] . "' code already registed in " . $accountLicenseData[0] . " restaurant" ;
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_GIFTCARD_ALREADY_REGISTED_ERROR;
$this->createFileJson($path, "GiftCard with '" . $data['gift_code'] . "' code already registed in " . $accountLicenseData[0] . " restaurant" . "\r");
} else {
$this->createFileJson($path, 'Error in licensor new Giftcard transaction! -> ' . $queryResponse . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError('Error in transaction!', WebService::GIFTCARD_WS_STATUS_TRANSACTION_ERROR);
}
}
} elseif (GiftCardTransaction::TRANSACTION_TYPE_NEW_GIFTCARD == (int) $data['type'] && !empty($giftCardRecord)) {
$this->createFileJson($path, 'Error: GiftCard already registed in licensor' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('GiftCard already registed!', WebService::GIFTCARD_WS_STATUS_GIFTCARD_ALREADY_REGISTED_ERROR);
} elseif (!empty($giftCardRecord) && $giftCardRecord[0]->getGcStatus() != GiftCard::STATUS_DEACTIVATE) {
$this->createFileJson($path, 'Searching old licensor giftcard...' . "\r");
if (!empty($giftCardRecord)) {
$this->createFileJson($path, 'Licensor giftcard found!' . "\r");
$theGiftCard = $giftCardRecord[0];
// if ($licenseToValidate->getAlAccountLicense()->getId() != $theGiftCard->getGcAccount()->getId()) {
// $this->createFileJson($path, 'Error: Giftcard of another franchise!' . "\r");
// return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
// ->respondWithError('Giftcard of another franchise!', WebService::GIFTCARD_WS_STATUS_GIFTCARD_OTHER_FRANCHISE_ERROR);
// }
if ($theGiftCard->getGcCreatorLicense()->getId() != $licenseToValidate->getId()) {
$emLevCreatorGiftCard = Util::emLicenseConnection($this->realContainer, $em, $licenseToValidate);
$levelWebGiftCardCreatorRepo = $emLevCreatorGiftCard->getRepository('App\Structure\GiftCard');
} else {
$emLevCreatorGiftCard = $emLev;
$levelWebGiftCardCreatorRepo = $levelWebGiftCardRepo;
}
switch ($data['type']) {
case GiftCardTransaction::TRANSACTION_TYPE_BUY_WITH_GIFTCARD:
$this->createFileJson($path, 'Transaction successfully!' . "\r");
if (isset($data['transaction_id'])) {
$theGiftCard->setGcLastTransactionDate($actualDate);
} else {
if (($theGiftCard->getGcAmount() - (double) $data['amount']) < 0.0) {
$this->createFileJson($path, 'Not eunogh founds in giftcard, transaction declined!' . "\r");
$responseArr['msg'] = 'Not eunogh founds in giftcard, transaction declined!';
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_TRANSACTION_ERROR;
$responseArr['amount'] = $theGiftCard->getGcAmount();
$responseArr['requestedAmount'] = $data['amount'];
$responseArr['isActive'] = (int) ((boolean) ($theGiftCard->getGcStatus() % GiftCard::STATUS_DEACTIVATE));
$responseArr['activationDate'] = "";
if ($theGiftCard->getGcActivateDate()) {
$responseArr['activationDate'] = $theGiftCard->getGcActivateDate()->format('Y-m-dTH:i:s');
}
$responseArr['lastTransactionDate'] = "";
if ($theGiftCard->getGcLastTransactionDate()) {
$responseArr['lastTransactionDate'] = $theGiftCard->getGcLastTransactionDate()->format('Y-m-dTH:i:s');
}
$responseArr['deactivationDate'] = "";
if ($theGiftCard->getGcDeactivateDate()) {
$responseArr['deactivationDate'] = $theGiftCard->getGcDeactivateDate()->format('Y-m-dTH:i:s');
}
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
$this->createFileJson($path, 'The WS Response -> ' . $jsonContent . "\r");
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
$theGiftCard->setGcAmount($theGiftCard->getGcAmount() - (double) $data['amount']);
}
}
$responseArr['msg'] = 'Transaction successfully!';
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_TRANSACTION_SUCCESS;
break;
case GiftCardTransaction::TRANSACTION_TYPE_RECHARGE_GIFTCARD:
$this->createFileJson($path, 'Recharge successfully!' . "\r");
$theGiftCard->setGcLastTransactionDate($actualDate);
$theGiftCard->setGcAmount($theGiftCard->getGcAmount() + (double) $data['amount']);
$responseArr['msg'] = 'Recharge successfully!';
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_RECHARGE_SUCCESS;
break;
case GiftCardTransaction::TRANSACTION_TYPE_REFUND_RECHARGE_GIFTCARD:
$this->createFileJson($path, 'Recharge canceled successfully!' . "\r");
$theGiftCard->setGcLastTransactionDate($actualDate);
$theGiftCard->setGcAmount($theGiftCard->getGcAmount() - (double) $data['amount']);
$responseArr['msg'] = 'Recharge canceled successfully!';
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_REFUND_RECHARGE_SUCCESS;
break;
case GiftCardTransaction::TRANSACTION_TYPE_REFUND_GIFTCARD:
$this->createFileJson($path, 'Refund successfully!' . "\r");
$theGiftCard->setGcLastTransactionDate($actualDate);
if (isset($data['transaction_id'])) {
$this->createFileJson($path, 'GiftCard if Refund!' . "\r");
$theGiftCard->setGcLastTransactionDate($actualDate);
$theRealTransactionAmount = $theGiftCard->getGcAmount() + (double) $data['amount'];
$giftCardTransaction->setGtTransactionAmount($data['amount']);
$theGiftCard->setGcAmount($theRealTransactionAmount);
} else {
$this->createFileJson($path, 'GiftCard else Refund!' . "\r");
$theGiftCard->setGcAmount($theGiftCard->getGcAmount() + (double) $data['amount']);
}
$responseArr['msg'] = 'Refund successfully!';
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_REFUND_SUCCESS;
break;
case GiftCardTransaction::TRANSACTION_TYPE_ADJUST_TRANSACTION:
$this->createFileJson($path, 'Try adjust order!' . "\r");
$theGiftCard->setGcLastTransactionDate($actualDate);
if (isset($data['transaction_id'])) {
$oldGiftCardTransaction = $em->getRepository('App\Entity\GiftCardTransaction')->find($data['transaction_id']);
$theRealTransactionAmount = $theGiftCard->getGcAmount() + $oldGiftCardTransaction->getGtTransactionAmount() - (double) $data['amount'];
$giftCardTransaction->setGtTransactionAmount($data['amount']);
$theGiftCard->setGcAmount($theRealTransactionAmount);
$responseArr['msg'] = 'Adjust successfully!';
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_ADJUST_SUCCESS;
}
break;
case GiftCardTransaction::TRANSACTION_TYPE_BUY_DEVOLUTION_GIFTCARD:
$this->createFileJson($path, 'Devolution successfully!' . "\r");
$theGiftCard->setGcLastTransactionDate($actualDate);
$theGiftCard->setGcAmount($theGiftCard->getGcAmount() + (double) $data['amount']);
$responseArr['msg'] = 'Devolution successfully!';
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_DEVOLUTION_SUCCESS;
break;
case GiftCardTransaction::TRANSACTION_TYPE_BUY_CANCELED_GIFTCARD:
$this->createFileJson($path, 'Cancelation successfully!' . "\r");
$theGiftCard->setGcLastTransactionDate($actualDate);
$theGiftCard->setGcAmount($theGiftCard->getGcAmount() + (double) $data['amount']);
$responseArr['msg'] = 'Cancelation successfully!';
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_CANCELATION_SUCCESS;
break;
case GiftCardTransaction::TRANSACTION_TYPE_INFORMATION_GIFTCARD:
$this->createFileJson($path, 'Information request!' . "\r");
$responseArr['msg'] = 'Information request!';
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_INFORMATION_SUCCESS;
break;
case GiftCardTransaction::TRANSACTION_TYPE_DISABLE_GIFTCARD:
$this->createFileJson($path, 'GiftCard Disabled...' . "\r");
$theGiftCard->setGcDeactivateDate($actualDate);
$theGiftCard->setIsDeactivationNotified(true);
$theGiftCard->setGcStatus(GiftCard::STATUS_DEACTIVATE);
$responseArr['msg'] = 'GiftCard Disabled!';
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_DISABLED_SUCCESS;
break;
default:
$data['type'] = GiftCardTransaction::TRANSACTION_TYPE_UNKNOWN_TRANSACTION;
$theTransactionType = $data['type'];
$this->createFileJson($path, 'Unknown Transaction...' . "\r");
$theGiftCard->setGcDeactivateDate($actualDate);
$theGiftCard->setIsDeactivationNotified(true);
$theGiftCard->setGcStatus(GiftCard::STATUS_DEACTIVATE);
$responseArr['msg'] = 'Unknown Transaction!';
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_UNKNOWN_TRANSACTION;
break;
}
} else {
$this->createFileJson($path, 'Error: Licensor Giftcard not found!' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Giftcard not found!', WebService::GIFTCARD_WS_STATUS_GIFTCARDNOTFOUND_ERROR);
}
$auxSearchingCode = $data['nickname'] . '-' . $data['gift_code'];
$this->createFileJson($path, 'Searching level GiftCard with code -> ' . $auxSearchingCode . "\r");
$levelGiftCard = $levelWebGiftCardCreatorRepo->findBy(['gcVerificationCode' => $auxSearchingCode]);
if (empty($levelGiftCard)) {
$this->createFileJson($path, 'Searching old level GiftCard with code -> ' . $data['gift_code'] . "\r");
$levelGiftCard = $levelWebGiftCardCreatorRepo->findBy(['gcVerificationCode' => $data['gift_code']]);
}
if (isset($data['debug'])) {
dump($theGiftCard);
dump($levelGiftCard);
}
if (empty($levelGiftCard)) {
$this->createFileJson($path, 'Level GiftCard not found, geting GiftCard from Licensor!' . "\r");
$giftCardWebData = Util::getStdClassForGiftCard($theGiftCard, true);
$giftCardWebData->id = UUIDGeneratorUtil::getUUIDv4();
$queryResponse = $levelWebGiftCardCreatorRepo->setDataUploadOne($this->realContainer, $giftCardWebData, $path);
} else {
$this->createFileJson($path, 'Level web GiftCard found!' . "\r");
$giftCardWebData = Util::getStdClassForGiftCard($theGiftCard, true);
$giftCardWebData->id = $levelGiftCard[0]->getId();
$this->createFileJson($path, 'Level web GiftCard id found -> ' . $levelGiftCard[0]->getId() . "\r");
$queryResponse = $levelWebGiftCardCreatorRepo->setDataUpdateUploadOne($this->realContainer, $levelGiftCard[0], $giftCardWebData, $path);
}
if (isset($data['debug'])) {
dump($queryResponse);
die;
}
if (!is_array($queryResponse) && GiftCardTransaction::TRANSACTION_TYPE_REFUND_RECHARGE_GIFTCARD != (int) $data['type']) {
// dump(strpos($queryResponse, '1062 Duplicate entry'));
// dump(strpos($queryResponse, $data['nickname'] .'-'. $data['gift_code']));
// die;
if (strpos($queryResponse, '1062 Duplicate entry') && strpos($queryResponse, $data['nickname'] .'-'. $data['gift_code'])) {
$responseArr['msg'] = "GiftCard with '" . $data['gift_code'] . "' code already registed in " . $accountLicenseData[0] . " restaurant" ;
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_GIFTCARD_ALREADY_REGISTED_ERROR;
$this->createFileJson($path, "GiftCard with '" . $data['gift_code'] . "' code already registed in " . $accountLicenseData[0] . " restaurant" . "\r");
} else {
$this->createFileJson($path, 'Error in licensor Giftcard transaction! -> ' . $queryResponse . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError('Error in transaction!', WebService::GIFTCARD_WS_STATUS_TRANSACTION_ERROR);
}
} elseif (!is_array($queryResponse)) {
$this->createFileJson($path, 'Error in licensor Giftcard recharge cancelation! -> ' . $queryResponse . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError('Error in recharge cancelation!', WebService::GIFTCARD_WS_STATUS_GIFTCARD_RECHARGE_CANCELATION_ERROR);
}
} elseif (!empty($giftCardRecord) && $giftCardRecord[0]->getGcStatus() == GiftCard::STATUS_DEACTIVATE) {
$doGiftCardLogRecord = false;
$theGiftCard = $giftCardRecord[0];
$responseArr['msg'] = 'GiftCard Disabled!';
$responseArr['status'] = WebService::GIFTCARD_WS_STATUS_DISABLED_SUCCESS;
$this->createFileJson($path, 'Deactivated GiftCard request found!' . "\r");
} elseif (empty($giftCardRecord) && GiftCardTransaction::TRANSACTION_TYPE_DISABLE_GIFTCARD == (int) $data['type']) {
$this->createFileJson($path, 'Error trying to disabled an unknown giftcard -> ' . "\r");
return $this->setStatusCode(WebService::CODE_ERR_CONFLICT)
->respondWithError('Error trying to disabled an unknown giftcard!', WebService::GIFTCARD_WS_STATUS_TRANSACTION_ERROR);
}
// else {
// $this->createFileJson($path, 'Error in licensor Giftcard recharge cancelation! -> ' . $queryResponse . "\r");
// return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
// ->respondWithError('Error in recharge cancelation!', WebService::GIFTCARD_WS_STATUS_GIFTCARD_RECHARGE_CANCELATION_ERROR);
// }
if (isset($data['debug'])) {
die;
}
if (GiftCardTransaction::TRANSACTION_TYPE_NEW_GIFTCARD != (int) $data['type']) {
$em->persist($theGiftCard);
$this->createFileJson($path, 'Licensor Giftcard updated!' . "\r");
if ($worksWithArmor) {
$log->createChannel('gift_card');
$urlData = [
'gift_card_id' => $theGiftCard->getGcVerificationCode(),
'identifier' => $theGiftCard->getId()
];
$paramToken = $armor->token($urlData);
$decodeJWT['gift_card_id'] = $theGiftCard->getId();
$decodeJWT['identifier'] = $theGiftCard->getId();
$decodeJWT['balance'] = Encryptor::encodeInfo($theGiftCard->getGcAmount(), 5);
$decodeJWT['status'] = $theGiftCard->getGcStatus();
$token = Encryptor::encodeInfo(json_encode($decodeJWT));
$request = $armor->duplicateRequestWithOverwritedContentForArmorServer($request, ['token' => $token]);
$url = $this->getParameter('armor_host') . 'gift/gift-cards/' . $paramToken . '/update';
$dataResponse = $armor->armorPut($request, $url, $log);
if ($dataResponse instanceof Response && $dataResponse->getStatusCode() != WebService::HTTP_CODE_SUCCESS) {
$jsonResponse = $dataResponse->getContent();
$decodedResponse = json_decode($jsonResponse, true);
$this->createFileJson($path, 'Unknown Armor error!!!! -> ' . $decodedResponse['data'] . "\r");
}
}
}
if ($doGiftCardLogRecord) {
$giftCardTransaction->setGtType($data['type']);
if (isset($data['order_id']) && $data['order_id'] != '') {
$giftCardTransaction->setGtOrder($data['order_id']);
}
if (isset($data['inv_id']) && $data['inv_id'] != '') {
$giftCardTransaction->setGtInvoice($data['inv_id']);
}
$giftCardTransaction->setGtTransactionAmount($data['amount']);
$giftCardTransaction->setGtGiftCard($theGiftCard);
$giftCardTransaction->setGtTransactionDate($actualDate);
$giftCardTransaction->setGtCreatorLicense($licenseToValidate);
$giftCardTransaction->setGtTotalAmount($theGiftCard->getGcAmount());
$em->persist($giftCardTransaction);
$this->createFileJson($path, 'Licensor GiftCardTransaction registed!' . "\r");
}
$em->flush();
if ($doGiftCardLogRecord && is_array($queryResponse)) {
$this->createFileJson($path, 'Preparing new GiftCardLog to level!' . "\r");
$levelGiftCardLogData = new stdClass();
$levelGiftCardLogData->gift_id = array_keys($queryResponse)[0];
$levelGiftCardLogData->licId = $giftCardTransaction->getId();
$levelGiftCardLogData->gifl_total = $theGiftCard->getGcAmount();
$levelGiftCardLogData->gifl_type = $theTransactionType;
$levelGiftCardLogData->gifl_price = $data['amount'];
if (isset($data['order_id']) && $data['order_id'] != '' ) {
$levelGiftCardLogData->ord_id = $data['order_id'];
}
if (isset($data['inv_id']) && $data['inv_id'] != '') {
$levelGiftCardLogData->inv_id = $data['inv_id'];
}
$levelGiftCardLogData->gift_code = $data['gift_code'];
$levelGiftCardLogData->gifl_date = $actualDate->format('Y-m-d H:i:s');
if (isset($data['transaction_id']) && (GiftCardTransaction::TRANSACTION_TYPE_BUY_WITH_GIFTCARD == (int) $data['type'] || GiftCardTransaction::TRANSACTION_TYPE_REFUND_GIFTCARD == (int) $data['type'])) {
$licesneGiftCardLogRecordToUpdate = $emLevCreatorGiftCard->getRepository('App\Structure\GiftCardLog')->findBy(['gclLicFk' => $giftCardTransaction->getId()]);
if (empty($licesneGiftCardLogRecordToUpdate)) {
$this->createFileJson($path, 'GiftCard log not found in license!' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError('GiftCard log not found!', WebService::GIFTCARD_WS_STATUS_GIFTCARD_LOG_NOT_FOUND_ERROR);
} else {
$licenseGiftCardLogOldRecord = $licesneGiftCardLogRecordToUpdate[0];
$queryResponse = $emLevCreatorGiftCard->getRepository('App\Structure\GiftCardLog')->setDataUpdateUploadOne($this->realContainer, $licenseGiftCardLogOldRecord, $levelGiftCardLogData, $path);
}
} else {
$levelGiftCardLogData->id = UUIDGeneratorUtil::getUUIDv4();
$queryResponse = $emLevCreatorGiftCard->getRepository('App\Structure\GiftCardLog')->setDataUploadOne($this->realContainer, $levelGiftCardLogData, $path);
}
$responseArr['gift_id'] = '';
if (!is_array($queryResponse)) {
$this->createFileJson($path, 'Error in level GiftCardLog transaction! -> ' . $queryResponse . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError('Error registering GiftCardLog!', WebService::GIFTCARD_WS_STATUS_GIFTCARDLOG_ERROR);
} else {
$this->createFileJson($path, 'The actual $queryResponse -> ' . json_encode($queryResponse) . "\r");
$responseArr['gift_id'] = array_keys($queryResponse)[0];
$this->createFileJson($path, 'GiftCardLog id to android -> ' . $responseArr['gift_id'] . "\r");
}
}
$responseArr['amount'] = $theGiftCard->getGcAmount();
$responseArr['transaction_id'] = $giftCardTransaction->getId();
$responseArr['isActive'] = (int) ((boolean) ($theGiftCard->getGcStatus() % GiftCard::STATUS_DEACTIVATE));
$responseArr['activationDate'] = "";
if ($theGiftCard->getGcActivateDate()) {
$responseArr['activationDate'] = $theGiftCard->getGcActivateDate()->format('Y-m-dTH:i:s');
}
$responseArr['lastTransactionDate'] = "";
if ($theGiftCard->getGcLastTransactionDate()) {
$responseArr['lastTransactionDate'] = $theGiftCard->getGcLastTransactionDate()->format('Y-m-dTH:i:s');
}
$responseArr['deactivationDate'] = "";
if ($theGiftCard->getGcDeactivateDate()) {
$responseArr['deactivationDate'] = $theGiftCard->getGcDeactivateDate()->format('Y-m-dTH:i:s');
}
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
$this->createFileJson($path, 'The WS Response -> ' . $jsonContent . "\r");
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
} else {
$this->createFileJson($path, 'Error: Wrong Content' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Wrong Content.', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
$this->createFileJson($path, 'Error: Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . "\r");
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS para notificar por correo electronico a los encargados de administrar el
* sistema y dar soporte con el fin de identificar si dicho dispositivo tiene
* algun inconveniente en el logueo ya sea licencia o sublicencia
* @author Aealan Z <lrobledo@kijho.com> 21/12/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function notifyDeviceInfo(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'notifyDeviceInfo', 'notifyDeviceInfo0.txt');
$this->createFileJson($path, 'Notify Device Info: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['version']) || !isset($data['uid'])) {
return $this->errorWrongArgs('Wrong Arguments!', WebService::CODE_WRONG_ARGUMENTS);
}
$dataToSearch = ['deviceUid' => $data['uid']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($dataToSearch);
$generalInfo = "<label>General Info: </label><br><br>";
$generalInfo .= "<label>Server: <strong>http://" . $this->realContainer->getParameter("licensor_base_url") . "/licensor/login</strong></label><br>";
$generalInfo .= "<label>Device UID: <strong>" . $data['uid'] . "</strong></label><br>";
if (!empty($accountLicenseData)) {
$generalInfo .= "<label>Last time used in: <strong>" . $accountLicenseData[0]->getAlLicenseUsername() . "</strong> license</label><br>";
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
$generalInfo .= "<label>Account <strong>" . $accountLicenseData[0]->getAlAccountLicense()->getAcName() . " </strong>incative</label><br>";
} else {
$generalInfo .= "<label>Account <strong>" . $accountLicenseData[0]->getAlAccountLicense()->getAcName() . " </strong>active</label><br>";
}
if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_ACTIVE) {
$generalInfo .= "<label>License <strong>active</strong><br></label>";
} else {
$generalInfo .= "<label>License <strong>incative</strong><br></label>";
}
} else {
$dataToSearch = ['deviceUid' => $data['uid']];
$subLicenseData = $em->getRepository('App\Entity\SubLicense')->findBy($dataToSearch);
if (!empty($subLicenseData)) {
$generalInfo .= "<label>Last time used in: <strong>" . $subLicenseData[0]->getChannelName() . "</strong> sublicense</label><br>";
if ($subLicenseData[0]->getLicense()->getAlAccountLicense()->getDeleted()) {
$generalInfo .= "<label>Account <strong>" . $subLicenseData[0]->getLicense()->getAlAccountLicense()->getAcName() . " </strong>incative</label><br>";
} else {
$generalInfo .= "<label>Account <strong>" . $subLicenseData[0]->getLicense()->getAlAccountLicense()->getAcName() . " </strong>active</label><br>";
}
if ($subLicenseData[0]->getLicense()->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_ACTIVE) {
$generalInfo .= "<label>License <strong>" . $subLicenseData[0]->getLicense()->getAlLicenseUsername() . " </strong>active</label><br>";
} else {
$generalInfo .= "<label>License <strong>" . $subLicenseData[0]->getLicense()->getAlLicenseUsername() . " </strong>incative</label><br>";
}
}
}
try {
$theRespArray = Util::getLastVersionByJsonVersionFile($this->realContainer, $data['version'], true, $path);
} catch (\Exception $ex) {
$theRespArray['updateAppError'] = true;
}
try {
$theRespArrayTwo = Util::getLastVersionByDirAvailableVersions($this->realContainer, $data['version'], true, $path);
} catch (\Exception $ex) {
$theRespArrayTwo['updateAppError'] = true;
}
if (isset($theRespArray['updateAppError']) && $theRespArray['updateAppError'] && isset($theRespArrayTwo['updateAppError']) && $theRespArrayTwo['updateAppError']) {
return $this->setStatusCode(WebService::HTTP_CODE_SERVICE_UNAVAILABLE)
->respondWithError('Error finding last version', WebService::CODE_OBJECT_NOT_FOUND);
}
if (isset($theRespArray["newVersion"]) && isset($theRespArrayTwo["newVersion"])) {
if ($theRespArray["newVersion"] < $theRespArrayTwo["newVersion"]) {
$theRespArray = $theRespArrayTwo;
}
} elseif (!isset($theRespArray["newVersion"]) && isset($theRespArrayTwo["newVersion"])) {
$theRespArray = $theRespArrayTwo;
}
$generalInfo .= "<label>APK version: <strong>" . $data['version'] . "</strong></label><br>";
if (isset($theRespArray['newVersion'])) {
$generalInfo .= "<label>New version available: <strong>" . $theRespArray['newVersion'] . "</strong></label><br>";
}
$emailsToNotify = $this->realContainer->getParameter('level_emails_syncs_errors');
$respArray['subject'] = "Device info request " . $data['uid'];
$respArray['message'] = "";
foreach ($emailsToNotify as $mailTo) {
$this->createFileJson($path, "Mail to -> " . $mailTo . "\r");
$respArray['to'] = $mailTo;
$emailSuccess = Utilx::sendMailInfo($this->realContainer, $respArray, $path, $generalInfo);
}
if (isset($emailSuccess['success']) && $emailSuccess['success']) {
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Info device data send!';
$responseArr['bigbag'] = true;
$responseArr['url'] = '';
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError('Erro notifiying device info by email!', WebService::CODE_INTERNAL_ERROR);
}
} else {
return $this->errorWrongArgs('Wrong Content.', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS para el boton de sincronizacion de arriba a abajo desde android
* @author Aealan Z <lrobledo@kijho.com> 30/10/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuestaa
*/
public function syncUpDownFromAndroid(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'syncUpDownFromAndroid', 'syncUpDownFromAndroid0.txt');
$this->createFileJson($path, 'Request content: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['nickname']) || !isset($data['uid'])) {
return $this->errorWrongArgs('Wrong arguments', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
$countResult = count($accountLicenseData);
$this->createFileJson($path, 'Request content: license count ' . $countResult . "\r");
if ($countResult > 0) {
$this->createFileJson($path, 'Request content: entro el chingo! ' . "\r");
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
return $this->errorWrongArgs('Account inactive, please contact your system manager', WebService::CODE_UNAUTHORIZED);
}
if (!$accountLicenseData[0]->getAlLicenseStatus()) {
return $this->errorWrongArgs('License inactive, please contact your system manager', WebService::CODE_UNAUTHORIZED);
}
if ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
return $this->errorWrongArgs('Unauthorized device', WebService::CODE_UNAUTHORIZED);
}
$arrHead = ['Content-Type: application/json'];
$dataToRequest = ["nickname" => Util::encodeInfo($data['nickname']), 'waitTime' => 0];
$dataPost = json_encode($dataToRequest);
$this->createFileJson($path, 'Request content: request to -> ' . $dataPost . "\r");
$url = $this->realContainer->getParameter('level_scheme') . '://' . $this->realContainer->getParameter('level_host') . $this->generateUrl('level_web_service_sync_data_web');
$this->createFileJson($path, 'Request content: request url -> ' . $url . "\r");
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $arrHead);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataPost);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$this->createFileJson($path, 'Request Response: ' . $response . "\r");
$responseData = Util::decryptDataForAndroid($this->realContainer, $response);
$responseDecData = json_decode($responseData['data']);
$responseArr['status'] = WebService::CODE_SUCCESS;
if (!empty($responseDecData->result) && $responseDecData->result == '__OK__') {
if (empty($responseDecData->msg)) {
$responseArr['status'] = 70;
$responseArr['msg'] = 'Synchronization triggered..';
} else {
$responseArr['status'] = 60;
$responseArr['msg'] = $responseDecData->msg;
}
$this->createFileJson($path, 'Request answered msg: ' . $responseArr['msg'] . "\r");
$idToWebSyncConsumer = $responseDecData->syncid;
$this->createFileJson($path, 'Searching sync with id: ' . $idToWebSyncConsumer . "\r");
$syncWebRecord = $em->getRepository('App\Entity\ReadFilesDataWeb')->find($idToWebSyncConsumer);
if ($syncWebRecord) {
sleep(4);
$this->createFileJson($path, 'Instant Request pre if -> ' . $syncWebRecord->getIsReadedByServer() . ' | ' . $syncWebRecord->getRfwStatus() . "\r");
if ($syncWebRecord->getIsReadedByServer() && ReadFilesDataWeb::STATUS_NOTIFIED == $syncWebRecord->getRfwStatus()) {
$em->clear();
$data['rwid'] = $syncWebRecord->getId();
ForcedAsynchronousCommandsUtil::consumeUpDownSyncCommand($this->realContainer, $data, true);
$this->createFileJson($path, 'Instant Request Proccessed!' . "\r");
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Server processing new data, please check for the new data in a few seconds!';
} else {
$responseArr['status'] = 80;
$responseArr['msg'] = 'Server is working... Please try 20 seconds latter!';
}
} else {
if ($idToWebSyncConsumer == 0) {
$this->createFileJson($path, 'Instant Request Push Resend.....' . "\r");
$responseArr['status'] = 90;
$responseArr['msg'] = 'Unanswered push by android server....';
} else {
$this->createFileJson($path, 'Instant Request Auch -> License sync web record not found!' . "\r");
return $this->setStatusCode(WebService::CODE_OBJECT_NOT_FOUND)
->respondWithError('License sync web record not found!', WebService::CODE_OBJECT_NOT_FOUND);
}
}
} else {
if (isset($response->error->message)) {
$responseArr['msg'] = $response->error->message;
} else {
$responseArr['status'] = 100;
$responseArr['msg'] = 'Nothing to synchronize';
}
}
$theUrlTrSt = new RespondedNotificationPushTransformer($responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_UNAUTHORIZED);
}
} else {
return $this->errorWrongArgs('Bad request', WebService::CODE_UNAUTHORIZED);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS que permite verificar el login de level lite
* @author Felipe Bautista <aarango@uva3.com> 10/04/2019
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function checkLoginLevel(Request $request) {
$em = $this->getDoctrine()->getManager();
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'checkLoginLevel', 'requestFromWebYYY0.txt');
$paramsIdLicense = $request->request->get('id_license');
if ($paramsIdLicense == null) {
$paramsIdLicense = $request->query->get('id_license');
}
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->find($paramsIdLicense);
if (isset($accountLicenseData)) {
if ($accountLicenseData->getLevelLightUser() !== "" && $accountLicenseData->getLevelLightUser() !== []) {
$userData = $accountLicenseData->getLevelLightUser();
$apikey = Util::doOMTDashboardLoginToGetToken($this->realContainer, $userData, $path, $accountLicenseData->getLoginType());
if (!empty($apikey)) {
$userData['apikey'] = $apikey;
$responseArr['apikey'] = $apikey;
} else {
$responseArr['apikey'] = '';
}
if (isset($responseArr['apikey']) || $accountLicenseData->getHasLogedOMT() == false) {
// $createDefaultUserOmt = Util::makeOMTDefaultDashboardsUserInsertRequest($this->realContainer, $userData, $path);
/**
* Allows to add the apikey to the user of lite level this exported in OMT
*/
if ($accountLicenseData->getHasLogedOMT() == true || $accountLicenseData->getIsLevelLight() == true) {
$accountLicenseData->setLevelLightUser($userData);
$em->persist($accountLicenseData);
$em->flush();
$responseToAjax['msg'] = 'Login successfull';
$responseToAjax['result'] = '__OK__';
}
$auxRepository = $em->getRepository('App\Entity\AccountLicense');
$connectionRecord = $auxRepository->find($paramsIdLicense);
$emLev = Util::emLicenseConnection($this->realContainer, $em, $connectionRecord);
$userLevelLite = $emLev->getRepository('App\Structure\Usuario')->findBy(['usuLogin' => $userData['username']]);
if (!isset($userLevelLite[0])) {
$responseToAjax['msg'] = (isset($responseToAjax['msg'])) ? $responseToAjax['msg'] . " and user level lite create" : "User level lite created";
$responseToAjax['result'] = '__OK__';
$levelUser = new Usuario();
$levelUser->setUsuNombre($userData['username']);
$levelUser->setUsuApellido($userData['username']);
$levelUser->setUsuTelefono($accountLicenseData->getAlPhoneNumber());
$levelUser->setUsuEmail($accountLicenseData->getAlLicenseEmail());
$levelUser->setUsuTipo(Usuario::USU_TYPE_MANAGER);
$levelUser->setUsuEstado(Usuario::STATUS_IS_ACTIVE);
$levelUser->setUsuLogin($userData['username']);
$levelUser->setUsuSalary(0.000000);
$actualDate = Util::getCurrentDate();
$levelUser->setUsuCreation($actualDate);
$encodeLevelWebPass = Util::encryptOwnReverseMD5($userData['realPass']);
$levelUser->setUsuPass($encodeLevelWebPass);
$levelUser->setUsuAccessCode($encodeLevelWebPass);
$levelUser->setUsuAcccessCode2($encodeLevelWebPass);
$levelUser->setUsuEmployecard($encodeLevelWebPass);
$levelUser->setUsuFirstLogin(1);
$emLev->persist($levelUser);
$emLev->flush();
} else if ($accountLicenseData->getHasLogedOMT() == false) {
$responseToAjax['msg'] = 'The level lite user exists on levelweb!';
$responseToAjax['result'] = '__OK__';
}
} else {
$responseToAjax['msg'] = 'Error in the login level lite!';
$responseToAjax['result'] = '__KO__';
}
} else {
$responseToAjax['msg'] = 'Level lite user not found!';
$responseToAjax['result'] = '__KO__';
}
} else {
$responseToAjax['msg'] = 'License Not Found!';
$responseToAjax['result'] = '__KO__';
}
return $this->respondJsonAjax($responseToAjax);
}
/**
* WS para el boton de sincronizacion all in one que realiza todas las
* en el orden correspondiente en cascada
* @author Aealan Zulalecius <lrobledo@kijho.com> 01/06/16
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function theUltimateSyncAllOneButton(Request $request) {
// dump($request);die;
// $start = microtime(true);
// while (false) {
// }
// $time_elapsed_secs = microtime(true) - $start;
//////////////
// $start = hrtime(true);
// sleep(5); // do something, in your case a loop
// $end = hrtime(true);
// $eta = $end - $start;
// // convert nanoseconds to milliseconds
// $eta /= 1e+6;
if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
if (0 !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) && 0 !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
return $this->errorWrongArgs('Bad request', WebService::CODE_UNAUTHORIZED);
}
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'UltimateSyncAllOneButton', 'UltimateSyncAllOneButton0.txt');
$this->createFileJson($path, "\r" . 'Sync all showtime! ' . "\r");
$this->createFileJson($path, 'The request -> ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['nickname']) || !isset($data['uid'])) {
return $this->errorWrongArgs('Wrong arguments', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
$countResult = count($accountLicenseData);
$this->createFileJson($path, 'License count -> ' . $countResult . "\r");
if ($countResult <= 0) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_UNAUTHORIZED);
}
$license = $accountLicenseData[0];
if ($license->getAlAccountLicense()->getDeleted()) {
$this->createFileJson($path, 'Deleted license! ' . "\r");
return $this->errorWrongArgs('Account inactive, please contact your system manager', WebService::CODE_UNAUTHORIZED);
}
if (!$license->getAlLicenseStatus()) {
$this->createFileJson($path, 'Incative license! ' . "\r");
return $this->errorWrongArgs('License inactive, please contact your system manager', WebService::CODE_UNAUTHORIZED);
}
if ($license->getDeviceUid() != $data['uid']) {
$this->createFileJson($path, 'Wrong UID -> espected: ' . $license->getDeviceUid() . ' found: ' . $data['uid'] . "\r");
return $this->errorWrongArgs('Unauthorized device', WebService::CODE_UNAUTHORIZED);
}
$syncAllCallStatus = $em->getRepository('App\Entity\SyncAllCallStatus')->syncCallStatusPerLicense($license);
if(!is_null($syncAllCallStatus) && $syncAllCallStatus->getPublishMessageStatus() == SyncAllCallStatus::SYNC_MESSAGE_ERROR && is_null($syncAllCallStatus->getDateNotified())){
$responseArr = json_decode($syncAllCallStatus->getErrorMessage(), true);
$syncAllCallStatus->setDateNotified(Utilx::getCurrentDate());
$em->persist($syncAllCallStatus);
$em->flush();
if (!isset($responseArr['status'])) {
$responseArr['status'] = WebService::CODE_OBJECT_NOT_FOUND;
}
return $this->setStatusCode($responseArr['status'])
->respondWithError($responseArr['msg'], $responseArr['status']);
} else if(!is_null($syncAllCallStatus) && $syncAllCallStatus->getPublishMessageStatus() == SyncAllCallStatus::SYNC_MESSAGE_FINISHED && is_null($syncAllCallStatus->getDateNotified())){
$responseArr = json_decode($syncAllCallStatus->getResponseBySync(), true);
$syncAllCallStatus->setDateNotified(Utilx::getCurrentDate());
$em->persist($syncAllCallStatus);
$em->flush();
$responseArr['msjTwo'] = $this->resultAndNewSync($path, $license, $data, $syncAllCallStatus, $em);
if (!isset($responseArr['status'])) {
$responseArr['status'] = WebService::CODE_SUCCESS;
}
} else if (is_null($syncAllCallStatus) || (!is_null($syncAllCallStatus) && ($syncAllCallStatus->getPublishMessageStatus() == SyncAllCallStatus::SYNC_MESSAGE_ERROR || $syncAllCallStatus->getPublishMessageStatus() == SyncAllCallStatus::SYNC_MESSAGE_FINISHED))) {
$responseArr = $this->resultAndNewSync($path, $license, $data, $syncAllCallStatus, $em);
} else if(!is_null($syncAllCallStatus) && ($syncAllCallStatus->getPublishMessageStatus() == SyncAllCallStatus::SYNC_MESSAGE_PROCESSING || $syncAllCallStatus->getPublishMessageStatus() == SyncAllCallStatus::SYNC_MESSAGE_PUBLISHED)){
$responseArr = ['msg' => 'You have a synchronization process running', 'status' => WebService::CODE_SUCCESS, 'result' => '__OK__', 'response_code' => WebService::CODE_SUCCESS];
} else {
if (!is_null($syncAllCallStatus)) {
$this->createFileJson($path, "wata fack, que estado tiiene sabiendo que abarque todas las condiciones, checar datos:
id: {$syncAllCallStatus->getId()} \n
publishMessageStatus: {$syncAllCallStatus->getPublishMessageStatus()} \n
errorMessage: {$syncAllCallStatus->getErrorMessage()} \n
responseBySync: {$syncAllCallStatus->getResponseBySync()} \n
\r");
} else {
$this->createFileJson($path, "wata fack, que estado tiiene sabiendo que abarque todas las condiciones, sync all call status es nulo !!!! \r");
}
$responseArr = ['msg' => 'Please contact with support', 'status' => WebService::HTTP_CODE_NOT_FOUND, 'result' => '__KO__'];
}
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
$this->createFileJson($path, 'The theUltimateSyncAllOneButton response -> ' . $jsonContent . "\r");
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
function resultAndNewSync($path, $license, $data, $syncAllCallStatus, $em) {
$dataToProducer = ['path' => $path, 'id' => $license->getId(), 'data' => $data, 'syncFullVersion' => SyncFullCallConsumer::SYNC_FULL_WEB_SERVICE_VERSION];
$this->realContainer->get('old_sound_rabbit_mq.sync_full_call_producer')->setContentType('application/json');
$this->realContainer->get('old_sound_rabbit_mq.sync_full_call_producer')->setDeliveryMode(2);
$this->realContainer->get('old_sound_rabbit_mq.sync_full_call_producer')->publish(json_encode($dataToProducer));
$counterNewPetition = 1;
if (is_null($syncAllCallStatus)) {
$syncAllCallStatus = new SyncAllCallStatus();
$syncAllCallStatus->setLicense($license->getId());
}else{
$counterNewPetition = $syncAllCallStatus->getCounterPetitions() + $counterNewPetition;
}
$syncAllCallStatus->setCounterPetitions($counterNewPetition);
$syncAllCallStatus->setPublishMessageStatus(SyncAllCallStatus::SYNC_MESSAGE_PUBLISHED);
$syncAllCallStatus->setDateChangeStatus(Utilx::getCurrentDate());
$syncAllCallStatus->setDateNotified(null); // Reiniciamos el campo desde el principio para que en realidad notifique
$em->persist($syncAllCallStatus);
$em->flush();
$command = "php ". $this->realContainer->getParameter('kernel.project_dir') ."/bin/console sync:call:consumer";
shell_exec("$command > /dev/null & echo!");
return ['msg' => 'You have a synchronization process running', 'status' => WebService::CODE_SUCCESS, 'result' => '__OK__', 'response_code' => WebService::CODE_SUCCESS];
}
/**
* @author Felipe Arango <aarango@uva3.com> 28/01/2021
* @param type $masterSyncRecord
* @param type $responseArr
* @param type $path
*/
public function resetSyncAll(Request $request) {
try {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET || $request->getMethod() === WebService::REQUEST_METHOD_POST) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'resetSync', 'resetSync0.txt');
$em = $this->getDoctrine()->getManager();
if ($request->getMethod() === WebService::REQUEST_METHOD_GET){
$this->createFileJson($path, 'get parameters => '. json_encode($request->query->all()) . "\r");
$nickname = $request->query->get("nickname");
}
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
$this->createFileJson($path, 'post parameters => '. $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
$nickname = $data['nickname'];
}
if ($nickname == null) {
$this->createFileJson($path, 'NicknName Undefined! ' . "\r");
return $this->errorWrongArgs('NicknName Undefined!', WebService::CODE_UNAUTHORIZED);
}
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findOneBy(["alLicenseUsername" => $nickname]);
if (isset($accountLicenseData)) {
if ($accountLicenseData->getAlAccountLicense()->getDeleted()) {
$this->createFileJson($path, 'Deleted license! ' . "\r");
return $this->errorWrongArgs('Account inactive, please contact your system manager', WebService::CODE_UNAUTHORIZED);
}
if (!$accountLicenseData->getAlLicenseStatus()) {
$this->createFileJson($path, 'Inactive license! ' . "\r");
return $this->errorWrongArgs('License inactive, please contact your system manager', WebService::CODE_UNAUTHORIZED);
}
$resultResetSync = $em->getRepository('App\Entity\MasterSync')->resetSyncByLicense($accountLicenseData->getId(), $accountLicenseData->getHasLogedOMT());
$licenseDataBaseEntity = $em->getRepository('App\Entity\LicenseDataBase')->findOneBy(['license' => $accountLicenseData->getId()]);
$dataOptionsRoot = [
'dbname' => $licenseDataBaseEntity->getDbname(),
'user' => $licenseDataBaseEntity->getDbuser(),
'password' => $licenseDataBaseEntity->getDbpass(),
'host' => $licenseDataBaseEntity->getDbhost(),
'driver' => 'pdo_mysql',
];
$emLev = Util::emCreateConfiguration($this->realContainer, $dataOptionsRoot);
$resultResetSync += $emLev->getRepository('App\Structure\RegistActions')->resetDataRegistAction();
$resultResetSync += $emLev->getRepository('App\Structure\Configuracion')->resetDataConfiguration();
$this->createFileJson($path, "rows affected -> $resultResetSync \r");
$responseArr['bigbag'] = true;
$responseArr['result'] = '__OK__';
$responseArr['msg'] = 'Successful synchronization reset';
$responseArr['status'] = WebService::CODE_SUCCESS;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
$this->createFileJson($path, 'Invalid nickname ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_UNAUTHORIZED);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_GET . " method or " . WebService::REQUEST_METHOD_POST . " method");
}
} catch (\Throwable $th) {
$err = ['Error message' => $th->getMessage(), 'Error Line' => $th->getLine(), 'Error File' => $th->getFile(), 'Error Trance' => $th->getTrace()];
$this->createFileJson($path, "error detected ". json_encode($err) ." \r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError($err, WebService::HTTP_CODE_INTERNAL_ERROR);
}
}
/**
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $masterSyncRecord
* @param type $responseArr
* @param type $path
*/
public function sendMailForUnansweredSyncPush($masterSyncRecord, $responseArr, $license, $path) {
$body = "<p><label>Server: <strong>http://" . $this->realContainer->getParameter("licensor_base_url") . "/licensor/login</strong></label><br></p>";
$theUnansweredPush = $masterSyncRecord[0]['msPushRecord'];
$type = 1;
if (!$theUnansweredPush) {
$type = 2;
}
if ($type == 1) {
$body .= "<label>Unanswered sync push detected...</label><br>";
$body .= "<label>Unanswered push id: <strong>" . $theUnansweredPush . "</strong></label><br>";
} else {
$body .= "<label>Unabled to send push...</label><br>";
}
$body .= "<label>Message delivered to android server <strong>" . $responseArr['msg'] . "</strong></label><br>";
$body .= "<label>Master Sync Number: <strong>" . $masterSyncRecord[0]['id'] . "</strong></label><br>";
$body .= "<label>License: <strong>" . $license . "</strong></label><br>";
$emailsToNotify = $this->realContainer->getParameter('level_emails_syncs_errors');
if ($type == 1) {
$respArray['subject'] = "Unanswered Sync Push In " . $license->getAlLicenseUsername() . " License";
} else {
$respArray['subject'] = "Unabled To Send Push To " . $license->getAlLicenseUsername() . " License Requested Sync";
}
$this->createFileJson($path, "The subject: " . $respArray['subject'] . "\r");
$respArray['message'] = "";
foreach ($emailsToNotify as $mailTo) {
$this->createFileJson($path, "Mail to -> " . $mailTo . "\r");
$respArray['to'] = $mailTo;
// Utilx::sendMailInfo($this->realContainer, $respArray, $path, $body);
}
}
/**
* Funcion polling que verifica si el push de sincronizacion de arriba a
* abajo fue enviado
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $masterSyncRecord registro maestro de la sincronizacion
* @return boolean indicando que el push de de la sincronizacion fue enviado
*/
public function checkForWebPushSend($masterSyncRecord, $path = null) {
$responseToPolling = [];
$auxCounter = 0;
$keepInWhile = true;
$masterSyncId = $masterSyncRecord['id'];
if (!is_null($path)) {
$this->createFileJson($path, 'Checking push send....' . "\r");
}
$em = $this->getDoctrine()->getManager();
do {
sleep(3);
++$auxCounter;
$masterSyncRecord = $em->getRepository('App\Entity\ReadFilesDataWeb')->getTheMasterSyncArrayRecordById($masterSyncId, true);
if (!is_null($path) && !empty($masterSyncRecord)) {
$this->createFileJson($path, "Checking push in'" . $masterSyncId . "' master sync record... \r");
$this->createFileJson($path, ".. and the push...? " . json_encode($masterSyncRecord[0]['msPushRecord']) . "\r");
}
if (!empty($masterSyncRecord) && is_null($masterSyncRecord[0]['msPushRecord']) && $auxCounter < 7) {
sleep(1);
$keepInWhile = true;
$responseToPolling['msg'] = 'Awaiting for push send....';
$responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
$responseToPolling['wasAnswered'] = true;
$responseToPolling['masterRecord'] = $masterSyncRecord[0];
} else {
if ($masterSyncRecord[0]['msPushRecord']) {
$keepInWhile = false;
$responseToPolling['msg'] = 'Push send... going forward whith the synchronization!';
$responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
$responseToPolling['wasAnswered'] = true;
$responseToPolling['masterRecord'] = $masterSyncRecord[0];
} elseif ($auxCounter >= 14) {
$keepInWhile = false;
if (!$masterSyncRecord[0]['msPushRecord']) {
$responseToPolling['msg'] = 'Waiting maximum time has been reached for push send.. Please try again later!';
$responseToPolling['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
$responseToPolling['wasAnswered'] = false;
$responseToPolling['masterRecord'] = $masterSyncRecord[0];
}
} elseif ($masterSyncRecord[0]['loginType'] == AccountLicense::LOGGED_BY_LEVEL_LITE && $masterSyncRecord[0]['hasLogedOMT']) {
$keepInWhile = false;
if ($masterSyncRecord[0]['msPushRecord']) {
$pushArray = $em->getRepository('App\Entity\PushSent')->getThePushSentArrayRecordById($masterSyncRecord[0]['msPushRecord']);
if (!empty($pushArray) && $pushArray[0]['omtCurlStatus'] == PushSent::STATUS_CURL_FINISHED) {
$responseToPolling['msg'] = 'Sync no needed..';
$responseToPolling['response_code'] = WebService::SYNC_DONE_SUCCESSFULLY;
$responseToPolling['wasAnswered'] = true;
$responseToPolling['masterRecord'] = $masterSyncRecord[0];
}
}
}
}
$em->clear();
} while ($keepInWhile && $auxCounter < 14);
return $responseToPolling;
}
/**
* Funcion polling que verifica si el push de sincronizacion de arriba a
* abajo fue enviado
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $masterSyncRecord registro maestro de la sincronizacion
* @return boolean indicando que el push de de la sincronizacion fue enviado
*/
public function checkForWebPushSendOMT($masterSyncRecord, $path = null) {
$responseToPolling = [];
$auxCounter = 0;
$keepInWhile = true;
$masterSyncId = $masterSyncRecord->getId();
if (!is_null($path)) {
$this->createFileJson($path, 'Checking push send....' . "\r");
}
$em = $this->getDoctrine()->getManager();
do {
sleep(3);
++$auxCounter;
$masterSyncRecord = $em->getRepository('App\Entity\MasterSync')->find($masterSyncId);
if (!is_null($path) && $masterSyncRecord) {
$this->createFileJson($path, "Checking push in'" . $masterSyncId . "' master sync record... \r");
$this->createFileJson($path, ".. and the push...? " . json_encode($masterSyncRecord->getMsPushRecord()) . "\r");
}
if ($masterSyncRecord && (is_null($masterSyncRecord->getMsPushRecord()) || is_null($masterSyncRecord->getMsPushRecord()->getOmtCurlStatus()))) {
sleep(1);
$keepInWhile = true;
$responseToPolling['msg'] = 'Awaiting response from the curl!!!!!!!!!!';
$responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
$responseToPolling['wasAnswered'] = true;
$responseToPolling['masterRecord'] = $masterSyncRecord;
} else {
if ($masterSyncRecord->getMsPushRecord()->getOmtCurlStatus() == PushSent::STATUS_CURL_PENDING) {
$keepInWhile = false;
$responseToPolling['msg'] = 'Push send... going forward whith the synchronization!';
$responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
$responseToPolling['wasAnswered'] = true;
$responseToPolling['masterRecord'] = $masterSyncRecord;
} elseif ($auxCounter >= 14) {
$keepInWhile = false;
if ($masterSyncRecord->getMsPushRecord()->getOmtCurlStatus() == PushSent::STATUS_CURL_PENDING || $masterSyncRecord->getMsPushRecord()->getOmtCurlStatus() == PushSent::STATUS_CURL_RESPONDED) {
$responseToPolling['msg'] = 'Waiting maximum time has been reached for push send.. Please try again later!';
$responseToPolling['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
$responseToPolling['wasAnswered'] = false;
$responseToPolling['masterRecord'] = $masterSyncRecord;
}
} elseif ($masterSyncRecord->getMsLicense()->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_LITE && $masterSyncRecord->getMsLicense()->getHasLogedOMT()) {
$keepInWhile = false;
if ($masterSyncRecord->getMsPushRecord()->getOmtCurlStatus() == PushSent::STATUS_CURL_FINISHED) {
$responseToPolling['msg'] = 'Sync no needed..';
$responseToPolling['response_code'] = WebService::SYNC_DONE_SUCCESSFULLY;
$responseToPolling['wasAnswered'] = true;
$responseToPolling['masterRecord'] = $masterSyncRecord;
}
}
}
$em->clear();
} while ($keepInWhile && $auxCounter < 14);
return $responseToPolling;
}
/**
* Funcion polling para verificar si el push de la sincronizacion de arriba
* a abajo fue respondido
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $unrespondedPush registro del push de sincronizacion de arriba a abajo enviado
* @return boolean que indica si fue respondido o no el push
*/
public function checkForWebPushResponse($unrespondedPush, $path) {
$responseToPolling = [];
$auxCounter = 0;
$keepInWhile = true;
$this->createFileJson($path, 'Checking push response....' . "\r");
$this->createFileJson($path, 'Checking push -> ' . $unrespondedPush[0]['id'] . "\r");
$em = $this->getDoctrine()->getManager();
do {
sleep(3);
++$auxCounter;
$pushArray = $em->getRepository('App\Entity\PushSent')->getThePushSentArrayRecordById($unrespondedPush[0]['id']);
// $unrespondedPush = $em->getRepository('App\Entity\PushSent')->find($unrespondedPush->getId());
if ($pushArray[0]['pushStatus'] == PushSent::STATUS_PUSH_READED) {
$keepInWhile = false;
$responseToPolling['msg'] = 'Push answered.. going forward whith the synchronization!';
$responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
$responseToPolling['wasAnswered'] = true;
} elseif ($auxCounter >= 14) {
$keepInWhile = false;
if ($pushArray[0]['pushStatus'] == PushSent::STATUS_PUSH_PENDING) {
$responseToPolling['msg'] = 'Waiting maximum time has been reached for push answer.. Please try again later!';
$responseToPolling['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
$responseToPolling['wasAnswered'] = false;
}
} elseif ($pushArray[0]['loginType'] == AccountLicense::LOGGED_BY_LEVEL_LITE && $pushArray[0]['hasLogedOMT']) {
$unrespondedPushEntity = $em->getRepository('App\Entity\PushSent')->find($unrespondedPush[0]['id']);
$unrespondedPushEntity->setPushStatus(PushSent::STATUS_PUSH_READED);
$unrespondedPushEntity->setRespondDate($unrespondedPushEntity->getRespondDate());
$em->persist($unrespondedPushEntity);
$em->flush();
$responseToPolling['msg'] = 'Automatic closure for unprocedent push!';
$responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
$responseToPolling['wasAnswered'] = true;
$keepInWhile = false;
} else {
$em->clear();
}
} while ($keepInWhile && $auxCounter < 14);
return $responseToPolling;
}
/**
* Funcion polling para determinar si fue respondida la sincronizacion de arriba
* a abajo por el servidor android
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $syncWebRecord registro de la sincronizacion web
* @return boolean que indica si fue respondida o no la sincronizacion web
*/
public function checkForWebResponse($syncWebRecord, $path) {
$responseToPolling = [];
$auxCounter = 0;
$keepInWhile = true;
$this->createFileJson($path, 'Checking sync web response....' . "\r");
$em = $this->getDoctrine()->getManager();
do {
sleep(3);
++$auxCounter;
$syncWebRecord = $em->getRepository('App\Entity\ReadFilesDataWeb')->getTheWebSyncArrayRecordById($syncWebRecord);
if ($syncWebRecord[0]['rfwStatus'] == ReadFilesDataWeb::STATUS_RESPONSE_READED) {
$keepInWhile = false;
$responseToPolling['msg'] = 'Web sync answered.. going forward whith the down up synchronization!';
$responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
$responseToPolling['wasAnswered'] = true;
} elseif ($auxCounter >= 14) {
$keepInWhile = false;
if ($syncWebRecord[0]['rfwStatus'] < ReadFilesDataWeb::STATUS_RESPONSE_READED) {
$responseToPolling['msg'] = 'Waiting maximum time has been reached for web sync answer.. Please try again later!';
$responseToPolling['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
$responseToPolling['wasAnswered'] = false;
}
} else {
$em->clear();
}
} while ($keepInWhile);
return $responseToPolling;
}
/**
* Funcion polling para verificar si termino con exito la sincronizacion de arriba a abajo
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $masterSyncRecord registro maestro de la sincronizacion en proceso
* @return boolean indicando si la sincronizacion de arriba a abajo termino con exito
*/
public function checkForWebSyncClose($masterSyncRecord, $path) {
$responseToPolling = [];
$auxCounter = 0;
$keepInWhile = true;
$this->createFileJson($path, 'Checking sync web finish....' . "\r");
if (!$masterSyncRecord['id']) {
$responseToPolling['msg'] = 'Waiting maximum time has been reached for web sync answer.. Please try again later!';
$responseToPolling['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
$responseToPolling['wasAnswered'] = false;
return $responseToPolling;
}
$em = $this->getDoctrine()->getManager();
do {
sleep(3);
++$auxCounter;
$masterSyncRecord = $em->getRepository('App\Entity\ReadFilesDataWeb')->getTheMasterSyncArrayRecordById($masterSyncRecord['id'], true);
if ($masterSyncRecord[0]['msStatus'] == MasterSync::MASTER_STATUS_CLOSED) {
$keepInWhile = false;
$responseToPolling['msg'] = 'Web sync finished.. going forward whith the down up synchronization!';
$responseToPolling['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
$responseToPolling['wasAnswered'] = true;
} elseif ($auxCounter >= 14) {
$keepInWhile = false;
if ($masterSyncRecord[0]['msStatus'] <= MasterSync::MASTER_STATUS_CLOSED) {
$responseToPolling['msg'] = 'Waiting maximum time has been reached for web sync finish.. Please try again later!';
$responseToPolling['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
$responseToPolling['wasAnswered'] = false;
}
} else {
$em->clear();
}
} while ($keepInWhile);
return $responseToPolling;
}
/**
* Funcion polling para verificar la respuesta de una sincronizacion de abajo
* a arriba, este funcion verifica en un tiempo maximo de 56 segundos
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $id id de lalicencia a la cual se verificara la respuesta
* @param type $paramLastId id de la ultima sincronizacion de abajo a arriba respondido
* @return boolean indica si se respondio o no la solicitud en el tiempo establecido
*/
public function checkForDownUpPolling($id, $paramLastId, $path) {
$checkResponse = [];
$auxCounter = 0;
$keepInWhile = true;
$this->createFileJson($path, 'Checking sync response for ' . $id . " license \r");
$em = $this->getDoctrine()->getManager();
do {
sleep(4);
++$auxCounter;
$lastReadDataForLicense = $em->getRepository('App\Entity\ReadFilesData')->checkForNewSyncPetitionByLicense($id, $paramLastId, true);
if (count($lastReadDataForLicense) > 0) {
$this->createFileJson($path, 'Count For Polling Status: -> ' . $paramLastId . ' -> ' . $lastReadDataForLicense[0]['id'] . ' => ' . $lastReadDataForLicense[0]['rfStatus'] . "\r");
} else {
$this->createFileJson($path, 'Count For Polling: -> ' . $paramLastId . ' => ' . count($lastReadDataForLicense) . "\r");
}
$askingSyncPushRecordArray = $em->getRepository('App\Entity\PushSent')->findLastAskingSyncPushToLicense($id, true);
$askingSyncPushRecord = $askingSyncPushRecordArray[0];
$this->createFileJson($path, 'Push Record Found In Polling: -> ' . $askingSyncPushRecord['id'] . "\r");
if (isset($askingSyncPushRecord['newPushSendedStage']) && $askingSyncPushRecord['newPushSendedStage'] == PushSent::SENDED_STAGE_OMT_SOCKET_PUSH) {
$keepInWhile = false;
$this->createFileJson($path, "push omt type detected!! \r");
$checkResponse['newPushSendedStage'] = PushSent::SENDED_STAGE_OMT_SOCKET_PUSH;
$checkResponse['wasAnswered'] = true;
$checkResponse['msg'] = 'Android server sync processed.. Please check for the new data!';
$checkResponse['response_code'] = WebService::SYNC_DONE_SUCCESSFULLY;
} elseif (!empty($lastReadDataForLicense) && $lastReadDataForLicense[0]['rfStatus'] > ReadFilesData::STATUS_UPLOADED) {
$keepInWhile = false;
$checkResponse['status'] = SyncAllWebsocketVersionCommand::ANDROID_SYNC_SUCCESS;
$checkResponse['msg'] = 'Android server sync processed.. Please check for the new data!';
$checkResponse['response_code'] = WebService::SYNC_DONE_SUCCESSFULLY;
$checkResponse['wasAnswered'] = true;
} elseif (!empty($askingSyncPushRecord) && $askingSyncPushRecord['askedResponse'] === false) {
$keepInWhile = false;
$checkResponse['status'] = SyncAllWebsocketVersionCommand::ANDROID_HAVE_NOTHING_TO_SYNC;
$checkResponse['msg'] = 'Android server have nothing to synchronize... finishing synchronization!';
$checkResponse['response_code'] = WebService::NOTHING_TO_WEB_SYNCHRONIZE;
$checkResponse['wasAnswered'] = true;
} elseif ($auxCounter > 7) {
$keepInWhile = false;
if (count($lastReadDataForLicense) > 0) {
$checkResponse['status'] = SyncAllWebsocketVersionCommand::ANDROID_SYNC_SUCCESS;
$checkResponse['msg'] = 'Android server sync processed.. Please check for the new data!';
$checkResponse['response_code'] = WebService::SYNC_DONE_SUCCESSFULLY;
$checkResponse['wasAnswered'] = true;
} else {
$checkResponse['status'] = SyncAllWebsocketVersionCommand::ANDROID_WAITING_MAXIMUM_TIME;
$checkResponse['msg'] = 'Waiting maximum time has been reached for Android new data.. Please try again later!';
$checkResponse['response_code'] = WebService::MAXIMUM_WAIT_TIME_REACHED;
$checkResponse['wasAnswered'] = false;
}
} elseif ($askingSyncPushRecord['loginType'] == AccountLicense::LOGGED_BY_LEVEL_LITE && $askingSyncPushRecord['hasLogedOMT']) {
$askingSyncPushRecord = $em->getRepository('App\Entity\PushSent')->find($askingSyncPushRecord['id']);
$askingSyncPushRecord->setPushStatus(PushSent::STATUS_PUSH_READED);
$askingSyncPushRecord->setRespondDate($askingSyncPushRecord->getRespondDate());
$askingSyncPushRecord->setAskedResponse(false);
$em->persist($askingSyncPushRecord);
$em->flush();
$checkResponse['status'] = SyncAllWebsocketVersionCommand::SYNC_DONE;
$checkResponse['msg'] = 'Sync done.. Please check for the new data!';
$checkResponse['response_code'] = WebService::SYNC_RESPONSE_PROCESSED;
$checkResponse['wasAnswered'] = true;
$keepInWhile = false;
} else {
$em->clear();
}
} while ($keepInWhile);
return $checkResponse;
}
public function checkForDownUp(AccountLicense $license, bool $pushAskedResponse, $path) {
$this->createFileJson($path, "Checking sync response for {$license->getId()} license \r");
$em = $this->getDoctrine()->getManager();
$lastReadDataForLicense = $em->getRepository('App\Entity\ReadFilesData')->findLastSyncPetitionIdByLicense($license->getId());
$lastReadDataForLicense = $em->getRepository('App\Entity\ReadFilesData')->checkForNewSyncPetitionByLicense($license->getId(), $lastReadDataForLicense, true);
$checkResponse = [];
if (!empty($lastReadDataForLicense) && $lastReadDataForLicense[0]['rfStatus'] > ReadFilesData::STATUS_UPLOADED) {
$this->createFileJson($path, "Android server sync processed.. Please check for the new data! \r");
$checkResponse['status'] = SyncAllWebsocketVersionCommand::ANDROID_SYNC_SUCCESS;
}else if(!$pushAskedResponse){
$this->createFileJson($path, "Android server have nothing to synchronize... finishing synchronization! \r");
$checkResponse['status'] = SyncAllWebsocketVersionCommand::ANDROID_HAVE_NOTHING_TO_SYNC;
}else{
$this->createFileJson($path, "clear \r");
$em->clear();
}
$this->createFileJson($path, "check response => ". json_encode($checkResponse) ." \r");
return $checkResponse;
}
/**
* WS generico experimental para la codificacion y decodificacion del encriptado
* utilizado entre licensor y android
* @author Aealan Z <lrobledo@kijho.com> 18/06/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function cosito(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
$path = $this->realContainer->getParameter('level_directory_data_android') . 'TestiDecodePath.txt';
$jsn = $this->realContainer->getParameter('level_directory_data_android') . 'TresChangos.txt';
$arrData = Util::getAllDecryptedJsonContent($this->realContainer, $jsn, true, $path, true, false);
$r = new Response($arrData);
$r->headers->set('Content-Type', 'application/json');
return $r;
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_GET . " method");
}
}
/**
* WS generico para que el cliente andorid responda todos los push enviados a los clientes
* @author Aealan Z <lrobledo@kijho.com> 18/06/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function cositoDos(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
$jsn = file_get_contents($this->realContainer->getParameter('level_directory_data_android') . 'UnChangoDos.txt');
$responseToAjax['content'] = trim($jsn, " \t\n\r\0\x0B");
return $this->respondJsonAjax($responseToAjax);
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS generico para que el cliente andorid responda todos los push enviados a los clientes
* @author Aealan Z <lrobledo@kijho.com> 18/06/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function cositoTres(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
// $jsn = file_get_contents($this->realContainer->getParameter('level_directory_data_android') . 'UnChangoTres.txt');
$cipher = "rijndael-128";
$mode = "cbc";
$secret_key = "D4:6E:AC:3F:F0:BE";
//iv length should be 16 bytes
$iv = "fedcba9876543210";
$key_len = strlen($secret_key);
if ($key_len < 16) {
$addS = 16 - $key_len;
for ($i = 0; $i < $addS; ++$i) {
$secret_key .= " ";
}
} else {
$secret_key = substr($secret_key, 0, 16);
}
$td = mcrypt_module_open($cipher, "", $mode, $iv);
mcrypt_generic_init($td, $secret_key, $iv);
var_dump($this->realContainer->getParameter('level_directory_data_android') . 'UnChangoTres.txt');
die();
$getText = file_get_contents($this->realContainer->getParameter('level_directory_data_android') . 'UnChangoTres.txt');
$textArray = explode('\r', $getText);
$textCount = count($textArray);
for ($i = 0; $i < $textCount; ++$i) {
$cyper_text = mcrypt_generic($td, $textArray[$i]);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$textEncrypt = bin2hex($cyper_text);
$setText = base64_encode($textEncrypt);
$fp = fopen($this->realContainer->getParameter('level_directory_data_android') . 'UnChangoTresResponse.txt', "a+");
fwrite($fp, $setText);
fclose($fp);
}
// $path = $this->realContainer->getParameter('level_directory_data_android') . 'UnChangoTresResponse.txt';
// $pathXD = $this->realContainer->getParameter('level_directory_data_android') . 'UnChangoTresTest.txt';
// Util::putAllEncryptedJsonContent($this->realContainer, trim($jsn, " \t\n\r\0\x0B"), $path, true, $pathXD);
$responseToAjax['content'] = 'Si encripto...?';
return $this->respondJsonAjax($responseToAjax);
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* Esta funcion permite notificar por correo, un error persistente dentro
* de los registros de sincronizacion de determinada licencia
* @author Aealan Z <lrobledo@kijho.com> 18/12/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function notifySyncRecurrentError(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
$data = [];
$dataForTrack = [];
$parameters = $request->request->all();
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'notifyRecurrentSyncError', 'notifyRecurrentSyncError0.txt');
$this->createFileJson($path, "The Request -> " . json_encode($parameters) . "\r");
$arrayEncryptResult = Util::decryptDataForUploadsFiles($this->realContainer, $parameters['nickname']);
$data['nickname'] = $arrayEncryptResult['data'];
$dataForTrack['nickname'] = $parameters['nickname'];
$arrayEncryptResult = Util::decryptDataForUploadsFiles($this->realContainer, $parameters['uid']);
$data['uid'] = $arrayEncryptResult['data'];
$dataForTrack['uid'] = $parameters['uid'];
$em = $this->getDoctrine()->getManager();
$search = ['alLicenseUsername' => $data['nickname']];
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($search);
if (empty($accountLicenseData)) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_UNAUTHORIZED);
} elseif ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::CODE_UNAUTHORIZED);
}
$respArray = [];
$respArray['result'] = '__OK__';
$respArray['msg'] = '';
if (isset($parameters['idsync'])) {
$arrayEncryptResult = Util::decryptDataForUploadsFiles($this->realContainer, $parameters['idsync']);
$data['idsync'] = $arrayEncryptResult['data'];
$dataForTrack['idsync'] = $arrayEncryptResult['data'];
$errorsToEmail = $em->getRepository('App\Entity\SyncReportedError')->find($data['idsync']);
if (!$errorsToEmail) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Error record not found!', WebService::CODE_UNAUTHORIZED);
}
} else {
$responseArrayWithUrl = Util::createLicenseDirectory($this->realContainer, $accountLicenseData[0], $data['nickname']);
$theAccountDirector = $responseArrayWithUrl['directory'];
$uploadFileResponse = Utilx::uploadFileTo($request, $theAccountDirector, $path);
if (!isset($uploadFileResponse['result']) || !isset($uploadFileResponse['msg'])) {
$this->createFileJson($path, 'Unknown error uploading file ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError('Unknown error uploading file', WebService::CODE_INTERNAL_ERROR);
}
if (isset($uploadFileResponse['result']) && isset($uploadFileResponse['msg']) && $uploadFileResponse['result'] == '__KO__') {
$this->createFileJson($path, $uploadFileResponse['msg'] . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError($uploadFileResponse['msg'], WebService::CODE_INTERNAL_ERROR);
}
$errorsToEmail = new SyncReportedError();
$errorsToEmail->setStatus(SyncReportedError::STATUS_CREATED);
$errorsToEmail->setLicense($accountLicenseData[0]);
$actualDate = Util::getCurrentDate();
$errorsToEmail->setDateErrorCreated($actualDate);
$errorsToEmail->setErrorFile($uploadFileResponse['fileName']);
$currentUrl = $request->getUri();
// if (strpos($currentUrl, 'app_dev.php') !== false) {
$errorsToEmail->setApplicationMode(false);
// } else {
// $errorsToEmail->setApplicationMode(true);
// }
$em->persist($errorsToEmail);
$em->flush();
$this->createFileJson($path, "File uploaded -> " . $uploadFileResponse['fileName'] . "\r");
}
$this->createFileJson($path, json_encode($dataForTrack) . "\r");
$emailsToNotify = $this->realContainer->getParameter('level_emails_syncs_errors');
$responseArrayWithUrl = Util::createLicenseDirectory($this->realContainer, $accountLicenseData[0], $data['nickname']);
$urlToErrorFile = $responseArrayWithUrl['directory'] . '/' . $errorsToEmail->getErrorFile();
$this->createFileJson($path, "Ya casi! -> " . $urlToErrorFile . "\r");
if (isset($parameters['isIgnored'])) {
$theSubject = $data['nickname'] . ' ignored records sync error ';
} else {
$theSubject = $data['nickname'] . ' recurrent sync error ';
}
$respArray['subject'] = $theSubject;
$respArray['message'] = "";
$body = "<html><body><div><p><label><strong>" . $data['nickname'] . "</strong> Uuppss... -_-!</label></p><br></div></body></html>";
foreach ($emailsToNotify as $mailTo) {
$this->createFileJson($path, "Mail to -> " . $mailTo . "\r");
$emailSuccess = true;
$respArray['to'] = $mailTo;
Utilx::sendMailInfo($this->realContainer, $respArray, $path, $body, $urlToErrorFile);
}
$this->createFileJson($path, "Si llego? -> " . $urlToErrorFile . "\r");
$statusArryMsg = [];
$statusArryMsg['status'] = WebService::CODE_SUCCESS;
if ($emailSuccess) {
$errorsToEmail->setStatus(SyncReportedError::STATUS_NOTIFIED);
$actualDate = Util::getCurrentDate();
$errorsToEmail->setDateErrorNotified($actualDate);
$em->persist($errorsToEmail);
$em->flush();
$statusArryMsg['msg'] = 'Recurrent sync errors notified!';
} else {
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError('Erro notifiying recurrent errors by email!', WebService::CODE_INTERNAL_ERROR);
}
$theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer, $statusArryMsg);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* Funcion para actualizar el registro de un push marcandolo como leido
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $pushEntity registro de push a actualizar
* @return boolean booleano que indica si se actualizo el registro con exito
*/
public function updateRegistPushSend($pushEntity) {
$em = $this->getDoctrine()->getManager();
$pushEntity->setPushStatus(PushSent::STATUS_PUSH_READED);
$actualDate = Util::getCurrentDate();
$pushEntity->setRespondDate($actualDate);
$em->persist($pushEntity);
try {
$em->flush();
return true;
} catch (\Exception $ex) {
return false;
}
}
/**
* Funcion para crear un nuevo registro de sincronizacion de abajo a arriba
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $license licencia a la cual se le creara el nuevo registro
* de sincronizacion
* @return boolean|ReadFilesData retorna el nuevo registro de sincronizacion
* si este fue creado correctamente, de lo contrario retorna un booleano (false)
*/
public function setRegistNewFile($license) {
$em = $this->getDoctrine()->getManager();
$masterSync = Utilx::setRegistNewMasterSyncRecordFile($em, $license, MasterSync::MASTER_SYNC_TYPE_DOWUP);
$entity = new ReadFilesData();
$entity->setRfLicenseId($license);
$entity->setRfStatus(ReadFilesData::STATUS_STANDBY);
$actualDate = Util::getCurrentDate();
$entity->setRfDateSincAsk($actualDate);
$entity->setIsReadedByServer(false);
$appMode = $this->realContainer->getParameter('kernel.environment');
if ($appMode == 'dev') {
$entity->setApplicationMode(false);
} else {
$entity->setApplicationMode(true);
}
$em->persist($entity);
try {
$em->flush();
$masterSync->setMsSyncRecord($entity);
$em->persist($masterSync);
$em->flush();
return $entity;
} catch (\Exception $ex) {
return false;
}
}
/**
* Funcion en donde se crea el registro de una notificacion de error
* por email junto con el error adjunto, en este funcion se notifican
* tanto licencias como sublicencias
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $license registro de la licencia a la que se notificara el error
* @param type $mailedTo email al que se el enviara el correo del error
* @param type $msgError mensaje de error a notificar
* @param type $deviceUid UID del dispositivo que reporta el error
* @param type $errorCode codigo que identifica a cada error distinto en el sistema
* @param type $subLicense registro de sublicencia a la que se le notificara el error
* @return boolean|ErrorAndroidEmailSent registro de la notificacion del error por email
* si se creo exitosamente, de lo contrario retorna un booleano (false)
*/
public function setRegistErrorEmail($license, $mailedTo, $msgError, $deviceUid, $errorCode, $subLicense = null) {
$em = $this->getDoctrine()->getManager();
$entity = new ErrorAndroidEmailSent();
if ($license) {
$entity->setLiceseError($license);
} else {
$entity->setSubLicenseError($subLicense);
}
$entity->setEmailRecordStatus(ErrorAndroidEmailSent::STATUS_SERVER_NOTIFIED);
$actualDate = Util::getCurrentDate();
$entity->setDateErrorReported($actualDate);
$entity->setErrorMsg($msgError);
$entity->setMailedTo($mailedTo);
$entity->setUidErrorDevice($deviceUid);
$entity->setErrorCode($errorCode);
$entity->setDateErrorLastReport($actualDate);
$entity->setErrorCounter(1);
$em->persist($entity);
try {
$em->flush();
return $entity;
} catch (\Exception $ex) {
return false;
}
}
/**
* Funcion en donde se crea el registro en el historico de errores de Android,
* en este funcion se registran tanto licencias como sublicencias.
* Basada en la función setRegistErrorEmail
* @author Jhonan V <jsmith@openmytab.com> 29/10/2021
* @param type $license registro de la licencia a la que se va a notificara el error
* @param type $mailedTo email al que se el enviara el correo del error
* @param type $msgError mensaje de error a notificar
* @param type $deviceUid UID del dispositivo que reporta el error
* @param type $errorCode codigo que identifica a cada error distinto en el sistema
* @param type $subLicense registro de sublicencia a la que se le notificara el error
* @return boolean|AndroidErrorsHistory registro de la notificacion del error por email
* si se creo exitosamente, de lo contrario retorna un booleano (false)
*/
public function setRegistAndroidError($error, $license, $mailedTo, $msgError, $deviceUid, $subLicense = null) {
$em = $this->getDoctrine()->getManager();
$entity = new AndroidErrorsHistory();
if ($license) {
$entity->setLiceseError($license);
} else {
$entity->setSubLicenseError($subLicense);
}
$entity->setErrorCode($error);
$entity->setEmailRecordStatus(ErrorAndroidEmailSent::STATUS_SERVER_NOTIFIED);
$actualDate = Util::getCurrentDate();
$entity->setDateErrorReported($actualDate);
$entity->setErrorMsg($msgError);
$entity->setMailedTo($mailedTo);
$entity->setUidErrorDevice($deviceUid);
$em->persist($entity);
try {
$em->flush();
return $entity;
} catch (\Exception $ex) {
return false;
}
}
/**
* Funcion en donde se actualiza el registro de notificacion de error enviado
* por email indicando que ya fue enviado dicho correo
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $errorAndroidEmailRecord registro de notificacion de error
* por email
* @return boolean booleano que indica si el registro
* fue actualizado correctamente
*/
public function updateRegistErrorEmail($errorAndroidEmailRecord) {
$em = $this->getDoctrine()->getManager();
$errorAndroidEmailRecord->setEmailRecordStatus(ErrorAndroidEmailSent::STATUS_EMAIL_SENT);
$actualDate = Util::getCurrentDate();
$errorAndroidEmailRecord->setDateErrorEmailSent($actualDate);
$em->persist($errorAndroidEmailRecord);
try {
$em->flush();
return $errorAndroidEmailRecord;
} catch (\Exception $ex) {
return false;
}
}
/**
* Funcion en donde se crea el registro de notificacion de log por email
* junto con el log adjunto, esta funcion se notifica tanto licencias
* como sublicencias
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $license registro de la licencia a la que se solicito el log
* @param type $mailedTo email al que se el enviara el correo con el log
* @param type $msgError log del servidor a ser notificado por email
* @param type $deviceUid UID del dispositivo al que se le solicita el log
* @param type $errorCode codigo unico del log solicitado
* @param type $subLicense registro de sublicencia
* a la que se le solicito el log
* @return boolean|LogAndroidEmailSent registro
* de nitificacion de log por correo si este se genero exitosamente,
* un booleano (false) de lo contrario
*/
public function setRegistLogEmail($license, $mailedTo, $msgError, $deviceUid, $errorCode, $subLicense = null) {
$em = $this->getDoctrine()->getManager();
$entity = new LogAndroidEmailSent();
if ($license) {
$entity->setLiceseLog($license);
} else {
$entity->setSubLicenseLog($subLicense);
}
$entity->setEmailRecordStatus(LogAndroidEmailSent::STATUS_SERVER_NOTIFIED);
$actualDate = Util::getCurrentDate();
$entity->setDateLogAsked($actualDate);
$entity->setLogMsg($msgError);
$entity->setMailedTo($mailedTo);
$entity->setUidLogDevice($deviceUid);
$entity->setLogCode($errorCode);
$em->persist($entity);
try {
$em->flush();
return $entity;
} catch (\Exception $ex) {
return false;
}
}
/**
* Funcion en donde se actualiza el registro de error notificado por email
* , en este funcion se actualiza el registro indicando que se envio
* exitosamente el correo con el error
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $errorAndroidEmailRecord registro del error
* notificado por email
* @return boolean booleano que indica si se actualizo
* el registro correctamente
*/
public function updateRegistLogEmail($errorAndroidEmailRecord) {
$em = $this->getDoctrine()->getManager();
$errorAndroidEmailRecord->setEmailRecordStatus(LogAndroidEmailSent::STATUS_EMAIL_SENT);
$actualDate = Util::getCurrentDate();
$errorAndroidEmailRecord->setDateLogEmailSent($actualDate);
$em->persist($errorAndroidEmailRecord);
try {
$em->flush();
return $errorAndroidEmailRecord;
} catch (\Exception $ex) {
return false;
}
}
/**
* @author Aealan Z <lrobledo@kijho.com> 29/07/2016
* @param type $readFileData
* @param type $fileName
* @return boolean
*/
public function updateRegistUploadFile($readFileData, $fileName, $fileInS3URI = '') {
$em = $this->getDoctrine()->getManager();
$masterSyncRecords = $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncRecord' => $readFileData->getId()]);
$masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_PROCESSED);
$readFileData->setRfStatus(ReadFilesData::STATUS_UPLOADED);
$readFileData->setRfNameFile($fileName);
$actualDate = Util::getCurrentDate();
$readFileData->setRfDateUpload($actualDate);
$readFileData->setIsReadedByServer(false);
if ($fileInS3URI != '') {
$readFileData->setFileInS3URI($fileInS3URI);
}
$em->persist($masterSyncRecords[0]);
$em->persist($readFileData);
try {
$em->flush();
return true;
} catch (\Exception $ex) {
return false;
}
}
/**
* Funcion para limpiar el estatus de error en una sincronizacion para
* poder reencolarla de nuevo
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $readFileDataWeb registro de la sincronizacion
* web a reencolar
* @return boolean booleano que indica si se actualizo
* correctamente el registro
*/
public function cleanErrorStatusToRetryWebSync($readFileDataWeb) {
$em = $this->getDoctrine()->getManager();
$masterSyncRecords = $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncWebRecord' => $readFileDataWeb->getId()]);
$masterSyncRecords[0]->setMsHasPersistentError(false);
$readFileDataWeb->setHasPersistentError(false);
$em->persist($masterSyncRecords[0]);
$em->persist($readFileDataWeb);
try {
$em->flush();
return true;
} catch (\Exception $ex) {
return false;
}
}
/**
* Funcion para actualizar el registro de sincronizacion de abajo a arriba
* marcandolo como entregado por licensor
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @param type $readFileData registro de la sincronizacion de abajo
* a arriba
* @return boolean booleano indicando si se actualizo el registro
* correctamente
*/
public function updateRegistDeliveredFile($readFileData) {
$em = $this->getDoctrine()->getManager();
$masterSyncRecords = $em->getRepository('App\Entity\MasterSync')->findBy(['msSyncRecord' => $readFileData->getId()]);
$masterSyncRecords[0]->setMsStatus(MasterSync::MASTER_STATUS_RESPONDED);
$readFileData->setRfStatus(ReadFilesData::STATUS_DELIVERED);
$actualDate = Util::getCurrentDate();
$readFileData->setRfDateDelivered($actualDate);
$em->persist($masterSyncRecords[0]);
$em->persist($readFileData);
try {
$em->flush();
return true;
} catch (\Exception $ex) {
return false;
}
}
/**
* WS para desbloquear sincronizaciones no terminadas por errores
* @author Aealan Z <lrobledo@kijho.com> 11/11/15
* @param \Symfony\Component\HttpFoundation\Request $request datos
* de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function clearBlockedSyncsByLicense(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'unblockSyncs', 'unblockSyncs0.txt');
$this->createFileJson($path, 'Clear blocked syncs: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['nickname']) || !isset($data['uid'])) {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
$countResult = count($accountLicenseData);
if ($countResult > 0) {
if ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::HTTP_CODE_UNAUTHORIZED);
}
$masterSyncRecords = $em->getRepository('App\Entity\MasterSync')->findMastersSyncsInProcessToBlockNewSyncs($accountLicenseData[0]->getId());
if (!empty($masterSyncRecords)) {
foreach ($masterSyncRecords as $masterSync) {
if ($masterSync->getMsType() == MasterSync::MASTER_SYNC_TYPE_DOWUP) {
$masterSync->setMsStatus(MasterSync::MASTER_STATUS_RESPONDED);
$downUpSyncRecord = $masterSync->getMsSyncRecord();
$downUpSyncRecord->setRfStatus(ReadFilesData::STATUS_DELIVERED);
} else {
$masterSync->setMsStatus(MasterSync::MASTER_STATUS_CLOSED);
$downUpSyncRecord = $masterSync->getMsSyncWebRecord();
$downUpSyncRecord->setRfwStatus(ReadFilesDataWeb::STATUS_RESPONSE_READED);
}
$em->persist($downUpSyncRecord);
$em->persist($masterSync);
}
$em->flush();
}
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'All blocking syncs are closed!';
$responseArr['bigbag'] = false;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} else {
return $this->errorWrongArgs('Wrong Content!', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* Funcion para obtener el ultimo error encontrado generico
* a la hora de decodificar un json
* @author Aealan Z <lrobledo@kijho.com> 11/06/2016
* @return string
*/
public function findErrorJsonDecode() {
$r = '- No error';
switch (json_last_error()) {
case JSON_ERROR_NONE:
return $r;
case JSON_ERROR_DEPTH:
return ' - Maximum stack depth exceeded';
case JSON_ERROR_STATE_MISMATCH:
return ' - Underflow or the modes mismatch';
case JSON_ERROR_CTRL_CHAR:
return ' - Unexpected control character found';
case JSON_ERROR_SYNTAX:
return ' - Syntax error, malformed JSON';
case JSON_ERROR_UTF8:
return ' - Malformed UTF-8 characters, possibly incorrectly encoded';
default:
return ' - Unknown error';
}
return $r;
}
/**
* WS para obtener un listado con todas las sublicencias registradas para
* una licencia de tipo call center para que el servidor android les asocie
* un dispositivo y las sincronice en licensor
* @author Aealan Z <lrobledo@kijho.com> 08/10/15
* @param \Symfony\Component\HttpFoundation\Request $request datos
* de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function getSublicenseByLicense(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'demoLogin', 'demoLogin0.txt');
$this->createFileJson($path, 'Login Mobile: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['nickname']) || !isset($data['uid'])) {
return $this->errorWrongArgs('Wrong Arguments!', WebService::CODE_WRONG_ARGUMENTS);
}
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($licenseUserName);
$countResult = count($accountLicenseData);
if ($countResult > 0) {
if (!$accountLicenseData[0]->getIsCallCenter()) {
return $this->errorWrongArgs('Invalid license type!', WebService::CODE_WRONG_ARGUMENTS);
}
if ($accountLicenseData[0]->getDeviceUid() == '' || null == $accountLicenseData[0]->getDeviceUid()) {
$accountLicenseByUID = $em->getRepository('App\Entity\AccountLicense')->findBy(array('deviceUid' => $data['uid']));
if (!empty($accountLicenseByUID)) {
if ($accountLicenseData[0]->getAlLicenseUsername() != $accountLicenseByUID[0]->getAlLicenseUsername()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Device already registed with another license!', WebService::CODE_ACCOUNT_SUSPENDED);
}
}
$accountLicenseData[0]->setDeviceUid($data['uid']);
} else {
if ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::CODE_ACCOUNT_SUSPENDED);
}
}
$arraySubLicense = [];
$sublicensesByLicense = $em->getRepository('App\Entity\SubLicense')->findBy(['license' => $accountLicenseData[0]->getId()]);
if (empty($sublicensesByLicense)) {
return $this->errorWrongArgs('No sub-licenses registerede for this license!', WebService::CODE_WRONG_ARGUMENTS);
} else {
foreach ($sublicensesByLicense as $subL) {
$arraySubLicense[] = $subL->getChannelName();
}
}
$em->persist($accountLicenseData[0]);
$em->flush();
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['list'] = json_encode($arraySubLicense);
$theUrlTrSt = new SublicensesListTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid channel', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} else {
return $this->errorWrongArgs('Wrong Content!', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS para registrar la pushy key del dispositivo de una sublicencia
* @author Aealan Z <lrobledo@kijho.com> 03/11/15
* @param \Symfony\Component\HttpFoundation\Request $request datos
* de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function registerPushyKeyToSublicense(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'subLRegisterPushy', 'subLRegisterPushy0.txt');
$this->createFileJson($path, 'Request Sub Pushy: ' . $request->getContent() . "\r");
try {
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
$this->createFileJson($path, 'Decrypted: ' . $request->getContent() . "\r");
if (!isset($data['channelname']) || !isset($data['uid']) || !isset($data['pushy'])) {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\SubLicense')
->findBy(['channelName' => $data['channelname']]);
$countResult = count($accountLicenseData);
$this->createFileJson($path, 'Lic Sub Count: ' . $countResult . "\r");
if ($countResult > 0) {
if ($accountLicenseData[0]->getDeviceUid() == '' || null == $accountLicenseData[0]->getDeviceUid()) {
$this->createFileJson($path, 'Into IF 1: ' . "\r");
$accountLicenseByUID = $em->getRepository('App\Entity\SubLicense')->findBy(['deviceUid' => $data['uid']]);
if (!empty($accountLicenseByUID)) {
$this->createFileJson($path, 'IF 2: cha ' . $accountLicenseData[0]->getChannelName() . ' chaByUID ' . $accountLicenseByUID[0]->getChannelName() . "\r");
if ($accountLicenseData[0]->getChannelName() != $accountLicenseByUID[0]->getChannelName()) {
$this->createFileJson($path, 'Error IF 2: ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Device already registed with another license!', WebService::HTTP_CODE_UNAUTHORIZED);
}
}
$accountLicenseData[0]->setDeviceUid($data['uid']);
} else {
$this->createFileJson($path, 'IF 3: UID ' . $accountLicenseData[0]->getDeviceUid() . ' requeUID ' . $data['uid'] . "\r");
if ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
$this->createFileJson($path, 'Error IF 3: ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::HTTP_CODE_UNAUTHORIZED);
}
}
if ($accountLicenseData[0]->getPushyKey() == '' || null == $accountLicenseData[0]->getPushyKey()) {
$accountLicenseByPushy = $em->getRepository('App\Entity\SubLicense')->findBy(['pushyKey' => $data['pushy']]);
if (!empty($accountLicenseByPushy)) {
$this->createFileJson($path, 'IF 4: cha ' . $accountLicenseData[0]->getChannelName() . ' chaPushy ' . $accountLicenseByPushy[0]->getChannelName() . "\r");
if ($accountLicenseData[0]->getChannelName() != $accountLicenseByPushy[0]->getChannelName()) {
$this->createFileJson($path, 'Error IF 4: ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Push key registed with another license!', WebService::HTTP_CODE_UNAUTHORIZED);
}
}
$accountLicenseData[0]->setPushyKey($data['pushy']);
} else {
$this->createFileJson($path, 'IF 5: Pushy ' . $accountLicenseData[0]->getPushyKey() . ' requePushy ' . $data['pushy'] . "\r");
if ($accountLicenseData[0]->getPushyKey() != $data['pushy']) {
$this->createFileJson($path, 'Error IF 5: ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::HTTP_CODE_UNAUTHORIZED);
}
}
$em->persist($accountLicenseData[0]);
$em->flush();
Util::updateAllPushKey([
"nickname" => $accountLicenseData[0]->getAlLicenseUsername(),
"pushyKey" => $data['pushy'],
"awsPushEndPoint" => $accountLicenseData[0]->getAwsPushEndPoint(),
"awsTopicARN" => $accountLicenseData[0]->getAwsTopicARN(),
"awsSubscriptionARN" => $accountLicenseData[0]->getAwsSubscriptionARN(),
"awsDeviceToken" => $accountLicenseData[0]->getAwsDeviceToken(),
], $this->realContainer);
$em = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]->getLicense());
$remoteStation = $em->getRepository('App\Structure\RemoteStation')->findBy(['parse' => $data['channelname']]);
if (empty($remoteStation)) {
$this->createFileJson($path, 'Error IF 6: ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_FORBIDDEN)
->respondWithError('Sublicense device record not found!', WebService::CODE_OBJECT_NOT_FOUND);
} else {
$this->createFileJson($path, ':D' . "\r");
$remoteStation[0]->setPushy($data['pushy']);
$registActions = new RegistActions();
$registActions->setReacTableName('remote_stations');
$registActions->setReacTableId($remoteStation[0]->getId());
$registActions->setReacTableAction('U');
$registActions->setReacRegistFk(0);
$registActions->setReacAndroidId($remoteStation[0]->getAndroidSync());
$actualDate = Util::getCurrentDate();
$registActions->setReacDateTime($actualDate);
$registActions->setReacEstatus(RegistActions::STATUS_NOTREADED);
$em->persist($remoteStation[0]);
$em->persist($registActions);
$em->flush();
}
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Valid license channel and pushy key registered!';
$responseArr['bigbag'] = false;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid channel', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} catch (\Throwable $th) {
$err = ['Error message' => $th->getMessage(), 'Error line' => $th->getLine(), 'Error file' => $th->getFile(), 'Error trance' => $th->getTrace()];
$this->createFileJson($path, 'Alert Error: ' . json_encode($err) . "\r");
return $this->errorWrongArgs('Wrong Content!', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorWrongArgs('Wrong Content!', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS para registrar la pushy key de un dispositivo de una licencia
* @author Aealan Z <lrobledo@kijho.com> 05/11/15
* @param \Symfony\Component\HttpFoundation\Request $request datos
* de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function registerPushyKeyToLicense(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'pushyRegist', 'pushyRegist0.txt');
$this->createFileJson($path, "\r" . 'Register Pushy Key: ' . $request->getContent() . "\r");
try {
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['nickname']) || !isset($data['uid']) || !isset($data['pushy'])) {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$this->createFileJson($path, 'Decrypted: ' . $arrayEncryptResult['data'] . "\r");
if ($data['nickname'] == '' || $data['uid'] == '' || $data['pushy'] == '') {
return $this->errorWrongArgs('Empty Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
$countResult = count($accountLicenseData);
if ($countResult > 0) {
$accountLicenseByPushy = $em->getRepository('App\Entity\AccountLicense')->findBy(['pushyKey' => $data['pushy']]);
// $accountLicenseByPushy = $em->getRepository('App\Entity\AccountLicense')->getLicenseByPushy($data['pushy'], $data['nickname']);
// function internaSaveInRegistAction($container, $em, $license){
// $emLev = Util::emLicenseConnection($container, $em, $license);
// $registAction = $emLev->getRepository('App\Structure\RegistActions')->findOneBy(['reacTableName' => 'licensor1', 'reacTableAction' => RegistActions::ACTION_UPDATE, 'reacStatus' => RegistActions::STATUS_NOTREADED]);
// if(is_null($registAction)){
// $registAction = new RegistActions();
// $registAction->setReacTableName('licensor1');
// $registAction->setReacTableId($license->getId());
// $registAction->setReacTableAction(RegistActions::ACTION_UPDATE);
// $registAction->setReacAndroidId($license->getId());
// $actualDate = Util::getCurrentDate();
// $registAction->setReacDateTime($actualDate);
// $emLev->persist($registAction);
// $emLev->flush();
// }
// }
if ($accountLicenseData[0]->getPushyKey() == '' || null == $accountLicenseData[0]->getPushyKey()) {
if (!empty($accountLicenseByPushy)) {
if ($accountLicenseData[0]->getAlLicenseUsername() != $accountLicenseByPushy[0]->getAlLicenseUsername()) {
$this->createFileJson($path, 'Error: push key registed with -> ' . $accountLicenseByPushy[0]->getAlLicenseUsername() . ' license!' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Push key registed with '.$accountLicenseByPushy[0]->getAlLicenseUsername().' license!', WebService::HTTP_CODE_UNAUTHORIZED);
}
}
$accountLicenseData[0]->setPushyKey($data['pushy']);
// $this->createFileJson($path, 'New regist action before insert new pushy key '. "\r");
// internaSaveInRegistAction($this->realContainer, $em, $accountLicenseData[0]);
} else {
if ($accountLicenseData[0]->getPushyKey() != $data['pushy']) {
if (empty($accountLicenseByPushy)) {
$accountLicenseData[0]->setPushyKey($data['pushy']);
// $this->createFileJson($path, 'New regist action before insert new pushy key '. "\r");
// internaSaveInRegistAction($this->realContainer, $em, $accountLicenseData[0]);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::HTTP_CODE_UNAUTHORIZED);
}
}
}
$em->persist($accountLicenseData[0]);
$em->flush();
Util::updateAllPushKey([
"nickname" => $accountLicenseData[0]->getAlLicenseUsername(),
"pushyKey" => $data['pushy'],
"awsPushEndPoint" => $accountLicenseData[0]->getAwsPushEndPoint(),
"awsTopicARN" => $accountLicenseData[0]->getAwsTopicARN(),
"awsSubscriptionARN" => $accountLicenseData[0]->getAwsSubscriptionARN(),
"awsDeviceToken" => $accountLicenseData[0]->getAwsDeviceToken(),
], $this->realContainer);
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Valid license and push key registered!';
$responseArr['bigbag'] = false;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
$this->createFileJson($path, 'Response to Android: ' . $jsonContent . "\r");
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid channel', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} catch (\Throwable $th) {
$err = ['Error message' => $th->getMessage(), 'Error line' => $th->getLine(), 'Error file' => $th->getFile(), 'Error trance' => $th->getTrace()];
$this->createFileJson($path, 'Alert Error: ' . json_encode($err) . "\r");
return $this->errorWrongArgs('Service error, please contact support.', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorWrongArgs('Wrong content format, please contact support.', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS para registrar la pushy key de un dispositivo de una licencia
* @author Aealan Z <lrobledo@kijho.com> 05/11/15
* @param \Symfony\Component\HttpFoundation\Request $request datos
* de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function createAndSendPusherVerificationPush(Request $request) {
// if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
// return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
// }
// if (0 !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) && 0 !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
// return $this->errorWrongArgs('Wrong Content!', WebService::CODE_WRONG_ARGUMENTS);
// }
$response = false;
$statusCode = 200;
$msg = "Valid license and pusher validation push send!";
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'createAndSendPusherVerificationPush', 'createAndSendPusherVerificationPush0.txt');
$this->createFileJson($path, "\r" . 'Register Pusher Key: ' . $request->getContent() . "\r");
$channelName = $request->get('channel_name');
$socketId = $request->get('socket_id');
try {
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['nickname']) || !isset($data['uid']) || !isset($socketId) || !isset($channelName)) {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$this->createFileJson($path, 'Decrypted: ' . $arrayEncryptResult['data'] . "\r");
if ($data['nickname'] == '' || $data['uid'] == '' || $socketId == '' || $channelName == '') {
return $this->errorWrongArgs('Empty Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
$countResult = count($accountLicenseData);
if ($countResult <= 0) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if ($accountLicenseData[0]->getDeviceUid() != $data['uid']) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Wrong device UID', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
// function internalSaveInRegistAction($container, $em, $license) {
// $emLev = Util::emLicenseConnection($container, $em, $license);
// $registAction = $emLev->getRepository('App\Structure\RegistActions')->findOneBy(['reacTableName' => 'licensor1', 'reacTableAction' => RegistActions::ACTION_UPDATE, 'reacStatus' => RegistActions::STATUS_NOTREADED]);
// if(is_null($registAction)){
// $registAction = new RegistActions();
// $registAction->setReacTableName('licensor1');
// $registAction->setReacTableId($license->getId());
// $registAction->setReacTableAction(RegistActions::ACTION_UPDATE);
// $registAction->setReacAndroidId($license->getId());
// $actualDate = Util::getCurrentDate();
// $registAction->setReacDateTime($actualDate);
// $emLev->persist($registAction);
// $emLev->flush();
// }
// }
if($channelName === 'presence-'.$data['nickname']){
if(strpos($channelName, 'presence-') !== false) {
$user = array(
"user_id" => $data['uid'],
"user_info" => [
"name" => $data['nickname']
]
);
$ownAPIsKeys = $em->getRepository('App\Entity\ThirdPartyAPIRecords')->getOwnPushServicesByLicense($accountLicenseData[0]->getId(), ThirdPartyAPIRecords::API_PUSHER);
if (!empty($ownAPIsKeys)) {
$pusher = new PusherManager($ownAPIsKeys[ThirdPartyAPIRecords::API_PUSHER]);
} else {
$pusher = new PusherManager();
}
$response = $pusher->authorizeChannel($channelName, $socketId, $user);
if(!empty($response)){
$newPusherTokenCallResult = NewUtil::generateNewPusherVerificationToken($this->realContainer, $em, $accountLicenseData[0], $path);
if (is_string($newPusherTokenCallResult)) {
$this->createFileJson($path, 'Error creating new pusher token -> ' . $newPusherTokenCallResult . "\r");
} else {
$msg = 'New pusher token created!';
$statusCode = 200;
$this->createFileJson($path, 'New pusher token created!'. "\r");
}
$pushWithSameKey = true;
$thePushKey = false;
while (!empty($pushWithSameKey)) {
$thePushKey = Util::randomPushKey();
$pushWithSameKey = $em->getRepository('App\Entity\PushSent')->searchPushSendRecords($thePushKey);
}
$pushEntity = new PushSent();
$pushVerificationCode = Util::createRegistPushSend($em, $pushEntity, PushSent::PUSH_TYPE_COMFIRM_PUSHER_LICENSE_CHANNEL, $thePushKey, $accountLicenseData[0], true, false, $path);
$response = json_decode($response, true);
$token["actions"] = 'ping';
$token["nickname"] = $accountLicenseData[0]->getAlLicenseUsername();
$token["pusherToken"] = $accountLicenseData[0]->getPusherOwnVerificationToken();
if ($pushVerificationCode && $pushVerificationCode != '') {
$this->createFileJson($path, 'Push send record created!' . "\r");
$token["code"] = $pushVerificationCode;
}
// $response['verify'] = $token;
ForcedAsynchronousCommandsUtil::sendPusherPushNotification($this->realContainer, 'presence-'.$accountLicenseData[0]->getAlLicenseUsername(), $token, 0, $path, true);
$em->persist($accountLicenseData[0]);
$em->flush();
}else {
$msg = "Not authorized channel!";
$statusCode = 403;
throw new Exception('Not authorized channel! 1');
}
} else {
$msg = "Not authorized channel!";
$statusCode = 403;
throw new Exception('Not authorized channel! 2');
}
}else {
$msg = "Not authorized channel!";
$statusCode = 403;
throw new Exception('Not authorized channel! 3');
}
// return $this->respondWithItem($jsonContent, $theUrlTrSt);
return new JsonResponse($response, $statusCode);
} catch (\Throwable $th) {
$err = ['Error message' => $th->getMessage(), 'Error line' => $th->getLine(), 'Error file' => $th->getFile(), 'Error trance' => $th->getTrace()];
$this->createFileJson($path, 'Alert Error: ' . json_encode($err) . "\r");
return $this->errorWrongArgs('Wrong Content!', WebService::CODE_WRONG_ARGUMENTS);
}
}
/**
* WS para registrar el device token de una licencia para los push de AWS
* @author Aealan Z <lrobledo@openmytab.com> 21/10/22
* @param \Symfony\Component\HttpFoundation\Request $request datos
* de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function registerAWSDeviceTokenToPushService(Request $request) {
if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
if (0 !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) && 0 !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
return $this->errorWrongArgs('Wrong Content!', WebService::CODE_WRONG_ARGUMENTS);
}
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'registerAWSDeviceTokenToPushService', 'registerAWSDeviceTokenToPushService0.txt');
$this->createFileJson($path, "\r" . 'Register AWS Device Token: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['nickname']) || !isset($data['uid']) || !isset($data['deviceToken'])) {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$this->createFileJson($path, 'Decrypted: ' . $arrayEncryptResult['data'] . "\r");
if ($data['nickname'] == '' || $data['uid'] == '' || $data['deviceToken'] == '') {
return $this->errorWrongArgs('Empty Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
$countResult = count($accountLicenseData);
if ($countResult <= 0) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$accountLicenseByPushy = $em->getRepository('App\Entity\AccountLicense')->findBy(['awsDeviceToken' => $data['deviceToken']]);
if ($accountLicenseData[0]->getPushyKey() == '' || null == $accountLicenseData[0]->getPushyKey()) {
if (!empty($accountLicenseByPushy)) {
if ($accountLicenseData[0]->getAlLicenseUsername() != $accountLicenseByPushy[0]->getAlLicenseUsername()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('DeviceToken registed with another license!', WebService::HTTP_CODE_UNAUTHORIZED);
}
}
$accountLicenseData[0]->setAwsDeviceToken($data['deviceToken']);
} else {
if ($accountLicenseData[0]->getAwsDeviceToken() != $data['deviceToken']) {
if (empty($accountLicenseByPushy)) {
$accountLicenseData[0]->setAwsDeviceToken($data['deviceToken']);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::HTTP_CODE_UNAUTHORIZED);
}
}
}
if (!$accountLicenseData[0]->getAwsTopicARN()) {
$creationTopicARNResult = NewUtil::registerAlternateNewDeviceToAWSSNSPushService($this->realContainer, $em, $accountLicenseData[0], $data['deviceToken'], $path);
$this->createFileJson($path, 'Creation of TopicARN result: ' . json_encode($creationTopicARNResult) . "\r");
}
$arrayResult = NewUtil::registerAlternateCreateAppEndpointForDeviceSNSPushService($this->realContainer, $em, $accountLicenseData[0], $data['deviceToken'], $path);
if (is_array($arrayResult) && isset($arrayResult['licenseEntity'])) {
$accountLicenseData[0] = $arrayResult['licenseEntity'];
}
if (is_array($arrayResult) && isset($arrayResult['EndpointArn'])) {
$responseArr['endpointArn'] = $arrayResult['EndpointArn'];
} else {
$responseArr['endpointArn'] = $arrayResult;
}
$arraySecondResult = NewUtil::registerAlternateSubscriptionToTopicForDeviceSNSPushService($this->realContainer, $em, $accountLicenseData[0], $path);
if (is_array($arraySecondResult) && isset($arraySecondResult['SubscriptionArn'])) {
$responseArr['subscriptionArn'] = $arraySecondResult['SubscriptionArn'];
} else {
$responseArr['subscriptionArn'] = $arraySecondResult;
}
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = "Valid license and AWS token registered with it's endpoint and topic subscription!";
$responseArr['topicArn'] = $accountLicenseData[0]->getAwsTopicARN();
$responseArr['bigbag'] = true;
Util::updateAllPushKey([
"nickname" => $accountLicenseData[0]->getAlLicenseUsername(),
"awsPushEndPoint" => $accountLicenseData[0]->getAwsPushEndPoint(),
"awsTopicARN" => $accountLicenseData[0]->getAwsTopicARN(),
"awsSubscriptionARN" => $accountLicenseData[0]->getAwsSubscriptionARN(),
"awsDeviceToken" => $accountLicenseData[0]->getAwsDeviceToken(),
], $this->realContainer);
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
/**
* WS para registrar la pushy key de un dispositivo de una licencia
* @author Aealan Z <lrobledo@kijho.com> 05/11/15
* @param \Symfony\Component\HttpFoundation\Request $request datos
* de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function registerCodeInstallToLicense(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'codeInstallRegist', 'codeInstallRegist0.txt');
$this->createFileJson($path, "\r" . 'Register Code Install: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['nickname']) || !isset($data['uid']) || !isset($data['codeInstall'])) {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$this->createFileJson($path, 'Decrypted: ' . $arrayEncryptResult['data'] . "\r");
if ($data['nickname'] == '' || $data['uid'] == '' || $data['codeInstall'] == '') {
return $this->errorWrongArgs('Empty Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
$countResult = count($accountLicenseData);
if ($countResult > 0) {
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('License is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
$accountLicenseData[0]->setApkInstallCode($data['codeInstall']);
$em->persist($accountLicenseData[0]);
$em->flush();
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Code install registered!';
$responseArr['bigbag'] = false;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid channel', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} else {
return $this->errorWrongArgs('Wrong Content!', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS para registrar la pushy key de un dispositivo de una licencia
* @author Aealan Z <lrobledo@kijho.com> 05/11/15
* @param \Symfony\Component\HttpFoundation\Request $request datos
* de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function notifyFattyAndroidDatabase(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'notifyFattyAndroidDatabase', 'notifyFattyAndroidDatabase0.txt');
$this->createFileJson($path, "\r" . 'Notify Fatty Android Database: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['nickname']) || !isset($data['uid'])) {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$this->createFileJson($path, 'Decrypted: ' . $arrayEncryptResult['data'] . "\r");
if ($data['nickname'] == '' || $data['uid'] == '') {
return $this->errorWrongArgs('Empty Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
$countResult = count($accountLicenseData);
if ($countResult > 0) {
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('License is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if (isset($data['days']) && ((int) $data['days']) > 0) {
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
$configurationLicenseRecord = $emLev->getRepository('App\Structure\Configuracion')->find(1);
$configurationLicenseRecord->setConfAllowAutoCleanseDB(1);
$configurationLicenseRecord->setConfDataSinceLastDays((int) $data['days']);
$emLev->persist($configurationLicenseRecord);
$emLev->flush();
$this->createFileJson($path, "Auto cleanse configured with '" . $data['days'] . "' ... \r");
}
$this->createFileJson($path, 'Ready for new cleanse request to be done!' . "\r");
$msg = [
'license' => $accountLicenseData[0]->getId()
];
$this->get('cleanse_for_fatty_android_database_producer')->setContentType('application/json');
$this->get('cleanse_for_fatty_android_database_producer')->setDeliveryMode(2);
$this->get('cleanse_for_fatty_android_database_producer')->publish(json_encode($msg));
$this->createFileJson($path, 'Rabbit produces message sended!' . "\r");
$data['rabbit_consumer'] = 'old_sound_rabbit_mq.operate_fatty_android_database_task_consumer';
$data['rabbit_queue'] = 'operate_fatty_android_database';
sleep(3);
ForcedAsynchronousCommandsUtil::callTheBizarreGenericConsumerCommand($this->realContainer, $data, true);
$this->createFileJson($path, 'Rabbit async consumer request sended!' . "\r");
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = "Cleanse database proccess started for '<strong>$accountLicenseData[0]</strong>' license!";
$responseArr['bigbag'] = false;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname.', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} else {
return $this->errorWrongArgs('Wrong Content!', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS para registrar la pushy key de un dispositivo de una licencia
* @author Aealan Z <lrobledo@kijho.com> 05/11/15
* @param \Symfony\Component\HttpFoundation\Request $request datos
* de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function experimentalAuthWS(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'experimentalAuthWS', 'experimentalAuthWS0.txt');
$this->createFileJson($path, "\r" . 'Experimental ecurity WS: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['nickname']) || !isset($data['uid']) || !isset($data['authCode'])) {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$this->createFileJson($path, 'Decrypted: ' . $arrayEncryptResult['data'] . "\r");
if ($data['nickname'] == '' || $data['uid'] == '' || $data['authCode'] == '') {
return $this->errorWrongArgs('Empty Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
$countResult = count($accountLicenseData);
if ($countResult > 0) {
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('License is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
// if (isset($data['authCode'])) {
// $google2fa = new Google2FA();
// $secret = $accountLicenseData[0]->getAuthSeed();
// $wasValid = $google2fa->verifyKey($secret, $data['authCode'], 10);
//
// if (!$wasValid) {
// return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
// ->respondWithError('Invalid authorization', WebService::CODE_INVALID_SECURITY_HASH);
// } else {
// $responseArr['msg'] = 'Code verified and pass!';
// $this->createFileJson($path, 'Experimental ecurity WS: Good code ;) ' . "\r");
// }
// } else {
// $responseArr['msg'] = 'Code without code verification...';
// }
$authResult = $this->validateAuth($accountLicenseData[0], $data);
if (is_string($authResult)) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError($authResult, WebService::CODE_INVALID_SECURITY_HASH);
}
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Code verified and pass!';
$responseArr['bigbag'] = false;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} else {
return $this->errorWrongArgs('Wrong content', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* Esta funcion permite al cliente adroid notificar que termino de
* subir el archivo de sincronizacion
* @author Aealan Z <lrobledo@kijho.com> 30/04/15
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function uploadSyncServiceUrlAlternate(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
$arrayRequestEncripted = [];
$arrayRequestEncripted['nickname'] = $request->request->get('nickname');
$arrayRequestEncripted['uid'] = $request->request->get('uid');
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'syncDownUpWSTest', 'syncDownUpWSTest0.txt');
$this->createFileJson($path, "\r" . 'The request ' . json_encode($arrayRequestEncripted) . "\r");
$parameters = $request->request->all();
// $this->createFileJson($path, 'All parameters in request -> ' . json_encode($parameters) . "\r");
$text = 'Hola Changoo!!';
$file = fopen($path, "a+");
fwrite($file, $text);
fclose($file);
dump($path);
dump($text);
die;
$data = [];
$arrayEncryptResult = Util::decryptDataForUploadsFiles($this->realContainer, $request->request->get('nickname'));
$data['nickname'] = $arrayEncryptResult['data'];
$arrayEncryptResult = Util::decryptDataForUploadsFiles($this->realContainer, $request->request->get('uid'));
$data['uid'] = $arrayEncryptResult['data'];
$this->createFileJson($path, 'Decripted ' . json_encode($data) . "\r");
$theTrueNameFile = $request->files->get('file')->getClientOriginalName();
$this->createFileJson($path, 'The Client IP -> ' . $request->getClientIp() . "\r");
$this->createFileJson($path, 'The File -> ' . $theTrueNameFile . "\r");
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($licenseUserName);
$forcedValidationPassed = false;
if (empty($accountLicenseData) && (null == $data['nickname'] ||
empty($data['nickname']) || $data['nickname'] == 'null') &&
(int) $this->realContainer->getParameter('device_recognition_by_ip_enabled') &&
!empty($theTrueNameFile) && $theTrueNameFile != '') {
$this->createFileJson($path, 'Forcing server android autentication... ' . "\r");
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy(['androidIP' => $request->getClientIp()]);
if (empty($accountLicenseData) || (int) $accountLicenseData[0]->getTimesCheckedIP() < (int) $this->realContainer->getParameter('ip_recognition_times_to_valid_check')) {
$accountLicenseData = [];
} else {
$forcedValidationPassed = true;
$this->createFileJson($path, 'Forced autentication succeeded! ' . "\r");
}
}
$countResult = count($accountLicenseData);
$statusArryMsg['status'] = WebService::CODE_OK_ACCEPTED;
$this->createFileJson($path, 'Number of license found -> ' . $countResult . "\r");
if ($countResult > 0) {
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
$this->createFileJson($path, 'Salio 1! ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if (!$forcedValidationPassed && $accountLicenseData[0]->getDeviceUid() != $data['uid']) {
$this->createFileJson($path, 'Salio 2! ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_ACTIVE) {
$this->createFileJson($path, 'License active! ' . "\r");
// $masterBlockingByDBUpdate = $em->getRepository('App\Entity\MasterSync')->findBy(['msLicense' => $accountLicenseData[0]->getId(), 'msType' => MasterSync::MASTER_SYNC_TYPE_DB_UPDATE, 'msStatus' => MasterSync::MASTER_STATUS_INITIALIZATED]);
//
// if (!empty($masterBlockingByDBUpdate)) {
// $this->createFileJson($path, 'Se Fue DB blocked!' . "\r");
// return $this->setStatusCode(WebService::CODE_OBJECT_NOT_FOUND)
// ->respondWithError('Synchronization blocked by DB update, please wait...', WebService::NOTHING_TO_WEB_SYNCHRONIZE);
// }
$readFilesDataEntity = $em->getRepository('App\Entity\ReadFilesData')->findBy(['rfStatus' => ReadFilesData::STATUS_UPLOADED, 'rfLicenseId' => $accountLicenseData[0]->getId(), 'hasPersistentError' => false]);
if (!empty($readFilesDataEntity)) {
$this->createFileJson($path, 'There is another sync petition in process, please wait until is finished' . "\r");
$statusArryMsg['msg'] = 'There is another sync petition in process, please wait until is finished';
$theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer, $statusArryMsg);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
$readFilesDataEntity = $em->getRepository('App\Entity\ReadFilesData')->findBy(['rfStatus' => ReadFilesData::STATUS_UPLOADED, 'rfLicenseId' => $accountLicenseData[0]->getId(), 'hasPersistentError' => true]);
if (!empty($readFilesDataEntity)) {
$this->createFileJson($path, 'There is another sync petition for this license with a problem in the sever, please contact your system supplier for more information' . "\r");
$statusArryMsg['msg'] = 'There is another sync petition for this license with a problem in the sever, please contact your system supplier for more information';
$theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer, $statusArryMsg);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
$isDirectoryReady = Util::createLicenseDirectory($this->realContainer, $accountLicenseData[0], $accountLicenseData[0]->getAlLicenseUsername());
$theAccountLicenseDirector = $isDirectoryReady['directory'];
if (!isset($isDirectoryReady['result']) || $isDirectoryReady['result'] == '__KO__') {
$msnError = 'An error occurred while creating your directory in server ';
return $this->setStatusCode(WebService::CODE_INTERNAL_ERROR)
->respondWithError($msnError, WebService::CODE_INTERNAL_ERROR);
}
$this->createFileJson($path, 'The license dir ' . $theAccountLicenseDirector . "\r");
$uploadFileResponse = Utilx::uploadFileTo($request, $theAccountLicenseDirector, $path);
dump($uploadFileResponse);
die;
///////////////////
///////////////////
if (!isset($uploadFileResponse['result']) || !isset($uploadFileResponse['msg'])) {
$this->createFileJson($path, 'Unknown error uploading file ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError('Unknown error uploading file', WebService::CODE_INTERNAL_ERROR);
}
if (isset($uploadFileResponse['result']) && isset($uploadFileResponse['msg']) && $uploadFileResponse['result'] == '__KO__') {
$this->createFileJson($path, $uploadFileResponse['msg'] . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
->respondWithError($uploadFileResponse['msg'], WebService::CODE_INTERNAL_ERROR);
}
$readFilesDataEntityByLicense = $em->getRepository('App\Entity\ReadFilesData')->findBy(['rfLicenseId' => $accountLicenseData[0]->getId(), 'rfStatus' => ReadFilesData::STATUS_STANDBY], ['rfDateSincAsk' => 'DESC']);
$this->createFileJson($path, 'The ReadFilesData count 1 -> ' . count($readFilesDataEntityByLicense) . "\r");
if (empty($readFilesDataEntityByLicense)) {
$readFilesDataEntityByLicense[0] = $this->setRegistNewFile($accountLicenseData[0]);
}
$registerStatus = $this->updateRegistUploadFile($readFilesDataEntityByLicense[0], $uploadFileResponse['fileName']);
if ($registerStatus) {
$statusArryMsg['msg'] = 'File has been uploaded and the record updated';
$this->createFileJson($path, 'File has been uploaded and the record updated' . "\r");
} else {
$this->createFileJson($path, 'Salio 9! ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_NOT_FOUND)
->respondWithError('Error updating syncronization control record', WebService::CODE_OBJECT_NOT_FOUND);
}
$licenseDataBaseEntity = $em->getRepository('App\Entity\LicenseDataBase')->findBy(['license' => $accountLicenseData[0]->getId()]);
if (!empty($licenseDataBaseEntity)) {
$pushSendRepository = $em->getRepository('App\Entity\PushSent');
$pushSendRepository->respondOldPushesForLicense(PushSent::PUSH_TYPE_SYNC_DOWNUP, $accountLicenseData[0]->getId());
$usernameByNickname = $licenseDataBaseEntity[0]->getLicense();
$theAccountPath = $this->realContainer->getParameter('level_directory_data_android') . $usernameByNickname->getAlAccountLicense()->getAcName() . '/' . $usernameByNickname->getAlLicenseUsername();
$theAccountPath = str_replace(' ', '_', $theAccountPath);
$dataOptionsRoot = [
'dbname' => $licenseDataBaseEntity[0]->getDbname(),
'user' => $licenseDataBaseEntity[0]->getDbuser(),
'password' => $licenseDataBaseEntity[0]->getDbpass(),
'host' => $licenseDataBaseEntity[0]->getDbhost(),
'driver' => 'pdo_mysql',
];
$msg = [
'id' => $readFilesDataEntityByLicense[0]->getId(),
'dataOptionsRoot' => $dataOptionsRoot,
'path' => $theAccountPath,
'fileName' => $readFilesDataEntityByLicense[0]->getRfNameFile(),
'AccountLicense' => $usernameByNickname->getAlAccountLicense()->getAcName(),
'pushchanel' => $usernameByNickname->getAlLicenseUsername()
];
$readFilesDataEntityByLicense[0]->setIsReadedByServer(true);
$em->persist($readFilesDataEntityByLicense[0]);
$em->flush();
// $this->get('incoming_android_sync_producer')->setContentType('application/json');
// $this->get('incoming_android_sync_producer')->setDeliveryMode(2);
// $this->get('incoming_android_sync_producer')->publish(json_encode($msg));
if (!$request->request->get('hold')) {
$statusArryMsg['msg'] = 'File has been uploaded and the sync process triggered';
$this->createFileJson($path, 'File has been uploaded and the sync process triggered' . "\r");
$data['readFilesDataId'] = $readFilesDataEntityByLicense[0]->getId();
// ForcedAsynchronousCommandsUtil::consumeDownUpSyncCommand($this->realContainer, $data, true);
} else {
$statusArryMsg['msg'] = 'File has been uploaded and the sync process is ready to start';
$this->createFileJson($path, 'File has been uploaded and the sync process is ready to start' . "\r");
}
}
$this->createFileJson($path, 'Track 7! ' . "\r");
$theUrlTrSt = new UploadSyncJsonNotifyTransformer($this->realContainer, $statusArryMsg);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
$this->createFileJson($path, 'Track 8! ' . "\r");
$this->createFileJson($path, 'UploadSyncJsonNotifyTransformer json to respond' . $jsonContent . "\r");
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
$this->createFileJson($path, 'Salio 3! ' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Inactive License', WebService::CODE_ACCOUNT_SUSPENDED);
}
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
public function licensorLicenseLastSync(Request $request){
if ($request->getMethod() != WebService::REQUEST_METHOD_GET) {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_GET . " method");
}
$response=$request->query->get("nicknamelicense");
if ($response == '') {
return $this->errorWrongArgs('Empty Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$em = $this->getDoctrine()->getManager();
$lastSync = $em->getRepository('App\Entity\MasterSync')->lastSyncForLicenseNickName($response);
if (!empty($lastSync)){
$date=$lastSync[0]["msDateSyncAsk"];
$stringDate = $date->format('Y-m-d H:i:s');
$lastSync[0]["msDateSyncAsk"]=$stringDate;
$lastSync = $lastSync[0];
}
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = $lastSync;
$responseArr['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
/**
* WS para registrar la pushy key de un dispositivo de una licencia
* @author Aealan Z <lrobledo@kijho.com> 05/11/15
* @param \Symfony\Component\HttpFoundation\Request $request datos
* de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function getSQLLiteQueryToCleanBadAndroidSyncDataRecords(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'getSQLLiteQueryToCleanBadAndroidSyncDataRecords', 'getSQLLiteQueryToCleanBadAndroidSyncDataRecords0.txt');
$this->createFileJson($path, "\r" . 'Incoming parameters: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['nickname']) || !isset($data['data'])) {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$this->createFileJson($path, 'Decrypted: ' . $arrayEncryptResult['data'] . "\r");
if ($data['nickname'] == '' || $data['data'] == '') {
return $this->errorWrongArgs('Empty Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
$countResult = count($accountLicenseData);
if ($countResult > 0) {
$basicJsonResponseToProcess = $data['data'];
$auxJsonDecodeArray = json_decode($basicJsonResponseToProcess, true);
$auxSQLString = "SELECT +'+ || syn_id || +'+ || +,+ FROM sync_data WHERE syn_record_id IN (";
foreach ($auxJsonDecodeArray['data'] as $tableIndex) {
foreach ($tableIndex as $tableData) {
if ($tableData) {
$auxSQLString .= "'$tableData',";
}
}
}
$auxSQLString .= ");";
$auxSQLString = str_replace(",)",")", $auxSQLString);
$auxSQLString = str_replace("+",'"', $auxSQLString);
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'SQLLite Query Obtained!';
$responseArr['sqlliteQuery'] = $auxSQLString;
$responseArr['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid channel', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} else {
return $this->errorWrongArgs('Wrong Content!', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* WS para registrar la pushy key de un dispositivo de una licencia
* @author Aealan Z <lrobledo@kijho.com> 05/11/15
* @param \Symfony\Component\HttpFoundation\Request $request datos
* de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function setBadSyncDataRecordsInRegistActionForCleanse(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
if (0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'setBadSyncDataRecordsInRegistActionForCleanse', 'setBadSyncDataRecordsInRegistActionForCleanse0.txt');
$this->createFileJson($path, "\r" . 'Incoming parameters: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
if (!isset($data['nickname']) || !isset($data['data'])) {
return $this->errorWrongArgs('Wrong Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$this->createFileJson($path, 'Decrypted: ' . $arrayEncryptResult['data'] . "\r");
if ($data['nickname'] == '' || $data['data'] == '') {
return $this->errorWrongArgs('Empty Arguments.', WebService::CODE_WRONG_ARGUMENTS);
}
$licenseUserName = ['alLicenseUsername' => $data['nickname']];
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findBy($licenseUserName);
$countResult = count($accountLicenseData);
if ($countResult > 0) {
$auxStringAndroidSyncDataIds = $data['data'];
$auxArrayToRegistActionRecord = explode(',', $auxStringAndroidSyncDataIds);
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
$insertCounter = 0;
foreach ($auxArrayToRegistActionRecord as $recordToRegistAction) {
if ($recordToRegistAction != '') {
Util::saveUpdateRecordInRegistActionsByDataArray($emLev, 'sync_data', ['level' => $recordToRegistAction, 'android' => $recordToRegistAction], 'D');
++$insertCounter;
}
}
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = "$insertCounter records where inserted into regist action! ready to sync?";
$responseArr['bigbag'] = false;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid channel', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} else {
return $this->errorWrongArgs('Wrong Content!', WebService::CODE_WRONG_ARGUMENTS);
}
} else {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
}
/**
* Crea la semilla de notificación para el contexto CONTEXT_NOTIFICATION_ANDROID_LAST_SYNC.
*
* Recibe la entidad de AccountLicense, invoca a la función getDateOfLastSync la cual trae la fecha de la ultima sincronización,
* luego se valida si la fecha retornada sea menor a la fecha actual menos una constate de días, si esto se cumple se procede a
* crear o actualizar la semilla, si este ultimo caso lleva mas de una semana de ser notificada.
*
* @author Jhonan Vargas <jsmith@openmytab.com> 19/01/2022
* @access private
* @param type AccountLicense $license
*/
public function notifyLastSyncByLicense($em, $license){
$dateLastSync = $em->getRepository('App\Entity\MasterSync')->getDateOfLastSync($license->getId());
if($dateLastSync){
$currentDate = Utilx::getCurrentDate();
$days = $this->realContainer->getParameter('max_days_without_android_sync');
$dateMinusDays = clone $currentDate;
$dateMinusDays->modify("-$days days");
if($dateMinusDays >= $dateLastSync){
$seed = $em->getRepository("App\Entity\NotificationInLicensorBell")->findOneBy(["context" => NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_LAST_SYNC, "license" => $license]);
$title = 'Android device not synced in ' . $license->getAlLicenseUsername() . ' license';
$message = "The Android device has not been synced for $days days or more.";
if(!is_null($seed)){
$dateMinusOneWeek = clone $currentDate;
$dateMinusOneWeek->modify('-1 week');
if($seed->getPickedtByValidatingCronDate()){
if ($dateMinusOneWeek >= $seed->getPickedtByValidatingCronDate()) {
$seed->setDateCreated($currentDate);
$seed->setPickedtByValidatingCronDate(null);
$seed->setNotificationMsg($message);
$em->persist($seed);
$em->flush();
}
}
} else {
$seed = new NotificationInLicensorBell();
$seed->setNotificationTitle($title);
$seed->setNotificationLabel(NotificationInLicensorBell::NOTIFICATION_TYPE_WARNING);
$seed->setNotificationMsg($message);
$seed->setDateCreated($currentDate);
$seed->setContext(NotificationInLicensorBell::CONTEXT_NOTIFICATION_ANDROID_LAST_SYNC);
$seed->setLicense($license);
$seed->setTypeRoleToNotify(NotificationInLicensorBell::ROLE_ADMINISTRATOR);
$seed->setNotificationAlt('Android has not synced');
$seed->setNotificationHTMLTitle($title);
$em->persist($seed);
$em->flush();
}
}
}
}
// public function
}