Files
Breadbot/src/utilties/discord/voice.ts

95 lines
2.9 KiB
TypeScript

import { VoiceBasedChannel } from "discord.js";
import { IsNull, Repository } from "typeorm";
import { DBCall } from "../storage/entities/DBCall";
import { DBCallUsers } from "../storage/entities/DBCallUsers";
import { DBUser } from "../storage/entities/DBUser";
export async function breadbotInCall(db: Repository<DBCall>, channel: VoiceBasedChannel) : Promise<boolean> {
return (await db.findOne({
where: {
channel: {channel_snowflake: channel.id},
call_end_time: IsNull()
}
})) != null
}
export async function getExistingCallID(db: Repository<DBCall>, channel: VoiceBasedChannel) : Promise<number | undefined> {
return (await db.findOne({
where: {
channel: {channel_snowflake: channel.id},
call_end_time: IsNull()
}
}))?.call_id
}
export async function returnOrCreateNewCallID(db: Repository<DBCall>, channel: VoiceBasedChannel) : Promise<number> {
const oldCallID = await getExistingCallID(db, channel)
if(oldCallID !== undefined) {
return oldCallID
} else {
const newCall : DBCall = await db.create({
channel: { channel_snowflake: channel.id },
call_start_time: new Date()
})
return (await db.save(newCall)).call_id;
}
}
export async function setCallEndTime(db: Repository<DBCall>, channel: VoiceBasedChannel) : Promise<DBCall | null> {
const call: DBCall | null = await db.findOne({
"where": {
channel: {
channel_snowflake: channel.id
},
call_end_time: IsNull()
}
})
if (call == null) {
return null
}
call.call_end_time = new Date()
return await db.save(call)
}
export async function numberOfUsersInCall(db: Repository<DBCallUsers>, call: DBCall | number) : Promise<number> {
const activeCallUsers : DBCallUsers[] = await db.find({
"where": {
call: (call instanceof DBCall) ? call : { call_id: call },
call_leave_time: IsNull()
}
})
return activeCallUsers.length
}
export async function registerUserInCall(db: Repository<DBCallUsers>, call: DBCall | number, user: DBUser) : Promise<DBCallUsers> {
return await db.save({
call: (call instanceof DBCall) ? call : {call_id: call},
user: user,
call_join_time: new Date()
})
}
export async function deregisterUserInCall(db: Repository<DBCallUsers>, call: DBCall | number, user: DBUser | string) : Promise<DBCallUsers | null> {
const callUser : DBCallUsers | null = await db.findOne({
where: {
call: (call instanceof DBCall) ? call : {call_id: call},
user: (user instanceof DBUser) ? user : {user_snowflake: user},
call_leave_time: IsNull()
}
})
if(callUser == null) {
return null
}
callUser.call_leave_time = new Date()
return await db.save(callUser)
}