Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 | 15x 15x 15x 15x 32x 32x 12x 12x 12x 12x 12x 8x 4x 2x 12x 11x 11x 11x 1x 10x 10x 10x 2x 4x 2x 2x 8x 4x 4x 2x 2x 6x 4x 4x 1x 3x 1x 4x 8x 4x 4x 5x 5x 2x 2x 4x 4x 4x 2x 4x 4x 2x 2x 2x 4x 4x 1x 3x 6x 18x 18x 18x 2x 16x 16x 16x 1x 18x 15x 2x 2x 13x 3x 3x 1x 2x 1x 11x 11x 11x 11x 11x 7x 7x 3x 3x 1x 2x 2x 1x 1x 1x 3x 3x 1x 2x 2x 2x 4x 4x 2x | import { Injectable, NotFoundException, ForbiddenException, BadRequestException, Logger } from '@nestjs/common';
import { PrismaService } from '@app/modules/prisma/prisma.service';
import { CreateConversationDto } from './dto/create-conversation.dto';
import { SendMessageDto } from './dto/send-message.dto';
import { sanitizeHtml } from '@app/utils/sanitize';
@Injectable()
export class MessagingService {
private readonly logger = new Logger(MessagingService.name);
constructor(private prisma: PrismaService) {}
/**
* Add computed type field to conversation based on participant count and listing presence
*/
private enrichConversation(conversation: any) {
Iif (!conversation) return conversation;
const participantCount = conversation.participants?.length || 0;
const hasListing = !!conversation.listingId;
// Determine type: DIRECT (2 participants, no listing), GROUP, or LISTING
let type = 'GROUP';
if (participantCount === 2 && !hasListing) {
type = 'DIRECT';
} else if (hasListing) {
type = 'LISTING';
}
return {
...conversation,
type,
};
}
async createConversation(userId: number, dto: CreateConversationDto) {
try {
this.logger.debug(`User ${userId} creating conversation with participants: ${dto.participantIds.join(', ')}`);
// Validate input
if (!dto.participantIds || dto.participantIds.length === 0) {
throw new BadRequestException('At least one participant is required');
}
// Include current user in participants if not already included
const allParticipantIds = Array.from(new Set([userId, ...dto.participantIds]));
// Verify all participants exist
const users = await this.prisma.user.findMany({
where: { id: { in: allParticipantIds } },
select: { id: true },
});
if (users.length !== allParticipantIds.length) {
const foundIds = users.map((u) => u.id);
const missingIds = allParticipantIds.filter((id) => !foundIds.includes(id));
this.logger.warn(`Attempted to create conversation with non-existent users: ${missingIds.join(', ')}`);
throw new NotFoundException(`Users not found: ${missingIds.join(', ')}`);
}
// Check if conversation already exists with same participants (for direct messages)
if (allParticipantIds.length === 2 && !dto.listingId) {
const existingConversation = await this.prisma.conversation.findFirst({
where: {
AND: [
{ participants: { some: { userId: allParticipantIds[0] } } },
{ participants: { some: { userId: allParticipantIds[1] } } },
{ listingId: null },
],
},
include: {
participants: { include: { user: { select: { id: true, name: true, email: true, avatarMedia: true } } } },
messages: { take: 1, orderBy: { createdAt: 'desc' }, include: { sender: true } },
listing: true,
},
});
if (existingConversation) {
this.logger.debug(`Found existing conversation ${existingConversation.id} for users ${allParticipantIds.join(', ')}`);
return this.enrichConversation(existingConversation);
}
}
// Verify listing exists if provided
if (dto.listingId) {
const listing = await this.prisma.listing.findUnique({
where: { id: dto.listingId },
select: { id: true, deletedAt: true },
});
if (!listing) {
throw new NotFoundException(`Listing #${dto.listingId} not found`);
}
if (listing.deletedAt) {
throw new BadRequestException('Cannot create conversation for deleted listing');
}
}
// Create new conversation
const conversation = await this.prisma.conversation.create({
data: {
listingId: dto.listingId,
participants: {
create: allParticipantIds.map((id) => ({ userId: id })),
},
},
include: {
participants: { include: { user: { select: { id: true, name: true, email: true, avatarMedia: true } } } },
listing: true,
},
});
this.logger.log(`Created conversation ${conversation.id} with ${allParticipantIds.length} participants`);
return this.enrichConversation(conversation);
} catch (error) {
if (error instanceof NotFoundException || error instanceof BadRequestException || error instanceof ForbiddenException) {
throw error;
}
this.logger.error(`Error creating conversation for user ${userId}:`, error);
throw new Error('Failed to create conversation');
}
}
async getMyConversations(userId: number) {
const conversations = await this.prisma.conversation.findMany({
where: { participants: { some: { userId } } },
include: {
participants: { include: { user: { select: { id: true, name: true, email: true, avatarMedia: true } } } },
messages: { take: 1, orderBy: { createdAt: 'desc' }, include: { sender: true } },
listing: true,
},
orderBy: { updatedAt: 'desc' },
});
// Add unread count and type for each conversation
const conversationsWithUnread = await Promise.all(
conversations.map(async (conv) => {
const unreadCount = await this.prisma.message.count({
where: {
conversationId: conv.id,
senderId: { not: userId },
readAt: null,
},
});
const enriched = this.enrichConversation(conv);
return {
...enriched,
unreadCount,
lastMessage: conv.messages[0] || null,
};
}),
);
return conversationsWithUnread;
}
async getConversation(conversationId: number, userId: number) {
// Verify user is participant
const participant = await this.prisma.conversationParticipant.findFirst({
where: { conversationId, userId },
});
if (!participant) {
throw new ForbiddenException('You are not a participant in this conversation');
}
const conversation = await this.prisma.conversation.findUnique({
where: { id: conversationId },
include: {
participants: { include: { user: true } },
listing: true,
},
});
return this.enrichConversation(conversation);
}
async getMessages(conversationId: number, userId: number, before?: number, limit = 50) {
// Verify user is participant
const participant = await this.prisma.conversationParticipant.findFirst({
where: { conversationId, userId },
});
if (!participant) {
throw new ForbiddenException('You are not a participant in this conversation');
}
const messages = await this.prisma.message.findMany({
where: {
conversationId,
...(before && { id: { lt: before } }),
},
include: {
sender: {
select: { id: true, name: true, email: true, avatarMedia: true },
},
media: true,
},
orderBy: { createdAt: 'desc' },
take: limit,
});
// Map DB 'text' to API 'content'
return (messages as any[]).map((m) => ({ ...m, content: (m as any).text }));
}
async sendMessage(conversationId: number, userId: number, dto: SendMessageDto) {
try {
this.logger.debug(`User ${userId} sending message to conversation ${conversationId}`);
// Validate input
if (!dto.content && !dto.mediaId) {
throw new BadRequestException('Message must contain text or media');
}
const result = await this.prisma.$transaction(async (tx) => {
// Verify conversation and participants in one go
const conversation = await tx.conversation.findUnique({
where: { id: conversationId },
include: { participants: true },
});
if (!conversation) {
throw new NotFoundException(`Conversation #${conversationId} not found`);
}
const isParticipant = conversation.participants.some((p: any) => p.userId === userId);
if (!isParticipant) {
this.logger.warn(`User ${userId} attempted to send message to conversation ${conversationId} without being a participant`);
throw new ForbiddenException('You are not a participant in this conversation');
}
// Verify media exists if provided
if (dto.mediaId) {
const media = await tx.media.findUnique({
where: { id: dto.mediaId },
select: { id: true, deletedAt: true },
});
if (!media) {
throw new NotFoundException(`Media #${dto.mediaId} not found`);
}
if (media.deletedAt) {
throw new BadRequestException('Cannot send deleted media');
}
}
const message = await tx.message.create({
data: {
conversationId,
senderId: userId,
text: dto.content ? sanitizeHtml(dto.content) : dto.content,
mediaId: dto.mediaId,
},
include: {
sender: {
select: { id: true, name: true, email: true, avatarMedia: true },
},
media: true,
},
});
await tx.conversation.update({
where: { id: conversationId },
data: { updatedAt: new Date() },
});
return message;
});
this.logger.log(`User ${userId} sent message ${result.id} to conversation ${conversationId}`);
// Map DB 'text' to API 'content'
return { ...result, content: (result as any).text };
} catch (error) {
if (error instanceof NotFoundException || error instanceof BadRequestException || error instanceof ForbiddenException) {
throw error;
}
this.logger.error(`Error sending message for user ${userId} to conversation ${conversationId}:`, error);
throw new Error('Failed to send message');
}
}
async markAsRead(messageId: number, userId: number) {
const message = await this.prisma.message.findUnique({
where: { id: messageId },
include: { conversation: { include: { participants: true } } },
});
if (!message) {
throw new NotFoundException('Message not found');
}
const isParticipant = message.conversation.participants.some((p) => p.userId === userId);
if (!isParticipant) {
throw new ForbiddenException('You are not a participant in this conversation');
}
// Only mark as read if user is not the sender
Iif (message.senderId === userId) {
return message;
}
return this.prisma.message.update({
where: { id: messageId },
data: { readAt: new Date() },
include: {
sender: {
select: { id: true, name: true, email: true, avatarMedia: true },
},
media: true,
},
});
}
async markConversationAsRead(conversationId: number, userId: number) {
// Verify participant
const participant = await this.prisma.conversationParticipant.findFirst({
where: { conversationId, userId },
});
if (!participant) {
throw new ForbiddenException('You are not a participant in this conversation');
}
// Mark all unread messages in conversation as read
await this.prisma.message.updateMany({
where: {
conversationId,
senderId: { not: userId },
readAt: null,
},
data: { readAt: new Date() },
});
return { success: true };
}
async getUnreadCount(userId: number) {
const conversations = await this.prisma.conversation.findMany({
where: { participants: { some: { userId } } },
include: {
messages: {
where: {
senderId: { not: userId },
readAt: null,
},
select: { id: true },
},
},
});
const count = conversations.reduce((sum, conv) => sum + conv.messages.length, 0);
const byConversation = conversations.map((c) => ({ conversationId: c.id, count: c.messages.length }));
return { count, byConversation };
}
}
|