CooldownCalculator.kt 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package io.r_a_d.radio2.ui.songs.request
  2. import kotlin.math.exp
  3. import kotlin.math.max
  4. /*
  5. //PHP cooldown calculator
  6. function pretty_cooldown($lp, $lr, $rc) {
  7. $delay = delay($rc);
  8. $now = time();
  9. $cd = intval(max($lp + $delay - $now, $lr + $delay - $now));
  10. if ($cd <= 0)
  11. return "Request";
  12. $days = intdiv_1($cd, 86400);
  13. $cd = $cd % 86400;
  14. $hours = intdiv_1($cd, 3600);
  15. $cd = $cd % 3600;
  16. $minutes = intdiv_1($cd, 60);
  17. $seconds = $cd % 60;
  18. if ($days > 0)
  19. return "Requestable in ".$days."d".$hours."h";
  20. else if ($hours > 0)
  21. return "Requestable in ".$hours."h".$minutes."m";
  22. else if ($minutes > 0)
  23. return "Requestable in ".$minutes."m".$seconds."s";
  24. return "Request";
  25. }
  26. function requestable($lastplayed, $requests) {
  27. $delay = delay($requests);
  28. return (time() - $lastplayed) > $delay;
  29. }
  30. function delay($priority) {
  31. // priority is 30 max
  32. if ($priority > 30)
  33. $priority = 30;
  34. // between 0 and 7 return magic
  35. if ($priority >= 0 and $priority <= 7)
  36. $cd = -11057 * $priority * $priority + 172954 * $priority + 81720;
  37. // if above that, return magic crazy numbers
  38. else
  39. $cd = (int) (599955 * exp(0.0372 * $priority) + 0.5);
  40. return $cd / 2;
  41. }
  42. */
  43. // this function implements the magic delay used on R/a/dio website:
  44. // https://github.com/R-a-dio/site/blob/develop/app/start/global.php#L125
  45. // (Seriously guys, what were you thinking with these crazy magic numbers...)
  46. fun delay(rawPriority: Int) : Int {
  47. val priority = if (rawPriority > 30) 30 else rawPriority
  48. val coolDown : Int =
  49. if (priority in 0..7)
  50. -11057 * priority * priority + 172954 * priority + 81720
  51. else
  52. (599955 * exp(0.0372 * (priority.toDouble()) + 0.5)).toInt()
  53. return coolDown/2
  54. }
  55. // I tweaked this to report in a single point whether the song is requestable or not
  56. fun coolDown(lastPlayed: Int?, lastRequest: Int?, requestsNbr: Int?) : Long {
  57. if (requestsNbr == null || lastPlayed == null || lastRequest == null)
  58. return Long.MAX_VALUE // maximum positive value : the song won't be requestable
  59. val delay = delay(requestsNbr)
  60. val now = (System.currentTimeMillis() / 1000)
  61. return max(lastPlayed, lastRequest) + delay - now
  62. // if coolDown < 0, the song is requestable.
  63. }