diff --git a/alembic/versions/20260727_020_add_message_sender_name.py b/alembic/versions/20260727_020_add_message_sender_name.py new file mode 100644 index 00000000..15ac10b8 --- /dev/null +++ b/alembic/versions/20260727_020_add_message_sender_name.py @@ -0,0 +1,42 @@ +"""Add immutable per-message sender name snapshots (#240). + +Revision ID: 020 +Revises: 019 +Create Date: 2026-07-27 +""" + +from collections.abc import Sequence + +import sqlalchemy as sa + +from alembic import op + +revision: str = "020" +down_revision: str | None = "019" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + +TABLE_NAME = "messages" +COLUMN_NAME = "sender_name" + + +def _column_exists(inspector: sa.Inspector) -> bool: + return COLUMN_NAME in {column["name"] for column in inspector.get_columns(TABLE_NAME)} + + +def upgrade() -> None: + conn = op.get_bind() + inspector = sa.inspect(conn) + if TABLE_NAME not in inspector.get_table_names(): + return + if not _column_exists(inspector): + op.add_column(TABLE_NAME, sa.Column(COLUMN_NAME, sa.Text(), nullable=True)) + + +def downgrade() -> None: + conn = op.get_bind() + inspector = sa.inspect(conn) + if TABLE_NAME not in inspector.get_table_names(): + return + if _column_exists(inspector): + op.drop_column(TABLE_NAME, COLUMN_NAME) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 8742b38f..dceca01a 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to this project are documented here. For upgrade instructions, see [Upgrading](#upgrading) at the bottom. +## [7.28.0] - 2026-07-27 + +### Added +- **Historical sender names are preserved per message.** New imports and captures store the sender label seen with the message instead of resolving every old message through a mutable user profile. Existing rows keep their current behavior, and a stored snapshot is filled once but never rewritten by later sweeps. +- **Sender details are available from group avatars.** The dialog shows the archived name, a different latest-known profile name when available, and the numeric Telegram ID. + +### Fixed +- **Telegram Desktop media imports are confined to the selected export and configured media directories.** Absolute paths, parent traversal, and escaping symlinks are rejected before files are read or written. +- **Imports now honor `MEDIA_MAX_FILENAME_BYTES`** for long and multibyte media names, and one failed media copy is skipped without aborting the remaining message history. +- **Imported supergroups show sender names and avatars** like live-captured groups. +- **Message runs have compact spacing within one sender's sequence and a larger gap when the sender changes.** + +### Upgrade note +- Migration `020` adds the nullable `messages.sender_name` snapshot column automatically. Existing messages are not backfilled. + ## [7.23.0] - 2026-07-18 ### Added diff --git a/pyproject.toml b/pyproject.toml index e0241e58..cfdef43d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "telegram-archive" -version = "7.27.1" +version = "7.28.0" description = "Automated Telegram backup with Docker. Performs incremental backups of messages and media on a configurable schedule." readme = "README.md" requires-python = ">=3.14" diff --git a/scripts/entrypoint.sh b/scripts/entrypoint.sh index 65575b06..02cffcc0 100644 --- a/scripts/entrypoint.sh +++ b/scripts/entrypoint.sh @@ -157,6 +157,17 @@ if has_tables and not has_alembic: \"\"\") has_018_reaction_removed_at = has_018_removed_at_col and cur.fetchone()[0] + # Check artifact from migration 020: messages.sender_name column. Migration + # 019 is data-only, so even schemas created from current ORM metadata must be + # stamped at 018 and run both 019 and guarded/idempotent 020. + cur.execute(\"\"\" + SELECT EXISTS ( + SELECT FROM information_schema.columns + WHERE table_name = 'messages' AND column_name = 'sender_name' + ); + \"\"\") + has_020_sender_name = cur.fetchone()[0] + # Check artifact from migration 014: messages soft-delete marker columns cur.execute(\"\"\" SELECT @@ -277,9 +288,9 @@ if has_tables and not has_alembic: has_push_subs = cur.fetchone()[0] # Determine which version to stamp based on existing schema - # Migration 019 is a data-only cleanup (deletes phantom chat-action rows) with - # no detectable schema artifact, so it is intentionally absent from this ladder; - # alembic upgrade head always runs it (idempotent) after stamping at 018. + # Migration 019 is a data-only cleanup with no detectable schema artifact. + # A schema with the 020 column was created from current ORM metadata, but it + # must still stamp at 018 so Alembic runs 019 before guarded/idempotent 020. if has_018_reaction_removed_at and has_017_chat_id_id_index and has_016_download_attempts and has_015_message_versions and has_014_soft_delete: stamp_version = '018' elif has_017_chat_id_id_index and has_016_download_attempts and has_015_message_versions and has_014_soft_delete: @@ -420,6 +431,10 @@ if has_tables and not has_alembic: cur.execute(\"SELECT name FROM sqlite_master WHERE type='index' AND name='idx_reactions_chat_message'\") has_018_reaction_removed_at = ('removed_at' in reaction_columns) and (cur.fetchone() is not None) + # Migration 020 is schema-only, but migration 019 before it is data-only and + # must still run for databases created from current ORM metadata. + has_020_sender_name = 'sender_name' in msg_columns + # Check all artifacts from migration 010: viewer_tokens, app_settings, viewer_accounts.no_download cur.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='viewer_tokens'\") has_010_tokens = cur.fetchone() is not None @@ -459,9 +474,8 @@ if has_tables and not has_alembic: has_push_subs = cur.fetchone() is not None # Determine which version to stamp based on existing schema - # Migration 019 is a data-only cleanup (deletes phantom chat-action rows) with - # no detectable schema artifact, so it is intentionally absent from this ladder; - # alembic upgrade head always runs it (idempotent) after stamping at 018. + # Even when the 020 artifact exists, cap the stamp at 018 so migration 019 + # runs before guarded/idempotent migration 020. if has_018_reaction_removed_at and has_017_chat_id_id_index and has_016_download_attempts and has_015_message_versions and has_014_soft_delete: stamp_version = '018' elif has_017_chat_id_id_index and has_016_download_attempts and has_015_message_versions and has_014_soft_delete: diff --git a/src/__init__.py b/src/__init__.py index eeecab5d..b27e350e 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -2,4 +2,4 @@ Telegram Backup Automation - Main Package """ -__version__ = "7.27.1" +__version__ = "7.28.0" diff --git a/src/__main__.py b/src/__main__.py index af94f892..c91f35ef 100644 --- a/src/__main__.py +++ b/src/__main__.py @@ -265,7 +265,7 @@ async def run_import(args) -> int: config = Config() setup_logging(config) - importer = await TelegramImporter.create(config.media_path) + importer = await TelegramImporter.create(config.media_path, config.max_filename_bytes) try: summary = await importer.run( export_path=args.path, diff --git a/src/db/adapter.py b/src/db/adapter.py index b3e3e63a..2d11180e 100644 --- a/src/db/adapter.py +++ b/src/db/adapter.py @@ -55,6 +55,10 @@ def _strip_tz(dt: datetime | None) -> datetime | None: return dt +def _is_nonblank_text(value: Any) -> bool: + return isinstance(value, str) and bool(value.strip()) + + def _message_conflict_update_values(message_data: dict[str, Any], values: dict[str, Any]) -> dict[str, Any]: """Build update values for message upserts without undoing soft deletes.""" update_values = dict(values) @@ -205,10 +209,13 @@ def convert_to_serializable(obj): return "{}" def _message_values(self, message_data: dict[str, Any]) -> dict[str, Any]: + sender_name = message_data.get("sender_name") + sender_name = sender_name.strip() if _is_nonblank_text(sender_name) else None return { "id": message_data["id"], "chat_id": message_data["chat_id"], "sender_id": message_data.get("sender_id"), + "sender_name": sender_name, "date": _strip_tz(message_data["date"]), "text": message_data.get("text"), "reply_to_msg_id": message_data.get("reply_to_msg_id"), @@ -370,9 +377,9 @@ def _pending_update_values( Applies the text/edit_date gating policy, then drops every key whose value already matches the row, so re-scanning an unchanged message performs no write at all. Deliberate scope note: when text is withheld (older or - no-evidence source), the remaining metadata (raw_data, reply_to_*, sender, - …) still refreshes from the incoming payload — non-text fields stay - last-writer-wins exactly as before versioning existed. + no-evidence source), remaining metadata still refreshes from the incoming + payload. The exception is sender_name: once nonblank, that capture-time + snapshot is immutable. """ update_values = _message_conflict_update_values(message_data, values) if self._should_apply_upsert_text(existing, values): @@ -384,6 +391,13 @@ def _pending_update_values( update_values.pop("text", None) update_values.pop("edit_date", None) + # Sender names are capture-time snapshots. A missing/blank snapshot may + # be hydrated once, but a nonblank archived value is immutable. + if _is_nonblank_text(getattr(existing, "sender_name", None)) or not _is_nonblank_text( + values.get("sender_name") + ): + update_values.pop("sender_name", None) + changed = {} for key, value in update_values.items(): if key in ("id", "chat_id"): @@ -971,11 +985,14 @@ def _message_to_dict(self, message: Message) -> dict[str, Any]: deleted_at = getattr(message, "deleted_at", None) if not isinstance(deleted_at, datetime): deleted_at = None + sender_name = getattr(message, "sender_name", None) + sender_name = sender_name.strip() if _is_nonblank_text(sender_name) else None return { "id": message.id, "chat_id": message.chat_id, "sender_id": message.sender_id, + "sender_name": sender_name, "date": message.date, "text": message.text, "reply_to_msg_id": message.reply_to_msg_id, @@ -1189,7 +1206,14 @@ async def get_media_paginated( """ async with self.db_manager.async_session_factory() as session: stmt = ( - select(Media, Message.date, User.first_name, User.last_name) + select( + Media, + Message.date, + Message.sender_name, + User.first_name, + User.last_name, + User.username, + ) .join( Message, and_( @@ -1245,9 +1269,9 @@ async def get_media_paginated( "height": media.height, "duration": media.duration, "message_date": msg_date.isoformat() if msg_date else None, - "sender_name": f"{first_name or ''} {last_name or ''}".strip() or None, + "sender_name": (sender_name or f"{first_name or ''} {last_name or ''}".strip() or username or None), } - for media, msg_date, first_name, last_name in rows[:limit] + for media, msg_date, sender_name, first_name, last_name, username in rows[:limit] ] return {"items": items, "has_more": has_more} @@ -2371,6 +2395,7 @@ async def get_messages_for_export(self, chat_id: int, include_media: bool = Fals Message.text, Message.is_outgoing, Message.reply_to_msg_id, + Message.sender_name, Media.type.label("media_type"), Media.file_path.label("media_file_path"), User.first_name, @@ -2390,6 +2415,7 @@ async def get_messages_for_export(self, chat_id: int, include_media: bool = Fals Message.text, Message.is_outgoing, Message.reply_to_msg_id, + Message.sender_name, User.first_name, User.last_name, User.username, @@ -2405,7 +2431,10 @@ async def get_messages_for_export(self, chat_id: int, include_media: bool = Fals "id": row.id, "date": row.date.isoformat() if row.date else None, "sender": { - "name": f"{row.first_name or ''} {row.last_name or ''}".strip() or row.username or "Unknown", + "name": row.sender_name + or f"{row.first_name or ''} {row.last_name or ''}".strip() + or row.username + or "Unknown", "username": row.username, }, "text": row.text, diff --git a/src/db/models.py b/src/db/models.py index 80ddb7c5..1a7c7022 100644 --- a/src/db/models.py +++ b/src/db/models.py @@ -74,6 +74,7 @@ class Message(Base): chat_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("chats.id"), primary_key=True) # NOTE: sender_id has no FK constraint because it can be channel/group IDs (not in users table) sender_id: Mapped[int | None] = mapped_column(BigInteger) + sender_name: Mapped[str | None] = mapped_column(Text, nullable=True) date: Mapped[datetime] = mapped_column(DateTime, nullable=False) text: Mapped[str | None] = mapped_column(Text) reply_to_msg_id: Mapped[int | None] = mapped_column(BigInteger) diff --git a/src/listener.py b/src/listener.py index ddd185dd..61cd0d81 100644 --- a/src/listener.py +++ b/src/listener.py @@ -46,6 +46,7 @@ fallback_media_filename, finalize_atomic_download, sanitize_media_filename, + sender_display_name, service_action_type, service_message_text, utcnow_naive, @@ -1024,18 +1025,28 @@ async def on_new_message(event: events.NewMessage.Event) -> None: } await self.db.upsert_chat(chat_data) + sender = message.sender + if sender is None: + try: + sender = await call_with_flood_retry( + event.get_sender, + non_retryable=lambda _exc: True, + ) + except Exception: + sender = None + # Save sender information if available # sender_user is kept for the WS notify payload below (mirrors the API row's # flat first_name/last_name/username fields). sender_user = None - if message.sender and isinstance(message.sender, User): + if sender and isinstance(sender, User): user_data = { - "id": message.sender.id, - "username": message.sender.username, - "first_name": message.sender.first_name, - "last_name": message.sender.last_name, - "phone": message.sender.phone, - "is_bot": message.sender.bot, + "id": sender.id, + "username": sender.username, + "first_name": sender.first_name, + "last_name": sender.last_name, + "phone": sender.phone, + "is_bot": sender.bot, } await self.db.upsert_user(user_data) sender_user = user_data @@ -1044,6 +1055,7 @@ async def on_new_message(event: events.NewMessage.Event) -> None: "id": message.id, "chat_id": chat_id, "sender_id": message.sender_id, + "sender_name": sender_display_name(sender), "date": message.date, "text": message.text or "", "reply_to_msg_id": message.reply_to_msg_id if hasattr(message, "reply_to_msg_id") else None, @@ -1185,6 +1197,18 @@ async def on_chat_action(event: events.ChatAction.Event) -> None: # chat_edit_title, ...), derived from the MessageAction class name. action_type = service_action_type(msg.action) + sender = getattr(msg, "sender", None) + if sender is None: + get_sender = getattr(msg, "get_sender", None) + if callable(get_sender): + try: + sender = await call_with_flood_retry( + get_sender, + non_retryable=lambda _exc: True, + ) + except Exception: + sender = None + # Metadata classification (Telethon 1.43 ChatAction semantics): # photo changed -> new_photo set AND photo is a Photo # photo removed -> new_photo set AND photo is None @@ -1237,6 +1261,7 @@ async def on_chat_action(event: events.ChatAction.Event) -> None: "id": msg.id, "chat_id": chat_id, "sender_id": msg.sender_id, + "sender_name": sender_display_name(sender), "date": msg.date, "text": service_text or "", "reply_to_msg_id": msg.reply_to_msg_id, diff --git a/src/message_utils.py b/src/message_utils.py index dca70f88..8b4402fb 100644 --- a/src/message_utils.py +++ b/src/message_utils.py @@ -18,6 +18,24 @@ def utcnow_naive() -> datetime: return datetime.now(UTC).replace(tzinfo=None) +def sender_display_name(sender: object | None) -> str | None: + """Return a trimmed capture-time display name for a Telegram sender.""" + if sender is None: + return None + + first_name = getattr(sender, "first_name", None) + last_name = getattr(sender, "last_name", None) + name_parts = [value.strip() for value in (first_name, last_name) if isinstance(value, str) and value.strip()] + if name_parts: + return " ".join(name_parts) + + for attribute in ("title", "username"): + value = getattr(sender, attribute, None) + if isinstance(value, str) and value.strip(): + return value.strip() + return None + + def compute_directory_size(path: str) -> int: """Return total on-disk size (bytes) of regular files under `path`. diff --git a/src/telegram_backup.py b/src/telegram_backup.py index b540e9d6..873e41c9 100644 --- a/src/telegram_backup.py +++ b/src/telegram_backup.py @@ -57,6 +57,7 @@ fallback_media_filename, finalize_atomic_download, resolve_shared_file_path, + sender_display_name, service_action_type, service_message_text, utcnow_naive, @@ -2276,9 +2277,14 @@ async def _process_message(self, message: Message, chat_id: int) -> dict: message: Message object from Telegram chat_id: Chat identifier """ + # Scheduled sweeps snapshot only sender entities already attached by + # Telethon; resolving a missing sender here would add one API request per + # message and create avoidable flood risk on large histories. + sender = message.sender + # Save sender information if available - if message.sender: - sender_data = self._extract_user_data(message.sender) + if sender: + sender_data = self._extract_user_data(sender) if sender_data: await self.db.upsert_user(sender_data) @@ -2291,6 +2297,7 @@ async def _process_message(self, message: Message, chat_id: int) -> dict: "id": message.id, "chat_id": chat_id, "sender_id": message.sender_id, + "sender_name": sender_display_name(sender), "date": message.date, "text": message.text or "", "reply_to_msg_id": message.reply_to_msg_id, @@ -2354,7 +2361,6 @@ async def _process_message(self, message: Message, chat_id: int) -> dict: if subject_id is not None: actor_name = await self._resolve_display_name(subject_id) else: - sender = message.sender actor_name = None if sender is not None: actor_name = getattr(sender, "first_name", "") or getattr(sender, "title", "") diff --git a/src/telegram_import.py b/src/telegram_import.py index 515b8618..fe3dacc3 100644 --- a/src/telegram_import.py +++ b/src/telegram_import.py @@ -8,16 +8,17 @@ Both formats insert messages, users, and media into the existing database schema. """ +import asyncio import json import logging import re import shutil from datetime import UTC, datetime -from pathlib import Path +from pathlib import Path, PurePosixPath from typing import Any from .db import DatabaseAdapter, close_database, get_adapter, init_database -from .message_utils import utcnow_naive +from .message_utils import build_media_filename, utcnow_naive logger = logging.getLogger(__name__) @@ -73,7 +74,7 @@ def parse_from_id(from_id: str | None) -> int | None: Formats: "user123456789", "channel123456789", "group123456789" """ - if not from_id: + if not isinstance(from_id, str) or not from_id: return None for prefix, multiplier in (("user", 1), ("channel", -1), ("group", -1)): if from_id.startswith(prefix): @@ -87,6 +88,13 @@ def parse_from_id(from_id: str | None) -> int | None: return None +def _clean_sender_name(value: Any) -> str | None: + if not isinstance(value, str): + return None + cleaned = value.strip() + return cleaned or None + + def derive_chat_id(export_id: int, export_type: str) -> int: """Derive a marked chat ID from the export's raw id and type.""" if export_type in ("personal_chat", "bot_chat", "saved_messages"): @@ -149,24 +157,56 @@ def parse_edited_date(msg: dict) -> datetime | None: return None -def _detect_media(msg: dict, export_path: Path) -> tuple[str | None, str | None, str | None]: +def _detect_media(msg: dict) -> tuple[str | None, str | None, str | None]: """Detect media type and file path from an export message. Returns (media_type, relative_path, original_filename). """ - if "photo" in msg and msg["photo"]: + if isinstance(msg.get("photo"), str) and msg["photo"]: rel = msg["photo"] return "photo", rel, Path(rel).name - if "file" in msg and msg["file"]: + if isinstance(msg.get("file"), str) and msg["file"]: rel = msg["file"] - fname = msg.get("file_name") or Path(rel).name - media_type = MEDIA_TYPE_MAP.get(msg.get("media_type", ""), "document") + supplied_name = msg.get("file_name") + fname = supplied_name if isinstance(supplied_name, str) and supplied_name else Path(rel).name + supplied_type = msg.get("media_type", "") + media_type = MEDIA_TYPE_MAP.get(supplied_type, "document") if isinstance(supplied_type, str) else "document" return media_type, rel, fname return None, None, None +def _resolve_export_media_path(export_root: Path, relative_path: str) -> Path | None: + """Resolve an export media reference without allowing it to leave the export root.""" + # SECURITY-REVIEW: Export paths are untrusted and must remain below export_root. + if not isinstance(relative_path, str) or not relative_path: + return None + + normalized = relative_path.replace("\\", "/") + if re.match(r"^[A-Za-z]:", normalized): + return None + + relative = PurePosixPath(normalized) + if relative.is_absolute() or ".." in relative.parts: + return None + + try: + root = export_root.resolve(strict=True) + candidate = root + for part in relative.parts: + candidate /= part + if candidate.is_symlink(): + return None + resolved = candidate.resolve(strict=True) + except OSError, RuntimeError, ValueError: + return None + + if not resolved.is_relative_to(root) or not resolved.is_file(): + return None + return resolved + + def _build_service_text(msg: dict) -> str: """Build display text for service messages from action fields.""" action = msg.get("action", "") @@ -227,22 +267,40 @@ def parse_html_date(date_str: str) -> str | None: return None +def _resolve_export_control_file(export_root: Path, candidate: Path) -> Path | None: + """Return a regular export control file only when it is contained and not a symlink.""" + # SECURITY-REVIEW: result.json/messages*.html are controlled by the export artifact. + if candidate.is_symlink(): + return None + try: + root = export_root.resolve(strict=True) + resolved = candidate.resolve(strict=True) + except OSError, RuntimeError, ValueError: + return None + if not resolved.is_relative_to(root) or not resolved.is_file(): + return None + return resolved + + def _find_html_files(path: Path) -> list[Path]: """Find and sort HTML message files in export directory. Returns sorted list: messages.html, messages2.html, messages3.html, ... """ files: list[Path] = [] - main = path / "messages.html" - if main.exists(): + main = _resolve_export_control_file(path, path / "messages.html") + if main is not None: files.append(main) idx = 2 while True: - f = path / f"messages{idx}.html" - if not f.exists(): + candidate = path / f"messages{idx}.html" + if not candidate.exists() and not candidate.is_symlink(): + break + html_file = _resolve_export_control_file(path, candidate) + if html_file is None: break - files.append(f) + files.append(html_file) idx += 1 return files @@ -505,15 +563,17 @@ def _parse_html_export(html_files: list[Path], export_path: Path) -> tuple[str, class TelegramImporter: """Import Telegram Desktop exports into Telegram-Archive database.""" - def __init__(self, db: DatabaseAdapter, media_path: str): + def __init__(self, db: DatabaseAdapter, media_path: str, max_filename_bytes: int = 143): self.db = db self.media_path = media_path + self.media_root = Path(media_path).resolve() + self.max_filename_bytes = max_filename_bytes @classmethod - async def create(cls, media_path: str) -> TelegramImporter: + async def create(cls, media_path: str, max_filename_bytes: int = 143) -> TelegramImporter: await init_database() db = await get_adapter() - return cls(db, media_path) + return cls(db, media_path, max_filename_bytes) async def close(self) -> None: await close_database() @@ -531,11 +591,11 @@ async def run( Auto-detects JSON (result.json) or HTML (messages.html) export format. Returns a summary dict with counts per chat. """ - path = Path(export_path) - result_file = path / "result.json" + path = Path(export_path).resolve() + result_file = _resolve_export_control_file(path, path / "result.json") html_files = _find_html_files(path) - if result_file.exists(): + if result_file is not None: logger.info(f"Reading {result_file}...") with open(result_file, encoding="utf-8") as f: data = json.load(f) @@ -650,13 +710,19 @@ async def _import_chat( max_msg_id = max(max_msg_id, msg_id) msg_type = msg.get("type", "message") - sender_id = parse_from_id(msg.get("from_id")) + if msg_type == "service": + sender_name = _clean_sender_name(msg.get("actor")) or _clean_sender_name(msg.get("from")) + sender_id = parse_from_id(msg.get("actor_id") or msg.get("from_id")) + else: + sender_name = _clean_sender_name(msg.get("from")) + sender_id = parse_from_id(msg.get("from_id")) + if sender_id and sender_id > 0 and sender_id not in seen_users and not dry_run: seen_users.add(sender_id) await self.db.upsert_user( { "id": sender_id, - "first_name": msg.get("from", ""), + "first_name": sender_name or "", } ) @@ -678,6 +744,7 @@ async def _import_chat( "id": msg_id, "chat_id": chat_id, "sender_id": sender_id, + "sender_name": sender_name, "date": date, "text": text, "reply_to_msg_id": msg.get("reply_to_message_id"), @@ -692,47 +759,61 @@ async def _import_chat( msg_count += 1 if not skip_media: - media_type, rel_path, orig_name = _detect_media(msg, export_path) + media_type, rel_path, orig_name = _detect_media(msg) if media_type and rel_path: - source = export_path / rel_path - if source.exists(): - media_id = f"import_{chat_id}_{msg_id}" - dest_dir = Path(self.media_path) / str(chat_id) - dest_name = f"{media_id}_{orig_name}" if orig_name else f"{media_id}" - dest_file = dest_dir / dest_name - stored_path = f"{chat_id}/{dest_name}" - - media_data = { - "id": media_id, - "message_id": msg_id, - "chat_id": chat_id, - "type": media_type, - "file_name": orig_name, - "file_path": stored_path, - "file_size": source.stat().st_size, - "mime_type": msg.get("mime_type"), - "width": msg.get("width"), - "height": msg.get("height"), - "duration": msg.get("duration_seconds"), - "downloaded": True, - "download_date": utcnow_naive(), - "_source": str(source), - "_dest": str(dest_file), - } - media_batch.append(media_data) - media_count += 1 + source = _resolve_export_media_path(export_path, rel_path) + if source is not None: + media_data = None + try: + media_id = f"import_{chat_id}_{msg_id}" + dest_dir = (self.media_root / str(chat_id)).resolve() + original_name = orig_name or Path(rel_path.replace("\\", "/")).name + dest_name = build_media_filename(media_id, original_name, self.max_filename_bytes) + dest_file = dest_dir / dest_name + resolved_dest = dest_file.resolve() + if not resolved_dest.is_relative_to(self.media_root): + logger.warning("Skipping imported media with an unsafe destination") + else: + file_size = source.stat().st_size + stored_path = f"{chat_id}/{dest_name}" + media_data = { + "id": media_id, + "message_id": msg_id, + "chat_id": chat_id, + "type": media_type, + "file_name": dest_name, + "file_path": stored_path, + "file_size": file_size, + "mime_type": msg.get("mime_type"), + "width": msg.get("width"), + "height": msg.get("height"), + "duration": msg.get("duration_seconds"), + "downloaded": True, + "download_date": utcnow_naive(), + "_source": str(source), + "_dest": str(resolved_dest), + } + except (OSError, RuntimeError, ValueError) as exc: + logger.warning( + "Skipping imported media after an invalid path or filesystem error (%s)", + type(exc).__name__, + ) + if media_data is not None: + media_batch.append(media_data) + if dry_run: + media_count += 1 else: - logger.warning(f"Media file not found: {source}") + logger.warning("Skipping imported media outside the export root or missing from the export") if len(batch) >= BATCH_SIZE: if not dry_run: - await self._flush_batch(batch, media_batch) + media_count += await self._flush_batch(batch, media_batch) batch.clear() media_batch.clear() logger.info(f" Progress: {msg_count}/{len(messages)} messages") if batch and not dry_run: - await self._flush_batch(batch, media_batch) + media_count += await self._flush_batch(batch, media_batch) if not dry_run and msg_count > 0: await self.db.update_sync_status(chat_id, max_msg_id, msg_count) @@ -752,17 +833,30 @@ async def _flush_batch( self, messages: list[dict[str, Any]], media: list[dict[str, Any]], - ) -> None: + ) -> int: """Flush a batch of messages and media to the database.""" await self.db.insert_messages_batch(messages) + copied = 0 for m in media: source = m.pop("_source") dest = m.pop("_dest") dest_path = Path(dest) - dest_path.parent.mkdir(parents=True, exist_ok=True) - if not dest_path.exists(): - shutil.copy2(source, dest) + # SECURITY-REVIEW: Re-check the untrusted import destination before filesystem writes. + try: + resolved_parent = dest_path.parent.resolve() + if not resolved_parent.is_relative_to(self.media_root) or dest_path.is_symlink(): + logger.warning("Skipping imported media with an unsafe destination") + continue + resolved_parent.mkdir(parents=True, exist_ok=True) + if not dest_path.exists(): + await asyncio.to_thread(shutil.copy2, source, dest_path) + except (OSError, RuntimeError, ValueError) as exc: + logger.warning("Skipping imported media after a filesystem error (%s)", type(exc).__name__) + continue await self.db.insert_media(m) + copied += 1 + + return copied diff --git a/src/web/main.py b/src/web/main.py index 7d4d4ec6..0914d4ef 100644 --- a/src/web/main.py +++ b/src/web/main.py @@ -209,11 +209,15 @@ async def handle_realtime_notification(payload: dict): chat = await db.get_chat_by_id(chat_id) if db else None chat_title = chat.get("title", "Telegram") if chat else "Telegram" - sender_name = "" - if message.get("sender_id"): + snapshot_name = message.get("sender_name") + sender_name = snapshot_name.strip() if isinstance(snapshot_name, str) else "" + if not sender_name and message.get("sender_id"): sender = await db.get_user_by_id(message.get("sender_id")) if db else None if sender: - sender_name = sender.get("first_name", "") or sender.get("username", "") + sender_name = ( + f"{sender.get('first_name') or ''} {sender.get('last_name') or ''}".strip() + or sender.get("username", "") + ) await push_manager.notify_new_message( chat_id=chat_id, diff --git a/src/web/templates/index.html b/src/web/templates/index.html index 8ffe3189..2e20a1f8 100644 --- a/src/web/templates/index.html +++ b/src/web/templates/index.html @@ -99,6 +99,14 @@ border-bottom-right-radius: 4px; } + .message-run-continue { + margin-bottom: 2px; + } + + .message-run-break { + margin-bottom: 10px; + } + html, body, @@ -1002,7 +1010,7 @@

Shared Media

-
{{ item.file_name }}
+
{{ getMediaDisplayName(item) }}
{{ formatFileSize(item.file_size) }} · {{ formatMediaDate(item.message_date) }}
@@ -1038,7 +1046,7 @@

Shared Media