Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
Push.php
1<?php
2
3namespace Bitrix\Im\V2\Link;
4
5use Bitrix\Im\V2\Common\ContextCustomer;
8
9class Push
10{
11 use ContextCustomer;
12
13 protected const MODULE_ID = 'im';
14
15 protected array $events;
16 protected array $recipientByChatId;
17 private static Push $instance;
18 private bool $isJobPlanned = false;
19
20 private function __construct()
21 {
22 }
23
24 public static function getInstance(): self
25 {
26 if (!isset(self::$instance))
27 {
28 self::$instance = new self();
29 }
30
31 return self::$instance;
32 }
33
34 public function sendFull(LinkRestConvertible $link, string $eventName, array $endpoint): void
35 {
36 $this->send((new RestAdapter($link))->toRestFormat(), $eventName, $endpoint);
37 }
38
39 public function sendIdOnly(LinkRestConvertible $link, string $eventName, array $endpoint): void
40 {
41 $this->send($link->toRestFormatIdOnly(), $eventName, $endpoint);
42 }
43
44 protected function send(array $params, string $eventName, array $endpoint): void
45 {
46 if (isset($endpoint['CHAT_ID']))
47 {
48 $recipient = $this->getRecipientByChatId((int)$endpoint['CHAT_ID']);
49 }
50 elseif (isset($endpoint['RECIPIENT']))
51 {
52 $recipient = $endpoint['RECIPIENT'];
53 }
54 else
55 {
56 return;
57 }
58
59 $this->events[] = [
60 'recipient' => $recipient,
61 'params' => [
62 'module_id' => self::MODULE_ID,
63 'command' => $eventName,
64 'params' => $params,
65 'extra' => \Bitrix\Im\Common::getPullExtra(),
66 ],
67 ];
68
69 $this->deferRun();
70 }
71
72 protected function push(): void
73 {
74 if (!\Bitrix\Main\Loader::includeModule('pull'))
75 {
76 return;
77 }
78 foreach ($this->events as $event)
79 {
80 \Bitrix\Pull\Event::add($event['recipient'], $event['params']);
81 }
82 $this->isJobPlanned = false;
83 $this->events = [];
84 }
85
86 protected function deferRun(): void
87 {
88 if (!$this->isJobPlanned)
89 {
90 Application::getInstance()->addBackgroundJob(function () {
91 $this->push();
92 });
93 $this->isJobPlanned = true;
94 }
95 }
96
97 protected function getRecipientByChatId(int $chatId): array
98 {
99 if (isset($this->recipientByChatId[$chatId]))
100 {
101 return $this->recipientByChatId[$chatId];
102 }
103
104 $relations = \Bitrix\Im\Chat::getRelation($chatId, ['SELECT' => ['ID', 'USER_ID'], 'WITHOUT_COUNTERS' => 'Y']);
105 $this->recipientByChatId[$chatId] = array_keys($relations);
106
107 return $this->recipientByChatId[$chatId];
108 }
109}