Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -8,8 +8,6 @@ from werkzeug.utils import secure_filename
|
|
| 8 |
from flask_apscheduler import APScheduler
|
| 9 |
import firebase_admin
|
| 10 |
from firebase_admin import credentials, db, auth as firebase_auth
|
| 11 |
-
from resend import Emails
|
| 12 |
-
from resend.exceptions import ResendError
|
| 13 |
import logging
|
| 14 |
from logging.handlers import RotatingFileHandler
|
| 15 |
import time
|
|
@@ -17,19 +15,8 @@ import random
|
|
| 17 |
from datetime import datetime as dt_class, timezone
|
| 18 |
from zoneinfo import ZoneInfo
|
| 19 |
import pandas as pd
|
| 20 |
-
import
|
| 21 |
-
import
|
| 22 |
-
|
| 23 |
-
# === DNS RESOLUTION FIX ===
|
| 24 |
-
# This is the definitive solution for networking issues in restricted environments.
|
| 25 |
-
# It intercepts DNS lookups for 'api.resend.com' and forces them through a
|
| 26 |
-
# reliable public DNS resolver, bypassing any potential issues with the
|
| 27 |
-
# container's default DNS settings.
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
|
| 34 |
# === Logging Configuration ===
|
| 35 |
if not os.path.exists('logs'):
|
|
@@ -49,42 +36,6 @@ root_logger.setLevel(logging.INFO)
|
|
| 49 |
root_logger.addHandler(file_handler)
|
| 50 |
root_logger.addHandler(console_handler)
|
| 51 |
|
| 52 |
-
def setup_dns_override():
|
| 53 |
-
"""Overrides the default socket address resolver for a specific domain."""
|
| 54 |
-
try:
|
| 55 |
-
# Use reliable public DNS servers
|
| 56 |
-
resolver = dns.resolver.Resolver()
|
| 57 |
-
resolver.nameservers = ['8.8.8.8', '8.8.4.4']
|
| 58 |
-
|
| 59 |
-
# Store the original resolver function
|
| 60 |
-
original_getaddrinfo = socket.getaddrinfo
|
| 61 |
-
|
| 62 |
-
def new_getaddrinfo(*args, **kwargs):
|
| 63 |
-
# Check if the domain we're looking up is the one we want to override
|
| 64 |
-
if args and isinstance(args[0], str) and 'api.resend.com' in args[0]:
|
| 65 |
-
try:
|
| 66 |
-
# Resolve the domain to an IP address using our custom resolver
|
| 67 |
-
answers = resolver.resolve(args[0], 'A')
|
| 68 |
-
ip_address = str(answers[0])
|
| 69 |
-
logger.info(f"DNS Override: Resolved {args[0]} to {ip_address}")
|
| 70 |
-
# Call the original function with the IP address instead of the domain
|
| 71 |
-
return original_getaddrinfo(ip_address, *args[1:], **kwargs)
|
| 72 |
-
except Exception as e:
|
| 73 |
-
logger.error(f"DNS Override Failed for {args[0]}: {e}. Falling back to default resolver.")
|
| 74 |
-
|
| 75 |
-
# For all other domains, use the original resolver
|
| 76 |
-
return original_getaddrinfo(*args, **kwargs)
|
| 77 |
-
|
| 78 |
-
# Replace the system's default resolver with our new one
|
| 79 |
-
socket.getaddrinfo = new_getaddrinfo
|
| 80 |
-
logger.info("Custom DNS resolver for 'api.resend.com' has been successfully set up.")
|
| 81 |
-
except Exception as e:
|
| 82 |
-
logger.error(f"Failed to set up custom DNS resolver: {e}")
|
| 83 |
-
|
| 84 |
-
# Apply the fix at startup
|
| 85 |
-
setup_dns_override()
|
| 86 |
-
# === END DNS FIX ===
|
| 87 |
-
|
| 88 |
# === ENV Config & Admin Setup ===
|
| 89 |
ADMIN_EMAILS = ["rairorr@gmail.com", "nharingosheperd@gmail.com"]
|
| 90 |
SEND_TO_EMAILS = ["rairorr@gmail.com", "nharingosheperd+guard@gmail.com"]
|
|
@@ -103,34 +54,68 @@ except Exception as e:
|
|
| 103 |
logger.error(f"Failed to initialize Firebase Admin: {e}", exc_info=True)
|
| 104 |
raise
|
| 105 |
|
| 106 |
-
# === Flask App & Scheduler
|
| 107 |
app = Flask(__name__)
|
| 108 |
CORS(app)
|
| 109 |
app.config.from_object(type('Config', (object,), {'SCHEDULER_API_ENABLED': True})())
|
| 110 |
scheduler = APScheduler()
|
| 111 |
scheduler.init_app(app)
|
| 112 |
scheduler.start()
|
| 113 |
-
|
| 114 |
-
logger.info("Flask, APScheduler, and Resend initialized.")
|
| 115 |
|
| 116 |
|
|
|
|
| 117 |
def send_email(to, subject, html):
|
| 118 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
try:
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
logger.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
return None
|
| 132 |
except Exception as e:
|
| 133 |
-
logger.error(f"An unexpected exception occurred
|
| 134 |
return None
|
| 135 |
|
| 136 |
|
|
|
|
| 8 |
from flask_apscheduler import APScheduler
|
| 9 |
import firebase_admin
|
| 10 |
from firebase_admin import credentials, db, auth as firebase_auth
|
|
|
|
|
|
|
| 11 |
import logging
|
| 12 |
from logging.handlers import RotatingFileHandler
|
| 13 |
import time
|
|
|
|
| 15 |
from datetime import datetime as dt_class, timezone
|
| 16 |
from zoneinfo import ZoneInfo
|
| 17 |
import pandas as pd
|
| 18 |
+
import requests # <-- Used for direct API calls
|
| 19 |
+
import certifi # <-- Used for modern SSL certificates
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
# === Logging Configuration ===
|
| 22 |
if not os.path.exists('logs'):
|
|
|
|
| 36 |
root_logger.addHandler(file_handler)
|
| 37 |
root_logger.addHandler(console_handler)
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
# === ENV Config & Admin Setup ===
|
| 40 |
ADMIN_EMAILS = ["rairorr@gmail.com", "nharingosheperd@gmail.com"]
|
| 41 |
SEND_TO_EMAILS = ["rairorr@gmail.com", "nharingosheperd+guard@gmail.com"]
|
|
|
|
| 54 |
logger.error(f"Failed to initialize Firebase Admin: {e}", exc_info=True)
|
| 55 |
raise
|
| 56 |
|
| 57 |
+
# === Flask App & Scheduler Setup ===
|
| 58 |
app = Flask(__name__)
|
| 59 |
CORS(app)
|
| 60 |
app.config.from_object(type('Config', (object,), {'SCHEDULER_API_ENABLED': True})())
|
| 61 |
scheduler = APScheduler()
|
| 62 |
scheduler.init_app(app)
|
| 63 |
scheduler.start()
|
| 64 |
+
logger.info("Flask and APScheduler initialized.")
|
|
|
|
| 65 |
|
| 66 |
|
| 67 |
+
# === DEFINITIVE EMAIL SENDING FUNCTION ===
|
| 68 |
def send_email(to, subject, html):
|
| 69 |
+
"""
|
| 70 |
+
Sends an email using a direct requests call to bypass library issues and
|
| 71 |
+
ensure a modern SSL certificate bundle is used.
|
| 72 |
+
"""
|
| 73 |
+
if not RESEND_API_KEY:
|
| 74 |
+
logger.error("RESEND_API_KEY is not configured. Cannot send email.")
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
url = "https://api.resend.com/emails"
|
| 78 |
+
headers = {
|
| 79 |
+
"Authorization": f"Bearer {RESEND_API_KEY.strip()}",
|
| 80 |
+
"Content-Type": "application/json"
|
| 81 |
+
}
|
| 82 |
+
payload = {
|
| 83 |
+
"from": "Admin <admin@resend.dev>",
|
| 84 |
+
"to": to.strip(),
|
| 85 |
+
"subject": subject,
|
| 86 |
+
"html": html
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
logger.info(f"Attempting DIRECT API call to Resend for recipient: {to}")
|
| 90 |
+
|
| 91 |
try:
|
| 92 |
+
# This is the critical part: make a direct request and explicitly
|
| 93 |
+
# tell it to verify the connection using certifi's CA bundle.
|
| 94 |
+
response = requests.post(
|
| 95 |
+
url,
|
| 96 |
+
headers=headers,
|
| 97 |
+
json=payload,
|
| 98 |
+
verify=certifi.where(),
|
| 99 |
+
timeout=15 # Add a reasonable timeout
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
logger.info(f"Direct call response status for '{to}': {response.status_code}")
|
| 103 |
+
|
| 104 |
+
# Check if the HTTP request itself was successful
|
| 105 |
+
response.raise_for_status()
|
| 106 |
+
|
| 107 |
+
response_data = response.json()
|
| 108 |
+
logger.info(f"Email sent successfully to {to}. Email ID: {response_data.get('id')}")
|
| 109 |
+
return response_data
|
| 110 |
+
|
| 111 |
+
except requests.exceptions.SSLError as e:
|
| 112 |
+
logger.error(f"CRITICAL: SSL Error occurred for '{to}' despite using Certifi. This points to a deep network issue or firewall. Error: {repr(e)}", exc_info=True)
|
| 113 |
+
return None
|
| 114 |
+
except requests.exceptions.RequestException as e:
|
| 115 |
+
logger.error(f"A low-level network error occurred for '{to}'. The raw error is: {repr(e)}", exc_info=True)
|
| 116 |
return None
|
| 117 |
except Exception as e:
|
| 118 |
+
logger.error(f"An unexpected exception occurred during direct API call for '{to}'. Error: {repr(e)}", exc_info=True)
|
| 119 |
return None
|
| 120 |
|
| 121 |
|