Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions alembic/versions/20260727_020_add_message_sender_name.py
Original file line number Diff line number Diff line change
@@ -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)
15 changes: 15 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
26 changes: 20 additions & 6 deletions scripts/entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion src/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
Telegram Backup Automation - Main Package
"""

__version__ = "7.27.1"
__version__ = "7.28.0"
2 changes: 1 addition & 1 deletion src/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
43 changes: 36 additions & 7 deletions src/db/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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):
Expand All @@ -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"):
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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_(
Expand Down Expand Up @@ -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}
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand Down
1 change: 1 addition & 0 deletions src/db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
39 changes: 32 additions & 7 deletions src/listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
fallback_media_filename,
finalize_atomic_download,
sanitize_media_filename,
sender_display_name,
service_action_type,
service_message_text,
utcnow_naive,
Expand Down Expand Up @@ -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
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

# 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
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
18 changes: 18 additions & 0 deletions src/message_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
Loading
Loading