Files
node-red-contrib-teamspeak/src/nodes/ts3-config/ts3-config.ts
2021-04-22 19:26:45 +02:00

73 lines
1.6 KiB
TypeScript

import { NodeDef, NodeInitializer, Node } from "node-red";
import { Ts3ConfigConfig, Ts3ConfigNode } from "./types";
import { TeamSpeak, QueryProtocol } from "ts3-nodejs-library"
const nodeInit: NodeInitializer = (RED): void => {
function Ts3Config(
this: Ts3ConfigNode,
config: Ts3ConfigConfig
): void {
RED.nodes.createNode(this, config)
const host = config.host
const nickname = config.nickname
let client: TeamSpeak | null = null
let connectPromise: Promise<TeamSpeak> | null = null
let shouldDissconect = false
this.getConnection = async (): Promise<TeamSpeak>=>{
if (client){
return client
}else if (connectPromise){
return connectPromise
}else{
try{
connectPromise = TeamSpeak.connect({
host: host,
protocol: QueryProtocol.RAW,
queryport: 10011,
serverport: 9987,
username: this.credentials.username,
password: this.credentials.password,
nickname: nickname
})
client = await connectPromise
if (client == null){
throw new Error("Failed to connect to Teamspeak")
}
client.on("close", async () => {
if (!shouldDissconect){
if (client != null){
await client.reconnect(-1, 1000)
}else{
// TODO: Emit error
}
}
})
return client
}catch(err){
// TODO: handle error
throw err
}
}
}
this.on("close",async ()=>{
shouldDissconect = true
await client?.quit()
})
}
RED.nodes.registerType("ts3-config", Ts3Config,{
credentials: {
username: {type: "text"},
password: {type: "password"}
}
});
};
export = nodeInit;