Spaces:
Running on Zero

cipher-attacks commited on
Commit
a1983b7
·
1 Parent(s): 6b161eb

watermark

Browse files
.env.example CHANGED
@@ -5,3 +5,9 @@ GATE_CHANNEL=@DBUCentral
5
  ADMIN_IDS=111111,222222
6
  DEFAULT_LANG=am
7
  LOG_LEVEL=INFO
 
 
 
 
 
 
 
5
  ADMIN_IDS=111111,222222
6
  DEFAULT_LANG=am
7
  LOG_LEVEL=INFO
8
+
9
+ # Watermark stamped on every uploaded PDF (defaults shown)
10
+ WATERMARK_ENABLED=true
11
+ WATERMARK_TEXT=DBU Freshman Central
12
+ # WATERMARK_URL=https://t.me/DBUCentral (empty = derived from GATE_CHANNEL)
13
+ WATERMARK_DIAGONAL=true
app/bot/handlers/admin.py CHANGED
@@ -6,7 +6,7 @@ from typing import Optional
6
 
7
  from aiogram import F, Router
8
  from aiogram.filters import BaseFilter, Command, CommandObject
9
- from aiogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message, ReactionTypeEmoji
10
  from sqlalchemy import text
11
  from sqlalchemy.ext.asyncio import AsyncSession
12
 
@@ -20,6 +20,7 @@ from app.core import season as clock
20
  from app.db.repos import users as users_repo
21
  from app.services import library as library_service
22
  from app.services import smart_ingest
 
23
  from app.services import season as season_service
24
  from app.services import xp as xp_service
25
  from app.services.ingest import KIND_ALIASES, clean_title, parse_caption
@@ -54,6 +55,7 @@ HELP = (
54
  "title and skips duplicates. If unsure it asks you (tap a button).\n"
55
  "/recent : last 15 files · /review : files waiting for you\n"
56
  "/move <id> <course_id> [kind] · /kind <id> <kind> · /rename <id> <title> · /del <id>\n"
 
57
  "/mergecourses : merge courses shared by both streams (run once, then /seedcourses)\n\n"
58
  "<b>Force a course:</b> <code>/upload 3 exam</code>, then send files, /done when finished.\n"
59
  "<b>Or</b> send a file with caption\n"
@@ -255,7 +257,7 @@ async def _ack(message: Message) -> None:
255
  def _line(o: smart_ingest.Outcome) -> str:
256
  m = o.material
257
  course = f"{o.course.code + ' ' if o.course and o.course.code else ''}{o.course.name}" if o.course else "❓ unsorted"
258
- text = f"✅ <b>#{m.id}</b> · {course} · <b>{o.kind}</b>\n“{o.title}”"
259
  if m.pages:
260
  text += f" · {m.pages} p"
261
  for note in o.notes:
@@ -304,6 +306,7 @@ async def ingest(message: Message, user: User, session: AsyncSession) -> None:
304
  elif out.status == "saved":
305
  if quiet:
306
  mode["saved"] += 1
 
307
  await _ack(message)
308
  else:
309
  await message.answer(_line(out))
@@ -437,3 +440,40 @@ async def merge_courses(message: Message, session: AsyncSession) -> None:
437
  session.sync_session.info["wrote"] = True
438
  library_service.invalidate_courses()
439
  await message.answer(f"✅ Merged {n} duplicate courses. Now run /seedcourses to add any missing ones, then /courses.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  from aiogram import F, Router
8
  from aiogram.filters import BaseFilter, Command, CommandObject
9
+ from aiogram.types import BufferedInputFile, CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message, ReactionTypeEmoji
10
  from sqlalchemy import text
11
  from sqlalchemy.ext.asyncio import AsyncSession
12
 
 
20
  from app.db.repos import users as users_repo
21
  from app.services import library as library_service
22
  from app.services import smart_ingest
23
+ from app.services import watermark as wm
24
  from app.services import season as season_service
25
  from app.services import xp as xp_service
26
  from app.services.ingest import KIND_ALIASES, clean_title, parse_caption
 
55
  "title and skips duplicates. If unsure it asks you (tap a button).\n"
56
  "/recent : last 15 files · /review : files waiting for you\n"
57
  "/move &lt;id&gt; &lt;course_id&gt; [kind] · /kind &lt;id&gt; &lt;kind&gt; · /rename &lt;id&gt; &lt;title&gt; · /del &lt;id&gt;\n"
58
+ "/rewatermark [n] : stamp the official channel link on already-saved PDFs (n at a time, default 15)\n"
59
  "/mergecourses : merge courses shared by both streams (run once, then /seedcourses)\n\n"
60
  "<b>Force a course:</b> <code>/upload 3 exam</code>, then send files, /done when finished.\n"
61
  "<b>Or</b> send a file with caption\n"
 
257
  def _line(o: smart_ingest.Outcome) -> str:
258
  m = o.material
259
  course = f"{o.course.code + ' ' if o.course and o.course.code else ''}{o.course.name}" if o.course else "❓ unsorted"
260
+ text = f"✅ <b>#{m.id}</b> · {course} · <b>{o.kind}</b>{' · 🔖' if m.watermarked else ''}\n“{o.title}”"
261
  if m.pages:
262
  text += f" · {m.pages} p"
263
  for note in o.notes:
 
306
  elif out.status == "saved":
307
  if quiet:
308
  mode["saved"] += 1
309
+ if quiet and not out.notes:
310
  await _ack(message)
311
  else:
312
  await message.answer(_line(out))
 
440
  session.sync_session.info["wrote"] = True
441
  library_service.invalidate_courses()
442
  await message.answer(f"✅ Merged {n} duplicate courses. Now run /seedcourses to add any missing ones, then /courses.")
443
+
444
+
445
+ @router.message(Command("rewatermark"))
446
+ async def rewatermark(message: Message, command: CommandObject, session: AsyncSession) -> None:
447
+ """Stamp PDFs that were saved before the watermark existed (or that failed to stamp)."""
448
+ limit = int(command.args) if (command.args or "").strip().isdigit() else 15
449
+ items = await repo.unstamped_pdfs(session, min(limit, 40), smart_ingest.BOT_API_DOWNLOAD_LIMIT)
450
+ if not items:
451
+ await message.answer("✅ Every readable PDF is already stamped.")
452
+ return
453
+ await message.answer(f"⏳ Stamping {len(items)} PDF(s)…")
454
+ style = wm.current_style()
455
+ target = get_settings().library_channel_id or message.from_user.id
456
+ done, failed = 0, []
457
+ for m in items:
458
+ source = m.orig_file_id or m.file_id
459
+ data = await smart_ingest._download(message.bot, source)
460
+ stamped, reason = await wm.stamp(data, style) if data else (None, "could not download")
461
+ if stamped is None:
462
+ failed.append(f"#{m.id} ({reason})")
463
+ continue
464
+ try:
465
+ sent = await message.bot.send_document(
466
+ target, BufferedInputFile(stamped, filename=m.source_name or "document.pdf"),
467
+ caption=f"📌 {m.title}"[:200], disable_notification=True,
468
+ )
469
+ except Exception as exc:
470
+ failed.append(f"#{m.id} (upload failed: {type(exc).__name__})")
471
+ continue
472
+ m.orig_file_id = m.orig_file_id or m.file_id
473
+ m.file_id, m.watermarked = sent.document.file_id, True
474
+ done += 1
475
+ session.sync_session.info["wrote"] = True
476
+ text = f"🔖 Stamped <b>{done}</b> of {len(items)}."
477
+ if failed:
478
+ text += "\nFailed: " + ", ".join(failed)
479
+ await message.answer(text)
app/config.py CHANGED
@@ -14,6 +14,16 @@ class Settings(BaseSettings):
14
  library_channel_id: int = 0 # private backup channel (0 = no backup copy)
15
  log_level: str = "INFO"
16
 
 
 
 
 
 
 
 
 
 
 
17
  # --- weekly season / prizes (money is OFF until you switch it on) ---
18
  prizes_enabled: bool = False
19
  prize_top: str = "50,30,20" # birr airtime card for rank 1,2,3 (comma separated)
 
14
  library_channel_id: int = 0 # private backup channel (0 = no backup copy)
15
  log_level: str = "INFO"
16
 
17
+ # --- watermark stamped on every PDF the admin uploads ---
18
+ watermark_enabled: bool = True
19
+ watermark_text: str = "DBU Freshman Central"
20
+ watermark_url: str = "" # empty = https://t.me/<GATE_CHANNEL>
21
+ watermark_diagonal: bool = True # faint diagonal brand text in the middle of each page
22
+
23
+ @property
24
+ def watermark_link(self) -> str:
25
+ return self.watermark_url or f"https://t.me/{self.gate_channel.lstrip('@')}"
26
+
27
  # --- weekly season / prizes (money is OFF until you switch it on) ---
28
  prizes_enabled: bool = False
29
  prize_top: str = "50,30,20" # birr airtime card for rank 1,2,3 (comma separated)
app/db/migrate.py CHANGED
@@ -33,6 +33,8 @@ POSTGRES_UPGRADES = [
33
  "ALTER TABLE materials ADD COLUMN IF NOT EXISTS size INTEGER",
34
  "ALTER TABLE materials ADD COLUMN IF NOT EXISTS source_name VARCHAR(256)",
35
  "ALTER TABLE materials ADD COLUMN IF NOT EXISTS status VARCHAR(8) NOT NULL DEFAULT 'ok'",
 
 
36
  "CREATE INDEX IF NOT EXISTS ix_materials_content_hash ON materials (content_hash)",
37
  "ALTER TABLE referrals ADD COLUMN IF NOT EXISTS qualified BOOLEAN NOT NULL DEFAULT FALSE",
38
  ]
 
33
  "ALTER TABLE materials ADD COLUMN IF NOT EXISTS size INTEGER",
34
  "ALTER TABLE materials ADD COLUMN IF NOT EXISTS source_name VARCHAR(256)",
35
  "ALTER TABLE materials ADD COLUMN IF NOT EXISTS status VARCHAR(8) NOT NULL DEFAULT 'ok'",
36
+ "ALTER TABLE materials ADD COLUMN IF NOT EXISTS orig_file_id VARCHAR(512)",
37
+ "ALTER TABLE materials ADD COLUMN IF NOT EXISTS watermarked BOOLEAN NOT NULL DEFAULT FALSE",
38
  "CREATE INDEX IF NOT EXISTS ix_materials_content_hash ON materials (content_hash)",
39
  "ALTER TABLE referrals ADD COLUMN IF NOT EXISTS qualified BOOLEAN NOT NULL DEFAULT FALSE",
40
  ]
app/db/models/material.py CHANGED
@@ -1,7 +1,7 @@
1
  from datetime import datetime
2
  from typing import Optional
3
 
4
- from sqlalchemy import BigInteger, DateTime, ForeignKey, Integer, String, func
5
  from sqlalchemy.orm import Mapped, mapped_column
6
 
7
  from app.db.base import Base
@@ -21,6 +21,8 @@ class Material(Base):
21
  kind: Mapped[str] = mapped_column(String(16), default="slide") # slide|exam|note|book
22
  title: Mapped[str] = mapped_column(String(256))
23
  file_id: Mapped[Optional[str]] = mapped_column(String(512))
 
 
24
  file_type: Mapped[str] = mapped_column(String(16), default="document", server_default="document")
25
  file_unique_id: Mapped[Optional[str]] = mapped_column(String(128), unique=True)
26
  content_hash: Mapped[Optional[str]] = mapped_column(String(64), index=True) # sha256 of the bytes
 
1
  from datetime import datetime
2
  from typing import Optional
3
 
4
+ from sqlalchemy import BigInteger, Boolean, DateTime, ForeignKey, Integer, String, func
5
  from sqlalchemy.orm import Mapped, mapped_column
6
 
7
  from app.db.base import Base
 
21
  kind: Mapped[str] = mapped_column(String(16), default="slide") # slide|exam|note|book
22
  title: Mapped[str] = mapped_column(String(256))
23
  file_id: Mapped[Optional[str]] = mapped_column(String(512))
24
+ orig_file_id: Mapped[Optional[str]] = mapped_column(String(512)) # the file as uploaded (before the stamp)
25
+ watermarked: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
26
  file_type: Mapped[str] = mapped_column(String(16), default="document", server_default="document")
27
  file_unique_id: Mapped[Optional[str]] = mapped_column(String(128), unique=True)
28
  content_hash: Mapped[Optional[str]] = mapped_column(String(64), index=True) # sha256 of the bytes
app/db/repos/library.py CHANGED
@@ -248,3 +248,18 @@ async def merge_duplicate_courses(session: AsyncSession) -> int:
248
  merged += 1
249
  await session.flush()
250
  return merged
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  merged += 1
249
  await session.flush()
250
  return merged
251
+
252
+
253
+ async def unstamped_pdfs(session: AsyncSession, limit: int, max_size: int) -> list[Material]:
254
+ res = await session.execute(
255
+ select(Material)
256
+ .where(
257
+ Material.file_type == "document",
258
+ Material.watermarked.is_(False),
259
+ Material.source_name.ilike("%.pdf"),
260
+ or_(Material.size.is_(None), Material.size <= max_size),
261
+ )
262
+ .order_by(Material.id)
263
+ .limit(limit)
264
+ )
265
+ return list(res.scalars())
app/services/smart_ingest.py CHANGED
@@ -7,12 +7,15 @@ from dataclasses import dataclass, field
7
  from typing import Optional
8
 
9
  from aiogram import Bot
 
10
  from sqlalchemy.ext.asyncio import AsyncSession
11
 
 
12
  from app.db.models import Course, Material
13
  from app.db.repos import library as repo
14
  from app.services import classifier as C
15
  from app.services import library as lib
 
16
  from app.services.doc_analyzer import DocInfo, analyze
17
 
18
  log = logging.getLogger(__name__)
@@ -64,7 +67,7 @@ async def ingest_file(
64
  return Outcome("duplicate", duplicate_of=existing, why="same Telegram file")
65
 
66
  # 2) read the content (only possible up to 20 MB) -> hash, text, pages
67
- content_hash, info = None, DocInfo()
68
  if file_type == "document" and size is not None and size <= BOT_API_DOWNLOAD_LIMIT:
69
  data = await _download(bot, file_id)
70
  if data:
@@ -116,6 +119,31 @@ async def ingest_file(
116
  notes.append(f"same title as an existing different file -> saved as “{new_title}”")
117
  title = new_title
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  status = "saved"
120
  if near is not None:
121
  status = "near_duplicate"
@@ -127,7 +155,11 @@ async def ingest_file(
127
  course_id=course.id if course else None,
128
  kind=kind,
129
  title=title[:250],
130
- file_id=file_id,
 
 
 
 
131
  file_type=file_type,
132
  file_unique_id=unique_id,
133
  uploader_id=uploader_id,
@@ -138,7 +170,7 @@ async def ingest_file(
138
  source_name=(file_name or "")[:250] or None,
139
  status="ok" if status == "saved" else "review",
140
  )
141
- if backup_channel and message is not None:
142
  try:
143
  copied = await message.copy_to(backup_channel)
144
  material.library_chat_id, material.library_message_id = backup_channel, copied.message_id
 
7
  from typing import Optional
8
 
9
  from aiogram import Bot
10
+ from aiogram.types import BufferedInputFile
11
  from sqlalchemy.ext.asyncio import AsyncSession
12
 
13
+ from app.config import get_settings
14
  from app.db.models import Course, Material
15
  from app.db.repos import library as repo
16
  from app.services import classifier as C
17
  from app.services import library as lib
18
+ from app.services import watermark as wm
19
  from app.services.doc_analyzer import DocInfo, analyze
20
 
21
  log = logging.getLogger(__name__)
 
67
  return Outcome("duplicate", duplicate_of=existing, why="same Telegram file")
68
 
69
  # 2) read the content (only possible up to 20 MB) -> hash, text, pages
70
+ content_hash, info, data = None, DocInfo(), None
71
  if file_type == "document" and size is not None and size <= BOT_API_DOWNLOAD_LIMIT:
72
  data = await _download(bot, file_id)
73
  if data:
 
119
  notes.append(f"same title as an existing different file -> saved as “{new_title}”")
120
  title = new_title
121
 
122
+ # 7b) stamp PDFs with the official channel link; students receive the STAMPED copy
123
+ stored_file_id, orig_file_id, stamped_ok = file_id, None, False
124
+ library_chat = library_msg = None
125
+ if get_settings().watermark_enabled and ext == ".pdf" and file_type == "document":
126
+ if data is None:
127
+ big = size is not None and size > BOT_API_DOWNLOAD_LIMIT
128
+ notes.append("not watermarked: over 20 MB, the bot cannot read it" if big else "not watermarked: could not read the file")
129
+ else:
130
+ stamped, reason = await wm.stamp(data, wm.current_style())
131
+ if stamped is None:
132
+ notes.append(f"not watermarked: {reason}")
133
+ else:
134
+ target = backup_channel or uploader_id # the library channel doubles as the backup
135
+ try:
136
+ sent = await bot.send_document(
137
+ target, BufferedInputFile(stamped, filename=file_name or "document.pdf"),
138
+ caption=f"📌 {title}"[:200], disable_notification=True,
139
+ )
140
+ stored_file_id, orig_file_id, stamped_ok = sent.document.file_id, file_id, True
141
+ if backup_channel:
142
+ library_chat, library_msg = backup_channel, sent.message_id
143
+ except Exception as exc:
144
+ log.warning("Could not upload the stamped copy: %r", exc)
145
+ notes.append("could not upload the stamped copy: original kept")
146
+
147
  status = "saved"
148
  if near is not None:
149
  status = "near_duplicate"
 
155
  course_id=course.id if course else None,
156
  kind=kind,
157
  title=title[:250],
158
+ file_id=stored_file_id,
159
+ orig_file_id=orig_file_id,
160
+ watermarked=stamped_ok,
161
+ library_chat_id=library_chat,
162
+ library_message_id=library_msg,
163
  file_type=file_type,
164
  file_unique_id=unique_id,
165
  uploader_id=uploader_id,
 
170
  source_name=(file_name or "")[:250] or None,
171
  status="ok" if status == "saved" else "review",
172
  )
173
+ if backup_channel and message is not None and not stamped_ok:
174
  try:
175
  copied = await message.copy_to(backup_channel)
176
  material.library_chat_id, material.library_message_id = backup_channel, copied.message_id
app/services/watermark.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stamp every page of a PDF with the official channel link:
2
+ * a neat rounded footer pill (clickable link) at the bottom centre
3
+ * an optional very faint diagonal brand text in the middle
4
+ Handles every page size, crop box and rotation. Latin text only (standard fonts), so no font files needed."""
5
+ import asyncio
6
+ import io
7
+ import logging
8
+ import re
9
+ from dataclasses import dataclass
10
+ from typing import Optional
11
+
12
+ log = logging.getLogger(__name__)
13
+ MARK_KEY = "/DBUWatermark" # written into the PDF metadata so a file is never stamped twice
14
+ BLUE = (0.10, 0.30, 0.60)
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Style:
19
+ text: str
20
+ url: str
21
+ diagonal: bool = True
22
+
23
+ @property
24
+ def footer(self) -> str:
25
+ return f"{self.text} | {display_url(self.url)}"
26
+
27
+
28
+ def display_url(url: str) -> str:
29
+ return re.sub(r"^https?://", "", url).rstrip("/")
30
+
31
+
32
+ # ------------------------------------------------ geometry (pure, tested)
33
+ def display_size(w: float, h: float, rotation: int) -> tuple[float, float]:
34
+ return (h, w) if rotation % 360 in (90, 270) else (w, h)
35
+
36
+
37
+ def to_page_space(dx: float, dy: float, w: float, h: float, rotation: int) -> tuple[float, float]:
38
+ """A point in what the reader SEES (origin bottom-left of the displayed page) -> the page's own
39
+ unrotated coordinates. w,h = unrotated size."""
40
+ r = rotation % 360
41
+ if r == 90:
42
+ return w - dy, dx
43
+ if r == 180:
44
+ return w - dx, h - dy
45
+ if r == 270:
46
+ return dy, h - dx
47
+ return dx, dy
48
+
49
+
50
+ def rect_to_page_space(x0: float, y0: float, x1: float, y1: float, w: float, h: float, rotation: int):
51
+ a = to_page_space(x0, y0, w, h, rotation)
52
+ b = to_page_space(x1, y1, w, h, rotation)
53
+ return (min(a[0], b[0]), min(a[1], b[1]), max(a[0], b[0]), max(a[1], b[1]))
54
+
55
+
56
+ def footer_geometry(text_width: float, dw: float, size: float) -> tuple[float, float, float, float]:
57
+ """Display-space rectangle of the footer pill: (x0, y0, x1, y1)."""
58
+ half = text_width / 2 + 9
59
+ y0 = 12.0
60
+ return dw / 2 - half, y0, dw / 2 + half, y0 + size + 9
61
+
62
+
63
+ # ------------------------------------------------ drawing
64
+ def _overlay(w: float, h: float, left: float, bottom: float, rotation: int, style: Style) -> tuple[bytes, tuple]:
65
+ from reportlab.pdfbase.pdfmetrics import stringWidth
66
+ from reportlab.pdfgen import canvas
67
+
68
+ buf = io.BytesIO()
69
+ c = canvas.Canvas(buf, pagesize=(left + w, bottom + h))
70
+ dw, dh = display_size(w, h, rotation)
71
+ size = max(6.5, min(9.5, dw / 62))
72
+ font = "Helvetica-Bold"
73
+ text_w = stringWidth(style.footer, font, size)
74
+ x0, y0, x1, y1 = footer_geometry(text_w, dw, size)
75
+
76
+ def at(dx: float, dy: float, theta: float, draw) -> None:
77
+ x, y = to_page_space(dx, dy, w, h, rotation)
78
+ c.saveState()
79
+ c.translate(left + x, bottom + y)
80
+ c.rotate(theta + rotation) # keep the text upright for the reader, whatever /Rotate says
81
+ draw()
82
+ c.restoreState()
83
+
84
+ if style.diagonal:
85
+ big = max(24, min(dw, dh) / 8)
86
+
87
+ def diagonal() -> None:
88
+ c.setFont(font, big)
89
+ c.setFillColorRGB(*BLUE, 0.06)
90
+ c.drawCentredString(0, 0, style.text)
91
+
92
+ at(dw / 2, dh / 2, 38, diagonal)
93
+
94
+ def pill() -> None:
95
+ c.setFillColorRGB(1, 1, 1, 0.88)
96
+ c.setStrokeColorRGB(*BLUE, 0.35)
97
+ c.setLineWidth(0.6)
98
+ c.roundRect(-(x1 - x0) / 2, -4.5, x1 - x0, size + 9, 5, stroke=1, fill=1)
99
+ c.setFillColorRGB(*BLUE, 0.95)
100
+ c.setFont(font, size)
101
+ c.drawCentredString(0, 0, style.footer)
102
+
103
+ at(dw / 2, y0 + 4.5, 0, pill)
104
+ c.showPage()
105
+ c.save()
106
+
107
+ rx0, ry0, rx1, ry1 = rect_to_page_space(x0, y0, x1, y1, w, h, rotation)
108
+ return buf.getvalue(), (left + rx0, bottom + ry0, left + rx1, bottom + ry1)
109
+
110
+
111
+ def stamp_pdf(data: bytes, style: Style) -> bytes:
112
+ """Return the stamped PDF. Raises on anything unexpected (the caller then keeps the original)."""
113
+ from pypdf import PdfReader, PdfWriter
114
+ from pypdf.annotations import Link
115
+
116
+ reader = PdfReader(io.BytesIO(data))
117
+ if reader.is_encrypted and not reader.decrypt(""):
118
+ raise ValueError("the PDF is password protected")
119
+ if reader.metadata and MARK_KEY in reader.metadata:
120
+ raise ValueError("already stamped")
121
+ pages = len(reader.pages)
122
+ if pages == 0:
123
+ raise ValueError("the PDF has no pages")
124
+
125
+ writer = PdfWriter(clone_from=reader)
126
+ cache: dict = {}
127
+ for i, page in enumerate(writer.pages):
128
+ box = page.cropbox # what viewers actually show
129
+ w, h = float(box.width), float(box.height)
130
+ key = (round(w, 1), round(h, 1), round(float(box.left), 1), round(float(box.bottom), 1), page.rotation % 360)
131
+ if key not in cache:
132
+ cache[key] = _overlay(w, h, float(box.left), float(box.bottom), page.rotation % 360, style)
133
+ overlay_bytes, link_rect = cache[key]
134
+ page.merge_page(PdfReader(io.BytesIO(overlay_bytes)).pages[0])
135
+ writer.add_annotation(page_number=i, annotation=Link(rect=link_rect, url=style.url))
136
+ writer.add_metadata({MARK_KEY: style.url})
137
+
138
+ out = io.BytesIO()
139
+ writer.write(out)
140
+ result = out.getvalue()
141
+ if len(PdfReader(io.BytesIO(result)).pages) != pages: # paranoia: never ship a broken file
142
+ raise ValueError("page count changed while stamping")
143
+ return result
144
+
145
+
146
+ async def stamp(data: bytes, style: Style) -> tuple[Optional[bytes], str]:
147
+ """(stamped bytes or None, reason when None). Heavy work runs in a thread."""
148
+ try:
149
+ return await asyncio.to_thread(stamp_pdf, data, style), ""
150
+ except Exception as exc:
151
+ log.info("Watermark skipped: %r", exc)
152
+ return None, str(exc)[:120] or type(exc).__name__
153
+
154
+
155
+ def current_style() -> Style:
156
+ from app.config import get_settings
157
+
158
+ cfg = get_settings()
159
+ return Style(text=cfg.watermark_text, url=cfg.watermark_link, diagonal=cfg.watermark_diagonal)
requirements.txt CHANGED
@@ -3,4 +3,5 @@ sqlalchemy[asyncio]>=2.0
3
  asyncpg>=0.29
4
  aiosqlite>=0.20
5
  pydantic-settings>=2.2
6
- pypdf>=4
 
 
3
  asyncpg>=0.29
4
  aiosqlite>=0.20
5
  pydantic-settings>=2.2
6
+ pypdf>=4.0
7
+ reportlab>=4.0
tests/test_logic.py CHANGED
@@ -254,6 +254,53 @@ def test_doc_analyzer_reads_pptx_and_docx():
254
  assert analyze("pic.png", b"x").pages is None
255
 
256
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
  if __name__ == "__main__":
258
  for name, fn in list(globals().items()):
259
  if name.startswith("test_"):
 
254
  assert analyze("pic.png", b"x").pages is None
255
 
256
 
257
+ def test_watermark_geometry_roundtrip():
258
+ from app.services import watermark as W
259
+
260
+ w, h = 595.0, 842.0
261
+
262
+ def forward(x, y, r): # page space -> what the reader sees (the inverse of to_page_space)
263
+ return {0: (x, y), 90: (y, w - x), 180: (w - x, h - y), 270: (h - y, x)}[r]
264
+
265
+ for r in (0, 90, 180, 270):
266
+ for x, y in ((10, 20), (300, 400), (595, 842)):
267
+ dx, dy = forward(x, y, r)
268
+ assert W.to_page_space(dx, dy, w, h, r) == (x, y), (r, x, y)
269
+ assert W.display_size(w, h, 90) == (h, w) and W.display_size(w, h, 0) == (w, h)
270
+ assert W.display_url("https://t.me/DBUCentral/") == "t.me/DBUCentral"
271
+ x0, y0, x1, y1 = W.rect_to_page_space(0, 0, 100, 20, w, h, 90)
272
+ assert x0 < x1 and y0 < y1
273
+
274
+
275
+ def test_watermark_stamps_real_pdfs():
276
+ try:
277
+ import io
278
+
279
+ from pypdf import PdfReader, PdfWriter
280
+ from reportlab.pdfgen import canvas
281
+ except ImportError:
282
+ return # libraries not installed here; the bot's requirements.txt installs them
283
+ from app.services import watermark as W
284
+
285
+ buf = io.BytesIO()
286
+ c = canvas.Canvas(buf)
287
+ for i in range(3):
288
+ c.setPageSize((595, 842) if i != 1 else (842, 595))
289
+ c.drawString(40, 500, f"Hello {i}")
290
+ c.showPage()
291
+ c.save()
292
+ style = W.Style("DBU Freshman Central", "https://t.me/DBUCentral", True)
293
+ out = W.stamp_pdf(buf.getvalue(), style)
294
+ pages = PdfReader(io.BytesIO(out)).pages
295
+ assert len(pages) == 3
296
+ assert all("t.me/DBUCentral" in p.extract_text() and f"Hello {i}" in p.extract_text() for i, p in enumerate(pages))
297
+ try:
298
+ W.stamp_pdf(out, style)
299
+ raise AssertionError("double stamp allowed")
300
+ except ValueError:
301
+ pass
302
+
303
+
304
  if __name__ == "__main__":
305
  for name, fn in list(globals().items()):
306
  if name.startswith("test_"):