|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace leocata\m1Bot\Workers; |
|
4
|
|
|
|
|
5
|
|
|
use leocata\M1\Api; |
|
6
|
|
|
use leocata\m1Bot\Bot\BaseBot; |
|
7
|
|
|
use leocata\m1Bot\Events\WebSocketEvents; |
|
8
|
|
|
use Ratchet\Client\Connector; |
|
9
|
|
|
use Ratchet\Client\WebSocket; |
|
10
|
|
|
use Ratchet\RFC6455\Messaging\MessageInterface; |
|
11
|
|
|
use React\EventLoop\Factory; |
|
12
|
|
|
|
|
13
|
|
|
class WebSocketWorker |
|
14
|
|
|
{ |
|
15
|
|
|
private $subProtocol = 'json.api.smile-soft.com'; |
|
16
|
|
|
private $wssHost = 'wss://m1online.net'; |
|
17
|
|
|
private $host = 'm1online.net'; |
|
18
|
|
|
private $auth; |
|
19
|
|
|
private $events; |
|
20
|
|
|
private $apiWrapper; |
|
21
|
|
|
private $gearmanClient; |
|
22
|
|
|
|
|
23
|
|
|
public function __construct(BaseBot $baseBot) |
|
24
|
|
|
{ |
|
25
|
|
|
$this->events = new WebSocketEvents(); |
|
26
|
|
|
$this->auth = $baseBot->getAuth(); |
|
27
|
|
|
$this->apiWrapper = new Api(); |
|
28
|
|
|
$this->gearmanClient = new \GearmanClient(); |
|
29
|
|
|
$this->gearmanClient->addServer(); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function execute() |
|
33
|
|
|
{ |
|
34
|
|
|
$loop = Factory::create(); |
|
35
|
|
|
$connector = new Connector($loop); |
|
36
|
|
|
|
|
37
|
|
|
$connector($this->wssHost, [$this->subProtocol], ['Host' => $this->host] + $this->auth->getBasicAuth())->then( |
|
38
|
|
|
|
|
39
|
|
|
function (WebSocket $stream) { |
|
40
|
|
|
$stream->on('message', function (MessageInterface $message) { |
|
41
|
|
|
$this->events->message($message, $this->apiWrapper, $this->gearmanClient); |
|
42
|
|
|
}); |
|
43
|
|
|
$stream->on('close', function ($code = null, $reason = null) { |
|
44
|
|
|
$this->events->close($code, $reason); |
|
45
|
|
|
}); |
|
46
|
|
|
}, function (\Exception $e) use ($loop) { |
|
47
|
|
|
$this->events->error($e); |
|
48
|
|
|
$loop->stop(); |
|
49
|
|
|
} |
|
50
|
|
|
); |
|
51
|
|
|
|
|
52
|
|
|
$loop->run(); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* @param string $host |
|
57
|
|
|
*/ |
|
58
|
|
|
public function setHost(string $host) |
|
59
|
|
|
{ |
|
60
|
|
|
$this->host = $host; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @param string $wssHost |
|
65
|
|
|
*/ |
|
66
|
|
|
public function setWssHost(string $wssHost) |
|
67
|
|
|
{ |
|
68
|
|
|
$this->wssHost = $wssHost; |
|
69
|
|
|
} |
|
70
|
|
|
/** |
|
71
|
|
|
* @param string $subProtocol |
|
72
|
|
|
*/ |
|
73
|
|
|
public function setSubProtocol(string $subProtocol) |
|
74
|
|
|
{ |
|
75
|
|
|
$this->subProtocol = $subProtocol; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|