/** * @file * @copyright 2020, Valentin Anger * @license ISC */ import { Client } from "./client.ts"; import IrcError from "./error.ts"; export default class Message { readonly prefix: string | undefined; readonly command: string; readonly parameters: string[]; readonly direct: boolean; readonly sender: | { nickname: string; user: string; host: string; } | undefined; constructor(readonly client: Client, readonly message: string) { let base = 0; if (message[0] == ":") { const prefix_end = message.indexOf(" "); this.prefix = message.substring(1, prefix_end); base = prefix_end + 1; } const trailing_colon = message.indexOf(" :", base); if (trailing_colon != -1) { // There is a trailing parameter const trailing = message.substring( trailing_colon + 2, message.length - 2, ); this.parameters = message.substring(base, trailing_colon).split(" "); this.parameters.push(trailing); } else { this.parameters = message.substring(base, message.length - 2).split(" "); } const command = this.parameters.shift(); if (command == undefined) { throw new IrcError("Malformed message"); } this.command = command; // Basic message parsing done if (this.prefix != undefined) { const match = this.prefix.match(/([^@!]+)(?:(?:!([^@]+))?@(.*))?/); if (match != null) { this.sender = { nickname: match[1], user: match[2], host: match[3], }; } } this.direct = this.parameters[0] == this.client.nickname; } channel(): string | undefined { return this.direct ? undefined : this.parameters[0]; } async replyPrivmsg( message: string, direct_reply: boolean = false, ): Promise { if (this.direct || direct_reply) { if (this.sender == undefined) { throw new IrcError("Cannot reply to unknown sender"); } await this.client.sendPrivmsg(this.sender.nickname, message); } else { await this.client.sendPrivmsg(this.parameters[0], message); } } async replyNotice( message: string, direct_reply: boolean = false, ): Promise { if (this.direct || direct_reply) { if (this.sender == undefined) { throw new IrcError("Cannot reply to unknown sender"); } await this.client.sendNotice(this.sender.nickname, message); } else { await this.client.sendNotice(this.parameters[0], message); } } toString(): string { return this.message; } }