peertube-plugin-livechat/bots/lib/bot/component.ts

82 lines
2.0 KiB
TypeScript
Raw Normal View History

2021-12-07 17:57:08 +00:00
/* eslint-disable no-void */
import { logger } from '../logger'
2021-12-08 11:29:21 +00:00
import type { XMPPStanza } from './types'
import { component, xml, Component } from '@xmpp/component'
import type { JID } from '@xmpp/jid'
2021-12-07 17:57:08 +00:00
interface ComponentConnectionConfig {
service: string
domain: string
password: string
}
abstract class ComponentBot {
2021-12-08 11:29:21 +00:00
protected xmpp?: Component
protected address?: JID
protected xml = xml
2021-12-07 17:57:08 +00:00
constructor (
public readonly botName: string,
protected readonly connectionConfig: ComponentConnectionConfig
) {}
public async connect (): Promise<void> {
this.xmpp = component({
service: this.connectionConfig.service,
domain: this.connectionConfig.domain,
password: this.connectionConfig.password
2021-12-08 11:29:21 +00:00
})
2021-12-07 17:57:08 +00:00
this.xmpp.on('error', (err: any) => {
logger.error(err)
})
this.xmpp.on('offline', () => {
logger.info(`${this.botName} is now offline.`)
})
this.xmpp.on('stanza', (stanza: XMPPStanza) => {
logger.debug('stanza received' + (stanza?.toString ? ': ' + stanza.toString() : ''))
if (stanza.is('message')) {
void this.onMessage(stanza)
}
if (stanza.is('presence')) {
void this.onPresence(stanza)
}
if (stanza.is('iq')) {
void this.onIq(stanza)
}
})
2021-12-08 11:29:21 +00:00
this.xmpp.on('online', (address) => {
2021-12-07 17:57:08 +00:00
logger.debug('Online with address' + address.toString())
this.address = address
void this.onOnline()
})
2021-12-08 11:29:21 +00:00
await this.xmpp.start()
2021-12-07 17:57:08 +00:00
}
public async stop (): Promise<any> {
const p = new Promise((resolve) => {
this.xmpp?.on('offline', () => {
logger.info(`Stoppping process: ${this.botName} is now offline.`)
resolve(true)
})
})
await this.xmpp?.stop()
await p
}
protected async onMessage (_stanza: XMPPStanza): Promise<void> {}
protected async onIq (_stanza: XMPPStanza): Promise<void> {}
protected async onPresence (_stanza: XMPPStanza): Promise<void> {}
protected async onOnline (): Promise<void> {}
}
export {
ComponentConnectionConfig,
ComponentBot
}