1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Nucleus - XMPP Library for PHP |
4
|
|
|
* |
5
|
|
|
* Copyright (C) 2016, Some rights reserved. |
6
|
|
|
* |
7
|
|
|
* @author Kacper "Kadet" Donat <[email protected]> |
8
|
|
|
* |
9
|
|
|
* Contact with author: |
10
|
|
|
* Xmpp: [email protected] |
11
|
|
|
* E-mail: [email protected] |
12
|
|
|
* |
13
|
|
|
* From Kadet with love. |
14
|
|
|
*/ |
15
|
|
|
|
16
|
|
|
namespace Kadet\Xmpp\Component; |
17
|
|
|
|
18
|
|
|
|
19
|
|
|
use Kadet\Xmpp\Stanza\Iq; |
20
|
|
|
use Kadet\Xmpp\XmppClient; |
21
|
|
|
use \Kadet\Xmpp\Utils\filter as with; |
22
|
|
|
use React\EventLoop\Timer\TimerInterface; |
23
|
|
|
|
24
|
|
|
class PingKeepAlive extends Component |
25
|
|
|
{ |
26
|
|
|
/** @var float|int */ |
27
|
|
|
private $_interval = 15; |
28
|
|
|
/** @var TimerInterface */ |
29
|
|
|
private $_timer; |
30
|
|
|
|
31
|
|
|
private $_handler = null; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* PingKeepAlive constructor. |
35
|
|
|
* |
36
|
|
|
* @param float|false $interval Keep alive interval in seconds or false to turn off |
37
|
|
|
*/ |
38
|
5 |
|
public function __construct($interval = 60.) |
39
|
|
|
{ |
40
|
5 |
|
$this->_interval = $interval; |
41
|
5 |
|
} |
42
|
|
|
|
43
|
4 |
|
public function setClient(XmppClient $client) |
44
|
|
|
{ |
45
|
4 |
|
parent::setClient($client); |
46
|
4 |
|
$this->_client->on('state', [$this, 'enable'], \Kadet\Xmpp\Utils\filter\equals('ready')); |
47
|
|
|
|
48
|
|
|
$this->_handler = $this->_client->on('iq', function(Iq $iq) { |
49
|
1 |
|
$this->handleIq($iq); |
50
|
4 |
|
}, with\all(with\iq\query(with\element('ping', 'urn:xmpp:ping')), with\stanza\type('get'))); |
51
|
4 |
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Starts keep alive timer |
55
|
|
|
*/ |
56
|
2 |
|
public function enable() |
57
|
|
|
{ |
58
|
2 |
|
if($this->_interval) { |
59
|
2 |
|
$this->_timer = $this->_client->connector->getLoop()->addPeriodicTimer($this->_interval, function() { |
60
|
1 |
|
$this->keepAlive(); |
61
|
2 |
|
}); |
62
|
|
|
} |
63
|
2 |
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Stops keep alive timer |
67
|
|
|
*/ |
68
|
|
|
public function disable() |
69
|
|
|
{ |
70
|
|
|
if($this->_timer) { |
71
|
|
|
$this->_timer->cancel(); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
$this->_client->removeListener('iq', $this->_handler); |
75
|
|
|
} |
76
|
|
|
|
77
|
1 |
|
private function keepAlive() |
78
|
|
|
{ |
79
|
1 |
|
$ping = new Iq('get', ['query' => new Iq\Query('urn:xmpp:ping', 'ping')]); |
80
|
|
|
|
81
|
1 |
|
$this->_client->write($ping); |
82
|
1 |
|
} |
83
|
|
|
|
84
|
1 |
|
private function handleIq(Iq $iq) |
85
|
|
|
{ |
86
|
1 |
|
$response = $iq->response(); |
87
|
1 |
|
$response->type = 'result'; |
88
|
1 |
|
$response->query = new Iq\Query('urn:xmpp:ping', 'ping'); |
89
|
|
|
|
90
|
1 |
|
$this->_client->write($response); |
91
|
1 |
|
} |
92
|
|
|
} |
93
|
|
|
|