139 lines
4.7 KiB
TypeScript
139 lines
4.7 KiB
TypeScript
import { Inject, Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
|
import { randomUUID } from 'crypto';
|
|
import { SecretService } from '../global/secret/secret.service';
|
|
import {
|
|
DakaoCommandEnvelope,
|
|
DakaoResultSubjects,
|
|
DakaoSegment,
|
|
DakaoSendMessagePayload,
|
|
} from './dakao.types';
|
|
import type { DakaoOptions } from './dakao.options';
|
|
import { DAKAO_OPTIONS } from './dakao.options';
|
|
import { resolveDakaoNatsNames } from './dakao.nats-names';
|
|
import { DakaoOutboxService } from './dakao-outbox.service';
|
|
|
|
const EVENT_SOURCE_DEFAULT = 'lolympus';
|
|
|
|
@Injectable()
|
|
export class DakaoPublisher implements OnModuleInit {
|
|
private readonly logger = new Logger(DakaoPublisher.name);
|
|
private readonly names = resolveDakaoNatsNames();
|
|
private sendMessageSubject = this.names.subjects.chatSendMessage;
|
|
private resultSubjects: DakaoResultSubjects = {
|
|
succeeded: this.names.subjects.chatSendMessageSucceeded,
|
|
failed: this.names.subjects.chatSendMessageFailed,
|
|
};
|
|
private eventSource = EVENT_SOURCE_DEFAULT;
|
|
|
|
constructor(
|
|
private readonly secretService: SecretService,
|
|
private readonly outboxService: DakaoOutboxService,
|
|
@Inject(DAKAO_OPTIONS) private readonly options: DakaoOptions,
|
|
) {}
|
|
|
|
async onModuleInit() {
|
|
const sendOverride = await this.secretService
|
|
.get<string>('DAKAO_CHAT_SEND_MESSAGE_SUBJECT')
|
|
.catch(() => undefined);
|
|
const sourceOverride = await this.secretService
|
|
.get<string>('DAKAO_EVENT_SOURCE')
|
|
.catch(() => undefined);
|
|
|
|
this.sendMessageSubject =
|
|
sendOverride || resolveDakaoNatsNames().subjects.chatSendMessage;
|
|
this.resultSubjects = {
|
|
succeeded: this.names.subjects.chatSendMessageSucceeded,
|
|
failed: this.names.subjects.chatSendMessageFailed,
|
|
};
|
|
this.eventSource = sourceOverride || EVENT_SOURCE_DEFAULT;
|
|
|
|
this.logger.log(
|
|
`Dakao send-message publisher ready on subject="${this.sendMessageSubject}" source="${this.eventSource}" instanceId="${this.options.instanceId}"`,
|
|
);
|
|
}
|
|
|
|
public async sendMessage(params: {
|
|
chatroomId: string;
|
|
segments: DakaoSegment[];
|
|
correlationId?: string;
|
|
eventId?: string;
|
|
}): Promise<void> {
|
|
const eventId =
|
|
params.eventId ??
|
|
(params.correlationId
|
|
? `${this.eventSource}:chat.send-message:${params.correlationId}`
|
|
: `${this.eventSource}:chat.send-message:${randomUUID()}`);
|
|
const payload: DakaoSendMessagePayload = {
|
|
chatroomId: params.chatroomId,
|
|
segments: this.normalizeSegments(params.segments),
|
|
};
|
|
const envelope: DakaoCommandEnvelope<DakaoSendMessagePayload> = {
|
|
schema: 'dakao.command.v1',
|
|
eventId,
|
|
type: 'chat.send-message',
|
|
eventSource: this.eventSource,
|
|
correlationId: params.correlationId,
|
|
resultSubjects: this.resultSubjects,
|
|
payload,
|
|
};
|
|
await this.outboxService.enqueueAndPublish({
|
|
subject: this.sendMessageSubject,
|
|
eventId,
|
|
envelope,
|
|
});
|
|
}
|
|
|
|
private normalizeSegments(segments: DakaoSegment[]): DakaoSegment[] {
|
|
const normalized: DakaoSegment[] = [];
|
|
|
|
for (const segment of segments) {
|
|
if (segment.kind === 'text') {
|
|
if (segment.text.length > 0) normalized.push(segment);
|
|
continue;
|
|
}
|
|
|
|
if (segment.kind === 'mention') {
|
|
const userId = segment.userId.trim();
|
|
const displayText = segment.displayText.trim();
|
|
|
|
if (this.isPositiveIntegerString(userId) && displayText.length > 0) {
|
|
normalized.push({ kind: 'mention', userId, displayText });
|
|
continue;
|
|
}
|
|
|
|
const fallbackText = this.renderMentionFallback(displayText, userId);
|
|
this.logger.warn(
|
|
`Dakao mention downgraded to text because userId/displayText is invalid: userId="${userId || '-'}" displayText="${displayText || '-'}"`,
|
|
);
|
|
normalized.push({ kind: 'text', text: fallbackText });
|
|
continue;
|
|
}
|
|
|
|
const id = segment.id.trim();
|
|
const altText = segment.altText.trim();
|
|
if (id.length > 0 && altText.length > 0 && !/[()@]/.test(altText)) {
|
|
normalized.push({ kind: 'emoticon', id, altText });
|
|
continue;
|
|
}
|
|
|
|
this.logger.warn(
|
|
`Dakao emoticon downgraded to text because id/altText is invalid: id="${id || '-'}" altText="${altText || '-'}"`,
|
|
);
|
|
normalized.push({ kind: 'text', text: `(${altText || '이모티콘'})` });
|
|
}
|
|
|
|
return normalized.length > 0
|
|
? normalized
|
|
: [{ kind: 'text', text: '명령 처리 결과를 보낼 수 없습니다.' }];
|
|
}
|
|
|
|
private isPositiveIntegerString(value: string): boolean {
|
|
return /^[1-9]\d*$/.test(value);
|
|
}
|
|
|
|
private renderMentionFallback(displayText: string, userId: string): string {
|
|
const label = displayText || userId || '사용자';
|
|
return label.startsWith('@') ? label : `@${label}`;
|
|
}
|
|
}
|