"""Admin-only tools (English on purpose). Admin ids come from the ADMIN_IDS secret."""
import html
import logging
import time
from datetime import datetime, timedelta, timezone
from uuid import uuid4
from typing import Optional
from aiogram import F, Router
from aiogram.filters import BaseFilter, Command, CommandObject
from aiogram.types import BufferedInputFile, CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message, ReactionTypeEmoji
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import get_settings
from app.core.catalog import KINDS, STREAMS
from app.core.seed_courses import FRESHMAN_COURSES
from app.db.models import User
from app.db.repos import library as repo
from app.db.repos import stats as stats_repo
from app.db.repos import submissions as sub_repo
from app.core import season as clock
from app.db.repos import users as users_repo
from app.bot import manual
from app.services import growth
from app.services import xp_rules as R
from app.services import library as library_service
from app.services import smart_ingest
from app.services import watermark as wm
from app.services import season as season_service
from app.services import xp as xp_service
from app.services.ingest import KIND_ALIASES, clean_title, parse_caption
log = logging.getLogger(__name__)
class IsAdmin(BaseFilter):
async def __call__(self, event: Message | CallbackQuery) -> bool:
return bool(event.from_user and event.from_user.id in get_settings().admin_id_set)
router = Router()
router.message.filter(IsAdmin())
router.callback_query.filter(IsAdmin())
def facts() -> dict:
"""Numbers shown in the manual and the channel announcement come from the live settings."""
cfg = get_settings()
return dict(
prizes_enabled=cfg.prizes_enabled, prizes=cfg.prize_list, raffle=cfg.prize_raffle, min_days=cfg.min_active_days,
min_xp=cfg.min_week_xp, contrib_xp=cfg.contribution_xp, contrib_bonus=cfg.contribution_bonus_xp,
contrib_cap=cfg.contribution_weekly_cap, daily_cap=R.DAILY_CAP, ref_join=R.REFERRAL_JOIN_XP,
ref_qualified=R.REFERRAL_QUALIFIED_XP, ref_weekly=R.REFERRAL_QUALIFIED_PER_WEEK,
)
ADDCOURSE_USAGE = (
"Usage: /addcourse <natural|social|all> <year 0-5> <code or -> <name...>\n"
"Example: /addcourse natural 1 Chem1012 Organic Chemistry\n"
"Full manual: /help"
)
@router.message(Command("help", "admin"))
async def admin_help(message: Message) -> None:
for chunk in manual.render(facts()):
await message.answer(chunk)
@router.message(Command("announce"))
async def announce(message: Message) -> None:
me = await message.bot.me()
text = manual.announcement_text(facts(), me.username)
await message.answer(text, parse_mode=None) # plain text: easy to copy as well
channel = get_settings().gate_list[0]
await message.answer(
f"π This is the announcement for {channel}. Post it to the channel from here?",
reply_markup=InlineKeyboardMarkup(inline_keyboard=[[
InlineKeyboardButton(text=f"π£ Post to {channel}", callback_data="an:post"),
InlineKeyboardButton(text="Cancel", callback_data="an:no"),
]]),
)
@router.callback_query(F.data.in_({"an:post", "an:no"}))
async def announce_button(call: CallbackQuery) -> None:
await call.answer()
if call.data == "an:no":
await call.message.edit_text("OK, not posted.")
return
me = await call.bot.me()
channel = get_settings().gate_list[0]
try:
await call.bot.send_message(
channel,
manual.announcement_text(facts(), me.username),
parse_mode=None,
reply_markup=InlineKeyboardMarkup(inline_keyboard=[[
InlineKeyboardButton(text="π Open the bot", url=growth.deep_link(me.username, "channel"))
]]),
)
await call.message.edit_text(f"β
Posted to {channel}. Pin it there.")
except Exception as exc:
await call.message.edit_text(
f"β Could not post to {channel}: {type(exc).__name__}: {exc}\n"
"The bot needs to be an admin of the channel with the right to post messages."
)
@router.message(Command("ping"))
async def ping(message: Message, session: AsyncSession) -> None:
"""Where does the time go? DB #1 includes connecting; DB #2 is the pure round-trip."""
t0 = time.perf_counter()
await session.execute(text("SELECT 1"))
db1 = (time.perf_counter() - t0) * 1000
t0 = time.perf_counter()
await session.execute(text("SELECT 1"))
db2 = (time.perf_counter() - t0) * 1000
t0 = time.perf_counter()
await message.bot.get_me()
tg = (time.perf_counter() - t0) * 1000
await message.answer(
f"π DB #1 (with checkout): {db1:.0f} ms\n"
f"DB #2 (pure round-trip): {db2:.0f} ms\n"
f"Telegram API: {tg:.0f} ms"
)
@router.message(Command("season"))
async def season_view(message: Message, session: AsyncSession) -> None:
await message.answer(await season_service.preview(session, clock.week_key()))
@router.message(Command("winners"))
async def winners(message: Message, session: AsyncSession) -> None:
await message.answer(await season_service.last_results_text(session))
@router.message(Command("closeweek"))
async def close_week_now(message: Message, command: CommandObject, session: AsyncSession) -> None:
week = (command.args or "").strip()
if len(week) != 7 or week >= clock.week_key():
await message.answer("Usage: /closeweek 2026W41 (a week that has already ended)")
return
if await season_service.xp_repo.season_closed(session, week):
await message.answer("That week is already closed. See /winners")
return
await message.answer(await season_service.close_week(session, message.bot, week))
@router.message(Command("give"))
async def give_xp(message: Message, command: CommandObject, session: AsyncSession) -> None:
parts = (command.args or "").split()
if len(parts) != 2 or not parts[0].isdigit() or not parts[1].isdigit() or not 0 < int(parts[1]) <= 500:
await message.answer("Usage: /give <user_id> <xp 1-500>")
return
target = await users_repo.get(session, int(parts[0]))
if not target:
await message.answer("No such user.")
return
res = await xp_service.award(session, target, "admin", int(parts[1]), ref=f"adm:{uuid4().hex[:8]}", capped=False)
session.sync_session.info.setdefault("invalidate", set()).add(target.id)
await message.answer(f"β
+{res.amount} XP to id{target.id}")
if res.leveled_up:
await xp_service.announce_level(message.bot, target, res.new_level)
@router.message(Command("trust"))
async def set_trust(message: Message, command: CommandObject, session: AsyncSession) -> None:
parts = (command.args or "").split()
try:
uid, delta = int(parts[0]), int(parts[1])
except (IndexError, ValueError):
await message.answer("Usage: /trust <user_id> <delta, e.g. -30>")
return
ok = await xp_service.adjust_trust(session, uid, delta, "admin")
await message.answer("β
Trust updated." if ok else "Nothing changed.")
@router.message(Command("addcourse"))
async def add_course(message: Message, command: CommandObject, session: AsyncSession) -> None:
parts = (command.args or "").split(maxsplit=3)
if len(parts) < 4 or not parts[1].isdigit() or parts[0] not in (*STREAMS, "all"):
await message.answer(ADDCOURSE_USAGE)
return
stream = None if parts[0] == "all" else parts[0]
year = int(parts[1]) or None
code = None if parts[2] == "-" else parts[2]
course = await repo.add_course(session, name=parts[3].strip(), code=code, stream=stream, year=year)
library_service.invalidate_courses()
await message.answer(f"β
Course #{course.id} added: {course.code} Β· {course.name}")
@router.message(Command("seedcourses"))
async def seed_courses(message: Message, session: AsyncSession) -> None:
added = skipped = 0
for stream, year, semester, code, name in FRESHMAN_COURSES:
stream = None if stream == "all" else stream
if await repo.find_course(session, name, stream, year):
skipped += 1
continue
await repo.add_course(session, name=name, code=code, stream=stream, year=year, semester=semester)
added += 1
library_service.invalidate_courses()
await message.answer(f"β
Added {added} courses, skipped {skipped} that already existed.\nSee /courses for ids.")
@router.message(Command("delcourse"))
async def del_course(message: Message, command: CommandObject, session: AsyncSession) -> None:
parts = (command.args or "").split()
if not parts or not parts[0].isdigit() or (len(parts) > 1 and not parts[1].isdigit()):
await message.answer("Usage: /delcourse <id> [move_files_to_id]")
return
cid, target = int(parts[0]), (int(parts[1]) if len(parts) > 1 else None)
course = await repo.get_course(session, cid)
if not course:
await message.answer(f"No course with id {cid}. See /courses")
return
files = await repo.count_course_files(session, cid)
if files and target is None:
await message.answer(
f"β Course #{cid} β{course.name}β still has {files} file(s), so I did not delete it.\n"
f"Move them and delete in one go: /delcourse {cid} <other_course_id>"
)
return
if target is not None:
if target == cid or not await repo.get_course(session, target):
await message.answer("The target course must exist and be a different course.")
return
await repo.move_course_files(session, cid, target)
await repo.delete_course(session, cid)
session.sync_session.info["wrote"] = True
library_service.invalidate_courses()
moved = f" ({files} file(s) moved to #{target})" if files else ""
await message.answer(f"π Deleted course #{cid} β{course.name}β{moved}.")
@router.message(Command("growth"))
async def growth_report(message: Message, session: AsyncSession) -> None:
since = datetime.now(timezone.utc) - timedelta(days=7)
r = await stats_repo.growth_report(session, since)
days = " ".join(f"{d[5:]}: {n}" for d, n in r["by_day"]) or "no new users"
lines = [
"π Growth",
f"Total users: {r['total']} Β· groups using the bot: {r['groups']}",
f"New users per day (7 days): {days}",
"\nWhere they come from\njoined β in channel + forum β finished setup β used the bot on 3+ days",
]
for source, joined, gate_ok, onboarded, active in r["by_source"]:
lines.append(f"β’ {source}: {joined} β {gate_ok} β {onboarded} β {active} ({round(100 * onboarded / joined)}% finished setup)")
if r["stuck"]:
lines.append("\nStuck at the join step (started the bot but are not in all required places yet)")
for missing, n in r["stuck"]:
what = ("not recorded yet (they have not tapped anything since this was added)" if missing == "unknown"
else "still has to join: " + " + ".join("@" + h for h in missing.split(",")))
lines.append(f"β’ {n}: {what}")
lines.append(
"\nSources: organic = found the bot by name or search; link = a shared course/file link; referral = a "
"friend's invite; poster / channel / group / any tag = links you made; before tracking = students from before "
"sources were recorded."
)
lines.append("\nMake a new trackable link by putting a tag after ?start= , e.g. t.me/YourBot?start=dorm5")
await message.answer("\n".join(lines))
@router.message(Command("poster"))
async def poster(message: Message, command: CommandObject) -> None:
from app.services.poster import make_poster_pdf
me = await message.bot.me()
tag = growth.safe_tag(command.args)
link = growth.deep_link(me.username, tag)
pdf = make_poster_pdf(link, me.username, get_settings().watermark_link)
await message.answer_document(
BufferedInputFile(pdf, filename=f"poster-{tag}.pdf"),
caption=f"π¨ Print it. The QR opens {link}\nSource tag: {tag}. See who came from it in /growth. "
"One poster per place works best: /poster dorm5, /poster cafeteria β¦",
)
# the same QR as images, to drop into your own Amharic design (Canva, Word, Photoshop...)
from app.services.qr import qr_png
await message.answer_document(
BufferedInputFile(qr_png(link), filename=f"qr-{tag}.png"),
caption="π³ QR on white (safest to print). Keep a clear white margin around it and do not shrink it below ~3 cm.",
)
await message.answer_document(
BufferedInputFile(qr_png(link, transparent=True), filename=f"qr-{tag}-transparent.png"),
caption="π³ QR with a transparent background: place it on a LIGHT area of your design.",
)
@router.message(Command("emptycourses"))
async def empty_courses(message: Message, session: AsyncSession) -> None:
items = await repo.empty_courses(session)
if not items:
await message.answer("β
Every course has at least one file.")
return
lines = [f"{c.id} Β· {c.stream or 'all'} Β· {c.code or '-'} Β· {c.name}" for c in items]
await message.answer(
f"π {len(items)} courses have no files:\n" + "\n".join(lines)
+ "\n\nβΉοΈ Students already do NOT see empty courses, so deleting is optional. "
"Deleted courses can be re-added with /seedcourses, but until then new files for them "
"cannot be sorted automatically.",
reply_markup=InlineKeyboardMarkup(inline_keyboard=[[
InlineKeyboardButton(text=f"π Delete these {len(items)}", callback_data="pr:y"),
InlineKeyboardButton(text="Keep them", callback_data="pr:n"),
]]),
)
@router.callback_query(F.data.in_({"pr:y", "pr:n"}))
async def prune_button(call: CallbackQuery, session: AsyncSession) -> None:
await call.answer()
if call.data == "pr:n":
text = "π Kept."
else:
items = await repo.empty_courses(session) # re-read: a file may have arrived meanwhile
for course in items:
await repo.delete_course(session, course.id)
session.sync_session.info["wrote"] = True
library_service.invalidate_courses()
text = f"π Deleted {len(items)} empty courses. Run /courses to see what is left."
if call.message:
try:
await call.message.edit_text(text)
except Exception:
await call.message.answer(text)
@router.message(Command("gatecheck"))
async def gate_check_cmd(message: Message) -> None:
from aiogram.enums import ChatMemberStatus
from app.services import gate as gate_service
me = await message.bot.me()
lines = ["π Join-gate check (users must join ALL of these)"]
for handle in gate_service.channels():
try:
chat = await message.bot.get_chat(handle)
member = await message.bot.get_chat_member(handle, me.id)
is_admin = member.status in (ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.CREATOR)
lines.append(
f"{'β
' if is_admin else 'β'} {handle} Β· {chat.title} Β· bot is {member.status}"
+ ("" if is_admin else " β make the bot an ADMIN there")
)
except Exception as exc:
lines.append(f"β {handle} Β· {type(exc).__name__}: {exc}")
await message.answer("\n".join(lines))
@router.message(Command("courses"))
async def list_courses(message: Message, session: AsyncSession) -> None:
courses = await repo.all_courses(session)
if not courses:
await message.answer("No courses yet. Use /addcourse")
return
lines = [
f"{c.id} Β· {c.stream or 'all'}/{c.year or 'all'} Β· {c.code or '-'} Β· {c.name}" for c in courses
]
chunk = ""
for line in lines:
if len(chunk) + len(line) > 3500:
await message.answer(chunk)
chunk = ""
chunk += line + "\n"
if chunk:
await message.answer(chunk)
@router.message(Command("stats"))
async def stats(message: Message, session: AsyncSession) -> None:
s = await stats_repo.overview(session, clock.now_et().date())
await message.answer(
"π Stats\n"
f"Users: {s['users']} (verified members {s['gate_passed']}, finished setup {s['onboarded']})\n"
f"Active today: {s['active_today']}\n"
f"Referrals: {s['referrals']}\n"
f"Student files waiting: {await sub_repo.pending_total(session)}\n"
f"Courses: {s['courses']} Β· Files: {s['materials']} Β· Downloads: {s['downloads']}"
)
def _extract(message: Message) -> Optional[tuple[str, str, str, Optional[str], Optional[int]]]:
"""-> (file_type, file_id, file_unique_id, file_name, size)"""
if message.document:
d = message.document
return "document", d.file_id, d.file_unique_id, d.file_name, d.file_size
if message.video:
v = message.video
return "video", v.file_id, v.file_unique_id, v.file_name, v.file_size
if message.audio:
a = message.audio
return "audio", a.file_id, a.file_unique_id, a.file_name or a.title, a.file_size
if message.photo:
p = message.photo[-1]
return "photo", p.file_id, p.file_unique_id, None, p.file_size
return None
# admin_id -> {"course_id": int, "kind": str, "saved": int, "dupes": int}
_upload_mode: dict[int, dict] = {}
@router.message(Command("upload"))
async def upload_on(message: Message, command: CommandObject, session: AsyncSession) -> None:
parts = (command.args or "").split()
kind = KIND_ALIASES.get(parts[1].lower().lstrip("#")) if len(parts) == 2 else None
if len(parts) != 2 or not parts[0].isdigit() or not kind:
await message.answer("Usage: /upload <course_id> <slide|exam|note|book>\nSee /courses for ids.")
return
course = await repo.get_course(session, int(parts[0]))
if not course:
await message.answer(f"β No course with id {parts[0]}. See /courses")
return
_upload_mode[message.from_user.id] = {"course_id": course.id, "kind": kind, "saved": 0, "dupes": 0}
await message.answer(
f"π₯ Forced mode ON: {course.name} Β· {kind}\n"
"Every file goes to this course. π = saved. Finish: /done\n"
"(Normally you do NOT need this: just send files and the bot sorts them.)"
)
@router.message(Command("done"))
async def upload_off(message: Message) -> None:
mode = _upload_mode.pop(message.from_user.id, None)
if not mode:
await message.answer("Forced mode was not on.")
return
await message.answer(f"β
Done. Saved {mode['saved']} files, skipped {mode['dupes']} duplicates.")
async def _ack(message: Message) -> None:
try:
await message.react([ReactionTypeEmoji(emoji="π")])
except Exception: # reactions unavailable: stay quiet
pass
def _mb(size: Optional[int]) -> str:
return f"{size / 1048576:.1f} MB" if size else "?"
def _hdr(file_name: Optional[str]) -> str:
"""Every reply names the file it is about (an album of 10 files gives 10 replies)."""
return f"π {html.escape((file_name or 'file')[:70])}\n"
def _course_label(c) -> str:
return f"{c.code + ' ' if c.code else ''}{c.name}" if c else "β unsorted"
def _line(o: smart_ingest.Outcome) -> str:
m = o.material
text = f"{_hdr(o.file_name)}β
#{m.id} Β· {_course_label(o.course)} Β· {o.kind}{' Β· π' if m.watermarked else ''}\nβ{o.title}β"
if m.pages:
text += f" Β· {m.pages} p"
for note in o.notes:
text += f"\nβ οΈ {note}"
return text
def _suggestion_rows(o: smart_ingest.Outcome) -> list:
mid = o.material.id
return [
[InlineKeyboardButton(text=f"π {_course_label(c)}"[:60], callback_data=f"rv:c:{mid}:{c.id}")]
for c in o.suggestions
]
def _kb_review(o: smart_ingest.Outcome) -> InlineKeyboardMarkup:
rows = _suggestion_rows(o)
rows.append([InlineKeyboardButton(text="π Delete", callback_data=f"rv:x:{o.material.id}")])
return InlineKeyboardMarkup(inline_keyboard=rows)
def _kb_near(o: smart_ingest.Outcome) -> InlineKeyboardMarkup:
new_id, old_id = o.material.id, o.duplicate_of.id
rows = _suggestion_rows(o) if o.course is None else [] # no course yet: picking one also keeps the file
actions = []
if o.course is not None:
actions.append(InlineKeyboardButton(text="β
Keep both", callback_data=f"rv:k:{new_id}"))
actions.append(InlineKeyboardButton(text=f"β»οΈ Replace #{old_id}", callback_data=f"rv:r:{new_id}:{old_id}"))
actions.append(InlineKeyboardButton(text="π Delete new", callback_data=f"rv:x:{new_id}"))
rows.append(actions)
return InlineKeyboardMarkup(inline_keyboard=rows)
@router.message(F.chat.type == "private", F.document | F.video | F.audio | F.photo)
async def ingest(message: Message, user: User, session: AsyncSession) -> None:
parsed = parse_caption(message.caption) # explicit " [title]" caption wins
mode = _upload_mode.get(user.id)
forced_course = forced_kind = forced_title = None
if parsed or mode:
course_id, forced_kind, forced_title = parsed if parsed else (mode["course_id"], mode["kind"], None)
forced_course = await repo.get_course(session, course_id)
if not forced_course:
await message.answer(f"β No course with id {course_id}. See /courses")
return
file_type, file_id, unique_id, file_name, size = _extract(message)
out = await smart_ingest.ingest_file(
message.bot, session,
uploader_id=user.id, file_type=file_type, file_id=file_id, unique_id=unique_id,
file_name=file_name, size=size, caption=message.caption,
forced_course=forced_course, forced_kind=forced_kind, forced_title=forced_title,
backup_channel=get_settings().library_channel_id, message=message,
)
quiet = bool(mode and not parsed) # forced bulk mode: one π per file instead of a message
hdr = _hdr(file_name)
if out.status == "duplicate":
if quiet:
mode["dupes"] += 1
await _ack(message)
else:
d = out.duplicate_of
was = f" (saved earlier as β{html.escape(d.source_name)}β)" if d.source_name else ""
await message.answer(f"{hdr}β»οΈ Skipped: {out.why}.\nAlready saved as #{d.id} β{d.title}β{was}.")
elif out.status == "saved":
if quiet:
mode["saved"] += 1
if quiet and not out.notes:
await _ack(message)
else:
await message.answer(_line(out))
elif out.status == "near_duplicate":
d, m = out.duplicate_of, out.material
await message.answer(
f"{hdr}π #{m.id} β{out.title}β ({m.pages or '?'} p, {_mb(m.size)})\n"
f"looks like #{d.id} β{d.title}β ({d.pages or '?'} p, {_mb(d.size)}).\n"
+ ("Which course is it, or what should I do?" if out.course is None else
f"π {_course_label(out.course)} Β· {out.kind}\nKeep both, or replace the old one with this version?"),
reply_markup=_kb_near(out),
)
else: # review
hint = "Pick the course:" if out.suggestions else f"No idea which course. Use /move {out.material.id} <course_id>"
await message.answer(
f"{hdr}π€ #{out.material.id} β{out.title}β Β· {out.kind}\nNot sure about the course. {hint}",
reply_markup=_kb_review(out) if out.suggestions else None,
)
# ---------- review buttons ----------
@router.callback_query(F.data.startswith("rv:"))
async def review_button(call: CallbackQuery, session: AsyncSession) -> None:
parts = call.data.split(":")
action, material_id = parts[1], int(parts[2])
material = await repo.get_material(session, material_id)
if not material:
await call.answer("Already gone.", show_alert=True)
return
if action == "x":
await repo.delete_material(session, material_id)
session.sync_session.info["wrote"] = True
text = f"π Deleted #{material_id}."
elif action == "k":
if material.course_id is None:
await call.answer(f"Pick a course first: /move {material_id} ", show_alert=True)
return
material.status = "ok"
course = await repo.get_course(session, material.course_id)
text = f"β
Kept #{material_id} β{material.title}β β {_course_label(course)} Β· {material.kind}"
elif action == "r": # the new file is a better/updated version: it takes the old one's place
old = await repo.get_material(session, int(parts[3]))
if not old:
await call.answer("The old file is already gone.", show_alert=True)
return
if material.course_id is None:
material.course_id = old.course_id
material.downloads = (material.downloads or 0) + (old.downloads or 0)
material.status = "ok"
await repo.delete_material(session, old.id)
session.sync_session.info["wrote"] = True
course = await repo.get_course(session, material.course_id) if material.course_id else None
text = f"β»οΈ #{material_id} replaced #{old.id} β {_course_label(course)} Β· {material.kind}"
else: # "c": assign course (and keep the file)
course = await repo.get_course(session, int(parts[3]))
if not course:
await call.answer("No such course.", show_alert=True)
return
material.course_id, material.status = course.id, "ok"
text = f"β
#{material_id} β {_course_label(course)} Β· {material.kind}"
library_service.invalidate_courses()
await call.answer()
if call.message:
try:
await call.message.edit_text(text)
except Exception:
await call.message.answer(text)
# ---------- corrections ----------
@router.message(Command("recent"))
async def recent(message: Message, session: AsyncSession) -> None:
items = await repo.recent_materials(session, 15)
if not items:
await message.answer("No files yet.")
return
courses = await repo.get_courses_map(session, {m.course_id for m in items if m.course_id})
lines = []
for m in items:
c = courses.get(m.course_id)
flag = "" if m.status == "ok" else " πΈreview"
lines.append(f"#{m.id} {c.name if c else 'β'} Β· {m.kind} Β· {m.title[:40]}{flag}")
await message.answer("\n".join(lines))
@router.message(Command("review"))
async def review_list(message: Message, session: AsyncSession) -> None:
items = await repo.review_materials(session)
if not items:
await message.answer("Nothing waiting for review π")
return
await message.answer("\n".join(f"#{m.id} {m.kind} Β· {m.title[:50]}" for m in items) + "\n\nFix with /move <id> <course_id> or /del <id>")
@router.message(Command("move"))
async def move(message: Message, command: CommandObject, session: AsyncSession) -> None:
parts = (command.args or "").split()
if len(parts) not in (2, 3) or not parts[0].isdigit() or not parts[1].isdigit():
await message.answer("Usage: /move <file_id> <course_id> [slide|exam|note|book]")
return
material, course = await repo.get_material(session, int(parts[0])), await repo.get_course(session, int(parts[1]))
if not material or not course:
await message.answer("File or course not found.")
return
material.course_id, material.status = course.id, "ok"
if len(parts) == 3 and KIND_ALIASES.get(parts[2].lower()):
material.kind = KIND_ALIASES[parts[2].lower()]
await message.answer(f"β
#{material.id} β {course.name} Β· {material.kind}")
@router.message(Command("kind"))
async def set_kind(message: Message, command: CommandObject, session: AsyncSession) -> None:
parts = (command.args or "").split()
kind = KIND_ALIASES.get(parts[1].lower()) if len(parts) == 2 else None
material = await repo.get_material(session, int(parts[0])) if parts and parts[0].isdigit() else None
if not material or not kind:
await message.answer("Usage: /kind <file_id> <slide|exam|note|book>")
return
material.kind = kind
await message.answer(f"β
#{material.id} is now {kind}")
@router.message(Command("rename"))
async def rename(message: Message, command: CommandObject, session: AsyncSession) -> None:
parts = (command.args or "").split(maxsplit=1)
material = await repo.get_material(session, int(parts[0])) if len(parts) == 2 and parts[0].isdigit() else None
if not material:
await message.answer("Usage: /rename <file_id> <new title>")
return
material.title = parts[1].strip()[:250]
await message.answer(f"β
#{material.id} renamed: β{material.title}β")
@router.message(Command("del"))
async def delete_cmd(message: Message, command: CommandObject, session: AsyncSession) -> None:
arg = (command.args or "").strip()
if not arg.isdigit() or not await repo.delete_material(session, int(arg)):
await message.answer("Usage: /del <file_id> (must exist)")
return
session.sync_session.info["wrote"] = True
await message.answer(f"π Deleted #{arg}.")
@router.message(Command("mergecourses"))
async def merge_courses(message: Message, session: AsyncSession) -> None:
n = await repo.merge_duplicate_courses(session)
session.sync_session.info["wrote"] = True
library_service.invalidate_courses()
await message.answer(f"β
Merged {n} duplicate courses. Now run /seedcourses to add any missing ones, then /courses.")
@router.message(Command("rewatermark"))
async def rewatermark(message: Message, command: CommandObject, session: AsyncSession) -> None:
"""Stamp PDFs that were saved before the watermark existed (or that failed to stamp)."""
limit = int(command.args) if (command.args or "").strip().isdigit() else 15
items = await repo.unstamped_pdfs(session, min(limit, 40), smart_ingest.BOT_API_DOWNLOAD_LIMIT)
if not items:
await message.answer("β
Every readable PDF is already stamped.")
return
await message.answer(f"β³ Stamping {len(items)} PDF(s)β¦")
style = wm.current_style()
target = get_settings().library_channel_id or message.from_user.id
done, failed = 0, []
for m in items:
source = m.orig_file_id or m.file_id
data = await smart_ingest._download(message.bot, source)
stamped, reason = await wm.stamp(data, style) if data else (None, "could not download")
if stamped is None:
failed.append(f"#{m.id} ({reason})")
continue
try:
sent = await message.bot.send_document(
target, BufferedInputFile(stamped, filename=m.source_name or "document.pdf"),
caption=f"π {m.title}"[:200], disable_notification=True,
)
except Exception as exc:
failed.append(f"#{m.id} (upload failed: {type(exc).__name__})")
continue
m.orig_file_id = m.orig_file_id or m.file_id
m.file_id, m.watermarked = sent.document.file_id, True
done += 1
session.sync_session.info["wrote"] = True
text = f"π Stamped {done} of {len(items)}."
if failed:
text += "\nFailed: " + ", ".join(failed)
await message.answer(text)