Repository navigation
feat: harden imports and preserve sender history - #241
Conversation
Confine imported media to trusted roots while making imports resilient, and preserve per-message sender identity across capture and viewing.
📝 WalkthroughWalkthroughChangesSender archive and presentation
Schema rollout and release metadata
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
🐳 Dev images published!
The dev/test instance will pick up these changes automatically (Portainer GitOps). To test locally: docker pull drumsergio/telegram-archive:dev
docker pull drumsergio/telegram-archive-viewer:dev |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #241 +/- ##
==========================================
+ Coverage 93.45% 93.47% +0.01%
==========================================
Files 27 27
Lines 8423 8532 +109
==========================================
+ Hits 7872 7975 +103
- Misses 551 557 +6
🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (7)
tests/test_web_routes.py (1)
1718-1718: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd the return type annotation.
Annotate the new async test as
-> Noneto comply with the repository’s Python type-hinting requirement.Proposed fix
- async def test_push_prefers_archived_sender_snapshot(self): + async def test_push_prefers_archived_sender_snapshot(self) -> None:🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/test_web_routes.py` at line 1718, Update the test_push_prefers_archived_sender_snapshot async test definition to include the repository-required None return type annotation.Source: Coding guidelines
src/web/templates/index.html (2)
1416-1421: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueLabel can say "Latest known name" for a synthesized placeholder.
When
sender_nameis absent and the profile fields are empty,getSenderInfoNamefalls back toUser <id>/Deleted AccountviagetSenderName, but thedtstill reads "Latest known name". Consider "Name" for that case.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/web/templates/index.html` around lines 1416 - 1421, Update the label logic in the sender information block to display “Name” when sender_name is absent and the profile fields are empty, matching the synthesized fallback returned by getSenderInfoName; retain “Archived name” for archived names and “Latest known name” when an actual latest profile name exists.
4052-4061: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
isRunEndandisSenderBreakare now the same predicate.Both compare
getSenderRunKey(newerMsg) !== getSenderRunKey(currMsg). They serve different consumers (bubble tail vs. spacing), so keeping both names is defensible, but define one and alias the other so they can't silently drift.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/web/templates/index.html` around lines 4052 - 4061, Consolidate the duplicated sender-transition predicate used by isRunEnd and isSenderBreak: retain one implementation and make the other delegate to or alias it. Preserve both named helpers for their separate consumers while ensuring both use identical getSenderRunKey comparison behavior.src/telegram_import.py (3)
763-815: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
continueon media-path failure skips the batch-size flush for that iteration.Lines 774 and 781 jump past the
len(batch) >= BATCH_SIZEcheck at line 807. The message row is already appended, so nothing is lost — the flush is just deferred to the next message. Harmless today, but it makes the batching contract implicit; consider setting a flag and falling through instead.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/telegram_import.py` around lines 763 - 815, Replace the media-path failure continues in the import loop around _resolve_export_media_path with control flow that records the media skip and still reaches the len(batch) >= BATCH_SIZE flush check for the current message. Preserve the existing warning behavior and ensure the message row remains appended while invalid media is omitted.
835-861: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueBlocking
shutil.copy2on the event loop.
_flush_batchis async but copies files synchronously; a large media import stalls the loop. For the one-shot CLI importer this is benign, butasyncio.to_thread(shutil.copy2, source, dest_path)would be a drop-in fix if this ever runs alongside other tasks.Destination re-validation and per-item error isolation look right.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/telegram_import.py` around lines 835 - 861, Update the media copy in _flush_batch to run shutil.copy2(source, dest_path) via asyncio.to_thread, awaiting its result so the async event loop is not blocked. Preserve the existing destination validation, filesystem exception handling, and per-item continuation behavior.
164-176: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
export_pathis now unused in_detect_media.The rewritten body never touches it; path resolution moved to
_resolve_export_media_path. Drop the parameter (and update the three call sites/tests) when convenient.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/telegram_import.py` around lines 164 - 176, Remove the unused export_path parameter from _detect_media, since path resolution is handled by _resolve_export_media_path. Update all three callers and related tests to use the revised signature without changing media detection behavior.tests/test_frontend_bootstrap.py (1)
32-85: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valuePlain pytest functions instead of
unittest.TestCase.The repo guideline asks for
unittest.TestCasefor test consistency. This file already uses module-level functions, so the new tests match local style — flagging only so the deviation is deliberate.Otherwise the assertions are fine; note that
html.count("getSenderRunKey(") >= 6currently matches exactly 6 call sites, so any refactor that inlines one will fail the test.As per coding guidelines: "Use
unittest.TestCasewithMagicMock/AsyncMockfor test consistency".🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/test_frontend_bootstrap.py` around lines 32 - 85, Convert the new module-level tests in tests/test_frontend_bootstrap.py into methods on a unittest.TestCase subclass, preserving their existing assertions and test coverage. Keep the getSenderRunKey call-site count requirement intact, and follow the repository’s unittest style without adding unrelated mocking.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/listener.py`:
- Around line 1028-1033: Update the fallback sender resolution in
listener.py:1028-1033 and the service-message path in listener.py:1197-1204 to
invoke event.get_sender() or msg.get_sender() through
call_with_flood_retry(...), retrying FloodWaitError while treating other
exceptions as non-retryable; if no sender is directly attached and resolution
still fails, leave the snapshot unset.
In `@tests/test_entrypoint_schema_detection.py`:
- Around line 125-145: Update tests/test_entrypoint_schema_detection.py:125-145,
159-168, and 254-260 by converting the affected module-level tests into methods
on unittest.TestCase classes and adding complete parameter and return
annotations, including -> None for the PostgreSQL detection test. In
tests/test_migration_020.py:15-64, annotate every helper signature and convert
all migration tests into unittest.TestCase methods, preserving their existing
assertions and behavior.
In `@tests/test_migration_020.py`:
- Around line 15-25: Update _load_migration and _run with complete type
annotations, including return types and appropriate parameter types. Convert the
module-level tests in tests/test_migration_020.py into methods on a
unittest.TestCase subclass, preserving their existing assertions and migration
behavior.
---
Nitpick comments:
In `@src/telegram_import.py`:
- Around line 763-815: Replace the media-path failure continues in the import
loop around _resolve_export_media_path with control flow that records the media
skip and still reaches the len(batch) >= BATCH_SIZE flush check for the current
message. Preserve the existing warning behavior and ensure the message row
remains appended while invalid media is omitted.
- Around line 835-861: Update the media copy in _flush_batch to run
shutil.copy2(source, dest_path) via asyncio.to_thread, awaiting its result so
the async event loop is not blocked. Preserve the existing destination
validation, filesystem exception handling, and per-item continuation behavior.
- Around line 164-176: Remove the unused export_path parameter from
_detect_media, since path resolution is handled by _resolve_export_media_path.
Update all three callers and related tests to use the revised signature without
changing media detection behavior.
In `@src/web/templates/index.html`:
- Around line 1416-1421: Update the label logic in the sender information block
to display “Name” when sender_name is absent and the profile fields are empty,
matching the synthesized fallback returned by getSenderInfoName; retain
“Archived name” for archived names and “Latest known name” when an actual latest
profile name exists.
- Around line 4052-4061: Consolidate the duplicated sender-transition predicate
used by isRunEnd and isSenderBreak: retain one implementation and make the other
delegate to or alias it. Preserve both named helpers for their separate
consumers while ensuring both use identical getSenderRunKey comparison behavior.
In `@tests/test_frontend_bootstrap.py`:
- Around line 32-85: Convert the new module-level tests in
tests/test_frontend_bootstrap.py into methods on a unittest.TestCase subclass,
preserving their existing assertions and test coverage. Keep the getSenderRunKey
call-site count requirement intact, and follow the repository’s unittest style
without adding unrelated mocking.
In `@tests/test_web_routes.py`:
- Line 1718: Update the test_push_prefers_archived_sender_snapshot async test
definition to include the repository-required None return type annotation.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: a4793a19-c64c-4eec-b6c6-8b50a4e3b689
⛔ Files ignored due to path filters (2)
alembic/versions/20260727_020_add_message_sender_name.pyis excluded by!alembic/versions/**uv.lockis excluded by!**/*.lock
📒 Files selected for processing (24)
docs/CHANGELOG.mdpyproject.tomlscripts/entrypoint.shsrc/__init__.pysrc/__main__.pysrc/db/adapter.pysrc/db/models.pysrc/listener.pysrc/message_utils.pysrc/telegram_backup.pysrc/telegram_import.pysrc/web/main.pysrc/web/templates/index.htmltests/test_db_adapter_soft_delete_upsert.pytests/test_entrypoint_schema_detection.pytests/test_frontend_bootstrap.pytests/test_listener_chat_actions.pytests/test_listener_extended.pytests/test_migration_020.pytests/test_sender_avatars.pytests/test_telegram_backup.pytests/test_telegram_import.pytests/test_web_messages_api.pytests/test_web_routes.py
Keep importer batching and the event loop responsive on media failures, preserve flood-aware sender resolution, and align UI and tests with repository conventions.
|
🐳 Dev images published!
The dev/test instance will pick up these changes automatically (Portainer GitOps). To test locally: docker pull drumsergio/telegram-archive:dev
docker pull drumsergio/telegram-archive-viewer:dev |
There was a problem hiding this comment.
🧹 Nitpick comments (3)
tests/test_telegram_import.py (3)
176-180: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAssert the complete no-media result.
This test checks
media_typeandrelbut notfname. Addself.assertIsNone(fname)so a stale or unexpected filename cannot pass unnoticed.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/test_telegram_import.py` around lines 176 - 180, Update test_no_media to also assert that the fname result from _detect_media({}) is None, while preserving the existing assertions for media_type and rel.
469-475: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winSkip when symlink creation is unavailable.
hasattr(os, "symlink")does not guarantee permission to create symlinks; on some platforms,os.symlink(...)can raiseOSErrorand fail the suite. Catch that setup error and callself.skipTest(...)in all three tests.Also applies to: 661-668, 674-678
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/test_telegram_import.py` around lines 469 - 475, Update the setup of all three symlink tests, including test_import_rejects_media_symlink_outside_export_root and the tests at the referenced locations, to catch OSError from os.symlink and call self.skipTest(...) when creation is unavailable. Keep the existing hasattr(os, "symlink") guard and test behavior unchanged when symlink creation succeeds.
181-181: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd type annotations to new test signatures.
The newly added test methods and
fail_first_copyhelper lack type hints. Add-> Noneto test methods and concrete argument/return annotations to the helper.As per coding guidelines, Python files must use type hints for function signatures.
Also applies to: 365-365, 435-435, 470-470, 500-500, 538-538, 566-566, 581-581, 662-662, 675-675
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/test_telegram_import.py` at line 181, Add type annotations to the newly added test methods in the test class, including test_non_string_paths_and_names_are_ignored_safely and the other affected tests, using -> None. Annotate the fail_first_copy helper with concrete types for every parameter and its return value, following the surrounding test conventions.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@tests/test_telegram_import.py`:
- Around line 176-180: Update test_no_media to also assert that the fname result
from _detect_media({}) is None, while preserving the existing assertions for
media_type and rel.
- Around line 469-475: Update the setup of all three symlink tests, including
test_import_rejects_media_symlink_outside_export_root and the tests at the
referenced locations, to catch OSError from os.symlink and call
self.skipTest(...) when creation is unavailable. Keep the existing hasattr(os,
"symlink") guard and test behavior unchanged when symlink creation succeeds.
- Line 181: Add type annotations to the newly added test methods in the test
class, including test_non_string_paths_and_names_are_ignored_safely and the
other affected tests, using -> None. Annotate the fail_first_copy helper with
concrete types for every parameter and its return value, following the
surrounding test conventions.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: c343a6a1-6ef7-4c54-9004-043b243d50fa
📒 Files selected for processing (8)
src/listener.pysrc/telegram_import.pysrc/web/templates/index.htmltests/test_entrypoint_schema_detection.pytests/test_frontend_bootstrap.pytests/test_migration_020.pytests/test_telegram_import.pytests/test_web_routes.py
🚧 Files skipped from review as they are similar to previous changes (6)
- src/listener.py
- tests/test_frontend_bootstrap.py
- tests/test_migration_020.py
- tests/test_entrypoint_schema_detection.py
- src/web/templates/index.html
- src/telegram_import.py
* feat: secure imports and preserve sender history Confine imported media to trusted roots while making imports resilient, and preserve per-message sender identity across capture and viewing. * fix: address v7.28 review findings Keep importer batching and the event loop responsive on media failures, preserve flood-aware sender resolution, and align UI and tests with repository conventions.
* feat: secure imports and preserve sender history Confine imported media to trusted roots while making imports resilient, and preserve per-message sender identity across capture and viewing. * fix: address v7.28 review findings Keep importer batching and the event loop responsive on media failures, preserve flood-aware sender resolution, and align UI and tests with repository conventions.
Summary
Addresses #236, #238, #239, and #240.
Type of Change
Database Changes
scripts/Migration 020 adds nullable
messages.sender_name; existing rows remain unchanged. Pre-Alembic databases still stamp at 018 so data-only migration 019 runs before guarded migration 020.Data Consistency Checklist
chat_idvalues use marked format (via_get_marked_id())_strip_tz()before DB operationssender_nameis normalized and first-nonblank/write-once in both single and batch upserts.Testing
.venv/bin/python -m pytest tests/ -q: 2,407 passed, 150 subtests).venv/bin/ruff check .).venv/bin/ruff format --check .)Additional review: independent code review approved with no medium-or-higher findings; independent security review found no medium-or-higher issues.
Security Checklist
Import control files, source paths, destination names, and destination roots are constrained before filesystem access. Copy failures are isolated per media item.
Deployment Notes
v7.28.0after merge publishes the release and both production Docker images.Summary by CodeRabbit
New Features
Bug Fixes
Upgrade