Files
forwarder/worker/worker.py
T
XikaandPaperclip d8daca15bd feat(backend): add FastAPI, worker, web nginx — full platform (BIT-26121)
- api/: FastAPI app with MySQL (accounts, forwarding_rules, messages)
  - GET/POST/PUT/DELETE /accounts + /accounts/{id}/test
  - GET /messages + /messages/{id}/retry
  - GET /stats
  - POST /connection/test
  - Auto-runs migrations/init.sql on startup
- worker/: Python IMAP poller + BizDocs upload (schedule every 5 min)
- web/: multi-stage Dockerfile — builds admin-ui via Node, serves via nginx
  - nginx proxies /api/ → api:8000, SPA fallback for React Router
- docker-compose.yml: updated web build context + mysql init.sql mount

Co-Authored-By: Paperclip <[email protected]>
2026-06-30 23:04:54 +00:00

115 lines
3.4 KiB
Python

"""BizDocs Forwarder worker — polls IMAP accounts and forwards attachments."""
import logging
import time
import schedule
from db import (
get_enabled_accounts, get_rules_for_account,
create_message, update_message, update_account_uid,
)
from imap_client import fetch_new_messages
from bizdocs_client import upload_document
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
log = logging.getLogger("worker")
POLL_INTERVAL_MINUTES = 5
def _rule_matches(rule: dict, msg: dict) -> bool:
if rule["filter_has_attachment"] and not msg["filename"]:
return False
if rule["filter_from"]:
if rule["filter_from"].lower() not in msg["sender"].lower():
return False
if rule["filter_subject"]:
if rule["filter_subject"].lower() not in msg["subject"].lower():
return False
ext = msg["filename"].rsplit(".", 1)[-1].lower() if "." in msg["filename"] else ""
allowed = [e.strip().lower() for e in rule["allowed_extensions"].split(",")]
if allowed and ext not in allowed:
return False
return True
def process_account(account: dict):
account_id = account["id"]
log.info("Checking account %s (%s)", account_id, account["email"])
max_uid = account["last_uid"]
rules = get_rules_for_account(account_id)
for msg in fetch_new_messages(account):
uid = msg["uid"]
max_uid = max(max_uid, uid)
if not rules:
log.debug("No forwarding rules for account %s, skipping uid=%d", account_id, uid)
continue
matched_rule = next((r for r in rules if _rule_matches(r, msg)), None)
if matched_rule is None:
log.debug("No matching rule for uid=%d file=%s", uid, msg["filename"])
continue
msg_id = create_message(
account_id=account_id,
rule_id=matched_rule["id"],
message_uid=uid,
subject=msg["subject"],
sender=msg["sender"],
received_at=msg["received_at"],
filename=msg["filename"],
file_size=msg["size"],
)
try:
doc_id = upload_document(
bizdocs_url="https://app.bizdocs.pt/api",
api_key=account["bizdocs_api_key"],
filename=msg["filename"],
data=msg["data"],
entity_id=account.get("bizdocs_entity_id"),
)
update_message(msg_id, "forwarded", bizdocs_doc_id=doc_id)
log.info("Forwarded %s → bizdocs doc %s", msg["filename"], doc_id)
except Exception as exc:
update_message(msg_id, "failed", error=str(exc))
log.error("Upload failed for uid=%d file=%s: %s", uid, msg["filename"], exc)
if max_uid > account["last_uid"]:
update_account_uid(account_id, max_uid)
def run():
accounts = get_enabled_accounts()
if not accounts:
log.info("No enabled accounts, skipping cycle")
return
for account in accounts:
try:
process_account(account)
except Exception as exc:
log.error("Unhandled error on account %s: %s", account.get("email"), exc)
def main():
log.info("BizDocs Forwarder worker starting, poll interval %d min", POLL_INTERVAL_MINUTES)
run()
schedule.every(POLL_INTERVAL_MINUTES).minutes.do(run)
while True:
schedule.run_pending()
time.sleep(30)
if __name__ == "__main__":
main()