Spaces:
Running on Zero
Running on Zero
Download app/bot/handlers/admin.py from cipher-attacks/Dbu-central-bot: direct link, hf CLI and curl.
- Browser
- Download file 32.2 kB
-
https://huggingface.co/spaces/cipher-attacks/Dbu-central-bot/resolve/main/app/bot/handlers/admin.py
- Command line
-
hf download hf://spaces/cipher-attacks/Dbu-central-bot/app/bot/handlers/admin.py
-
curl -L -o admin.py https://huggingface.co/spaces/cipher-attacks/Dbu-central-bot/resolve/main/app/bot/handlers/admin.py
32.2 kB
| """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: <code>/addcourse <natural|social|all> <year 0-5> <code or -> <name...></code>\n" | |
| "Example: <code>/addcourse natural 1 Chem1012 Organic Chemistry</code>\n" | |
| "Full manual: /help" | |
| ) | |
| async def admin_help(message: Message) -> None: | |
| for chunk in manual.render(facts()): | |
| await message.answer(chunk) | |
| 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"), | |
| ]]), | |
| ) | |
| 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." | |
| ) | |
| 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): <b>{db1:.0f} ms</b>\n" | |
| f"DB #2 (pure round-trip): <b>{db2:.0f} ms</b>\n" | |
| f"Telegram API: <b>{tg:.0f} ms</b>" | |
| ) | |
| async def season_view(message: Message, session: AsyncSession) -> None: | |
| await message.answer(await season_service.preview(session, clock.week_key())) | |
| async def winners(message: Message, session: AsyncSession) -> None: | |
| await message.answer(await season_service.last_results_text(session)) | |
| 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: <code>/closeweek 2026W41</code> (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)) | |
| 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: <code>/give <user_id> <xp 1-500></code>") | |
| 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) | |
| 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: <code>/trust <user_id> <delta, e.g. -30></code>") | |
| return | |
| ok = await xp_service.adjust_trust(session, uid, delta, "admin") | |
| await message.answer("✅ Trust updated." if ok else "Nothing changed.") | |
| 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 <b>#{course.id}</b> added: {course.code} · {course.name}") | |
| 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 <b>{added}</b> courses, skipped {skipped} that already existed.\nSee /courses for ids.") | |
| 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: <code>/delcourse <id> [move_files_to_id]</code>") | |
| 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 <b>{files}</b> file(s), so I did not delete it.\n" | |
| f"Move them and delete in one go: <code>/delcourse {cid} <other_course_id></code>" | |
| ) | |
| 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}.") | |
| 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:]}: <b>{n}</b>" for d, n in r["by_day"]) or "no new users" | |
| lines = [ | |
| "📈 <b>Growth</b>", | |
| f"Total users: <b>{r['total']}</b> · groups using the bot: <b>{r['groups']}</b>", | |
| f"New users per day (7 days): {days}", | |
| "\n<b>Where they come from</b>\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"• <b>{source}</b>: {joined} → {gate_ok} → {onboarded} → {active} ({round(100 * onboarded / joined)}% finished setup)") | |
| if r["stuck"]: | |
| lines.append("\n<b>Stuck at the join step</b> (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"• <b>{n}</b>: {what}") | |
| lines.append( | |
| "\n<b>Sources:</b> 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)) | |
| 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: <b>{tag}</b>. 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.", | |
| ) | |
| 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"<b>{c.id}</b> · {c.stream or 'all'} · {c.code or '-'} · {c.name}" for c in items] | |
| await message.answer( | |
| f"🗂 <b>{len(items)}</b> 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"), | |
| ]]), | |
| ) | |
| 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) | |
| 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 = ["🔐 <b>Join-gate check</b> (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 <b>{member.status}</b>" | |
| + ("" 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)) | |
| 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"<b>{c.id}</b> · {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) | |
| async def stats(message: Message, session: AsyncSession) -> None: | |
| s = await stats_repo.overview(session, clock.now_et().date()) | |
| await message.answer( | |
| "📊 <b>Stats</b>\n" | |
| f"Users: <b>{s['users']}</b> (verified members {s['gate_passed']}, finished setup {s['onboarded']})\n" | |
| f"Active today: <b>{s['active_today']}</b>\n" | |
| f"Referrals: <b>{s['referrals']}</b>\n" | |
| f"Student files waiting: <b>{await sub_repo.pending_total(session)}</b>\n" | |
| f"Courses: <b>{s['courses']}</b> · Files: <b>{s['materials']}</b> · Downloads: <b>{s['downloads']}</b>" | |
| ) | |
| 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] = {} | |
| 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: <code>/upload <course_id> <slide|exam|note|book></code>\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 <b>ON</b>: {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.)" | |
| ) | |
| 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 <b>{mode['saved']}</b> 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"📎 <i>{html.escape((file_name or 'file')[:70])}</i>\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)}✅ <b>#{m.id}</b> · {_course_label(o.course)} · <b>{o.kind}</b>{' · 🔖' 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) | |
| async def ingest(message: Message, user: User, session: AsyncSession) -> None: | |
| parsed = parse_caption(message.caption) # explicit "<id> <kind> [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 <b>#{d.id}</b> “{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}🔍 <b>#{m.id}</b> “{out.title}” ({m.pages or '?'} p, {_mb(m.size)})\n" | |
| f"looks like <b>#{d.id}</b> “{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 <code>/move {out.material.id} <course_id></code>" | |
| await message.answer( | |
| f"{hdr}🤔 <b>#{out.material.id}</b> “{out.title}” · {out.kind}\nNot sure about the course. {hint}", | |
| reply_markup=_kb_review(out) if out.suggestions else None, | |
| ) | |
| # ---------- review buttons ---------- | |
| 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} <course_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 ---------- | |
| 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"<b>#{m.id}</b> {c.name if c else '❓'} · {m.kind} · {m.title[:40]}{flag}") | |
| await message.answer("\n".join(lines)) | |
| 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"<b>#{m.id}</b> {m.kind} · {m.title[:50]}" for m in items) + "\n\nFix with /move <id> <course_id> or /del <id>") | |
| 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: <code>/move <file_id> <course_id> [slide|exam|note|book]</code>") | |
| 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}") | |
| 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: <code>/kind <file_id> <slide|exam|note|book></code>") | |
| return | |
| material.kind = kind | |
| await message.answer(f"✅ #{material.id} is now <b>{kind}</b>") | |
| 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: <code>/rename <file_id> <new title></code>") | |
| return | |
| material.title = parts[1].strip()[:250] | |
| await message.answer(f"✅ #{material.id} renamed: “{material.title}”") | |
| 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: <code>/del <file_id></code> (must exist)") | |
| return | |
| session.sync_session.info["wrote"] = True | |
| await message.answer(f"🗑 Deleted #{arg}.") | |
| 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.") | |
| 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 <b>{done}</b> of {len(items)}." | |
| if failed: | |
| text += "\nFailed: " + ", ".join(failed) | |
| await message.answer(text) | |