ApiController.php
5.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
<?php
/**
* Created by PhpStorm.
* User: eduardo
* Date: 14/10/14
* Time: 01:36
*/
namespace Swpb\Bundle\CocarBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Swpb\Bundle\CocarBundle\Entity\PrinterCounter;
use Swpb\Bundle\CocarBundle\Entity\Printer;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
/**
* Class ApiController
* @package Swpb\Bundle\CocarBundle\Controller
*
* @Route("/api")
*/
class ApiController extends Controller {
/**
* @Route("/login", name="api_login")
* @Method("POST")
* Faz login do agente do Cocar
*/
public function loginAction(Request $request)
{
$logger = $this->get('logger');
$em = $this->getDoctrine()->getManager();
$data = $request->getContent();
$session = $request->getSession();
$session->start();
$chavecrip = '123456';
$usuario = $this->get('security.context')->getToken()->getUser();
$logger->debug("Usuario encontrado: ".$usuario->getUserName());
$auth = new JsonResponse();
$auth->setContent(json_encode(array(
'session' => $session->getId(),
'chavecrip' => $usuario->getApiKey()
)));
return $auth;
}
/**
* @param $ip_addr
* @Route("/printer/{ip_addr}", name="printer_counter_update")
* @Method("POST")
*/
public function printerAction($ip_addr, Request $request) {
$em = $this->getDoctrine()->getManager();
$logger = $this->get('logger');
$status = $request->getContent();
$dados = json_decode($status, true);
if (empty($dados)) {
$logger->error("JSON INVÁLIDO!!!!!!!!!!!!!!!!!!! Erro no envio das informações da impressora $ip_addr");
// Retorna erro se o JSON for inválido
$error_msg = '{
"message": "JSON Inválido",
"codigo": 1
}';
$response = new JsonResponse();
$response->setStatusCode('500');
$response->setContent($error_msg);
return $response;
}
$logger->debug("Atualizando informações para a impressora com IP = $ip_addr\n".$status);
$printer = $em->getRepository('CocarBundle:Printer')->findOneBy(array('host' => $ip_addr));
if (empty($printer)) {
$logger->error("COLETA: Impressora não cadastrada: $ip_addr. Inserindo....");
// Insere impressora que não estiver cadastrada
$printer = new Printer();
// FIXME: Deve ser retornado pelo Cocar
$data = new \DateTime();
$printer->setCommunitySnmpPrinter('public');
$printer->setHost($ip_addr);
$printer->setDescription('Impressora detectada automaticamente em '.$data->format('d/m/Y'));
$printer->setName("Impressora $ip_addr");
}
$counter = $this->getDoctrine()->getManager()->getRepository('CocarBundle:PrinterCounter')->findBy(array(
'printer' => $printer->getId(),
'date' => $dados['counter_time']
));
if(empty($counter)) {
$counter = new PrinterCounter;
} else {
$this->get('logger')->error("Entrada repetida para impressora". $printer->getId() ." e data ".$dados['counter_time']);
$response = new JsonResponse();
$response->setStatusCode('200');
return $response;
}
// Atualiza impressora sempre que alterar o serial
if (!empty($dados['model'])) {
$printer->setName($dados['model']);
}
if (!empty($dados['serial'])) {
$printer->setSerie($dados['serial']);
}
if (!empty($dados['description'])) {
$printer->setDescription($dados['description']);
}
// Grava o contador
$counter->setPrinter($printer);
$counter->setPrints($dados['counter']);
$counter->setDate($dados['counter_time']);
$em->persist($printer);
$em->persist($counter);
$em->flush();
$response = new JsonResponse();
$response->setStatusCode('200');
return $response;
}
/**
* @Route("/printer", name="printer_list")
* @Method("GET")
*/
public function printerListAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$logger = $this->get('logger');
$printer = $em->getRepository('CocarBundle:Printer')->findAll();
$teste = array();
foreach($printer as $elm) {
$saida = array(
'network_ip' => $elm->getHost(),
'community' => $elm->getCommunitySnmpPrinter()
);
array_push($teste, $saida);
}
$dados = json_encode(array(
'printers'=> $teste
),
true);
$logger->debug("Enviando lista de impressoras \n".$dados);
$response = new JsonResponse();
$response->setStatusCode('200');
$response->setContent($dados);
return $response;
}
}