feat: filter WebDAV sync by year folders (2025/2026)
Add webdav_include_years account setting, skip files outside allowed year folders during sync, and a setup tool to mark older paths as already forwarded.
This commit is contained in:
1 parent
529ecb31a4
commit
28164ad9f4
8 files changed
+173
No files matched your search
@@ -0,0 +1,23 @@
|
||||
"""Add webdav_include_years for year-folder filtering
|
||||
|
||||
Revision ID: 005_webdav_years
|
||||
Revises: 004_webdav
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "005_webdav_years"
|
||||
down_revision: Union[str, None] = "004_webdav"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("accounts", sa.Column("webdav_include_years", sa.JSON(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("accounts", "webdav_include_years")
|
||||
@@ -20,6 +20,7 @@ class AccountBase(BaseModel):
|
||||
webdav_path: str | None = None
|
||||
webdav_user: str | None = None
|
||||
webdav_verify_ssl: bool = True
|
||||
webdav_include_years: list[str] | None = None
|
||||
delivery_mode: str = "smtp"
|
||||
smtp_host: str | None = None
|
||||
smtp_port: int = 587
|
||||
@@ -116,6 +117,7 @@ class AccountUpdate(BaseModel):
|
||||
webdav_user: str | None = None
|
||||
webdav_password: str | None = None
|
||||
webdav_verify_ssl: bool | None = None
|
||||
webdav_include_years: list[str] | None = None
|
||||
smtp_host: str | None = None
|
||||
smtp_port: int | None = None
|
||||
smtp_user: str | None = None
|
||||
|
||||
@@ -93,6 +93,7 @@ class Account(Base):
|
||||
webdav_user: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
webdav_password_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
webdav_verify_ssl: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||
webdav_include_years: Mapped[list[Any] | None] = mapped_column(JSON, nullable=True)
|
||||
|
||||
smtp_host: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
smtp_port: Mapped[int] = mapped_column(Integer, default=587, nullable=False)
|
||||
|
||||
@@ -56,6 +56,7 @@ def account_to_dict(account: Account, *, include_secrets: bool = False) -> dict:
|
||||
"webdav_user": account.webdav_user,
|
||||
"webdav_password": mask_password(),
|
||||
"webdav_verify_ssl": account.webdav_verify_ssl,
|
||||
"webdav_include_years": account.webdav_include_years,
|
||||
"delivery_mode": delivery_mode,
|
||||
"smtp_host": account.smtp_host,
|
||||
"smtp_port": account.smtp_port,
|
||||
@@ -137,6 +138,7 @@ def create_account(db: Session, data: dict) -> Account:
|
||||
else None
|
||||
),
|
||||
webdav_verify_ssl=data.get("webdav_verify_ssl", True),
|
||||
webdav_include_years=data.get("webdav_include_years") if source_type == SourceType.webdav else None,
|
||||
delivery_mode=delivery_mode,
|
||||
smtp_host=data.get("smtp_host"),
|
||||
smtp_port=data.get("smtp_port", 587),
|
||||
@@ -179,6 +181,7 @@ def update_account(db: Session, account_id: int, data: dict) -> Account:
|
||||
"webdav_path",
|
||||
"webdav_user",
|
||||
"webdav_verify_ssl",
|
||||
"webdav_include_years",
|
||||
"smtp_host",
|
||||
"smtp_port",
|
||||
"smtp_user",
|
||||
|
||||
@@ -44,6 +44,7 @@ from forwarder.webdav.client import (
|
||||
list_files,
|
||||
normalize_webdav_folder_path,
|
||||
parse_webdav_message_key,
|
||||
webdav_path_matches_include_years,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -108,6 +109,12 @@ def sync_webdav_account(
|
||||
):
|
||||
continue
|
||||
|
||||
if not webdav_path_matches_include_years(
|
||||
remote_file.relative_path,
|
||||
account.webdav_include_years,
|
||||
):
|
||||
continue
|
||||
|
||||
message_key = get_webdav_message_key(remote_file.relative_path)
|
||||
if message_key in processed_keys:
|
||||
result.messages_skipped += 1
|
||||
|
||||
@@ -94,6 +94,31 @@ def parse_webdav_message_key(message_key: str) -> str | None:
|
||||
return path
|
||||
|
||||
|
||||
def webdav_year_folder(relative_path: str) -> str | None:
|
||||
parts = [part for part in relative_path.strip("/").split("/") if part]
|
||||
if not parts:
|
||||
return None
|
||||
head = parts[0]
|
||||
if len(head) == 4 and head.isdigit():
|
||||
return head
|
||||
return None
|
||||
|
||||
|
||||
def webdav_path_matches_include_years(
|
||||
relative_path: str,
|
||||
include_years: list[str] | None,
|
||||
) -> bool:
|
||||
if not include_years:
|
||||
return True
|
||||
allowed = {year.strip() for year in include_years if year and year.strip()}
|
||||
if not allowed:
|
||||
return True
|
||||
year = webdav_year_folder(relative_path)
|
||||
if year is None:
|
||||
return False
|
||||
return year in allowed
|
||||
|
||||
|
||||
def _client(config: WebdavConfig, *, timeout: float = 60.0) -> httpx.Client:
|
||||
return httpx.Client(
|
||||
timeout=timeout,
|
||||
|
||||
@@ -7,6 +7,7 @@ from forwarder.webdav.client import (
|
||||
get_webdav_message_key,
|
||||
normalize_webdav_folder_path,
|
||||
parse_webdav_message_key,
|
||||
webdav_path_matches_include_years,
|
||||
)
|
||||
|
||||
PROPFIND_SAMPLE = b"""<?xml version="1.0" encoding="utf-8"?>
|
||||
@@ -71,6 +72,14 @@ def test_webdav_message_key_roundtrip():
|
||||
assert parse_webdav_message_key("imap:123") is None
|
||||
|
||||
|
||||
def test_webdav_path_matches_include_years():
|
||||
assert webdav_path_matches_include_years("2025/invoice.pdf", ["2025", "2026"])
|
||||
assert webdav_path_matches_include_years("2026/a.pdf", ["2025", "2026"])
|
||||
assert not webdav_path_matches_include_years("2024/old.pdf", ["2025", "2026"])
|
||||
assert not webdav_path_matches_include_years("misc/file.pdf", ["2025", "2026"])
|
||||
assert webdav_path_matches_include_years("2024/old.pdf", None)
|
||||
|
||||
|
||||
def test_parse_propfind_response():
|
||||
root = "https://cloud.example.com/remote.php/dav/files/user/Faturas/"
|
||||
files = _parse_propfind_response(root, PROPFIND_SAMPLE)
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Mark pre-cutoff WebDAV files as forwarded; optionally list folder stats."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from collections import Counter
|
||||
|
||||
from forwarder.db.models import MessageStatus
|
||||
from forwarder.db.session import SessionLocal
|
||||
from forwarder.services.account_service import get_account
|
||||
from forwarder.services.sync_service import _upsert_message
|
||||
from forwarder.services.webdav_sync_service import resolve_webdav_config
|
||||
from forwarder.webdav.client import (
|
||||
get_webdav_message_key,
|
||||
list_files,
|
||||
normalize_webdav_folder_path,
|
||||
webdav_path_matches_include_years,
|
||||
webdav_year_folder,
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="WebDAV year filter setup")
|
||||
parser.add_argument("account_id", type=int)
|
||||
parser.add_argument(
|
||||
"--allowed-years",
|
||||
default="2025,2026",
|
||||
help="Comma-separated year folder names to keep active (default: 2025,2026)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--mark-skipped",
|
||||
action="store_true",
|
||||
help="Insert skipped records for files outside allowed years",
|
||||
)
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
allowed = {year.strip() for year in args.allowed_years.split(",") if year.strip()}
|
||||
if not allowed:
|
||||
print("No allowed years specified", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
account = get_account(db, args.account_id)
|
||||
config = resolve_webdav_config(account)
|
||||
files = list_files(config)
|
||||
folder_label = normalize_webdav_folder_path(account.webdav_path)
|
||||
|
||||
allowed_list = sorted(allowed)
|
||||
by_year: Counter[str] = Counter()
|
||||
unknown = 0
|
||||
for remote_file in files:
|
||||
year = webdav_year_folder(remote_file.relative_path)
|
||||
if year is None:
|
||||
unknown += 1
|
||||
else:
|
||||
by_year[year] += 1
|
||||
|
||||
print(f"Account {account.id} ({account.name}): {len(files)} file(s) listed")
|
||||
print("By year folder:")
|
||||
for year in sorted(by_year):
|
||||
flag = "KEEP" if year in allowed else "SKIP"
|
||||
print(f" {year}: {by_year[year]} ({flag})")
|
||||
if unknown:
|
||||
print(f" (no year folder): {unknown}")
|
||||
|
||||
if not args.mark_skipped:
|
||||
return 0
|
||||
|
||||
marked = 0
|
||||
for remote_file in files:
|
||||
if webdav_path_matches_include_years(remote_file.relative_path, allowed_list):
|
||||
continue
|
||||
message_key = get_webdav_message_key(remote_file.relative_path)
|
||||
if args.dry_run:
|
||||
marked += 1
|
||||
continue
|
||||
_upsert_message(
|
||||
db,
|
||||
account_id=account.id,
|
||||
message_key=message_key,
|
||||
folder=folder_label,
|
||||
uid=remote_file.etag or str(remote_file.size),
|
||||
subject=remote_file.name,
|
||||
from_addr=f"webdav:{account.webdav_url}",
|
||||
date=remote_file.modified or "",
|
||||
status=MessageStatus.forwarded,
|
||||
error_message="skipped: pre-cutoff year folder",
|
||||
)
|
||||
marked += 1
|
||||
|
||||
action = "Would mark" if args.dry_run else "Marked"
|
||||
print(f"{action} {marked} file(s) as forwarded (outside {sorted(allowed)})")
|
||||
return 0
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user