23 private static array $httpClients = [];
33 parent::__construct($connection);
34 $this->userId = $userId;
36 if (!$this->initHttpClient())
38 $this->deactivateConnection();
50 private function initHttpClient(
bool $force =
false): bool
53 $userId = $this->userId;
54 if (!isset(self::$httpClients[$userId]) || $force)
56 if (!Loader::includeModule(
'socialservices'))
62 $oAuthEntity = $this->prepareAuthEntity($userId);
64 if ($oAuthEntity->getToken())
66 $httpClient->setHeader(
'Authorization',
'Bearer ' . $oAuthEntity->getToken());
67 $httpClient->setHeader(
'Content-Type',
'application/json');
68 $httpClient->setHeader(
'Referer', \
Bitrix\Calendar\Sync\
Util\Helper::getDomain());
76 self::$httpClients[$userId] =
new HttpQuery($httpClient, $userId);
79 $this->httpClient = self::$httpClients[$userId];
89 private function prepareAuthEntity(
int $userId): \CGoogleOAuthInterface|\CGoogleProxyOAuthInterface
91 if (\CSocServGoogleProxyOAuth::isProxyAuth())
93 $oAuth = new \CSocServGoogleProxyOAuth($userId);
97 $oAuth = new \CSocServGoogleOAuth($userId);
100 $oAuthEntity = $oAuth->getEntityOAuth();
101 $oAuthEntity->addScope(Helper::NEED_SCOPE);
102 $oAuthEntity->setUser($userId);
107 $oAuthEntity->setToken($tokens[
'OATOKEN']);
108 $oAuthEntity->setAccessTokenExpires($tokens[
'OATOKEN_EXPIRES']);
109 $oAuthEntity->setRefreshToken($tokens[
'REFRESH_TOKEN']);
112 if (!$oAuthEntity->checkAccessToken())
114 $oAuthEntity->getNewAccessToken(
115 $oAuthEntity->getRefreshToken(),
124 private function deactivateConnection()
126 if ($this->connection->getId())
129 ->setStatus(
'[401] Unauthorized')
130 ->setLastSyncTime(
new Core\Base\Date())
134 $mapperFactory = ServiceLocator::getInstance()->get(
'calendar.service.mappers.factory');
135 $mapperFactory->getConnection()->update($this->connection);
141 'type' => $this->connection->getAccountType(),
143 'id' => $this->connection->getId(),
154 return \Bitrix\Socialservices\UserTable::query()
155 ->setSelect([
'USER_ID',
'EXTERNAL_AUTH_ID',
'OATOKEN',
'OATOKEN_EXPIRES',
'REFRESH_TOKEN'])
156 ->where(
'USER_ID', $userId)
157 ->where(
'EXTERNAL_AUTH_ID',
'GoogleOAuth')
167 return $this->httpClient->getStatus() === 200;
172 $acceptedCodes = [200, 201, 204, 404];
174 return in_array($this->httpClient->getStatus(), $acceptedCodes);
184 $userId = $connection->getOwner()->getId();
185 $oAuth = $this->prepareAuthEntity($userId);
187 $refreshResult =
false;
189 if ($userTokenInfo[
'REFRESH_TOKEN'])
191 $refreshResult = $oAuth->getNewAccessToken($userTokenInfo[
'REFRESH_TOKEN'], $userId,
true);
196 $this->deactivateConnection();