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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import uuid
|
| 4 |
+
import pytz
|
| 5 |
+
import psycopg2
|
| 6 |
+
import requests
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import json
|
| 9 |
+
import pickle
|
| 10 |
+
import base64
|
| 11 |
+
|
| 12 |
+
from google.auth.transport.requests import Request
|
| 13 |
+
from googleapiclient.discovery import build
|
| 14 |
+
from google.oauth2.credentials import Credentials
|
| 15 |
+
|
| 16 |
+
from email.mime.text import MIMEText
|
| 17 |
+
from datetime import datetime, date
|
| 18 |
+
from dotenv import load_dotenv
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ================= LOAD ENV =================
|
| 22 |
+
|
| 23 |
+
load_dotenv()
|
| 24 |
+
|
| 25 |
+
DB_URL = os.getenv("DB_URL")
|
| 26 |
+
GMAIL_USER = os.getenv("GMAIL_USER")
|
| 27 |
+
CRON_SECRET = os.getenv("CRON")
|
| 28 |
+
HF_URL = os.getenv("HF_URL")
|
| 29 |
+
|
| 30 |
+
LEETCODE_API = "https://leetcode-api-vercel.vercel.app"
|
| 31 |
+
|
| 32 |
+
SCOPES = ["https://www.googleapis.com/auth/gmail.send"]
|
| 33 |
+
TOKEN_FILE = "token.pkl"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ================= DB =================
|
| 37 |
+
|
| 38 |
+
def get_db():
|
| 39 |
+
return psycopg2.connect(DB_URL, sslmode="require")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# ================= GMAIL =================
|
| 43 |
+
|
| 44 |
+
def get_gmail_service():
|
| 45 |
+
creds = None
|
| 46 |
+
|
| 47 |
+
# First, try to load existing token
|
| 48 |
+
if os.path.exists(TOKEN_FILE):
|
| 49 |
+
try:
|
| 50 |
+
with open(TOKEN_FILE, "rb") as f:
|
| 51 |
+
creds = pickle.load(f)
|
| 52 |
+
except Exception as e:
|
| 53 |
+
print(f"⚠️ Failed to load token.pkl: {e}")
|
| 54 |
+
creds = None
|
| 55 |
+
|
| 56 |
+
# Refresh token if needed
|
| 57 |
+
if creds and creds.expired and creds.refresh_token:
|
| 58 |
+
try:
|
| 59 |
+
print("🔄 Refreshing expired token...")
|
| 60 |
+
creds.refresh(Request())
|
| 61 |
+
|
| 62 |
+
# Save refreshed token
|
| 63 |
+
with open(TOKEN_FILE, "wb") as f:
|
| 64 |
+
pickle.dump(creds, f)
|
| 65 |
+
print("✅ Token refreshed and saved")
|
| 66 |
+
|
| 67 |
+
except Exception as e:
|
| 68 |
+
print(f"❌ Failed to refresh token: {e}")
|
| 69 |
+
creds = None
|
| 70 |
+
|
| 71 |
+
# If no valid token, try to create from credentials.json
|
| 72 |
+
if not creds or not creds.valid:
|
| 73 |
+
creds = create_token_from_credentials()
|
| 74 |
+
|
| 75 |
+
return build("gmail", "v1", credentials=creds)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def create_token_from_credentials():
|
| 79 |
+
"""Create token.pkl from credentials.json using OAuth flow"""
|
| 80 |
+
|
| 81 |
+
credentials_file = "credentials.json"
|
| 82 |
+
|
| 83 |
+
if not os.path.exists(credentials_file):
|
| 84 |
+
raise Exception(f"""
|
| 85 |
+
❌ Neither {TOKEN_FILE} nor {credentials_file} found!
|
| 86 |
+
|
| 87 |
+
Please provide one of:
|
| 88 |
+
1. Upload token.pkl (ready-to-use token)
|
| 89 |
+
2. Upload credentials.json (will generate token.pkl)
|
| 90 |
+
|
| 91 |
+
To get credentials.json:
|
| 92 |
+
1. Go to Google Cloud Console
|
| 93 |
+
2. Enable Gmail API
|
| 94 |
+
3. Create OAuth 2.0 credentials
|
| 95 |
+
4. Download as credentials.json
|
| 96 |
+
""")
|
| 97 |
+
|
| 98 |
+
try:
|
| 99 |
+
print(f"📁 Found {credentials_file}, creating token...")
|
| 100 |
+
|
| 101 |
+
from google_auth_oauthlib.flow import InstalledAppFlow
|
| 102 |
+
|
| 103 |
+
# Create flow from credentials
|
| 104 |
+
flow = InstalledAppFlow.from_client_secrets_file(
|
| 105 |
+
credentials_file,
|
| 106 |
+
SCOPES
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# Run local server for OAuth (will open browser)
|
| 110 |
+
creds = flow.run_local_server(
|
| 111 |
+
port=8080,
|
| 112 |
+
prompt='consent',
|
| 113 |
+
authorization_prompt_message='Please visit this URL to authorize: {url}',
|
| 114 |
+
success_message='Authorization complete! You can close this window.',
|
| 115 |
+
open_browser=True
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
# Save token for future use
|
| 119 |
+
with open(TOKEN_FILE, "wb") as f:
|
| 120 |
+
pickle.dump(creds, f)
|
| 121 |
+
|
| 122 |
+
print(f"✅ Token created and saved to {TOKEN_FILE}")
|
| 123 |
+
print("ℹ️ You can now delete credentials.json for security")
|
| 124 |
+
|
| 125 |
+
return creds
|
| 126 |
+
|
| 127 |
+
except ImportError:
|
| 128 |
+
raise Exception("""
|
| 129 |
+
❌ Missing required package!
|
| 130 |
+
|
| 131 |
+
Please install: pip install google-auth-oauthlib
|
| 132 |
+
|
| 133 |
+
This is needed to create token from credentials.json
|
| 134 |
+
""")
|
| 135 |
+
|
| 136 |
+
except Exception as e:
|
| 137 |
+
raise Exception(f"""
|
| 138 |
+
❌ Failed to create token from credentials.json: {e}
|
| 139 |
+
|
| 140 |
+
Common issues:
|
| 141 |
+
1. Invalid credentials.json format
|
| 142 |
+
2. Gmail API not enabled
|
| 143 |
+
3. OAuth consent screen not configured
|
| 144 |
+
4. Port 8080 already in use
|
| 145 |
+
|
| 146 |
+
Please check your Google Cloud Console settings.
|
| 147 |
+
""")
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def validate_gmail_setup():
|
| 151 |
+
"""Validate Gmail API setup and provide helpful error messages"""
|
| 152 |
+
|
| 153 |
+
try:
|
| 154 |
+
service = get_gmail_service()
|
| 155 |
+
|
| 156 |
+
# Test API access
|
| 157 |
+
profile = service.users().getProfile(userId="me").execute()
|
| 158 |
+
email = profile.get('emailAddress')
|
| 159 |
+
|
| 160 |
+
print(f"✅ Gmail API connected: {email}")
|
| 161 |
+
return True, email
|
| 162 |
+
|
| 163 |
+
except Exception as e:
|
| 164 |
+
error_msg = str(e)
|
| 165 |
+
|
| 166 |
+
if "credentials" in error_msg.lower():
|
| 167 |
+
return False, "❌ Missing credentials. Upload token.pkl or credentials.json"
|
| 168 |
+
elif "quota" in error_msg.lower():
|
| 169 |
+
return False, "❌ Gmail API quota exceeded. Try again later"
|
| 170 |
+
elif "permission" in error_msg.lower():
|
| 171 |
+
return False, "❌ Insufficient permissions. Re-authorize with full Gmail access"
|
| 172 |
+
else:
|
| 173 |
+
return False, f"❌ Gmail API error: {error_msg}"
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def send_email(to, subject, html):
|
| 177 |
+
|
| 178 |
+
try:
|
| 179 |
+
service = get_gmail_service()
|
| 180 |
+
|
| 181 |
+
msg = MIMEText(html, "html")
|
| 182 |
+
msg["To"] = to
|
| 183 |
+
msg["From"] = GMAIL_USER
|
| 184 |
+
msg["Subject"] = subject
|
| 185 |
+
|
| 186 |
+
raw = base64.urlsafe_b64encode(
|
| 187 |
+
msg.as_bytes()
|
| 188 |
+
).decode()
|
| 189 |
+
|
| 190 |
+
body = {"raw": raw}
|
| 191 |
+
|
| 192 |
+
service.users().messages().send(
|
| 193 |
+
userId="me",
|
| 194 |
+
body=body
|
| 195 |
+
).execute()
|
| 196 |
+
|
| 197 |
+
print("✅ Sent:", to)
|
| 198 |
+
return True
|
| 199 |
+
|
| 200 |
+
except Exception as e:
|
| 201 |
+
print("❌ Gmail error:", e)
|
| 202 |
+
return False
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def create_email_template(title, content, unsubscribe_link, email_type="reminder", problem_link=None, difficulty=None):
|
| 206 |
+
"""Create a beautiful HTML email template"""
|
| 207 |
+
|
| 208 |
+
# Color scheme based on email type
|
| 209 |
+
colors = {
|
| 210 |
+
"morning": {"primary": "#4CAF50", "secondary": "#81C784", "bg": "#E8F5E8"},
|
| 211 |
+
"afternoon": {"primary": "#FF9800", "secondary": "#FFB74D", "bg": "#FFF3E0"},
|
| 212 |
+
"night": {"primary": "#F44336", "secondary": "#EF5350", "bg": "#FFEBEE"},
|
| 213 |
+
"verification": {"primary": "#2196F3", "secondary": "#64B5F6", "bg": "#E3F2FD"}
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
color = colors.get(email_type, colors["morning"])
|
| 217 |
+
|
| 218 |
+
# Difficulty badge colors
|
| 219 |
+
difficulty_colors = {
|
| 220 |
+
"Easy": "#00B04F",
|
| 221 |
+
"Medium": "#FFA116",
|
| 222 |
+
"Hard": "#FF375F"
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
# Handle special cases for verification emails
|
| 226 |
+
if email_type == "verification":
|
| 227 |
+
problem_button = f"""
|
| 228 |
+
<div style="text-align: center; margin: 30px 0;">
|
| 229 |
+
<a href="{unsubscribe_link}"
|
| 230 |
+
style="display: inline-block; background: linear-gradient(135deg, {color['primary']}, {color['secondary']});
|
| 231 |
+
color: white; padding: 15px 30px; text-decoration: none; border-radius: 25px;
|
| 232 |
+
font-weight: bold; font-size: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.2);
|
| 233 |
+
transition: transform 0.2s;">
|
| 234 |
+
✅ Verify Email
|
| 235 |
+
</a>
|
| 236 |
+
</div>
|
| 237 |
+
"""
|
| 238 |
+
tips_section = ""
|
| 239 |
+
motivation_section = ""
|
| 240 |
+
difficulty_badge = ""
|
| 241 |
+
else:
|
| 242 |
+
# Use provided problem_link or construct from title
|
| 243 |
+
if problem_link:
|
| 244 |
+
link_url = problem_link
|
| 245 |
+
else:
|
| 246 |
+
link_url = f"https://leetcode.com/problems/{title.lower().replace(' ', '-').replace('.', '')}"
|
| 247 |
+
|
| 248 |
+
# Add difficulty badge
|
| 249 |
+
if difficulty:
|
| 250 |
+
diff_color = difficulty_colors.get(difficulty, "#666")
|
| 251 |
+
difficulty_badge = f"""
|
| 252 |
+
<div style="text-align: center; margin: 10px 0;">
|
| 253 |
+
<span style="background-color: {diff_color}; color: white; padding: 4px 12px;
|
| 254 |
+
border-radius: 12px; font-size: 12px; font-weight: bold;">
|
| 255 |
+
{difficulty}
|
| 256 |
+
</span>
|
| 257 |
+
</div>
|
| 258 |
+
"""
|
| 259 |
+
else:
|
| 260 |
+
difficulty_badge = ""
|
| 261 |
+
|
| 262 |
+
problem_button = f"""
|
| 263 |
+
<div style="text-align: center; margin: 30px 0;">
|
| 264 |
+
<a href="{link_url}"
|
| 265 |
+
style="display: inline-block; background: linear-gradient(135deg, {color['primary']}, {color['secondary']});
|
| 266 |
+
color: white; padding: 15px 30px; text-decoration: none; border-radius: 25px;
|
| 267 |
+
font-weight: bold; font-size: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.2);
|
| 268 |
+
transition: transform 0.2s;">
|
| 269 |
+
🚀 Solve Problem
|
| 270 |
+
</a>
|
| 271 |
+
</div>
|
| 272 |
+
"""
|
| 273 |
+
|
| 274 |
+
# Dynamic tips based on difficulty
|
| 275 |
+
if difficulty == "Easy":
|
| 276 |
+
tips_content = """
|
| 277 |
+
<li>Focus on understanding the problem clearly</li>
|
| 278 |
+
<li>Think about the simplest approach first</li>
|
| 279 |
+
<li>Test with the given examples</li>
|
| 280 |
+
<li>Consider edge cases like empty inputs</li>
|
| 281 |
+
"""
|
| 282 |
+
elif difficulty == "Medium":
|
| 283 |
+
tips_content = """
|
| 284 |
+
<li>Break the problem into smaller subproblems</li>
|
| 285 |
+
<li>Consider multiple approaches (greedy, DP, etc.)</li>
|
| 286 |
+
<li>Think about time and space complexity</li>
|
| 287 |
+
<li>Use appropriate data structures</li>
|
| 288 |
+
"""
|
| 289 |
+
else: # Hard
|
| 290 |
+
tips_content = """
|
| 291 |
+
<li>Study similar problems and patterns</li>
|
| 292 |
+
<li>Don't rush - take time to understand</li>
|
| 293 |
+
<li>Consider advanced algorithms and techniques</li>
|
| 294 |
+
<li>Break it down step by step</li>
|
| 295 |
+
"""
|
| 296 |
+
|
| 297 |
+
tips_section = f"""
|
| 298 |
+
<!-- Tips Section -->
|
| 299 |
+
<div style="background-color: #f8f9fa; padding: 20px; border-radius: 8px; margin: 25px 0;">
|
| 300 |
+
<h3 style="color: #333; margin: 0 0 15px 0; font-size: 18px;">💡 {difficulty} Problem Tips</h3>
|
| 301 |
+
<ul style="color: #666; margin: 0; padding-left: 20px; line-height: 1.6;">
|
| 302 |
+
{tips_content}
|
| 303 |
+
</ul>
|
| 304 |
+
</div>
|
| 305 |
+
"""
|
| 306 |
+
|
| 307 |
+
motivation_quotes = [
|
| 308 |
+
"The expert in anything was once a beginner.",
|
| 309 |
+
"Every problem is a step forward in your journey.",
|
| 310 |
+
"Consistency beats perfection every time.",
|
| 311 |
+
"Code today, conquer tomorrow.",
|
| 312 |
+
"Small progress is still progress."
|
| 313 |
+
]
|
| 314 |
+
import random
|
| 315 |
+
quote = random.choice(motivation_quotes)
|
| 316 |
+
|
| 317 |
+
motivation_section = f"""
|
| 318 |
+
<!-- Stats or Motivation -->
|
| 319 |
+
<div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 8px; margin: 25px 0;">
|
| 320 |
+
<p style="color: white; margin: 0; font-size: 16px; font-style: italic;">
|
| 321 |
+
"{quote}" 💪
|
| 322 |
+
</p>
|
| 323 |
+
</div>
|
| 324 |
+
"""
|
| 325 |
+
|
| 326 |
+
return f"""
|
| 327 |
+
<!DOCTYPE html>
|
| 328 |
+
<html>
|
| 329 |
+
<head>
|
| 330 |
+
<meta charset="UTF-8">
|
| 331 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 332 |
+
<title>LeetCode Daily Tracker</title>
|
| 333 |
+
</head>
|
| 334 |
+
<body style="margin: 0; padding: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f5f5f5;">
|
| 335 |
+
<div style="max-width: 600px; margin: 0 auto; background-color: white; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">
|
| 336 |
+
|
| 337 |
+
<!-- Header -->
|
| 338 |
+
<div style="background: linear-gradient(135deg, {color['primary']}, {color['secondary']}); padding: 30px; text-align: center;">
|
| 339 |
+
<h1 style="color: white; margin: 0; font-size: 28px; font-weight: 300;">
|
| 340 |
+
🧠 LeetCode Daily Tracker
|
| 341 |
+
</h1>
|
| 342 |
+
<p style="color: rgba(255,255,255,0.9); margin: 10px 0 0 0; font-size: 16px;">
|
| 343 |
+
Your coding journey companion
|
| 344 |
+
</p>
|
| 345 |
+
</div>
|
| 346 |
+
|
| 347 |
+
<!-- Content -->
|
| 348 |
+
<div style="padding: 40px 30px;">
|
| 349 |
+
<div style="background-color: {color['bg']}; border-left: 4px solid {color['primary']}; padding: 20px; margin-bottom: 25px; border-radius: 0 8px 8px 0;">
|
| 350 |
+
{content}
|
| 351 |
+
{difficulty_badge}
|
| 352 |
+
</div>
|
| 353 |
+
|
| 354 |
+
{problem_button}
|
| 355 |
+
|
| 356 |
+
{tips_section}
|
| 357 |
+
|
| 358 |
+
{motivation_section}
|
| 359 |
+
</div>
|
| 360 |
+
|
| 361 |
+
<!-- Footer -->
|
| 362 |
+
<div style="background-color: #f8f9fa; padding: 25px 30px; border-top: 1px solid #eee;">
|
| 363 |
+
<div style="text-align: center;">
|
| 364 |
+
<p style="color: #666; margin: 0 0 15px 0; font-size: 14px;">
|
| 365 |
+
Keep coding, keep growing! 🌱
|
| 366 |
+
</p>
|
| 367 |
+
<div style="margin: 15px 0;">
|
| 368 |
+
<a href="https://leetcode.com" style="color: {color['primary']}; text-decoration: none; margin: 0 10px;">📊 LeetCode</a>
|
| 369 |
+
<span style="color: #ccc;">|</span>
|
| 370 |
+
<a href="https://github.com" style="color: {color['primary']}; text-decoration: none; margin: 0 10px;">💻 GitHub</a>
|
| 371 |
+
<span style="color: #ccc;">|</span>
|
| 372 |
+
<a href="{unsubscribe_link if email_type != 'verification' else '#'}" style="color: #999; text-decoration: none; margin: 0 10px; font-size: 12px;">{'Unsubscribe' if email_type != 'verification' else ''}</a>
|
| 373 |
+
</div>
|
| 374 |
+
<p style="color: #999; font-size: 12px; margin: 15px 0 0 0;">
|
| 375 |
+
© 2024 LeetCode Daily Tracker. Made with ❤️ for coders.
|
| 376 |
+
</p>
|
| 377 |
+
</div>
|
| 378 |
+
</div>
|
| 379 |
+
</div>
|
| 380 |
+
</body>
|
| 381 |
+
</html>
|
| 382 |
+
"""
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
# ================= VALIDATION =================
|
| 386 |
+
|
| 387 |
+
EMAIL_REGEX = re.compile(
|
| 388 |
+
r"^[\w\.-]+@[\w\.-]+\.\w+$"
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def valid_email(email):
|
| 393 |
+
return bool(email and EMAIL_REGEX.match(email))
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def valid_leetcode(username):
|
| 397 |
+
|
| 398 |
+
if not username or len(username) < 3:
|
| 399 |
+
return False
|
| 400 |
+
|
| 401 |
+
try:
|
| 402 |
+
r = requests.get(
|
| 403 |
+
f"{LEETCODE_API}/{username}",
|
| 404 |
+
timeout=8
|
| 405 |
+
)
|
| 406 |
+
return r.status_code == 200
|
| 407 |
+
|
| 408 |
+
except:
|
| 409 |
+
return False
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
# ================= LEETCODE =================
|
| 413 |
+
|
| 414 |
+
def get_daily_problem():
|
| 415 |
+
try:
|
| 416 |
+
r = requests.get(f"{LEETCODE_API}/daily", timeout=10)
|
| 417 |
+
r.raise_for_status()
|
| 418 |
+
|
| 419 |
+
d = r.json()
|
| 420 |
+
print("📡 Daily API response keys:", list(d.keys()))
|
| 421 |
+
|
| 422 |
+
# Handle the current API format
|
| 423 |
+
if "questionTitle" in d and "titleSlug" in d:
|
| 424 |
+
title = d["questionTitle"]
|
| 425 |
+
slug = d["titleSlug"]
|
| 426 |
+
link = d.get("questionLink", f"https://leetcode.com/problems/{slug}/")
|
| 427 |
+
difficulty = d.get("difficulty", "Unknown")
|
| 428 |
+
print(f"✅ Found daily problem: {title} ({difficulty}) - {slug}")
|
| 429 |
+
return title, slug, link, difficulty
|
| 430 |
+
|
| 431 |
+
# Fallback for older format
|
| 432 |
+
if "title" in d and "titleSlug" in d:
|
| 433 |
+
title = d["title"]
|
| 434 |
+
slug = d["titleSlug"]
|
| 435 |
+
link = f"https://leetcode.com/problems/{slug}/"
|
| 436 |
+
difficulty = d.get("difficulty", "Unknown")
|
| 437 |
+
print(f"✅ Found daily problem (fallback): {title} ({difficulty}) - {slug}")
|
| 438 |
+
return title, slug, link, difficulty
|
| 439 |
+
|
| 440 |
+
# If we can't find the expected fields, print the response
|
| 441 |
+
print("❌ Available fields in API response:", list(d.keys()))
|
| 442 |
+
raise Exception("Could not find title and slug in daily API response")
|
| 443 |
+
|
| 444 |
+
except requests.exceptions.RequestException as e:
|
| 445 |
+
print(f"❌ Network error calling daily API: {e}")
|
| 446 |
+
raise Exception(f"Failed to fetch daily problem: {e}")
|
| 447 |
+
|
| 448 |
+
except json.JSONDecodeError as e:
|
| 449 |
+
print(f"❌ JSON decode error: {e}")
|
| 450 |
+
raise Exception("Invalid JSON response from daily API")
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def solved_today(username, slug):
|
| 454 |
+
|
| 455 |
+
try:
|
| 456 |
+
r = requests.get(
|
| 457 |
+
f"{LEETCODE_API}/{username}/acSubmission?limit=20",
|
| 458 |
+
timeout=10
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
if r.status_code != 200:
|
| 462 |
+
return False
|
| 463 |
+
|
| 464 |
+
d = r.json()
|
| 465 |
+
|
| 466 |
+
if "submission" in d:
|
| 467 |
+
subs = d["submission"]
|
| 468 |
+
elif "data" in d:
|
| 469 |
+
subs = d["data"]
|
| 470 |
+
elif isinstance(d, list):
|
| 471 |
+
subs = d
|
| 472 |
+
else:
|
| 473 |
+
return False
|
| 474 |
+
|
| 475 |
+
today = date.today()
|
| 476 |
+
|
| 477 |
+
for s in subs:
|
| 478 |
+
|
| 479 |
+
if not isinstance(s, dict):
|
| 480 |
+
continue
|
| 481 |
+
|
| 482 |
+
if s.get("titleSlug") != slug:
|
| 483 |
+
continue
|
| 484 |
+
|
| 485 |
+
ts = s.get("timestamp")
|
| 486 |
+
|
| 487 |
+
if not ts:
|
| 488 |
+
continue
|
| 489 |
+
|
| 490 |
+
solved = datetime.fromtimestamp(
|
| 491 |
+
int(ts),
|
| 492 |
+
tz=pytz.utc
|
| 493 |
+
).date()
|
| 494 |
+
|
| 495 |
+
if solved == today:
|
| 496 |
+
return True
|
| 497 |
+
|
| 498 |
+
return False
|
| 499 |
+
|
| 500 |
+
except:
|
| 501 |
+
return False
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
# ================= SUBSCRIBE =================
|
| 505 |
+
|
| 506 |
+
def subscribe(username, email, timezone):
|
| 507 |
+
|
| 508 |
+
if not valid_leetcode(username):
|
| 509 |
+
return "❌ Invalid LeetCode username"
|
| 510 |
+
|
| 511 |
+
if not valid_email(email):
|
| 512 |
+
return "❌ Invalid email"
|
| 513 |
+
|
| 514 |
+
conn = get_db()
|
| 515 |
+
cur = conn.cursor()
|
| 516 |
+
|
| 517 |
+
cur.execute("""
|
| 518 |
+
SELECT email_verified, verification_token, unsubscribed
|
| 519 |
+
FROM users WHERE email=%s
|
| 520 |
+
""", (email,))
|
| 521 |
+
|
| 522 |
+
row = cur.fetchone()
|
| 523 |
+
|
| 524 |
+
# Existing user logic...
|
| 525 |
+
if row:
|
| 526 |
+
verified, token, unsub = row
|
| 527 |
+
|
| 528 |
+
if verified and not unsub:
|
| 529 |
+
cur.close()
|
| 530 |
+
conn.close()
|
| 531 |
+
return "⚠️ Already subscribed"
|
| 532 |
+
|
| 533 |
+
if verified and unsub:
|
| 534 |
+
cur.execute("""
|
| 535 |
+
UPDATE users
|
| 536 |
+
SET unsubscribed=false,
|
| 537 |
+
leetcode_username=%s,
|
| 538 |
+
timezone=%s,
|
| 539 |
+
last_sent_date=NULL,
|
| 540 |
+
last_sent_slot=NULL
|
| 541 |
+
WHERE email=%s
|
| 542 |
+
""", (username, timezone, email))
|
| 543 |
+
|
| 544 |
+
conn.commit()
|
| 545 |
+
cur.close()
|
| 546 |
+
conn.close()
|
| 547 |
+
return "✅ Re-subscribed"
|
| 548 |
+
|
| 549 |
+
# Resend verification with enhanced template
|
| 550 |
+
verification_content = f"""
|
| 551 |
+
<h2 style="color: #2196F3; margin: 0 0 15px 0;">Welcome back! 👋</h2>
|
| 552 |
+
<p style="color: #333; font-size: 16px; line-height: 1.6; margin: 0 0 15px 0;">
|
| 553 |
+
We're excited to have you on your coding journey again!
|
| 554 |
+
</p>
|
| 555 |
+
<p style="color: #666; font-size: 14px; margin: 0;">
|
| 556 |
+
Click the verification button above to activate your daily LeetCode reminders.
|
| 557 |
+
</p>
|
| 558 |
+
"""
|
| 559 |
+
|
| 560 |
+
html_email = create_email_template(
|
| 561 |
+
"Email Verification",
|
| 562 |
+
verification_content,
|
| 563 |
+
f"{HF_URL}?verify={token}",
|
| 564 |
+
"verification"
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
send_email(email, "🔔 Please verify your email", html_email)
|
| 568 |
+
cur.close()
|
| 569 |
+
conn.close()
|
| 570 |
+
return "📩 Verification re-sent"
|
| 571 |
+
|
| 572 |
+
# New user - remove duplicate code
|
| 573 |
+
token = uuid.uuid4().hex
|
| 574 |
+
|
| 575 |
+
cur.execute("""
|
| 576 |
+
INSERT INTO users(
|
| 577 |
+
leetcode_username,email,timezone,
|
| 578 |
+
email_verified,verification_token,unsubscribed
|
| 579 |
+
)
|
| 580 |
+
VALUES(%s,%s,%s,false,%s,false)
|
| 581 |
+
""", (username, email, timezone, token))
|
| 582 |
+
|
| 583 |
+
conn.commit()
|
| 584 |
+
cur.close()
|
| 585 |
+
conn.close()
|
| 586 |
+
|
| 587 |
+
# Welcome email with enhanced template
|
| 588 |
+
welcome_content = f"""
|
| 589 |
+
<h2 style="color: #4CAF50; margin: 0 0 15px 0;">Welcome to the club! 🎉</h2>
|
| 590 |
+
<p style="color: #333; font-size: 16px; line-height: 1.6; margin: 0 0 15px 0;">
|
| 591 |
+
You're about to embark on an amazing coding journey with daily LeetCode challenges!
|
| 592 |
+
</p>
|
| 593 |
+
<div style="background-color: white; border: 2px dashed #4CAF50; padding: 15px; border-radius: 8px; margin: 15px 0;">
|
| 594 |
+
<p style="color: #4CAF50; font-weight: bold; margin: 0 0 5px 0;">📅 Your Schedule:</p>
|
| 595 |
+
<p style="color: #666; font-size: 14px; margin: 0;">
|
| 596 |
+
🌅 <strong>9 AM</strong> - Daily problem<br>
|
| 597 |
+
🌆 <strong>3 PM</strong> - Gentle reminder<br>
|
| 598 |
+
🌙 <strong>8 PM</strong> - Final reminder
|
| 599 |
+
</p>
|
| 600 |
+
</div>
|
| 601 |
+
<p style="color: #666; font-size: 14px; margin: 0;">
|
| 602 |
+
Click the verification button above to start receiving your personalized reminders!
|
| 603 |
+
</p>
|
| 604 |
+
"""
|
| 605 |
+
|
| 606 |
+
html_email = create_email_template(
|
| 607 |
+
"Welcome",
|
| 608 |
+
welcome_content,
|
| 609 |
+
f"{HF_URL}?verify={token}",
|
| 610 |
+
"verification"
|
| 611 |
+
)
|
| 612 |
+
|
| 613 |
+
send_email(email, "🎯 Verify your LeetCode journey!", html_email)
|
| 614 |
+
return "📩 Verification sent"
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
# ================= VERIFY =================
|
| 618 |
+
|
| 619 |
+
def verify_user(token):
|
| 620 |
+
|
| 621 |
+
conn = get_db()
|
| 622 |
+
cur = conn.cursor()
|
| 623 |
+
|
| 624 |
+
cur.execute("""
|
| 625 |
+
UPDATE users
|
| 626 |
+
SET email_verified=true
|
| 627 |
+
WHERE verification_token=%s
|
| 628 |
+
AND email_verified=false
|
| 629 |
+
""", (token,))
|
| 630 |
+
|
| 631 |
+
ok = cur.rowcount
|
| 632 |
+
|
| 633 |
+
conn.commit()
|
| 634 |
+
cur.close()
|
| 635 |
+
conn.close()
|
| 636 |
+
|
| 637 |
+
if ok == 0:
|
| 638 |
+
return "❌ Invalid link"
|
| 639 |
+
|
| 640 |
+
return "✅ Email verified"
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
# ================= UNSUBSCRIBE =================
|
| 644 |
+
|
| 645 |
+
def unsubscribe_user(token):
|
| 646 |
+
|
| 647 |
+
conn = get_db()
|
| 648 |
+
cur = conn.cursor()
|
| 649 |
+
|
| 650 |
+
cur.execute("""
|
| 651 |
+
UPDATE users
|
| 652 |
+
SET unsubscribed=true
|
| 653 |
+
WHERE verification_token=%s
|
| 654 |
+
""", (token,))
|
| 655 |
+
|
| 656 |
+
ok = cur.rowcount
|
| 657 |
+
|
| 658 |
+
conn.commit()
|
| 659 |
+
cur.close()
|
| 660 |
+
conn.close()
|
| 661 |
+
|
| 662 |
+
if ok == 0:
|
| 663 |
+
return "❌ Invalid link"
|
| 664 |
+
|
| 665 |
+
return "✅ Unsubscribed"
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
# ================= URL HANDLER =================
|
| 669 |
+
|
| 670 |
+
def handle_url(request: gr.Request):
|
| 671 |
+
|
| 672 |
+
try:
|
| 673 |
+
params = request.query_params
|
| 674 |
+
|
| 675 |
+
if "verify" in params:
|
| 676 |
+
return verify_user(params["verify"])
|
| 677 |
+
|
| 678 |
+
if "unsubscribe" in params:
|
| 679 |
+
return unsubscribe_user(params["unsubscribe"])
|
| 680 |
+
|
| 681 |
+
return ""
|
| 682 |
+
|
| 683 |
+
except Exception as e:
|
| 684 |
+
print("URL error:", e)
|
| 685 |
+
return ""
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
def run_scheduler(secret):
|
| 690 |
+
|
| 691 |
+
if secret != CRON_SECRET:
|
| 692 |
+
return "❌ Unauthorized"
|
| 693 |
+
|
| 694 |
+
conn = get_db()
|
| 695 |
+
cur = conn.cursor()
|
| 696 |
+
|
| 697 |
+
cur.execute("""
|
| 698 |
+
SELECT id,leetcode_username,email,timezone,
|
| 699 |
+
last_sent_date,last_sent_slot,verification_token
|
| 700 |
+
FROM users
|
| 701 |
+
WHERE email_verified=true
|
| 702 |
+
AND unsubscribed=false
|
| 703 |
+
""")
|
| 704 |
+
|
| 705 |
+
users = cur.fetchall()
|
| 706 |
+
|
| 707 |
+
try:
|
| 708 |
+
title, slug, problem_link, difficulty = get_daily_problem()
|
| 709 |
+
except Exception as e:
|
| 710 |
+
cur.close()
|
| 711 |
+
conn.close()
|
| 712 |
+
return f"❌ Failed to get daily problem: {e}"
|
| 713 |
+
|
| 714 |
+
now = datetime.now(pytz.utc)
|
| 715 |
+
sent = 0
|
| 716 |
+
|
| 717 |
+
for uid, user, mail, tz, last_d, last_s, token in users:
|
| 718 |
+
|
| 719 |
+
try:
|
| 720 |
+
local = now.astimezone(pytz.timezone(tz))
|
| 721 |
+
h = local.hour
|
| 722 |
+
|
| 723 |
+
# Enhanced email content based on time
|
| 724 |
+
if 8 <= h <= 9:
|
| 725 |
+
slot = "morning"
|
| 726 |
+
subject = f"🌅 Today's LeetCode Challenge: {title}"
|
| 727 |
+
content = f"""
|
| 728 |
+
<h2 style="color: #4CAF50; margin: 0 0 15px 0;">Good morning, coder! ☀️</h2>
|
| 729 |
+
<p style="color: #333; font-size: 18px; font-weight: bold; margin: 0 0 10px 0;">
|
| 730 |
+
Today's Problem: <span style="color: #4CAF50;">{title}</span>
|
| 731 |
+
</p>
|
| 732 |
+
<p style="color: #666; font-size: 16px; line-height: 1.6; margin: 0;">
|
| 733 |
+
Start your day with a fresh challenge! This {difficulty} problem is perfect for warming up
|
| 734 |
+
your coding muscles. Take your time to understand the requirements! 🚀
|
| 735 |
+
</p>
|
| 736 |
+
"""
|
| 737 |
+
email_type = "morning"
|
| 738 |
+
|
| 739 |
+
elif 14 <= h <= 15:
|
| 740 |
+
slot = "afternoon"
|
| 741 |
+
subject = f"⏰ Afternoon Coding Break: {title}"
|
| 742 |
+
content = f"""
|
| 743 |
+
<h2 style="color: #FF9800; margin: 0 0 15px 0;">Time for a coding break! ⚡</h2>
|
| 744 |
+
<p style="color: #333; font-size: 16px; margin: 0 0 15px 0;">
|
| 745 |
+
Haven't tackled <strong style="color: #FF9800;">{title}</strong> yet? No worries!
|
| 746 |
+
</p>
|
| 747 |
+
<p style="color: #666; font-size: 16px; line-height: 1.6; margin: 0;">
|
| 748 |
+
This {difficulty} problem is waiting for you. Sometimes a fresh afternoon perspective
|
| 749 |
+
can lead to breakthrough solutions! 💡
|
| 750 |
+
</p>
|
| 751 |
+
"""
|
| 752 |
+
email_type = "afternoon"
|
| 753 |
+
|
| 754 |
+
elif 19 <= h <= 20:
|
| 755 |
+
slot = "night"
|
| 756 |
+
subject = f"🌙 Last Call: {title}"
|
| 757 |
+
content = f"""
|
| 758 |
+
<h2 style="color: #F44336; margin: 0 0 15px 0;">Final reminder! 🔥</h2>
|
| 759 |
+
<p style="color: #333; font-size: 16px; margin: 0 0 15px 0;">
|
| 760 |
+
<strong style="color: #F44336;">{title}</strong> ({difficulty}) is still waiting for you!
|
| 761 |
+
</p>
|
| 762 |
+
<p style="color: #666; font-size: 16px; line-height: 1.6; margin: 0 0 15px 0;">
|
| 763 |
+
Don't let the day end without giving it a try. Even reading through the problem
|
| 764 |
+
and thinking about approaches counts as progress!
|
| 765 |
+
</p>
|
| 766 |
+
<div style="background-color: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 8px;">
|
| 767 |
+
<p style="color: #856404; margin: 0; font-size: 14px;">
|
| 768 |
+
💪 <strong>Remember:</strong> Consistency beats perfection. Every attempt makes you stronger!
|
| 769 |
+
</p>
|
| 770 |
+
</div>
|
| 771 |
+
"""
|
| 772 |
+
email_type = "night"
|
| 773 |
+
|
| 774 |
+
else:
|
| 775 |
+
continue
|
| 776 |
+
|
| 777 |
+
today = date.today()
|
| 778 |
+
|
| 779 |
+
# Check if already sent today
|
| 780 |
+
if last_d == today and last_s == slot:
|
| 781 |
+
print(f"⏭️ Skipping {mail} - already sent {slot} email today")
|
| 782 |
+
continue
|
| 783 |
+
|
| 784 |
+
# Check if user already solved the problem
|
| 785 |
+
if solved_today(user, slug):
|
| 786 |
+
print(f"✅ {user} already solved {slug} - skipping email")
|
| 787 |
+
continue
|
| 788 |
+
|
| 789 |
+
# Create beautiful HTML email with all enhancements
|
| 790 |
+
html_email = create_email_template(
|
| 791 |
+
title,
|
| 792 |
+
content,
|
| 793 |
+
f"{HF_URL}?unsubscribe={token}",
|
| 794 |
+
email_type,
|
| 795 |
+
problem_link,
|
| 796 |
+
difficulty
|
| 797 |
+
)
|
| 798 |
+
|
| 799 |
+
ok = send_email(mail, subject, html_email)
|
| 800 |
+
|
| 801 |
+
if not ok:
|
| 802 |
+
print(f"❌ Failed to send email to {mail}")
|
| 803 |
+
continue
|
| 804 |
+
|
| 805 |
+
# Update database
|
| 806 |
+
cur.execute("""
|
| 807 |
+
UPDATE users
|
| 808 |
+
SET last_sent_date=%s,
|
| 809 |
+
last_sent_slot=%s
|
| 810 |
+
WHERE id=%s
|
| 811 |
+
""", (today, slot, uid))
|
| 812 |
+
|
| 813 |
+
sent += 1
|
| 814 |
+
|
| 815 |
+
except Exception as e:
|
| 816 |
+
print(f"❌ Error processing user {user} ({mail}): {e}")
|
| 817 |
+
continue
|
| 818 |
+
|
| 819 |
+
conn.commit()
|
| 820 |
+
cur.close()
|
| 821 |
+
conn.close()
|
| 822 |
+
|
| 823 |
+
return f"✅ Scheduler completed. Sent: {sent} emails"
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
# ================= UI =================
|
| 828 |
+
with gr.Blocks(
|
| 829 |
+
title="LeetCode Notifier",
|
| 830 |
+
theme=gr.themes.Soft(),
|
| 831 |
+
css="""
|
| 832 |
+
.gradio-container {
|
| 833 |
+
max-width: 800px !important;
|
| 834 |
+
margin: auto !important;
|
| 835 |
+
}
|
| 836 |
+
"""
|
| 837 |
+
) as app:
|
| 838 |
+
|
| 839 |
+
gr.Markdown("""
|
| 840 |
+
# 📬 LeetCode Daily Email Notifier
|
| 841 |
+
|
| 842 |
+
Get personalized daily LeetCode problem reminders sent directly to your inbox!
|
| 843 |
+
Never miss a day of coding practice.
|
| 844 |
+
""")
|
| 845 |
+
|
| 846 |
+
with gr.Row():
|
| 847 |
+
with gr.Column():
|
| 848 |
+
u = gr.Textbox(
|
| 849 |
+
label="🧑💻 LeetCode Username",
|
| 850 |
+
placeholder="Enter your LeetCode username",
|
| 851 |
+
info="We'll verify this username exists on LeetCode"
|
| 852 |
+
)
|
| 853 |
+
m = gr.Textbox(
|
| 854 |
+
label="📧 Email Address",
|
| 855 |
+
placeholder="your.email@gmail.com",
|
| 856 |
+
info="You'll receive a verification email"
|
| 857 |
+
)
|
| 858 |
+
tz = gr.Dropdown(
|
| 859 |
+
choices=sorted(pytz.all_timezones),
|
| 860 |
+
value="Asia/Kolkata",
|
| 861 |
+
label="🌍 Timezone",
|
| 862 |
+
info="Choose your timezone for proper scheduling"
|
| 863 |
+
)
|
| 864 |
+
|
| 865 |
+
with gr.Row():
|
| 866 |
+
subscribe_btn = gr.Button("🚀 Subscribe", variant="primary", scale=2)
|
| 867 |
+
|
| 868 |
+
out = gr.Textbox(label="📝 Status", interactive=False, lines=2)
|
| 869 |
+
|
| 870 |
+
subscribe_btn.click(subscribe, [u, m, tz], out)
|
| 871 |
+
|
| 872 |
+
gr.Markdown("""
|
| 873 |
+
---
|
| 874 |
+
### ⏰ Email Schedule
|
| 875 |
+
- **🌅 9:00 AM** - Daily problem notification
|
| 876 |
+
- **🌆 3:00 PM** - Gentle reminder (if not solved)
|
| 877 |
+
- **🌙 8:00 PM** - Final reminder (if not solved)
|
| 878 |
+
|
| 879 |
+
### 🔒 Admin Panel
|
| 880 |
+
""")
|
| 881 |
+
|
| 882 |
+
with gr.Row():
|
| 883 |
+
sec = gr.Textbox(
|
| 884 |
+
label="🔑 Secret Key",
|
| 885 |
+
type="password",
|
| 886 |
+
placeholder="Enter scheduler secret key"
|
| 887 |
+
)
|
| 888 |
+
run_btn = gr.Button("▶️ Run Scheduler", variant="secondary")
|
| 889 |
+
|
| 890 |
+
run_btn.click(run_scheduler, sec, out)
|
| 891 |
+
|
| 892 |
+
# URL handler for verification/unsubscribe
|
| 893 |
+
app.load(handle_url, outputs=out)
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
if __name__ == "__main__":
|
| 897 |
+
app.launch(debug=True)
|