ClientImpl.php
13.1 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
<?php
declare(ticks=1);
/**
* TCP Client implementation for AMI.
*
* PHP Version 5
*
* @category Pami
* @package Client
* @subpackage Impl
* @author Marcelo Gornstein <[email protected]>
* @license http://marcelog.github.com/PAMI/ Apache License 2.0
* @version SVN: $Id$
* @link http://marcelog.github.com/PAMI/
*
* Copyright 2011 Marcelo Gornstein <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace PAMI\Client\Impl;
use PAMI\Message\OutgoingMessage;
use PAMI\Message\Message;
use PAMI\Message\IncomingMessage;
use PAMI\Message\Action\LoginAction;
use PAMI\Message\Action\LogoffAction;
use PAMI\Message\Response\ResponseMessage;
use PAMI\Message\Event\EventMessage;
use PAMI\Message\Event\Factory\Impl\EventFactoryImpl;
use PAMI\Listener\IEventListener;
use PAMI\Client\Exception\ClientException;
use PAMI\Client\IClient;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* TCP Client implementation for AMI.
*
* PHP Version 5
*
* @category Pami
* @package Client
* @subpackage Impl
* @author Marcelo Gornstein <[email protected]>
* @license http://marcelog.github.com/PAMI/ Apache License 2.0
* @link http://marcelog.github.com/PAMI/
*/
class ClientImpl implements IClient
{
/**
* PSR-3 logger.
* @var Logger
*/
private $logger;
/**
* Hostname
* @var string
*/
private $host;
/**
* TCP Port.
* @var integer
*/
private $port;
/**
* Username
* @var string
*/
private $user;
/**
* Password
* @var string
*/
private $pass;
/**
* Connection timeout, in seconds.
* @var integer
*/
private $cTimeout;
/**
* Connection scheme, like tcp:// or tls://
* @var string
*/
private $scheme;
/**
* Event factory.
* @var EventFactoryImpl
*/
private $eventFactory;
/**
* R/W timeout, in milliseconds.
* @var integer
*/
private $rTimeout;
/**
* Our stream socket resource.
* @var resource
*/
private $socket;
/**
* Our stream context resource.
* @var resource
*/
private $context;
/**
* Our event listeners
* @var IEventListener[]
*/
private $eventListeners;
/**
* The receiving queue.
* @var IncomingMessage[]
*/
private $incomingQueue;
/**
* Our current received message. May be incomplete, will be completed
* eventually with an EOM.
* @var string
*/
private $currentProcessingMessage;
/**
* This should not happen. Asterisk may send responses without a
* corresponding ActionId.
* @var string
*/
private $lastActionId;
/**
* Opens a tcp connection to ami.
*
* @throws \PAMI\Client\Exception\ClientException
* @return void
*/
public function open()
{
$cString = $this->scheme . $this->host . ':' . $this->port;
$this->context = stream_context_create();
$errno = 0;
$errstr = '';
$this->socket = @stream_socket_client(
$cString,
$errno,
$errstr,
$this->cTimeout,
STREAM_CLIENT_CONNECT,
$this->context
);
if ($this->socket === false) {
throw new ClientException('Error connecting to ami: ' . $errstr);
}
$msg = new LoginAction($this->user, $this->pass);
$asteriskId = @stream_get_line($this->socket, 1024, Message::EOL);
if (strstr($asteriskId, 'Asterisk') === false) {
throw new ClientException(
"Unknown peer. Is this an ami?: $asteriskId"
);
}
$response = $this->send($msg);
if (!$response->isSuccess()) {
throw new ClientException(
'Could not connect: ' . $response->getMessage()
);
}
@stream_set_blocking($this->socket, 0);
$this->currentProcessingMessage = '';
$this->logger->debug('Logged in successfully to ami.');
}
/**
* Registers the given listener so it can receive events. Returns the generated
* id for this new listener. You can pass in a an IEventListener, a Closure,
* and an array containing the object and name of the method to invoke. Can specify
* an optional predicate to invoke before calling the callback.
*
* @param mixed $listener
* @param \Closure|null $predicate
*
* @return string
*/
public function registerEventListener($listener, $predicate = null)
{
$listenerId = uniqid('PamiListener');
$this->eventListeners[$listenerId] = array($listener, $predicate);
return $listenerId;
}
/**
* Unregisters an event listener.
*
* @param string $listenerId The id returned by registerEventListener.
*
* @return void
*/
public function unregisterEventListener($listenerId)
{
if (isset($this->eventListeners[$listenerId])) {
unset($this->eventListeners[$listenerId]);
}
}
/**
* Reads a complete message over the stream until EOM.
*
* @throws ClientException
* @return \string[]
*/
protected function getMessages()
{
$msgs = array();
// Read something.
$read = @fread($this->socket, 65535);
if ($read === false || @feof($this->socket)) {
throw new ClientException('Error reading');
}
$this->currentProcessingMessage .= $read;
// If we have a complete message, then return it. Save the rest for
// later.
while (($marker = strpos($this->currentProcessingMessage, Message::EOM))) {
$msg = substr($this->currentProcessingMessage, 0, $marker);
$this->currentProcessingMessage = substr(
$this->currentProcessingMessage,
$marker + strlen(Message::EOM)
);
$msgs[] = $msg;
}
return $msgs;
}
/**
* Main processing loop. Also called from send(), you should call this in
* your own application in order to continue reading events and responses
* from ami.
*/
public function process()
{
$msgs = $this->getMessages();
foreach ($msgs as $aMsg) {
$this->logger->debug(
'------ Received: ------ ' . "\n" . $aMsg . "\n\n"
);
$resPos = strpos($aMsg, 'Response:');
$evePos = strpos($aMsg, 'Event:');
if (($resPos !== false) &&
(($resPos < $evePos) || $evePos === false)
) {
$response = $this->messageToResponse($aMsg);
$this->incomingQueue[$response->getActionId()] = $response;
} elseif ($evePos !== false) {
$event = $this->messageToEvent($aMsg);
$response = $this->findResponse($event);
if ($response === false || $response->isComplete()) {
$this->dispatch($event);
} else {
$response->addEvent($event);
}
} else {
// broken ami.. sending a response with events without
// Event and ActionId
$bMsg = 'Event: ResponseEvent' . "\r\n";
$bMsg .= 'ActionId: ' . $this->lastActionId . "\r\n" . $aMsg;
$event = $this->messageToEvent($bMsg);
$response = $this->findResponse($event);
$response->addEvent($event);
}
$this->logger->debug('----------------');
}
}
/**
* Tries to find an associated response for the given message.
*
* @param IncomingMessage $message Message sent by asterisk.
*
* @return \PAMI\Message\Response\ResponseMessage
*/
protected function findResponse(IncomingMessage $message)
{
$actionId = $message->getActionId();
if (isset($this->incomingQueue[$actionId])) {
return $this->incomingQueue[$actionId];
}
return false;
}
/**
* Dispatchs the incoming message to a handler.
*
* @param \PAMI\Message\IncomingMessage $message Message to dispatch.
*
* @return void
*/
protected function dispatch(IncomingMessage $message)
{
foreach ($this->eventListeners as $data) {
$listener = $data[0];
$predicate = $data[1];
if (is_callable($predicate) && !call_user_func($predicate, $message)) {
continue;
}
if ($listener instanceof \Closure) {
$listener($message);
} elseif (is_array($listener)) {
$listener[0]->{$listener[1]}($message);
} else {
$listener->handle($message);
}
}
}
/**
* Returns a ResponseMessage from a raw string that came from asterisk.
*
* @param string $msg Raw string.
*
* @return \PAMI\Message\Response\ResponseMessage
*/
private function messageToResponse($msg)
{
$response = new ResponseMessage($msg);
$actionId = $response->getActionId();
if (is_null($actionId)) {
$actionId = $this->lastActionId;
$response->setActionId($this->lastActionId);
}
return $response;
}
/**
* Returns a EventMessage from a raw string that came from asterisk.
*
* @param string $msg Raw string.
*
* @return \PAMI\Message\Event\EventMessage
*/
private function messageToEvent($msg)
{
return $this->eventFactory->createFromRaw($msg);
}
/**
* Returns a message (response) related to the given message. This uses
* the ActionID tag (key).
*
* @todo not suitable for multithreaded applications.
*
* @return \PAMI\Message\IncomingMessage
*/
protected function getRelated(OutgoingMessage $message)
{
$ret = false;
$id = $message->getActionID('ActionID');
if (isset($this->incomingQueue[$id])) {
$response = $this->incomingQueue[$id];
if ($response->isComplete()) {
unset($this->incomingQueue[$id]);
$ret = $response;
}
}
return $ret;
}
/**
* Sends a message to ami.
*
* @param \PAMI\Message\OutgoingMessage $message Message to send.
*
* @see ClientImpl::send()
* @throws \PAMI\Client\Exception\ClientException
* @return \PAMI\Message\Response\ResponseMessage
*/
public function send(OutgoingMessage $message)
{
$messageToSend = $message->serialize();
$length = strlen($messageToSend);
$this->logger->debug(
'------ Sending: ------ ' . "\n" . $messageToSend . '----------'
);
$this->lastActionId = $message->getActionId();
if (@fwrite($this->socket, $messageToSend) < $length) {
throw new ClientException('Could not send message');
}
$read = 0;
while ($read <= $this->rTimeout) {
$this->process();
$response = $this->getRelated($message);
if ($response != false) {
$this->lastActionId = false;
return $response;
}
usleep(1000); // 1ms delay
if ($this->rTimeout > 0) {
$read++;
}
}
throw new ClientException('Read timeout');
}
/**
* Closes the connection to ami.
*
* @return void
*/
public function close()
{
$this->logger->debug('Closing connection to asterisk.');
@stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
}
/**
* Sets the logger implementation.
*
* @param Psr\Log\LoggerInterface $logger The PSR3-Logger
*
* @return void
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* Constructor.
*
* @param string[] $options Options for ami client.
*
*/
public function __construct(array $options)
{
$this->logger = new NullLogger;
$this->host = $options['host'];
$this->port = intval($options['port']);
$this->user = $options['username'];
$this->pass = $options['secret'];
$this->cTimeout = $options['connect_timeout'];
$this->rTimeout = $options['read_timeout'];
$this->scheme = isset($options['scheme']) ? $options['scheme'] : 'tcp://';
$this->eventListeners = array();
$this->eventFactory = new EventFactoryImpl();
$this->incomingQueue = array();
$this->lastActionId = false;
}
}