]> git.localhorst.tv Git - alttp.git/blob - app/Console/Commands/SyncSpeedGaming.php
fixup speedgaming timezone shenanigangs?
[alttp.git] / app / Console / Commands / SyncSpeedGaming.php
1 <?php
2
3 namespace App\Console\Commands;
4
5 use App\Models\Channel;
6 use App\Models\DiscordBotCommand;
7 use App\Models\Episode;
8 use App\Models\EpisodeCrew;
9 use App\Models\EpisodePlayer;
10 use App\Models\Event;
11 use App\Models\Organization;
12 use App\Models\User;
13 use Carbon\Carbon;
14 use Illuminate\Console\Command;
15 use Illuminate\Database\Eloquent\Builder;
16 use Illuminate\Support\Facades\Http;
17
18 class SyncSpeedGaming extends Command {
19
20         /**
21          * The name and signature of the console command.
22          *
23          * @var string
24          */
25         protected $signature = 'sync:speedgaming';
26
27         /**
28          * The console command description.
29          *
30          * @var string
31          */
32         protected $description = 'Synchronize SpeedGaming schedule';
33
34         /**
35          * Execute the console command.
36          *
37          * @return int
38          */
39         public function handle() {
40                 $this->org = Organization::where('name', '=', 'sg')->firstOrFail();
41
42                 $events = Event::where('external_schedule', 'LIKE', 'sg:%')
43                         ->where(function (Builder $query) {
44                                 $query->whereNull('end');
45                                 $query->orWhere('end', '<', now());
46                         })
47                         ->get();
48
49                 foreach ($events as $event) {
50                         try {
51                                 $this->line('syncing '.$event->name);
52                                 $this->syncEvent($event);
53                         } catch (\Exception $e) {
54                                 $this->error('error syncing event '.$event->name.': '.$e->getMessage());
55                         }
56                 }
57
58                 return 0;
59         }
60
61         private function syncEvent(Event $event) {
62                 $sgHandle = substr($event->external_schedule, 3);
63                 $from = now()->sub(1, 'day');
64                 $to = now()->add(14, 'day');
65                 $sgSchedule = HTTP::get('https://speedgaming.org/api/schedule/', [
66                         'event' => $sgHandle,
67                         'from' => $from->toIso8601String(),
68                         'to' => $to->toIso8601String(),
69                 ])->json();
70                 $this->purgeSchedule($event, $from, $to, $sgSchedule);
71                 foreach ($sgSchedule as $sgEntry) {
72                         try {
73                                 $this->syncSchedule($event, $sgEntry);
74                         } catch (Exception $e) {
75                                 $this->error('error syncing episode '.$sgEntry['id'].': '.$e->getMessage());
76                         }
77                 }
78         }
79
80         private function purgeSchedule(Event $event, $from, $to, $sgSchedule) {
81                 $ext_ids = [];
82                 foreach ($sgSchedule as $sgEntry) {
83                         $ext_ids[] = 'sg:'.$sgEntry['id'];
84                 }
85                 $to_purge = $event->episodes()
86                         ->where('start', '>=', $from)
87                         ->where('start', '<=', $to)
88                         ->whereNotIn('ext_id', $ext_ids);
89                 foreach ($to_purge->get() as $episode) {
90                         $episode->channels()->detach();
91                         $episode->crew()->delete();
92                         $episode->players()->delete();
93                 }
94                 $to_purge->delete();
95         }
96
97         private function syncSchedule(Event $event, $sgEntry) {
98                 $ext_id = 'sg:'.$sgEntry['id'];
99                 $episode = Episode::firstWhere('ext_id', '=', $ext_id);
100                 if (!$episode) {
101                         $episode = new Episode();
102                         $episode->ext_id = $ext_id;
103                 }
104                 $episode->event()->associate($event);
105                 $episode->title = $sgEntry['match1']['title'];
106                 $start = Carbon::createFromFormat('Y-m-d\TH:i:sP', $sgEntry['when']);
107                 // if speedgaming is in DST, it fucks up the timestamp
108                 if (Carbon::now(new \DateTimeZone('America/Chicago'))->dst) {
109                         $start->add(1, 'hour');
110                 }
111                 if (!$episode->start || $start->ne($episode->start)) {
112                         $episode->start = $start;
113                 }
114                 $episode->estimate = $sgEntry['length'] * 60;
115                 $episode->confirmed = $sgEntry['approved'];
116                 $episode->comment = $sgEntry['match1']['note'];
117                 $episode->save();
118
119                 $this->purgeChannels($episode, $sgEntry);
120                 $channelIds = [];
121                 foreach ($sgEntry['channels'] as $sgChannel) {
122                         if ($sgChannel['initials'] == 'NONE') continue;
123                         try {
124                                 $channel = $this->syncChannel($episode, $sgChannel);
125                                 $channelIds[] = $channel->id;
126                         } catch (Exception $e) {
127                                 $this->error('error syncing channel '.$sgChannel['id'].': '.$e->getMessage());
128                         }
129                 }
130                 if (!empty($channelIds)) {
131                         $episode->channels()->syncWithoutDetaching($channelIds);
132                 }
133
134                 $this->purgeCrew($episode, $sgEntry['broadcasters'], 'brd');
135                 foreach ($sgEntry['broadcasters'] as $sgCrew) {
136                         try {
137                                 $this->syncCrew($episode, $sgCrew, 'brd', 'setup');
138                         } catch (Exception $e) {
139                                 $this->error('error syncing broadcaster '.$sgCrew['id'].': '.$e->getMessage());
140                         }
141                 }
142
143                 $this->purgeCrew($episode, $sgEntry['commentators'], 'comm');
144                 foreach ($sgEntry['commentators'] as $sgCrew) {
145                         try {
146                                 $this->syncCrew($episode, $sgCrew, 'comm', 'commentary');
147                         } catch (Exception $e) {
148                                 $this->error('error syncing commentator '.$sgCrew['id'].': '.$e->getMessage());
149                         }
150                 }
151
152                 $this->purgeCrew($episode, $sgEntry['helpers'], 'help');
153                 foreach ($sgEntry['helpers'] as $sgCrew) {
154                         try {
155                                 $this->syncCrew($episode, $sgCrew, 'help', 'setup');
156                         } catch (Exception $e) {
157                                 $this->error('error syncing helper '.$sgCrew['id'].': '.$e->getMessage());
158                         }
159                 }
160
161                 $this->purgeCrew($episode, $sgEntry['trackers'], 'track');
162                 foreach ($sgEntry['trackers'] as $sgCrew) {
163                         try {
164                                 $this->syncCrew($episode, $sgCrew, 'track', 'tracking');
165                         } catch (Exception $e) {
166                                 $this->error('error syncing tracker '.$sgCrew['id'].': '.$e->getMessage());
167                         }
168                 }
169
170                 $this->purgePlayers($episode, $sgEntry);
171                 foreach ($sgEntry['match1']['players'] as $sgPlayer) {
172                         try {
173                                 $this->syncPlayer($episode, $sgPlayer);
174                         } catch (Exception $e) {
175                                 $this->error('error syncing player '.$sgPlayer['id'].': '.$e->getMessage());
176                         }
177                 }
178         }
179
180         private function purgeChannels(Episode $episode, $sgEntry) {
181                 $ext_ids = [];
182                 foreach ($sgEntry['channels'] as $sgChannel) {
183                         $ext_ids[] = 'sg:'.$sgChannel['id'];
184                 }
185                 $channels = $episode->channels()
186                         ->where('ext_id', 'LIKE', 'sg:%')
187                         ->whereNotIn('ext_id', $ext_ids)
188                         ->get();
189                 if (!$channels->isEmpty()) {
190                         $episode->channels()->detach($channels->pluck('id'));
191                 }
192         }
193
194         private function syncChannel(Episode $episode, $sgChannel) {
195                 $ext_id = 'sg:'.$sgChannel['id'];
196                 $channel = $this->org->channels()->firstWhere('ext_id', '=', $ext_id);
197                 if (!$channel) {
198                         $channel = new Channel();
199                         $channel->ext_id = $ext_id;
200                         $channel->organization()->associate($this->org);
201                 }
202                 $channel->short_name = $sgChannel['initials'];
203                 $channel->title = $sgChannel['name'];
204                 $channel->stream_link = 'https://twitch.tv/'.strtolower($sgChannel['name']);
205                 $channel->languages = [$sgChannel['language']];
206                 $channel->save();
207                 return $channel;
208         }
209
210         private function purgeCrew(Episode $episode, $sgCrews, $prefix) {
211                 $ext_ids = [];
212                 foreach ($sgCrews as $sgCrew) {
213                         $ext_ids[] = 'sg:'.$prefix.':'.$sgCrew['id'];
214                 }
215                 $episode->crew()->where('ext_id', 'LIKE', 'sg:'.$prefix.':%')->whereNotIn('ext_id', $ext_ids)->delete();
216         }
217
218         private function syncCrew(Episode $episode, $sgCrew, $prefix, $role) {
219                 $ext_id = 'sg:'.$prefix.':'.$sgCrew['id'];
220                 $crew = $episode->crew()->firstWhere('ext_id', '=', $ext_id);
221                 if (!$crew) {
222                         $crew = new EpisodeCrew();
223                         $crew->ext_id = $ext_id;
224                         $crew->episode()->associate($episode);
225                 }
226                 $user = $this->getUserBySGPlayer($sgCrew);
227                 if ($user) {
228                         $crew->user()->associate($user);
229                 } else {
230                         $crew->user()->disassociate();
231                 }
232                 if ($role == 'commentary') {
233                         $channel = $this->getChannelByCrew($episode, $sgCrew);
234                         if ($channel) {
235                                 $crew->channel()->associate($channel);
236                         } else {
237                                 $crew->channel()->disassociate();
238                         }
239                 }
240                 $crew->role = $role;
241                 $crew->confirmed = $sgCrew['approved'] ?: false;
242                 if (!empty($sgCrew['displayName'])) {
243                         $crew->name_override = $sgCrew['displayName'];
244                 }
245                 if (!empty($sgCrew['publicStream'])) {
246                         $crew->stream_override = 'https://twitch.tv/'.strtolower($sgCrew['publicStream']);
247                 }
248                 $crew->save();
249         }
250
251         private function purgePlayers(Episode $episode, $sgEntry) {
252                 $ext_ids = [];
253                 foreach ($sgEntry['match1']['players'] as $sgPlayer) {
254                         $ext_ids[] = 'sg:'.$sgPlayer['id'];
255                 }
256                 $episode->players()->whereNotIn('ext_id', $ext_ids)->delete();
257         }
258
259         private function syncPlayer(Episode $episode, $sgPlayer) {
260                 $ext_id = 'sg:'.$sgPlayer['id'];
261                 $player = $episode->players()->firstWhere('ext_id', '=', $ext_id);
262                 if (!$player) {
263                         $player = new EpisodePlayer();
264                         $player->ext_id = $ext_id;
265                         $player->episode()->associate($episode);
266                 }
267                 $user = $this->getUserBySGPlayer($sgPlayer);
268                 if ($user) {
269                         $player->user()->associate($user);
270                 } else {
271                         $player->user()->disassociate();
272                 }
273                 if (!empty($sgPlayer['displayName'])) {
274                         $player->name_override = $sgPlayer['displayName'];
275                 }
276                 if (!empty($sgPlayer['streamingFrom'])) {
277                         $player->stream_override = 'https://twitch.tv/'.strtolower($sgPlayer['streamingFrom']);
278                 }
279                 $player->save();
280         }
281
282         private function getChannelByCrew(Episode $episode, $sgCrew) {
283                 $channel = $episode->channels()
284                   ->where('ext_id', 'LIKE', 'sg:%')
285                   ->whereJsonContains('languages', $sgCrew['language'])
286                   ->first();
287                 if ($channel) {
288                         return $channel;
289                 }
290                 return $episode->channels()
291                   ->where('ext_id', 'LIKE', 'sg:%')
292                   ->first();
293         }
294
295         private function getUserBySGPlayer($player) {
296                 if (!empty($player['discordId'])) {
297                         $user = User::find($player['discordId']);
298                         if ($user) {
299                                 if (empty($user->stream_link)) {
300                                         if (!empty($sgPlayer['publicStream'])) {
301                                                 $user->stream_link = 'https://twitch.tv/'.strtolower($sgPlayer['publicStream']);
302                                                 $user->save();
303                                         } else if (!empty($sgPlayer['streamingFrom'])) {
304                                                 $user->stream_link = 'https://twitch.tv/'.strtolower($sgPlayer['streamingFrom']);
305                                                 $user->save();
306                                         }
307                                 }
308                                 return $user;
309                         }
310                         DiscordBotCommand::syncUser($player['discordId']);
311                 }
312                 if (!empty($player['discordTag'])) {
313                         $tag = explode('#', $player['discordTag']);
314                         $user = User::firstWhere([
315                                 ['username', 'LIKE', $tag[0]],
316                                 ['discriminator', '=', $tag[1]],
317                         ]);
318                         if ($user) return $user;
319                 }
320                 return null;
321         }
322
323         private $org;
324
325 }