family update
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Get, Headers, Param, Patch, Post, Query } from '@nestjs/common';
|
||||
import { Body, Controller, Delete, Get, Headers, Param, Patch, Post, Query } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
@@ -6,7 +6,10 @@ import { map } from 'rxjs/operators';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { getAuthorizedUserId } from '../document-access';
|
||||
import {
|
||||
AddChatRoomMemberDto,
|
||||
CreateChatRoomDto,
|
||||
EditChatMessageDto,
|
||||
MarkRoomReadDto,
|
||||
SendChatMessageDto,
|
||||
SetRoomNotificationsMutedDto,
|
||||
UpdateChatRoomDto,
|
||||
@@ -71,6 +74,28 @@ export class ChatController {
|
||||
);
|
||||
}
|
||||
|
||||
@Post('rooms/:roomId/members')
|
||||
@ApiOperation({ summary: 'Добавить участника в чат' })
|
||||
async addMember(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('roomId') roomId: string,
|
||||
@Body() dto: AddChatRoomMemberDto
|
||||
) {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(this.core.chat.AddRoomMember({ userId, roomId, memberUserId: dto.memberUserId }));
|
||||
}
|
||||
|
||||
@Delete('rooms/:roomId/members/:memberUserId')
|
||||
@ApiOperation({ summary: 'Удалить участника из чата' })
|
||||
async removeMember(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('roomId') roomId: string,
|
||||
@Param('memberUserId') memberUserId: string
|
||||
) {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(this.core.chat.RemoveRoomMember({ userId, roomId, memberUserId }));
|
||||
}
|
||||
|
||||
@Get('rooms/:roomId/messages')
|
||||
@ApiOperation({ summary: 'Сообщения чата' })
|
||||
async listMessages(
|
||||
@@ -139,4 +164,35 @@ export class ChatController {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(this.core.chat.SetRoomNotificationsMuted({ userId, roomId, muted: dto.muted }));
|
||||
}
|
||||
|
||||
@Patch('messages/:messageId')
|
||||
@ApiOperation({ summary: 'Редактировать сообщение' })
|
||||
async editMessage(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('messageId') messageId: string,
|
||||
@Body() dto: EditChatMessageDto
|
||||
) {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(this.core.chat.EditMessage({ userId, messageId, content: dto.content }));
|
||||
}
|
||||
|
||||
@Delete('messages/:messageId')
|
||||
@ApiOperation({ summary: 'Удалить сообщение' })
|
||||
async deleteMessage(@Headers('authorization') authorization: string | undefined, @Param('messageId') messageId: string) {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(this.core.chat.DeleteMessage({ userId, messageId }));
|
||||
}
|
||||
|
||||
@Post('rooms/:roomId/read')
|
||||
@ApiOperation({ summary: 'Отметить сообщения чата прочитанными' })
|
||||
async markRoomRead(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('roomId') roomId: string,
|
||||
@Body() dto: MarkRoomReadDto
|
||||
) {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(
|
||||
this.core.chat.MarkRoomRead({ userId, roomId, lastMessageId: dto.lastMessageId })
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,5 +144,12 @@ export class FamilyController {
|
||||
const userId = await this.auth(authorization);
|
||||
return firstValueFrom(this.core.family.RespondFamilyInvite({ userId, inviteId, accept: dto.accept }));
|
||||
}
|
||||
|
||||
@Get('groups/:groupId/presence')
|
||||
@ApiOperation({ summary: 'Онлайн-статус участников семьи' })
|
||||
async getPresence(@Headers('authorization') authorization: string | undefined, @Param('groupId') groupId: string) {
|
||||
const requesterId = await this.auth(authorization);
|
||||
return firstValueFrom(this.core.family.GetFamilyPresence({ requesterId, groupId }));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -256,4 +256,37 @@ export class MediaController {
|
||||
this.core.media.GetChatMediaAccessUrl({ requesterId, roomId, storageKey, fileName })
|
||||
);
|
||||
}
|
||||
|
||||
@Post('chat/:roomId/avatar/upload-url')
|
||||
@ApiBearerAuth()
|
||||
async createChatRoomAvatarUploadUrl(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('roomId') roomId: string,
|
||||
@Body() dto: AvatarUploadDto
|
||||
) {
|
||||
const requesterId = await this.authUserId(authorization);
|
||||
return firstValueFrom(
|
||||
this.core.media.CreateChatRoomAvatarUploadUrl({ requesterId, roomId, contentType: dto.contentType })
|
||||
);
|
||||
}
|
||||
|
||||
@Post('chat/:roomId/avatar/confirm')
|
||||
@ApiBearerAuth()
|
||||
async confirmChatRoomAvatar(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Param('roomId') roomId: string,
|
||||
@Body() dto: ConfirmAvatarDto
|
||||
) {
|
||||
const requesterId = await this.authUserId(authorization);
|
||||
return firstValueFrom(
|
||||
this.core.media.ConfirmChatRoomAvatar({ requesterId, roomId, storageKey: dto.storageKey })
|
||||
);
|
||||
}
|
||||
|
||||
@Get('chat/:roomId/avatar/url')
|
||||
@ApiBearerAuth()
|
||||
async getChatRoomAvatarUrl(@Headers('authorization') authorization: string | undefined, @Param('roomId') roomId: string) {
|
||||
const requesterId = await this.authUserId(authorization);
|
||||
return firstValueFrom(this.core.media.GetChatRoomAvatarAccessUrl({ requesterId, roomId }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,3 +66,20 @@ export class SetRoomNotificationsMutedDto {
|
||||
@IsBoolean()
|
||||
muted!: boolean;
|
||||
}
|
||||
|
||||
export class AddChatRoomMemberDto {
|
||||
@IsString()
|
||||
memberUserId!: string;
|
||||
}
|
||||
|
||||
export class EditChatMessageDto {
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
content!: string;
|
||||
}
|
||||
|
||||
export class MarkRoomReadDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
lastMessageId?: string;
|
||||
}
|
||||
|
||||
168
apps/frontend/components/chat/voice-message-player.tsx
Normal file
168
apps/frontend/components/chat/voice-message-player.tsx
Normal file
@@ -0,0 +1,168 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Loader2, Pause, Play } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
function seedWaveform(seed: string, count = 36) {
|
||||
let hash = 0;
|
||||
for (let index = 0; index < seed.length; index += 1) {
|
||||
hash = (hash * 31 + seed.charCodeAt(index)) | 0;
|
||||
}
|
||||
return Array.from({ length: count }, (_, index) => {
|
||||
const wave = Math.abs(Math.sin((hash + 1) * (index + 1) * 0.17));
|
||||
return 0.25 + wave * 0.75;
|
||||
});
|
||||
}
|
||||
|
||||
function formatDuration(seconds: number) {
|
||||
if (!Number.isFinite(seconds) || seconds <= 0) return '0:00';
|
||||
const whole = Math.floor(seconds);
|
||||
const mins = Math.floor(whole / 60);
|
||||
const secs = whole % 60;
|
||||
return `${mins}:${secs.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export function VoiceMessagePlayer({
|
||||
src,
|
||||
seed,
|
||||
durationMs,
|
||||
variant = 'theirs'
|
||||
}: {
|
||||
src?: string;
|
||||
seed: string;
|
||||
durationMs?: number;
|
||||
variant?: 'mine' | 'theirs';
|
||||
}) {
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [duration, setDuration] = useState(durationMs ? durationMs / 1000 : 0);
|
||||
const bars = useMemo(() => seedWaveform(seed), [seed]);
|
||||
|
||||
useEffect(() => {
|
||||
const audio = new Audio();
|
||||
audio.preload = 'metadata';
|
||||
audioRef.current = audio;
|
||||
|
||||
const onLoaded = () => {
|
||||
if (Number.isFinite(audio.duration) && audio.duration > 0) {
|
||||
setDuration(audio.duration);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
const onTimeUpdate = () => {
|
||||
if (!audio.duration) return;
|
||||
setProgress(audio.currentTime / audio.duration);
|
||||
};
|
||||
const onEnded = () => {
|
||||
setPlaying(false);
|
||||
setProgress(0);
|
||||
audio.currentTime = 0;
|
||||
};
|
||||
const onWaiting = () => setLoading(true);
|
||||
const onCanPlay = () => setLoading(false);
|
||||
const onError = () => {
|
||||
setLoading(false);
|
||||
setPlaying(false);
|
||||
};
|
||||
|
||||
audio.addEventListener('loadedmetadata', onLoaded);
|
||||
audio.addEventListener('timeupdate', onTimeUpdate);
|
||||
audio.addEventListener('ended', onEnded);
|
||||
audio.addEventListener('waiting', onWaiting);
|
||||
audio.addEventListener('canplay', onCanPlay);
|
||||
audio.addEventListener('error', onError);
|
||||
|
||||
return () => {
|
||||
audio.pause();
|
||||
audio.removeEventListener('loadedmetadata', onLoaded);
|
||||
audio.removeEventListener('timeupdate', onTimeUpdate);
|
||||
audio.removeEventListener('ended', onEnded);
|
||||
audio.removeEventListener('waiting', onWaiting);
|
||||
audio.removeEventListener('canplay', onCanPlay);
|
||||
audio.removeEventListener('error', onError);
|
||||
audioRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const audio = audioRef.current;
|
||||
if (!audio || !src) return;
|
||||
setLoading(true);
|
||||
audio.src = src;
|
||||
audio.load();
|
||||
}, [src]);
|
||||
|
||||
async function togglePlayback() {
|
||||
const audio = audioRef.current;
|
||||
if (!audio || !src) return;
|
||||
|
||||
if (playing) {
|
||||
audio.pause();
|
||||
setPlaying(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
await audio.play();
|
||||
setPlaying(true);
|
||||
} catch {
|
||||
setPlaying(false);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function seekTo(ratio: number) {
|
||||
const audio = audioRef.current;
|
||||
if (!audio || !audio.duration) return;
|
||||
const next = Math.min(Math.max(ratio, 0), 1);
|
||||
audio.currentTime = next * audio.duration;
|
||||
setProgress(next);
|
||||
}
|
||||
|
||||
const accent = variant === 'mine' ? 'bg-[#5bb85d]' : 'bg-[#3390ec]';
|
||||
const accentSoft = variant === 'mine' ? 'bg-[#5bb85d]/25' : 'bg-[#3390ec]/25';
|
||||
const remaining = duration * (1 - progress);
|
||||
|
||||
return (
|
||||
<div className="flex min-w-[240px] max-w-[320px] items-center gap-3 py-1">
|
||||
<button
|
||||
type="button"
|
||||
disabled={!src}
|
||||
onClick={() => void togglePlayback()}
|
||||
className={cn(
|
||||
'flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-white transition hover:opacity-90 disabled:opacity-50',
|
||||
accent
|
||||
)}
|
||||
aria-label={playing ? 'Пауза' : 'Воспроизвести'}
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : playing ? <Pause className="h-4 w-4" /> : <Play className="ml-0.5 h-4 w-4" />}
|
||||
</button>
|
||||
|
||||
<button type="button" className="flex h-10 flex-1 items-end gap-[2px]" onClick={(event) => {
|
||||
const rect = event.currentTarget.getBoundingClientRect();
|
||||
seekTo((event.clientX - rect.left) / rect.width);
|
||||
}}>
|
||||
{bars.map((height, index) => {
|
||||
const barProgress = (index + 1) / bars.length;
|
||||
const active = barProgress <= progress;
|
||||
return (
|
||||
<span
|
||||
key={`${seed}-${index}`}
|
||||
className={cn('w-[3px] rounded-full transition-colors', active ? accent : accentSoft)}
|
||||
style={{ height: `${Math.round(height * 28 + 8)}px` }}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</button>
|
||||
|
||||
<span className="w-10 shrink-0 text-right text-[11px] tabular-nums text-[#667085]">
|
||||
{formatDuration(playing || progress > 0 ? remaining : duration)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,36 +6,57 @@ import {
|
||||
ArrowLeft,
|
||||
BarChart3,
|
||||
Camera,
|
||||
Check,
|
||||
CheckCheck,
|
||||
FileText,
|
||||
Loader2,
|
||||
Mic,
|
||||
MoreVertical,
|
||||
Paperclip,
|
||||
Pencil,
|
||||
Plus,
|
||||
Send,
|
||||
Smile,
|
||||
Trash2,
|
||||
UserPlus,
|
||||
Users,
|
||||
Volume2,
|
||||
VolumeX
|
||||
} from 'lucide-react';
|
||||
import { VoiceMessagePlayer } from '@/components/chat/voice-message-player';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
import { useRealtime } from '@/components/notifications/realtime-provider';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { useRequireAuth } from '@/hooks/use-require-auth';
|
||||
import {
|
||||
addChatRoomMember,
|
||||
apiFetch,
|
||||
ChatMessage,
|
||||
ChatRoom,
|
||||
createChatRoom,
|
||||
deleteChatMessage,
|
||||
editChatMessage,
|
||||
FamilyGroup,
|
||||
FamilyInviteCandidate,
|
||||
FamilyPresenceMember,
|
||||
fetchChatMessages,
|
||||
fetchChatRooms,
|
||||
fetchFamilyGroup,
|
||||
fetchFamilyPresence,
|
||||
getApiErrorMessage,
|
||||
markChatRoomRead,
|
||||
removeChatRoomMember,
|
||||
removeFamilyMember,
|
||||
searchFamilyInviteUsers,
|
||||
sendChatMessage,
|
||||
sendFamilyInvite,
|
||||
@@ -74,12 +95,54 @@ interface LoadedChatMedia {
|
||||
blobUrl: string;
|
||||
expiresAt: number;
|
||||
fileName?: string;
|
||||
mimeType?: string;
|
||||
}
|
||||
|
||||
function formatMessageTime(value: string) {
|
||||
return new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' }).format(new Date(value));
|
||||
}
|
||||
|
||||
function formatLastSeen(value?: string) {
|
||||
if (!value) return 'Не в сети';
|
||||
const date = new Date(value);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffMinutes = Math.floor(diffMs / 60_000);
|
||||
if (diffMinutes < 1) return 'был(а) только что';
|
||||
if (diffMinutes < 60) return `был(а) ${diffMinutes} мин. назад`;
|
||||
const diffHours = Math.floor(diffMinutes / 60);
|
||||
if (diffHours < 24) return `был(а) ${diffHours} ч. назад`;
|
||||
return new Intl.DateTimeFormat('ru-RU', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }).format(date);
|
||||
}
|
||||
|
||||
function formatPresenceStatus(member: FamilyPresenceMember) {
|
||||
if (member.online) return 'В сети';
|
||||
return formatLastSeen(member.lastSeenAt);
|
||||
}
|
||||
|
||||
function messagePreview(message?: ChatMessage) {
|
||||
if (!message) return '';
|
||||
if (message.isDeleted) return 'Сообщение удалено';
|
||||
if (message.type === 'POLL') return '📊 Опрос';
|
||||
if (message.type === 'VOICE') return '🎤 Голосовое';
|
||||
if (message.type === 'AUDIO') return '🎵 Аудио';
|
||||
if (message.type === 'IMAGE') return '📷 Фото';
|
||||
if (message.type === 'FILE') return '📄 Файл';
|
||||
return message.content ?? '';
|
||||
}
|
||||
|
||||
function OnlineDot({ online, className }: { online?: boolean; className?: string }) {
|
||||
if (!online) return null;
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
'absolute bottom-0 right-0 h-3 w-3 rounded-full border-2 border-white bg-emerald-500 shadow-sm',
|
||||
className
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FamilyAvatar({ groupId, name, hasAvatar, token }: { groupId: string; name: string; hasAvatar?: boolean; token: string | null }) {
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
@@ -96,12 +159,38 @@ function FamilyAvatar({ groupId, name, hasAvatar, token }: { groupId: string; na
|
||||
);
|
||||
}
|
||||
|
||||
function ChatRoomAvatar({ roomId, name, hasAvatar, token }: { roomId: string; name: string; hasAvatar?: boolean; token: string | null }) {
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!hasAvatar || !token) return;
|
||||
apiFetch<{ accessUrl: string }>(`/media/chat/${roomId}/avatar/url`, {}, token)
|
||||
.then((response) => setUrl(response.accessUrl))
|
||||
.catch(() => setUrl(null));
|
||||
}, [hasAvatar, roomId, token]);
|
||||
return (
|
||||
<Avatar className="h-11 w-11">
|
||||
{url ? <AvatarImage src={url} alt={name} /> : null}
|
||||
<AvatarFallback>{name.slice(0, 2).toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
|
||||
function memberRoleLabel(member: { familyRole?: string; isChatCreator?: boolean }) {
|
||||
if (member.familyRole === 'owner') return 'Создатель семьи';
|
||||
if (member.isChatCreator) return 'Создатель чата';
|
||||
return 'Участник';
|
||||
}
|
||||
|
||||
function familyMemberRoleLabel(role: string) {
|
||||
return role === 'owner' ? 'Создатель семьи' : 'Участник';
|
||||
}
|
||||
|
||||
export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
const router = useRouter();
|
||||
const { user, token } = useAuth();
|
||||
const { isReady, isPinLocked } = useRequireAuth();
|
||||
const { showToast } = useToast();
|
||||
const { subscribe } = useRealtime();
|
||||
const { subscribe, connected } = useRealtime();
|
||||
|
||||
const [group, setGroup] = useState<FamilyGroup | null>(null);
|
||||
const [rooms, setRooms] = useState<ChatRoom[]>([]);
|
||||
@@ -113,6 +202,9 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
const [inviteOpen, setInviteOpen] = useState(false);
|
||||
const [createRoomOpen, setCreateRoomOpen] = useState(false);
|
||||
const [pollOpen, setPollOpen] = useState(false);
|
||||
const [membersOpen, setMembersOpen] = useState(false);
|
||||
const [familyMembersOpen, setFamilyMembersOpen] = useState(false);
|
||||
const [addMembersOpen, setAddMembersOpen] = useState(false);
|
||||
const [inviteQuery, setInviteQuery] = useState('');
|
||||
const [inviteResults, setInviteResults] = useState<FamilyInviteCandidate[]>([]);
|
||||
const [selectedInviteUser, setSelectedInviteUser] = useState<FamilyInviteCandidate | null>(null);
|
||||
@@ -126,12 +218,17 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
const [recording, setRecording] = useState(false);
|
||||
const [mediaUrls, setMediaUrls] = useState<Record<string, LoadedChatMedia>>({});
|
||||
const [downloadingKey, setDownloadingKey] = useState<string | null>(null);
|
||||
const [editingMessageId, setEditingMessageId] = useState<string | null>(null);
|
||||
const [editDraft, setEditDraft] = useState('');
|
||||
const [presenceMembers, setPresenceMembers] = useState<FamilyPresenceMember[]>([]);
|
||||
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const readReceiptTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
|
||||
const recordingStartedAtRef = useRef<number | null>(null);
|
||||
const mediaUrlsRef = useRef<Record<string, LoadedChatMedia>>({});
|
||||
const avatarInputRef = useRef<HTMLInputElement>(null);
|
||||
const roomAvatarInputRef = useRef<HTMLInputElement>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -144,6 +241,20 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
|
||||
const activeRoom = useMemo(() => rooms.find((room) => room.id === activeRoomId) ?? null, [activeRoomId, rooms]);
|
||||
const myMembership = activeRoom?.members.find((member) => member.userId === user?.id);
|
||||
const isFamilyOwner = group?.ownerId === user?.id;
|
||||
const isChatCreator = activeRoom?.createdById === user?.id;
|
||||
const canManageChatMembers = Boolean(isFamilyOwner || isChatCreator);
|
||||
const familyMembersNotInRoom = useMemo(() => {
|
||||
if (!group?.members || !activeRoom) return [];
|
||||
const inRoom = new Set(activeRoom.members.map((member) => member.userId));
|
||||
return group.members.filter((member) => !inRoom.has(member.userId));
|
||||
}, [activeRoom, group?.members]);
|
||||
|
||||
const presenceByUserId = useMemo(
|
||||
() => new Map(presenceMembers.map((member) => [member.userId, member])),
|
||||
[presenceMembers]
|
||||
);
|
||||
const onlineCount = useMemo(() => presenceMembers.filter((member) => member.online).length, [presenceMembers]);
|
||||
|
||||
const loadGroup = useCallback(async () => {
|
||||
if (!token || isPinLocked) return;
|
||||
@@ -161,34 +272,85 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
setMessages(response.messages ?? []);
|
||||
}, [isPinLocked, token]);
|
||||
|
||||
const loadPresence = useCallback(async () => {
|
||||
if (!token || isPinLocked) return;
|
||||
try {
|
||||
const response = await fetchFamilyPresence(groupId, token);
|
||||
setPresenceMembers(response.members ?? []);
|
||||
} catch {
|
||||
// ignore background presence errors
|
||||
}
|
||||
}, [groupId, isPinLocked, token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isReady || !token || isPinLocked) return;
|
||||
setLoading(true);
|
||||
loadGroup()
|
||||
.catch((error) => showToast(getApiErrorMessage(error, 'Не удалось загрузить семью') ?? 'Ошибка'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [isPinLocked, isReady, loadGroup, showToast, token]);
|
||||
void loadPresence();
|
||||
}, [isPinLocked, isReady, loadGroup, loadPresence, showToast, token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || isPinLocked) return;
|
||||
void loadPresence();
|
||||
const timer = window.setInterval(() => void loadPresence(), 25_000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [connected, isPinLocked, loadPresence, token]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeRoomId) return;
|
||||
void loadMessages(activeRoomId);
|
||||
setEditingMessageId(null);
|
||||
setEditDraft('');
|
||||
}, [activeRoomId, loadMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeRoomId || !token || !messages.length) return;
|
||||
const timer = window.setTimeout(() => {
|
||||
const last = messages[messages.length - 1];
|
||||
void markChatRoomRead(activeRoomId, last.id, token).catch(() => {});
|
||||
}, 500);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [activeRoomId, messages, token]);
|
||||
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||
}, [messages]);
|
||||
|
||||
useEffect(() => {
|
||||
return subscribe((event) => {
|
||||
if (event.type !== 'chat_message') return;
|
||||
const payload = event.payload;
|
||||
if (!payload?.roomId || payload.roomId !== activeRoomId) return;
|
||||
if (payload.message) {
|
||||
appendMessage(payload.message);
|
||||
} else {
|
||||
void loadMessages(activeRoomId!);
|
||||
if (payload?.roomId && payload.roomId !== activeRoomId) {
|
||||
if (event.type === 'chat_message') void loadGroup();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'chat_message') {
|
||||
if (payload?.message) {
|
||||
appendMessage(payload.message);
|
||||
} else if (activeRoomId) {
|
||||
void loadMessages(activeRoomId);
|
||||
}
|
||||
void loadGroup();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'chat_message_updated' || event.type === 'chat_message_deleted') {
|
||||
const updated = payload?.message;
|
||||
if (updated) {
|
||||
setMessages((current) => current.map((item) => (item.id === updated.id ? updated : item)));
|
||||
} else if (activeRoomId) {
|
||||
void loadMessages(activeRoomId);
|
||||
}
|
||||
void loadGroup();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'chat_read_receipt' && activeRoomId) {
|
||||
if (readReceiptTimerRef.current) clearTimeout(readReceiptTimerRef.current);
|
||||
readReceiptTimerRef.current = setTimeout(() => void loadMessages(activeRoomId), 400);
|
||||
}
|
||||
void loadGroup();
|
||||
});
|
||||
}, [activeRoomId, appendMessage, loadGroup, loadMessages, subscribe]);
|
||||
|
||||
@@ -201,6 +363,7 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
|
||||
const meta = parseMessageMetadata(message.metadataJson);
|
||||
const fileName = meta.fileName || message.content || undefined;
|
||||
const mimeType = message.mimeType || (message.type === 'VOICE' ? 'audio/webm' : message.type === 'AUDIO' ? 'audio/mpeg' : undefined);
|
||||
const query = new URLSearchParams({ storageKey });
|
||||
if (fileName) query.set('fileName', fileName);
|
||||
|
||||
@@ -210,7 +373,7 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
{},
|
||||
token
|
||||
);
|
||||
const blob = await fetchAuthenticatedMediaBlob(access.accessUrl, token);
|
||||
const blob = await fetchAuthenticatedMediaBlob(access.accessUrl, token, mimeType);
|
||||
const blobUrl = createBlobObjectUrl(blob);
|
||||
setMediaUrls((current) => {
|
||||
revokeBlobObjectUrl(current[storageKey]?.blobUrl);
|
||||
@@ -219,7 +382,8 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
[storageKey]: {
|
||||
blobUrl,
|
||||
expiresAt: mediaExpiresAtMs(access.expiresAt),
|
||||
fileName
|
||||
fileName,
|
||||
mimeType
|
||||
}
|
||||
};
|
||||
});
|
||||
@@ -289,6 +453,70 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadRoomAvatar(file: File) {
|
||||
if (!token || !activeRoomId) return;
|
||||
try {
|
||||
const presigned = await apiFetch<PresignedUploadResponse>(
|
||||
`/media/chat/${activeRoomId}/avatar/upload-url`,
|
||||
{ method: 'POST', body: JSON.stringify({ contentType: file.type }) },
|
||||
token
|
||||
);
|
||||
await uploadMediaObject(presigned, file, file.type);
|
||||
await apiFetch(`/media/chat/${activeRoomId}/avatar/confirm`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ storageKey: presigned.storageKey })
|
||||
}, token);
|
||||
await loadGroup();
|
||||
showToast('Фото чата обновлено');
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось загрузить фото чата') ?? 'Ошибка');
|
||||
}
|
||||
}
|
||||
|
||||
function applyRoomUpdate(room: ChatRoom) {
|
||||
setRooms((current) => current.map((item) => (item.id === room.id ? room : item)));
|
||||
}
|
||||
|
||||
async function handleAddRoomMember(memberUserId: string) {
|
||||
if (!token || !activeRoomId) return;
|
||||
try {
|
||||
const room = await addChatRoomMember(activeRoomId, memberUserId, token);
|
||||
applyRoomUpdate(room);
|
||||
setAddMembersOpen(false);
|
||||
showToast('Участник добавлен в чат');
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось добавить участника') ?? 'Ошибка');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemoveFromChat(memberUserId: string) {
|
||||
if (!token || !activeRoomId) return;
|
||||
try {
|
||||
const room = await removeChatRoomMember(activeRoomId, memberUserId, token);
|
||||
applyRoomUpdate(room);
|
||||
if (memberUserId === user?.id) {
|
||||
setActiveRoomId(null);
|
||||
setMembersOpen(false);
|
||||
}
|
||||
showToast('Участник удалён из чата');
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось удалить участника из чата') ?? 'Ошибка');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemoveFromFamily(memberId: string) {
|
||||
if (!token) return;
|
||||
try {
|
||||
await removeFamilyMember(memberId, token);
|
||||
await loadGroup();
|
||||
setMembersOpen(false);
|
||||
setFamilyMembersOpen(false);
|
||||
showToast('Участник удалён из семьи');
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось удалить участника из семьи') ?? 'Ошибка');
|
||||
}
|
||||
}
|
||||
|
||||
async function saveRename() {
|
||||
if (!token || !renameValue.trim()) return;
|
||||
try {
|
||||
@@ -368,6 +596,51 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
}
|
||||
}
|
||||
|
||||
async function startEditMessage(message: ChatMessage) {
|
||||
if (message.isDeleted) return;
|
||||
setEditingMessageId(message.id);
|
||||
setEditDraft(message.content ?? '');
|
||||
}
|
||||
|
||||
async function submitEditMessage() {
|
||||
if (!token || !editingMessageId) return;
|
||||
const content = editDraft.trim();
|
||||
if (!content) {
|
||||
showToast('Сообщение не может быть пустым');
|
||||
return;
|
||||
}
|
||||
setSending(true);
|
||||
try {
|
||||
const updated = await editChatMessage(editingMessageId, content, token);
|
||||
setMessages((current) => current.map((item) => (item.id === updated.id ? updated : item)));
|
||||
setEditingMessageId(null);
|
||||
setEditDraft('');
|
||||
void loadGroup();
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось изменить сообщение') ?? 'Ошибка');
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteMessage(messageId: string) {
|
||||
if (!token) return;
|
||||
setSending(true);
|
||||
try {
|
||||
const updated = await deleteChatMessage(messageId, token);
|
||||
setMessages((current) => current.map((item) => (item.id === updated.id ? updated : item)));
|
||||
if (editingMessageId === messageId) {
|
||||
setEditingMessageId(null);
|
||||
setEditDraft('');
|
||||
}
|
||||
void loadGroup();
|
||||
} catch (error) {
|
||||
showToast(getApiErrorMessage(error, 'Не удалось удалить сообщение') ?? 'Ошибка');
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendText(type: string = 'TEXT') {
|
||||
if (!token || !activeRoomId || sending) return;
|
||||
const content = draft.trim();
|
||||
@@ -544,6 +817,22 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
<Camera className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setFamilyMembersOpen(true)}
|
||||
className="mt-3 flex w-full items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3 text-left transition hover:bg-[#eceef4]"
|
||||
>
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-[#3390ec]/10 text-[#3390ec]">
|
||||
<Users className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium">Участники семьи</p>
|
||||
<p className="text-xs text-[#667085]">
|
||||
{onlineCount > 0 ? `${onlineCount} в сети · ` : ''}
|
||||
{group?.members?.length ?? 0} человек
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-4 py-3">
|
||||
<p className="text-sm font-semibold text-[#667085]">Чаты</p>
|
||||
@@ -562,9 +851,7 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
activeRoomId === room.id && 'bg-[#3390ec]/10'
|
||||
)}
|
||||
>
|
||||
<div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-[#3390ec] text-sm font-semibold text-white">
|
||||
{room.name.slice(0, 2).toUpperCase()}
|
||||
</div>
|
||||
<ChatRoomAvatar roomId={room.id} name={room.name} hasAvatar={room.hasAvatar} token={token} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="truncate font-medium">{room.name}</p>
|
||||
@@ -573,7 +860,7 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
) : null}
|
||||
</div>
|
||||
<p className="truncate text-sm text-[#667085]">
|
||||
{room.lastMessage?.content ?? (room.type === 'GENERAL' ? 'Общий чат семьи' : 'Нет сообщений')}
|
||||
{messagePreview(room.lastMessage) || (room.type === 'GENERAL' ? 'Общий чат семьи' : 'Нет сообщений')}
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
@@ -585,28 +872,105 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
{activeRoom ? (
|
||||
<>
|
||||
<div className="flex items-center justify-between border-b border-[#dce3ec] bg-white px-4 py-3">
|
||||
<div>
|
||||
<h2 className="font-semibold">{activeRoom.name}</h2>
|
||||
<p className="text-xs text-[#667085]">{activeRoom.members.length} участников</p>
|
||||
<button type="button" className="flex min-w-0 items-center gap-3 text-left" onClick={() => setMembersOpen(true)}>
|
||||
<div className="shrink-0 overflow-hidden rounded-full">
|
||||
<ChatRoomAvatar roomId={activeRoom.id} name={activeRoom.name} hasAvatar={activeRoom.hasAvatar} token={token} />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<h2 className="font-semibold">{activeRoom.name}</h2>
|
||||
<p className="text-xs text-[#667085]">
|
||||
{onlineCount > 0 ? (
|
||||
<span className="text-emerald-600">{onlineCount} в сети</span>
|
||||
) : (
|
||||
'Никого нет в сети'
|
||||
)}
|
||||
{' · '}
|
||||
{activeRoom.members.length} участников
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
{activeRoom.type === 'GROUP' ? (
|
||||
<Button size="sm" variant="secondary" className="rounded-xl" onClick={() => roomAvatarInputRef.current?.click()}>
|
||||
<Camera className="h-4 w-4" />
|
||||
</Button>
|
||||
) : null}
|
||||
<Button size="sm" variant="secondary" className="rounded-xl" onClick={() => setMembersOpen(true)}>
|
||||
<Users className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button size="sm" variant="secondary" className="rounded-xl" onClick={() => void toggleMute()}>
|
||||
{myMembership?.notificationsMuted ? <VolumeX className="h-4 w-4" /> : <Volume2 className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
<Button size="sm" variant="secondary" className="rounded-xl" onClick={() => void toggleMute()}>
|
||||
{myMembership?.notificationsMuted ? <VolumeX className="h-4 w-4" /> : <Volume2 className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 space-y-2 overflow-y-auto px-4 py-4">
|
||||
{messages.map((message) => {
|
||||
const mine = message.senderId === user?.id;
|
||||
const isEditing = editingMessageId === message.id;
|
||||
const canEdit = mine && !message.isDeleted && (message.type === 'TEXT' || message.type === 'EMOJI');
|
||||
return (
|
||||
<div key={message.id} className={cn('flex', mine ? 'justify-end' : 'justify-start')}>
|
||||
<div key={message.id} className={cn('group flex', mine ? 'justify-end' : 'justify-start')}>
|
||||
<div
|
||||
className={cn(
|
||||
'max-w-[78%] rounded-[18px] px-3 py-2 shadow-sm',
|
||||
mine ? 'rounded-br-md bg-[#effdde] text-[#1f2430]' : 'rounded-bl-md bg-white text-[#1f2430]'
|
||||
'relative max-w-[78%] rounded-[18px] px-3 py-2 shadow-sm',
|
||||
mine ? 'rounded-br-md bg-[#effdde] text-[#1f2430]' : 'rounded-bl-md bg-white text-[#1f2430]',
|
||||
message.isDeleted && 'bg-[#eef1f6]/90 text-[#667085] italic'
|
||||
)}
|
||||
>
|
||||
{canEdit ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'absolute -right-2 -top-2 flex h-7 w-7 items-center justify-center rounded-full bg-white text-[#667085] opacity-0 shadow-sm transition group-hover:opacity-100',
|
||||
mine ? '-left-2 right-auto' : ''
|
||||
)}
|
||||
aria-label="Действия с сообщением"
|
||||
>
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align={mine ? 'end' : 'start'} className="rounded-xl">
|
||||
<DropdownMenuItem onClick={() => void startEditMessage(message)}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Изменить
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-red-600 focus:text-red-600"
|
||||
onClick={() => void handleDeleteMessage(message.id)}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Удалить
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : null}
|
||||
{!mine ? <p className="mb-1 text-xs font-semibold text-[#3390ec]">{message.senderName}</p> : null}
|
||||
{message.type === 'POLL' && message.poll ? (
|
||||
{message.isDeleted ? (
|
||||
<p className="text-[15px] italic text-[#8b93a7]">Сообщение удалено</p>
|
||||
) : isEditing ? (
|
||||
<div className="space-y-2">
|
||||
<textarea
|
||||
value={editDraft}
|
||||
onChange={(event) => setEditDraft(event.target.value)}
|
||||
rows={2}
|
||||
className="w-full resize-none rounded-xl border border-[#dce3ec] bg-white px-3 py-2 text-[15px] outline-none focus:border-[#3390ec]"
|
||||
/>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button size="sm" variant="secondary" className="h-8 rounded-xl" onClick={() => {
|
||||
setEditingMessageId(null);
|
||||
setEditDraft('');
|
||||
}}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button size="sm" className="h-8 rounded-xl" disabled={sending} onClick={() => void submitEditMessage()}>
|
||||
Сохранить
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : message.type === 'POLL' && message.poll ? (
|
||||
<div className="space-y-2">
|
||||
<p className="font-medium">{message.poll.question}</p>
|
||||
{message.poll.options.map((option) => {
|
||||
@@ -650,18 +1014,14 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
);
|
||||
}
|
||||
if (message.type === 'VOICE' || message.type === 'AUDIO') {
|
||||
const metaDuration = parseMessageMetadata(message.metadataJson).durationMs;
|
||||
return (
|
||||
<div className="flex min-w-[220px] items-center gap-3 rounded-xl bg-black/5 px-3 py-2">
|
||||
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-[#3390ec] text-white">
|
||||
{message.type === 'VOICE' ? <Mic className="h-4 w-4" /> : <Volume2 className="h-4 w-4" />}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-xs font-medium text-[#667085]">
|
||||
{message.type === 'VOICE' ? 'Голосовое сообщение' : 'Аудиофайл'}
|
||||
</p>
|
||||
<audio controls preload="metadata" src={media.blobUrl} className="mt-1 h-8 w-full max-w-[240px]" />
|
||||
</div>
|
||||
</div>
|
||||
<VoiceMessagePlayer
|
||||
src={media.blobUrl}
|
||||
seed={message.storageKey ?? message.id}
|
||||
durationMs={typeof metaDuration === 'number' ? metaDuration : undefined}
|
||||
variant={mine ? 'mine' : 'theirs'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
@@ -689,9 +1049,17 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
) : (
|
||||
<p className="whitespace-pre-wrap break-words text-[15px] leading-relaxed">{message.content}</p>
|
||||
)}
|
||||
<p className={cn('mt-1 text-[11px]', mine ? 'text-[#7ea06a]' : 'text-[#a8adbc]')}>
|
||||
{formatMessageTime(message.createdAt)}
|
||||
</p>
|
||||
<div className={cn('mt-1 flex items-center justify-end gap-1 text-[11px]', mine ? 'text-[#7ea06a]' : 'text-[#a8adbc]')}>
|
||||
{message.editedAt ? <span className="mr-1">изменено</span> : null}
|
||||
<span>{formatMessageTime(message.createdAt)}</span>
|
||||
{mine && !message.isDeleted ? (
|
||||
message.readByAll ? (
|
||||
<CheckCheck className="h-3.5 w-3.5 text-[#3390ec]" aria-label="Прочитано" />
|
||||
) : (
|
||||
<Check className="h-3.5 w-3.5" aria-label="Отправлено" />
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -766,6 +1134,11 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
if (file) void uploadFamilyAvatar(file);
|
||||
event.target.value = '';
|
||||
}} />
|
||||
<input ref={roomAvatarInputRef} type="file" accept="image/*" className="hidden" onChange={(event) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (file) void uploadRoomAvatar(file);
|
||||
event.target.value = '';
|
||||
}} />
|
||||
<input ref={fileInputRef} type="file" className="hidden" onChange={(event) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (file) void uploadChatFile(file);
|
||||
@@ -841,6 +1214,149 @@ export function FamilyGroupView({ groupId }: { groupId: string }) {
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={familyMembersOpen} onOpenChange={setFamilyMembersOpen}>
|
||||
<DialogContent className="rounded-[28px] sm:max-w-[480px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Участники семьи</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-[#667085]">
|
||||
{group?.name} · {group?.members?.length ?? 0} {group?.members?.length === 1 ? 'участник' : 'участников'}
|
||||
</p>
|
||||
<div className="mt-3 max-h-[420px] space-y-2 overflow-y-auto">
|
||||
{(group?.members ?? []).map((member) => {
|
||||
const isSelf = member.userId === user?.id;
|
||||
const canRemove =
|
||||
member.role !== 'owner' && (isFamilyOwner || isSelf);
|
||||
const presence = presenceByUserId.get(member.userId);
|
||||
|
||||
return (
|
||||
<div key={member.id} className="flex items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3">
|
||||
<div className="relative shrink-0">
|
||||
<Avatar className="h-10 w-10">
|
||||
<AvatarFallback>{member.displayName.slice(0, 1)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<OnlineDot online={presence?.online} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate font-medium">
|
||||
{member.displayName}
|
||||
{isSelf ? <span className="ml-1 text-xs font-normal text-[#667085]">(Вы)</span> : null}
|
||||
</p>
|
||||
<p className="text-xs text-[#667085]">{familyMemberRoleLabel(member.role)}</p>
|
||||
<p className={cn('text-xs', presence?.online ? 'font-medium text-emerald-600' : 'text-[#a8adbc]')}>
|
||||
{presence ? formatPresenceStatus(presence) : 'Статус неизвестен'}
|
||||
</p>
|
||||
</div>
|
||||
{canRemove ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 shrink-0 rounded-xl text-xs text-red-600 hover:text-red-700"
|
||||
onClick={() => void handleRemoveFromFamily(member.id)}
|
||||
>
|
||||
{isSelf ? 'Выйти' : 'Удалить'}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<Button className="mt-4 w-full rounded-xl" variant="secondary" onClick={() => {
|
||||
setFamilyMembersOpen(false);
|
||||
setInviteOpen(true);
|
||||
}}>
|
||||
<UserPlus className="mr-2 h-4 w-4" />
|
||||
Пригласить в семью
|
||||
</Button>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={membersOpen} onOpenChange={setMembersOpen}>
|
||||
<DialogContent className="rounded-[28px] sm:max-w-[480px]">
|
||||
<DialogHeader><DialogTitle>Участники чата</DialogTitle></DialogHeader>
|
||||
<div className="max-h-[420px] space-y-2 overflow-y-auto">
|
||||
{activeRoom?.members.map((member) => {
|
||||
const familyMember = group?.members?.find((item) => item.userId === member.userId);
|
||||
const presence = presenceByUserId.get(member.userId);
|
||||
const canRemoveFromChat =
|
||||
canManageChatMembers &&
|
||||
activeRoom.type === 'GROUP' &&
|
||||
member.userId !== user?.id &&
|
||||
!(member.isChatCreator && !isFamilyOwner);
|
||||
const canRemoveFromFamily = isFamilyOwner && member.familyRole !== 'owner' && familyMember;
|
||||
|
||||
return (
|
||||
<div key={member.id} className="flex items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3">
|
||||
<div className="relative shrink-0">
|
||||
<Avatar className="h-10 w-10">
|
||||
<AvatarFallback>{member.displayName.slice(0, 1)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<OnlineDot online={presence?.online} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate font-medium">{member.displayName}</p>
|
||||
<p className="text-xs text-[#667085]">{memberRoleLabel(member)}</p>
|
||||
<p className={cn('text-xs', presence?.online ? 'font-medium text-emerald-600' : 'text-[#a8adbc]')}>
|
||||
{presence ? formatPresenceStatus(presence) : 'Статус неизвестен'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-col gap-1">
|
||||
{canRemoveFromChat ? (
|
||||
<Button size="sm" variant="secondary" className="h-8 rounded-xl text-xs" onClick={() => void handleRemoveFromChat(member.userId)}>
|
||||
<Trash2 className="mr-1 h-3.5 w-3.5" />
|
||||
Из чата
|
||||
</Button>
|
||||
) : null}
|
||||
{canRemoveFromFamily ? (
|
||||
<Button size="sm" variant="ghost" className="h-8 rounded-xl text-xs text-red-600 hover:text-red-700" onClick={() => void handleRemoveFromFamily(familyMember!.id)}>
|
||||
Из семьи
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{activeRoom?.type === 'GROUP' && familyMembersNotInRoom.length > 0 ? (
|
||||
<Button className="mt-4 w-full rounded-xl" onClick={() => {
|
||||
setMembersOpen(false);
|
||||
setAddMembersOpen(true);
|
||||
}}>
|
||||
<UserPlus className="mr-2 h-4 w-4" />
|
||||
Добавить участника
|
||||
</Button>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={addMembersOpen} onOpenChange={setAddMembersOpen}>
|
||||
<DialogContent className="rounded-[28px] sm:max-w-[420px]">
|
||||
<DialogHeader><DialogTitle>Добавить в чат</DialogTitle></DialogHeader>
|
||||
<div className="space-y-2">
|
||||
{familyMembersNotInRoom.length ? (
|
||||
familyMembersNotInRoom.map((member) => (
|
||||
<button
|
||||
key={member.id}
|
||||
type="button"
|
||||
className="flex w-full items-center gap-3 rounded-2xl bg-[#f4f5f8] px-3 py-3 text-left transition hover:bg-[#eceef4]"
|
||||
onClick={() => void handleAddRoomMember(member.userId)}
|
||||
>
|
||||
<Avatar className="h-9 w-9">
|
||||
<AvatarFallback>{member.displayName.slice(0, 1)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<p className="font-medium">{member.displayName}</p>
|
||||
<p className="text-xs text-[#667085]">{member.role === 'owner' ? 'Создатель семьи' : 'Участник семьи'}</p>
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<p className="py-6 text-center text-sm text-[#667085]">Все участники семьи уже в этом чате</p>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={createRoomOpen} onOpenChange={setCreateRoomOpen}>
|
||||
<DialogContent className="rounded-[28px] sm:max-w-[480px]">
|
||||
<DialogHeader><DialogTitle>Новый групповой чат</DialogTitle></DialogHeader>
|
||||
|
||||
@@ -667,6 +667,9 @@ export interface ChatMessage {
|
||||
mimeType?: string;
|
||||
metadataJson?: string;
|
||||
createdAt: string;
|
||||
editedAt?: string;
|
||||
isDeleted?: boolean;
|
||||
readByAll?: boolean;
|
||||
poll?: {
|
||||
id: string;
|
||||
question: string;
|
||||
@@ -676,14 +679,37 @@ export interface ChatMessage {
|
||||
};
|
||||
}
|
||||
|
||||
export interface FamilyPresenceMember {
|
||||
userId: string;
|
||||
displayName: string;
|
||||
online: boolean;
|
||||
lastSeenAt?: string;
|
||||
}
|
||||
|
||||
export interface FamilyPresence {
|
||||
members: FamilyPresenceMember[];
|
||||
onlineCount: number;
|
||||
}
|
||||
|
||||
export interface ChatRoomMember {
|
||||
id: string;
|
||||
userId: string;
|
||||
displayName: string;
|
||||
hasAvatar: boolean;
|
||||
notificationsMuted: boolean;
|
||||
familyRole?: string;
|
||||
isChatCreator?: boolean;
|
||||
}
|
||||
|
||||
export interface ChatRoom {
|
||||
id: string;
|
||||
groupId: string;
|
||||
type: string;
|
||||
name: string;
|
||||
hasAvatar: boolean;
|
||||
createdById?: string;
|
||||
updatedAt: string;
|
||||
members: Array<{ id: string; userId: string; displayName: string; hasAvatar: boolean; notificationsMuted: boolean }>;
|
||||
members: ChatRoomMember[];
|
||||
lastMessage?: ChatMessage;
|
||||
}
|
||||
|
||||
@@ -738,6 +764,21 @@ export async function createChatRoom(groupId: string, name: string, memberUserId
|
||||
}, token);
|
||||
}
|
||||
|
||||
export async function addChatRoomMember(roomId: string, memberUserId: string, token?: string | null) {
|
||||
return apiFetch<ChatRoom>(`/chat/rooms/${roomId}/members`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ memberUserId })
|
||||
}, token);
|
||||
}
|
||||
|
||||
export async function removeChatRoomMember(roomId: string, memberUserId: string, token?: string | null) {
|
||||
return apiFetch<ChatRoom>(`/chat/rooms/${roomId}/members/${memberUserId}`, { method: 'DELETE' }, token);
|
||||
}
|
||||
|
||||
export async function removeFamilyMember(memberId: string, token?: string | null) {
|
||||
return apiFetch<{ count: number }>(`/family/members/${memberId}`, { method: 'DELETE' }, token);
|
||||
}
|
||||
|
||||
export async function fetchChatMessages(roomId: string, token?: string | null, beforeMessageId?: string) {
|
||||
const query = beforeMessageId ? `?beforeMessageId=${beforeMessageId}` : '';
|
||||
return apiFetch<{ messages?: ChatMessage[] }>(`/chat/rooms/${roomId}/messages${query}`, {}, token);
|
||||
@@ -767,5 +808,24 @@ export async function setChatRoomMuted(roomId: string, muted: boolean, token?: s
|
||||
return apiFetch(`/chat/rooms/${roomId}/mute`, { method: 'POST', body: JSON.stringify({ muted }) }, token);
|
||||
}
|
||||
|
||||
export async function editChatMessage(messageId: string, content: string, token?: string | null) {
|
||||
return apiFetch<ChatMessage>(`/chat/messages/${messageId}`, { method: 'PATCH', body: JSON.stringify({ content }) }, token);
|
||||
}
|
||||
|
||||
export async function deleteChatMessage(messageId: string, token?: string | null) {
|
||||
return apiFetch<ChatMessage>(`/chat/messages/${messageId}`, { method: 'DELETE' }, token);
|
||||
}
|
||||
|
||||
export async function markChatRoomRead(roomId: string, lastMessageId: string | undefined, token?: string | null) {
|
||||
return apiFetch<{ count: number }>(`/chat/rooms/${roomId}/read`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ lastMessageId })
|
||||
}, token);
|
||||
}
|
||||
|
||||
export async function fetchFamilyPresence(groupId: string, token?: string | null) {
|
||||
return apiFetch<FamilyPresence>(`/family/groups/${groupId}/presence`, {}, token);
|
||||
}
|
||||
|
||||
/** @deprecated Используйте getWsUrl() — URL может переключаться на same-origin /idp-api/ws в браузере */
|
||||
export const WS_URL = configuredWsUrl;
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
export async function fetchAuthenticatedMediaBlob(accessUrl: string, token: string) {
|
||||
export async function fetchAuthenticatedMediaBlob(accessUrl: string, token: string, mimeType?: string) {
|
||||
const response = await fetch(accessUrl, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Не удалось загрузить файл');
|
||||
}
|
||||
return response.blob();
|
||||
const raw = await response.blob();
|
||||
if (mimeType && (!raw.type || raw.type === 'application/octet-stream')) {
|
||||
return new Blob([await raw.arrayBuffer()], { type: mimeType });
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
export function createBlobObjectUrl(blob: Blob) {
|
||||
|
||||
@@ -59,6 +59,7 @@ func (h *Hub) Remove(ctx context.Context, userID string, conn *websocket.Conn) {
|
||||
delete(h.connections, userID)
|
||||
_ = h.redis.SRem(ctx, "ws:online_users", userID).Err()
|
||||
_ = h.redis.Del(ctx, "ws:user:"+userID).Err()
|
||||
_ = h.redis.Set(ctx, "ws:last_seen:"+userID, time.Now().UTC().Format(time.RFC3339), 0).Err()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -384,8 +384,10 @@ model ChatRoomMember {
|
||||
id String @id @default(uuid())
|
||||
roomId String
|
||||
userId String
|
||||
notificationsMuted Boolean @default(false)
|
||||
joinedAt DateTime @default(now())
|
||||
notificationsMuted Boolean @default(false)
|
||||
lastReadAt DateTime?
|
||||
lastReadMessageId String?
|
||||
joinedAt DateTime @default(now())
|
||||
room ChatRoom @relation(fields: [roomId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@ -404,6 +406,7 @@ model ChatMessage {
|
||||
mimeType String?
|
||||
createdAt DateTime @default(now())
|
||||
editedAt DateTime?
|
||||
deletedAt DateTime?
|
||||
room ChatRoom @relation(fields: [roomId], references: [id], onDelete: Cascade)
|
||||
sender User @relation(fields: [senderId], references: [id], onDelete: Cascade)
|
||||
poll ChatPoll?
|
||||
|
||||
@@ -26,6 +26,7 @@ import { FamilyService } from './domain/family.service';
|
||||
import { MediaService } from './domain/media.service';
|
||||
import { NotificationsService } from './domain/notifications.service';
|
||||
import { ChatService } from './domain/chat.service';
|
||||
import { PresenceService } from './domain/presence.service';
|
||||
import { NotificationPublisherService } from './infra/notification-publisher.service';
|
||||
import { MinioService } from './infra/minio.service';
|
||||
import { LdapClientService } from './infra/ldap-client.service';
|
||||
@@ -63,6 +64,7 @@ import { TotpService } from './domain/totp.service';
|
||||
MediaService,
|
||||
NotificationsService,
|
||||
ChatService,
|
||||
PresenceService,
|
||||
NotificationPublisherService,
|
||||
MinioService,
|
||||
LdapClientService,
|
||||
|
||||
@@ -20,6 +20,7 @@ import { FamilyService } from './family.service';
|
||||
import { MediaService } from './media.service';
|
||||
import { NotificationsService } from './notifications.service';
|
||||
import { ChatService } from './chat.service';
|
||||
import { PresenceService } from './presence.service';
|
||||
import { TotpService } from './totp.service';
|
||||
import { MessagingService } from '../infra/messaging.service';
|
||||
|
||||
@@ -44,6 +45,7 @@ export class AuthGrpcController {
|
||||
private readonly media: MediaService,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly chat: ChatService,
|
||||
private readonly presence: PresenceService,
|
||||
private readonly messaging: MessagingService,
|
||||
private readonly totp: TotpService
|
||||
) {}
|
||||
@@ -624,6 +626,21 @@ export class AuthGrpcController {
|
||||
return this.media.getChatMediaAccessUrl(command.requesterId, command.roomId, command.storageKey, command.fileName);
|
||||
}
|
||||
|
||||
@GrpcMethod('MediaService', 'CreateChatRoomAvatarUploadUrl')
|
||||
createChatRoomAvatarUploadUrl(command: { requesterId: string; roomId: string; contentType: string }) {
|
||||
return this.media.createChatRoomAvatarUploadUrl(command.requesterId, command.roomId, command.contentType);
|
||||
}
|
||||
|
||||
@GrpcMethod('MediaService', 'ConfirmChatRoomAvatar')
|
||||
confirmChatRoomAvatar(command: { requesterId: string; roomId: string; storageKey: string }) {
|
||||
return this.media.confirmChatRoomAvatar(command.requesterId, command.roomId, command.storageKey);
|
||||
}
|
||||
|
||||
@GrpcMethod('MediaService', 'GetChatRoomAvatarAccessUrl')
|
||||
getChatRoomAvatarAccessUrl(command: { requesterId: string; roomId: string }) {
|
||||
return this.media.getChatRoomAvatarAccessUrl(command.requesterId, command.roomId);
|
||||
}
|
||||
|
||||
@GrpcMethod('OAuthCoreService', 'Authorize')
|
||||
authorize(command: { userId: string; clientId: string; redirectUri: string; scope: string; state?: string }) {
|
||||
return this.oauthCore.authorize(command);
|
||||
@@ -738,6 +755,11 @@ export class AuthGrpcController {
|
||||
return this.family.listInvites(command.userId, command.groupId);
|
||||
}
|
||||
|
||||
@GrpcMethod('FamilyService', 'GetFamilyPresence')
|
||||
getFamilyPresence(command: { requesterId: string; groupId: string }) {
|
||||
return this.presence.getFamilyPresence(command.requesterId, command.groupId);
|
||||
}
|
||||
|
||||
@GrpcMethod('NotificationsService', 'ListNotifications')
|
||||
listNotifications(command: { userId: string; limit?: number; unreadOnly?: boolean }) {
|
||||
return this.notifications.list(command.userId, command.limit, command.unreadOnly);
|
||||
@@ -783,6 +805,16 @@ export class AuthGrpcController {
|
||||
return this.chat.updateRoomSettings(command.userId, command.roomId, command.name, command.notificationsMuted);
|
||||
}
|
||||
|
||||
@GrpcMethod('ChatService', 'AddRoomMember')
|
||||
addChatRoomMember(command: { userId: string; roomId: string; memberUserId: string }) {
|
||||
return this.chat.addRoomMember(command.userId, command.roomId, command.memberUserId);
|
||||
}
|
||||
|
||||
@GrpcMethod('ChatService', 'RemoveRoomMember')
|
||||
removeChatRoomMember(command: { userId: string; roomId: string; memberUserId: string }) {
|
||||
return this.chat.removeRoomMember(command.userId, command.roomId, command.memberUserId);
|
||||
}
|
||||
|
||||
@GrpcMethod('ChatService', 'ListMessages')
|
||||
listChatMessages(command: { userId: string; roomId: string; beforeMessageId?: string; limit?: number }) {
|
||||
return this.chat.listMessages(command.userId, command.roomId, command.beforeMessageId, command.limit);
|
||||
@@ -823,6 +855,21 @@ export class AuthGrpcController {
|
||||
return this.chat.setRoomNotificationsMuted(command.userId, command.roomId, command.muted);
|
||||
}
|
||||
|
||||
@GrpcMethod('ChatService', 'EditMessage')
|
||||
editChatMessage(command: { userId: string; messageId: string; content: string }) {
|
||||
return this.chat.editMessage(command.userId, command.messageId, command.content);
|
||||
}
|
||||
|
||||
@GrpcMethod('ChatService', 'DeleteMessage')
|
||||
deleteChatMessage(command: { userId: string; messageId: string }) {
|
||||
return this.chat.deleteMessage(command.userId, command.messageId);
|
||||
}
|
||||
|
||||
@GrpcMethod('ChatService', 'MarkRoomRead')
|
||||
markChatRoomRead(command: { userId: string; roomId: string; lastMessageId?: string }) {
|
||||
return this.chat.markRoomRead(command.userId, command.roomId, command.lastMessageId);
|
||||
}
|
||||
|
||||
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 }) {
|
||||
return {
|
||||
id: session.id,
|
||||
|
||||
@@ -10,6 +10,11 @@ interface PollPayload {
|
||||
isAnonymous?: boolean;
|
||||
}
|
||||
|
||||
interface ReadContextMember {
|
||||
userId: string;
|
||||
lastReadAt: Date | null;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ChatService {
|
||||
constructor(
|
||||
@@ -51,27 +56,18 @@ export class ChatService {
|
||||
orderBy: [{ type: 'asc' }, { updatedAt: 'desc' }]
|
||||
});
|
||||
|
||||
const familyMembers = await this.prisma.familyMember.findMany({ where: { groupId } });
|
||||
const familyRoleByUserId = new Map(familyMembers.map((member) => [member.userId, member.role]));
|
||||
|
||||
return {
|
||||
rooms: await Promise.all(
|
||||
rooms.map(async (room) => {
|
||||
const membership = room.members.find((member) => member.userId === userId);
|
||||
const lastMessage = room.messages[0];
|
||||
return {
|
||||
id: room.id,
|
||||
groupId: room.groupId,
|
||||
type: room.type,
|
||||
name: room.name,
|
||||
hasAvatar: room.hasAvatar,
|
||||
updatedAt: room.updatedAt.toISOString(),
|
||||
members: room.members.map((member) => ({
|
||||
id: member.id,
|
||||
userId: member.userId,
|
||||
displayName: member.user.displayName,
|
||||
hasAvatar: Boolean(member.user.avatarStorageKey),
|
||||
notificationsMuted: member.notificationsMuted
|
||||
})),
|
||||
lastMessage: lastMessage ? await this.toMessage(lastMessage, userId) : undefined
|
||||
};
|
||||
return this.formatRoom(
|
||||
room,
|
||||
familyRoleByUserId,
|
||||
lastMessage ? await this.toMessage(lastMessage, userId, await this.getRoomReadContext(room.id)) : undefined
|
||||
);
|
||||
})
|
||||
)
|
||||
};
|
||||
@@ -107,21 +103,61 @@ export class ChatService {
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
id: room.id,
|
||||
groupId: room.groupId,
|
||||
type: room.type,
|
||||
name: room.name,
|
||||
hasAvatar: room.hasAvatar,
|
||||
updatedAt: room.updatedAt.toISOString(),
|
||||
members: room.members.map((member) => ({
|
||||
id: member.id,
|
||||
userId: member.userId,
|
||||
displayName: member.user.displayName,
|
||||
hasAvatar: Boolean(member.user.avatarStorageKey),
|
||||
notificationsMuted: member.notificationsMuted
|
||||
}))
|
||||
};
|
||||
const familyMembers = await this.prisma.familyMember.findMany({ where: { groupId } });
|
||||
const familyRoleByUserId = new Map(familyMembers.map((member) => [member.userId, member.role]));
|
||||
|
||||
return this.formatRoom(room, familyRoleByUserId);
|
||||
}
|
||||
|
||||
async addRoomMember(userId: string, roomId: string, memberUserId: string) {
|
||||
const room = await this.getRoomForMember(roomId, userId);
|
||||
if (room.type === 'GENERAL') {
|
||||
throw new BadRequestException('В общий чат нельзя добавлять участников вручную');
|
||||
}
|
||||
if (room.members.some((member) => member.userId === memberUserId)) {
|
||||
throw new BadRequestException('Пользователь уже состоит в чате');
|
||||
}
|
||||
if (!room.group.members.some((member) => member.userId === memberUserId)) {
|
||||
throw new BadRequestException('Пользователь должен состоять в семье');
|
||||
}
|
||||
|
||||
await this.prisma.chatRoomMember.create({
|
||||
data: { roomId, userId: memberUserId }
|
||||
});
|
||||
|
||||
return this.getRoomResponse(roomId, userId);
|
||||
}
|
||||
|
||||
async removeRoomMember(userId: string, roomId: string, memberUserId: string) {
|
||||
const room = await this.getRoomForMember(roomId, userId);
|
||||
if (room.type === 'GENERAL') {
|
||||
throw new BadRequestException('Нельзя удалить участника из общего чата');
|
||||
}
|
||||
|
||||
const isFamilyOwner = room.group.ownerId === userId;
|
||||
const isChatCreator = room.createdById === userId;
|
||||
if (!isFamilyOwner && !isChatCreator) {
|
||||
throw new ForbiddenException('Недостаточно прав для удаления участника из чата');
|
||||
}
|
||||
|
||||
if (memberUserId === room.createdById && !isFamilyOwner) {
|
||||
throw new BadRequestException('Создателя чата может удалить только создатель семьи');
|
||||
}
|
||||
|
||||
if (memberUserId === userId && room.members.length <= 1) {
|
||||
throw new BadRequestException('В чате должен остаться хотя бы один участник');
|
||||
}
|
||||
|
||||
const membership = room.members.find((member) => member.userId === memberUserId);
|
||||
if (!membership) {
|
||||
throw new NotFoundException('Участник не найден в этом чате');
|
||||
}
|
||||
|
||||
await this.prisma.chatRoomMember.delete({
|
||||
where: { roomId_userId: { roomId, userId: memberUserId } }
|
||||
});
|
||||
|
||||
return this.getRoomResponse(roomId, userId);
|
||||
}
|
||||
|
||||
async updateRoomSettings(userId: string, roomId: string, name?: string, notificationsMuted?: boolean) {
|
||||
@@ -148,6 +184,7 @@ export class ChatService {
|
||||
async listMessages(userId: string, roomId: string, beforeMessageId?: string, limit = 50) {
|
||||
await this.getRoomForMember(roomId, userId);
|
||||
const take = Math.min(Math.max(limit, 1), 100);
|
||||
const readContext = await this.getRoomReadContext(roomId);
|
||||
|
||||
let cursorDate: Date | undefined;
|
||||
if (beforeMessageId) {
|
||||
@@ -170,7 +207,7 @@ export class ChatService {
|
||||
|
||||
const ordered = messages.reverse();
|
||||
return {
|
||||
messages: await Promise.all(ordered.map((message) => this.toMessage(message, userId)))
|
||||
messages: await Promise.all(ordered.map((message) => this.toMessage(message, userId, readContext)))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -255,11 +292,93 @@ export class ChatService {
|
||||
}
|
||||
});
|
||||
|
||||
const response = await this.toMessage(fullMessage!, userId);
|
||||
const readContext = await this.getRoomReadContext(roomId);
|
||||
const response = await this.toMessage(fullMessage!, userId, readContext);
|
||||
await this.notifyRoomMembers(room, userId, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
async editMessage(userId: string, messageId: string, content: string) {
|
||||
const message = await this.prisma.chatMessage.findUnique({
|
||||
where: { id: messageId },
|
||||
include: { room: { include: { members: true } } }
|
||||
});
|
||||
if (!message || message.deletedAt) {
|
||||
throw new NotFoundException('Сообщение не найдено');
|
||||
}
|
||||
if (message.senderId !== userId) {
|
||||
throw new ForbiddenException('Можно редактировать только свои сообщения');
|
||||
}
|
||||
if (!['TEXT', 'EMOJI'].includes(message.type)) {
|
||||
throw new BadRequestException('Этот тип сообщения нельзя редактировать');
|
||||
}
|
||||
|
||||
const trimmed = content.trim();
|
||||
if (!trimmed) {
|
||||
throw new BadRequestException('Сообщение не может быть пустым');
|
||||
}
|
||||
|
||||
await this.prisma.chatMessage.update({
|
||||
where: { id: messageId },
|
||||
data: { content: trimmed, editedAt: new Date() }
|
||||
});
|
||||
|
||||
const response = await this.loadMessageResponse(messageId, userId);
|
||||
await this.publishRoomEvent(message.room, 'chat_message_updated', response);
|
||||
return response;
|
||||
}
|
||||
|
||||
async deleteMessage(userId: string, messageId: string) {
|
||||
const message = await this.prisma.chatMessage.findUnique({
|
||||
where: { id: messageId },
|
||||
include: { room: { include: { members: true } } }
|
||||
});
|
||||
if (!message || message.deletedAt) {
|
||||
throw new NotFoundException('Сообщение не найдено');
|
||||
}
|
||||
if (message.senderId !== userId) {
|
||||
throw new ForbiddenException('Можно удалять только свои сообщения');
|
||||
}
|
||||
|
||||
await this.prisma.chatMessage.update({
|
||||
where: { id: messageId },
|
||||
data: { deletedAt: new Date(), content: null, storageKey: null, mimeType: null, metadata: undefined }
|
||||
});
|
||||
|
||||
const response = await this.loadMessageResponse(messageId, userId);
|
||||
await this.publishRoomEvent(message.room, 'chat_message_deleted', response);
|
||||
return response;
|
||||
}
|
||||
|
||||
async markRoomRead(userId: string, roomId: string, lastMessageId?: string) {
|
||||
const room = await this.getRoomForMember(roomId, userId);
|
||||
let readAt = new Date();
|
||||
|
||||
if (lastMessageId) {
|
||||
const message = await this.prisma.chatMessage.findFirst({ where: { id: lastMessageId, roomId } });
|
||||
if (message) {
|
||||
readAt = message.createdAt;
|
||||
}
|
||||
}
|
||||
|
||||
await this.prisma.chatRoomMember.update({
|
||||
where: { roomId_userId: { roomId, userId } },
|
||||
data: { lastReadAt: readAt, lastReadMessageId: lastMessageId ?? null }
|
||||
});
|
||||
|
||||
for (const member of room.members) {
|
||||
if (member.userId === userId) continue;
|
||||
await this.notifications.publishRealtime(member.userId, 'chat_read_receipt', room.name, '', {
|
||||
roomId,
|
||||
userId,
|
||||
lastReadAt: readAt.toISOString(),
|
||||
lastReadMessageId: lastMessageId
|
||||
});
|
||||
}
|
||||
|
||||
return { count: 1 };
|
||||
}
|
||||
|
||||
async votePoll(userId: string, messageId: string, optionIds: string[]) {
|
||||
const message = await this.prisma.chatMessage.findUnique({
|
||||
where: { id: messageId },
|
||||
@@ -302,7 +421,7 @@ export class ChatService {
|
||||
poll: { include: { options: { include: { votes: true } } } }
|
||||
}
|
||||
});
|
||||
return this.toMessage(updated!, userId);
|
||||
return this.toMessage(updated!, userId, await this.getRoomReadContext(updated!.roomId));
|
||||
}
|
||||
|
||||
async setRoomNotificationsMuted(userId: string, roomId: string, muted: boolean) {
|
||||
@@ -335,27 +454,88 @@ export class ChatService {
|
||||
return room;
|
||||
}
|
||||
|
||||
private formatRoom(
|
||||
room: {
|
||||
id: string;
|
||||
groupId: string;
|
||||
type: string;
|
||||
name: string;
|
||||
hasAvatar: boolean;
|
||||
updatedAt: Date;
|
||||
createdById: string | null;
|
||||
members: Array<{
|
||||
id: string;
|
||||
userId: string;
|
||||
notificationsMuted: boolean;
|
||||
user: { displayName: string; avatarStorageKey: string | null };
|
||||
}>;
|
||||
},
|
||||
familyRoleByUserId: Map<string, string>,
|
||||
lastMessage?: Awaited<ReturnType<ChatService['toMessage']>>
|
||||
) {
|
||||
return {
|
||||
id: room.id,
|
||||
groupId: room.groupId,
|
||||
type: room.type,
|
||||
name: room.name,
|
||||
hasAvatar: room.hasAvatar,
|
||||
createdById: room.createdById ?? undefined,
|
||||
updatedAt: room.updatedAt.toISOString(),
|
||||
members: room.members.map((member) => ({
|
||||
id: member.id,
|
||||
userId: member.userId,
|
||||
displayName: member.user.displayName,
|
||||
hasAvatar: Boolean(member.user.avatarStorageKey),
|
||||
notificationsMuted: member.notificationsMuted,
|
||||
familyRole: familyRoleByUserId.get(member.userId) ?? 'member',
|
||||
isChatCreator: room.createdById === member.userId
|
||||
})),
|
||||
lastMessage
|
||||
};
|
||||
}
|
||||
|
||||
private async getRoomResponse(roomId: string, userId: string) {
|
||||
const room = await this.getRoomForMember(roomId, userId);
|
||||
const full = await this.prisma.chatRoom.findUnique({
|
||||
where: { id: roomId },
|
||||
include: { members: { include: { user: true } } }
|
||||
});
|
||||
return {
|
||||
id: full!.id,
|
||||
groupId: full!.groupId,
|
||||
type: full!.type,
|
||||
name: full!.name,
|
||||
hasAvatar: full!.hasAvatar,
|
||||
updatedAt: full!.updatedAt.toISOString(),
|
||||
members: full!.members.map((member) => ({
|
||||
id: member.id,
|
||||
userId: member.userId,
|
||||
displayName: member.user.displayName,
|
||||
hasAvatar: Boolean(member.user.avatarStorageKey),
|
||||
notificationsMuted: member.notificationsMuted
|
||||
}))
|
||||
};
|
||||
const familyMembers = await this.prisma.familyMember.findMany({ where: { groupId: full!.groupId } });
|
||||
const familyRoleByUserId = new Map(familyMembers.map((member) => [member.userId, member.role]));
|
||||
return this.formatRoom(full!, familyRoleByUserId);
|
||||
}
|
||||
|
||||
private async getRoomReadContext(roomId: string): Promise<ReadContextMember[]> {
|
||||
const members = await this.prisma.chatRoomMember.findMany({ where: { roomId } });
|
||||
return members.map((member) => ({ userId: member.userId, lastReadAt: member.lastReadAt }));
|
||||
}
|
||||
|
||||
private async loadMessageResponse(messageId: string, viewerId: string) {
|
||||
const message = await this.prisma.chatMessage.findUnique({
|
||||
where: { id: messageId },
|
||||
include: {
|
||||
sender: true,
|
||||
poll: { include: { options: { include: { votes: true } } } }
|
||||
}
|
||||
});
|
||||
if (!message) {
|
||||
throw new NotFoundException('Сообщение не найдено');
|
||||
}
|
||||
const readContext = await this.getRoomReadContext(message.roomId);
|
||||
return this.toMessage(message, viewerId, readContext);
|
||||
}
|
||||
|
||||
private async publishRoomEvent(
|
||||
room: { id: string; name: string; members: Array<{ userId: string }> },
|
||||
eventType: string,
|
||||
message: Awaited<ReturnType<ChatService['toMessage']>>
|
||||
) {
|
||||
for (const member of room.members) {
|
||||
await this.notifications.publishRealtime(member.userId, eventType, room.name, '', {
|
||||
roomId: room.id,
|
||||
message
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async notifyRoomMembers(
|
||||
@@ -412,6 +592,8 @@ export class ChatService {
|
||||
mimeType: string | null;
|
||||
metadata: unknown;
|
||||
createdAt: Date;
|
||||
editedAt?: Date | null;
|
||||
deletedAt?: Date | null;
|
||||
sender: { displayName: string; avatarStorageKey: string | null };
|
||||
poll?: {
|
||||
id: string;
|
||||
@@ -422,8 +604,17 @@ export class ChatService {
|
||||
options: Array<{ id: string; text: string; votes: Array<{ userId: string }> }>;
|
||||
} | null;
|
||||
},
|
||||
viewerId: string
|
||||
viewerId: string,
|
||||
readContext?: ReadContextMember[]
|
||||
) {
|
||||
const isDeleted = Boolean(message.deletedAt);
|
||||
let readByAll = false;
|
||||
if (readContext && message.senderId === viewerId && !isDeleted) {
|
||||
const others = readContext.filter((member) => member.userId !== message.senderId);
|
||||
readByAll =
|
||||
others.length > 0 && others.every((member) => member.lastReadAt && member.lastReadAt >= message.createdAt);
|
||||
}
|
||||
|
||||
return {
|
||||
id: message.id,
|
||||
roomId: message.roomId,
|
||||
@@ -431,13 +622,16 @@ export class ChatService {
|
||||
senderName: message.sender.displayName,
|
||||
senderHasAvatar: Boolean(message.sender.avatarStorageKey),
|
||||
type: message.type,
|
||||
content: message.content ?? undefined,
|
||||
content: isDeleted ? undefined : message.content ?? undefined,
|
||||
replyToId: message.replyToId ?? undefined,
|
||||
storageKey: message.storageKey ?? undefined,
|
||||
mimeType: message.mimeType ?? undefined,
|
||||
metadataJson: message.metadata ? JSON.stringify(message.metadata) : undefined,
|
||||
storageKey: isDeleted ? undefined : message.storageKey ?? undefined,
|
||||
mimeType: isDeleted ? undefined : message.mimeType ?? undefined,
|
||||
metadataJson: isDeleted ? undefined : message.metadata ? JSON.stringify(message.metadata) : undefined,
|
||||
createdAt: message.createdAt.toISOString(),
|
||||
poll: message.poll
|
||||
editedAt: message.editedAt?.toISOString(),
|
||||
isDeleted,
|
||||
readByAll: message.senderId === viewerId ? readByAll : undefined,
|
||||
poll: !isDeleted && message.poll
|
||||
? {
|
||||
id: message.poll.id,
|
||||
question: message.poll.question,
|
||||
|
||||
@@ -128,11 +128,11 @@ export class MediaService {
|
||||
throw new ForbiddenException('Ссылка недействительна');
|
||||
}
|
||||
|
||||
if (payload.objectKey.startsWith('chat/')) {
|
||||
if (payload.objectKey.startsWith('chat/') || payload.objectKey.startsWith('chat-rooms/')) {
|
||||
if (!requesterId) {
|
||||
throw new ForbiddenException('Для доступа к файлу чата требуется авторизация');
|
||||
}
|
||||
const roomId = payload.roomId ?? this.extractChatRoomId(payload.objectKey);
|
||||
const roomId = payload.roomId ?? this.extractChatRoomId(payload.objectKey) ?? this.extractChatRoomAvatarRoomId(payload.objectKey);
|
||||
if (!roomId) {
|
||||
throw new ForbiddenException('Некорректный ключ файла чата');
|
||||
}
|
||||
@@ -238,6 +238,39 @@ export class MediaService {
|
||||
return this.createStreamAccessUrl(storageKey, requesterId, { roomId, fileName });
|
||||
}
|
||||
|
||||
async createChatRoomAvatarUploadUrl(requesterId: string, roomId: string, contentType: string) {
|
||||
await this.assertChatMember(roomId, requesterId);
|
||||
try {
|
||||
this.minio.assertImageContentType(contentType);
|
||||
} catch (error) {
|
||||
throw new BadRequestException(error instanceof Error ? error.message : 'Некорректный тип файла');
|
||||
}
|
||||
const extension = this.minio.extensionForContentType(contentType);
|
||||
const storageKey = `chat-rooms/${roomId}/${crypto.randomUUID()}.${extension}`;
|
||||
return this.createUploadTarget(requesterId, storageKey, contentType);
|
||||
}
|
||||
|
||||
async confirmChatRoomAvatar(requesterId: string, roomId: string, storageKey: string) {
|
||||
await this.assertChatMember(roomId, requesterId);
|
||||
if (!storageKey.startsWith(`chat-rooms/${roomId}/`)) {
|
||||
throw new BadRequestException('Некорректный ключ аватара чата');
|
||||
}
|
||||
await this.prisma.chatRoom.update({
|
||||
where: { id: roomId },
|
||||
data: { avatarStorageKey: storageKey, hasAvatar: true }
|
||||
});
|
||||
return { roomId, hasAvatar: true };
|
||||
}
|
||||
|
||||
async getChatRoomAvatarAccessUrl(requesterId: string, roomId: string) {
|
||||
await this.assertChatMember(roomId, requesterId);
|
||||
const room = await this.prisma.chatRoom.findUnique({ where: { id: roomId } });
|
||||
if (!room?.avatarStorageKey) {
|
||||
throw new NotFoundException('Аватар чата не найден');
|
||||
}
|
||||
return this.createStreamAccessUrl(room.avatarStorageKey, requesterId, { roomId });
|
||||
}
|
||||
|
||||
private extractChatRoomId(storageKey: string) {
|
||||
const [prefix, roomId] = storageKey.split('/');
|
||||
if (prefix !== 'chat' || !roomId) {
|
||||
@@ -246,6 +279,14 @@ export class MediaService {
|
||||
return roomId;
|
||||
}
|
||||
|
||||
private extractChatRoomAvatarRoomId(storageKey: string) {
|
||||
const [prefix, roomId] = storageKey.split('/');
|
||||
if (prefix !== 'chat-rooms' || !roomId) {
|
||||
return null;
|
||||
}
|
||||
return roomId;
|
||||
}
|
||||
|
||||
private async createUploadTarget(userId: string, storageKey: string, contentType: string) {
|
||||
const viaApi = this.config.get<string>('MINIO_UPLOAD_VIA_API', 'true') !== 'false';
|
||||
const expiresAt = new Date(Date.now() + UPLOAD_TTL_SECONDS * 1000).toISOString();
|
||||
|
||||
44
apps/sso-core/src/domain/presence.service.ts
Normal file
44
apps/sso-core/src/domain/presence.service.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { RedisService } from '../infra/redis.service';
|
||||
import { FamilyService } from './family.service';
|
||||
|
||||
const ONLINE_KEY_PREFIX = 'ws:user:';
|
||||
const LAST_SEEN_KEY_PREFIX = 'ws:last_seen:';
|
||||
|
||||
@Injectable()
|
||||
export class PresenceService {
|
||||
constructor(
|
||||
private readonly redis: RedisService,
|
||||
private readonly family: FamilyService
|
||||
) {}
|
||||
|
||||
async isUserOnline(userId: string) {
|
||||
const value = await this.redis.client.get(`${ONLINE_KEY_PREFIX}${userId}`);
|
||||
return value === 'online';
|
||||
}
|
||||
|
||||
async getUserLastSeen(userId: string) {
|
||||
return this.redis.client.get(`${LAST_SEEN_KEY_PREFIX}${userId}`);
|
||||
}
|
||||
|
||||
async getFamilyPresence(requesterId: string, groupId: string) {
|
||||
const group = await this.family.assertFamilyMember(groupId, requesterId);
|
||||
const members = await Promise.all(
|
||||
group.members.map(async (member) => {
|
||||
const online = await this.isUserOnline(member.userId);
|
||||
const lastSeenRaw = online ? null : await this.getUserLastSeen(member.userId);
|
||||
return {
|
||||
userId: member.userId,
|
||||
displayName: member.user.displayName,
|
||||
online,
|
||||
lastSeenAt: online ? new Date().toISOString() : lastSeenRaw ?? undefined
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
members,
|
||||
onlineCount: members.filter((member) => member.online).length
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user