aboutsummaryrefslogtreecommitdiffstats
path: root/src/database/mod.rs
blob: b68d927f4e5787f75cd7ef5e7838d929a5196443 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
use chrono::{DateTime, Utc};
use sqlx::FromRow;
use sqlx::SqlitePool;

use crate::error::{Error, Result};

pub type DbPool = SqlitePool;

pub async fn init_pool(path: &str) -> Result<DbPool> {
    if let Some(parent) = std::path::Path::new(path).parent() {
        tokio::fs::create_dir_all(parent).await.map_err(Error::Io)?;
    }
    let pool = SqlitePool::connect(&format!("sqlite:{path}?mode=rwc")).await?;
    run_migrations(&pool).await?;
    // Clear stale voice activity records from previous run.
    sqlx::query("DELETE FROM voice_activity")
        .execute(&pool)
        .await?;
    Ok(pool)
}

async fn run_migrations(pool: &DbPool) -> Result<()> {
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS settings (
            key TEXT PRIMARY KEY,
            value TEXT NOT NULL
        )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS voice_activity (
            user_id TEXT PRIMARY KEY,
            join_time REAL NOT NULL DEFAULT 0,
            total_active REAL NOT NULL DEFAULT 0,
            total_afk REAL NOT NULL DEFAULT 0,
            is_afk INTEGER NOT NULL DEFAULT 0,
            afk_start REAL NOT NULL DEFAULT 0,
            active_start REAL NOT NULL DEFAULT 0,
            channel_name TEXT NOT NULL DEFAULT '',
            last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS cron_jobs (
            id INTEGER PRIMARY KEY,
            cron_expression TEXT NOT NULL,
            type TEXT NOT NULL CHECK(type IN ('audio', 'wiadomość')),
            channel_id INTEGER NOT NULL,
            active INTEGER NOT NULL DEFAULT 1,
            audio_filename TEXT,
            message TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            last_run TIMESTAMP
        )",
    )
    .execute(pool)
    .await?;

    // Add last_run column for pre-existing databases that lack it.
    sqlx::query("ALTER TABLE cron_jobs ADD COLUMN last_run TIMESTAMP")
        .execute(pool)
        .await
        .ok();

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS triggers (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT UNIQUE NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS trigger_keywords (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            trigger_id INTEGER NOT NULL REFERENCES triggers(id) ON DELETE CASCADE,
            keyword TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            UNIQUE(trigger_id, keyword)
        )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS trigger_responses (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            trigger_id INTEGER NOT NULL REFERENCES triggers(id) ON DELETE CASCADE,
            response_text TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )",
    )
    .execute(pool)
    .await?;

    sqlx::query(
        "CREATE TABLE IF NOT EXISTS user_stats (
            user_id TEXT PRIMARY KEY,
            message_count INTEGER NOT NULL DEFAULT 0,
            total_voice_active REAL NOT NULL DEFAULT 0,
            total_voice_afk REAL NOT NULL DEFAULT 0,
            last_message_at TIMESTAMP
        )",
    )
    .execute(pool)
    .await?;

    Ok(())
}

// -- Voice Activity --
#[derive(Debug, Clone, FromRow)]
pub struct VoiceActivity {
    pub user_id: String,
    pub join_time: f64,
    pub total_active: f64,
    pub total_afk: f64,
    pub is_afk: i32,
    pub afk_start: f64,
    pub active_start: f64,
    pub channel_name: String,
    #[allow(dead_code)]
    pub last_updated: Option<DateTime<Utc>>,
}

#[allow(dead_code)]
pub async fn get_voice_activity(pool: &DbPool, user_id: &str) -> Result<Option<VoiceActivity>> {
    Ok(
        sqlx::query_as("SELECT * FROM voice_activity WHERE user_id = ?")
            .bind(user_id)
            .fetch_optional(pool)
            .await?,
    )
}

pub async fn upsert_voice_activity(pool: &DbPool, va: &VoiceActivity) -> Result<()> {
    sqlx::query(
        "INSERT INTO voice_activity (user_id, join_time, total_active, total_afk, is_afk, afk_start, active_start, channel_name)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)
         ON CONFLICT(user_id) DO UPDATE SET
            join_time = excluded.join_time,
            total_active = excluded.total_active,
            total_afk = excluded.total_afk,
            is_afk = excluded.is_afk,
            afk_start = excluded.afk_start,
            active_start = excluded.active_start,
            channel_name = excluded.channel_name,
            last_updated = CURRENT_TIMESTAMP",
    )
    .bind(&va.user_id)
    .bind(va.join_time)
    .bind(va.total_active)
    .bind(va.total_afk)
    .bind(va.is_afk)
    .bind(va.afk_start)
    .bind(va.active_start)
    .bind(&va.channel_name)
    .execute(pool)
    .await?;
    Ok(())
}

// -- User Stats (leaderboard) --
#[derive(Debug, Clone, FromRow)]
pub struct UserStats {
    pub user_id: String,
    pub message_count: i64,
    pub total_voice_active: f64,
    pub total_voice_afk: f64,
}

/// Increment message count for a user.
pub async fn increment_message_count(pool: &DbPool, user_id: &str) -> Result<()> {
    sqlx::query(
        "INSERT INTO user_stats (user_id, message_count, last_message_at)
         VALUES (?, 1, CURRENT_TIMESTAMP)
         ON CONFLICT(user_id) DO UPDATE SET
            message_count = message_count + 1,
            last_message_at = CURRENT_TIMESTAMP",
    )
    .bind(user_id)
    .execute(pool)
    .await?;
    Ok(())
}

/// Add voice time to a user's cumulative stats.
pub async fn add_voice_time(
    pool: &DbPool,
    user_id: &str,
    active_seconds: f64,
    afk_seconds: f64,
) -> Result<()> {
    sqlx::query(
        "INSERT INTO user_stats (user_id, total_voice_active, total_voice_afk)
         VALUES (?, ?, ?)
         ON CONFLICT(user_id) DO UPDATE SET
            total_voice_active = total_voice_active + ?,
            total_voice_afk = total_voice_afk + ?",
    )
    .bind(user_id)
    .bind(active_seconds)
    .bind(afk_seconds)
    .bind(active_seconds)
    .bind(afk_seconds)
    .execute(pool)
    .await?;
    Ok(())
}

/// Get stats for a single user.
pub async fn get_user_stats(pool: &DbPool, user_id: &str) -> Result<Option<UserStats>> {
    Ok(
        sqlx::query_as("SELECT * FROM user_stats WHERE user_id = ?")
            .bind(user_id)
            .fetch_optional(pool)
            .await?,
    )
}

/// Get leaderboard entries sorted by a metric.
/// Returns (entries, total_count) where total_count is used for pagination.
/// SAFETY: `order_clause` and `order` are derived from fixed match arms, not user input.
pub async fn get_leaderboard(
    pool: &DbPool,
    metric: &str,
    ascending: bool,
    limit: i64,
    offset: i64,
) -> Result<(Vec<UserStats>, i64)> {
    let order = if ascending { "ASC" } else { "DESC" };
    // SAFETY: all arms are compile-time constant strings
    #[allow(clippy::disallowed_methods)]
    let order_clause = match metric {
        "messages" => "message_count",
        "active" => "total_voice_active",
        "afk" => "total_voice_afk",
        "total" => "total_voice_active + total_voice_afk",
        _ => "message_count",
    };

    let total: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM user_stats")
        .fetch_one(pool)
        .await?;

    // SAFETY: order_clause and order are not user-controlled
    let query = format!(
        "SELECT * FROM user_stats ORDER BY {} {} LIMIT ? OFFSET ?",
        order_clause, order
    );
    let entries: Vec<UserStats> = sqlx::query_as(sqlx::AssertSqlSafe(query))
        .bind(limit)
        .bind(offset)
        .fetch_all(pool)
        .await?;

    Ok((entries, total.0))
}

/// Get a user's rank for a metric (1-indexed, 0 if not found).
/// SAFETY: `order_clause` is derived from fixed match arms, not user input.
pub async fn get_user_rank(pool: &DbPool, user_id: &str, metric: &str) -> Result<i64> {
    // SAFETY: all arms are compile-time constant strings
    #[allow(clippy::disallowed_methods)]
    let order_clause = match metric {
        "messages" => "message_count",
        "active" => "total_voice_active",
        "afk" => "total_voice_afk",
        "total" => "total_voice_active + total_voice_afk",
        _ => "message_count",
    };

    // SAFETY: order_clause is not user-controlled
    let query = format!(
        "SELECT COUNT(*) + 1 FROM user_stats WHERE {} > (
            SELECT {} FROM user_stats WHERE user_id = ?
        )",
        order_clause, order_clause
    );
    let result: (i64,) = sqlx::query_as(sqlx::AssertSqlSafe(query))
        .bind(user_id)
        .fetch_one(pool)
        .await?;

    // If user doesn't exist, return 0
    let user_exists: Option<(i64,)> = sqlx::query_as(
        "SELECT 1 FROM user_stats WHERE user_id = ?"
    )
    .bind(user_id)
    .fetch_optional(pool)
    .await?;

    Ok(if user_exists.is_some() { result.0 } else { 0 })
}

// -- Cron Jobs --
#[derive(Debug, Clone, FromRow)]
pub struct CronJob {
    pub id: i64,
    pub cron_expression: String,
    pub r#type: String,
    pub channel_id: i64,
    pub active: i32,
    pub audio_filename: Option<String>,
    pub message: Option<String>,
    #[allow(dead_code)]
    pub created_at: Option<DateTime<Utc>>,
    pub last_run: Option<DateTime<Utc>>,
}

#[allow(dead_code)]
pub async fn list_cron_jobs(pool: &DbPool) -> Result<Vec<CronJob>> {
    Ok(sqlx::query_as("SELECT * FROM cron_jobs ORDER BY id")
        .fetch_all(pool)
        .await?)
}

#[allow(dead_code)]
pub async fn list_active_cron_jobs(pool: &DbPool) -> Result<Vec<CronJob>> {
    Ok(sqlx::query_as("SELECT * FROM cron_jobs WHERE active = 1")
        .fetch_all(pool)
        .await?)
}

pub async fn add_cron_job(
    pool: &DbPool,
    cron_expression: &str,
    r#type: &str,
    channel_id: i64,
    audio_filename: Option<&str>,
    message: Option<&str>,
) -> Result<i64> {
    // Find the lowest unused ID to reuse freed slots
    let existing: Vec<i64> = sqlx::query_scalar("SELECT id FROM cron_jobs ORDER BY id")
        .fetch_all(pool)
        .await?;

    let next_id = existing.iter().enumerate().find_map(|(i, &id)| {
        let expected = (i as i64) + 1;
        if id != expected {
            Some(expected)
        } else {
            None
        }
    }).unwrap_or(existing.len() as i64 + 1);

    let result = sqlx::query(
        "INSERT INTO cron_jobs (id, cron_expression, type, channel_id, audio_filename, message) VALUES (?, ?, ?, ?, ?, ?)",
    )
    .bind(next_id)
    .bind(cron_expression)
    .bind(r#type)
    .bind(channel_id)
    .bind(audio_filename)
    .bind(message)
    .execute(pool)
    .await?;
    Ok(result.last_insert_rowid())
}

pub async fn delete_cron_job(pool: &DbPool, id: i64) -> Result<bool> {
    let result = sqlx::query("DELETE FROM cron_jobs WHERE id = ?")
        .bind(id)
        .execute(pool)
        .await?;
    Ok(result.rows_affected() > 0)
}

pub async fn update_cron_last_run(pool: &DbPool, id: i64, last_run: DateTime<Utc>) -> Result<()> {
    sqlx::query("UPDATE cron_jobs SET last_run = ? WHERE id = ?")
        .bind(last_run)
        .bind(id)
        .execute(pool)
        .await?;
    Ok(())
}

pub async fn set_cron_job_active(pool: &DbPool, id: i64, active: bool) -> Result<bool> {
    let result = sqlx::query("UPDATE cron_jobs SET active = ? WHERE id = ?")
        .bind(if active { 1 } else { 0 })
        .bind(id)
        .execute(pool)
        .await?;
    Ok(result.rows_affected() > 0)
}

// -- Triggers --
#[derive(Debug, Clone, FromRow)]
pub struct Trigger {
    pub id: i64,
    pub name: String,
    pub created_at: Option<DateTime<Utc>>,
    pub last_updated: Option<DateTime<Utc>>,
}

#[allow(dead_code)]
#[derive(Debug, Clone, FromRow)]
pub struct TriggerKeyword {
    pub id: i64,
    pub trigger_id: i64,
    pub keyword: String,
}

#[allow(dead_code)]
#[derive(Debug, Clone, FromRow)]
pub struct TriggerResponse {
    pub id: i64,
    pub trigger_id: i64,
    pub response_text: String,
}

pub async fn create_trigger(pool: &DbPool, name: &str) -> Result<i64> {
    let result = sqlx::query("INSERT INTO triggers (name) VALUES (?)")
        .bind(name)
        .execute(pool)
        .await?;
    Ok(result.last_insert_rowid())
}

pub async fn delete_trigger(pool: &DbPool, id: i64) -> Result<bool> {
    let result = sqlx::query("DELETE FROM triggers WHERE id = ?")
        .bind(id)
        .execute(pool)
        .await?;
    Ok(result.rows_affected() > 0)
}

pub async fn get_trigger_by_name(pool: &DbPool, name: &str) -> Result<Option<Trigger>> {
    Ok(sqlx::query_as("SELECT * FROM triggers WHERE name = ?")
        .bind(name)
        .fetch_optional(pool)
        .await?)
}

pub async fn list_triggers(pool: &DbPool) -> Result<Vec<Trigger>> {
    Ok(sqlx::query_as("SELECT * FROM triggers ORDER BY name")
        .fetch_all(pool)
        .await?)
}

pub async fn add_keyword(pool: &DbPool, trigger_id: i64, keyword: &str) -> Result<()> {
    sqlx::query("INSERT OR IGNORE INTO trigger_keywords (trigger_id, keyword) VALUES (?, ?)")
        .bind(trigger_id)
        .bind(keyword)
        .execute(pool)
        .await?;
    update_trigger_timestamp(pool, trigger_id).await
}

pub async fn remove_keyword(pool: &DbPool, trigger_id: i64, keyword: &str) -> Result<bool> {
    let result = sqlx::query("DELETE FROM trigger_keywords WHERE trigger_id = ? AND keyword = ?")
        .bind(trigger_id)
        .bind(keyword)
        .execute(pool)
        .await?;
    update_trigger_timestamp(pool, trigger_id).await?;
    Ok(result.rows_affected() > 0)
}

pub async fn add_response(pool: &DbPool, trigger_id: i64, response: &str) -> Result<()> {
    sqlx::query("INSERT INTO trigger_responses (trigger_id, response_text) VALUES (?, ?)")
        .bind(trigger_id)
        .bind(response)
        .execute(pool)
        .await?;
    update_trigger_timestamp(pool, trigger_id).await
}

pub async fn remove_response(pool: &DbPool, trigger_id: i64, response: &str) -> Result<bool> {
    let result =
        sqlx::query("DELETE FROM trigger_responses WHERE trigger_id = ? AND response_text = ?")
            .bind(trigger_id)
            .bind(response)
            .execute(pool)
            .await?;
    update_trigger_timestamp(pool, trigger_id).await?;
    Ok(result.rows_affected() > 0)
}

pub async fn get_keywords(pool: &DbPool, trigger_id: i64) -> Result<Vec<String>> {
    let rows: Vec<(String,)> =
        sqlx::query_as("SELECT keyword FROM trigger_keywords WHERE trigger_id = ?")
            .bind(trigger_id)
            .fetch_all(pool)
            .await?;
    Ok(rows.into_iter().map(|r| r.0).collect())
}

pub async fn get_responses(pool: &DbPool, trigger_id: i64) -> Result<Vec<String>> {
    let rows: Vec<(String,)> =
        sqlx::query_as("SELECT response_text FROM trigger_responses WHERE trigger_id = ?")
            .bind(trigger_id)
            .fetch_all(pool)
            .await?;
    Ok(rows.into_iter().map(|r| r.0).collect())
}

pub async fn load_all_triggers_with_keywords_and_responses(
    pool: &DbPool,
) -> Result<Vec<(Trigger, Vec<String>, Vec<String>)>> {
    let triggers = list_triggers(pool).await?;
    let mut result = Vec::new();
    for t in triggers {
        let keywords = get_keywords(pool, t.id).await?;
        let responses = get_responses(pool, t.id).await?;
        result.push((t, keywords, responses));
    }
    Ok(result)
}

async fn update_trigger_timestamp(pool: &DbPool, id: i64) -> Result<()> {
    sqlx::query("UPDATE triggers SET last_updated = CURRENT_TIMESTAMP WHERE id = ?")
        .bind(id)
        .execute(pool)
        .await?;
    Ok(())
}