309 lines
11 KiB
TypeScript
309 lines
11 KiB
TypeScript
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 { 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';
|
||
import { PrimaryAccountChangeHandler } from './handlers/primary-account-change.handler';
|
||
import { resolveDakaoNatsNames } from './dakao.nats-names';
|
||
import { DakaoInboxService } from './dakao-inbox.service';
|
||
import { DakaoJetStreamResourceService } from './dakao-jetstream-resource.service';
|
||
|
||
@Injectable()
|
||
export class DakaoSubscriber implements OnModuleInit {
|
||
private readonly logger = new Logger(DakaoSubscriber.name);
|
||
private readonly natsNames = resolveDakaoNatsNames();
|
||
private botUserId: string | undefined;
|
||
private readonly usageCommands = [
|
||
'!내전 일정',
|
||
'!내전 신청 코드 소환사이름#태그 포지션1,포지션2',
|
||
'!내전 계정등록 소환사이름#태그',
|
||
'!내전 선호포지션등록 포지션1,포지션2',
|
||
'!내전 대표계정변경 소환사이름#태그',
|
||
];
|
||
|
||
constructor(
|
||
private readonly natsService: NatsService,
|
||
private readonly secretService: SecretService,
|
||
private readonly dakaoUserService: DakaoUserService,
|
||
private readonly publisher: DakaoPublisher,
|
||
private readonly inbox: DakaoInboxService,
|
||
private readonly resources: DakaoJetStreamResourceService,
|
||
private readonly accountRegisterHandler: AccountRegisterHandler,
|
||
private readonly matchListHandler: MatchListHandler,
|
||
private readonly matchJoinHandler: MatchJoinHandler,
|
||
private readonly matchCancelHandler: MatchCancelHandler,
|
||
private readonly preferredPositionRegisterHandler: PreferredPositionRegisterHandler,
|
||
private readonly primaryAccountChangeHandler: PrimaryAccountChangeHandler,
|
||
) {}
|
||
|
||
async onModuleInit() {
|
||
this.botUserId = await this.secretService
|
||
.get<string>('DAKAO_BOT_USER_ID')
|
||
.catch(() => undefined);
|
||
|
||
await this.resources.ensure();
|
||
void this.natsService.consumeJetStream<DakaoInboundEvent>(
|
||
{
|
||
stream: this.natsNames.streams.botCommand,
|
||
durable: this.natsNames.consumers.botCommand,
|
||
},
|
||
(event) => this.handleEvent(event),
|
||
);
|
||
this.logger.log(
|
||
`Dakao inbound subscriber ready on stream="${this.natsNames.streams.botCommand}" durable="${this.natsNames.consumers.botCommand}"`,
|
||
);
|
||
}
|
||
|
||
private async handleEvent(event: DakaoInboundEvent): Promise<void> {
|
||
if (!this.validate(event)) return;
|
||
|
||
if (this.botUserId && event.userId === this.botUserId) {
|
||
return;
|
||
}
|
||
|
||
const chatLogLogId = this.serializeDakaoLong(event.origin.chatLog.logId);
|
||
let claimed = false;
|
||
if (chatLogLogId) {
|
||
const claim = await this.inbox.claim({
|
||
consumer: this.natsNames.consumers.botCommand,
|
||
projectId: event.projectId,
|
||
chatLogLogId,
|
||
});
|
||
if (claim.status === 'duplicate') return;
|
||
if (claim.status === 'inflight') {
|
||
throw new Error(
|
||
`Dakao event is already being processed projectId=${event.projectId} logId=${chatLogLogId}`,
|
||
);
|
||
}
|
||
claimed = true;
|
||
}
|
||
|
||
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}`,
|
||
);
|
||
if (claimed) await this.markProcessed(event, chatLogLogId);
|
||
return;
|
||
}
|
||
if (err.code === 'community_not_found') {
|
||
// 우리 쪽이 모르는 projectId. 메시지를 보내봤자 컨텍스트가 없으므로 로그만.
|
||
this.logger.warn(`Unknown dakao projectId: ${event.projectId}`);
|
||
if (claimed) await this.markProcessed(event, chatLogLogId);
|
||
return;
|
||
}
|
||
}
|
||
if (claimed) await this.markFailed(event, chatLogLogId, err);
|
||
throw err;
|
||
}
|
||
|
||
let segments: DakaoSegment[];
|
||
const senderNickname = this.resolveSenderNickname(event);
|
||
const correlationId = chatLogLogId;
|
||
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 'primary-account-change':
|
||
segments = await this.primaryAccountChangeHandler.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,
|
||
});
|
||
if (claimed) await this.markProcessed(event, chatLogLogId);
|
||
} catch (err) {
|
||
if (err instanceof CommandParseError) {
|
||
// not_a_command 는 명령이 아닌 일반 메시지 → 무시.
|
||
if (err.code === 'not_a_command') {
|
||
if (claimed) await this.markProcessed(event, chatLogLogId);
|
||
return;
|
||
}
|
||
await this.publisher.sendMessage({
|
||
chatroomId: event.chatroomId,
|
||
segments: this.parseErrorReply(event, senderNickname, err),
|
||
correlationId,
|
||
});
|
||
if (claimed) await this.markProcessed(event, chatLogLogId);
|
||
return;
|
||
}
|
||
this.logger.error(
|
||
`Unhandled dakao event error: ${(err as Error)?.stack ?? err}`,
|
||
);
|
||
if (claimed) await this.markFailed(event, chatLogLogId, err);
|
||
throw err;
|
||
}
|
||
}
|
||
|
||
private validate(event: unknown): event is DakaoInboundEvent {
|
||
if (!event || typeof event !== 'object') return false;
|
||
const e = event as Partial<DakaoInboundEvent>;
|
||
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 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 async markProcessed(
|
||
event: DakaoInboundEvent,
|
||
chatLogLogId: string,
|
||
): Promise<void> {
|
||
await this.inbox.markProcessed({
|
||
consumer: this.natsNames.consumers.botCommand,
|
||
projectId: event.projectId,
|
||
chatLogLogId,
|
||
});
|
||
}
|
||
|
||
private async markFailed(
|
||
event: DakaoInboundEvent,
|
||
chatLogLogId: string,
|
||
error: unknown,
|
||
): Promise<void> {
|
||
await this.inbox.markFailed({
|
||
consumer: this.natsNames.consumers.botCommand,
|
||
projectId: event.projectId,
|
||
chatLogLogId,
|
||
error,
|
||
});
|
||
}
|
||
|
||
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 ` 알 수 없는 명령어입니다.\n`;
|
||
case 'usage':
|
||
return ` 내전 명령어 사용법\n`;
|
||
case 'invalid_match_id':
|
||
return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`;
|
||
case 'invalid_riot_id':
|
||
return ` 라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).`;
|
||
case 'invalid_position':
|
||
return ` 포지션 입력이 올바르지 않습니다. 쉼표로 구분해서 최소 2개를 중복 없이 입력해주세요. 사용 가능: 탑, 정글, 미드, 원딜, 서폿`;
|
||
default:
|
||
return ` 명령을 처리할 수 없습니다.`;
|
||
}
|
||
})();
|
||
if (err.code === 'unknown_command' || err.code === 'usage') {
|
||
return [...head, { kind: 'text', text }, ...this.usageCommandSegments()];
|
||
}
|
||
return [...head, { kind: 'text', text }];
|
||
}
|
||
|
||
private usageCommandSegments(): DakaoSegment[] {
|
||
return this.usageCommands.flatMap((command, index) => [
|
||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' } as const,
|
||
{
|
||
kind: 'text',
|
||
text:
|
||
index === this.usageCommands.length - 1
|
||
? ` ${command}`
|
||
: ` ${command} \n`,
|
||
} as const,
|
||
]);
|
||
}
|
||
}
|