service-irc/irc/parser.ts

78 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-11-29 13:16:00 +00:00
// :nickname!username@hostname command arg ume nts :trailing
// or
// :hostname command arg ume nts :trailing
export interface IIRCUser {
nickname: string;
username: string;
hostname: string;
}
export interface IIRCLine {
user: IIRCUser;
command: string;
arguments?: string[];
trailing?: string;
raw: string;
}
function parseERROR(line: string[]): IIRCLine {
2021-06-15 19:55:04 +00:00
const final: IIRCLine = {
2020-11-29 13:16:00 +00:00
user: { nickname: '', username: '', hostname: '' },
command: 'ERROR',
trailing: '',
raw: line.join(' ')
};
let pass1 = line.slice(1).join(' ');
if (pass1.indexOf(':') === 0) {
pass1 = pass1.substring(1);
}
final.trailing = pass1;
return final;
}
export function parse(rawline: string): IIRCLine {
2021-06-15 19:55:04 +00:00
const final: IIRCLine = {
2020-11-29 13:16:00 +00:00
user: {
nickname: '',
username: '',
hostname: ''
},
command: '',
arguments: [],
trailing: '',
raw: rawline
};
2021-06-15 19:55:04 +00:00
const pass1 = (rawline.indexOf(':') === 0 ? rawline.substring(1).split(' ') : rawline.split(' '));
2020-11-29 13:16:00 +00:00
if (pass1[0] === 'ERROR') {
return parseERROR(pass1);
}
if (pass1[0].indexOf('!') !== -1) {
2021-06-15 19:55:04 +00:00
const nickuser = pass1[0].split('!');
2020-11-29 13:16:00 +00:00
final.user.nickname = nickuser[0];
2021-06-15 19:55:04 +00:00
const userhost = nickuser[1].split('@');
2020-11-29 13:16:00 +00:00
final.user.username = userhost[0];
final.user.hostname = userhost[1];
} else {
final.user.hostname = pass1[0];
}
final.command = pass1[1];
2021-06-15 19:55:04 +00:00
const pass2 = pass1.slice(2).join(' ');
2020-11-29 13:16:00 +00:00
if (pass2.indexOf(':') !== -1) {
final.arguments = pass2.substring(0, pass2.indexOf(' :')).split(' ');
final.trailing = pass2.substring(pass2.indexOf(':') + 1);
} else {
final.arguments = pass2.split(' ');
}
2021-06-15 19:55:04 +00:00
return final;
2020-11-29 13:16:00 +00:00
}