refactor(all): uniformisation
This commit is contained in:
89 files changed
+10215
-10215
No files matched your search
+63
-63
@@ -1,63 +1,63 @@
|
||||
import { mkdirSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { env } from '../config/env.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
|
||||
const log = createLogger('database');
|
||||
const migrationsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'migrations');
|
||||
|
||||
let db;
|
||||
|
||||
function runMigrations(database) {
|
||||
database.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
name TEXT PRIMARY KEY,
|
||||
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
)`);
|
||||
|
||||
const applied = new Set(
|
||||
database
|
||||
.prepare('SELECT name FROM schema_migrations')
|
||||
.all()
|
||||
.map((row) => row.name),
|
||||
);
|
||||
const pending = readdirSync(migrationsDir)
|
||||
.filter((file) => file.endsWith('.sql') && !applied.has(file))
|
||||
.sort();
|
||||
|
||||
for (const file of pending) {
|
||||
database.exec('BEGIN');
|
||||
try {
|
||||
database.exec(readFileSync(path.join(migrationsDir, file), 'utf8'));
|
||||
database.prepare('INSERT INTO schema_migrations (name) VALUES (?)').run(file);
|
||||
database.exec('COMMIT');
|
||||
log.info(`Applied migration ${file}`);
|
||||
} catch (error) {
|
||||
database.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function initDatabase(filePath = env.database.path) {
|
||||
if (db) return db;
|
||||
|
||||
if (filePath !== ':memory:') {
|
||||
mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
}
|
||||
db = new DatabaseSync(filePath);
|
||||
db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;');
|
||||
runMigrations(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
export function getDatabase() {
|
||||
if (!db) throw new Error('Database not initialized. Call initDatabase() first.');
|
||||
return db;
|
||||
}
|
||||
|
||||
export function closeDatabase() {
|
||||
db?.close();
|
||||
db = undefined;
|
||||
}
|
||||
import { mkdirSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { env } from '../config/env.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
|
||||
const log = createLogger('database');
|
||||
const migrationsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'migrations');
|
||||
|
||||
let db;
|
||||
|
||||
function runMigrations(database) {
|
||||
database.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
name TEXT PRIMARY KEY,
|
||||
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
)`);
|
||||
|
||||
const applied = new Set(
|
||||
database
|
||||
.prepare('SELECT name FROM schema_migrations')
|
||||
.all()
|
||||
.map((row) => row.name),
|
||||
);
|
||||
const pending = readdirSync(migrationsDir)
|
||||
.filter((file) => file.endsWith('.sql') && !applied.has(file))
|
||||
.sort();
|
||||
|
||||
for (const file of pending) {
|
||||
database.exec('BEGIN');
|
||||
try {
|
||||
database.exec(readFileSync(path.join(migrationsDir, file), 'utf8'));
|
||||
database.prepare('INSERT INTO schema_migrations (name) VALUES (?)').run(file);
|
||||
database.exec('COMMIT');
|
||||
log.info(`Applied migration ${file}`);
|
||||
} catch (error) {
|
||||
database.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function initDatabase(filePath = env.database.path) {
|
||||
if (db) return db;
|
||||
|
||||
if (filePath !== ':memory:') {
|
||||
mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
}
|
||||
db = new DatabaseSync(filePath);
|
||||
db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;');
|
||||
runMigrations(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
export function getDatabase() {
|
||||
if (!db) throw new Error('Database not initialized. Call initDatabase() first.');
|
||||
return db;
|
||||
}
|
||||
|
||||
export function closeDatabase() {
|
||||
db?.close();
|
||||
db = undefined;
|
||||
}
|
||||
@@ -1,97 +1,97 @@
|
||||
-- Server settings, isolated per guild (M3-T06)
|
||||
CREATE TABLE IF NOT EXISTS guild_settings (
|
||||
guild_id TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT,
|
||||
updated_by TEXT,
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (guild_id, key)
|
||||
);
|
||||
|
||||
-- Notification type -> channel mapping (M9-T01)
|
||||
CREATE TABLE IF NOT EXISTS notification_channels (
|
||||
guild_id TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
channel_id TEXT NOT NULL,
|
||||
detail_level TEXT NOT NULL DEFAULT 'normal',
|
||||
PRIMARY KEY (guild_id, type)
|
||||
);
|
||||
|
||||
-- Ticket categories (M6-T01) and tickets (M6)
|
||||
CREATE TABLE IF NOT EXISTS ticket_categories (
|
||||
guild_id TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
label TEXT NOT NULL,
|
||||
description TEXT,
|
||||
scope TEXT NOT NULL,
|
||||
PRIMARY KEY (guild_id, id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tickets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT NOT NULL,
|
||||
channel_id TEXT UNIQUE,
|
||||
category_id TEXT NOT NULL,
|
||||
author_id TEXT NOT NULL,
|
||||
claimed_by TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
closed_at TEXT,
|
||||
closed_by TEXT
|
||||
);
|
||||
-- Prevents duplicate open tickets per author and category (M6-T08)
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_tickets_open_unique
|
||||
ON tickets (guild_id, author_id, category_id) WHERE status = 'open';
|
||||
|
||||
-- Moderation actions (M8)
|
||||
CREATE TABLE IF NOT EXISTS moderation_actions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT NOT NULL,
|
||||
action TEXT NOT NULL CHECK (action IN ('warn', 'mute', 'kick', 'ban', 'clear', 'role')),
|
||||
target_id TEXT,
|
||||
moderator_id TEXT NOT NULL,
|
||||
reason TEXT,
|
||||
duration_ms INTEGER,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_moderation_target ON moderation_actions (guild_id, target_id);
|
||||
|
||||
-- Polls (M10)
|
||||
CREATE TABLE IF NOT EXISTS polls (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT NOT NULL,
|
||||
channel_id TEXT NOT NULL,
|
||||
message_id TEXT UNIQUE,
|
||||
creator_id TEXT NOT NULL,
|
||||
question TEXT NOT NULL,
|
||||
choices TEXT NOT NULL,
|
||||
ends_at TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS poll_votes (
|
||||
poll_id INTEGER NOT NULL REFERENCES polls (id) ON DELETE CASCADE,
|
||||
user_id TEXT NOT NULL,
|
||||
choice_index INTEGER NOT NULL,
|
||||
voted_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (poll_id, user_id)
|
||||
);
|
||||
|
||||
-- Functional event log (M11-T05)
|
||||
CREATE TABLE IF NOT EXISTS event_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT,
|
||||
type TEXT NOT NULL,
|
||||
actor_id TEXT,
|
||||
payload TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_event_logs_created ON event_logs (created_at);
|
||||
|
||||
-- Delivered Gitea webhook deliveries, to avoid duplicate notifications (M9-T08)
|
||||
CREATE TABLE IF NOT EXISTS webhook_deliveries (
|
||||
delivery_id TEXT PRIMARY KEY,
|
||||
event TEXT NOT NULL,
|
||||
received_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
-- Server settings, isolated per guild (M3-T06)
|
||||
CREATE TABLE IF NOT EXISTS guild_settings (
|
||||
guild_id TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT,
|
||||
updated_by TEXT,
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (guild_id, key)
|
||||
);
|
||||
|
||||
-- Notification type -> channel mapping (M9-T01)
|
||||
CREATE TABLE IF NOT EXISTS notification_channels (
|
||||
guild_id TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
channel_id TEXT NOT NULL,
|
||||
detail_level TEXT NOT NULL DEFAULT 'normal',
|
||||
PRIMARY KEY (guild_id, type)
|
||||
);
|
||||
|
||||
-- Ticket categories (M6-T01) and tickets (M6)
|
||||
CREATE TABLE IF NOT EXISTS ticket_categories (
|
||||
guild_id TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
label TEXT NOT NULL,
|
||||
description TEXT,
|
||||
scope TEXT NOT NULL,
|
||||
PRIMARY KEY (guild_id, id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tickets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT NOT NULL,
|
||||
channel_id TEXT UNIQUE,
|
||||
category_id TEXT NOT NULL,
|
||||
author_id TEXT NOT NULL,
|
||||
claimed_by TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
closed_at TEXT,
|
||||
closed_by TEXT
|
||||
);
|
||||
-- Prevents duplicate open tickets per author and category (M6-T08)
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_tickets_open_unique
|
||||
ON tickets (guild_id, author_id, category_id) WHERE status = 'open';
|
||||
|
||||
-- Moderation actions (M8)
|
||||
CREATE TABLE IF NOT EXISTS moderation_actions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT NOT NULL,
|
||||
action TEXT NOT NULL CHECK (action IN ('warn', 'mute', 'kick', 'ban', 'clear', 'role')),
|
||||
target_id TEXT,
|
||||
moderator_id TEXT NOT NULL,
|
||||
reason TEXT,
|
||||
duration_ms INTEGER,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_moderation_target ON moderation_actions (guild_id, target_id);
|
||||
|
||||
-- Polls (M10)
|
||||
CREATE TABLE IF NOT EXISTS polls (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT NOT NULL,
|
||||
channel_id TEXT NOT NULL,
|
||||
message_id TEXT UNIQUE,
|
||||
creator_id TEXT NOT NULL,
|
||||
question TEXT NOT NULL,
|
||||
choices TEXT NOT NULL,
|
||||
ends_at TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS poll_votes (
|
||||
poll_id INTEGER NOT NULL REFERENCES polls (id) ON DELETE CASCADE,
|
||||
user_id TEXT NOT NULL,
|
||||
choice_index INTEGER NOT NULL,
|
||||
voted_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (poll_id, user_id)
|
||||
);
|
||||
|
||||
-- Functional event log (M11-T05)
|
||||
CREATE TABLE IF NOT EXISTS event_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT,
|
||||
type TEXT NOT NULL,
|
||||
actor_id TEXT,
|
||||
payload TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_event_logs_created ON event_logs (created_at);
|
||||
|
||||
-- Delivered Gitea webhook deliveries, to avoid duplicate notifications (M9-T08)
|
||||
CREATE TABLE IF NOT EXISTS webhook_deliveries (
|
||||
delivery_id TEXT PRIMARY KEY,
|
||||
event TEXT NOT NULL,
|
||||
received_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
@@ -1,14 +1,14 @@
|
||||
-- Several "join to create" triggers per guild, each with its own home category (M14)
|
||||
CREATE TABLE IF NOT EXISTS voice_triggers (
|
||||
trigger_id TEXT PRIMARY KEY,
|
||||
guild_id TEXT NOT NULL,
|
||||
label TEXT,
|
||||
category_id TEXT,
|
||||
template TEXT,
|
||||
user_limit INTEGER NOT NULL DEFAULT 0,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_voice_triggers_guild ON voice_triggers (guild_id);
|
||||
-- Several "join to create" triggers per guild, each with its own home category (M14)
|
||||
CREATE TABLE IF NOT EXISTS voice_triggers (
|
||||
trigger_id TEXT PRIMARY KEY,
|
||||
guild_id TEXT NOT NULL,
|
||||
label TEXT,
|
||||
category_id TEXT,
|
||||
template TEXT,
|
||||
user_limit INTEGER NOT NULL DEFAULT 0,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_voice_triggers_guild ON voice_triggers (guild_id);
|
||||
@@ -1,42 +1,42 @@
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
/** Adds a status and returns the stored row, so the command can show its id. */
|
||||
export function addBotStatus({ text, type = 'watching', url = null, createdBy = null }) {
|
||||
const result = getDatabase()
|
||||
.prepare('INSERT INTO bot_statuses (text, type, url, created_by) VALUES (?, ?, ?, ?)')
|
||||
.run(text, type, url, createdBy);
|
||||
return getBotStatus(Number(result.lastInsertRowid));
|
||||
}
|
||||
|
||||
export function getBotStatus(id) {
|
||||
return getDatabase().prepare('SELECT * FROM bot_statuses WHERE id = ?').get(id) ?? null;
|
||||
}
|
||||
|
||||
/** Every status, disabled ones included, in the order they were added. */
|
||||
export function listBotStatuses() {
|
||||
return getDatabase().prepare('SELECT * FROM bot_statuses ORDER BY id ASC').all();
|
||||
}
|
||||
|
||||
/** The statuses the rotation is allowed to show. */
|
||||
export function listEnabledBotStatuses() {
|
||||
return getDatabase().prepare('SELECT * FROM bot_statuses WHERE enabled = 1 ORDER BY id ASC').all();
|
||||
}
|
||||
|
||||
export function setBotStatusEnabled(id, enabled) {
|
||||
return getDatabase()
|
||||
.prepare('UPDATE bot_statuses SET enabled = ? WHERE id = ?')
|
||||
.run(enabled ? 1 : 0, id).changes;
|
||||
}
|
||||
|
||||
export function removeBotStatus(id) {
|
||||
return getDatabase().prepare('DELETE FROM bot_statuses WHERE id = ?').run(id).changes;
|
||||
}
|
||||
|
||||
export function clearBotStatuses() {
|
||||
return getDatabase().prepare('DELETE FROM bot_statuses').run().changes;
|
||||
}
|
||||
|
||||
export function countBotStatuses() {
|
||||
const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM bot_statuses').get();
|
||||
return row.count;
|
||||
}
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
/** Adds a status and returns the stored row, so the command can show its id. */
|
||||
export function addBotStatus({ text, type = 'watching', url = null, createdBy = null }) {
|
||||
const result = getDatabase()
|
||||
.prepare('INSERT INTO bot_statuses (text, type, url, created_by) VALUES (?, ?, ?, ?)')
|
||||
.run(text, type, url, createdBy);
|
||||
return getBotStatus(Number(result.lastInsertRowid));
|
||||
}
|
||||
|
||||
export function getBotStatus(id) {
|
||||
return getDatabase().prepare('SELECT * FROM bot_statuses WHERE id = ?').get(id) ?? null;
|
||||
}
|
||||
|
||||
/** Every status, disabled ones included, in the order they were added. */
|
||||
export function listBotStatuses() {
|
||||
return getDatabase().prepare('SELECT * FROM bot_statuses ORDER BY id ASC').all();
|
||||
}
|
||||
|
||||
/** The statuses the rotation is allowed to show. */
|
||||
export function listEnabledBotStatuses() {
|
||||
return getDatabase().prepare('SELECT * FROM bot_statuses WHERE enabled = 1 ORDER BY id ASC').all();
|
||||
}
|
||||
|
||||
export function setBotStatusEnabled(id, enabled) {
|
||||
return getDatabase()
|
||||
.prepare('UPDATE bot_statuses SET enabled = ? WHERE id = ?')
|
||||
.run(enabled ? 1 : 0, id).changes;
|
||||
}
|
||||
|
||||
export function removeBotStatus(id) {
|
||||
return getDatabase().prepare('DELETE FROM bot_statuses WHERE id = ?').run(id).changes;
|
||||
}
|
||||
|
||||
export function clearBotStatuses() {
|
||||
return getDatabase().prepare('DELETE FROM bot_statuses').run().changes;
|
||||
}
|
||||
|
||||
export function countBotStatuses() {
|
||||
const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM bot_statuses').get();
|
||||
return row.count;
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function logEvent({ guildId = null, type, actorId = null, payload = null }) {
|
||||
getDatabase()
|
||||
.prepare('INSERT INTO event_logs (guild_id, type, actor_id, payload) VALUES (?, ?, ?, ?)')
|
||||
.run(guildId, type, actorId, payload ? JSON.stringify(payload) : null);
|
||||
}
|
||||
|
||||
export function purgeEventsOlderThan(days) {
|
||||
return getDatabase()
|
||||
.prepare("DELETE FROM event_logs WHERE created_at < datetime('now', ?)")
|
||||
.run(`-${days} days`).changes;
|
||||
}
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function logEvent({ guildId = null, type, actorId = null, payload = null }) {
|
||||
getDatabase()
|
||||
.prepare('INSERT INTO event_logs (guild_id, type, actor_id, payload) VALUES (?, ?, ?, ?)')
|
||||
.run(guildId, type, actorId, payload ? JSON.stringify(payload) : null);
|
||||
}
|
||||
|
||||
export function purgeEventsOlderThan(days) {
|
||||
return getDatabase()
|
||||
.prepare("DELETE FROM event_logs WHERE created_at < datetime('now', ?)")
|
||||
.run(`-${days} days`).changes;
|
||||
}
|
||||
@@ -1,50 +1,50 @@
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function recordAction({
|
||||
guildId,
|
||||
action,
|
||||
moderatorId,
|
||||
targetId = null,
|
||||
reason = null,
|
||||
durationMs = null,
|
||||
}) {
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO moderation_actions (guild_id, action, target_id, moderator_id, reason, duration_ms)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(guildId, action, targetId, moderatorId, reason, durationMs);
|
||||
}
|
||||
|
||||
export function listActions({ guildId, targetId = null, action = null, limit = 20 }) {
|
||||
const clauses = ['guild_id = ?'];
|
||||
const params = [guildId];
|
||||
if (targetId) {
|
||||
clauses.push('target_id = ?');
|
||||
params.push(targetId);
|
||||
}
|
||||
if (action) {
|
||||
clauses.push('action = ?');
|
||||
params.push(action);
|
||||
}
|
||||
params.push(limit);
|
||||
|
||||
return getDatabase()
|
||||
.prepare(`SELECT * FROM moderation_actions WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
|
||||
.all(...params);
|
||||
}
|
||||
|
||||
export function countActions({ guildId, targetId, action }) {
|
||||
const row = getDatabase()
|
||||
.prepare(
|
||||
'SELECT COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? AND target_id = ? AND action = ?',
|
||||
)
|
||||
.get(guildId, targetId, action);
|
||||
return row.count;
|
||||
}
|
||||
|
||||
export function countByAction(guildId) {
|
||||
return getDatabase()
|
||||
.prepare('SELECT action, COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? GROUP BY action')
|
||||
.all(guildId);
|
||||
}
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function recordAction({
|
||||
guildId,
|
||||
action,
|
||||
moderatorId,
|
||||
targetId = null,
|
||||
reason = null,
|
||||
durationMs = null,
|
||||
}) {
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO moderation_actions (guild_id, action, target_id, moderator_id, reason, duration_ms)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(guildId, action, targetId, moderatorId, reason, durationMs);
|
||||
}
|
||||
|
||||
export function listActions({ guildId, targetId = null, action = null, limit = 20 }) {
|
||||
const clauses = ['guild_id = ?'];
|
||||
const params = [guildId];
|
||||
if (targetId) {
|
||||
clauses.push('target_id = ?');
|
||||
params.push(targetId);
|
||||
}
|
||||
if (action) {
|
||||
clauses.push('action = ?');
|
||||
params.push(action);
|
||||
}
|
||||
params.push(limit);
|
||||
|
||||
return getDatabase()
|
||||
.prepare(`SELECT * FROM moderation_actions WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
|
||||
.all(...params);
|
||||
}
|
||||
|
||||
export function countActions({ guildId, targetId, action }) {
|
||||
const row = getDatabase()
|
||||
.prepare(
|
||||
'SELECT COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? AND target_id = ? AND action = ?',
|
||||
)
|
||||
.get(guildId, targetId, action);
|
||||
return row.count;
|
||||
}
|
||||
|
||||
export function countByAction(guildId) {
|
||||
return getDatabase()
|
||||
.prepare('SELECT action, COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? GROUP BY action')
|
||||
.all(guildId);
|
||||
}
|
||||
@@ -1,34 +1,34 @@
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
/** Per-guild override of a notification channel (M9-T01). */
|
||||
export function setNotificationChannel({ guildId, type, channelId, detailLevel = 'normal' }) {
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO notification_channels (guild_id, type, channel_id, detail_level)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (guild_id, type) DO UPDATE SET
|
||||
channel_id = excluded.channel_id,
|
||||
detail_level = excluded.detail_level`,
|
||||
)
|
||||
.run(guildId, type, channelId, detailLevel);
|
||||
}
|
||||
|
||||
export function getNotificationChannel(guildId, type) {
|
||||
return (
|
||||
getDatabase()
|
||||
.prepare('SELECT * FROM notification_channels WHERE guild_id = ? AND type = ?')
|
||||
.get(guildId, type) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function listNotificationChannels(guildId) {
|
||||
return getDatabase()
|
||||
.prepare('SELECT * FROM notification_channels WHERE guild_id = ? ORDER BY type')
|
||||
.all(guildId);
|
||||
}
|
||||
|
||||
export function removeNotificationChannel(guildId, type) {
|
||||
return getDatabase()
|
||||
.prepare('DELETE FROM notification_channels WHERE guild_id = ? AND type = ?')
|
||||
.run(guildId, type).changes;
|
||||
}
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
/** Per-guild override of a notification channel (M9-T01). */
|
||||
export function setNotificationChannel({ guildId, type, channelId, detailLevel = 'normal' }) {
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO notification_channels (guild_id, type, channel_id, detail_level)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (guild_id, type) DO UPDATE SET
|
||||
channel_id = excluded.channel_id,
|
||||
detail_level = excluded.detail_level`,
|
||||
)
|
||||
.run(guildId, type, channelId, detailLevel);
|
||||
}
|
||||
|
||||
export function getNotificationChannel(guildId, type) {
|
||||
return (
|
||||
getDatabase()
|
||||
.prepare('SELECT * FROM notification_channels WHERE guild_id = ? AND type = ?')
|
||||
.get(guildId, type) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function listNotificationChannels(guildId) {
|
||||
return getDatabase()
|
||||
.prepare('SELECT * FROM notification_channels WHERE guild_id = ? ORDER BY type')
|
||||
.all(guildId);
|
||||
}
|
||||
|
||||
export function removeNotificationChannel(guildId, type) {
|
||||
return getDatabase()
|
||||
.prepare('DELETE FROM notification_channels WHERE guild_id = ? AND type = ?')
|
||||
.run(guildId, type).changes;
|
||||
}
|
||||
@@ -1,97 +1,97 @@
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function createPoll({ guildId, channelId, creatorId, question, choices, endsAt = null }) {
|
||||
const { lastInsertRowid } = getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO polls (guild_id, channel_id, creator_id, question, choices, ends_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(guildId, channelId, creatorId, question, JSON.stringify(choices), endsAt);
|
||||
return Number(lastInsertRowid);
|
||||
}
|
||||
|
||||
export function attachPollMessage(id, messageId) {
|
||||
getDatabase().prepare('UPDATE polls SET message_id = ? WHERE id = ?').run(messageId, id);
|
||||
}
|
||||
|
||||
export function getPoll(id) {
|
||||
return getDatabase().prepare('SELECT * FROM polls WHERE id = ?').get(id) ?? null;
|
||||
}
|
||||
|
||||
export function getPollByMessage(messageId) {
|
||||
return getDatabase().prepare('SELECT * FROM polls WHERE message_id = ?').get(messageId) ?? null;
|
||||
}
|
||||
|
||||
export function listPolls({ guildId, status = null, limit = 10 }) {
|
||||
const clauses = ['guild_id = ?'];
|
||||
const params = [guildId];
|
||||
if (status) {
|
||||
clauses.push('status = ?');
|
||||
params.push(status);
|
||||
}
|
||||
params.push(limit);
|
||||
|
||||
return getDatabase()
|
||||
.prepare(`SELECT * FROM polls WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
|
||||
.all(...params);
|
||||
}
|
||||
|
||||
/** Polls whose end date is reached and that are still open (M10-T05). */
|
||||
export function listDuePolls(limit = 10) {
|
||||
return getDatabase()
|
||||
.prepare(
|
||||
`SELECT * FROM polls
|
||||
WHERE status = 'open' AND ends_at IS NOT NULL AND ends_at <= datetime('now')
|
||||
ORDER BY ends_at ASC LIMIT ?`,
|
||||
)
|
||||
.all(limit);
|
||||
}
|
||||
|
||||
export function listOpenPolls(limit = 25) {
|
||||
return getDatabase()
|
||||
.prepare("SELECT * FROM polls WHERE status = 'open' ORDER BY id ASC LIMIT ?")
|
||||
.all(limit);
|
||||
}
|
||||
|
||||
export function listVotes(pollId) {
|
||||
return getDatabase().prepare('SELECT user_id, choice_index FROM poll_votes WHERE poll_id = ?').all(pollId);
|
||||
}
|
||||
|
||||
/** Counts votes per choice index: `[{ choice_index, count }]`. */
|
||||
export function countVotes(pollId) {
|
||||
return getDatabase()
|
||||
.prepare('SELECT choice_index, COUNT(*) AS count FROM poll_votes WHERE poll_id = ? GROUP BY choice_index')
|
||||
.all(pollId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates or updates a vote. Returns 'created', 'changed' or 'unchanged' (M10-T04).
|
||||
*/
|
||||
export function castVote(pollId, userId, choiceIndex) {
|
||||
const database = getDatabase();
|
||||
const previous = database
|
||||
.prepare('SELECT choice_index FROM poll_votes WHERE poll_id = ? AND user_id = ?')
|
||||
.get(pollId, userId);
|
||||
|
||||
if (previous && previous.choice_index === choiceIndex) return 'unchanged';
|
||||
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO poll_votes (poll_id, user_id, choice_index) VALUES (?, ?, ?)
|
||||
ON CONFLICT (poll_id, user_id) DO UPDATE SET choice_index = excluded.choice_index,
|
||||
voted_at = datetime('now')`,
|
||||
)
|
||||
.run(pollId, userId, choiceIndex);
|
||||
|
||||
return previous ? 'changed' : 'created';
|
||||
}
|
||||
|
||||
export function closePoll(id) {
|
||||
return getDatabase().prepare("UPDATE polls SET status = 'closed' WHERE id = ? AND status = 'open'").run(id)
|
||||
.changes;
|
||||
}
|
||||
|
||||
export function countPolls(guildId) {
|
||||
const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM polls WHERE guild_id = ?').get(guildId);
|
||||
return row.count;
|
||||
}
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function createPoll({ guildId, channelId, creatorId, question, choices, endsAt = null }) {
|
||||
const { lastInsertRowid } = getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO polls (guild_id, channel_id, creator_id, question, choices, ends_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(guildId, channelId, creatorId, question, JSON.stringify(choices), endsAt);
|
||||
return Number(lastInsertRowid);
|
||||
}
|
||||
|
||||
export function attachPollMessage(id, messageId) {
|
||||
getDatabase().prepare('UPDATE polls SET message_id = ? WHERE id = ?').run(messageId, id);
|
||||
}
|
||||
|
||||
export function getPoll(id) {
|
||||
return getDatabase().prepare('SELECT * FROM polls WHERE id = ?').get(id) ?? null;
|
||||
}
|
||||
|
||||
export function getPollByMessage(messageId) {
|
||||
return getDatabase().prepare('SELECT * FROM polls WHERE message_id = ?').get(messageId) ?? null;
|
||||
}
|
||||
|
||||
export function listPolls({ guildId, status = null, limit = 10 }) {
|
||||
const clauses = ['guild_id = ?'];
|
||||
const params = [guildId];
|
||||
if (status) {
|
||||
clauses.push('status = ?');
|
||||
params.push(status);
|
||||
}
|
||||
params.push(limit);
|
||||
|
||||
return getDatabase()
|
||||
.prepare(`SELECT * FROM polls WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
|
||||
.all(...params);
|
||||
}
|
||||
|
||||
/** Polls whose end date is reached and that are still open (M10-T05). */
|
||||
export function listDuePolls(limit = 10) {
|
||||
return getDatabase()
|
||||
.prepare(
|
||||
`SELECT * FROM polls
|
||||
WHERE status = 'open' AND ends_at IS NOT NULL AND ends_at <= datetime('now')
|
||||
ORDER BY ends_at ASC LIMIT ?`,
|
||||
)
|
||||
.all(limit);
|
||||
}
|
||||
|
||||
export function listOpenPolls(limit = 25) {
|
||||
return getDatabase()
|
||||
.prepare("SELECT * FROM polls WHERE status = 'open' ORDER BY id ASC LIMIT ?")
|
||||
.all(limit);
|
||||
}
|
||||
|
||||
export function listVotes(pollId) {
|
||||
return getDatabase().prepare('SELECT user_id, choice_index FROM poll_votes WHERE poll_id = ?').all(pollId);
|
||||
}
|
||||
|
||||
/** Counts votes per choice index: `[{ choice_index, count }]`. */
|
||||
export function countVotes(pollId) {
|
||||
return getDatabase()
|
||||
.prepare('SELECT choice_index, COUNT(*) AS count FROM poll_votes WHERE poll_id = ? GROUP BY choice_index')
|
||||
.all(pollId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates or updates a vote. Returns 'created', 'changed' or 'unchanged' (M10-T04).
|
||||
*/
|
||||
export function castVote(pollId, userId, choiceIndex) {
|
||||
const database = getDatabase();
|
||||
const previous = database
|
||||
.prepare('SELECT choice_index FROM poll_votes WHERE poll_id = ? AND user_id = ?')
|
||||
.get(pollId, userId);
|
||||
|
||||
if (previous && previous.choice_index === choiceIndex) return 'unchanged';
|
||||
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO poll_votes (poll_id, user_id, choice_index) VALUES (?, ?, ?)
|
||||
ON CONFLICT (poll_id, user_id) DO UPDATE SET choice_index = excluded.choice_index,
|
||||
voted_at = datetime('now')`,
|
||||
)
|
||||
.run(pollId, userId, choiceIndex);
|
||||
|
||||
return previous ? 'changed' : 'created';
|
||||
}
|
||||
|
||||
export function closePoll(id) {
|
||||
return getDatabase().prepare("UPDATE polls SET status = 'closed' WHERE id = ? AND status = 'open'").run(id)
|
||||
.changes;
|
||||
}
|
||||
|
||||
export function countPolls(guildId) {
|
||||
const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM polls WHERE guild_id = ?').get(guildId);
|
||||
return row.count;
|
||||
}
|
||||
@@ -1,33 +1,33 @@
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function getSetting(guildId, key, fallback = null) {
|
||||
const row = getDatabase()
|
||||
.prepare('SELECT value FROM guild_settings WHERE guild_id = ? AND key = ?')
|
||||
.get(guildId, key);
|
||||
return row ? JSON.parse(row.value) : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a setting without throwing when the database is not ready (tests, early startup).
|
||||
* Never use it when a missing database should be an error.
|
||||
*/
|
||||
export function resolveSetting(guildId, key, fallback = null) {
|
||||
try {
|
||||
return getSetting(guildId, key, fallback);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export function setSetting(guildId, key, value, updatedBy = null) {
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO guild_settings (guild_id, key, value, updated_by)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (guild_id, key) DO UPDATE SET
|
||||
value = excluded.value,
|
||||
updated_by = excluded.updated_by,
|
||||
updated_at = datetime('now')`,
|
||||
)
|
||||
.run(guildId, key, JSON.stringify(value), updatedBy);
|
||||
}
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function getSetting(guildId, key, fallback = null) {
|
||||
const row = getDatabase()
|
||||
.prepare('SELECT value FROM guild_settings WHERE guild_id = ? AND key = ?')
|
||||
.get(guildId, key);
|
||||
return row ? JSON.parse(row.value) : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a setting without throwing when the database is not ready (tests, early startup).
|
||||
* Never use it when a missing database should be an error.
|
||||
*/
|
||||
export function resolveSetting(guildId, key, fallback = null) {
|
||||
try {
|
||||
return getSetting(guildId, key, fallback);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export function setSetting(guildId, key, value, updatedBy = null) {
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO guild_settings (guild_id, key, value, updated_by)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (guild_id, key) DO UPDATE SET
|
||||
value = excluded.value,
|
||||
updated_by = excluded.updated_by,
|
||||
updated_at = datetime('now')`,
|
||||
)
|
||||
.run(guildId, key, JSON.stringify(value), updatedBy);
|
||||
}
|
||||
@@ -1,71 +1,71 @@
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function createTicket({ guildId, channelId, categoryId, authorId }) {
|
||||
const { lastInsertRowid } = getDatabase()
|
||||
.prepare('INSERT INTO tickets (guild_id, channel_id, category_id, author_id) VALUES (?, ?, ?, ?)')
|
||||
.run(guildId, channelId, categoryId, authorId);
|
||||
return Number(lastInsertRowid);
|
||||
}
|
||||
|
||||
export function getTicket(id) {
|
||||
return getDatabase().prepare('SELECT * FROM tickets WHERE id = ?').get(id) ?? null;
|
||||
}
|
||||
|
||||
export function getTicketByChannel(channelId) {
|
||||
return getDatabase().prepare('SELECT * FROM tickets WHERE channel_id = ?').get(channelId) ?? null;
|
||||
}
|
||||
|
||||
/** Returns the open ticket of an author for a category, if any (M6-T08). */
|
||||
export function getOpenTicket({ guildId, authorId, categoryId }) {
|
||||
return (
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`SELECT * FROM tickets
|
||||
WHERE guild_id = ? AND author_id = ? AND category_id = ? AND status = 'open'`,
|
||||
)
|
||||
.get(guildId, authorId, categoryId) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function listTickets({ guildId, status = null, authorId = null, limit = 20 }) {
|
||||
const clauses = ['guild_id = ?'];
|
||||
const params = [guildId];
|
||||
if (status) {
|
||||
clauses.push('status = ?');
|
||||
params.push(status);
|
||||
}
|
||||
if (authorId) {
|
||||
clauses.push('author_id = ?');
|
||||
params.push(authorId);
|
||||
}
|
||||
params.push(limit);
|
||||
|
||||
return getDatabase()
|
||||
.prepare(`SELECT * FROM tickets WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
|
||||
.all(...params);
|
||||
}
|
||||
|
||||
export function claimTicket(id, userId) {
|
||||
return getDatabase()
|
||||
.prepare(
|
||||
"UPDATE tickets SET claimed_by = ?, claimed_at = datetime('now') WHERE id = ? AND status = 'open'",
|
||||
)
|
||||
.run(userId, id).changes;
|
||||
}
|
||||
|
||||
export function closeTicket(id, { closedBy, reason = null }) {
|
||||
return getDatabase()
|
||||
.prepare(
|
||||
`UPDATE tickets
|
||||
SET status = 'closed', closed_at = datetime('now'), closed_by = ?, close_reason = ?
|
||||
WHERE id = ? AND status = 'open'`,
|
||||
)
|
||||
.run(closedBy, reason, id).changes;
|
||||
}
|
||||
|
||||
export function countOpenTickets(guildId) {
|
||||
const row = getDatabase()
|
||||
.prepare("SELECT COUNT(*) AS count FROM tickets WHERE guild_id = ? AND status = 'open'")
|
||||
.get(guildId);
|
||||
return row.count;
|
||||
}
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function createTicket({ guildId, channelId, categoryId, authorId }) {
|
||||
const { lastInsertRowid } = getDatabase()
|
||||
.prepare('INSERT INTO tickets (guild_id, channel_id, category_id, author_id) VALUES (?, ?, ?, ?)')
|
||||
.run(guildId, channelId, categoryId, authorId);
|
||||
return Number(lastInsertRowid);
|
||||
}
|
||||
|
||||
export function getTicket(id) {
|
||||
return getDatabase().prepare('SELECT * FROM tickets WHERE id = ?').get(id) ?? null;
|
||||
}
|
||||
|
||||
export function getTicketByChannel(channelId) {
|
||||
return getDatabase().prepare('SELECT * FROM tickets WHERE channel_id = ?').get(channelId) ?? null;
|
||||
}
|
||||
|
||||
/** Returns the open ticket of an author for a category, if any (M6-T08). */
|
||||
export function getOpenTicket({ guildId, authorId, categoryId }) {
|
||||
return (
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`SELECT * FROM tickets
|
||||
WHERE guild_id = ? AND author_id = ? AND category_id = ? AND status = 'open'`,
|
||||
)
|
||||
.get(guildId, authorId, categoryId) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function listTickets({ guildId, status = null, authorId = null, limit = 20 }) {
|
||||
const clauses = ['guild_id = ?'];
|
||||
const params = [guildId];
|
||||
if (status) {
|
||||
clauses.push('status = ?');
|
||||
params.push(status);
|
||||
}
|
||||
if (authorId) {
|
||||
clauses.push('author_id = ?');
|
||||
params.push(authorId);
|
||||
}
|
||||
params.push(limit);
|
||||
|
||||
return getDatabase()
|
||||
.prepare(`SELECT * FROM tickets WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
|
||||
.all(...params);
|
||||
}
|
||||
|
||||
export function claimTicket(id, userId) {
|
||||
return getDatabase()
|
||||
.prepare(
|
||||
"UPDATE tickets SET claimed_by = ?, claimed_at = datetime('now') WHERE id = ? AND status = 'open'",
|
||||
)
|
||||
.run(userId, id).changes;
|
||||
}
|
||||
|
||||
export function closeTicket(id, { closedBy, reason = null }) {
|
||||
return getDatabase()
|
||||
.prepare(
|
||||
`UPDATE tickets
|
||||
SET status = 'closed', closed_at = datetime('now'), closed_by = ?, close_reason = ?
|
||||
WHERE id = ? AND status = 'open'`,
|
||||
)
|
||||
.run(closedBy, reason, id).changes;
|
||||
}
|
||||
|
||||
export function countOpenTickets(guildId) {
|
||||
const row = getDatabase()
|
||||
.prepare("SELECT COUNT(*) AS count FROM tickets WHERE guild_id = ? AND status = 'open'")
|
||||
.get(guildId);
|
||||
return row.count;
|
||||
}
|
||||
@@ -1,72 +1,72 @@
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function addVoiceChannel({ channelId, guildId, ownerId, triggerId = null, name, userLimit = 0 }) {
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO voice_channels (channel_id, guild_id, owner_id, trigger_id, name, user_limit)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (channel_id) DO UPDATE SET
|
||||
owner_id = excluded.owner_id,
|
||||
name = excluded.name`,
|
||||
)
|
||||
.run(channelId, guildId, ownerId, triggerId, name, userLimit);
|
||||
}
|
||||
|
||||
export function getVoiceChannel(channelId) {
|
||||
return getDatabase().prepare('SELECT * FROM voice_channels WHERE channel_id = ?').get(channelId) ?? null;
|
||||
}
|
||||
|
||||
export function listVoiceChannels(guildId) {
|
||||
return getDatabase()
|
||||
.prepare('SELECT * FROM voice_channels WHERE guild_id = ? ORDER BY created_at ASC')
|
||||
.all(guildId);
|
||||
}
|
||||
|
||||
/** Channels still owned by a member, used to move them back instead of creating another (M14-T03). */
|
||||
export function listOwnedVoiceChannels(guildId, ownerId) {
|
||||
return getDatabase()
|
||||
.prepare('SELECT * FROM voice_channels WHERE guild_id = ? AND owner_id = ? ORDER BY created_at ASC')
|
||||
.all(guildId, ownerId);
|
||||
}
|
||||
|
||||
export function setVoiceOwner(channelId, ownerId) {
|
||||
return getDatabase()
|
||||
.prepare('UPDATE voice_channels SET owner_id = ? WHERE channel_id = ?')
|
||||
.run(ownerId, channelId).changes;
|
||||
}
|
||||
|
||||
export function setVoiceName(channelId, name) {
|
||||
return getDatabase().prepare('UPDATE voice_channels SET name = ? WHERE channel_id = ?').run(name, channelId)
|
||||
.changes;
|
||||
}
|
||||
|
||||
export function setVoiceLocked(channelId, locked) {
|
||||
return getDatabase()
|
||||
.prepare('UPDATE voice_channels SET locked = ? WHERE channel_id = ?')
|
||||
.run(locked ? 1 : 0, channelId).changes;
|
||||
}
|
||||
|
||||
export function setVoiceLimit(channelId, userLimit) {
|
||||
return getDatabase()
|
||||
.prepare('UPDATE voice_channels SET user_limit = ? WHERE channel_id = ?')
|
||||
.run(userLimit, channelId).changes;
|
||||
}
|
||||
|
||||
export function removeVoiceChannel(channelId) {
|
||||
return getDatabase().prepare('DELETE FROM voice_channels WHERE channel_id = ?').run(channelId).changes;
|
||||
}
|
||||
|
||||
export function countVoiceChannels(guildId) {
|
||||
const row = getDatabase()
|
||||
.prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE guild_id = ?')
|
||||
.get(guildId);
|
||||
return row.count;
|
||||
}
|
||||
|
||||
/** Channels still alive for one trigger, used by the configuration embed (M14-T01). */
|
||||
export function countVoiceChannelsByTrigger(triggerId) {
|
||||
const row = getDatabase()
|
||||
.prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE trigger_id = ?')
|
||||
.get(triggerId);
|
||||
return row.count;
|
||||
}
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function addVoiceChannel({ channelId, guildId, ownerId, triggerId = null, name, userLimit = 0 }) {
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO voice_channels (channel_id, guild_id, owner_id, trigger_id, name, user_limit)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (channel_id) DO UPDATE SET
|
||||
owner_id = excluded.owner_id,
|
||||
name = excluded.name`,
|
||||
)
|
||||
.run(channelId, guildId, ownerId, triggerId, name, userLimit);
|
||||
}
|
||||
|
||||
export function getVoiceChannel(channelId) {
|
||||
return getDatabase().prepare('SELECT * FROM voice_channels WHERE channel_id = ?').get(channelId) ?? null;
|
||||
}
|
||||
|
||||
export function listVoiceChannels(guildId) {
|
||||
return getDatabase()
|
||||
.prepare('SELECT * FROM voice_channels WHERE guild_id = ? ORDER BY created_at ASC')
|
||||
.all(guildId);
|
||||
}
|
||||
|
||||
/** Channels still owned by a member, used to move them back instead of creating another (M14-T03). */
|
||||
export function listOwnedVoiceChannels(guildId, ownerId) {
|
||||
return getDatabase()
|
||||
.prepare('SELECT * FROM voice_channels WHERE guild_id = ? AND owner_id = ? ORDER BY created_at ASC')
|
||||
.all(guildId, ownerId);
|
||||
}
|
||||
|
||||
export function setVoiceOwner(channelId, ownerId) {
|
||||
return getDatabase()
|
||||
.prepare('UPDATE voice_channels SET owner_id = ? WHERE channel_id = ?')
|
||||
.run(ownerId, channelId).changes;
|
||||
}
|
||||
|
||||
export function setVoiceName(channelId, name) {
|
||||
return getDatabase().prepare('UPDATE voice_channels SET name = ? WHERE channel_id = ?').run(name, channelId)
|
||||
.changes;
|
||||
}
|
||||
|
||||
export function setVoiceLocked(channelId, locked) {
|
||||
return getDatabase()
|
||||
.prepare('UPDATE voice_channels SET locked = ? WHERE channel_id = ?')
|
||||
.run(locked ? 1 : 0, channelId).changes;
|
||||
}
|
||||
|
||||
export function setVoiceLimit(channelId, userLimit) {
|
||||
return getDatabase()
|
||||
.prepare('UPDATE voice_channels SET user_limit = ? WHERE channel_id = ?')
|
||||
.run(userLimit, channelId).changes;
|
||||
}
|
||||
|
||||
export function removeVoiceChannel(channelId) {
|
||||
return getDatabase().prepare('DELETE FROM voice_channels WHERE channel_id = ?').run(channelId).changes;
|
||||
}
|
||||
|
||||
export function countVoiceChannels(guildId) {
|
||||
const row = getDatabase()
|
||||
.prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE guild_id = ?')
|
||||
.get(guildId);
|
||||
return row.count;
|
||||
}
|
||||
|
||||
/** Channels still alive for one trigger, used by the configuration embed (M14-T01). */
|
||||
export function countVoiceChannelsByTrigger(triggerId) {
|
||||
const row = getDatabase()
|
||||
.prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE trigger_id = ?')
|
||||
.get(triggerId);
|
||||
return row.count;
|
||||
}
|
||||
@@ -1,52 +1,52 @@
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
/**
|
||||
* Declares (or updates) a trigger channel. Every value is explicit: the service merges the
|
||||
* previous row before writing, so an omitted option keeps its stored value (M14-T01).
|
||||
*/
|
||||
export function upsertVoiceTrigger({
|
||||
triggerId,
|
||||
guildId,
|
||||
label = null,
|
||||
categoryId = null,
|
||||
template = null,
|
||||
userLimit = 0,
|
||||
enabled = true,
|
||||
}) {
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO voice_triggers (trigger_id, guild_id, label, category_id, template, user_limit, enabled)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (trigger_id) DO UPDATE SET
|
||||
guild_id = excluded.guild_id,
|
||||
label = excluded.label,
|
||||
category_id = excluded.category_id,
|
||||
template = excluded.template,
|
||||
user_limit = excluded.user_limit,
|
||||
enabled = excluded.enabled,
|
||||
updated_at = datetime('now')`,
|
||||
)
|
||||
.run(triggerId, guildId, label, categoryId, template, userLimit, enabled ? 1 : 0);
|
||||
}
|
||||
|
||||
export function getVoiceTrigger(triggerId) {
|
||||
return getDatabase().prepare('SELECT * FROM voice_triggers WHERE trigger_id = ?').get(triggerId) ?? null;
|
||||
}
|
||||
|
||||
/** All the triggers of a guild, disabled ones included, in creation order. */
|
||||
export function listVoiceTriggers(guildId) {
|
||||
return getDatabase()
|
||||
.prepare('SELECT * FROM voice_triggers WHERE guild_id = ? ORDER BY created_at ASC, trigger_id ASC')
|
||||
.all(guildId);
|
||||
}
|
||||
|
||||
export function removeVoiceTrigger(triggerId) {
|
||||
return getDatabase().prepare('DELETE FROM voice_triggers WHERE trigger_id = ?').run(triggerId).changes;
|
||||
}
|
||||
|
||||
export function countVoiceTriggers(guildId) {
|
||||
const row = getDatabase()
|
||||
.prepare('SELECT COUNT(*) AS count FROM voice_triggers WHERE guild_id = ?')
|
||||
.get(guildId);
|
||||
return row.count;
|
||||
}
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
/**
|
||||
* Declares (or updates) a trigger channel. Every value is explicit: the service merges the
|
||||
* previous row before writing, so an omitted option keeps its stored value (M14-T01).
|
||||
*/
|
||||
export function upsertVoiceTrigger({
|
||||
triggerId,
|
||||
guildId,
|
||||
label = null,
|
||||
categoryId = null,
|
||||
template = null,
|
||||
userLimit = 0,
|
||||
enabled = true,
|
||||
}) {
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO voice_triggers (trigger_id, guild_id, label, category_id, template, user_limit, enabled)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (trigger_id) DO UPDATE SET
|
||||
guild_id = excluded.guild_id,
|
||||
label = excluded.label,
|
||||
category_id = excluded.category_id,
|
||||
template = excluded.template,
|
||||
user_limit = excluded.user_limit,
|
||||
enabled = excluded.enabled,
|
||||
updated_at = datetime('now')`,
|
||||
)
|
||||
.run(triggerId, guildId, label, categoryId, template, userLimit, enabled ? 1 : 0);
|
||||
}
|
||||
|
||||
export function getVoiceTrigger(triggerId) {
|
||||
return getDatabase().prepare('SELECT * FROM voice_triggers WHERE trigger_id = ?').get(triggerId) ?? null;
|
||||
}
|
||||
|
||||
/** All the triggers of a guild, disabled ones included, in creation order. */
|
||||
export function listVoiceTriggers(guildId) {
|
||||
return getDatabase()
|
||||
.prepare('SELECT * FROM voice_triggers WHERE guild_id = ? ORDER BY created_at ASC, trigger_id ASC')
|
||||
.all(guildId);
|
||||
}
|
||||
|
||||
export function removeVoiceTrigger(triggerId) {
|
||||
return getDatabase().prepare('DELETE FROM voice_triggers WHERE trigger_id = ?').run(triggerId).changes;
|
||||
}
|
||||
|
||||
export function countVoiceTriggers(guildId) {
|
||||
const row = getDatabase()
|
||||
.prepare('SELECT COUNT(*) AS count FROM voice_triggers WHERE guild_id = ?')
|
||||
.get(guildId);
|
||||
return row.count;
|
||||
}
|
||||
Reference in new issue
Block a user