diff --git a/.env.example b/.env.example index 7bafab9..59397f4 100644 --- a/.env.example +++ b/.env.example @@ -1,15 +1,17 @@ -# BizDocs Forwarder — environment template -# Copy to .env and fill in values. Never commit .env to git. -# Secrets managed via Infisical CT 235 (http://10.10.50.35) +# Copy to .env — never commit .env # MySQL -MYSQL_ROOT_PASSWORD=change_me_strong_root_password +MYSQL_ROOT_PASSWORD=change_me_root MYSQL_DATABASE=forwarder -MYSQL_USER=forwarder_app -MYSQL_PASSWORD=change_me_strong_app_password +MYSQL_USER=forwarder +MYSQL_PASSWORD=change_me_db -# FastAPI -SECRET_KEY=change_me_64char_random_hex_string +# App +DATABASE_URL=mysql+pymysql://forwarder:change_me_db@mysql:3306/forwarder?charset=utf8mb4 +ENCRYPTION_KEY=change_me_fernet_key +APP_SECRET=change_me_jwt_secret +ADMIN_USERNAME=admin +ADMIN_PASSWORD=change_me -# MySQL backup read-only user (created in Phase 4 of deploy runbook) -MYSQL_BACKUP_PASS=change_me_backup_password +# Worker +SYNC_INTERVAL_MINUTES=15 diff --git a/.gitignore b/.gitignore index e35f993..8087f39 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,51 @@ -# Node -admin-ui/node_modules/ -admin-ui/dist/ - # Python __pycache__/ -*.pyc -*.pyo -.env +*.py[cod] +*$py.class +*.so +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ *.egg-info/ +.installed.cfg +*.egg + +# Virtual environments .venv/ venv/ +ENV/ + +# Environment +.env +.env.local + +# IDE +.idea/ +.vscode/ +*.swp +*.swo + +# Testing +.pytest_cache/ +.coverage +htmlcov/ + +# Legacy state +processed_emails.json # Docker -.docker/ +*.log -# Editor -.vscode/ -.idea/ +# OS +.DS_Store +Thumbs.db diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..9bf9d1d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,23 @@ +FROM python:3.12-slim + +WORKDIR /app + +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc \ + default-libmysqlclient-dev \ + pkg-config \ + && rm -rf /var/lib/apt/lists/* + +COPY pyproject.toml README.md ./ +COPY src ./src +COPY alembic.ini ./ +COPY migrations ./migrations + +RUN pip install --no-cache-dir -e . + +ENV PYTHONUNBUFFERED=1 +ENV PYTHONPATH=/app/src + +EXPOSE 8000 + +CMD ["uvicorn", "forwarder.api.app:app", "--host", "0.0.0.0", "--port", "8000", "--app-dir", "src"] diff --git a/README.md b/README.md index 59da809..6a51542 100644 --- a/README.md +++ b/README.md @@ -1,35 +1,50 @@ # BizDocs Forwarder -IMAP-to-BizDocs multi-account forwarder platform. +Multi-account IMAP → BizDocs forwarder: detect invoice attachments (PDF/XML/ZIP), re-send via SMTP as `.eml`. -## Overview - -Automates document forwarding from IMAP email accounts to the BizDocs platform. Supports multiple accounts, with a background worker, REST API, and admin UI. - -## Architecture - -| Component | Description | -|-----------|-------------| -| **Worker** | Background process: polls IMAP, extracts attachments, forwards to BizDocs API | -| **API** | REST endpoints for account management, forwarding rules, and job status | -| **Admin UI** | Web interface for configuration and monitoring | -| **DB** | MySQL — account config, forwarding rules, job history | +- **Repo:** https://git.bitreport.pt/BitReport.pt/forwarder +- **Paperclip:** http://10.10.50.17:3100/BIT/projects/bizdocs-forwarder ## Stack -- Python (worker + API) -- MySQL -- Docker / Proxmox LXC (deploy target) +| Component | Path | Description | +|-----------|------|-------------| +| API | `src/forwarder/api/` | FastAPI REST | +| Worker | `src/forwarder/worker/` | APScheduler IMAP sync | +| Admin UI | `admin-ui/` | Vite + React | +| DB | MySQL 8 | Alembic migrations | -## Getting Started +## Quick start ```bash cp .env.example .env -# Edit .env with your IMAP credentials and BizDocs API key -docker compose up -d +# Generate ENCRYPTION_KEY: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())" + +docker compose up -d --build +docker compose exec api alembic upgrade head ``` -## Related +- API: http://localhost:8000/api/health +- Admin UI: http://localhost:8080 +- Auth: HTTP Basic (`ADMIN_USERNAME` / `ADMIN_PASSWORD`) -- Project board: http://10.10.50.17:3100/BIT/projects/bizdocs-forwarder -- Repo: https://git.bitreport.pt/BitReport.pt/forwarder +## Local dev + +```bash +python3 -m venv .venv && source .venv/bin/activate +pip install -e . +docker compose up -d mysql +alembic upgrade head +uvicorn forwarder.api.app:app --reload --app-dir src +forwarder worker # second terminal +cd admin-ui && npm install && npm run dev # third terminal +``` + +## Deploy (Proxmox CT) + +```bash +git clone https://git.bitreport.pt/BitReport.pt/forwarder.git +cd forwarder && cp .env.example .env +docker compose up -d --build +docker compose exec api alembic upgrade head +``` diff --git a/admin-ui/Dockerfile b/admin-ui/Dockerfile new file mode 100644 index 0000000..fac6b7f --- /dev/null +++ b/admin-ui/Dockerfile @@ -0,0 +1,10 @@ +FROM node:20-alpine AS build +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci +COPY . . +RUN npm run build + +FROM nginx:alpine +COPY nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /app/dist /usr/share/nginx/html diff --git a/admin-ui/nginx.conf b/admin-ui/nginx.conf new file mode 100644 index 0000000..ee8ea1a --- /dev/null +++ b/admin-ui/nginx.conf @@ -0,0 +1,17 @@ +server { + listen 80; + server_name _; + + location /api/ { + proxy_pass http://api:8000/api/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + location / { + root /usr/share/nginx/html; + try_files $uri $uri/ /index.html; + } +} diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..e23ad90 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,43 @@ +[alembic] +script_location = migrations +prepend_sys_path = . + src +version_path_separator = os + +sqlalchemy.url = driver://user:pass@localhost/dbname + +[post_write_hooks] + +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/deploy/nginx.conf b/deploy/nginx.conf new file mode 100644 index 0000000..36fd15a --- /dev/null +++ b/deploy/nginx.conf @@ -0,0 +1,17 @@ +server { + listen 80; + server_name _; + + location /api/ { + proxy_pass http://api:8000/api/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + location / { + return 200 'BizDocs Forwarder API — use /api/health\n'; + add_header Content-Type text/plain; + } +} diff --git a/docker-compose.yml b/docker-compose.yml index 3b08d07..5ad0e00 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -3,76 +3,57 @@ services: image: mysql:8.0 restart: unless-stopped environment: - MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} - MYSQL_DATABASE: ${MYSQL_DATABASE:-forwarder} - MYSQL_USER: ${MYSQL_USER:-forwarder_app} - MYSQL_PASSWORD: ${MYSQL_PASSWORD} + MYSQL_ROOT_PASSWORD: root + MYSQL_DATABASE: forwarder + MYSQL_USER: forwarder + MYSQL_PASSWORD: forwarder + ports: + - "3306:3306" volumes: - mysql_data:/var/lib/mysql - ./api/migrations/init.sql:/docker-entrypoint-initdb.d/init.sql:ro healthcheck: - test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}"] + test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uforwarder", "-pforwarder"] interval: 10s timeout: 5s retries: 5 start_period: 30s api: - build: - context: ./api - dockerfile: Dockerfile + build: . restart: unless-stopped ports: - "8000:8000" + env_file: + - .env environment: - - MYSQL_HOST=mysql - - MYSQL_PORT=3306 - - MYSQL_DATABASE=${MYSQL_DATABASE:-forwarder} - - MYSQL_USER=${MYSQL_USER:-forwarder_app} - - MYSQL_PASSWORD=${MYSQL_PASSWORD} - - SECRET_KEY=${SECRET_KEY} + DATABASE_URL: mysql+pymysql://forwarder:forwarder@mysql:3306/forwarder depends_on: mysql: condition: service_healthy - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:8000/health"] - interval: 30s - timeout: 10s - retries: 3 - start_period: 15s + command: ["uvicorn", "forwarder.api.app:app", "--host", "0.0.0.0", "--port", "8000", "--app-dir", "src"] worker: - build: - context: ./worker - dockerfile: Dockerfile + build: . restart: unless-stopped + env_file: + - .env environment: - - MYSQL_HOST=mysql - - MYSQL_PORT=3306 - - MYSQL_DATABASE=${MYSQL_DATABASE:-forwarder} - - MYSQL_USER=${MYSQL_USER:-forwarder_app} - - MYSQL_PASSWORD=${MYSQL_PASSWORD} - - SECRET_KEY=${SECRET_KEY} + DATABASE_URL: mysql+pymysql://forwarder:forwarder@mysql:3306/forwarder depends_on: mysql: condition: service_healthy - api: - condition: service_healthy + command: ["forwarder", "worker"] web: build: - context: . - dockerfile: web/Dockerfile + context: ./admin-ui + dockerfile: Dockerfile restart: unless-stopped ports: - - "3000:80" + - "8080:80" depends_on: - api - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:80/"] - interval: 30s - timeout: 5s - retries: 3 volumes: mysql_data: diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..fa08399 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,58 @@ +import sys +from logging.config import fileConfig +from pathlib import Path + +from alembic import context + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) +from sqlalchemy import engine_from_config, pool + +from forwarder.config import get_settings +from forwarder.db.base import Base +from forwarder.db import models # noqa: F401 + +config = context.config + +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +target_metadata = Base.metadata + + +def get_url() -> str: + return get_settings().database_url + + +def run_migrations_offline() -> None: + url = get_url() + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + configuration = config.get_section(config.config_ini_section) or {} + configuration["sqlalchemy.url"] = get_url() + connectable = engine_from_config( + configuration, + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure(connection=connection, target_metadata=target_metadata) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..fbc4b07 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,26 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/001_initial_schema.py b/migrations/versions/001_initial_schema.py new file mode 100644 index 0000000..4fe1383 --- /dev/null +++ b/migrations/versions/001_initial_schema.py @@ -0,0 +1,159 @@ +"""Initial schema + +Revision ID: 001_initial +Revises: +Create Date: 2026-06-30 + +""" +from typing import Sequence, Union + +import sqlalchemy as sa +from alembic import op + +revision: str = "001_initial" +down_revision: Union[str, None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.create_table( + "users", + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("username", sa.String(length=128), nullable=False), + sa.Column("password_hash", sa.String(length=255), nullable=False), + sa.Column("is_admin", sa.Boolean(), nullable=False, server_default=sa.text("1")), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("username"), + ) + + op.create_table( + "accounts", + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("name", sa.String(length=255), nullable=False), + sa.Column("enabled", sa.Boolean(), nullable=False, server_default=sa.text("1")), + sa.Column("sync_interval_minutes", sa.Integer(), nullable=False, server_default=sa.text("15")), + sa.Column("imap_host", sa.String(length=255), nullable=False), + sa.Column("imap_port", sa.Integer(), nullable=False, server_default=sa.text("993")), + sa.Column("imap_user", sa.String(length=255), nullable=False), + sa.Column("imap_password_encrypted", sa.Text(), nullable=False), + sa.Column("smtp_host", sa.String(length=255), nullable=False), + sa.Column("smtp_port", sa.Integer(), nullable=False, server_default=sa.text("587")), + sa.Column("smtp_user", sa.String(length=255), nullable=False), + sa.Column("smtp_password_encrypted", sa.Text(), nullable=False), + sa.Column("smtp_use_tls", sa.Boolean(), nullable=False, server_default=sa.text("1")), + sa.Column("destination_email", sa.String(length=255), nullable=False), + sa.Column("include_all_attachments", sa.Boolean(), nullable=False, server_default=sa.text("0")), + sa.Column("allowed_extensions", sa.JSON(), nullable=False), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False), + sa.PrimaryKeyConstraint("id"), + ) + + op.create_table( + "user_accounts", + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("user_id", sa.Integer(), nullable=False), + sa.Column("account_id", sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(["account_id"], ["accounts.id"]), + sa.ForeignKeyConstraint(["user_id"], ["users.id"]), + sa.PrimaryKeyConstraint("id"), + ) + + op.create_table( + "messages", + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("account_id", sa.Integer(), nullable=False), + sa.Column("message_key", sa.String(length=512), nullable=False), + sa.Column("folder", sa.String(length=512), nullable=False), + sa.Column("uid", sa.String(length=64), nullable=False), + sa.Column("subject", sa.String(length=1024), nullable=False, server_default=""), + sa.Column("from_addr", sa.String(length=512), nullable=False, server_default=""), + sa.Column("date", sa.String(length=128), nullable=False, server_default=""), + sa.Column( + "status", + sa.Enum("pending", "forwarded", "failed", "skipped", "dry_run", name="messagestatus"), + nullable=False, + ), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False), + sa.ForeignKeyConstraint(["account_id"], ["accounts.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("account_id", "message_key", name="uq_account_message_key"), + ) + op.create_index("ix_messages_account_id", "messages", ["account_id"]) + op.create_index("ix_messages_status", "messages", ["status"]) + + op.create_table( + "forward_attempts", + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("message_id", sa.Integer(), nullable=False), + sa.Column("success", sa.Boolean(), nullable=False), + sa.Column("dry_run", sa.Boolean(), nullable=False, server_default=sa.text("0")), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False), + sa.ForeignKeyConstraint(["message_id"], ["messages.id"]), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index("ix_forward_attempts_message_id", "forward_attempts", ["message_id"]) + + op.create_table( + "sync_runs", + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("account_id", sa.Integer(), nullable=False), + sa.Column( + "status", + sa.Enum("running", "completed", "failed", name="syncrunstatus"), + nullable=False, + ), + sa.Column("dry_run", sa.Boolean(), nullable=False, server_default=sa.text("0")), + sa.Column("max_emails", sa.Integer(), nullable=True), + sa.Column("messages_scanned", sa.Integer(), nullable=False, server_default=sa.text("0")), + sa.Column("messages_matched", sa.Integer(), nullable=False, server_default=sa.text("0")), + sa.Column("messages_forwarded", sa.Integer(), nullable=False, server_default=sa.text("0")), + sa.Column("messages_skipped", sa.Integer(), nullable=False, server_default=sa.text("0")), + sa.Column("messages_failed", sa.Integer(), nullable=False, server_default=sa.text("0")), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("started_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False), + sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(["account_id"], ["accounts.id"]), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index("ix_sync_runs_account_id", "sync_runs", ["account_id"]) + + op.create_table( + "connection_tests", + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("account_id", sa.Integer(), nullable=True), + sa.Column( + "test_type", + sa.Enum("imap", "smtp", "send", name="connectiontesttype"), + nullable=False, + ), + sa.Column("success", sa.Boolean(), nullable=False), + sa.Column("message", sa.Text(), nullable=False, server_default=""), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False), + sa.ForeignKeyConstraint(["account_id"], ["accounts.id"]), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index("ix_connection_tests_account_id", "connection_tests", ["account_id"]) + + +def downgrade() -> None: + op.drop_index("ix_connection_tests_account_id", table_name="connection_tests") + op.drop_table("connection_tests") + op.drop_index("ix_sync_runs_account_id", table_name="sync_runs") + op.drop_table("sync_runs") + op.drop_index("ix_forward_attempts_message_id", table_name="forward_attempts") + op.drop_table("forward_attempts") + op.drop_index("ix_messages_status", table_name="messages") + op.drop_index("ix_messages_account_id", table_name="messages") + op.drop_table("messages") + op.drop_table("user_accounts") + op.drop_table("accounts") + op.drop_table("users") + op.execute("DROP TYPE IF EXISTS connectiontesttype") + op.execute("DROP TYPE IF EXISTS syncrunstatus") + op.execute("DROP TYPE IF EXISTS messagestatus") diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..9cc45c2 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,38 @@ +[build-system] +requires = ["setuptools>=68", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "bizdocs-forwarder" +version = "0.1.0" +description = "Multi-account IMAP to BizDocs email forwarder" +readme = "README.md" +requires-python = ">=3.12" +dependencies = [ + "fastapi>=0.115.0", + "uvicorn[standard]>=0.32.0", + "sqlalchemy>=2.0.36", + "alembic>=1.14.0", + "pymysql>=1.1.1", + "cryptography>=43.0.0", + "apscheduler>=3.10.4", + "pydantic>=2.10.0", + "pydantic-settings>=2.6.0", + "python-multipart>=0.0.17", + "passlib[bcrypt]>=1.7.4", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.0.0", + "httpx>=0.28.0", +] + +[project.scripts] +forwarder = "forwarder.cli:main" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.setuptools.package-data] +forwarder = ["py.typed"] diff --git a/src/forwarder/__init__.py b/src/forwarder/__init__.py new file mode 100644 index 0000000..daa196f --- /dev/null +++ b/src/forwarder/__init__.py @@ -0,0 +1,3 @@ +"""BizDocs Forwarder — multi-account IMAP to BizDocs email forwarder.""" + +__version__ = "0.1.0" diff --git a/src/forwarder/__main__.py b/src/forwarder/__main__.py new file mode 100644 index 0000000..06cea36 --- /dev/null +++ b/src/forwarder/__main__.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from forwarder.config import get_settings + +__all__ = ["main"] + + +def main() -> None: + from forwarder.cli import main as cli_main + + cli_main() + + +if __name__ == "__main__": + main() diff --git a/src/forwarder/api/__init__.py b/src/forwarder/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/forwarder/api/app.py b/src/forwarder/api/app.py new file mode 100644 index 0000000..56d4e80 --- /dev/null +++ b/src/forwarder/api/app.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +import logging + +from fastapi import FastAPI + +from forwarder import __version__ +from forwarder.api.routes import accounts, health, messages, sync_runs +from forwarder.services.auth_service import ensure_admin_user + +logger = logging.getLogger(__name__) + + +def create_app() -> FastAPI: + app = FastAPI( + title="BizDocs Forwarder", + version=__version__, + description="Multi-account IMAP to BizDocs email forwarder", + ) + + @app.on_event("startup") + def on_startup() -> None: + ensure_admin_user() + logger.info("BizDocs Forwarder API started") + + app.include_router(health.router, prefix="/api") + app.include_router(accounts.router, prefix="/api") + app.include_router(messages.router, prefix="/api") + app.include_router(sync_runs.router, prefix="/api") + + return app + + +app = create_app() diff --git a/src/forwarder/api/deps.py b/src/forwarder/api/deps.py new file mode 100644 index 0000000..c776dde --- /dev/null +++ b/src/forwarder/api/deps.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from typing import Annotated + +from fastapi import Depends, HTTPException, status +from fastapi.security import HTTPBasic, HTTPBasicCredentials +from sqlalchemy.orm import Session + +from forwarder.db.session import get_db +from forwarder.services.auth_service import authenticate_user + +security = HTTPBasic() + + +def get_current_user( + credentials: Annotated[HTTPBasicCredentials, Depends(security)], +) -> str: + user = authenticate_user(credentials.username, credentials.password) + if user is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid credentials", + headers={"WWW-Authenticate": "Basic"}, + ) + return user.username + + +DbSession = Annotated[Session, Depends(get_db)] +CurrentUser = Annotated[str, Depends(get_current_user)] diff --git a/src/forwarder/api/routes/__init__.py b/src/forwarder/api/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/forwarder/api/routes/accounts.py b/src/forwarder/api/routes/accounts.py new file mode 100644 index 0000000..c2a220c --- /dev/null +++ b/src/forwarder/api/routes/accounts.py @@ -0,0 +1,202 @@ +from __future__ import annotations + +from fastapi import APIRouter, HTTPException, Query, status + +from forwarder.api.deps import CurrentUser, DbSession +from forwarder.api.schemas import ( + AccountCreate, + AccountResponse, + AccountUpdate, + ConnectionTestResponse, + InlineConnectionConfig, + SyncRunResponse, +) +from forwarder.services import account_service +from forwarder.services.sync_service import sync_account + +router = APIRouter(prefix="/accounts", tags=["accounts"]) + + +def _to_response(account) -> AccountResponse: + data = account_service.account_to_dict(account) + return AccountResponse(**data) + + +@router.post("/test/imap", response_model=ConnectionTestResponse) +def test_imap_presave( + inline: InlineConnectionConfig, + db: DbSession, + _user: CurrentUser, +) -> ConnectionTestResponse: + data = inline.model_dump(exclude_unset=True) + required = ("imap_host", "imap_user", "imap_password") + for field in required: + if not data.get(field): + raise HTTPException(status_code=400, detail=f"{field} is required") + success, message = account_service.run_imap_test(db, None, data) + return ConnectionTestResponse(success=success, message=message) + + +@router.post("/test/smtp", response_model=ConnectionTestResponse) +def test_smtp_presave( + inline: InlineConnectionConfig, + db: DbSession, + _user: CurrentUser, +) -> ConnectionTestResponse: + data = inline.model_dump(exclude_unset=True) + required = ("smtp_host", "smtp_user", "smtp_password") + for field in required: + if not data.get(field): + raise HTTPException(status_code=400, detail=f"{field} is required") + success, message = account_service.run_smtp_test(db, None, data) + return ConnectionTestResponse(success=success, message=message) + + +@router.post("/test/send", response_model=ConnectionTestResponse) +def test_send_presave( + inline: InlineConnectionConfig, + db: DbSession, + _user: CurrentUser, +) -> ConnectionTestResponse: + data = inline.model_dump(exclude_unset=True) + required = ("smtp_host", "smtp_user", "smtp_password", "destination_email") + for field in required: + if not data.get(field): + raise HTTPException(status_code=400, detail=f"{field} is required") + success, message = account_service.run_send_test(db, None, data) + return ConnectionTestResponse(success=success, message=message) + + +@router.get("", response_model=list[AccountResponse]) +def list_accounts(db: DbSession, _user: CurrentUser) -> list[AccountResponse]: + return [_to_response(a) for a in account_service.list_accounts(db)] + + +@router.get("/{account_id}", response_model=AccountResponse) +def get_account(account_id: int, db: DbSession, _user: CurrentUser) -> AccountResponse: + try: + account = account_service.get_account(db, account_id) + except account_service.AccountNotFoundError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + return _to_response(account) + + +@router.post("", response_model=AccountResponse, status_code=status.HTTP_201_CREATED) +def create_account( + payload: AccountCreate, db: DbSession, _user: CurrentUser +) -> AccountResponse: + account = account_service.create_account(db, payload.model_dump()) + return _to_response(account) + + +@router.put("/{account_id}", response_model=AccountResponse) +def update_account( + account_id: int, + payload: AccountUpdate, + db: DbSession, + _user: CurrentUser, +) -> AccountResponse: + try: + account = account_service.update_account( + db, account_id, payload.model_dump(exclude_unset=True) + ) + except account_service.AccountNotFoundError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + return _to_response(account) + + +@router.delete("/{account_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_account(account_id: int, db: DbSession, _user: CurrentUser) -> None: + try: + account_service.delete_account(db, account_id) + except account_service.AccountNotFoundError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + + +def _inline_dict(inline: InlineConnectionConfig | None) -> dict | None: + if inline is None: + return None + data = inline.model_dump(exclude_unset=True) + if not data: + return None + return data + + +@router.post("/{account_id}/test/imap", response_model=ConnectionTestResponse) +def test_imap( + account_id: int, + db: DbSession, + _user: CurrentUser, + inline: InlineConnectionConfig | None = None, +) -> ConnectionTestResponse: + """Test IMAP for a saved account; optional body overrides stored credentials.""" + try: + success, message = account_service.run_imap_test( + db, account_id, _inline_dict(inline) + ) + except (account_service.AccountNotFoundError, ValueError) as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + return ConnectionTestResponse(success=success, message=message) + + +@router.post("/{account_id}/test/smtp", response_model=ConnectionTestResponse) +def test_smtp( + account_id: int, + db: DbSession, + _user: CurrentUser, + inline: InlineConnectionConfig | None = None, +) -> ConnectionTestResponse: + try: + success, message = account_service.run_smtp_test( + db, account_id, _inline_dict(inline) + ) + except (account_service.AccountNotFoundError, ValueError) as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + return ConnectionTestResponse(success=success, message=message) + + +@router.post("/{account_id}/test/send", response_model=ConnectionTestResponse) +def test_send( + account_id: int, + db: DbSession, + _user: CurrentUser, + inline: InlineConnectionConfig | None = None, +) -> ConnectionTestResponse: + try: + success, message = account_service.run_send_test( + db, account_id, _inline_dict(inline) + ) + except (account_service.AccountNotFoundError, ValueError) as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + return ConnectionTestResponse(success=success, message=message) + + +@router.post("/{account_id}/sync", response_model=SyncRunResponse) +def trigger_sync( + account_id: int, + db: DbSession, + _user: CurrentUser, + dry_run: bool = Query(default=False), + max_emails: int | None = Query(default=None, ge=1), +) -> SyncRunResponse: + try: + account_service.get_account(db, account_id) + except account_service.AccountNotFoundError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + + sync_run = sync_account(db, account_id, dry_run=dry_run, max_emails=max_emails) + return SyncRunResponse( + id=sync_run.id, + account_id=sync_run.account_id, + status=sync_run.status.value, + dry_run=sync_run.dry_run, + max_emails=sync_run.max_emails, + messages_scanned=sync_run.messages_scanned, + messages_matched=sync_run.messages_matched, + messages_forwarded=sync_run.messages_forwarded, + messages_skipped=sync_run.messages_skipped, + messages_failed=sync_run.messages_failed, + error_message=sync_run.error_message, + started_at=sync_run.started_at, + finished_at=sync_run.finished_at, + ) diff --git a/src/forwarder/api/routes/health.py b/src/forwarder/api/routes/health.py new file mode 100644 index 0000000..8b0befb --- /dev/null +++ b/src/forwarder/api/routes/health.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +from fastapi import APIRouter + +from forwarder import __version__ + +router = APIRouter() + + +@router.get("/health", response_model=dict) +def health() -> dict: + return {"status": "ok", "version": __version__} diff --git a/src/forwarder/api/routes/messages.py b/src/forwarder/api/routes/messages.py new file mode 100644 index 0000000..0869b51 --- /dev/null +++ b/src/forwarder/api/routes/messages.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from fastapi import APIRouter, Query + +from forwarder.api.deps import CurrentUser, DbSession +from forwarder.api.schemas import MessageResponse +from forwarder.db.models import Message, MessageStatus + +router = APIRouter(prefix="/messages", tags=["messages"]) + + +@router.get("", response_model=list[MessageResponse]) +def list_messages( + db: DbSession, + _user: CurrentUser, + account_id: int | None = Query(default=None), + status: str | None = Query(default=None), + limit: int = Query(default=100, ge=1, le=500), + offset: int = Query(default=0, ge=0), +) -> list[MessageResponse]: + query = db.query(Message).order_by(Message.id.desc()) + + if account_id is not None: + query = query.filter(Message.account_id == account_id) + + if status is not None: + try: + status_enum = MessageStatus(status) + except ValueError: + return [] + query = query.filter(Message.status == status_enum) + + rows = query.offset(offset).limit(limit).all() + return [ + MessageResponse( + id=m.id, + account_id=m.account_id, + message_key=m.message_key, + folder=m.folder, + uid=m.uid, + subject=m.subject, + from_addr=m.from_addr, + date=m.date, + status=m.status.value, + error_message=m.error_message, + created_at=m.created_at, + updated_at=m.updated_at, + ) + for m in rows + ] diff --git a/src/forwarder/api/routes/sync_runs.py b/src/forwarder/api/routes/sync_runs.py new file mode 100644 index 0000000..b14f63e --- /dev/null +++ b/src/forwarder/api/routes/sync_runs.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from fastapi import APIRouter, Query + +from forwarder.api.deps import CurrentUser, DbSession +from forwarder.api.schemas import SyncRunResponse +from forwarder.db.models import SyncRun + +router = APIRouter(prefix="/sync-runs", tags=["sync-runs"]) + + +@router.get("", response_model=list[SyncRunResponse]) +def list_sync_runs( + db: DbSession, + _user: CurrentUser, + account_id: int | None = Query(default=None), + limit: int = Query(default=50, ge=1, le=200), + offset: int = Query(default=0, ge=0), +) -> list[SyncRunResponse]: + query = db.query(SyncRun).order_by(SyncRun.id.desc()) + + if account_id is not None: + query = query.filter(SyncRun.account_id == account_id) + + rows = query.offset(offset).limit(limit).all() + return [ + SyncRunResponse( + id=r.id, + account_id=r.account_id, + status=r.status.value, + dry_run=r.dry_run, + max_emails=r.max_emails, + messages_scanned=r.messages_scanned, + messages_matched=r.messages_matched, + messages_forwarded=r.messages_forwarded, + messages_skipped=r.messages_skipped, + messages_failed=r.messages_failed, + error_message=r.error_message, + started_at=r.started_at, + finished_at=r.finished_at, + ) + for r in rows + ] diff --git a/src/forwarder/api/schemas.py b/src/forwarder/api/schemas.py new file mode 100644 index 0000000..1f8d9ba --- /dev/null +++ b/src/forwarder/api/schemas.py @@ -0,0 +1,117 @@ +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field + + +class AccountBase(BaseModel): + name: str + enabled: bool = True + sync_interval_minutes: int = 15 + imap_host: str + imap_port: int = 993 + imap_user: str + smtp_host: str + smtp_port: int = 587 + smtp_user: str + smtp_use_tls: bool = True + destination_email: str + include_all_attachments: bool = False + allowed_extensions: list[str] = Field(default_factory=lambda: [".pdf", ".xml", ".zip"]) + + +class AccountCreate(AccountBase): + imap_password: str + smtp_password: str + + +class AccountUpdate(BaseModel): + name: str | None = None + enabled: bool | None = None + sync_interval_minutes: int | None = None + imap_host: str | None = None + imap_port: int | None = None + imap_user: str | None = None + imap_password: str | None = None + smtp_host: str | None = None + smtp_port: int | None = None + smtp_user: str | None = None + smtp_password: str | None = None + smtp_use_tls: bool | None = None + destination_email: str | None = None + include_all_attachments: bool | None = None + allowed_extensions: list[str] | None = None + + +class AccountResponse(AccountBase): + model_config = ConfigDict(from_attributes=True) + + id: int + imap_password: str = "********" + smtp_password: str = "********" + created_at: datetime + updated_at: datetime + + +class InlineConnectionConfig(BaseModel): + imap_host: str | None = None + imap_port: int | None = None + imap_user: str | None = None + imap_password: str | None = None + smtp_host: str | None = None + smtp_port: int | None = None + smtp_user: str | None = None + smtp_password: str | None = None + smtp_use_tls: bool | None = None + destination_email: str | None = None + + +class ConnectionTestResponse(BaseModel): + success: bool + message: str + + +class MessageResponse(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: int + account_id: int + message_key: str + folder: str + uid: str + subject: str + from_addr: str + date: str + status: str + error_message: str | None = None + created_at: datetime + updated_at: datetime + + +class SyncRunResponse(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: int + account_id: int + status: str + dry_run: bool + max_emails: int | None = None + messages_scanned: int + messages_matched: int + messages_forwarded: int + messages_skipped: int + messages_failed: int + error_message: str | None = None + started_at: datetime + finished_at: datetime | None = None + + +class HealthResponse(BaseModel): + status: str + version: str + + +class ErrorResponse(BaseModel): + detail: str diff --git a/src/forwarder/cli.py b/src/forwarder/cli.py new file mode 100644 index 0000000..13ed562 --- /dev/null +++ b/src/forwarder/cli.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +import argparse +import logging +import sys + +from forwarder.config import get_settings +from forwarder.services.auth_service import ensure_admin_user +from forwarder.worker.scheduler import run_worker + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", +) + + +def main() -> None: + parser = argparse.ArgumentParser(prog="forwarder", description="BizDocs Forwarder CLI") + subparsers = parser.add_subparsers(dest="command", required=True) + + worker_parser = subparsers.add_parser("worker", help="Run APScheduler sync worker") + worker_parser.add_argument( + "--interval", + type=int, + default=None, + help="Override default sync interval (minutes) for accounts without custom value", + ) + + args = parser.parse_args() + + if args.command == "worker": + ensure_admin_user() + settings = get_settings() + default_interval = args.interval or settings.sync_interval_minutes + logging.getLogger(__name__).info( + "Starting worker (default interval: %s min)", default_interval + ) + run_worker(default_interval=default_interval) + return + + parser.print_help() + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/src/forwarder/config.py b/src/forwarder/config.py new file mode 100644 index 0000000..aed7ed8 --- /dev/null +++ b/src/forwarder/config.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +from functools import lru_cache + +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + model_config = SettingsConfigDict( + env_file=".env", + env_file_encoding="utf-8", + extra="ignore", + ) + + database_url: str = "mysql+pymysql://forwarder:forwarder@localhost:3306/forwarder" + encryption_key: str = "" + app_secret: str = "change-me" + admin_username: str = "admin" + admin_password: str = "change-me" + sync_interval_minutes: int = 15 + api_host: str = "0.0.0.0" + api_port: int = 8000 + + +@lru_cache +def get_settings() -> Settings: + return Settings() diff --git a/src/forwarder/crypto.py b/src/forwarder/crypto.py new file mode 100644 index 0000000..3de546c --- /dev/null +++ b/src/forwarder/crypto.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from cryptography.fernet import Fernet, InvalidToken + +from forwarder.config import get_settings + + +class EncryptionError(Exception): + pass + + +def get_fernet() -> Fernet: + key = get_settings().encryption_key.strip() + if not key: + raise EncryptionError("ENCRYPTION_KEY is not configured") + return Fernet(key.encode() if isinstance(key, str) else key) + + +def encrypt_password(plain: str) -> str: + if not plain: + return "" + return get_fernet().encrypt(plain.encode()).decode() + + +def decrypt_password(token: str) -> str: + if not token: + return "" + try: + return get_fernet().decrypt(token.encode()).decode() + except InvalidToken as exc: + raise EncryptionError("Failed to decrypt password") from exc + + +def mask_password(_plain: str | None = None) -> str: + return "********" diff --git a/src/forwarder/db/__init__.py b/src/forwarder/db/__init__.py new file mode 100644 index 0000000..da88645 --- /dev/null +++ b/src/forwarder/db/__init__.py @@ -0,0 +1,21 @@ +from forwarder.db.base import Base +from forwarder.db.models import ( + Account, + ConnectionTest, + ForwardAttempt, + Message, + SyncRun, + User, + UserAccount, +) + +__all__ = [ + "Base", + "Account", + "ConnectionTest", + "ForwardAttempt", + "Message", + "SyncRun", + "User", + "UserAccount", +] diff --git a/src/forwarder/db/base.py b/src/forwarder/db/base.py new file mode 100644 index 0000000..fa2b68a --- /dev/null +++ b/src/forwarder/db/base.py @@ -0,0 +1,5 @@ +from sqlalchemy.orm import DeclarativeBase + + +class Base(DeclarativeBase): + pass diff --git a/src/forwarder/db/models.py b/src/forwarder/db/models.py new file mode 100644 index 0000000..00c7a62 --- /dev/null +++ b/src/forwarder/db/models.py @@ -0,0 +1,206 @@ +from __future__ import annotations + +import enum +from datetime import datetime +from typing import Any + +from sqlalchemy import ( + JSON, + Boolean, + DateTime, + Enum, + ForeignKey, + Integer, + String, + Text, + UniqueConstraint, + func, +) +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from forwarder.db.base import Base + +DEFAULT_ALLOWED_EXTENSIONS = [".pdf", ".xml", ".zip"] + + +class MessageStatus(str, enum.Enum): + pending = "pending" + forwarded = "forwarded" + failed = "failed" + skipped = "skipped" + dry_run = "dry_run" + + +class SyncRunStatus(str, enum.Enum): + running = "running" + completed = "completed" + failed = "failed" + + +class ConnectionTestType(str, enum.Enum): + imap = "imap" + smtp = "smtp" + send = "send" + + +class User(Base): + __tablename__ = "users" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + username: Mapped[str] = mapped_column(String(128), unique=True, nullable=False) + password_hash: Mapped[str] = mapped_column(String(255), nullable=False) + is_admin: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now(), nullable=False + ) + + user_accounts: Mapped[list[UserAccount]] = relationship( + back_populates="user", cascade="all, delete-orphan" + ) + + +class Account(Base): + __tablename__ = "accounts" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + name: Mapped[str] = mapped_column(String(255), nullable=False) + enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) + sync_interval_minutes: Mapped[int] = mapped_column(Integer, default=15, nullable=False) + + imap_host: Mapped[str] = mapped_column(String(255), nullable=False) + imap_port: Mapped[int] = mapped_column(Integer, default=993, nullable=False) + imap_user: Mapped[str] = mapped_column(String(255), nullable=False) + imap_password_encrypted: Mapped[str] = mapped_column(Text, nullable=False) + + smtp_host: Mapped[str] = mapped_column(String(255), nullable=False) + smtp_port: Mapped[int] = mapped_column(Integer, default=587, nullable=False) + smtp_user: Mapped[str] = mapped_column(String(255), nullable=False) + smtp_password_encrypted: Mapped[str] = mapped_column(Text, nullable=False) + smtp_use_tls: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) + + destination_email: Mapped[str] = mapped_column(String(255), nullable=False) + include_all_attachments: Mapped[bool] = mapped_column( + Boolean, default=False, nullable=False + ) + allowed_extensions: Mapped[list[Any]] = mapped_column( + JSON, default=list, nullable=False + ) + + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now(), nullable=False + ) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + server_default=func.now(), + onupdate=func.now(), + nullable=False, + ) + + messages: Mapped[list[Message]] = relationship( + back_populates="account", cascade="all, delete-orphan" + ) + sync_runs: Mapped[list[SyncRun]] = relationship( + back_populates="account", cascade="all, delete-orphan" + ) + user_accounts: Mapped[list[UserAccount]] = relationship( + back_populates="account", cascade="all, delete-orphan" + ) + + +class UserAccount(Base): + __tablename__ = "user_accounts" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False) + account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False) + + user: Mapped[User] = relationship(back_populates="user_accounts") + account: Mapped[Account] = relationship(back_populates="user_accounts") + + +class Message(Base): + __tablename__ = "messages" + __table_args__ = (UniqueConstraint("account_id", "message_key", name="uq_account_message_key"),) + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False, index=True) + message_key: Mapped[str] = mapped_column(String(512), nullable=False) + folder: Mapped[str] = mapped_column(String(512), nullable=False) + uid: Mapped[str] = mapped_column(String(64), nullable=False) + subject: Mapped[str] = mapped_column(String(1024), default="", nullable=False) + from_addr: Mapped[str] = mapped_column(String(512), default="", nullable=False) + date: Mapped[str] = mapped_column(String(128), default="", nullable=False) + status: Mapped[MessageStatus] = mapped_column( + Enum(MessageStatus), default=MessageStatus.pending, nullable=False, index=True + ) + error_message: Mapped[str | None] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now(), nullable=False + ) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + server_default=func.now(), + onupdate=func.now(), + nullable=False, + ) + + account: Mapped[Account] = relationship(back_populates="messages") + forward_attempts: Mapped[list[ForwardAttempt]] = relationship( + back_populates="message", cascade="all, delete-orphan" + ) + + +class ForwardAttempt(Base): + __tablename__ = "forward_attempts" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + message_id: Mapped[int] = mapped_column(ForeignKey("messages.id"), nullable=False, index=True) + success: Mapped[bool] = mapped_column(Boolean, nullable=False) + dry_run: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) + error_message: Mapped[str | None] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now(), nullable=False + ) + + message: Mapped[Message] = relationship(back_populates="forward_attempts") + + +class SyncRun(Base): + __tablename__ = "sync_runs" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False, index=True) + status: Mapped[SyncRunStatus] = mapped_column( + Enum(SyncRunStatus), default=SyncRunStatus.running, nullable=False + ) + dry_run: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) + max_emails: Mapped[int | None] = mapped_column(Integer, nullable=True) + messages_scanned: Mapped[int] = mapped_column(Integer, default=0, nullable=False) + messages_matched: Mapped[int] = mapped_column(Integer, default=0, nullable=False) + messages_forwarded: Mapped[int] = mapped_column(Integer, default=0, nullable=False) + messages_skipped: Mapped[int] = mapped_column(Integer, default=0, nullable=False) + messages_failed: Mapped[int] = mapped_column(Integer, default=0, nullable=False) + error_message: Mapped[str | None] = mapped_column(Text, nullable=True) + started_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now(), nullable=False + ) + finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) + + account: Mapped[Account] = relationship(back_populates="sync_runs") + + +class ConnectionTest(Base): + __tablename__ = "connection_tests" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + account_id: Mapped[int | None] = mapped_column( + ForeignKey("accounts.id"), nullable=True, index=True + ) + test_type: Mapped[ConnectionTestType] = mapped_column( + Enum(ConnectionTestType), nullable=False + ) + success: Mapped[bool] = mapped_column(Boolean, nullable=False) + message: Mapped[str] = mapped_column(Text, default="", nullable=False) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now(), nullable=False + ) diff --git a/src/forwarder/db/session.py b/src/forwarder/db/session.py new file mode 100644 index 0000000..e5f0322 --- /dev/null +++ b/src/forwarder/db/session.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from collections.abc import Generator + +from sqlalchemy import create_engine +from sqlalchemy.orm import Session, sessionmaker + +from forwarder.config import get_settings + +_engine = None +_SessionLocal = None + + +def get_engine(): + global _engine + if _engine is None: + _engine = create_engine( + get_settings().database_url, + pool_pre_ping=True, + pool_recycle=3600, + ) + return _engine + + +def get_session_factory() -> sessionmaker[Session]: + global _SessionLocal + if _SessionLocal is None: + _SessionLocal = sessionmaker( + bind=get_engine(), + autocommit=False, + autoflush=False, + ) + return _SessionLocal + + +def get_db() -> Generator[Session, None, None]: + db = get_session_factory()() + try: + yield db + finally: + db.close() diff --git a/src/forwarder/email/__init__.py b/src/forwarder/email/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/forwarder/email/imap_client.py b/src/forwarder/email/imap_client.py new file mode 100644 index 0000000..e7d7960 --- /dev/null +++ b/src/forwarder/email/imap_client.py @@ -0,0 +1,100 @@ +"""IMAP client helpers.""" + +from __future__ import annotations + +import email +import imaplib +import re +from dataclasses import dataclass +from email import policy + +SKIP_FOLDERS = [ + "trash", + "junk", + "spam", + "deleted", + "draft", + "sent", + "enviados", + "lixo", + "rascunhos", +] + + +@dataclass +class ImapConfig: + host: str + port: int + user: str + password: str + + +def decode_mbox_name(raw_name: bytes | str) -> str: + if isinstance(raw_name, bytes): + raw_name = raw_name.decode(errors="replace") + return raw_name.strip('"') + + +def should_skip_folder(folder: str) -> bool: + lowered = folder.lower() + for fragment in SKIP_FOLDERS: + if fragment in lowered: + return True + return False + + +def list_mailboxes(imap: imaplib.IMAP4_SSL) -> list[str]: + status, boxes = imap.list() + if status != "OK" or not boxes: + return [] + + folders: list[str] = [] + for box in boxes: + if box is None: + continue + decoded = box.decode(errors="replace") if isinstance(box, bytes) else str(box) + match = re.search(r' "/" (.+)$', decoded) or re.search(r' "." (.+)$', decoded) + if not match: + continue + folders.append(decode_mbox_name(match.group(1))) + return folders + + +def select_folder_readonly(imap: imaplib.IMAP4_SSL, folder: str) -> bool: + mailbox = f'"{folder}"' if " " in folder else folder + status, _ = imap.select(mailbox, readonly=True) + return status == "OK" + + +def fetch_message( + imap: imaplib.IMAP4_SSL, uid: bytes +) -> email.message.EmailMessage | None: + status, msg_data = imap.uid("fetch", uid, "(RFC822)") + if status != "OK" or not msg_data or not msg_data[0]: + return None + raw_email = msg_data[0][1] + if not isinstance(raw_email, (bytes, bytearray)): + return None + return email.message_from_bytes(raw_email, policy=policy.default) + + +def connect_imap(config: ImapConfig) -> imaplib.IMAP4_SSL: + imap = imaplib.IMAP4_SSL(config.host, config.port) + imap.login(config.user, config.password) + return imap + + +def test_imap_connection(config: ImapConfig) -> tuple[bool, str]: + imap = None + try: + imap = connect_imap(config) + folders = list_mailboxes(imap) + return True, f"IMAP OK — {len(folders)} mailbox(es) found" + except Exception as exc: + return False, str(exc) + finally: + if imap is not None: + try: + imap.logout() + except imaplib.IMAP4.error: + pass diff --git a/src/forwarder/email/parsing.py b/src/forwarder/email/parsing.py new file mode 100644 index 0000000..13a34f2 --- /dev/null +++ b/src/forwarder/email/parsing.py @@ -0,0 +1,127 @@ +"""Email parsing utilities.""" + +from __future__ import annotations + +import email +from email.header import decode_header, make_header +from email.message import EmailMessage + +DEFAULT_ALLOWED_EXTENSIONS = {".pdf", ".xml", ".zip"} + +ALLOWED_MIME_TYPES = { + "application/pdf", + "application/xml", + "text/xml", + "application/zip", + "application/x-zip-compressed", +} + + +def clean_header(value: str | None) -> str: + if not value: + return "" + try: + return str(make_header(decode_header(value))) + except Exception: + return value + + +def clean_subject(subject: str | None) -> str: + cleaned = clean_header(subject) + if cleaned: + return cleaned + return "(no subject)" + + +def normalize_message_id(message_id: str | None) -> str | None: + if not message_id: + return None + cleaned = message_id.strip() + if cleaned.startswith("<") and cleaned.endswith(">"): + cleaned = cleaned[1:-1].strip() + if cleaned: + return cleaned + return None + + +def get_message_key(folder: str, uid: bytes | str, msg: email.message.EmailMessage) -> str: + msg_id = normalize_message_id(msg.get("Message-ID")) + if msg_id: + return msg_id + uid_str = uid.decode() if isinstance(uid, bytes) else str(uid) + return f"{folder}:{uid_str}" + + +def part_filename(part: email.message.Message) -> str: + filename = part.get_filename() + if filename: + return clean_header(filename).lower() + name = part.get_param("name", header="content-disposition") + if name: + return clean_header(name).lower() + return "" + + +def is_real_attachment(part: email.message.Message) -> bool: + disposition = (part.get_content_disposition() or "").lower() + filename = part_filename(part) + content_type = (part.get_content_type() or "").lower() + + if disposition == "inline" and not filename: + return False + + if disposition == "attachment": + return True + + if filename: + return True + + if content_type in ALLOWED_MIME_TYPES: + return True + + return False + + +def attachment_allowed( + part: email.message.Message, + *, + include_all_attachments: bool, + allowed_extensions: set[str], +) -> bool: + if not is_real_attachment(part): + return False + + if include_all_attachments: + return True + + filename = part_filename(part) + if filename: + import os + + _, ext = os.path.splitext(filename) + if ext in allowed_extensions: + return True + + content_type = (part.get_content_type() or "").lower() + return content_type in ALLOWED_MIME_TYPES + + +def has_matching_attachment( + msg: EmailMessage, + *, + include_all_attachments: bool = False, + allowed_extensions: set[str] | None = None, +) -> bool: + if allowed_extensions is None: + allowed_extensions = DEFAULT_ALLOWED_EXTENSIONS + + for part in msg.walk(): + if part.is_multipart(): + continue + if attachment_allowed( + part, + include_all_attachments=include_all_attachments, + allowed_extensions=allowed_extensions, + ): + return True + return False diff --git a/src/forwarder/email/smtp_client.py b/src/forwarder/email/smtp_client.py new file mode 100644 index 0000000..b25beaf --- /dev/null +++ b/src/forwarder/email/smtp_client.py @@ -0,0 +1,116 @@ +"""SMTP client helpers.""" + +from __future__ import annotations + +import smtplib +from dataclasses import dataclass +from email import policy +from email.message import EmailMessage + + +@dataclass +class SmtpConfig: + host: str + port: int + user: str + password: str + use_tls: bool = True + + +def create_smtp_client(config: SmtpConfig) -> smtplib.SMTP: + if config.port == 465 and not config.use_tls: + client = smtplib.SMTP_SSL(config.host, config.port, timeout=60) + else: + client = smtplib.SMTP(config.host, config.port, timeout=60) + if config.use_tls: + client.starttls() + client.login(config.user, config.password) + return client + + +def forward_email_as_eml( + original_msg: EmailMessage, + *, + smtp_config: SmtpConfig, + destination_email: str, + smtp: smtplib.SMTP | None = None, +) -> None: + from forwarder.email.parsing import clean_subject + + subject = clean_subject(original_msg.get("Subject")) + sender = original_msg.get("From", "") + date = original_msg.get("Date", "") + + fwd = EmailMessage() + fwd["From"] = smtp_config.user + fwd["To"] = destination_email + fwd["Subject"] = f"FWD BizDocs: {subject}" + + body = ( + "Forwarded automatically to BizDocs.\n\n" + f"Original From: {sender}\n" + f"Original Date: {date}\n" + f"Original Subject: {subject}\n" + ) + fwd.set_content(body) + + raw_bytes = original_msg.as_bytes(policy=policy.default) + fwd.add_attachment( + raw_bytes, + maintype="message", + subtype="rfc822", + filename="original-email.eml", + ) + + owns_client = smtp is None + client = smtp + if client is None: + client = create_smtp_client(smtp_config) + + try: + client.send_message(fwd) + finally: + if owns_client: + try: + client.quit() + except smtplib.SMTPException: + pass + + +def test_smtp_connection(config: SmtpConfig) -> tuple[bool, str]: + client = None + try: + client = create_smtp_client(config) + return True, "SMTP login OK" + except Exception as exc: + return False, str(exc) + finally: + if client is not None: + try: + client.quit() + except smtplib.SMTPException: + pass + + +def send_test_email( + config: SmtpConfig, + destination_email: str, +) -> tuple[bool, str]: + client = None + try: + client = create_smtp_client(config) + msg = EmailMessage() + msg["From"] = config.user + msg["To"] = destination_email + msg["Subject"] = "BizDocs Forwarder test" + msg.set_content("This is a test message from BizDocs Forwarder.") + client.send_message(msg) + return True, f"Test email sent to {destination_email}" + except Exception as exc: + return False, str(exc) + finally: + if client is not None: + try: + client.quit() + except smtplib.SMTPException: + pass diff --git a/src/forwarder/services/__init__.py b/src/forwarder/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/forwarder/services/account_service.py b/src/forwarder/services/account_service.py new file mode 100644 index 0000000..6d8aa52 --- /dev/null +++ b/src/forwarder/services/account_service.py @@ -0,0 +1,241 @@ +from __future__ import annotations + +from datetime import datetime, timezone + +from sqlalchemy.orm import Session + +from forwarder.crypto import decrypt_password, encrypt_password, mask_password +from forwarder.db.models import ( + Account, + ConnectionTest, + ConnectionTestType, + DEFAULT_ALLOWED_EXTENSIONS, +) +from forwarder.email.imap_client import ImapConfig, test_imap_connection +from forwarder.email.smtp_client import SmtpConfig, send_test_email, test_smtp_connection + + +class AccountNotFoundError(Exception): + pass + + +def _normalize_extensions(extensions: list[str] | None) -> list[str]: + if not extensions: + return list(DEFAULT_ALLOWED_EXTENSIONS) + normalized: list[str] = [] + for ext in extensions: + if not ext: + continue + if not ext.startswith("."): + ext = f".{ext}" + normalized.append(ext.lower()) + if not normalized: + return list(DEFAULT_ALLOWED_EXTENSIONS) + return normalized + + +def account_to_dict(account: Account, *, include_secrets: bool = False) -> dict: + data = { + "id": account.id, + "name": account.name, + "enabled": account.enabled, + "sync_interval_minutes": account.sync_interval_minutes, + "imap_host": account.imap_host, + "imap_port": account.imap_port, + "imap_user": account.imap_user, + "imap_password": mask_password(), + "smtp_host": account.smtp_host, + "smtp_port": account.smtp_port, + "smtp_user": account.smtp_user, + "smtp_password": mask_password(), + "smtp_use_tls": account.smtp_use_tls, + "destination_email": account.destination_email, + "include_all_attachments": account.include_all_attachments, + "allowed_extensions": account.allowed_extensions or list(DEFAULT_ALLOWED_EXTENSIONS), + "created_at": account.created_at, + "updated_at": account.updated_at, + } + if include_secrets: + data["imap_password_plain"] = decrypt_password(account.imap_password_encrypted) + data["smtp_password_plain"] = decrypt_password(account.smtp_password_encrypted) + return data + + +def list_accounts(db: Session) -> list[Account]: + return db.query(Account).order_by(Account.id).all() + + +def get_account(db: Session, account_id: int) -> Account: + account = db.get(Account, account_id) + if account is None: + raise AccountNotFoundError(f"Account {account_id} not found") + return account + + +def create_account(db: Session, data: dict) -> Account: + settings_sync = data.get("sync_interval_minutes") + account = Account( + name=data["name"], + enabled=data.get("enabled", True), + sync_interval_minutes=settings_sync if settings_sync is not None else 15, + imap_host=data["imap_host"], + imap_port=data.get("imap_port", 993), + imap_user=data["imap_user"], + imap_password_encrypted=encrypt_password(data["imap_password"]), + smtp_host=data["smtp_host"], + smtp_port=data.get("smtp_port", 587), + smtp_user=data["smtp_user"], + smtp_password_encrypted=encrypt_password(data["smtp_password"]), + smtp_use_tls=data.get("smtp_use_tls", True), + destination_email=data["destination_email"], + include_all_attachments=data.get("include_all_attachments", False), + allowed_extensions=_normalize_extensions(data.get("allowed_extensions")), + ) + db.add(account) + db.commit() + db.refresh(account) + return account + + +def update_account(db: Session, account_id: int, data: dict) -> Account: + account = get_account(db, account_id) + + for field in ("name", "enabled", "sync_interval_minutes", "imap_host", "imap_port", + "imap_user", "smtp_host", "smtp_port", "smtp_user", "smtp_use_tls", + "destination_email", "include_all_attachments"): + if field in data and data[field] is not None: + setattr(account, field, data[field]) + + if "allowed_extensions" in data and data["allowed_extensions"] is not None: + account.allowed_extensions = _normalize_extensions(data["allowed_extensions"]) + + imap_password = data.get("imap_password") + if imap_password: + account.imap_password_encrypted = encrypt_password(imap_password) + + smtp_password = data.get("smtp_password") + if smtp_password: + account.smtp_password_encrypted = encrypt_password(smtp_password) + + account.updated_at = datetime.now(timezone.utc) + db.commit() + db.refresh(account) + return account + + +def delete_account(db: Session, account_id: int) -> None: + account = get_account(db, account_id) + db.delete(account) + db.commit() + + +def resolve_imap_config(db: Session, account_id: int | None, inline: dict | None) -> ImapConfig: + if inline: + password = inline.get("imap_password") or inline.get("password") or "" + if not password and account_id is not None: + account = get_account(db, account_id) + password = decrypt_password(account.imap_password_encrypted) + return ImapConfig( + host=inline["imap_host"], + port=int(inline.get("imap_port", 993)), + user=inline["imap_user"], + password=password, + ) + + if account_id is None: + raise ValueError("account_id or inline config required") + + account = get_account(db, account_id) + return ImapConfig( + host=account.imap_host, + port=account.imap_port, + user=account.imap_user, + password=decrypt_password(account.imap_password_encrypted), + ) + + +def resolve_smtp_config(db: Session, account_id: int | None, inline: dict | None) -> SmtpConfig: + if inline: + password = inline.get("smtp_password") or inline.get("password") or "" + if not password and account_id is not None: + account = get_account(db, account_id) + password = decrypt_password(account.smtp_password_encrypted) + return SmtpConfig( + host=inline["smtp_host"], + port=int(inline.get("smtp_port", 587)), + user=inline["smtp_user"], + password=password, + use_tls=inline.get("smtp_use_tls", True), + ) + + if account_id is None: + raise ValueError("account_id or inline config required") + + account = get_account(db, account_id) + return SmtpConfig( + host=account.smtp_host, + port=account.smtp_port, + user=account.smtp_user, + password=decrypt_password(account.smtp_password_encrypted), + use_tls=account.smtp_use_tls, + ) + + +def resolve_destination(db: Session, account_id: int | None, inline: dict | None) -> str: + if inline and inline.get("destination_email"): + return inline["destination_email"] + if account_id is None: + raise ValueError("destination_email required") + account = get_account(db, account_id) + return account.destination_email + + +def record_connection_test( + db: Session, + *, + account_id: int | None, + test_type: ConnectionTestType, + success: bool, + message: str, +) -> ConnectionTest: + row = ConnectionTest( + account_id=account_id, + test_type=test_type, + success=success, + message=message, + ) + db.add(row) + db.commit() + db.refresh(row) + return row + + +def run_imap_test(db: Session, account_id: int | None, inline: dict | None) -> tuple[bool, str]: + config = resolve_imap_config(db, account_id, inline) + success, message = test_imap_connection(config) + record_connection_test( + db, account_id=account_id, test_type=ConnectionTestType.imap, + success=success, message=message, + ) + return success, message + + +def run_smtp_test(db: Session, account_id: int | None, inline: dict | None) -> tuple[bool, str]: + config = resolve_smtp_config(db, account_id, inline) + success, message = test_smtp_connection(config) + record_connection_test( + db, account_id=account_id, test_type=ConnectionTestType.smtp, + success=success, message=message, + ) + return success, message + + +def run_send_test(db: Session, account_id: int | None, inline: dict | None) -> tuple[bool, str]: + config = resolve_smtp_config(db, account_id, inline) + destination = resolve_destination(db, account_id, inline) + success, message = send_test_email(config, destination) + record_connection_test( + db, account_id=account_id, test_type=ConnectionTestType.send, + success=success, message=message, + ) + return success, message diff --git a/src/forwarder/services/auth_service.py b/src/forwarder/services/auth_service.py new file mode 100644 index 0000000..be3d6a1 --- /dev/null +++ b/src/forwarder/services/auth_service.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from passlib.context import CryptContext + +from forwarder.config import get_settings +from forwarder.db.models import User +from forwarder.db.session import get_session_factory + +_pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + + +def hash_password(password: str) -> str: + return _pwd_context.hash(password) + + +def verify_password(plain: str, hashed: str) -> bool: + return _pwd_context.verify(plain, hashed) + + +def ensure_admin_user() -> None: + settings = get_settings() + db = get_session_factory()() + try: + existing = db.query(User).filter(User.username == settings.admin_username).first() + if existing is not None: + return + admin = User( + username=settings.admin_username, + password_hash=hash_password(settings.admin_password), + is_admin=True, + ) + db.add(admin) + db.commit() + finally: + db.close() + + +def authenticate_user(username: str, password: str) -> User | None: + db = get_session_factory()() + try: + user = db.query(User).filter(User.username == username).first() + if user is None: + return None + if not verify_password(password, user.password_hash): + return None + return user + finally: + db.close() diff --git a/src/forwarder/services/sync_service.py b/src/forwarder/services/sync_service.py new file mode 100644 index 0000000..8d8cb01 --- /dev/null +++ b/src/forwarder/services/sync_service.py @@ -0,0 +1,332 @@ +from __future__ import annotations + +import imaplib +import logging +from datetime import datetime, timezone + +import smtplib +from sqlalchemy.orm import Session + +from forwarder.crypto import decrypt_password +from forwarder.db.models import ( + Account, + ForwardAttempt, + Message, + MessageStatus, + SyncRun, + SyncRunStatus, +) +from forwarder.email.imap_client import ( + connect_imap, + fetch_message, + list_mailboxes, + select_folder_readonly, + should_skip_folder, + ImapConfig, +) +from forwarder.email.parsing import ( + clean_subject, + get_message_key, + has_matching_attachment, +) +from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_email_as_eml +from forwarder.services.account_service import get_account + +logger = logging.getLogger(__name__) + + +class SyncResult: + def __init__(self) -> None: + self.messages_scanned = 0 + self.messages_matched = 0 + self.messages_forwarded = 0 + self.messages_skipped = 0 + self.messages_failed = 0 + + +def _get_processed_keys(db: Session, account_id: int) -> set[str]: + rows = ( + db.query(Message.message_key) + .filter( + Message.account_id == account_id, + Message.status.in_([ + MessageStatus.forwarded, + MessageStatus.dry_run, + ]), + ) + .all() + ) + return {row[0] for row in rows} + + +def _upsert_message( + db: Session, + *, + account_id: int, + message_key: str, + folder: str, + uid: str, + subject: str, + from_addr: str, + date: str, + status: MessageStatus, + error_message: str | None = None, +) -> Message: + existing = ( + db.query(Message) + .filter(Message.account_id == account_id, Message.message_key == message_key) + .first() + ) + if existing is not None: + existing.status = status + existing.error_message = error_message + existing.updated_at = datetime.now(timezone.utc) + db.commit() + db.refresh(existing) + return existing + + msg = Message( + account_id=account_id, + message_key=message_key, + folder=folder, + uid=uid, + subject=subject, + from_addr=from_addr, + date=date, + status=status, + error_message=error_message, + ) + db.add(msg) + db.commit() + db.refresh(msg) + return msg + + +def _record_forward_attempt( + db: Session, + *, + message: Message, + success: bool, + dry_run: bool, + error_message: str | None = None, +) -> None: + attempt = ForwardAttempt( + message_id=message.id, + success=success, + dry_run=dry_run, + error_message=error_message, + ) + db.add(attempt) + db.commit() + + +def sync_account( + db: Session, + account_id: int, + *, + dry_run: bool = False, + max_emails: int | None = None, +) -> SyncRun: + account = get_account(db, account_id) + sync_run = SyncRun( + account_id=account_id, + status=SyncRunStatus.running, + dry_run=dry_run, + max_emails=max_emails, + ) + db.add(sync_run) + db.commit() + db.refresh(sync_run) + + result = SyncResult() + imap = None + smtp = None + + try: + imap_config = ImapConfig( + host=account.imap_host, + port=account.imap_port, + user=account.imap_user, + password=decrypt_password(account.imap_password_encrypted), + ) + smtp_config = SmtpConfig( + host=account.smtp_host, + port=account.smtp_port, + user=account.smtp_user, + password=decrypt_password(account.smtp_password_encrypted), + use_tls=account.smtp_use_tls, + ) + + allowed_extensions = set(account.allowed_extensions or []) + processed_keys = _get_processed_keys(db, account_id) + handled_count = 0 + stop_all = False + + imap = connect_imap(imap_config) + if not dry_run: + smtp = create_smtp_client(smtp_config) + + folders = list_mailboxes(imap) + logger.info("Account %s: %d mailbox(es)", account_id, len(folders)) + + for folder in folders: + if stop_all: + break + + if should_skip_folder(folder): + logger.debug("Skipping folder: %s", folder) + continue + + try: + if not select_folder_readonly(imap, folder): + logger.warning("Could not open folder: %s", folder) + continue + except imaplib.IMAP4.error as exc: + logger.warning("Could not open folder %s: %s", folder, exc) + continue + + try: + status, data = imap.uid("search", None, "ALL") + except imaplib.IMAP4.error as exc: + logger.warning("Search failed in %s: %s", folder, exc) + continue + + if status != "OK" or not data or not data[0]: + continue + + uids = data[0].split() + + for uid in uids: + if max_emails is not None and handled_count >= max_emails: + stop_all = True + break + + result.messages_scanned += 1 + uid_str = uid.decode() if isinstance(uid, bytes) else str(uid) + + try: + msg = fetch_message(imap, uid) + except imaplib.IMAP4.error as exc: + logger.error("Fetch error UID %s in %s: %s", uid_str, folder, exc) + result.messages_failed += 1 + continue + + if msg is None: + result.messages_failed += 1 + continue + + message_key = get_message_key(folder, uid, msg) + subject = clean_subject(msg.get("Subject")) + from_addr = msg.get("From", "") or "" + date = msg.get("Date", "") or "" + + if message_key in processed_keys: + result.messages_skipped += 1 + continue + + if not has_matching_attachment( + msg, + include_all_attachments=account.include_all_attachments, + allowed_extensions=allowed_extensions, + ): + continue + + result.messages_matched += 1 + + if dry_run: + message_row = _upsert_message( + db, + account_id=account_id, + message_key=message_key, + folder=folder, + uid=uid_str, + subject=subject, + from_addr=from_addr, + date=date, + status=MessageStatus.dry_run, + ) + _record_forward_attempt( + db, message=message_row, success=True, dry_run=True, + ) + processed_keys.add(message_key) + result.messages_forwarded += 1 + handled_count += 1 + logger.info("DRY_RUN matched: %s", subject) + continue + + try: + forward_email_as_eml( + msg, + smtp_config=smtp_config, + destination_email=account.destination_email, + smtp=smtp, + ) + message_row = _upsert_message( + db, + account_id=account_id, + message_key=message_key, + folder=folder, + uid=uid_str, + subject=subject, + from_addr=from_addr, + date=date, + status=MessageStatus.forwarded, + ) + _record_forward_attempt( + db, message=message_row, success=True, dry_run=False, + ) + processed_keys.add(message_key) + result.messages_forwarded += 1 + handled_count += 1 + logger.info("Forwarded: %s", subject) + except Exception as exc: + error_text = str(exc) + logger.error("Forward failed for %s: %s", subject, error_text) + message_row = _upsert_message( + db, + account_id=account_id, + message_key=message_key, + folder=folder, + uid=uid_str, + subject=subject, + from_addr=from_addr, + date=date, + status=MessageStatus.failed, + error_message=error_text, + ) + _record_forward_attempt( + db, + message=message_row, + success=False, + dry_run=False, + error_message=error_text, + ) + result.messages_failed += 1 + + sync_run.status = SyncRunStatus.completed + except Exception as exc: + sync_run.status = SyncRunStatus.failed + sync_run.error_message = str(exc) + logger.exception("Sync failed for account %s", account_id) + finally: + if imap is not None: + try: + imap.logout() + except imaplib.IMAP4.error: + pass + if smtp is not None: + try: + smtp.quit() + except smtplib.SMTPException: + pass + + sync_run.messages_scanned = result.messages_scanned + sync_run.messages_matched = result.messages_matched + sync_run.messages_forwarded = result.messages_forwarded + sync_run.messages_skipped = result.messages_skipped + sync_run.messages_failed = result.messages_failed + sync_run.finished_at = datetime.now(timezone.utc) + db.commit() + db.refresh(sync_run) + + return sync_run diff --git a/src/forwarder/worker/__init__.py b/src/forwarder/worker/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/forwarder/worker/scheduler.py b/src/forwarder/worker/scheduler.py new file mode 100644 index 0000000..b682ea5 --- /dev/null +++ b/src/forwarder/worker/scheduler.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +import logging + +from apscheduler.schedulers.blocking import BlockingScheduler +from apscheduler.triggers.interval import IntervalTrigger + +from forwarder.db.models import Account +from forwarder.db.session import get_session_factory +from forwarder.services.sync_service import sync_account + +logger = logging.getLogger(__name__) + + +def _sync_job(account_id: int) -> None: + db = get_session_factory()() + try: + logger.info("Scheduled sync starting for account %s", account_id) + sync_account(db, account_id, dry_run=False) + except Exception: + logger.exception("Scheduled sync failed for account %s", account_id) + finally: + db.close() + + +def run_worker(*, default_interval: int = 15) -> None: + scheduler = BlockingScheduler() + + db = get_session_factory()() + try: + accounts = db.query(Account).filter(Account.enabled.is_(True)).all() + for account in accounts: + interval = account.sync_interval_minutes or default_interval + scheduler.add_job( + _sync_job, + trigger=IntervalTrigger(minutes=interval), + args=[account.id], + id=f"sync-account-{account.id}", + replace_existing=True, + max_instances=1, + ) + logger.info( + "Scheduled account %s (%s) every %s minutes", + account.id, + account.name, + interval, + ) + finally: + db.close() + + if not scheduler.get_jobs(): + logger.warning("No enabled accounts — worker idle (restarts pick up new accounts)") + + scheduler.start()