Files
lolympus-tournament-support/apps/api/src/modules/dakao/handlers/match-join.handler.ts
T

353 lines
11 KiB
TypeScript

import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { MatchService } from '../../match/match.service';
import {
MatchDocument,
Position,
PositionPreference,
RiotAccount,
UserDocument,
} from '../../global/database/schema';
import { DakaoSegment } from '../dakao.types';
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
import { normalizeRiotIdPart } from '../riot-id.util';
import { resolveRecruitingMatchReference } from './match-reference.util';
interface JoinHandlerParams {
communityId: mongoose.Types.ObjectId;
matchAndRiotId: string;
senderUserId: string; // kakaoTalkId
senderNickname: string; // kakaoTalkNickname
positions?: Position[];
}
interface ResolvedJoinTarget {
matchId: mongoose.Types.ObjectId;
gameName?: string;
tagLine?: string;
}
@Injectable()
export class MatchJoinHandler {
constructor(
private readonly matchService: MatchService,
private readonly dakaoUserService: DakaoUserService,
) {}
public async handle(params: JoinHandlerParams): Promise<DakaoSegment[]> {
const joinTarget = await this.resolveJoinTarget(params);
if (typeof joinTarget === 'string') {
return this.errorReply(params, joinTarget);
}
let resolved:
| { user: UserDocument; riotAccount: RiotAccount }
| string;
try {
resolved =
joinTarget.gameName && joinTarget.tagLine
? await this.dakaoUserService.resolveRiotAccount({
communityId: params.communityId,
kakaoTalkId: params.senderUserId,
kakaoTalkNickname: params.senderNickname,
gameName: joinTarget.gameName,
tagLine: joinTarget.tagLine,
})
: await this.resolveRegisteredRiotAccount(params);
} catch (err) {
if (err instanceof DakaoUserError) {
return this.errorReply(params, this.translateUserError(err));
}
throw err;
}
if (typeof resolved === 'string') {
return this.errorReply(params, resolved);
}
const preferredPositions = this.resolvePreferredPositions(
params.positions,
resolved.user.preferredPositions,
);
if (typeof preferredPositions === 'string') {
return this.errorReply(params, preferredPositions);
}
try {
const match = await this.matchService.join({
matchId: joinTarget.matchId,
userId: resolved.user._id,
preferredPositions,
riotPuuid: resolved.riotAccount.puuid,
});
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{
kind: 'text',
text:
` 신청 완료 (${match.participants.length}/${match.maxParticipants})` +
`\n내전: ${match.title}` +
`\n계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}` +
`\n포지션: ${preferredPositions
.map((entry) => entry.position)
.join(', ')}`,
},
];
} catch (err) {
if (err instanceof NotFoundException) {
return this.errorReply(params, '내전을 찾을 수 없습니다.');
}
if (err instanceof BadRequestException) {
return this.errorReply(params, this.translateBadRequest(err.message));
}
throw err;
}
}
private async resolveJoinTarget(
params: JoinHandlerParams,
): Promise<ResolvedJoinTarget | string> {
if (!params.matchAndRiotId.includes('#')) {
return this.resolveJoinTargetWithoutRiotId(params);
}
const riotId = this.parseRiotId(params.matchAndRiotId);
if (typeof riotId === 'string') return riotId;
const objectIdMatch = riotId.gameNameWithOptionalMatchRef.match(
/^([a-f0-9]{24})(?:\s+(.+))?$/i,
);
if (objectIdMatch) {
const gameName = normalizeRiotIdPart(objectIdMatch[2] ?? '');
if (!gameName) {
return '라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).';
}
return {
matchId: new mongoose.Types.ObjectId(objectIdMatch[1]),
gameName,
tagLine: riotId.tagLine,
};
}
const recruitingMatches = await this.matchService.list({
communityId: params.communityId,
status: 'recruiting',
limit: 50,
});
if (recruitingMatches.length === 0) {
return '모집 중인 내전이 없습니다.';
}
const titleTarget = this.resolveTitleTarget(
riotId.gameNameWithOptionalMatchRef,
recruitingMatches,
);
if (titleTarget.kind === 'matched') {
return {
matchId: titleTarget.match._id,
gameName: titleTarget.gameName,
tagLine: riotId.tagLine,
};
}
if (titleTarget.kind === 'ambiguous') {
return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${titleTarget.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
}
if (recruitingMatches.length === 1) {
return {
matchId: recruitingMatches[0]._id,
gameName: riotId.gameNameWithOptionalMatchRef,
tagLine: riotId.tagLine,
};
}
return '모집 중인 내전을 찾을 수 없습니다. !내전 리스트에서 코드 또는 제목을 확인해주세요.';
}
private async resolveJoinTargetWithoutRiotId(
params: JoinHandlerParams,
): Promise<ResolvedJoinTarget | string> {
const reference = params.matchAndRiotId.trim();
if (/^[a-f0-9]{24}$/i.test(reference)) {
return {
matchId: new mongoose.Types.ObjectId(reference),
};
}
const recruitingMatches = await this.matchService.list({
communityId: params.communityId,
status: 'recruiting',
limit: 50,
});
if (recruitingMatches.length === 0) {
return '모집 중인 내전이 없습니다.';
}
if (!reference) {
if (recruitingMatches.length === 1) {
return { matchId: recruitingMatches[0]._id };
}
return '모집 중인 내전이 여러 개입니다. !내전 일정에서 코드 또는 제목을 확인해주세요.';
}
const result = resolveRecruitingMatchReference(
reference,
recruitingMatches,
);
if (result.kind === 'matched') {
return { matchId: result.match._id };
}
if (result.kind === 'ambiguous') {
return `내전 코드 또는 제목이 여러 개와 겹칩니다 (${result.titles.join(', ')}). 더 길게 입력하거나 ID를 사용해주세요.`;
}
return '모집 중인 내전을 찾을 수 없습니다. !내전 일정에서 코드 또는 제목을 확인해주세요.';
}
private parseRiotId(
value: string,
): { gameNameWithOptionalMatchRef: string; tagLine: string } | string {
const hashIndex = value.lastIndexOf('#');
if (hashIndex <= 0 || hashIndex === value.length - 1) {
return '라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).';
}
const gameNameWithOptionalMatchRef = normalizeRiotIdPart(
value.slice(0, hashIndex),
);
const tagLine = normalizeRiotIdPart(value.slice(hashIndex + 1));
if (!gameNameWithOptionalMatchRef || !tagLine) {
return '라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).';
}
return { gameNameWithOptionalMatchRef, tagLine };
}
private resolveTitleTarget(
value: string,
matches: MatchDocument[],
):
| { kind: 'matched'; match: MatchDocument; gameName: string }
| { kind: 'ambiguous'; titles: string[] }
| { kind: 'not-found' } {
let ambiguousTitles: string[] | null = null;
for (const splitAt of splitPositionsFromRight(value)) {
const matchTitlePrefix = value.slice(0, splitAt).trim();
const gameName = normalizeRiotIdPart(value.slice(splitAt + 1));
if (!matchTitlePrefix || !gameName) continue;
const result = resolveRecruitingMatchReference(
matchTitlePrefix,
matches,
);
if (result.kind === 'matched') {
return { kind: 'matched', match: result.match, gameName };
}
if (result.kind === 'ambiguous') {
ambiguousTitles = result.titles;
}
}
return ambiguousTitles
? { kind: 'ambiguous', titles: ambiguousTitles }
: { kind: 'not-found' };
}
private async resolveRegisteredRiotAccount(
params: JoinHandlerParams,
): Promise<{ user: UserDocument; riotAccount: RiotAccount } | string> {
const user = await this.dakaoUserService.findUserByKakaoTalkId({
communityId: params.communityId,
kakaoTalkId: params.senderUserId,
});
if (!user) {
return '먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.';
}
const riotAccount =
user.riotAccounts.find((account) => account.isPrimary) ??
user.riotAccounts[0];
if (!riotAccount) {
return '먼저 !내전 계정등록 <닉네임>#<태그> 로 계정을 등록해주세요.';
}
return { user, riotAccount };
}
private resolvePreferredPositions(
inputPositions: Position[] | undefined,
registeredPositions: PositionPreference[],
): PositionPreference[] | string {
if (inputPositions?.length) {
return inputPositions.map((position, index) => ({
position,
priority: index + 1,
}));
}
const preferredPositions = [...(registeredPositions ?? [])]
.sort((left, right) => left.priority - right.priority)
.filter((entry) => entry.position);
if (preferredPositions.length < 2) {
return '선호포지션을 입력하거나 !내전 선호포지션등록 미드,정글 로 먼저 등록해주세요.';
}
return preferredPositions;
}
private errorReply(
params: JoinHandlerParams,
message: string,
): DakaoSegment[] {
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{ kind: 'text', text: ` ${message}` },
];
}
private translateUserError(err: DakaoUserError): string {
switch (err.code) {
case 'invalid_project_id':
return '커뮤니티 식별자가 올바르지 않습니다.';
case 'community_not_found':
return '연결된 커뮤니티를 찾을 수 없습니다.';
case 'riot_account_not_found':
return `라이엇 계정을 찾을 수 없습니다 (${err.detail ?? ''}).`;
case 'riot_account_already_registered':
return `이미 등록된 라이엇 계정이 있습니다 (${err.detail ?? ''}).`;
case 'riot_account_conflict':
return `이미 다른 사용자가 등록한 라이엇 계정입니다 (${err.detail ?? ''}).`;
case 'riot_account_lookup_failed':
return '라이엇 계정 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.';
}
}
private translateBadRequest(raw: string): string {
if (raw.includes('different communities'))
return '이 내전은 현재 채팅방의 커뮤니티 소속이 아닙니다.';
if (raw.includes('not recruiting')) return '모집 중인 내전이 아닙니다.';
if (raw.includes('full')) return '정원이 가득 찼습니다.';
if (raw.includes('already joined')) return '이미 신청한 내전입니다.';
return raw;
}
}
function splitPositionsFromRight(value: string): number[] {
const positions: number[] = [];
for (let index = value.length - 1; index >= 0; index -= 1) {
if (/\s/.test(value[index])) positions.push(index);
}
return positions;
}