Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
Sender.php
1<?php
2
4
5use Bitrix\ImConnector\Library;
6use Bitrix\ImOpenLines\Im;
7use Bitrix\ImOpenLines\Session;
13
15{
21
22 public function __construct(
23 Providers\OptionManager $optionManager,
24 Providers\SupportChecker $supportChecker,
25 Providers\Edna\EdnaRu $utils,
26 EmojiConverter $emoji
27 )
28 {
29 parent::__construct($optionManager, $supportChecker, $utils);
30 $this->emoji = $emoji;
31
32 $this->connectorLine = new ConnectorLine($this->utils);
33 }
34
35 protected function getSendMessageMethod(array $messageFields): string
36 {
37 return Providers\Edna\Constants\Method::SEND_MESSAGE;
38 }
39
47 public function prepareMessageBodyForSave(string $text): string
48 {
49 return $this->emoji->convertEmoji($text, InternalOption::EMOJI_ENCODE);
50 }
51
52 protected function getSendMessageParams(array $messageFields): Result
53 {
54 $cascadeResult = new Result();
55 if (is_numeric($messageFields['MESSAGE_FROM']))
56 {
57 $cascadeResult = $this->utils->getCascadeIdFromSubject(
58 (int)$messageFields['MESSAGE_FROM'],
59 static function(array $externalSubjectData, int $internalSubject)
60 {
61 return $externalSubjectData['id'] === $internalSubject;
62 }
63 );
64 }
65 elseif (is_string($messageFields['MESSAGE_FROM']))
66 {
67 $cascadeResult = $this->utils->getCascadeIdFromSubject(
68 $messageFields['MESSAGE_FROM'],
69 static function(array $externalSubjectData, string $internalSubject)
70 {
71 return $externalSubjectData['subject'] === $internalSubject;
72 }
73 );
74 }
75 else
76 {
77 return $cascadeResult->addError(new Error('Invalid subject id'));
78 }
79
80 if (!$cascadeResult->isSuccess())
81 {
82 return $cascadeResult;
83 }
84
85 $messageFields['MESSAGE_BODY'] = $this->emoji->convertEmoji($messageFields['MESSAGE_BODY'], InternalOption::EMOJI_DECODE);
86
87 $params = [
88 'requestId' => uniqid('', true),
89 'cascadeId' => $cascadeResult->getData()['cascadeId'],
90 'subscriberFilter' => [
91 'address' => str_replace('+', '', $messageFields['MESSAGE_TO']),
92 'type' => 'PHONE',
93 ],
94 ];
95
96 $params['content'] = $this->getMessageContent($messageFields);
97 $result = new Result();
98 $result->setData($params);
99
100 return $result;
101 }
102
112 public function isTemplateMessage(array $messageFields): bool
113 {
114 if (isset($messageFields['MESSAGE_HEADERS']['template']['text']))
115 {
116 return true;
117 }
118
119 return false;
120 }
121
126 protected function getMessageContent(array $messageFields): array
127 {
128 $whatsAppContent =
129 $this->isTemplateMessage($messageFields)
130 ? $this->getHSMContent($messageFields)
131 : $this->getSimpleMessageContent($messageFields)
132 ;
133
134 return [
135 'whatsappContent' => $whatsAppContent
136 ];
137 }
138
143 private function getHSMContent(array $messageFields): array
144 {
145 $params = [
146 'contentType' => Providers\Edna\Constants\ContentType::TEXT,
147 'text' => $messageFields['MESSAGE_HEADERS']['template']['text']
148 ];
149
150 foreach (['header', 'footer', 'keyboard'] as $templateField)
151 {
152 if (
153 isset($messageFields['MESSAGE_HEADERS']['template'][$templateField])
154 && count($messageFields['MESSAGE_HEADERS']['template'][$templateField]) > 0
155 )
156 {
157 $params[$templateField] = $messageFields['MESSAGE_HEADERS']['template'][$templateField];
158 }
159 }
160
161 return $this->emoji->convertEmojiInTemplate($params, InternalOption::EMOJI_DECODE);
162 }
163
168 private function getSimpleMessageContent(array $messageFields): array
169 {
170 return [
171 'contentType' => 'TEXT',
172 'text' => $messageFields['MESSAGE_BODY']
173 ];
174 }
175
176 protected function sendHSMtoChat(array $messageFields): Result
177 {
178 if (!Loader::includeModule('imopenlines') || !Loader::includeModule('imconnector'))
179 {
180 return (new Result())->addError(new Error('Missing modules imopenlines and imconnector'));
181 }
182
183 $externalChatId = str_replace('+', '', $messageFields['MESSAGE_TO']);
184 $userId = $this->getImconnectorUserId($externalChatId);
185 if (!$userId)
186 {
187 return (new Result())->addError(new Error('Missing User Id'));
188 }
189
190 $from = $messageFields['MESSAGE_FROM'];
191 $lineId = $this->connectorLine->getLineId();
192 $userSessionCode = $this->getSessionUserCode($lineId, $externalChatId, $from, $userId);
193 $chatId = $this->getOpenedSessionChatId($userSessionCode);
194 if (!$chatId)
195 {
196 return (new Result())->addError(new Error('Missing Chat Id'));
197 }
198
199 $messageId = Im::addMessage([
200 'TO_CHAT_ID' => $chatId,
201 'MESSAGE' => $this->utils->prepareTemplateMessageText($messageFields),
202 'SYSTEM' => 'Y',
203 'SKIP_COMMAND' => 'Y',
204 'NO_SESSION_OL' => 'Y',
205 'PARAMS' => [
206 'CLASS' => 'bx-messenger-content-item-ol-output'
207 ],
208 ]);
209
210 $result = new Result();
211 $resultData = $messageFields;
212 $resultData['messageId'] = $messageId;
213 $resultData['chatId'] = $chatId;
214 $result->setData($resultData);
215
216 if (!$messageId)
217 {
218 $result->addError(new Error('Error sending a message to the chat'));
219 }
220 return $result;
221 }
222
223 protected function getImconnectorUserId(string $externalChatId): ?string
224 {
225 $userXmlId = Library::ID_EDNA_WHATSAPP_CONNECTOR . '|' . $externalChatId;
226 $user = \Bitrix\Main\UserTable::getRow([
227 'select' => ['ID'],
228 'filter' => ['=XML_ID' => $userXmlId],
229 ]);
230
231 return $user ? $user['ID'] : null;
232 }
233
234 protected function getSessionUserCode(string $lineId, string $externalChatId, string $from, string $userId): string
235 {
236 return Library::ID_EDNA_WHATSAPP_CONNECTOR. '|'. $lineId. '|'. $externalChatId. '@'. $from. '|' . $userId;
237 }
238
239 protected function getOpenedSessionChatId(string $userSessionCode): ?string
240 {
241 $session = new Session();
242 $sessionLoadResult = $session->getLast(['USER_CODE' => $userSessionCode]);
243 if (!$sessionLoadResult->isSuccess())
244 {
245 return null;
246 }
247 $sessionData = $session->getData();
248 $chatId = $sessionData['CHAT_ID'];
249 $closed = $sessionData['CLOSED'] === 'Y';
250 if ($closed)
251 {
252 return null;
253 }
254
255 return $chatId;
256 }
257
258 protected function initializeDefaultExternalSender(): Providers\ExternalSender
259 {
260 return new ExternalSender(
261 $this->optionManager->getOption(InternalOption::API_KEY),
262 RegionHelper::getApiEndPoint(),
263 $this->optionManager->getSocketTimeout(),
264 $this->optionManager->getStreamTimeout()
265 );
266 }
267}
addError(Error $error)
Definition result.php:50
getSessionUserCode(string $lineId, string $externalChatId, string $from, string $userId)
Definition Sender.php:234
__construct(Providers\OptionManager $optionManager, Providers\SupportChecker $supportChecker, Providers\Edna\EdnaRu $utils, EmojiConverter $emoji)
Definition Sender.php:22