-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
515 lines (451 loc) · 17.9 KB
/
Copy pathdb.py
File metadata and controls
515 lines (451 loc) · 17.9 KB
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
from __future__ import annotations
import os
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, Optional, Sequence
try:
import aiomysql
except Exception:
aiomysql = None
@dataclass(frozen=True)
class MariaDBConfig:
host: str
port: int
user: str
password: str
database: str
min_pool: int = 1
max_pool: int = 10
def _env_truthy(value: Optional[str]) -> bool:
return str(value or "").strip().lower() in {"1", "true", "yes", "y", "on"}
def load_mariadb_config() -> Optional[MariaDBConfig]:
host = (os.getenv("MARIADB_HOST") or "").strip()
user = (os.getenv("MARIADB_USER") or "").strip()
password = os.getenv("MARIADB_PASSWORD") or ""
database = (os.getenv("MARIADB_DATABASE") or "").strip()
if not (host and user and database):
return None
try:
port = int(os.getenv("MARIADB_PORT", "3306"))
except ValueError:
port = 3306
try:
min_pool = int(os.getenv("MARIADB_MIN_POOL", "1"))
except ValueError:
min_pool = 1
try:
max_pool = int(os.getenv("MARIADB_MAX_POOL", "10"))
except ValueError:
max_pool = 10
if min_pool < 1:
min_pool = 1
if max_pool < min_pool:
max_pool = min_pool
return MariaDBConfig(
host=host,
port=port,
user=user,
password=password,
database=database,
min_pool=min_pool,
max_pool=max_pool,
)
def mariadb_enabled() -> bool:
return load_mariadb_config() is not None
async def create_mariadb_pool(cfg: MariaDBConfig):
if aiomysql is None:
raise RuntimeError("aiomysql is not installed")
return await aiomysql.create_pool(
host=cfg.host,
port=cfg.port,
user=cfg.user,
password=cfg.password,
db=cfg.database,
minsize=cfg.min_pool,
maxsize=cfg.max_pool,
autocommit=True,
)
async def ensure_schema(pool) -> None:
"""Create tables needed by JartonBot when MARIADB_AUTO_MIGRATE is enabled."""
if not _env_truthy(os.getenv("MARIADB_AUTO_MIGRATE")):
return
tables: dict[str, str] = {
"badword_offenses": (
"CREATE TABLE IF NOT EXISTS badword_offenses ("
"id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,"
"user_id BIGINT UNSIGNED NOT NULL,"
"guild_id BIGINT UNSIGNED NOT NULL,"
"channel_id BIGINT UNSIGNED NOT NULL,"
"message_id BIGINT UNSIGNED NULL,"
"content TEXT NOT NULL,"
"detected_words TEXT NOT NULL,"
"created_at DATETIME(6) NOT NULL,"
"PRIMARY KEY (id),"
"INDEX idx_badword_user_created (user_id, created_at),"
"INDEX idx_badword_created (created_at)"
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
),
"tickets": (
"CREATE TABLE IF NOT EXISTS tickets ("
"id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,"
"guild_id BIGINT UNSIGNED NOT NULL,"
"channel_id BIGINT UNSIGNED NOT NULL,"
"category VARCHAR(64) NOT NULL,"
"opener_id BIGINT UNSIGNED NOT NULL,"
"status VARCHAR(16) NOT NULL,"
"created_at DATETIME(6) NOT NULL,"
"closed_at DATETIME(6) NULL,"
"closed_by BIGINT UNSIGNED NULL,"
"close_reason VARCHAR(255) NULL,"
"transcript_path VARCHAR(512) NULL,"
"PRIMARY KEY (id),"
"UNIQUE KEY uq_tickets_channel (channel_id),"
"INDEX idx_tickets_guild_status (guild_id, status),"
"INDEX idx_tickets_opener (opener_id, created_at)"
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
),
"applications": (
"CREATE TABLE IF NOT EXISTS applications ("
"id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,"
"guild_id BIGINT UNSIGNED NULL,"
"user_id BIGINT UNSIGNED NOT NULL,"
"role_applied VARCHAR(64) NOT NULL,"
"answers_json LONGTEXT NOT NULL,"
"submitted_at DATETIME(6) NOT NULL,"
"thread_id BIGINT UNSIGNED NULL,"
"transcript_channel_id BIGINT UNSIGNED NULL,"
"PRIMARY KEY (id),"
"INDEX idx_apps_user (user_id, submitted_at),"
"INDEX idx_apps_guild (guild_id, submitted_at)"
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
),
"mod_warns": (
"CREATE TABLE IF NOT EXISTS mod_warns ("
"id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,"
"guild_id BIGINT UNSIGNED NOT NULL,"
"user_id BIGINT UNSIGNED NOT NULL,"
"moderator_id BIGINT UNSIGNED NOT NULL,"
"reason VARCHAR(512) NOT NULL,"
"created_at DATETIME(6) NOT NULL,"
"PRIMARY KEY (id),"
"INDEX idx_modwarn_user (guild_id, user_id, created_at)"
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
),
"count_state": (
"CREATE TABLE IF NOT EXISTS count_state ("
"guild_id BIGINT UNSIGNED NOT NULL,"
"state_json LONGTEXT NOT NULL,"
"updated_at DATETIME(6) NOT NULL,"
"PRIMARY KEY (guild_id)"
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
),
"invite_joins": (
"CREATE TABLE IF NOT EXISTS invite_joins ("
"guild_id BIGINT UNSIGNED NOT NULL,"
"member_id BIGINT UNSIGNED NOT NULL,"
"inviter_id BIGINT UNSIGNED NULL,"
"joined_at DATETIME(6) NOT NULL,"
"PRIMARY KEY (guild_id, member_id),"
"INDEX idx_invite_inviter (guild_id, inviter_id),"
"INDEX idx_invite_joined (guild_id, joined_at)"
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
),
"suggestions": (
"CREATE TABLE IF NOT EXISTS suggestions ("
"id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,"
"guild_id BIGINT UNSIGNED NOT NULL,"
"channel_id BIGINT UNSIGNED NOT NULL,"
"message_id BIGINT UNSIGNED NOT NULL,"
"author_id BIGINT UNSIGNED NOT NULL,"
"title VARCHAR(120) NOT NULL,"
"description TEXT NOT NULL,"
"status VARCHAR(16) NOT NULL,"
"denial_reason VARCHAR(500) NULL,"
"reviewed_by BIGINT UNSIGNED NULL,"
"reviewed_at DATETIME(6) NULL,"
"created_at DATETIME(6) NOT NULL,"
"PRIMARY KEY (id),"
"UNIQUE KEY uq_suggestions_message (message_id),"
"INDEX idx_suggestions_guild_status (guild_id, status, created_at),"
"INDEX idx_suggestions_author (author_id, created_at)"
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
),
}
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT DATABASE()")
db_row = await cur.fetchone()
db_name = db_row[0] if db_row else None
created = 0
existed = 0
for table_name, ddl in tables.items():
exists = False
if db_name:
await cur.execute(
"SELECT 1 FROM information_schema.tables WHERE table_schema=%s AND table_name=%s LIMIT 1",
(db_name, table_name),
)
exists = (await cur.fetchone()) is not None
if exists:
existed += 1
print(f"ℹ️ MariaDB schema: {table_name} already exists; skipping.")
continue
await cur.execute(ddl)
created += 1
print(f"✅ MariaDB schema: created {table_name}.")
print(f"✅ MariaDB schema ready (created {created}, existing {existed}).")
def utcnow() -> datetime:
return datetime.now(timezone.utc)
async def record_suggestion_submit(
pool,
*,
guild_id: int,
channel_id: int,
message_id: int,
author_id: int,
title: str,
description: str,
created_at: datetime,
) -> None:
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO suggestions (guild_id, channel_id, message_id, author_id, title, description, status, created_at) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s) "
"ON DUPLICATE KEY UPDATE "
"guild_id=VALUES(guild_id), channel_id=VALUES(channel_id), author_id=VALUES(author_id), "
"title=VALUES(title), description=VALUES(description), status=VALUES(status), "
"denial_reason=NULL, reviewed_by=NULL, reviewed_at=NULL",
(
guild_id,
channel_id,
message_id,
author_id,
(title or "")[:120],
description or "",
"pending",
created_at.replace(tzinfo=None),
),
)
async def get_suggestion_by_message_id(pool, *, message_id: int) -> Optional[dict[str, Any]]:
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT id, guild_id, channel_id, message_id, author_id, title, description, status, denial_reason, reviewed_by, reviewed_at, created_at "
"FROM suggestions WHERE message_id=%s LIMIT 1",
(message_id,),
)
row = await cur.fetchone()
if not row:
return None
return {
"id": int(row[0]),
"guild_id": int(row[1]),
"channel_id": int(row[2]),
"message_id": int(row[3]),
"author_id": int(row[4]),
"title": row[5],
"description": row[6],
"status": row[7],
"denial_reason": row[8],
"reviewed_by": int(row[9]) if row[9] is not None else None,
"reviewed_at": row[10],
"created_at": row[11],
}
async def record_suggestion_review(
pool,
*,
message_id: int,
status: str,
reviewed_by: int,
reviewed_at: datetime,
denial_reason: Optional[str] = None,
) -> bool:
normalized_status = "approved" if status == "approved" else "denied"
normalized_reason = None if normalized_status == "approved" else (denial_reason or "")[:500]
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"UPDATE suggestions SET status=%s, denial_reason=%s, reviewed_by=%s, reviewed_at=%s "
"WHERE message_id=%s AND status=%s",
(
normalized_status,
normalized_reason,
reviewed_by,
reviewed_at.replace(tzinfo=None),
message_id,
"pending",
),
)
return bool(cur.rowcount)
async def record_badword_offense(
pool,
*,
user_id: int,
guild_id: int,
channel_id: int,
message_id: Optional[int],
content: str,
detected_words: Sequence[str],
created_at: datetime,
) -> None:
words = ",".join(sorted({w.lower() for w in detected_words if w}))
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO badword_offenses (user_id, guild_id, channel_id, message_id, content, detected_words, created_at) "
"VALUES (%s,%s,%s,%s,%s,%s,%s)",
(user_id, guild_id, channel_id, message_id, content, words, created_at.replace(tzinfo=None)),
)
async def record_ticket_open(
pool,
*,
guild_id: int,
channel_id: int,
category: str,
opener_id: int,
created_at: datetime,
) -> None:
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO tickets (guild_id, channel_id, category, opener_id, status, created_at) "
"VALUES (%s,%s,%s,%s,%s,%s) "
"ON DUPLICATE KEY UPDATE category=VALUES(category), opener_id=VALUES(opener_id), status=VALUES(status)",
(guild_id, channel_id, category[:64], opener_id, "open", created_at.replace(tzinfo=None)),
)
async def record_ticket_close(
pool,
*,
channel_id: int,
closed_by: Optional[int],
close_reason: str,
transcript_path: Optional[str],
closed_at: datetime,
) -> None:
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"UPDATE tickets SET status=%s, closed_at=%s, closed_by=%s, close_reason=%s, transcript_path=%s "
"WHERE channel_id=%s",
(
"closed",
closed_at.replace(tzinfo=None),
closed_by,
(close_reason or "")[:255],
transcript_path,
channel_id,
),
)
async def record_application_submit(
pool,
*,
guild_id: Optional[int],
user_id: int,
role_applied: str,
answers: Any,
submitted_at: datetime,
thread_id: Optional[int],
transcript_channel_id: Optional[int],
) -> None:
import json
answers_json = json.dumps(answers, ensure_ascii=False)
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO applications (guild_id, user_id, role_applied, answers_json, submitted_at, thread_id, transcript_channel_id) "
"VALUES (%s,%s,%s,%s,%s,%s,%s)",
(
guild_id,
user_id,
role_applied[:64],
answers_json,
submitted_at.replace(tzinfo=None),
thread_id,
transcript_channel_id,
),
)
async def record_mod_warn(
pool,
*,
guild_id: int,
user_id: int,
moderator_id: int,
reason: str,
created_at: datetime,
) -> None:
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO mod_warns (guild_id, user_id, moderator_id, reason, created_at) VALUES (%s,%s,%s,%s,%s)",
(guild_id, user_id, moderator_id, (reason or "No reason provided")[:512], created_at.replace(tzinfo=None)),
)
async def upsert_count_state(pool, *, guild_id: int, state_json: str, updated_at: datetime) -> None:
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO count_state (guild_id, state_json, updated_at) VALUES (%s,%s,%s) "
"ON DUPLICATE KEY UPDATE state_json=VALUES(state_json), updated_at=VALUES(updated_at)",
(guild_id, state_json, updated_at.replace(tzinfo=None)),
)
async def get_count_state(pool, *, guild_id: int) -> Optional[str]:
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT state_json FROM count_state WHERE guild_id=%s", (guild_id,))
row = await cur.fetchone()
return row[0] if row else None
async def record_invite_join(
pool,
*,
guild_id: int,
member_id: int,
inviter_id: Optional[int],
joined_at: datetime,
) -> None:
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO invite_joins (guild_id, member_id, inviter_id, joined_at) VALUES (%s,%s,%s,%s) "
"ON DUPLICATE KEY UPDATE inviter_id=VALUES(inviter_id), joined_at=VALUES(joined_at)",
(guild_id, member_id, inviter_id, joined_at.replace(tzinfo=None)),
)
async def get_invite_count(pool, *, guild_id: int, inviter_id: int) -> int:
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT COUNT(*) FROM invite_joins WHERE guild_id=%s AND inviter_id=%s",
(guild_id, inviter_id),
)
row = await cur.fetchone()
return int(row[0] if row else 0)
async def get_top_invites(pool, *, guild_id: int, limit: int = 10) -> list[tuple[int, int]]:
lim = max(1, min(int(limit), 25))
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT inviter_id, COUNT(*) AS c "
"FROM invite_joins WHERE guild_id=%s AND inviter_id IS NOT NULL "
"GROUP BY inviter_id ORDER BY c DESC LIMIT %s",
(guild_id, lim),
)
rows = await cur.fetchall() or []
return [(int(inviter_id), int(count)) for (inviter_id, count) in rows if inviter_id is not None]
async def badword_count_last_7d(pool, *, user_id: int, now: datetime) -> int:
window_start = now - __import__("datetime").timedelta(days=7)
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT COUNT(*) FROM badword_offenses WHERE user_id=%s AND created_at >= %s",
(user_id, window_start.replace(tzinfo=None)),
)
row = await cur.fetchone()
return int(row[0] if row else 0)
async def purge_badwords_older_than_7d(pool, *, now: datetime) -> int:
cutoff = now - __import__("datetime").timedelta(days=7)
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"DELETE FROM badword_offenses WHERE created_at < %s",
(cutoff.replace(tzinfo=None),),
)
return int(cur.rowcount or 0)