#!/usr/bin/env python3
import subprocess
import os
import sys
import logging
import requests
from pathlib import Path
from datetime import datetime
# === CONFIG ===
BASE_DIR = Path("/home/matrixhasyou/mutt")
PYTHON_BIN = "/usr/bin/python3"
GOOGLE_PYTHON_BIN = "/home/matrixhasyou/swarm-services/domovoy-bot/venv-google/bin/python"
EXPORT_SCRIPT = BASE_DIR / "export_emails.py"
CONSOLIDATE_SCRIPT = BASE_DIR / "consolidate_to_mega_pdf.py"
DRIVE_SYNC_SCRIPT = Path("/home/matrixhasyou/domovoy_drive_sync.py")
MASTER_PDF = BASE_DIR / "ALL_EMAILS_CONSOLIDATED.pdf"
BOT_TOKEN = "8725618164:AAH1tGalq-pw1l0t4P5c0sdLkCVJdh7IE7M"
CHAT_ID = "197957361"
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
log = logging.getLogger("MasterSync")
def send_tg(text):
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
try:
requests.post(url, json={"chat_id": CHAT_ID, "text": text, "parse_mode": "HTML"},
timeout=20)
except Exception as e:
log.error(f"TG notification failed: {e}")
def run_step(name, cmd):
log.info(f"--- Step: {name} ---")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
log.error(f"Step {name} FAILED!")
log.error(result.stderr)
return False, result.stderr
log.info(f"Step {name} completed.")
return True, result.stdout
def main():
start_time = datetime.now()
log.info(f"Starting Master Sync at {start_time}")
# 1. Export Emails
ok, out_export = run_step("Export Emails", [PYTHON_BIN, str(EXPORT_SCRIPT)])
if not ok:
send_tg(f"❌ Mutt Master Sync: FAILED\nStep: Export Emails\nError: {out_export[:200]}")
return
# 2. Consolidate PDF
ok, out_consolidate = run_step("Consolidate PDF", [PYTHON_BIN, str(CONSOLIDATE_SCRIPT)])
if not ok:
send_tg(f"❌ Mutt Master Sync: FAILED\nStep: Consolidate PDF\nError: {out_consolidate[:200]}")
return
# 3. Sync to G-Drive
ok, out_drive = run_step("G-Drive Sync", [GOOGLE_PYTHON_BIN, str(DRIVE_SYNC_SCRIPT), str(MASTER_PDF)])
if not ok:
send_tg(f"❌ Mutt Master Sync: FAILED\nStep: G-Drive Sync\nError: {out_drive[:200]}")
return
end_time = datetime.now()
# Parsing Stats
new_emails = 0
total_emails = 0
for line in out_export.split('\n'):
if "Processed this run:" in line:
try: new_emails = int(line.split(':')[-1].strip())
except: pass
for line in out_consolidate.split('\n'):
if "Found" in line and "PDFs" in line:
try: total_emails = int(line.split('Found')[-1].split('PDFs')[0].strip())
except: pass
pdf_size_mb = os.path.getsize(MASTER_PDF) / (1024 * 1024)
summary = f"""
🚀 AI ПОЧТОВЫЙ ТУРБО-СИНХРОН: OK 🚀
📥 Новых писем: {new_emails}
📚 Всего в архиве: {total_emails}
🐘 Размер PDF: {pdf_size_mb:.2f} МБ
☁️ G-Drive: Обновлено ✅
📅 {end_time.strftime("%Y-%m-%d %H:%M")}
Робот закончил работу. NotebookLM готов к анализу.
"""
send_tg(summary)
log.info("Master Sync completed successfully.")
# Save last sync time for web UI
sync_time_file = Path("/home/matrixhasyou/mutt/last_ai_sync.txt")
with open(sync_time_file, "w") as f:
f.write(end_time.strftime("%Y-%m-%d %H:%M:%S"))
if __name__ == "__main__":
main()