24 private static array $httpClients = [];
37 if (!$this->initHttpClient())
39 $this->deactivateConnection();
51 private function initHttpClient(
bool $force =
false): bool
55 if (!isset(self::$httpClients[
$userId]) || $force)
57 if (!Loader::includeModule(
'socialservices'))
63 $oAuthEntity = $this->prepareAuthEntity(
$userId);
65 if ($oAuthEntity->getToken())
67 $httpClient->setHeader(
'Authorization',
'Bearer ' . $oAuthEntity->getToken());
68 $httpClient->setHeader(
'Content-Type',
'application/json');
80 $this->httpClient = self::$httpClients[
$userId];
90 private function prepareAuthEntity(
int $userId): \CGoogleOAuthInterface|\CGoogleProxyOAuthInterface
92 if (\CSocServGoogleProxyOAuth::isProxyAuth())
94 $oAuth = new \CSocServGoogleProxyOAuth(
$userId);
98 $oAuth = new \CSocServGoogleOAuth(
$userId);
101 $oAuthEntity = $oAuth->getEntityOAuth();
102 $oAuthEntity->addScope([
103 'https://www.googleapis.com/auth/calendar',
104 'https://www.googleapis.com/auth/calendar.readonly'
106 $oAuthEntity->removeScope(
'https://www.googleapis.com/auth/drive');
108 $oAuthEntity->setUser(
$userId);
113 $oAuthEntity->setToken($tokens[
'OATOKEN']);
114 $oAuthEntity->setAccessTokenExpires($tokens[
'OATOKEN_EXPIRES']);
115 $oAuthEntity->setRefreshToken($tokens[
'REFRESH_TOKEN']);
118 if (!$oAuthEntity->checkAccessToken())
120 $oAuthEntity->getNewAccessToken(
121 $oAuthEntity->getRefreshToken(),
130 private function deactivateConnection()
132 if ($this->connection->getId())
135 ->setStatus(
'[401] Unauthorized')
136 ->setLastSyncTime(
new Core\Base\Date())
140 $mapperFactory = ServiceLocator::getInstance()->get(
'calendar.service.mappers.factory');
141 $mapperFactory->getConnection()->update($this->connection);
144 PushCommand::RefreshSyncStatus,
145 $this->connection->getOwner()->getId(),
150 'type' => $this->connection->getAccountType(),
152 'id' => $this->connection->getId(),
164 return \Bitrix\Socialservices\UserTable::query()
165 ->setSelect([
'USER_ID',
'EXTERNAL_AUTH_ID',
'OATOKEN',
'OATOKEN_EXPIRES',
'REFRESH_TOKEN'])
167 ->where(
'EXTERNAL_AUTH_ID',
'GoogleOAuth')
177 return $this->httpClient->getStatus() === 200;
182 $acceptedCodes = [200, 201, 204, 404];
184 return in_array($this->httpClient->getStatus(), $acceptedCodes);
195 $oAuth = $this->prepareAuthEntity(
$userId);
197 $refreshResult =
false;
199 if ($userTokenInfo[
'REFRESH_TOKEN'])
201 $refreshResult = $oAuth->getNewAccessToken($userTokenInfo[
'REFRESH_TOKEN'],
$userId,
true);
206 $this->deactivateConnection();