-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
419 lines (348 loc) · 13.7 KB
/
Copy pathdatabase.py
File metadata and controls
419 lines (348 loc) · 13.7 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
from __future__ import annotations
import aiosqlite
from datetime import datetime, timedelta
from typing import Any, Optional
import config
SCHEMA = """
CREATE TABLE IF NOT EXISTS templates (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_admin_id INTEGER NOT NULL,
name TEXT NOT NULL,
first_text TEXT,
first_photo_path TEXT,
first_button_text TEXT,
first_button_url TEXT,
mailing_enabled INTEGER DEFAULT 0,
mailing_text TEXT,
mailing_photo_path TEXT,
mailing_interval_minutes INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS bots (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_admin_id INTEGER NOT NULL,
token TEXT UNIQUE NOT NULL,
tg_bot_id INTEGER,
username TEXT,
full_name TEXT,
template_id INTEGER NOT NULL,
is_alive INTEGER DEFAULT 1,
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
silent_until TIMESTAMP,
FOREIGN KEY (template_id) REFERENCES templates(id)
);
CREATE TABLE IF NOT EXISTS bot_users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
bot_id INTEGER NOT NULL,
tg_user_id INTEGER NOT NULL,
username TEXT,
first_name TEXT,
language_code TEXT,
geo TEXT,
started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(bot_id, tg_user_id),
FOREIGN KEY (bot_id) REFERENCES bots(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS report_bots (
admin_id INTEGER PRIMARY KEY,
token TEXT NOT NULL,
chat_id INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_templates_owner ON templates(owner_admin_id);
CREATE INDEX IF NOT EXISTS idx_bots_owner ON bots(owner_admin_id);
CREATE INDEX IF NOT EXISTS idx_bot_users_bot ON bot_users(bot_id);
CREATE INDEX IF NOT EXISTS idx_bot_users_started ON bot_users(bot_id, started_at);
CREATE INDEX IF NOT EXISTS idx_bot_users_geo ON bot_users(bot_id, geo);
"""
SILENT_MINUTES_AFTER_ADD = 40
async def init() -> None:
async with aiosqlite.connect(config.DB_PATH) as db:
await db.execute("PRAGMA foreign_keys = ON")
await db.executescript(SCHEMA)
cur = await db.execute("PRAGMA table_info(bots)")
cols = {row[1] for row in await cur.fetchall()}
if "silent_until" not in cols:
await db.execute("ALTER TABLE bots ADD COLUMN silent_until TIMESTAMP")
await db.commit()
def _conn():
conn = aiosqlite.connect(config.DB_PATH)
return conn
async def _open():
db = await _conn()
await db.execute("PRAGMA foreign_keys = ON")
return db
# ---------- templates ----------
async def create_template(
owner_admin_id: int,
name: str,
first_text: Optional[str],
first_photo_path: Optional[str],
first_button_text: Optional[str],
first_button_url: Optional[str],
mailing_enabled: bool,
mailing_text: Optional[str],
mailing_photo_path: Optional[str],
mailing_interval_minutes: Optional[int],
) -> int:
async with _conn() as db:
cur = await db.execute(
"""INSERT INTO templates
(owner_admin_id, name, first_text, first_photo_path, first_button_text, first_button_url,
mailing_enabled, mailing_text, mailing_photo_path, mailing_interval_minutes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
owner_admin_id, name, first_text, first_photo_path, first_button_text, first_button_url,
int(mailing_enabled), mailing_text, mailing_photo_path, mailing_interval_minutes,
),
)
await db.commit()
return cur.lastrowid
async def list_templates(owner_admin_id: int) -> list[dict[str, Any]]:
async with _conn() as db:
db.row_factory = aiosqlite.Row
cur = await db.execute(
"SELECT * FROM templates WHERE owner_admin_id = ? ORDER BY id DESC",
(owner_admin_id,),
)
rows = await cur.fetchall()
return [dict(r) for r in rows]
async def get_template(template_id: int) -> Optional[dict[str, Any]]:
async with _conn() as db:
db.row_factory = aiosqlite.Row
cur = await db.execute("SELECT * FROM templates WHERE id = ?", (template_id,))
r = await cur.fetchone()
return dict(r) if r else None
async def bulk_update_button_url(owner_admin_id: int, new_url: str) -> int:
"""Меняет first_button_url во всех шаблонах владельца, у которых уже есть
кнопка (задан first_button_text). Возвращает число обновлённых строк."""
async with _conn() as db:
cur = await db.execute(
"""UPDATE templates
SET first_button_url = ?
WHERE owner_admin_id = ?
AND first_button_text IS NOT NULL
AND first_button_text != ''""",
(new_url, owner_admin_id),
)
await db.commit()
return cur.rowcount
async def delete_template(template_id: int, owner_admin_id: int) -> None:
async with _conn() as db:
await db.execute(
"DELETE FROM templates WHERE id = ? AND owner_admin_id = ?",
(template_id, owner_admin_id),
)
await db.commit()
async def update_template_fields(template_id: int, owner_admin_id: int, **fields: Any) -> None:
"""Обновляет любые поля шаблона владельца. Ключи — реальные имена колонок."""
if not fields:
return
allowed = {
"first_text", "first_photo_path", "first_button_text", "first_button_url",
"mailing_enabled", "mailing_text", "mailing_photo_path", "mailing_interval_minutes",
}
safe = {k: v for k, v in fields.items() if k in allowed}
if not safe:
return
sets = ", ".join(f"{k} = ?" for k in safe)
params = list(safe.values()) + [template_id, owner_admin_id]
async with _conn() as db:
await db.execute(
f"UPDATE templates SET {sets} WHERE id = ? AND owner_admin_id = ?",
params,
)
await db.commit()
async def bots_using_template(template_id: int) -> list[dict[str, Any]]:
async with _conn() as db:
db.row_factory = aiosqlite.Row
cur = await db.execute(
"SELECT * FROM bots WHERE template_id = ? AND is_alive = 1",
(template_id,),
)
rows = await cur.fetchall()
return [dict(r) for r in rows]
async def update_bot_template(bot_id: int, owner_admin_id: int, template_id: int) -> bool:
async with _conn() as db:
cur = await db.execute(
"UPDATE bots SET template_id = ? WHERE id = ? AND owner_admin_id = ?",
(template_id, bot_id, owner_admin_id),
)
await db.commit()
return cur.rowcount > 0
# ---------- bots (workers) ----------
async def add_bot(
owner_admin_id: int,
token: str,
tg_bot_id: int,
username: str,
full_name: str,
template_id: int,
silent_minutes: int = SILENT_MINUTES_AFTER_ADD,
) -> int:
silent_until = (
(datetime.utcnow() + timedelta(minutes=silent_minutes)).strftime("%Y-%m-%d %H:%M:%S")
if silent_minutes > 0
else None
)
async with _conn() as db:
cur = await db.execute(
"""INSERT INTO bots (owner_admin_id, token, tg_bot_id, username, full_name,
template_id, is_alive, silent_until)
VALUES (?, ?, ?, ?, ?, ?, 1, ?)""",
(owner_admin_id, token, tg_bot_id, username, full_name, template_id, silent_until),
)
await db.commit()
return cur.lastrowid
async def is_bot_silent(bot_id: int) -> bool:
async with _conn() as db:
cur = await db.execute("SELECT silent_until FROM bots WHERE id = ?", (bot_id,))
row = await cur.fetchone()
if not row or not row[0]:
return False
try:
until = datetime.strptime(row[0], "%Y-%m-%d %H:%M:%S")
except (TypeError, ValueError):
return False
return datetime.utcnow() < until
async def get_bot(bot_id: int) -> Optional[dict[str, Any]]:
async with _conn() as db:
db.row_factory = aiosqlite.Row
cur = await db.execute("SELECT * FROM bots WHERE id = ?", (bot_id,))
r = await cur.fetchone()
return dict(r) if r else None
async def get_bot_by_tg_id(tg_bot_id: int) -> Optional[dict[str, Any]]:
async with _conn() as db:
db.row_factory = aiosqlite.Row
cur = await db.execute("SELECT * FROM bots WHERE tg_bot_id = ?", (tg_bot_id,))
r = await cur.fetchone()
return dict(r) if r else None
async def get_bot_by_token(token: str) -> Optional[dict[str, Any]]:
async with _conn() as db:
db.row_factory = aiosqlite.Row
cur = await db.execute("SELECT * FROM bots WHERE token = ?", (token,))
r = await cur.fetchone()
return dict(r) if r else None
async def list_bots(
owner_admin_id: Optional[int] = None,
alive_only: bool = False,
) -> list[dict[str, Any]]:
q = "SELECT * FROM bots"
where = []
params: list[Any] = []
if owner_admin_id is not None:
where.append("owner_admin_id = ?")
params.append(owner_admin_id)
if alive_only:
where.append("is_alive = 1")
if where:
q += " WHERE " + " AND ".join(where)
q += " ORDER BY id DESC"
async with _conn() as db:
db.row_factory = aiosqlite.Row
cur = await db.execute(q, params)
rows = await cur.fetchall()
return [dict(r) for r in rows]
async def mark_bot_dead(bot_id: int) -> None:
async with _conn() as db:
await db.execute("UPDATE bots SET is_alive = 0 WHERE id = ?", (bot_id,))
await db.commit()
async def delete_bot(bot_id: int, owner_admin_id: int) -> None:
async with _conn() as db:
await db.execute("PRAGMA foreign_keys = ON")
await db.execute(
"DELETE FROM bot_users WHERE bot_id = ? AND bot_id IN (SELECT id FROM bots WHERE owner_admin_id = ?)",
(bot_id, owner_admin_id),
)
await db.execute(
"DELETE FROM bots WHERE id = ? AND owner_admin_id = ?",
(bot_id, owner_admin_id),
)
await db.commit()
async def delete_bot_user(bot_id: int, tg_user_id: int) -> None:
async with _conn() as db:
await db.execute(
"DELETE FROM bot_users WHERE bot_id = ? AND tg_user_id = ?",
(bot_id, tg_user_id),
)
await db.commit()
# ---------- bot_users ----------
async def record_bot_user(
bot_id: int,
tg_user_id: int,
username: Optional[str],
first_name: Optional[str],
language_code: Optional[str],
geo: str,
) -> bool:
async with _conn() as db:
cur = await db.execute(
"""INSERT OR IGNORE INTO bot_users
(bot_id, tg_user_id, username, first_name, language_code, geo)
VALUES (?, ?, ?, ?, ?, ?)""",
(bot_id, tg_user_id, username, first_name, language_code, geo),
)
await db.commit()
return cur.rowcount > 0
async def get_bot_users(bot_id: int) -> list[dict[str, Any]]:
async with _conn() as db:
db.row_factory = aiosqlite.Row
cur = await db.execute("SELECT * FROM bot_users WHERE bot_id = ?", (bot_id,))
rows = await cur.fetchall()
return [dict(r) for r in rows]
async def count_bot_users(bot_id: int) -> int:
async with _conn() as db:
cur = await db.execute("SELECT COUNT(*) FROM bot_users WHERE bot_id = ?", (bot_id,))
(n,) = await cur.fetchone()
return int(n)
async def geo_breakdown_for_bot(bot_id: int) -> list[tuple[str, int]]:
async with _conn() as db:
cur = await db.execute(
"SELECT geo, COUNT(*) FROM bot_users WHERE bot_id = ? GROUP BY geo ORDER BY 2 DESC",
(bot_id,),
)
return [(g, int(c)) for g, c in await cur.fetchall()]
# ---------- per-admin aggregate stats ----------
async def total_users_for_admin(admin_id: int) -> int:
async with _conn() as db:
cur = await db.execute(
"""SELECT COUNT(*) FROM bot_users
WHERE bot_id IN (SELECT id FROM bots WHERE owner_admin_id = ?)""",
(admin_id,),
)
(n,) = await cur.fetchone()
return int(n)
async def users_since_for_admin(admin_id: int, hours_ago: int) -> int:
since = (datetime.utcnow() - timedelta(hours=hours_ago)).strftime("%Y-%m-%d %H:%M:%S")
async with _conn() as db:
cur = await db.execute(
"""SELECT COUNT(*) FROM bot_users
WHERE started_at >= ?
AND bot_id IN (SELECT id FROM bots WHERE owner_admin_id = ?)""",
(since, admin_id),
)
(n,) = await cur.fetchone()
return int(n)
async def geo_breakdown_for_admin(admin_id: int) -> list[tuple[str, int]]:
async with _conn() as db:
cur = await db.execute(
"""SELECT geo, COUNT(*) FROM bot_users
WHERE bot_id IN (SELECT id FROM bots WHERE owner_admin_id = ?)
GROUP BY geo ORDER BY 2 DESC""",
(admin_id,),
)
return [(g, int(c)) for g, c in await cur.fetchall()]
# ---------- report bots (per-admin) ----------
async def set_report_bot(admin_id: int, token: str, chat_id: int) -> None:
async with _conn() as db:
await db.execute(
"""INSERT INTO report_bots (admin_id, token, chat_id) VALUES (?, ?, ?)
ON CONFLICT(admin_id) DO UPDATE SET token=excluded.token, chat_id=excluded.chat_id""",
(admin_id, token, chat_id),
)
await db.commit()
async def get_report_bot(admin_id: int) -> Optional[dict[str, Any]]:
async with _conn() as db:
db.row_factory = aiosqlite.Row
cur = await db.execute("SELECT * FROM report_bots WHERE admin_id = ?", (admin_id,))
r = await cur.fetchone()
return dict(r) if r else None