Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -674,18 +674,64 @@ def send_notifications_for_events(new_events):
|
|
| 674 |
|
| 675 |
total_sent = 0
|
| 676 |
|
| 677 |
-
|
|
|
|
|
|
|
| 678 |
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 686 |
|
| 687 |
-
|
| 688 |
-
|
|
|
|
| 689 |
|
| 690 |
cur.close()
|
| 691 |
db.close()
|
|
|
|
| 674 |
|
| 675 |
total_sent = 0
|
| 676 |
|
| 677 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 678 |
+
import threading
|
| 679 |
+
import time
|
| 680 |
|
| 681 |
+
send_lock = threading.Lock()
|
| 682 |
+
last_sent_time = 0
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
def rate_limited_send(mail, subject, html):
|
| 686 |
+
global last_sent_time
|
| 687 |
+
|
| 688 |
+
with send_lock:
|
| 689 |
+
now = time.time()
|
| 690 |
+
|
| 691 |
+
# 馃敟 STRICT: 1 mail per second globally
|
| 692 |
+
if now - last_sent_time < 1:
|
| 693 |
+
time.sleep(1 - (now - last_sent_time))
|
| 694 |
+
|
| 695 |
+
last_sent_time = time.time()
|
| 696 |
+
|
| 697 |
+
return send_email(mail, subject, html)
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
# ================= REPLACE LOOP =================
|
| 701 |
+
|
| 702 |
+
max_workers = 5
|
| 703 |
+
batch_size = 20
|
| 704 |
+
total_sent = 0
|
| 705 |
+
|
| 706 |
+
for i in range(0, len(users), batch_size):
|
| 707 |
+
batch = users[i:i + batch_size]
|
| 708 |
+
|
| 709 |
+
print(f"馃摝 Sending batch {i//batch_size + 1} ({len(batch)} users)")
|
| 710 |
+
|
| 711 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
| 712 |
+
futures = []
|
| 713 |
+
|
| 714 |
+
for uid, mail, unsubscribe_token in batch:
|
| 715 |
+
|
| 716 |
+
html = f"""
|
| 717 |
+
<h2>馃摙 New BIP Events Alert</h2>
|
| 718 |
+
<p>{len(new_events)} new events have been added:</p>
|
| 719 |
+
{events_html}
|
| 720 |
+
<hr>
|
| 721 |
+
<a href="{HF_URL}?unsubscribe={unsubscribe_token}">Unsubscribe</a>
|
| 722 |
+
"""
|
| 723 |
+
|
| 724 |
+
futures.append(
|
| 725 |
+
executor.submit(rate_limited_send, mail, subject, html)
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
for future in as_completed(futures):
|
| 729 |
+
if future.result():
|
| 730 |
+
total_sent += 1
|
| 731 |
|
| 732 |
+
# 馃敟 COOL DOWN between batches
|
| 733 |
+
print("鈴革笍 Cooling down 3 sec...")
|
| 734 |
+
time.sleep(3)
|
| 735 |
|
| 736 |
cur.close()
|
| 737 |
db.close()
|