dbadmin.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. from __future__ import annotations
  2. import asyncio
  3. import re
  4. from datetime import UTC, datetime
  5. from secrets import token_hex
  6. from typing import Any
  7. from pymongo import ASCENDING, DESCENDING
  8. from wbb import BOT_PROFILE_ID, control_db, db
  9. admin_usersdb = control_db.admin_users
  10. admin_sessionsdb = control_db.admin_sessions
  11. auditdb = db.admin_audit_logs
  12. managed_chatsdb = db.managed_chats
  13. managed_chat_settingsdb = db.managed_chat_settings
  14. invite_linksdb = db.admin_invite_links
  15. recent_chat_membersdb = db.recent_chat_members
  16. member_identity_changesdb = db.member_identity_changes
  17. _index_lock = asyncio.Lock()
  18. _indexes_ready = False
  19. def utc_now() -> datetime:
  20. return datetime.now(UTC)
  21. async def ensure_admin_indexes() -> None:
  22. global _indexes_ready
  23. if _indexes_ready:
  24. return
  25. async with _index_lock:
  26. if _indexes_ready:
  27. return
  28. await admin_usersdb.create_index([("username", ASCENDING)], unique=True)
  29. await admin_sessionsdb.create_index([("token_hash", ASCENDING)], unique=True)
  30. await admin_sessionsdb.create_index("expires_at", expireAfterSeconds=0)
  31. await auditdb.create_index([("created_at", DESCENDING)])
  32. await auditdb.create_index(
  33. [("chat_id", ASCENDING), ("created_at", DESCENDING)]
  34. )
  35. await managed_chatsdb.create_index(
  36. [("bot_id", ASCENDING), ("chat_id", ASCENDING)], unique=True
  37. )
  38. await managed_chatsdb.create_index([("last_seen_at", DESCENDING)])
  39. await managed_chat_settingsdb.create_index(
  40. [("bot_id", ASCENDING), ("chat_id", ASCENDING)], unique=True
  41. )
  42. await invite_linksdb.create_index(
  43. [("bot_id", ASCENDING), ("chat_id", ASCENDING), ("created_at", DESCENDING)]
  44. )
  45. await recent_chat_membersdb.create_index(
  46. [
  47. ("bot_id", ASCENDING),
  48. ("chat_id", ASCENDING),
  49. ("user_id", ASCENDING),
  50. ],
  51. unique=True,
  52. )
  53. await recent_chat_membersdb.create_index(
  54. [("bot_id", ASCENDING), ("chat_id", ASCENDING), ("last_seen_at", DESCENDING)]
  55. )
  56. await member_identity_changesdb.create_index(
  57. [("bot_id", ASCENDING), ("chat_id", ASCENDING), ("observed_at", DESCENDING)]
  58. )
  59. await member_identity_changesdb.create_index(
  60. [
  61. ("bot_id", ASCENDING),
  62. ("chat_id", ASCENDING),
  63. ("user_id", ASCENDING),
  64. ("observed_at", DESCENDING),
  65. ]
  66. )
  67. _indexes_ready = True
  68. async def ensure_default_admin(
  69. *, username: str, password_hash: str
  70. ) -> dict[str, Any]:
  71. await ensure_admin_indexes()
  72. now = utc_now()
  73. await admin_usersdb.update_one(
  74. {"username": username},
  75. {
  76. "$setOnInsert": {
  77. "username": username,
  78. "password_hash": password_hash,
  79. "must_change_password": True,
  80. "failed_login_count": 0,
  81. "created_at": now,
  82. "updated_at": now,
  83. }
  84. },
  85. upsert=True,
  86. )
  87. return await admin_usersdb.find_one({"username": username})
  88. async def get_admin_user(username: str) -> dict[str, Any] | None:
  89. await ensure_admin_indexes()
  90. return await admin_usersdb.find_one({"username": username})
  91. async def record_login_failure(username: str) -> None:
  92. await ensure_admin_indexes()
  93. await admin_usersdb.update_one(
  94. {"username": username},
  95. {
  96. "$inc": {"failed_login_count": 1},
  97. "$set": {"last_failed_login_at": utc_now(), "updated_at": utc_now()},
  98. },
  99. )
  100. async def record_login_success(username: str) -> None:
  101. await ensure_admin_indexes()
  102. await admin_usersdb.update_one(
  103. {"username": username},
  104. {
  105. "$set": {
  106. "failed_login_count": 0,
  107. "last_login_at": utc_now(),
  108. "updated_at": utc_now(),
  109. }
  110. },
  111. )
  112. async def update_admin_password(username: str, password_hash: str) -> bool:
  113. await ensure_admin_indexes()
  114. result = await admin_usersdb.update_one(
  115. {"username": username},
  116. {
  117. "$set": {
  118. "password_hash": password_hash,
  119. "must_change_password": False,
  120. "password_updated_at": utc_now(),
  121. "updated_at": utc_now(),
  122. }
  123. },
  124. )
  125. if result.modified_count:
  126. await admin_sessionsdb.delete_many({"username": username})
  127. return result.modified_count == 1
  128. async def create_admin_session(
  129. *,
  130. username: str,
  131. token_hash: str,
  132. csrf_token: str,
  133. expires_at: datetime,
  134. remote_address: str,
  135. user_agent: str,
  136. ) -> None:
  137. await ensure_admin_indexes()
  138. now = utc_now()
  139. await admin_sessionsdb.insert_one(
  140. {
  141. "username": username,
  142. "token_hash": token_hash,
  143. "csrf_token": csrf_token,
  144. "remote_address": remote_address[:200],
  145. "user_agent": user_agent[:500],
  146. "created_at": now,
  147. "last_seen_at": now,
  148. "expires_at": expires_at,
  149. }
  150. )
  151. async def get_admin_session(token_hash: str) -> dict[str, Any] | None:
  152. await ensure_admin_indexes()
  153. session = await admin_sessionsdb.find_one(
  154. {"token_hash": token_hash, "expires_at": {"$gt": utc_now()}}
  155. )
  156. if not session:
  157. return None
  158. user = await get_admin_user(session["username"])
  159. if not user:
  160. return None
  161. await admin_sessionsdb.update_one(
  162. {"_id": session["_id"]}, {"$set": {"last_seen_at": utc_now()}}
  163. )
  164. return {**session, "user": user}
  165. async def revoke_admin_session(token_hash: str) -> None:
  166. await ensure_admin_indexes()
  167. await admin_sessionsdb.delete_one({"token_hash": token_hash})
  168. async def revoke_admin_sessions(username: str) -> None:
  169. await ensure_admin_indexes()
  170. await admin_sessionsdb.delete_many({"username": username})
  171. async def upsert_managed_chat(
  172. *,
  173. chat_id: int,
  174. title: str | None,
  175. username: str | None,
  176. chat_type: str,
  177. member_count: int | None = None,
  178. accessible: bool = True,
  179. bot_status: str | None = None,
  180. bot_privileges: list[str] | None = None,
  181. ) -> None:
  182. await ensure_admin_indexes()
  183. now = utc_now()
  184. values: dict[str, Any] = {
  185. "title": title or str(chat_id),
  186. "username": username,
  187. "type": chat_type,
  188. "accessible": accessible,
  189. "last_seen_at": now,
  190. "updated_at": now,
  191. }
  192. if member_count is not None:
  193. values["member_count"] = int(member_count)
  194. if bot_status is not None:
  195. values["bot_status"] = bot_status
  196. if bot_privileges is not None:
  197. values["bot_privileges"] = bot_privileges
  198. await managed_chatsdb.update_one(
  199. {"bot_id": BOT_PROFILE_ID, "chat_id": chat_id},
  200. {
  201. "$set": values,
  202. "$setOnInsert": {"bot_id": BOT_PROFILE_ID, "created_at": now},
  203. },
  204. upsert=True,
  205. )
  206. async def mark_managed_chat_unavailable(chat_id: int, reason: str) -> None:
  207. await ensure_admin_indexes()
  208. await managed_chatsdb.update_one(
  209. {"bot_id": BOT_PROFILE_ID, "chat_id": chat_id},
  210. {
  211. "$set": {
  212. "accessible": False,
  213. "last_error": reason[:500],
  214. "updated_at": utc_now(),
  215. }
  216. },
  217. upsert=True,
  218. )
  219. async def delete_unavailable_managed_chat(chat_id: int) -> bool:
  220. """Remove an unavailable chat from this bot's management index only."""
  221. await ensure_admin_indexes()
  222. result = await managed_chatsdb.delete_one(
  223. {
  224. "bot_id": BOT_PROFILE_ID,
  225. "chat_id": int(chat_id),
  226. "accessible": False,
  227. }
  228. )
  229. return result.deleted_count == 1
  230. async def managed_chat_exists(chat_id: int) -> bool:
  231. await ensure_admin_indexes()
  232. return (
  233. await managed_chatsdb.find_one(
  234. {"bot_id": BOT_PROFILE_ID, "chat_id": int(chat_id)}, {"_id": 1}
  235. )
  236. is not None
  237. )
  238. async def list_managed_chats(
  239. *, query: str = "", page: int = 1, page_size: int = 20
  240. ) -> tuple[list[dict[str, Any]], int]:
  241. await ensure_admin_indexes()
  242. filters: dict[str, Any] = {"bot_id": BOT_PROFILE_ID}
  243. query = query.strip()
  244. if query:
  245. if query.lstrip("-").isdigit():
  246. filters["chat_id"] = int(query)
  247. else:
  248. value = re.escape(query.lstrip("@"))
  249. filters["$or"] = [
  250. {"title": {"$regex": value, "$options": "i"}},
  251. {"username": {"$regex": value, "$options": "i"}},
  252. ]
  253. page = max(1, page)
  254. page_size = max(1, min(page_size, 100))
  255. total = await managed_chatsdb.count_documents(filters)
  256. cursor = (
  257. managed_chatsdb.find(filters)
  258. .sort([("accessible", DESCENDING), ("last_seen_at", DESCENDING)])
  259. .skip((page - 1) * page_size)
  260. .limit(page_size)
  261. )
  262. return [doc async for doc in cursor], total
  263. async def record_audit(
  264. *,
  265. source: str,
  266. actor_id: int | str | None,
  267. actor_name: str,
  268. action: str,
  269. chat_id: int | None = None,
  270. target_id: int | str | None = None,
  271. summary: str = "",
  272. success: bool = True,
  273. error: str = "",
  274. metadata: dict[str, Any] | None = None,
  275. ) -> None:
  276. await ensure_admin_indexes()
  277. await auditdb.insert_one(
  278. {
  279. "source": source,
  280. "actor_id": actor_id,
  281. "actor_name": actor_name,
  282. "action": action,
  283. "chat_id": chat_id,
  284. "target_id": target_id,
  285. "summary": summary[:1000],
  286. "success": bool(success),
  287. "error": error[:1000],
  288. "metadata": metadata or {},
  289. "bot_id": BOT_PROFILE_ID,
  290. "created_at": utc_now(),
  291. }
  292. )
  293. async def list_audit_logs(
  294. *,
  295. chat_id: int | None = None,
  296. action: str | None = None,
  297. page: int = 1,
  298. page_size: int = 20,
  299. ) -> tuple[list[dict[str, Any]], int]:
  300. await ensure_admin_indexes()
  301. filters: dict[str, Any] = {}
  302. if chat_id is not None:
  303. filters["chat_id"] = chat_id
  304. if action:
  305. filters["action"] = action
  306. page = max(1, page)
  307. page_size = max(1, min(page_size, 100))
  308. total = await auditdb.count_documents(filters)
  309. cursor = (
  310. auditdb.find(filters)
  311. .sort("created_at", DESCENDING)
  312. .skip((page - 1) * page_size)
  313. .limit(page_size)
  314. )
  315. return [doc async for doc in cursor], total
  316. async def get_managed_chat_settings(chat_id: int) -> dict[str, Any]:
  317. await ensure_admin_indexes()
  318. doc = await managed_chat_settingsdb.find_one(
  319. {"bot_id": BOT_PROFILE_ID, "chat_id": int(chat_id)}
  320. )
  321. return doc or {
  322. "chat_id": int(chat_id),
  323. "auto_replies": [],
  324. "blacklist_words": [],
  325. "welcome": {"enabled": False, "text": "", "media": None},
  326. "identity_monitor": {"enabled": False, "notify_in_chat": False},
  327. "captcha_enabled": False,
  328. "chatbot_enabled": False,
  329. "antiflood_enabled": True,
  330. }
  331. async def update_managed_chat_settings(
  332. chat_id: int, values: dict[str, Any]
  333. ) -> dict[str, Any]:
  334. await ensure_admin_indexes()
  335. allowed = {
  336. "auto_replies",
  337. "blacklist_words",
  338. "risk_control",
  339. "risk_rules",
  340. "identity_monitor",
  341. "welcome",
  342. "captcha_enabled",
  343. "chatbot_enabled",
  344. "antiflood_enabled",
  345. }
  346. update = {key: value for key, value in values.items() if key in allowed}
  347. now = utc_now()
  348. await managed_chat_settingsdb.update_one(
  349. {"bot_id": BOT_PROFILE_ID, "chat_id": int(chat_id)},
  350. {
  351. "$set": {**update, "updated_at": now},
  352. "$setOnInsert": {
  353. "bot_id": BOT_PROFILE_ID,
  354. "chat_id": int(chat_id),
  355. "created_at": now,
  356. },
  357. },
  358. upsert=True,
  359. )
  360. return await get_managed_chat_settings(chat_id)
  361. async def upsert_recent_chat_member(
  362. *,
  363. chat_id: int,
  364. user_id: int,
  365. username: str | None,
  366. first_name: str | None,
  367. last_name: str | None,
  368. is_bot: bool,
  369. ) -> None:
  370. await ensure_admin_indexes()
  371. now = utc_now()
  372. await recent_chat_membersdb.update_one(
  373. {
  374. "bot_id": BOT_PROFILE_ID,
  375. "chat_id": int(chat_id),
  376. "user_id": int(user_id),
  377. },
  378. {
  379. "$set": {
  380. "username": username,
  381. "first_name": first_name,
  382. "last_name": last_name,
  383. "is_bot": bool(is_bot),
  384. "last_seen_at": now,
  385. },
  386. "$inc": {"message_count": 1},
  387. "$setOnInsert": {
  388. "bot_id": BOT_PROFILE_ID,
  389. "chat_id": int(chat_id),
  390. "user_id": int(user_id),
  391. "created_at": now,
  392. },
  393. },
  394. upsert=True,
  395. )
  396. async def get_recent_chat_member(chat_id: int, user_id: int) -> dict[str, Any] | None:
  397. await ensure_admin_indexes()
  398. return await recent_chat_membersdb.find_one(
  399. {
  400. "bot_id": BOT_PROFILE_ID,
  401. "chat_id": int(chat_id),
  402. "user_id": int(user_id),
  403. }
  404. )
  405. async def record_member_identity_change(
  406. *,
  407. chat_id: int,
  408. user_id: int,
  409. before: dict[str, Any],
  410. after: dict[str, Any],
  411. changed_fields: list[str],
  412. ) -> dict[str, Any]:
  413. await ensure_admin_indexes()
  414. event = {
  415. "change_id": token_hex(10),
  416. "bot_id": BOT_PROFILE_ID,
  417. "chat_id": int(chat_id),
  418. "user_id": int(user_id),
  419. "before": before,
  420. "after": after,
  421. "changed_fields": changed_fields,
  422. "observed_at": utc_now(),
  423. }
  424. await member_identity_changesdb.insert_one(event)
  425. return event
  426. async def list_member_identity_changes(
  427. chat_id: int,
  428. *,
  429. page: int = 1,
  430. page_size: int = 20,
  431. ) -> tuple[list[dict[str, Any]], int]:
  432. await ensure_admin_indexes()
  433. filters = {"bot_id": BOT_PROFILE_ID, "chat_id": int(chat_id)}
  434. page = max(1, int(page))
  435. page_size = max(1, min(int(page_size), 100))
  436. total = await member_identity_changesdb.count_documents(filters)
  437. cursor = (
  438. member_identity_changesdb.find(filters)
  439. .sort("observed_at", DESCENDING)
  440. .skip((page - 1) * page_size)
  441. .limit(page_size)
  442. )
  443. return [item async for item in cursor], total
  444. async def list_recent_chat_members(
  445. chat_id: int,
  446. *,
  447. query: str = "",
  448. limit: int = 30,
  449. ) -> list[dict[str, Any]]:
  450. await ensure_admin_indexes()
  451. filters: dict[str, Any] = {
  452. "bot_id": BOT_PROFILE_ID,
  453. "chat_id": int(chat_id),
  454. "is_bot": {"$ne": True},
  455. }
  456. normalized_query = query.strip().lstrip("@")
  457. if normalized_query:
  458. if normalized_query.isdigit():
  459. filters["user_id"] = int(normalized_query)
  460. else:
  461. pattern = re.escape(normalized_query)
  462. filters["$or"] = [
  463. {"username": {"$regex": pattern, "$options": "i"}},
  464. {"first_name": {"$regex": pattern, "$options": "i"}},
  465. {"last_name": {"$regex": pattern, "$options": "i"}},
  466. ]
  467. cursor = (
  468. recent_chat_membersdb.find(filters)
  469. .sort("last_seen_at", DESCENDING)
  470. .limit(max(1, min(int(limit), 50)))
  471. )
  472. return [item async for item in cursor]
  473. async def store_invite_link(
  474. *, chat_id: int, invite_link: str, name: str, expires_at: datetime | None
  475. ) -> None:
  476. await ensure_admin_indexes()
  477. await invite_linksdb.update_one(
  478. {
  479. "bot_id": BOT_PROFILE_ID,
  480. "chat_id": int(chat_id),
  481. "invite_link": invite_link,
  482. },
  483. {
  484. "$set": {
  485. "name": name,
  486. "expires_at": expires_at,
  487. "revoked": False,
  488. "updated_at": utc_now(),
  489. },
  490. "$setOnInsert": {"bot_id": BOT_PROFILE_ID, "created_at": utc_now()},
  491. },
  492. upsert=True,
  493. )
  494. async def revoke_stored_invite_link(chat_id: int, invite_link: str) -> None:
  495. await ensure_admin_indexes()
  496. await invite_linksdb.update_one(
  497. {
  498. "bot_id": BOT_PROFILE_ID,
  499. "chat_id": int(chat_id),
  500. "invite_link": invite_link,
  501. },
  502. {"$set": {"revoked": True, "revoked_at": utc_now()}},
  503. )
  504. async def list_stored_invite_links(chat_id: int) -> list[dict[str, Any]]:
  505. await ensure_admin_indexes()
  506. cursor = invite_linksdb.find(
  507. {"bot_id": BOT_PROFILE_ID, "chat_id": int(chat_id)}
  508. ).sort(
  509. "created_at", DESCENDING
  510. )
  511. return [doc async for doc in cursor]
  512. async def dashboard_counts() -> dict[str, int]:
  513. await ensure_admin_indexes()
  514. return {
  515. "chats": await managed_chatsdb.count_documents({"accessible": {"$ne": False}}),
  516. "audit_events": await auditdb.count_documents({}),
  517. }