Chrunos commited on
Commit
25ad852
·
verified ·
1 Parent(s): b8bcfff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -0
app.py CHANGED
@@ -452,8 +452,89 @@ async def logout():
452
  clear_instagram_session()
453
  return RedirectResponse(url="/status", status_code=303)
454
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
455
  @app.get("/stories/{username}")
456
  async def get_stories(username: str, cached: bool = False):
 
 
 
 
 
 
 
 
 
 
 
457
  logger.info(f"Request for @{username} stories")
458
 
459
  if cached:
 
452
  clear_instagram_session()
453
  return RedirectResponse(url="/status", status_code=303)
454
 
455
+
456
+
457
+
458
+ class RateLimiter:
459
+ def __init__(self, max_requests: int, time_window: timedelta):
460
+ self.max_requests = max_requests
461
+ self.time_window = time_window
462
+ self.requests: Dict[str, list] = defaultdict(list)
463
+
464
+ def _cleanup_old_requests(self, user_ip: str) -> None:
465
+ """Remove requests that are outside the time window."""
466
+ current_time = time.time()
467
+ self.requests[user_ip] = [
468
+ timestamp for timestamp in self.requests[user_ip]
469
+ if current_time - timestamp < self.time_window.total_seconds()
470
+ ]
471
+
472
+ def is_rate_limited(self, user_ip: str) -> bool:
473
+ """Check if the user has exceeded their rate limit."""
474
+ self._cleanup_old_requests(user_ip)
475
+
476
+ # Get current count after cleanup
477
+ current_count = len(self.requests[user_ip])
478
+
479
+ # Add current request timestamp (incrementing the count)
480
+ current_time = time.time()
481
+ self.requests[user_ip].append(current_time)
482
+
483
+ # Check if user has exceeded the maximum requests
484
+ return (current_count + 1) > self.max_requests
485
+
486
+ def get_current_count(self, user_ip: str) -> int:
487
+ """Get the current request count for an IP."""
488
+ self._cleanup_old_requests(user_ip)
489
+ return len(self.requests[user_ip])
490
+
491
+
492
+ # Initialize rate limiter with 100 requests per day
493
+ rate_limiter = RateLimiter(
494
+ max_requests=6,
495
+ time_window=timedelta(days=1)
496
+ )
497
+
498
+ def get_user_ip(request: Request) -> str:
499
+ """Helper function to get user's IP address."""
500
+ forwarded = request.headers.get("X-Forwarded-For")
501
+ if forwarded:
502
+ return forwarded.split(",")[0]
503
+ return request.client.host
504
+
505
+
506
+ class ApiRotator:
507
+ def __init__(self, apis):
508
+ self.apis = apis
509
+ self.last_successful_index = None
510
+
511
+ def get_prioritized_apis(self):
512
+ if self.last_successful_index is not None:
513
+ # Move the last successful API to the front
514
+ rotated_apis = (
515
+ [self.apis[self.last_successful_index]] +
516
+ self.apis[:self.last_successful_index] +
517
+ self.apis[self.last_successful_index+1:]
518
+ )
519
+ return rotated_apis
520
+ return self.apis
521
+
522
+ def update_last_successful(self, index):
523
+ self.last_successful_index = index
524
+
525
  @app.get("/stories/{username}")
526
  async def get_stories(username: str, cached: bool = False):
527
+ user_ip = get_user_ip(request)
528
+
529
+ if rate_limiter.is_rate_limited(user_ip):
530
+ current_count = rate_limiter.get_current_count(user_ip)
531
+ raise HTTPException(
532
+ status_code=429,
533
+ detail={
534
+ "error": "You have exceeded the maximum number of requests per day. Please try again tomorrow.",
535
+ "url": "https://t.me/chrunoss"
536
+ }
537
+ )
538
  logger.info(f"Request for @{username} stories")
539
 
540
  if cached: