38430-vm/backend/src/db/api/bot_instances.js
2026-02-14 16:49:50 +00:00

636 lines
16 KiB
JavaScript

const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Bot_instancesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const bot_instances = await db.bot_instances.create(
{
id: data.id || undefined,
instance_name: data.instance_name
||
null
,
bot_client_key: data.bot_client_key
||
null
,
status: data.status
||
null
,
auto_reconnect_enabled: data.auto_reconnect_enabled
||
false
,
reconnect_backoff_seconds: data.reconnect_backoff_seconds
||
null
,
last_connected_at: data.last_connected_at
||
null
,
last_disconnect_at: data.last_disconnect_at
||
null
,
last_error_message: data.last_error_message
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await bot_instances.setDiscord_server( data.discord_server || null, {
transaction,
});
await bot_instances.setCurrent_voice_channel( data.current_voice_channel || null, {
transaction,
});
return bot_instances;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const bot_instancesData = data.map((item, index) => ({
id: item.id || undefined,
instance_name: item.instance_name
||
null
,
bot_client_key: item.bot_client_key
||
null
,
status: item.status
||
null
,
auto_reconnect_enabled: item.auto_reconnect_enabled
||
false
,
reconnect_backoff_seconds: item.reconnect_backoff_seconds
||
null
,
last_connected_at: item.last_connected_at
||
null
,
last_disconnect_at: item.last_disconnect_at
||
null
,
last_error_message: item.last_error_message
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const bot_instances = await db.bot_instances.bulkCreate(bot_instancesData, { transaction });
// For each item created, replace relation files
return bot_instances;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const bot_instances = await db.bot_instances.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.instance_name !== undefined) updatePayload.instance_name = data.instance_name;
if (data.bot_client_key !== undefined) updatePayload.bot_client_key = data.bot_client_key;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.auto_reconnect_enabled !== undefined) updatePayload.auto_reconnect_enabled = data.auto_reconnect_enabled;
if (data.reconnect_backoff_seconds !== undefined) updatePayload.reconnect_backoff_seconds = data.reconnect_backoff_seconds;
if (data.last_connected_at !== undefined) updatePayload.last_connected_at = data.last_connected_at;
if (data.last_disconnect_at !== undefined) updatePayload.last_disconnect_at = data.last_disconnect_at;
if (data.last_error_message !== undefined) updatePayload.last_error_message = data.last_error_message;
updatePayload.updatedById = currentUser.id;
await bot_instances.update(updatePayload, {transaction});
if (data.discord_server !== undefined) {
await bot_instances.setDiscord_server(
data.discord_server,
{ transaction }
);
}
if (data.current_voice_channel !== undefined) {
await bot_instances.setCurrent_voice_channel(
data.current_voice_channel,
{ transaction }
);
}
return bot_instances;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const bot_instances = await db.bot_instances.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of bot_instances) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of bot_instances) {
await record.destroy({transaction});
}
});
return bot_instances;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const bot_instances = await db.bot_instances.findByPk(id, options);
await bot_instances.update({
deletedBy: currentUser.id
}, {
transaction,
});
await bot_instances.destroy({
transaction
});
return bot_instances;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const bot_instances = await db.bot_instances.findOne(
{ where },
{ transaction },
);
if (!bot_instances) {
return bot_instances;
}
const output = bot_instances.get({plain: true});
output.voice_sessions_bot_instance = await bot_instances.getVoice_sessions_bot_instance({
transaction
});
output.discord_server = await bot_instances.getDiscord_server({
transaction
});
output.current_voice_channel = await bot_instances.getCurrent_voice_channel({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userDiscord_servers = (user && user.discord_servers?.id) || null;
if (userDiscord_servers) {
if (options?.currentUser?.discord_serversId) {
where.discord_serversId = options.currentUser.discord_serversId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.discord_servers,
as: 'discord_server',
},
{
model: db.voice_channels,
as: 'current_voice_channel',
where: filter.current_voice_channel ? {
[Op.or]: [
{ id: { [Op.in]: filter.current_voice_channel.split('|').map(term => Utils.uuid(term)) } },
{
channel_name: {
[Op.or]: filter.current_voice_channel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.instance_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'bot_instances',
'instance_name',
filter.instance_name,
),
};
}
if (filter.bot_client_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'bot_instances',
'bot_client_key',
filter.bot_client_key,
),
};
}
if (filter.last_error_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'bot_instances',
'last_error_message',
filter.last_error_message,
),
};
}
if (filter.reconnect_backoff_secondsRange) {
const [start, end] = filter.reconnect_backoff_secondsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reconnect_backoff_seconds: {
...where.reconnect_backoff_seconds,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reconnect_backoff_seconds: {
...where.reconnect_backoff_seconds,
[Op.lte]: end,
},
};
}
}
if (filter.last_connected_atRange) {
const [start, end] = filter.last_connected_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_connected_at: {
...where.last_connected_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_connected_at: {
...where.last_connected_at,
[Op.lte]: end,
},
};
}
}
if (filter.last_disconnect_atRange) {
const [start, end] = filter.last_disconnect_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_disconnect_at: {
...where.last_disconnect_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_disconnect_at: {
...where.last_disconnect_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.auto_reconnect_enabled) {
where = {
...where,
auto_reconnect_enabled: filter.auto_reconnect_enabled,
};
}
if (filter.discord_server) {
const listItems = filter.discord_server.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
discord_serverId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.discord_serversId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.bot_instances.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'bot_instances',
'instance_name',
query,
),
],
};
}
const records = await db.bot_instances.findAll({
attributes: [ 'id', 'instance_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['instance_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.instance_name,
}));
}
};