5 use Illuminate\Database\Eloquent\Factories\HasFactory;
6 use Illuminate\Database\Eloquent\Model;
8 class Channel extends Model
12 public function getCurrentEpisode() {
13 return $this->episodes()
14 ->where('start', '<', now()->subMinutes(10))
15 ->orderBy('start', 'DESC')
19 public function hasActiveGuessing() {
20 return !is_null($this->guessing_start);
23 public function isAcceptingGuesses() {
24 return !is_null($this->guessing_start) && is_null($this->guessing_end);
27 public function startGuessing($type) {
28 $this->guessing_type = $type;
29 $this->guessing_start = now();
33 public function stopGuessing() {
34 $this->guessing_end = now();
38 public function solveGuessing($solution) {
39 $start = $this->guessing_start;
40 $end = is_null($this->guessing_end) ? now() : $this->guessing_end;
41 $guesses = $this->guesses()->whereBetween('created_at', [$start, $end])->orderBy('created_at', 'ASC')->get();
43 foreach ($guesses as $guess) {
44 $unique_guesses[$guess->uid] = $guess;
47 foreach ($unique_guesses as $guess) {
48 if ($guess->guess == $solution) {
49 $candidates[] = $guess;
52 if (empty($candidates) && is_numeric($solution)) {
54 foreach ($unique_guesses as $guess) {
55 $distance = abs(intval($guess->guess) - intval($solution));
56 if (is_null($min_distance) || $distance == $min_distance) {
57 $candidates[] = $guess;
58 } else if ($distance < $min_distance) {
59 $candidates = [$guess];
60 $min_distance = $distance;
66 foreach ($candidates as $candidate) {
67 $score = $this->scoreGuessing($solution, $candidate->guess, $first);
68 $winner = new GuessingWinner();
69 $winner->channel()->associate($this);
70 $winner->pod = $start;
71 $winner->uid = $candidate->uid;
72 $winner->uname = $candidate->uname;
73 $winner->guess = $candidate->guess;
74 $winner->solution = $solution;
75 $winner->score = $score;
83 public function clearGuessing() {
84 $this->guessing_start = null;
85 $this->guessing_end = null;
89 public function registerGuess($uid, $uname, $guess) {
90 $model = new GuessingGuess();
91 $model->channel()->associate($this);
93 $model->uname = $uname;
94 $model->guess = $guess;
98 public function scoreGuessing($solution, $guess, $first) {
102 public function isValidGuess($solution) {
103 if ($this->guessing_type == 'gtbk') {
104 $int_solution = intval($solution);
105 return $int_solution > 0 && $int_solution < 23;
110 public function crews() {
111 return $this->hasMany(ChannelCrew::class);
114 public function episodes() {
115 return $this->belongsToMany(Episode::class)
116 ->using(Restream::class)
117 ->withPivot('accept_comms', 'accept_tracker');
120 public function guesses() {
121 return $this->hasMany(GuessingGuess::class);
124 public function organization() {
125 return $this->belongsTo(Organization::class);
130 'chat_commands' => 'array',
131 'chat_settings' => 'array',
132 'guessing_start' => 'datetime',
133 'guessing_end' => 'datetime',
134 'languages' => 'array',
138 protected $hidden = [