import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; import mongoose from 'mongoose'; import { NatsService } from '../global/nats/nats.service'; import { SecretService } from '../global/secret/secret.service'; import { CommandParseError, parseCommand } from './parsers/command.parser'; import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types'; import { DakaoPublisher } from './dakao.publisher'; import { DakaoUserError, DakaoUserService } from './dakao-user.service'; import { IdempotencyCache } from './idempotency.cache'; import { AccountRegisterHandler } from './handlers/account-register.handler'; import { MatchCancelHandler } from './handlers/match-cancel.handler'; import { MatchJoinHandler } from './handlers/match-join.handler'; import { MatchListHandler } from './handlers/match-list.handler'; import { PreferredPositionRegisterHandler } from './handlers/preferred-position-register.handler'; const INBOUND_SUBJECT_DEFAULT = 'lolympus-tournament-support.kakaotalk.command'; @Injectable() export class DakaoSubscriber implements OnModuleInit { private readonly logger = new Logger(DakaoSubscriber.name); private inboundSubject = INBOUND_SUBJECT_DEFAULT; private botUserId: string | undefined; constructor( private readonly natsService: NatsService, private readonly secretService: SecretService, private readonly dakaoUserService: DakaoUserService, private readonly publisher: DakaoPublisher, private readonly idempotency: IdempotencyCache, private readonly accountRegisterHandler: AccountRegisterHandler, private readonly matchListHandler: MatchListHandler, private readonly matchJoinHandler: MatchJoinHandler, private readonly matchCancelHandler: MatchCancelHandler, private readonly preferredPositionRegisterHandler: PreferredPositionRegisterHandler, ) {} async onModuleInit() { const subjectOverride = await this.secretService .get('DAKAO_INBOUND_SUBJECT') .catch(() => undefined); this.inboundSubject = subjectOverride || INBOUND_SUBJECT_DEFAULT; this.botUserId = await this.secretService .get('DAKAO_BOT_USER_ID') .catch(() => undefined); this.natsService.subscribe( this.inboundSubject, (event) => this.handleEvent(event), ); this.logger.log( `Dakao inbound subscriber ready on subject="${this.inboundSubject}"`, ); } private async handleEvent(event: DakaoInboundEvent): Promise { if (!this.validate(event)) return; if (this.botUserId && event.userId === this.botUserId) { return; } const logIdKey = this.deriveLogIdKey(event); if (logIdKey && this.idempotency.has(logIdKey)) { return; } if (logIdKey) this.idempotency.remember(logIdKey); let communityId: mongoose.Types.ObjectId; try { communityId = await this.dakaoUserService.resolveCommunityIdByDakaoProjectId( event.projectId, ); } catch (err) { if (err instanceof DakaoUserError) { if (err.code === 'invalid_project_id') { this.logger.warn(`Invalid dakao projectId format: ${event.projectId}`); return; } if (err.code === 'community_not_found') { // 우리 쪽이 모르는 projectId. 메시지를 보내봤자 컨텍스트가 없으므로 로그만. this.logger.warn(`Unknown dakao projectId: ${event.projectId}`); return; } } throw err; } let segments: DakaoSegment[]; const senderNickname = this.resolveSenderNickname(event); const correlationId = this.serializeDakaoLong(event.origin.chatLog.logId); try { const command = parseCommand(event.origin.chatLog.message); switch (command.kind) { case 'match-list': segments = await this.matchListHandler.handle({ communityId, senderUserId: event.userId, senderNickname, }); break; case 'account-register': segments = await this.accountRegisterHandler.handle({ communityId, senderUserId: event.userId, senderNickname, gameName: command.gameName, tagLine: command.tagLine, }); break; case 'match-join': segments = await this.matchJoinHandler.handle({ communityId, matchAndRiotId: command.matchAndRiotId, senderUserId: event.userId, senderNickname, positions: command.positions?.positions, }); break; case 'preferred-position-register': segments = await this.preferredPositionRegisterHandler.handle({ communityId, senderUserId: event.userId, senderNickname, positions: command.positions.positions, }); break; case 'match-cancel': segments = await this.matchCancelHandler.handle({ communityId, matchId: command.matchId, senderUserId: event.userId, senderNickname, }); break; } await this.publisher.sendMessage({ chatroomId: event.chatroomId, segments, correlationId, }); } catch (err) { if (err instanceof CommandParseError) { // not_a_command 는 명령이 아닌 일반 메시지 → 무시. if (err.code === 'not_a_command') return; await this.publisher.sendMessage({ chatroomId: event.chatroomId, segments: this.parseErrorReply(event, senderNickname, err), correlationId, }); return; } this.logger.error( `Unhandled dakao event error: ${(err as Error)?.stack ?? err}`, ); } } private validate(event: unknown): event is DakaoInboundEvent { if (!event || typeof event !== 'object') return false; const e = event as Partial; if (typeof e.projectId !== 'string' || e.projectId.length === 0) return false; if (typeof e.chatroomId !== 'string' || e.chatroomId.length === 0) return false; if (typeof e.nickname !== 'string') return false; if (typeof e.userId !== 'string' || e.userId.length === 0) return false; if (!e.origin || typeof e.origin !== 'object') return false; const chatLog = (e.origin as { chatLog?: unknown }).chatLog; if (!chatLog || typeof chatLog !== 'object') return false; if (typeof (chatLog as { message?: unknown }).message !== 'string') return false; return true; } private deriveLogIdKey(event: DakaoInboundEvent): string | null { const serialized = this.serializeDakaoLong(event.origin.chatLog.logId); return serialized ? `${event.projectId}:${serialized}` : null; } private serializeDakaoLong(value: DakaoLong | string | undefined): string { if (typeof value === 'string') return value; if (!value || typeof value !== 'object') return ''; const high = BigInt(value.high ?? 0); const low = BigInt.asUintN(32, BigInt(value.low ?? 0)); const combined = (high << 32n) | low; return value.unsigned ? BigInt.asUintN(64, combined).toString() : BigInt.asIntN(64, combined).toString(); } private resolveSenderNickname(event: DakaoInboundEvent): string { const primary = event.nickname?.trim(); if (primary) return primary; const fallback = event.origin.authorNickname?.trim(); return fallback ?? ''; } private parseErrorReply( event: DakaoInboundEvent, senderNickname: string, err: CommandParseError, ): DakaoSegment[] { const head: DakaoSegment[] = [ { kind: 'mention', userId: event.userId, displayText: senderNickname, }, ]; const text = ((): string => { switch (err.code) { case 'unknown_command': return ` 알 수 없는 명령어입니다. 사용법: !내전 일정, !내전 계정등록 <게임명>#<태그>, !내전 선호포지션등록 미드,정글, !내전 신청 [코드] [게임명#태그] [포지션1,포지션2], !내전 취소 <코드>`; case 'usage': return ` 사용법: !내전 일정, !내전 계정등록 <게임명>#<태그>, !내전 선호포지션등록 미드,정글, !내전 신청 [코드] [게임명#태그] [포지션1,포지션2], !내전 취소 <코드>`; case 'invalid_match_id': return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`; case 'invalid_riot_id': return ` 라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).`; case 'invalid_position': return ` 포지션 입력이 올바르지 않습니다. 쉼표로 구분해서 최소 2개를 중복 없이 입력해주세요. 사용 가능: 탑, 정글, 미드, 원딜, 서폿`; default: return ` 명령을 처리할 수 없습니다.`; } })(); return [...head, { kind: 'text', text }]; } }