from aiohttp import web
|
|
import db
|
import mod
|
import perms as pm
|
from captcha import CAP_STATE
|
import cfg
|
from cfg import bot
|
from perms import P_BAN, P_CFG, P_MUTE, P_PERMS, P_UNBAN, P_UNMUTE, P_UNWARN, P_WARN, PERM_LABELS
|
from util import fmt_dt, fmt_dur, now_ts, parse_dur
|
from web.auth import is_staff
|
from web.render import render
|
|
# Соответствие действия и требуемого права.
|
ACTION_PERM = {
|
"warn": P_WARN,
|
"mute": P_MUTE,
|
"ban": P_BAN,
|
"unmute": P_UNMUTE,
|
"unban": P_UNBAN,
|
"unwarn": P_UNWARN,
|
}
|
|
|
async def allowed_chats(user_id: int):
|
if is_staff(user_id):
|
return await db.list_chats(active_only=True)
|
return await pm.adm_chats(bot, user_id)
|
|
|
async def _allowed_ids(user_id: int) -> set:
|
return {c["chat_id"] for c in await allowed_chats(user_id)}
|
|
|
async def _user(request) -> dict:
|
return request["user"]
|
|
|
async def dashboard(request) -> web.Response:
|
user = await _user(request)
|
chats = await allowed_chats(user["user_id"])
|
ids = {c["chat_id"] for c in chats}
|
names = {c["chat_id"]: c["title"] for c in chats}
|
st = await db.stats(now_ts())
|
captchas = [
|
{"chat_id": k[0], "user_id": k[1], "left": max(0, v.get("deadline", 0) - now_ts())}
|
for k, v in CAP_STATE.items()
|
if k[0] in ids
|
]
|
logs = [row for row in await db.list_log(limit=300) if row["chat_id"] in ids][:10]
|
return render(
|
request, "dashboard.html", active="dash", st=st, captchas=captchas, logs=logs, names=names
|
)
|
|
|
async def chats_page(request) -> web.Response:
|
user = await _user(request)
|
chats = await allowed_chats(user["user_id"])
|
cfgs = {c["chat_id"]: await db.get_chat_cfg(c["chat_id"]) for c in chats}
|
return render(request, "chats.html", active="chats", chats=chats, cfgs=cfgs)
|
|
|
async def chat_page(request) -> web.Response:
|
user = await _user(request)
|
chat_id = int(request.match_info["chat_id"])
|
if chat_id not in await _allowed_ids(user["user_id"]):
|
raise web.HTTPForbidden()
|
chat = await db.get_chat(chat_id) or {"chat_id": chat_id, "title": str(chat_id)}
|
cfg = await db.get_chat_cfg(chat_id)
|
|
admins = []
|
try:
|
for m in await bot.get_chat_administrators(chat_id):
|
u = m.user
|
admins.append(
|
{
|
"id": u.id,
|
"name": u.full_name,
|
"username": u.username or "",
|
"perms": await pm.perms_of(chat_id, u.id),
|
}
|
)
|
except Exception:
|
pass
|
|
warns = await db.list_warns(chat_id)
|
punish = await db.list_punish(chat_id, active_only=False)
|
return render(
|
request,
|
"chat.html",
|
active="chats",
|
chat=chat,
|
cfg=cfg,
|
admins=admins,
|
warns=warns,
|
punish=punish,
|
labels=PERM_LABELS,
|
fmt_dt=fmt_dt,
|
fmt_dur=fmt_dur,
|
)
|
|
|
async def chat_cfg(request) -> web.Response:
|
user = await _user(request)
|
data = await request.post()
|
chat_id = int(data["chat_id"])
|
if chat_id not in await _allowed_ids(user["user_id"]):
|
raise web.HTTPForbidden()
|
if not await pm.check_perm(chat_id, user["user_id"], P_CFG):
|
raise web.HTTPForbidden()
|
try:
|
fields = {
|
"btn_count": int(data["btn_count"]),
|
"timeout": int(data["timeout"]),
|
"max_attempts": int(data["max_attempts"]),
|
"warn_limit": int(data["warn_limit"]),
|
"warn_action": data["warn_action"],
|
"warn_duration": int(data["warn_duration"]),
|
}
|
except (KeyError, ValueError):
|
raise web.HTTPFound(f"/chats/{chat_id}?err=cfg")
|
if fields["warn_action"] not in ("mute", "ban"):
|
fields["warn_action"] = "mute"
|
await db.save_chat_cfg(chat_id, **fields)
|
raise web.HTTPFound(f"/chats/{chat_id}")
|
|
|
async def chat_perm(request) -> web.Response:
|
user = await _user(request)
|
data = await request.post()
|
chat_id = int(data["chat_id"])
|
target_id = int(data["user_id"])
|
perm = data["perm"]
|
allow = data.get("allow") == "1"
|
if chat_id not in await _allowed_ids(user["user_id"]):
|
raise web.HTTPForbidden()
|
if perm not in PERM_LABELS:
|
raise web.HTTPFound(f"/chats/{chat_id}")
|
await pm.set_perm(chat_id, user["user_id"], target_id, perm, allow)
|
raise web.HTTPFound(f"/chats/{chat_id}")
|
|
|
async def users_page(request) -> web.Response:
|
user = await _user(request)
|
chats = await allowed_chats(user["user_id"])
|
names = {c["chat_id"]: c["title"] for c in chats}
|
rows = []
|
for c in chats:
|
for p in await db.list_punish(c["chat_id"], active_only=True):
|
rows.append(p)
|
warns = []
|
for c in chats:
|
warns.extend(await db.list_warns(c["chat_id"]))
|
return render(
|
request, "users.html", active="users", rows=rows, warns=warns, names=names, fmt_dt=fmt_dt, fmt_dur=fmt_dur
|
)
|
|
|
async def user_page(request) -> web.Response:
|
user = await _user(request)
|
chat_id = int(request.match_info["chat_id"])
|
target_id = int(request.match_info["user_id"])
|
if chat_id not in await _allowed_ids(user["user_id"]):
|
raise web.HTTPForbidden()
|
chat = await db.get_chat(chat_id) or {"chat_id": chat_id, "title": str(chat_id)}
|
warns = await db.list_warns(chat_id, target_id)
|
hist = await db.hist_punish(chat_id, target_id)
|
return render(
|
request,
|
"user.html",
|
active="users",
|
chat=chat,
|
target_id=target_id,
|
warns=warns,
|
hist=hist,
|
fmt_dt=fmt_dt,
|
fmt_dur=fmt_dur,
|
)
|
|
|
async def action(request) -> web.Response:
|
user = await _user(request)
|
data = await request.post()
|
chat_id = int(data["chat_id"])
|
target_id = int(data["user_id"])
|
kind = data.get("kind", "")
|
reason = (data.get("reason") or "").strip()
|
name = (data.get("name") or str(target_id)).strip()
|
back = data.get("back") or f"/chats/{chat_id}"
|
|
if chat_id not in await _allowed_ids(user["user_id"]):
|
raise web.HTTPForbidden()
|
if kind not in ACTION_PERM:
|
raise web.HTTPFound(back)
|
# Себя (бота) наказывать нельзя.
|
if target_id == cfg.BOT_ID:
|
raise web.HTTPFound(back)
|
if not await pm.check_perm(chat_id, user["user_id"], ACTION_PERM[kind]):
|
raise web.HTTPForbidden()
|
|
if kind in ("mute", "ban"):
|
try:
|
dur = parse_dur(data.get("dur") or "-")
|
except ValueError:
|
dur = None
|
else:
|
dur = None
|
|
actor = user["user_id"]
|
if kind == "warn":
|
await mod.apply_warn(chat_id, target_id, name, actor, reason)
|
elif kind == "mute":
|
await mod.apply_mute(chat_id, target_id, name, dur, actor, reason)
|
elif kind == "ban":
|
await mod.apply_ban(chat_id, target_id, name, dur, actor, reason)
|
elif kind == "unmute":
|
await mod.apply_unmute(chat_id, target_id, name, actor, reason)
|
elif kind == "unban":
|
await mod.apply_unban(chat_id, target_id, name, actor, reason)
|
elif kind == "unwarn":
|
await mod.apply_unwarn(chat_id, target_id, name, actor)
|
raise web.HTTPFound(back)
|
|
|
async def captcha_page(request) -> web.Response:
|
user = await _user(request)
|
chats = await allowed_chats(user["user_id"])
|
names = {c["chat_id"]: c["title"] for c in chats}
|
ids = set(names)
|
rows = [
|
{"chat_id": k[0], "user_id": k[1], "left": max(0, v.get("deadline", 0) - now_ts())}
|
for k, v in CAP_STATE.items()
|
if k[0] in ids
|
]
|
return render(request, "captcha.html", active="captcha", rows=rows, names=names)
|
|
|
async def log_page(request) -> web.Response:
|
user = await _user(request)
|
chats = await allowed_chats(user["user_id"])
|
names = {c["chat_id"]: c["title"] for c in chats}
|
ids = set(names)
|
rows = [r for r in await db.list_log(limit=500) if r["chat_id"] in ids][:200]
|
return render(request, "log.html", active="log", rows=rows, names=names, fmt_dt=fmt_dt)
|