fix docker for tauri app

This commit is contained in:
lendry
2026-06-26 16:43:17 +03:00
parent f1068edc89
commit 3ab48d8537
11 changed files with 220 additions and 76 deletions

View File

@@ -914,7 +914,9 @@ export class AuthGrpcController {
inviteeUserId: command.inviteeUserId
});
if (invite.status === 'ACCEPTED') {
await this.chat.syncFamilyChats(command.groupId);
if (invite.inviteeUserId) {
await this.chat.ensureBotRoomForMember(command.groupId, command.requesterId, invite.inviteeUserId);
}
}
return invite;
}
@@ -1192,8 +1194,8 @@ export class AuthGrpcController {
}
@GrpcMethod('BotService', 'SubmitBotInboundMessage')
submitBotInboundMessage(command: { senderUserId: string; botRef: string; text: string }) {
return this.botInbound.submitUserMessage(command.senderUserId, command.botRef, command.text);
submitBotInboundMessage(command: { senderUserId: string; botRef: string; text: string; roomId?: string }) {
return this.botInbound.submitUserMessage(command.senderUserId, command.botRef, command.text, command.roomId);
}
@GrpcMethod('BotService', 'SubmitBotCallbackQuery')
@@ -1202,8 +1204,8 @@ export class AuthGrpcController {
}
@GrpcMethod('BotService', 'ListBotChatMessages')
listBotChatMessages(command: { userId: string; botRef: string }) {
return this.botApi.listBotChatMessages(command.userId, command.botRef);
listBotChatMessages(command: { userId: string; botRef: string; roomId?: string }) {
return this.botApi.listBotChatMessages(command.userId, command.botRef, command.roomId);
}
private toSessionResponse(session: { id: string; userId: string; deviceId: string | null; pinVerified: boolean; status: string; ipAddress: string | null; userAgent: string | null; expiresAt: Date; createdAt: Date; updatedAt: Date }) {

View File

@@ -208,7 +208,7 @@ export class BotApiService {
return message;
}
async listBotChatMessages(userId: string, botRef: string) {
async listBotChatMessages(userId: string, botRef: string, roomId?: string) {
const sender = await this.prisma.user.findUnique({
where: { id: userId },
select: { isSystemAccount: true, linkedBotId: true, deletedAt: true, status: true }
@@ -247,10 +247,12 @@ export class BotApiService {
};
}
const chat = await this.prisma.botChat.findUnique({
where: { botId_recipientUserId: { botId: bot.id, recipientUserId: userId } },
include: { menuButton: true }
});
const chat = roomId
? await this.resolveSharedFamilyBotChat(bot.id, userId, roomId)
: await this.prisma.botChat.findUnique({
where: { botId_recipientUserId: { botId: bot.id, recipientUserId: userId } },
include: { menuButton: true }
});
const composer = this.resolveComposerForBot(bot, chat?.menuButton?.menuButton ?? null);
const emptyResponse = {
@@ -336,6 +338,30 @@ export class BotApiService {
};
}
private async resolveSharedFamilyBotChat(botId: string, viewerUserId: string, roomId: string) {
const room = await this.prisma.chatRoom.findUnique({
where: { id: roomId },
include: {
members: { include: { user: { select: { linkedBotId: true } } } }
}
});
if (!room || room.type !== 'BOT' || !room.members.some((member) => member.userId === viewerUserId)) {
return null;
}
const botMember = room.members.find((member) => member.user.linkedBotId === botId);
if (!botMember || room.peerUserId !== botMember.userId) {
return null;
}
const ownerUserId =
room.createdById ??
room.members.find((member) => !member.user.linkedBotId)?.userId ??
viewerUserId;
return this.prisma.botChat.findUnique({
where: { botId_recipientUserId: { botId, recipientUserId: ownerUserId } },
include: { menuButton: true }
});
}
private async setChatMenuButton(bot: ValidatedBot, payload: SetChatMenuButtonPayload) {
const chatIdRaw = payload.chat_id;
const parsedMenuButton = parseMenuButtonInput(payload.menu_button);
@@ -865,7 +891,7 @@ export class BotApiService {
mediaUrl?: string
) {
const payloadMarkup = this.serializer.readPayload(message.payload);
await this.notifications.publishRealtime(userId, 'bot_message', bot.name, message.text ?? '', {
const payload = {
botId: bot.id,
botUsername: bot.username,
chatId: chat.telegramChatId.toString(),
@@ -875,7 +901,9 @@ export class BotApiService {
mediaUrl: message.mediaUrl ?? mediaUrl ?? null,
replyMarkup: replyMarkup ?? payloadMarkup.replyMarkup ?? null,
telegramReplyMarkup: payloadMarkup.telegramReplyMarkup ?? null
});
};
await this.notifications.publishRealtime(userId, 'bot_message', bot.name, message.text ?? '', payload);
await this.publishToSharedBotRoomMembers(userId, bot, 'bot_message', message.text ?? '', payload);
}
private async publishBotMessagePinned(
@@ -888,14 +916,16 @@ export class BotApiService {
pinnedAt?: Date | null;
}
) {
await this.notifications.publishRealtime(userId, 'bot_message_pinned', bot.name, '', {
const payload = {
botId: bot.id,
botUsername: bot.username,
chatId: chat.telegramChatId.toString(),
messageId: message.telegramMsgId,
isPinned: Boolean(message.isPinned),
pinnedAt: message.pinnedAt?.toISOString() ?? null
});
};
await this.notifications.publishRealtime(userId, 'bot_message_pinned', bot.name, '', payload);
await this.publishToSharedBotRoomMembers(userId, bot, 'bot_message_pinned', '', payload);
}
private async publishBotMessageEdited(
@@ -913,7 +943,7 @@ export class BotApiService {
replyMarkup: unknown
) {
const payloadMarkup = this.serializer.readPayload(message.payload);
await this.notifications.publishRealtime(userId, 'bot_message_edited', bot.name, message.text ?? '', {
const payload = {
botId: bot.id,
botUsername: bot.username,
chatId: chat.telegramChatId.toString(),
@@ -924,7 +954,41 @@ export class BotApiService {
replyMarkup: replyMarkup ?? payloadMarkup.replyMarkup ?? null,
telegramReplyMarkup: payloadMarkup.telegramReplyMarkup ?? null,
editedAt: message.editedAt?.toISOString() ?? new Date().toISOString()
};
await this.notifications.publishRealtime(userId, 'bot_message_edited', bot.name, message.text ?? '', payload);
await this.publishToSharedBotRoomMembers(userId, bot, 'bot_message_edited', message.text ?? '', payload);
}
private async publishToSharedBotRoomMembers(
ownerUserId: string,
bot: ValidatedBot,
eventType: string,
message: string,
payload: Record<string, unknown>
) {
const rooms = await this.prisma.chatRoom.findMany({
where: {
type: 'BOT',
botUsername: bot.username,
createdById: ownerUserId
},
include: {
members: { include: { user: { select: { linkedBotId: true } } } }
}
});
const recipients = new Set<string>();
for (const room of rooms) {
for (const member of room.members) {
if (member.userId !== ownerUserId && !member.user.linkedBotId) {
recipients.add(member.userId);
}
}
}
await Promise.all(
[...recipients].map((recipientId) => this.notifications.publishRealtime(recipientId, eventType, bot.name, message, payload))
);
}
private mergePayload(existing: unknown, parsed: ReturnType<TelegramSerializerService['parseReplyMarkup']>) {

View File

@@ -17,7 +17,7 @@ export class BotInboundService {
private readonly seed: BotFatherSeedService,
private readonly assistant: BotFatherAssistantService
) {}
async submitUserMessage(senderUserId: string, botRef: string, text: string) {
async submitUserMessage(senderUserId: string, botRef: string, text: string, roomId?: string) {
await this.assertHumanSender(senderUserId);
const trimmedText = text.trim();
@@ -30,7 +30,9 @@ export class BotInboundService {
throw new NotFoundException('Бот не найден или заблокирован');
}
const chat = await this.ensureBotChat(bot.id, senderUserId);
const chat = roomId
? await this.resolveSharedFamilyBotChat(bot.id, senderUserId, roomId)
: await this.ensureBotChat(bot.id, senderUserId);
const event = await this.createMessageEvent(bot.id, chat.id, senderUserId, chat.telegramChatId, trimmedText);
await this.dispatchEvent(event);
if (bot.isSystemBot) {
@@ -210,4 +212,25 @@ export class BotInboundService {
return fallback;
}
}
private async resolveSharedFamilyBotChat(botId: string, senderUserId: string, roomId: string) {
const room = await this.prisma.chatRoom.findUnique({
where: { id: roomId },
include: {
members: { include: { user: { select: { linkedBotId: true } } } }
}
});
if (!room || room.type !== 'BOT' || !room.members.some((member) => member.userId === senderUserId)) {
throw new NotFoundException('Чат с ботом не найден');
}
const botMember = room.members.find((member) => member.user.linkedBotId === botId);
if (!botMember || room.peerUserId !== botMember.userId) {
throw new NotFoundException('Бот не найден в этом чате');
}
const ownerUserId =
room.createdById ??
room.members.find((member) => !member.user.linkedBotId)?.userId ??
senderUserId;
return this.ensureBotChat(botId, ownerUserId);
}
}

View File

@@ -127,8 +127,6 @@ export class ChatService {
});
const humans = members.filter((member) => !member.user.linkedBotId);
const bots = members.filter((member) => member.user.linkedBotId);
const legacyRooms = await this.prisma.chatRoom.findMany({
where: { groupId, type: 'GROUP' },
include: { members: true }
@@ -177,17 +175,23 @@ export class ChatService {
}
}
for (const botMember of bots) {
for (const human of humans) {
await this.ensureBotRoom(
groupId,
human.userId,
botMember.userId,
botMember.user.linkedBot!.username,
botMember.user.displayName
);
}
// BOT-чаты создаются только для тех людей, которым явно выдали доступ к боту.
// Не создаём комнаты "каждый человек x каждый бот", иначе бот становится видимым всей семье.
}
async ensureBotRoomForMember(groupId: string, requesterId: string, botUserId: string) {
const group = await this.family.assertFamilyMember(groupId, requesterId);
const botMember = group.members.find((member) => member.userId === botUserId);
if (!botMember?.user?.linkedBotId || !botMember.user.linkedBot) {
throw new BadRequestException('Бот не найден в этой семье');
}
return this.ensureBotRoom(
groupId,
requesterId,
botUserId,
botMember.user.linkedBot.username,
botMember.user.displayName
);
}
async createRoom(userId: string, groupId: string, name: string, memberUserIds: string[]) {
@@ -313,7 +317,7 @@ export class ChatService {
if (room.type === 'GENERAL') {
throw new BadRequestException('В общий чат нельзя добавлять участников вручную');
}
if (room.type === 'DIRECT' || room.type === 'BOT' || room.type === 'E2E') {
if (room.type === 'DIRECT' || room.type === 'E2E') {
throw new BadRequestException('Нельзя изменять состав личного чата или чата с ботом');
}
if (room.members.some((member) => member.userId === memberUserId)) {
@@ -322,6 +326,15 @@ export class ChatService {
if (!room.group.members.some((member) => member.userId === memberUserId)) {
throw new BadRequestException('Пользователь должен состоять в семье');
}
if (room.type === 'BOT') {
const targetUser = await this.prisma.user.findUnique({
where: { id: memberUserId },
select: { linkedBotId: true, isSystemAccount: true }
});
if (!targetUser || targetUser.linkedBotId || targetUser.isSystemAccount) {
throw new BadRequestException('В чат с ботом можно добавить только обычного участника семьи');
}
}
await this.prisma.chatRoomMember.create({
data: { roomId, userId: memberUserId }
@@ -335,21 +348,24 @@ export class ChatService {
if (room.type === 'GENERAL') {
throw new BadRequestException('Нельзя удалить участника из общего чата');
}
if (room.type === 'DIRECT' || room.type === 'BOT' || room.type === 'E2E') {
if (room.type === 'DIRECT' || room.type === 'E2E') {
throw new BadRequestException('Нельзя изменять состав личного чата или чата с ботом');
}
const isFamilyOwner = room.group.ownerId === userId;
const isChatCreator = room.createdById === userId;
if (!isFamilyOwner && !isChatCreator) {
if (room.type !== 'BOT' && !isFamilyOwner && !isChatCreator) {
throw new ForbiddenException('Недостаточно прав для удаления участника из чата');
}
if (room.type === 'BOT' && memberUserId === room.peerUserId) {
throw new BadRequestException('Нельзя удалить бота из его чата');
}
if (memberUserId === room.createdById && !isFamilyOwner) {
throw new BadRequestException('Создателя чата может удалить только создатель семьи');
}
if (memberUserId === userId && room.members.length <= 1) {
if (memberUserId === userId && room.members.length <= (room.type === 'BOT' ? 2 : 1)) {
throw new BadRequestException('В чате должен остаться хотя бы один участник');
}
@@ -915,7 +931,7 @@ export class ChatService {
userId: string;
notificationsMuted: boolean;
pinnedAt?: Date | null;
user: { displayName: string; avatarStorageKey: string | null; isVerified: boolean; verificationIcon: string | null };
user: { displayName: string; avatarStorageKey: string | null; isVerified: boolean; verificationIcon: string | null; linkedBotId?: string | null };
}>;
},
familyRoleByUserId: Map<string, string>,
@@ -924,9 +940,11 @@ export class ChatService {
) {
const viewerMembership = viewerId ? room.members.find((member) => member.userId === viewerId) : undefined;
const peerMember =
viewerId && (room.type === 'DIRECT' || room.type === 'BOT' || room.type === 'E2E')
? room.members.find((member) => member.userId !== viewerId)
: undefined;
room.type === 'BOT'
? room.members.find((member) => Boolean(member.user.linkedBotId))
: viewerId && (room.type === 'DIRECT' || room.type === 'E2E')
? room.members.find((member) => member.userId !== viewerId)
: undefined;
return {
id: room.id,
@@ -1195,6 +1213,7 @@ export class ChatService {
name: botDisplayName,
peerUserId: botUserId,
botUsername,
createdById: humanUserId,
isE2E: false,
members: {
create: [{ userId: humanUserId }, { userId: botUserId }]

View File

@@ -106,7 +106,7 @@ export class FamilyService {
return this.toGroup(group);
return this.toGroup(group, ownerId);
}
@@ -124,7 +124,7 @@ export class FamilyService {
});
return { groups: groups.map((group) => this.toGroup(group)) };
return { groups: await Promise.all(groups.map((group) => this.toGroup(group, userId))) };
}
@@ -136,7 +136,7 @@ export class FamilyService {
this.assertMember(group, requesterId);
return this.toGroup(group);
return this.toGroup(group, requesterId);
}
@@ -166,7 +166,7 @@ export class FamilyService {
});
return this.toGroup(updated);
return this.toGroup(updated, requesterId);
}
@@ -457,23 +457,30 @@ export class FamilyService {
throw new BadRequestException('Пользователь не найден. Выберите его из результатов поиска.');
}
const inviter = await this.prisma.user.findUnique({ where: { id: requesterId } });
const isBotInvite = isProtectedSystemAccount(invitee);
const inviteeAlreadyInFamily = group.members.some((member) => member.userId === invitee.id);
if (invitee.id === requesterId) {
throw new BadRequestException('Нельзя пригласить самого себя');
}
if (group.members.some((member) => member.userId === invitee.id)) {
if (isBotInvite) {
const visibleBotUserIds = await this.getVisibleBotUserIds(groupId, requesterId);
if (visibleBotUserIds.has(invitee.id)) {
throw new BadRequestException('Этот бот уже доступен вам в семье');
}
} else if (inviteeAlreadyInFamily) {
throw new BadRequestException('Пользователь уже состоит в семье');
}
const existingPending = await this.prisma.familyInvite.findFirst({
where: { groupId, inviteeUserId: invitee.id, status: 'PENDING' }
});
if (existingPending) {
if (existingPending && !isBotInvite) {
throw new BadRequestException('Приглашение уже отправлено');
}
const inviter = await this.prisma.user.findUnique({ where: { id: requesterId } });
const isBotInvite = isProtectedSystemAccount(invitee);
if (isBotInvite) {
const invite = await this.prisma.familyInvite.create({
data: {
@@ -490,7 +497,9 @@ export class FamilyService {
inviter: true
}
});
await this.addMember(groupId, invitee.id, 'bot');
if (!inviteeAlreadyInFamily) {
await this.addMember(groupId, invitee.id, 'bot');
}
await this.notifications.create(
requesterId,
'family_bot_added',
@@ -537,24 +546,18 @@ export class FamilyService {
return { users: [] };
}
const excludedIds = [...group.members.map((member) => member.userId), requesterId];
const excludedBotUsernames = new Set(
group.members
.map((member) => member.user?.linkedBot?.username)
.filter((username): username is string => Boolean(username))
);
const excludedIds = [...group.members.filter((member) => !member.user?.linkedBotId).map((member) => member.userId), requesterId];
const visibleBotUserIds = await this.getVisibleBotUserIds(groupId, requesterId);
const botFatherUserId = await this.botFatherSeed.getBotFatherUserId();
const botFatherBotId = await this.botFatherSeed.getBotFatherBotId();
const getMyIdUserId = await this.botFatherSeed.getGetMyIdBotUserId();
const getMyIdBotId = await this.botFatherSeed.getGetMyIdBotId();
const botFatherMatches =
/bot\s*father|бот\s*father|botfather/i.test(trimmed) &&
!excludedIds.includes(botFatherUserId) &&
!excludedBotUsernames.has(BOTFATHER_BOT_USERNAME);
!visibleBotUserIds.has(botFatherUserId);
const getMyIdMatches =
/get\s*my\s*id|getmyid|мой\s*id|айди|chat[_\s-]*id/i.test(trimmed) &&
!excludedIds.includes(getMyIdUserId) &&
!excludedBotUsernames.has(GET_MY_ID_BOT_USERNAME);
!visibleBotUserIds.has(getMyIdUserId);
const digits = trimmed.replace(/\D/g, '');
const normalizedBotQuery = normalizeBotUsername(trimmed.replace(/^@/, ''));
@@ -619,13 +622,12 @@ export class FamilyService {
}> = [];
for (const bot of matchedBots) {
if (excludedBotUsernames.has(bot.username)) continue;
if (botFatherMatches && bot.username === BOTFATHER_BOT_USERNAME) continue;
if (getMyIdMatches && bot.username === GET_MY_ID_BOT_USERNAME) continue;
const { userId } = bot.linkedSystemUser
? { userId: bot.linkedSystemUser.id }
: await this.botFather.ensureBotSystemUser(bot.id);
if (excludedIds.includes(userId)) continue;
if (visibleBotUserIds.has(userId)) continue;
botCandidates.push({
id: userId,
botId: bot.id,
@@ -963,7 +965,7 @@ export class FamilyService {
private toGroup(group: {
private async toGroup(group: {
id: string;
@@ -1000,7 +1002,9 @@ export class FamilyService {
}>;
}) {
}, viewerId?: string) {
const visibleBotUserIds = viewerId ? await this.getVisibleBotUserIds(group.id, viewerId) : new Set<string>();
const visibleMembers = group.members.filter((member) => !member.user?.linkedBotId || visibleBotUserIds.has(member.userId));
return {
@@ -1016,13 +1020,13 @@ export class FamilyService {
updatedAt: group.updatedAt.toISOString(),
members: group.members.map((member) => this.toMember(member)),
members: visibleMembers.map((member) => this.toMember(member)),
botFatherAvailable: !group.members.some(
botFatherAvailable: !visibleMembers.some(
(member) => member.user?.linkedBot?.username === BOTFATHER_BOT_USERNAME
),
getMyIdBotAvailable: !group.members.some(
getMyIdBotAvailable: !visibleMembers.some(
(member) => member.user?.linkedBot?.username === GET_MY_ID_BOT_USERNAME
)
@@ -1030,6 +1034,27 @@ export class FamilyService {
}
private async getVisibleBotUserIds(groupId: string, viewerId: string) {
const rooms = await this.prisma.chatRoom.findMany({
where: {
groupId,
type: 'BOT',
members: { some: { userId: viewerId } }
},
include: {
members: {
include: { user: { select: { linkedBotId: true } } }
}
}
});
return new Set(
rooms
.flatMap((room) => room.members)
.filter((member) => Boolean(member.user.linkedBotId))
.map((member) => member.userId)
);
}
private toMember(member: {