"""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()