.
This commit is contained in:
@@ -84,6 +84,87 @@ public class FacebookPostingService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper class to hold page credentials (Page ID and Page Access Token)
|
||||
*/
|
||||
private static class PageCredentials {
|
||||
String pageId;
|
||||
String pageToken;
|
||||
|
||||
public PageCredentials(String pageId, String pageToken) {
|
||||
this.pageId = pageId;
|
||||
this.pageToken = pageToken;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает Page Access Token и Page ID из User Access Token
|
||||
* Вызывает /me/accounts для получения списка страниц, которыми управляет
|
||||
* пользователь
|
||||
*
|
||||
* @param userAccessToken User Access Token
|
||||
* @return PageCredentials с Page ID и Page Access Token
|
||||
* @throws FacebookTokenExpiredException если токен истек
|
||||
* @throws RuntimeException если не удалось получить credentials
|
||||
* страницы
|
||||
*/
|
||||
private PageCredentials getPageCredentials(String userAccessToken) {
|
||||
try {
|
||||
String response = webClient.get()
|
||||
.uri(uriBuilder -> uriBuilder
|
||||
.path("/me/accounts")
|
||||
.queryParam("access_token", userAccessToken)
|
||||
.build())
|
||||
.retrieve()
|
||||
.bodyToMono(String.class)
|
||||
.block(Duration.ofMillis(timeoutMs));
|
||||
|
||||
JsonNode jsonNode = objectMapper.readTree(response);
|
||||
|
||||
// Проверяем наличие массива data
|
||||
if (!jsonNode.has("data") || !jsonNode.get("data").isArray()) {
|
||||
logger.error("Facebook API response does not contain 'data' array");
|
||||
throw new RuntimeException("Failed to get page credentials: no pages found in response");
|
||||
}
|
||||
|
||||
JsonNode dataArray = jsonNode.get("data");
|
||||
if (dataArray.size() == 0) {
|
||||
logger.error("User has no pages available");
|
||||
throw new RuntimeException("Failed to get page credentials: user has no pages");
|
||||
}
|
||||
|
||||
// Берем первую страницу из списка
|
||||
JsonNode firstPage = dataArray.get(0);
|
||||
String pageId = firstPage.has("id") ? firstPage.get("id").asText() : null;
|
||||
String pageToken = firstPage.has("access_token") ? firstPage.get("access_token").asText() : null;
|
||||
|
||||
if (pageId == null || pageToken == null) {
|
||||
logger.error("Page credentials incomplete: pageId={}, pageToken={}", pageId,
|
||||
pageToken != null ? "present" : "null");
|
||||
throw new RuntimeException("Failed to get page credentials: incomplete page data");
|
||||
}
|
||||
|
||||
logger.info("Successfully retrieved page credentials for page ID: {}", pageId);
|
||||
return new PageCredentials(pageId, pageToken);
|
||||
|
||||
} catch (WebClientResponseException e) {
|
||||
if (isTokenExpiredError(e)) {
|
||||
throw parseFacebookError(e);
|
||||
}
|
||||
logger.error("Failed to get Facebook page credentials: {} - {}", e.getStatusCode(),
|
||||
e.getResponseBodyAsString());
|
||||
throw new RuntimeException("Failed to get page credentials: " + e.getMessage(), e);
|
||||
} catch (JsonProcessingException e) {
|
||||
logger.error("Failed to parse Facebook page credentials response", e);
|
||||
throw new RuntimeException("Failed to parse page credentials response", e);
|
||||
} catch (FacebookTokenExpiredException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
logger.error("Unexpected error getting page credentials", e);
|
||||
throw new RuntimeException("Failed to get page credentials", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает ID страницы пользователя
|
||||
*/
|
||||
@@ -169,11 +250,12 @@ public class FacebookPostingService {
|
||||
// Формируем полный текст поста с хештегами
|
||||
String fullPostText = buildPostText(postText, hashtags);
|
||||
|
||||
// Получаем ID страницы пользователя (me)
|
||||
String pageId = getPageId(accessToken);
|
||||
// Получаем Page Access Token и Page ID из User Access Token
|
||||
PageCredentials creds = getPageCredentials(accessToken);
|
||||
|
||||
// Загружаем изображение и публикуем пост
|
||||
String postId = publishPostWithImage(accessToken, pageId, fullPostText, imageData, imageContentType);
|
||||
// Загружаем изображение и публикуем пост используя Page Token
|
||||
String postId = publishPostWithImage(creds.pageToken, creds.pageId, fullPostText, imageData,
|
||||
imageContentType);
|
||||
|
||||
logger.info("Successfully posted to Facebook with image. Post ID: {}", postId);
|
||||
return postId;
|
||||
|
||||
Reference in New Issue
Block a user