refactor(tgbot-front): replaced the context usage with a new thread-safe one

This commit is contained in:
Kirill 2025-12-06 05:05:10 +03:00
parent a6848bb4d7
commit dc4c430231

View file

@ -42,37 +42,26 @@ void BotHandlers::processCallbackImpl(TgBot::CallbackQuery::Ptr query) {
int64_t userId = query->from->id;
int64_t chatId = query->message->chat->id;
int64_t messageId = query->message->messageId;
auto it = userContexts.find(userId);
if (it == userContexts.end()) {
std::optional<UserContext> ctx = contextManager.getContext(userId);
if (!ctx.has_value()) {
// TODO: log
sendError(chatId, messageId, BotConstants::Text::AUTH_ERROR);
std::cout << "Error: Не нашел пользователя " << userId;
return;
}
UserContext& ctx = it->second;
if (data.starts_with(BotConstants::Callback::NAVIGATION)) {
handleNavigation(query, ctx);
handleNavigation(query);
}
else if (data.starts_with(BotConstants::Callback::ERROR)) {
handleError(query, ctx);
handleError(query);
}
else {
botApi.sendMessage(query->message->chat->id, BotConstants::Text::SAD_ERROR, nullptr, nullptr);
}
}
void BotHandlers::pushState(UserContext& ctx, UserState newState, int64_t payload) {
ctx.history.push_back({newState, payload});
}
bool BotHandlers::popState(UserContext& ctx) {
if (ctx.history.size() <= 1) return false; // нельзя выйти из MAIN_MENU
ctx.history.pop_back();
return true;
}
void BotHandlers::reducePayload(int64_t& payload, const UserState curState) {
if (curState == UserState::VIEWING_MY_TITLES ||
curState == UserState::VIEWING_FOUND_TITLES) {
@ -130,19 +119,15 @@ void BotHandlers::sendError(int64_t chatId, int64_t messageId, const std::string
editMessage(chatId, messageId, {errText, keyboard});
}
void BotHandlers::createInitContext(int64_t chatId) {
NavigationStep init = {UserState::MAIN_MENU, BotConstants::NULL_PAYLOAD};
userContexts[chatId] = {chatId, {init}};
}
void BotHandlers::handleError(TgBot::CallbackQuery::Ptr query, UserContext& ctx) {
void BotHandlers::handleError(TgBot::CallbackQuery::Ptr query) {
const std::string& data = query->data;
int64_t userId = query->from->id;
int64_t chatId = query->message->chat->id;
int64_t messageId = query->message->messageId;
if(data == BotConstants::Callback::ERROR_NAVIGATION) {
ctx.history.clear();
ctx.history.push_back({UserState::MAIN_MENU, 0});
contextManager.removeContext(userId);
contextManager.createInitContext(userId);
auto result = showMainMenu();
editMessage(chatId, messageId, result);
}
@ -152,3 +137,7 @@ void BotHandlers::handleError(TgBot::CallbackQuery::Ptr query, UserContext& ctx)
editMessage(chatId, messageId, result);
}
}
void BotHandlers::initUser(int64_t userId) {
contextManager.createInitContext(userId);
}