Spaces:
Running
Running
File size: 21,568 Bytes
d208f3c 4f81de9 d208f3c 4f81de9 d208f3c 4f81de9 d208f3c 9326bf5 d208f3c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 | import os
import uuid
import json
import pickle
import base64
import threading
import time
import schedule
import psycopg2
import requests
import gradio as gr
from dotenv import load_dotenv
from email.mime.text import MIMEText
from datetime import datetime
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
# ================= ENV =================
load_dotenv()
DB_URL = os.getenv("DB_URL")
GMAIL_USER = os.getenv("GMAIL_USER")
HF_URL = os.getenv("HF_URL")
ADMIN_SECRET = os.getenv("ADMIN_SECRET")
XSRF_TOKEN = os.getenv("XSRF_TOKEN")
BIP_SESSION = os.getenv("BIP_SESSION")
BIP_API = "https://bip.bitsathy.ac.in/nova-api/student-activity-masters"
TOKEN_FILE = "token.pkl"
# COOKIE_FILE = "bip_cookies.json"
STATE_FILE = "state.json"
NEW_EVENTS_FILE = "new_events.json"
PAGE1_LOG_FILE = "page1_logs.json"
SCOPES = ["https://www.googleapis.com/auth/gmail.send"]
MAX_PAGES = 50
REQUEST_TIMEOUT = 20
# ================= DB =================
def get_db():
try:
return psycopg2.connect(DB_URL, sslmode="require")
except Exception as e:
print(f"β DB Connection error: {e}")
raise
# ================= COOKIES =================
# ================= COOKIES =================
def load_cookies():
"""Load cookies from environment variables only"""
if not XSRF_TOKEN or not BIP_SESSION:
raise Exception("XSRF_TOKEN and BIP_SESSION must be set in environment variables")
# Clean the values - remove any cookie header prefixes
xsrf_value = XSRF_TOKEN.strip()
session_value = BIP_SESSION.strip()
# Remove "XSRF-TOKEN=" prefix if present
if xsrf_value.startswith("XSRF-TOKEN="):
xsrf_value = xsrf_value[12:] # Remove "XSRF-TOKEN="
# Remove "bip_session=" prefix if present
if session_value.startswith("bip_session="):
session_value = session_value[12:] # Remove "bip_session="
# Remove any trailing cookie parts (like "; other_cookie=...")
if ";" in xsrf_value:
xsrf_value = xsrf_value.split(";")[0]
if ";" in session_value:
session_value = session_value.split(";")[0]
return {
"XSRF-TOKEN": xsrf_value,
"bip_session": session_value
}
# ================= GMAIL =================
def create_token():
if not os.path.exists("credentials.json"):
raise Exception("credentials.json missing")
flow = InstalledAppFlow.from_client_secrets_file(
"credentials.json",
SCOPES
)
creds = flow.run_local_server(port=0)
with open(TOKEN_FILE, "wb") as f:
pickle.dump(creds, f)
return creds
def get_gmail():
creds = None
if os.path.exists(TOKEN_FILE):
with open(TOKEN_FILE, "rb") as f:
creds = pickle.load(f)
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
with open(TOKEN_FILE, "wb") as f:
pickle.dump(creds, f)
if not creds:
creds = create_token()
return build("gmail", "v1", credentials=creds)
def send_email(to, subject, html):
try:
service = get_gmail()
msg = MIMEText(html, "html")
msg["To"] = to
msg["From"] = GMAIL_USER
msg["Subject"] = subject
raw = base64.urlsafe_b64encode(msg.as_bytes()).decode()
service.users().messages().send(
userId="me",
body={"raw": raw}
).execute()
print("β
Sent:", to)
return True
except Exception as e:
print("β Mail error:", e)
return False
# ================= EMAIL =================
def create_event_email(event, unsub):
return f"""
<h2>π’ New BIP Event</h2>
<b>{event['event_name']}</b>
<ul>
<li>Code: {event['event_code']}</li>
<li>Organizer: {event['organizer']}</li>
<li>Date: {event['start_date']}</li>
<li>Location: {event['location']}</li>
</ul>
<a href="{event['web_url']}">View</a>
<hr>
<a href="{unsub}">Unsubscribe</a>
"""
# ================= BIP API =================
HEADERS = {
"accept": "application/json",
"x-requested-with": "XMLHttpRequest",
}
BASE_PARAMS = {
"perPage": 10
}
def fetch_page(page):
"""Fetch a specific page from BIP API"""
cookies = load_cookies()
params = BASE_PARAMS.copy()
params["page"] = page
r = requests.get(
BIP_API,
params=params,
headers=HEADERS,
cookies=cookies,
timeout=REQUEST_TIMEOUT
)
# Expired session
if "text/html" in r.headers.get("Content-Type", ""):
raise Exception("Session expired. Login again.")
r.raise_for_status()
return r.json()
def fetch_latest():
"""Legacy function - now uses fetch_page"""
return fetch_page(1)["resources"]
def parse_event(resource):
"""Parse event resource into clean data structure"""
data = {}
for f in resource.get("fields", []):
key = f.get("attribute")
val = f.get("value")
if key:
data[key] = val
data["id"] = resource["id"]["value"]
data["title"] = resource.get("title")
return data
def fetch_new_events(old_id):
"""Fetch all new events since the last known ID"""
page = 1
new_events = []
while page <= MAX_PAGES:
print(f"π Fetching page {page}...")
try:
data = fetch_page(page)
resources = data.get("resources", [])
except Exception as e:
print(f"β Error fetching page {page}: {e}")
break
if not resources:
break
for res in resources:
ev = parse_event(res)
if ev["id"] == old_id:
return new_events
new_events.append(ev)
page += 1
return new_events
# ================= STATE MANAGEMENT =================
def load_state():
"""Load the last processed event state"""
try:
with open(STATE_FILE, "r") as f:
return json.load(f)
except:
return None
def save_state(latest_id):
"""Save the latest processed event ID"""
state = {
"latest_id": latest_id,
"last_updated": datetime.now().isoformat()
}
with open(STATE_FILE, "w") as f:
json.dump(state, f, indent=2)
def save_new_events(events):
"""Save new events to file"""
data = {
"timestamp": datetime.now().isoformat(),
"count": len(events),
"events": events
}
with open(NEW_EVENTS_FILE, "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# ================= PAGE 1 LOGGER =================
def load_page1_logs():
"""Load page 1 historical logs"""
try:
with open(PAGE1_LOG_FILE, "r") as f:
return json.load(f)
except:
return []
def save_page1_logs(logs):
"""Save page 1 logs to file"""
with open(PAGE1_LOG_FILE, "w") as f:
json.dump(logs, f, indent=2, ensure_ascii=False)
def log_page1_to_file():
"""Save page 1 snapshot to file"""
try:
data = fetch_page(1)
resources = data.get("resources", [])
events = []
for res in resources:
events.append(parse_event(res))
logs = load_page1_logs()
entry = {
"timestamp": datetime.now().isoformat(),
"count": len(events),
"events": events
}
logs.append(entry)
# Keep only last 100 entries to prevent file from growing too large
if len(logs) > 100:
logs = logs[-100:]
save_page1_logs(logs)
print(f"π Page-1 snapshot saved ({len(events)} events)")
return True
except Exception as e:
print(f"β Failed to log page 1: {e}")
return False
# ================= SUBSCRIBE =================
def subscribe(email):
if not email or not email.endswith("@bitsathy.ac.in"):
return "β Use college email only"
try:
db = get_db()
cur = db.cursor()
# Check if user already exists and is verified
cur.execute("""
SELECT email_verified, unsubscribed
FROM users
WHERE email=%s
""", (email,))
existing_user = cur.fetchone()
if existing_user:
verified, unsubscribed = existing_user
if verified and not unsubscribed:
cur.close()
db.close()
return "β
You're already subscribed to BIP alerts"
elif verified and unsubscribed:
# Re-subscribe previously unsubscribed user
cur.execute("""
UPDATE users
SET unsubscribed=false
WHERE email=%s
""", (email,))
db.commit()
cur.close()
db.close()
return "β
Successfully re-subscribed to BIP alerts"
elif not verified:
# User exists but not verified - generate new token and resend
token = uuid.uuid4().hex
cur.execute("""
UPDATE users
SET verification_token=%s
WHERE email=%s
""", (token, email))
db.commit()
link = f"{HF_URL}?verify={token}"
if send_email(
email,
"Verify BIP Alerts",
f"Click <a href='{link}'>here</a> to verify"
):
result = "π© New verification email sent (previous one expired)"
else:
result = "β Failed to send verification email"
cur.close()
db.close()
return result
# New user - create account and send verification
token = uuid.uuid4().hex
cur.execute("""
INSERT INTO users(email, verification_token)
VALUES(%s, %s)
""", (email, token))
db.commit()
link = f"{HF_URL}?verify={token}"
if send_email(
email,
"Verify BIP Alerts",
f"Click <a href='{link}'>here</a> to verify"
):
result = "π© Verification sent to your email"
else:
result = "β Failed to send verification email"
cur.close()
db.close()
return result
except Exception as e:
print(f"β Subscribe error: {e}")
return f"β Error: {str(e)}"
# ================= VERIFY =================
def verify_user(token):
if not token:
return ""
try:
db = get_db()
cur = db.cursor()
cur.execute("""
UPDATE users
SET email_verified=true,
verification_token=NULL,
unsubscribed=false
WHERE verification_token=%s
""", (token,))
if cur.rowcount > 0:
result = "β
Email verified successfully!"
else:
result = "β Invalid verification token"
db.commit()
cur.close()
db.close()
return result
except Exception as e:
print(f"β Verify error: {e}")
return f"β Verification failed: {str(e)}"
# ================= UNSUBSCRIBE =================
def unsubscribe_user(token):
if not token:
return ""
try:
db = get_db()
cur = db.cursor()
cur.execute("""
UPDATE users
SET unsubscribed=true
WHERE verification_token=%s OR email IN (
SELECT email FROM users WHERE verification_token=%s
)
""", (token, token))
if cur.rowcount > 0:
result = "β
Successfully unsubscribed from BIP alerts"
else:
result = "β Invalid unsubscribe link"
db.commit()
cur.close()
db.close()
return result
except Exception as e:
print(f"β Unsubscribe error: {e}")
return f"β Unsubscribe failed: {str(e)}"
# ================= EMAIL STATUS =================
def check_email_status(email):
if not email or not email.endswith("@bitsathy.ac.in"):
return "β Please enter a valid college email"
try:
db = get_db()
cur = db.cursor()
cur.execute("""
SELECT email_verified, unsubscribed, verification_token
FROM users
WHERE email=%s
""", (email,))
result = cur.fetchone()
cur.close()
db.close()
if not result:
return "π§ Email not found. Click Subscribe to register."
verified, unsubscribed, token = result
if unsubscribed:
return "π« Email is unsubscribed from alerts"
elif verified:
return "β
Email is verified and subscribed to alerts"
else:
return "β³ Email registered but not verified. Check your inbox."
except Exception as e:
print(f"β Status check error: {e}")
return f"β Database error: {str(e)}"
# ================= ENHANCED NOTIFIER =================
def check_events():
"""Enhanced event checker with state tracking"""
print("\nπ Checking for new events...")
try:
# Save page 1 snapshot
log_page1_to_file()
state = load_state()
# First run
if not state:
print("π First run detected")
data = fetch_page(1)
resources = data.get("resources", [])
if not resources:
print("β οΈ No events found")
return "β οΈ No events found on first run"
first_event = parse_event(resources[0])
save_state(first_event["id"])
print("π Saved initial ID:", first_event["id"])
return f"π Initialized with event ID: {first_event['id']}"
old_id = state["latest_id"]
print("π Last known ID:", old_id)
new_events = fetch_new_events(old_id)
if not new_events:
print("β³ No new events added")
return "β³ No new events found"
latest = new_events[0]
print(f"\nπ₯ {len(new_events)} NEW EVENT(S) ADDED!")
print("π’ Latest Event:", latest.get("event_name", "Unknown"))
# Save new events to file
save_new_events(new_events)
# Update state
save_state(latest["id"])
# Send notifications to users
return send_notifications_for_events(new_events)
except Exception as e:
error_msg = f"β Event check error: {e}"
print(error_msg)
return error_msg
def send_notifications_for_events(new_events):
"""Send one combined email for all new events"""
if not new_events:
return "π No events to notify"
try:
db = get_db()
cur = db.cursor()
cur.execute("""
SELECT id,email,verification_token
FROM users
WHERE email_verified=true
AND unsubscribed=false
""")
users = cur.fetchall()
if not users:
cur.close()
db.close()
return "π No verified users"
# Build combined HTML
events_html = ""
for i, event in enumerate(new_events, 1):
events_html += f"""
<hr>
<h3>{i}. {event['event_name']}</h3>
<ul>
<li><b>Code:</b> {event['event_code']}</li>
<li><b>Event Name:</b> {event['event_name']}</li>
<li><b>Organizer:</b> {event['organizer']}</li>
<li><b>Date:</b> {event['start_date']}</li>
<li><b>Category:</b> {event['event_category']}</li>
<li><b>Location:</b> {event['location']}</li>
<li><b>View:</b> <a href="{event['web_url']}">Link</a></li>
</ul>
"""
subject = f"π’ {len(new_events)} New BIP Events Added"
total_sent = 0
for uid, mail, token in users:
html = f"""
<h2>π’ New BIP Events Alert</h2>
<p>{len(new_events)} new events have been added:</p>
{events_html}
<hr>
<a href="{HF_URL}?unsubscribe={token}">Unsubscribe</a>
"""
if send_email(mail, subject, html):
total_sent += 1
cur.close()
db.close()
return f"β
Sent {total_sent} combined notifications"
except Exception as e:
print("β Notification error:", e)
return f"β Error: {e}"
def run_notifier():
"""Legacy function - now uses enhanced check_events"""
return check_events()
# ================= SCHEDULER =================
def scheduler_worker():
print("β° Scheduler started")
# Initial run
try:
result = check_events()
print(f"Initial check: {result}")
except Exception as e:
print(f"β Initial check failed: {e}")
# Schedule every 3 minutes
schedule.every(3).minutes.do(check_events)
while True:
try:
schedule.run_pending()
except Exception as e:
print(f"β Scheduler error: {e}")
time.sleep(30)
# ================= ROUTER =================
def route_handler(req: gr.Request):
try:
params = req.query_params
if "verify" in params:
return verify_user(params["verify"])
if "unsubscribe" in params:
return unsubscribe_user(params["unsubscribe"])
return ""
except Exception as e:
print(f"β Router error: {e}")
return f"β Error: {str(e)}"
# ================= UI =================
with gr.Blocks(title="BIP Notifier", theme=gr.themes.Soft()) as app:
gr.Markdown("# π’ BIP Event Email Alerts")
gr.Markdown("*Auto-checking every 3 minutes for new events*")
# ---------- Main Section ----------
with gr.Row():
with gr.Column():
email = gr.Textbox(
label="College Email (@bitsathy.ac.in)",
placeholder="your.name@bitsathy.ac.in"
)
with gr.Row():
sub_btn = gr.Button("Subscribe", variant="primary")
status_btn = gr.Button("Check Status", variant="secondary")
out = gr.Textbox(label="Status", interactive=False, lines=3)
sub_btn.click(subscribe, email, out)
status_btn.click(check_email_status, email, out)
# ---------- System Status ----------
with gr.Accordion("π System Status", open=False):
def get_system_status():
try:
state = load_state()
page1_logs = load_page1_logs()
status = "### Current State:\n"
if state:
status += f"- **Last Event ID**: {state.get('latest_id', 'N/A')}\n"
status += f"- **Last Updated**: {state.get('last_updated', 'N/A')}\n"
else:
status += "- **Status**: Not initialized\n"
status += f"- **Page 1 Logs**: {len(page1_logs)} entries\n"
if os.path.exists(NEW_EVENTS_FILE):
with open(NEW_EVENTS_FILE, 'r') as f:
new_events = json.load(f)
status += f"- **Last New Events**: {new_events.get('count', 0)} events\n"
else:
status += "- **Last New Events**: None\n"
return status
except Exception as e:
return f"β Error loading status: {e}"
status_btn = gr.Button("Get System Status")
status_out = gr.Textbox(label="System Status", lines=5, interactive=False)
status_btn.click(get_system_status, None, status_out)
# ---------- Instructions ----------
with gr.Accordion("π Instructions", open=False):
gr.Markdown("""
### How to use:
1. Enter your college email (@bitsathy.ac.in)
2. Click **Subscribe**
3. Check your email and click the verification link
4. You'll receive alerts for new BIP events automatically
### Admin Setup:
1. Login to BIP portal in browser
2. Open Developer Tools (F12) β Network tab
3. Make any request and copy XSRF-TOKEN and bip_session cookies
4. Paste them in Admin Controls above
### Files Created:
- `state.json`: Tracks last processed event
- `page1_logs.json`: Historical snapshots of page 1
- `new_events.json`: Latest batch of new events found
""")
# ---------- URL Handler ----------
app.load(route_handler, None, out)
# ================= MAIN =================
if __name__ == "__main__":
print("π BIP Event Notifier (Enhanced with File Tracking)")
print("=" * 50)
# Start scheduler in background
scheduler_thread = threading.Thread(
target=scheduler_worker,
daemon=True
)
scheduler_thread.start()
# Start Gradio app
app.launch(
share=False # Set
) |