-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
4031 lines (3452 loc) · 143 KB
/
Copy pathapp.py
File metadata and controls
4031 lines (3452 loc) · 143 KB
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import json
import logging
import os
import random
import re
import sqlite3
from datetime import datetime
from typing import Optional, Dict, List, Any
import aiohttp
from aiohttp import web
import aiohttp_cors
from aiofiles import open as aio_open
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo import errors as pymongo_errors
from bson import ObjectId
log_formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - [%(name)s] - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
file_handler = logging.FileHandler('astrisk_app.log', encoding='utf-8')
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(log_formatter)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(log_formatter)
logging.basicConfig(
level=logging.INFO,
handlers=[file_handler, console_handler]
)
logger = logging.getLogger(__name__)
http_logger = logging.getLogger('astrisk.http')
http_formatter = logging.Formatter(
'%(asctime)s - HTTP - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
http_file_handler = logging.FileHandler('astrisk_http.log', encoding='utf-8')
http_file_handler.setLevel(logging.INFO)
http_file_handler.setFormatter(http_formatter)
http_logger.addHandler(http_file_handler)
http_logger.addHandler(console_handler)
http_logger.setLevel(logging.INFO)
http_logger.propagate = False
logger.info("=" * 80)
logger.info("ASTRISK Tournament System - Starting Up")
logger.info("=" * 80)
MONGO_URI = os.environ.get(
"MONGODB_URL", ""
)
DB_NAME = "astrisk_tournament"
mongo_client = AsyncIOMotorClient(MONGO_URI)
db = mongo_client[DB_NAME]
registrations = db.registrations
matches_collection = db.matches
SQLITE_DB = "registrations_backup.db"
MASTER_PASSWORD = "0022"
RATE_LIMIT_STORAGE = {}
sse_clients: List[asyncio.Queue] = []
def serialize_datetime(obj: Any) -> Any:
if isinstance(obj, datetime):
return obj.isoformat()
elif isinstance(obj, dict):
return {key: serialize_datetime(value) for key, value in obj.items()}
elif isinstance(obj, list):
return [serialize_datetime(item) for item in obj]
elif isinstance(obj, tuple):
return tuple(serialize_datetime(item) for item in obj)
else:
return obj
def init_sqlite():
conn = sqlite3.connect(SQLITE_DB)
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS registrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
registration_id TEXT UNIQUE NOT NULL,
team_name TEXT UNIQUE NOT NULL,
college_name TEXT,
lead_name TEXT NOT NULL,
lead_email TEXT NOT NULL,
lead_contact TEXT NOT NULL,
members TEXT NOT NULL,
substitute TEXT,
ip_address TEXT,
timestamp TEXT NOT NULL,
payment_status TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
"""
)
cursor.execute(
"""
CREATE INDEX IF NOT EXISTS idx_team_name ON registrations(team_name)
"""
)
cursor.execute(
"""
CREATE INDEX IF NOT EXISTS idx_payment_status ON registrations(payment_status)
"""
)
cursor.execute(
"""
CREATE INDEX IF NOT EXISTS idx_registration_id ON registrations(registration_id)
"""
)
conn.commit()
conn.close()
logger.info("SQLite backup database initialized")
def save_to_sqlite(registration_data: Dict) -> bool:
try:
conn = sqlite3.connect(SQLITE_DB)
cursor = conn.cursor()
members_json = json.dumps(registration_data["members"])
substitute_json = json.dumps(registration_data.get("substitute", {}))
cursor.execute(
"""
INSERT INTO registrations
(registration_id, team_name, college_name, lead_name, lead_email, lead_contact,
members, substitute, ip_address, timestamp, payment_status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
registration_data["registration_id"],
registration_data["team_name"],
registration_data.get("college_name", ""),
registration_data["lead"]["name"],
registration_data["lead"]["email"],
registration_data["lead"]["contact"],
members_json,
substitute_json,
registration_data.get("ip_address", ""),
(
registration_data["timestamp"].isoformat()
if isinstance(registration_data["timestamp"], datetime)
else str(registration_data["timestamp"])
),
registration_data["payment_status"],
),
)
conn.commit()
conn.close()
logger.info(
f"Registration backed up to SQLite: {registration_data['team_name']}"
)
return True
except sqlite3.IntegrityError as e:
logger.warning(f"SQLite backup failed (duplicate): {str(e)}")
return False
except Exception as e:
logger.error(f"SQLite backup error: {str(e)}")
return False
def update_payment_sqlite(team_name: str, new_status: str) -> bool:
try:
conn = sqlite3.connect(SQLITE_DB)
cursor = conn.cursor()
cursor.execute(
"""
UPDATE registrations
SET payment_status = ?
WHERE team_name = ?
""",
(new_status, team_name),
)
conn.commit()
rows_affected = cursor.rowcount
conn.close()
if rows_affected > 0:
logger.info(f"SQLite backup updated: {team_name} -> {new_status}")
return True
return False
except Exception as e:
logger.error(f"SQLite update error: {str(e)}")
return False
def validate_email(email: str) -> bool:
"""Validate email format"""
pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
return re.match(pattern, email) is not None
def validate_phone(phone: str) -> bool:
"""Validate Indian phone number"""
pattern = r"^[6-9]\d{9}$"
return re.match(pattern, phone) is not None
def validate_team_name(team_name: str) -> bool:
"""Validate team name"""
if len(team_name) < 3 or len(team_name) > 50:
return False
pattern = r"^[a-zA-Z0-9\s\-_\.]+$"
return re.match(pattern, team_name) is not None
async def send_whatsapp(to_number: str, content: str) -> bool:
"""Send a WhatsApp message via a local service"""
try:
if not to_number:
logger.warning("send_whatsapp called without phone number")
return False
payload = {"phnnumber": to_number, "content": content}
async with aiohttp.ClientSession() as session:
async with session.post(
"http://127.0.0.1:4005/send-message",
json=payload,
timeout=aiohttp.ClientTimeout(total=5)
) as resp:
if resp.status == 200:
logger.info(f"WhatsApp message sent to {to_number}")
return True
else:
logger.warning(f"WhatsApp service returned {resp.status}: {await resp.text()}")
return False
except Exception as e:
logger.error(f"Failed to send WhatsApp message to {to_number}: {e}")
return False
def build_whatsapp_message(event: str, **kwargs) -> str:
"""Build human-friendly WhatsApp messages for different events"""
def wrap_message(body_text):
header = "*ASTERISK | ACM AJCE*\n\n"
footer = "\n\nRegards ~ ACM AJCE"
return header + body_text + footer
try:
if event == "registration_success":
body = (
"✅ *Registration — Confirmation*\n\n"
f"*Team:* {kwargs.get('team_name')}\n"
f"*Registration ID:* {kwargs.get('registration_id','N/A')}\n"
f"*Team Auth Code:* {kwargs.get('auth_code')}\n"
f"*Amount Due:* ₹{kwargs.get('amount', 600)}\n\n"
"Dear Team Lead,\n\n"
"Your team has been successfully registered for ASTRISK 2025."
" Please retain the Team Auth Code securely; it is required to manage your team and respond to join requests via the dashboard.\n\n"
"Access your team dashboard here: https://astrisk.vercel.app/team.html\n\n"
"If you have any questions, reply to this message or contact the event organisers."
)
return wrap_message(body)
if event == "open_team_created":
body = (
"🔓 *Open Team — Notification*\n\n"
f"*Team:* {kwargs.get('team_name')}\n"
f"*Team Auth Code:* {kwargs.get('auth_code')}\n\n"
"Your team is now marked as *open* and may receive join requests from other participants."
" Please review incoming requests promptly and accept only those you trust.\n\n"
"Manage requests via: https://astrisk.vercel.app/team.html"
)
return wrap_message(body)
if event == "join_request_received":
body = (
"📨 *Join Request Received*\n\n"
f"*Team:* {kwargs.get('team_name')}\n\n"
"Requester details:\n"
f"• Name: {kwargs.get('name')}\n"
f"• Email: {kwargs.get('email')}\n"
f"• Phone: {kwargs.get('contact')}\n"
f"• Riot ID: {kwargs.get('riot_id')}\n\n"
"Please review this request in your team dashboard and respond at your earliest convenience."
)
return wrap_message(body)
if event == "join_request_accepted":
body = (
"🎉 *Join Request — Accepted*\n\n"
f"Dear {kwargs.get('name')},\n\n"
f"Your request to join *{kwargs.get('team_name')}* has been accepted."
" You have been added to the team roster.\n\n"
"Please check the team dashboard for further details and follow any onboarding instructions provided by the team lead."
)
return wrap_message(body)
if event == "join_request_declined":
body = (
"ℹ️ *Join Request — Declined*\n\n"
f"Dear {kwargs.get('name')},\n\n"
f"We regret to inform you that your request to join *{kwargs.get('team_name')}* has been declined by the team lead.\n\n"
"You may explore other open teams or contact the team lead for clarification."
)
return wrap_message(body)
if event == "payment_completed":
body = (
"✅ *Payment Received — Confirmation*\n\n"
f"*Team:* {kwargs.get('team_name')}\n"
f"*Registration ID:* {kwargs.get('registration_id','N/A')}\n"
f"*Amount Paid:* ₹{kwargs.get('amount',600)}\n\n"
"Thank you. We confirm receipt of your payment and your team is now fully registered for ASTRISK 2025."
" A confirmation will be reflected on your team dashboard shortly.\n\n"
"We look forward to your participation."
)
return wrap_message(body)
generic = kwargs.get('content', '')
if generic:
return wrap_message(generic)
return ''
except Exception as e:
logger.error(f"Error building whatsapp message for {event}: {e}")
return kwargs.get('content', '')
async def check_duplicate_emails(emails: List[str]) -> tuple:
"""Check if any email is already registered"""
for email in emails:
doc = await registrations.find_one(
{
"$or": [{"members.email": email}, {"substitute.email": email}],
"payment_status": "completed",
}
)
if doc:
return True, email
return False, None
def get_client_ip(request: web.Request) -> str:
"""Get client IP address from request"""
x_forwarded_for = request.headers.get('X-Forwarded-For')
if x_forwarded_for:
return x_forwarded_for.split(',')[0].strip()
return request.remote or '127.0.0.1'
# ============================================================================
# SSE (Server-Sent Events) for Real-time Updates
# ============================================================================
async def broadcast_sse_event(event_type: str, data: Dict):
"""Broadcast an event to all connected SSE clients"""
event_data = json.dumps({"type": event_type, "data": data})
dead_clients = []
for i, client_queue in enumerate(sse_clients):
try:
await client_queue.put(event_data)
except:
dead_clients.append(i)
# Remove dead clients
for i in reversed(dead_clients):
sse_clients.pop(i)
logger.info(f"Broadcasted SSE event '{event_type}' to {len(sse_clients)} clients")
# ============================================================================
# UTILITY FUNCTIONS FOR TOURNAMENT LOGIC
# ============================================================================
async def calculate_best_loser() -> Optional[Dict[str, Any]]:
"""
Calculate the best loser from Round of 18 matches.
Returns the losing team with the highest score.
"""
try:
# Get all completed Round of 18 matches
matches = await matches_collection.find({
"round": "Round of 18",
"status": "completed"
}).to_list(None)
if not matches:
return None
best_loser = None
highest_score = -1
for match in matches:
# Determine the loser and their score
winner = match.get("winner")
team1 = match.get("team1")
team2 = match.get("team2")
team1_score = match.get("team1_score", 0)
team2_score = match.get("team2_score", 0)
if not winner:
continue
# Find the losing team and their score
if winner == team1:
loser = team2
loser_score = team2_score
loser_seed = match.get("team2_seed")
else:
loser = team1
loser_score = team1_score
loser_seed = match.get("team1_seed")
# Update best loser if this loser has a higher score
if loser_score > highest_score:
highest_score = loser_score
best_loser = {
"team": loser,
"score": loser_score,
"seed": loser_seed,
"match_id": str(match.get("_id")),
"match_number": match.get("match_number")
}
return best_loser
except Exception as e:
logger.error(f"Error calculating best loser: {e}")
return None
async def get_tournament_advancement_status() -> Dict[str, Any]:
"""
Get current tournament advancement status:
- Winners from Round of 18
- Best loser
- Teams advancing to quarterfinals
"""
try:
# Get all Round of 18 matches
matches = await matches_collection.find({
"round": "Round of 18"
}).to_list(None)
winners = []
completed_count = 0
for match in matches:
if match.get("status") == "completed" and match.get("winner"):
winners.append({
"team": match.get("winner"),
"match_number": match.get("match_number"),
"seed": match.get("team1_seed") if match.get("winner") == match.get("team1") else match.get("team2_seed")
})
completed_count += 1
# Calculate best loser
best_loser = await calculate_best_loser()
# Determine teams advancing
advancing_teams = winners.copy()
if best_loser and completed_count == 9: # All matches completed
advancing_teams.append({
"team": best_loser["team"],
"match_number": best_loser["match_number"],
"seed": best_loser["seed"],
"is_best_loser": True
})
return {
"total_matches": len(matches),
"completed_matches": completed_count,
"winners": winners,
"best_loser": best_loser,
"advancing_teams": advancing_teams,
"ready_for_quarterfinals": completed_count == 9 and len(advancing_teams) == 10
}
except Exception as e:
logger.error(f"Error getting advancement status: {e}")
return {
"error": str(e),
"total_matches": 0,
"completed_matches": 0,
"winners": [],
"best_loser": None,
"advancing_teams": [],
"ready_for_quarterfinals": False
}
async def sse_handler(request: web.Request) -> web.StreamResponse:
"""Server-Sent Events endpoint for real-time match updates"""
response = web.StreamResponse()
response.headers['Content-Type'] = 'text/event-stream'
response.headers['Cache-Control'] = 'no-cache'
response.headers['Connection'] = 'keep-alive'
response.headers['X-Accel-Buffering'] = 'no' # Disable nginx buffering
await response.prepare(request)
# Create a queue for this client
client_queue = asyncio.Queue()
sse_clients.append(client_queue)
logger.info(f"New SSE client connected. Total clients: {len(sse_clients)}")
try:
# Send initial connection confirmation
await response.write(b'data: {"type":"connected","message":"SSE connection established"}\n\n')
# Keep sending events from the queue
while True:
event_data = await client_queue.get()
await response.write(f'data: {event_data}\n\n'.encode('utf-8'))
except asyncio.CancelledError:
pass
except Exception as e:
logger.error(f"SSE error: {e}")
finally:
if client_queue in sse_clients:
sse_clients.remove(client_queue)
logger.info(f"SSE client disconnected. Remaining clients: {len(sse_clients)}")
return response
# ============================================================================
# MATCH MANAGEMENT ENDPOINTS
# ============================================================================
async def get_matches(request: web.Request) -> web.Response:
"""Get all matches"""
try:
matches = []
async for match in matches_collection.find().sort("round", 1).sort("match_number", 1):
match['_id'] = str(match['_id'])
matches.append(match)
# Serialize datetime objects
matches = serialize_datetime(matches)
return web.json_response({
"success": True,
"matches": matches
})
except Exception as e:
logger.error(f"Get matches error: {e}")
return web.json_response({
"success": False,
"message": "Error fetching matches"
}, status=500)
async def create_match(request: web.Request) -> web.Response:
"""Create a new match (admin only)"""
try:
# Check authentication
auth_header = request.headers.get("X-Auth-Token", "")
if auth_header != MASTER_PASSWORD:
return web.json_response({
"success": False,
"message": "Unauthorized"
}, status=401)
data = await request.json()
match_data = {
"round": data.get("round"), # "Round of 16", "Quarterfinals", etc.
"match_number": data.get("match_number"),
"team1": data.get("team1"),
"team2": data.get("team2"),
"team1_seed": data.get("team1_seed"),
"team2_seed": data.get("team2_seed"),
"winner": data.get("winner"), # null until match is completed
"status": data.get("status", "upcoming"), # "upcoming", "live", "completed"
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow()
}
result = await matches_collection.insert_one(match_data)
match_data['_id'] = str(result.inserted_id)
match_data = serialize_datetime(match_data)
await broadcast_sse_event("match_created", match_data)
return web.json_response({
"success": True,
"message": "Match created",
"match": match_data
})
except Exception as e:
logger.error(f"Create match error: {e}")
return web.json_response({
"success": False,
"message": "Error creating match"
}, status=500)
async def update_match(request: web.Request) -> web.Response:
"""Update a match (admin only)"""
try:
# Check authentication
auth_header = request.headers.get("X-Auth-Token", "")
if auth_header != MASTER_PASSWORD:
return web.json_response({
"success": False,
"message": "Unauthorized"
}, status=401)
match_id_str = request.match_info['match_id']
data = await request.json()
# Convert string ID to ObjectId
try:
match_id = ObjectId(match_id_str)
except Exception:
return web.json_response({
"success": False,
"message": "Invalid match ID format"
}, status=400)
update_data = {
"updated_at": datetime.utcnow()
}
# Only update provided fields
for field in ["round", "match_number", "team1", "team2", "team1_seed", "team2_seed", "winner", "status"]:
if field in data:
update_data[field] = data[field]
result = await matches_collection.update_one(
{"_id": match_id},
{"$set": update_data}
)
if result.matched_count == 0:
return web.json_response({
"success": False,
"message": "Match not found"
}, status=404)
updated_match = await matches_collection.find_one({"_id": match_id})
if updated_match is None:
return web.json_response({
"success": False,
"message": "Match not found after update"
}, status=404)
updated_match['_id'] = str(updated_match['_id'])
updated_match = serialize_datetime(updated_match)
await broadcast_sse_event("match_updated", updated_match)
return web.json_response({
"success": True,
"message": "Match updated",
"match": updated_match
})
except Exception as e:
logger.error(f"Update match error: {e}")
return web.json_response({
"success": False,
"message": "Error updating match"
}, status=500)
async def delete_match(request: web.Request) -> web.Response:
"""Delete a match (admin only)"""
try:
# Check authentication
auth_header = request.headers.get("X-Auth-Token", "")
if auth_header != MASTER_PASSWORD:
return web.json_response({
"success": False,
"message": "Unauthorized"
}, status=401)
match_id_str = request.match_info['match_id']
# Convert string ID to ObjectId
try:
match_id = ObjectId(match_id_str)
except Exception:
return web.json_response({
"success": False,
"message": "Invalid match ID format"
}, status=400)
result = await matches_collection.delete_one({"_id": match_id})
if result.deleted_count == 0:
return web.json_response({
"success": False,
"message": "Match not found"
}, status=404)
# Broadcast to SSE clients
await broadcast_sse_event("match_deleted", {"match_id": match_id_str})
return web.json_response({
"success": True,
"message": "Match deleted"
})
except Exception as e:
logger.error(f"Delete match error: {e}")
return web.json_response({
"success": False,
"message": "Error deleting match"
}, status=500)
# ============================================================================
# TOURNAMENT CONTROL PANEL ENDPOINTS
# ============================================================================
async def initialize_tournament_bracket(request: web.Request) -> web.Response:
"""Initialize the tournament bracket with baseline data from matchlineup.html"""
try:
# Check authentication
auth_header = request.headers.get("X-Auth-Token", "")
if auth_header != MASTER_PASSWORD:
return web.json_response({
"success": False,
"message": "Unauthorized"
}, status=401)
# Clear existing matches
await matches_collection.delete_many({})
# Baseline data - Round of 16 (9 matches)
baseline_matches = [
{
"round": "Round of 16",
"round_number": 1,
"match_number": 1,
"team1": "Go Lose Fast",
"team2": "Gods Own Country",
"team1_seed": 1,
"team2_seed": 16,
"winner": None,
"team1_score": 0,
"team2_score": 0,
"status": "pending",
"is_active": False,
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow()
},
{
"round": "Round of 16",
"round_number": 1,
"match_number": 2,
"team1": "EXODUS",
"team2": "Domain 5",
"team1_seed": 8,
"team2_seed": 9,
"winner": None,
"team1_score": 0,
"team2_score": 0,
"status": "pending",
"is_active": False,
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow()
},
{
"round": "Round of 16",
"round_number": 1,
"match_number": 3,
"team1": "Targaryens",
"team2": "Hestia",
"team1_seed": 4,
"team2_seed": 13,
"winner": None,
"team1_score": 0,
"team2_score": 0,
"status": "pending",
"is_active": False,
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow()
},
{
"round": "Round of 16",
"round_number": 1,
"match_number": 4,
"team1": "Renegades",
"team2": "Spike Rushers",
"team1_seed": 5,
"team2_seed": 12,
"winner": None,
"team1_score": 0,
"team2_score": 0,
"status": "pending",
"is_active": False,
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow()
},
{
"round": "Round of 16",
"round_number": 1,
"match_number": 5,
"team1": "BLACKLISTED",
"team2": "Log Bait",
"team1_seed": 2,
"team2_seed": 15,
"winner": None,
"team1_score": 0,
"team2_score": 0,
"status": "pending",
"is_active": False,
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow()
},
{
"round": "Round of 16",
"round_number": 1,
"match_number": 6,
"team1": "BINARY LEGION",
"team2": "Vitality",
"team1_seed": 7,
"team2_seed": 10,
"winner": None,
"team1_score": 0,
"team2_score": 0,
"status": "pending",
"is_active": False,
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow()
},
{
"round": "Round of 16",
"round_number": 1,
"match_number": 7,
"team1": "Hardstuck",
"team2": "XLr8",
"team1_seed": 3,
"team2_seed": 14,
"winner": None,
"team1_score": 0,
"team2_score": 0,
"status": "pending",
"is_active": False,
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow()
},
{
"round": "Round of 16",
"round_number": 1,
"match_number": 8,
"team1": "LavaLoon",
"team2": "ULTF4",
"team1_seed": 6,
"team2_seed": 11,
"winner": None,
"team1_score": 0,
"team2_score": 0,
"status": "pending",
"is_active": False,
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow()
},
{
"round": "Round of 16",
"round_number": 1,
"match_number": 9,
"team1": "LABWUBWU",
"team2": "Esports Division NITC Alpha",
"team1_seed": "TBD",
"team2_seed": "TBD",
"winner": None,
"team1_score": 0,
"team2_score": 0,
"status": "pending",
"is_active": False,
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow()
}
]
# Insert baseline matches
result = await matches_collection.insert_many(baseline_matches)
logger.info(f"Tournament bracket initialized with {len(result.inserted_ids)} matches")
# Broadcast to SSE clients
await broadcast_sse_event("bracket_initialized", {
"matches_count": len(result.inserted_ids)
})
return web.json_response({
"success": True,
"message": "Tournament bracket initialized",
"matches_created": len(result.inserted_ids)
})
except Exception as e:
logger.error(f"Initialize bracket error: {e}")
return web.json_response({
"success": False,
"message": f"Error initializing bracket: {str(e)}"
}, status=500)
async def set_active_match(request: web.Request) -> web.Response:
"""Set a specific match as active (admin only)"""
try:
# Check authentication
auth_header = request.headers.get("X-Auth-Token", "")
if auth_header != MASTER_PASSWORD:
return web.json_response({
"success": False,
"message": "Unauthorized"
}, status=401)
data = await request.json()
match_id_str = data.get("match_id")
if not match_id_str:
return web.json_response({
"success": False,
"message": "Match ID required"
}, status=400)
# Convert string ID to ObjectId
try:
match_id = ObjectId(match_id_str)
except Exception:
return web.json_response({
"success": False,
"message": "Invalid match ID format"
}, status=400)
# Deactivate all other matches
await matches_collection.update_many(
{},
{"$set": {"is_active": False}}
)
# Activate the specified match and set to live
result = await matches_collection.update_one(
{"_id": match_id},
{
"$set": {
"is_active": True,
"status": "live",
"updated_at": datetime.utcnow()
}
}
)
if result.matched_count == 0:
return web.json_response({
"success": False,
"message": "Match not found"
}, status=404)
active_match = await matches_collection.find_one({"_id": match_id})
if active_match is None:
return web.json_response({
"success": False,
"message": "Match not found after activation"
}, status=404)
active_match['_id'] = str(active_match['_id'])
active_match = serialize_datetime(active_match)
await broadcast_sse_event("active_match_changed", active_match)
logger.info(f"Match {match_id_str} set as active")
return web.json_response({
"success": True,
"message": "Match activated",
"match": active_match
})
except Exception as e:
logger.error(f"Set active match error: {e}")
return web.json_response({
"success": False,
"message": f"Error setting active match: {str(e)}"
}, status=500)
async def advance_winners(request: web.Request) -> web.Response:
"""Advance winners from one round to the next (admin only)"""
try:
# Check authentication
auth_header = request.headers.get("X-Auth-Token", "")
if auth_header != MASTER_PASSWORD:
return web.json_response({