70 lines
2.9 KiB
Python
70 lines
2.9 KiB
Python
# -*- coding: utf-8 -*-
|
||
# =============================================================================
|
||
# Nazev: watch_new_emails_v1.0.py
|
||
# Verze: 1.0
|
||
# Datum: 2026-06-12
|
||
# Popis: Background poller pro feasibility session. Sleduje kolekci
|
||
# emaily."vbuzalka@its.jnj.com" v Mongo (192.168.1.76:27017) a ceka,
|
||
# az pribude email novejsi nez baseline (nejnovejsi received_at pri
|
||
# startu). Jakmile neco najde, vypise prehled novych emailu a SKONCI
|
||
# (exit 0) -> background task tim re-invokuje Claude, ktery je vyhodnoti.
|
||
# Polluje kazdych POLL_SECONDS. Po MAX_HOURS se ukonci (exit 0) i bez
|
||
# nalezu, aby session nedrzel proces donekonecna.
|
||
# Pouziti: python watch_new_emails_v1.0.py
|
||
# =============================================================================
|
||
import sys
|
||
import time
|
||
from datetime import datetime, timedelta
|
||
from pymongo import MongoClient
|
||
|
||
MONGO_URI = "mongodb://192.168.1.76:27017"
|
||
DB = "emaily"
|
||
COLL = "vbuzalka@its.jnj.com"
|
||
FOLDER = "/vbuzalka@its.jnj.com/Inbox"
|
||
POLL_SECONDS = 120
|
||
MAX_HOURS = 12
|
||
|
||
def newest(col):
|
||
doc = col.find_one({"jnj_folder": FOLDER}, sort=[("received_at", -1)],
|
||
projection={"received_at": 1})
|
||
return doc["received_at"] if doc else None
|
||
|
||
def fmt(v):
|
||
if isinstance(v, datetime):
|
||
return v.strftime("%Y-%m-%d %H:%M:%S")
|
||
return str(v)
|
||
|
||
def main():
|
||
client = MongoClient(MONGO_URI, serverSelectionTimeoutMS=10000)
|
||
col = client[DB][COLL]
|
||
baseline = newest(col)
|
||
print(f"[watch] start baseline received_at = {fmt(baseline)}", flush=True)
|
||
deadline = datetime.now() + timedelta(hours=MAX_HOURS)
|
||
|
||
while datetime.now() < deadline:
|
||
time.sleep(POLL_SECONDS)
|
||
try:
|
||
cur = newest(col)
|
||
except Exception as e:
|
||
print(f"[watch] poll error: {e}", flush=True)
|
||
continue
|
||
if cur is not None and baseline is not None and cur > baseline:
|
||
new_docs = list(col.find(
|
||
{"jnj_folder": FOLDER, "received_at": {"$gt": baseline}},
|
||
projection={"received_at": 1, "sender.email": 1, "subject": 1,
|
||
"attachments.filename": 1},
|
||
sort=[("received_at", -1)]))
|
||
print(f"\n=== NOVE EMAILY: {len(new_docs)} (po {fmt(baseline)}) ===", flush=True)
|
||
for d in new_docs:
|
||
snd = (d.get("sender") or {}).get("email", "")
|
||
atts = [a.get("filename") for a in (d.get("attachments") or [])]
|
||
print(f"- {fmt(d.get('received_at'))} | {snd} | {d.get('subject')}"
|
||
+ (f" | prilohy: {atts}" if atts else ""), flush=True)
|
||
print(f" _id: {d.get('_id')}", flush=True)
|
||
print("=== KONEC – task skoncil, vyhodnot v session ===", flush=True)
|
||
return
|
||
print("[watch] MAX_HOURS vyprselo bez noveho emailu – konec.", flush=True)
|
||
|
||
if __name__ == "__main__":
|
||
main()
|