ckratelimit.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. function ckratelimit($headers) {
  3. $aaheaders=[];
  4. array_shift($headers);
  5. foreach ($headers as $header)
  6. if (preg_match('#^([^:]+): (.*)$#',$header,$matches)===1)
  7. $aaheaders[strtolower($matches[1])]=$matches[2];
  8. //$aaheaders['x-ratelimit-remaining']=0;
  9. //print_r($aaheaders);
  10. if (!isset($aaheaders['date'])) return ['ok'=>false,'error'=>'no «date» header'];
  11. if (!isset($aaheaders['x-ratelimit-reset'])) return ['ok'=>false,'error'=>'no «x-ratelimit-reset» header'];
  12. if (!isset($aaheaders['x-ratelimit-remaining'])) return ['ok'=>false,'error'=>'no «x-ratelimit-remaining» header'];
  13. if (preg_match('#^\d+$#',$aaheaders['x-ratelimit-remaining'])!==1) return ['ok'=>false,'error'=>'«x-ratelimit-remaining» header is not an integer'];
  14. $remaining=$aaheaders['x-ratelimit-remaining']+0;
  15. $date=@strtotime($aaheaders['date']);
  16. if (!is_int($date)) return ['ok'=>false,'error'=>'«date» header could not be converted to a unix timestamp'];
  17. $reset=@strtotime($aaheaders['x-ratelimit-reset']);
  18. if (!is_int($reset)) return ['ok'=>false,'error'=>'«x-ratelimit-reset» header could not be converted to a unix timestamp'];
  19. // don't do the one on the line below, since it happens lots of times
  20. //if ($reset<$date) return ['ok'=>false,'error'=>'the unix timestamp parsed from «x-ratelimit-reset» header is less than the unix timestamp parsed from «date» header'];
  21. return ['ok'=>true,'sleep'=>$reset-$date+1,'remaining'=>$remaining];
  22. }
  23. /*
  24. // test
  25. $context=[
  26. 'http'=>[
  27. 'header'=>"Accept: application/json\r\n";
  28. ]
  29. ];
  30. $context=stream_context_create($context);
  31. while (true) {
  32. $res=@file_get_contents('https://livellosegreto.it/api/v2/instance',false,$context);
  33. echo "{$res}\n";
  34. print_r($http_response_header);
  35. $rl=ckratelimit($http_response_header);
  36. print_r($rl);
  37. if ($rl['sleep']>0) {
  38. echo 'Reached rate limit, sleeping for '.ght($rl['sleep']).' (until '.date('c',time()+$rl['sleep']).') ...';
  39. sleep($rl['sleep']);
  40. echo "\n";
  41. }
  42. }
  43. exit(0);*/
  44. ?>