]> git.localhorst.tv Git - alttp.git/blob - app/Console/Commands/SyncSpeedGaming.php
fix type in sg sync
[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 ($event->fix_timezone && !$episode->timezone_fix_override) {
108                         $sg_zone = new \DateTimeZone('America/Detroit');
109                         $event_zone = new \DateTimeZone($event->fix_timezone);
110                         // if speedgaming is in DST, it fucks up the timestamp
111                         if (Carbon::createFromTimestamp($start->timestamp, $sg_zone)->dst && !Carbon::createFromTimestamp($start->timestamp, $event_zone)->dst) {
112                                 $start->add(1, 'hour');
113                         } else if (!Carbon::createFromTimestamp($start->timestamp, $sg_zone)->dst && Carbon::createFromTimestamp($start->timestamp, $event_zone)->dst) {
114                                 $start->sub(1, 'hour');
115                         }
116                 }
117                 if (!$episode->start || $start->ne($episode->start)) {
118                         $episode->start = $start;
119                 }
120                 $episode->estimate = $sgEntry['length'] * 60;
121                 $episode->confirmed = $sgEntry['approved'];
122                 $episode->comment = $sgEntry['match1']['note'];
123                 $episode->save();
124
125                 $this->purgeChannels($episode, $sgEntry);
126                 $channelIds = [];
127                 foreach ($sgEntry['channels'] as $sgChannel) {
128                         if ($sgChannel['initials'] == 'NONE' || $sgChannel['name'] == 'Undecided, Not SG') continue;
129                         try {
130                                 $channel = $this->syncChannel($episode, $sgChannel);
131                                 $channelIds[] = $channel->id;
132                         } catch (Exception $e) {
133                                 $this->error('error syncing channel '.$sgChannel['id'].': '.$e->getMessage());
134                         }
135                 }
136                 if (!empty($channelIds)) {
137                         $episode->channels()->syncWithoutDetaching($channelIds);
138                 }
139
140                 $this->purgeCrew($episode, $sgEntry['broadcasters'], 'brd');
141                 foreach ($sgEntry['broadcasters'] as $sgCrew) {
142                         try {
143                                 $this->syncCrew($episode, $sgCrew, 'brd', 'setup');
144                         } catch (Exception $e) {
145                                 $this->error('error syncing broadcaster '.$sgCrew['id'].': '.$e->getMessage());
146                         }
147                 }
148
149                 $this->purgeCrew($episode, $sgEntry['commentators'], 'comm');
150                 foreach ($sgEntry['commentators'] as $sgCrew) {
151                         try {
152                                 $this->syncCrew($episode, $sgCrew, 'comm', 'commentary');
153                         } catch (Exception $e) {
154                                 $this->error('error syncing commentator '.$sgCrew['id'].': '.$e->getMessage());
155                         }
156                 }
157
158                 $this->purgeCrew($episode, $sgEntry['helpers'], 'help');
159                 foreach ($sgEntry['helpers'] as $sgCrew) {
160                         try {
161                                 $this->syncCrew($episode, $sgCrew, 'help', 'setup');
162                         } catch (Exception $e) {
163                                 $this->error('error syncing helper '.$sgCrew['id'].': '.$e->getMessage());
164                         }
165                 }
166
167                 $this->purgeCrew($episode, $sgEntry['trackers'], 'track');
168                 foreach ($sgEntry['trackers'] as $sgCrew) {
169                         try {
170                                 $this->syncCrew($episode, $sgCrew, 'track', 'tracking');
171                         } catch (Exception $e) {
172                                 $this->error('error syncing tracker '.$sgCrew['id'].': '.$e->getMessage());
173                         }
174                 }
175
176                 $this->purgePlayers($episode, $sgEntry);
177                 foreach ($sgEntry['match1']['players'] as $sgPlayer) {
178                         try {
179                                 $this->syncPlayer($episode, $sgPlayer);
180                         } catch (Exception $e) {
181                                 $this->error('error syncing player '.$sgPlayer['id'].': '.$e->getMessage());
182                         }
183                 }
184         }
185
186         private function purgeChannels(Episode $episode, $sgEntry) {
187                 $ext_ids = [];
188                 foreach ($sgEntry['channels'] as $sgChannel) {
189                         $ext_ids[] = 'sg:'.$sgChannel['id'];
190                 }
191                 $channels = $episode->channels()
192                         ->where('ext_id', 'LIKE', 'sg:%')
193                         ->whereNotIn('ext_id', $ext_ids)
194                         ->get();
195                 if (!$channels->isEmpty()) {
196                         $episode->channels()->detach($channels->pluck('id'));
197                 }
198         }
199
200         private function syncChannel(Episode $episode, $sgChannel) {
201                 $ext_id = 'sg:'.$sgChannel['id'];
202                 $channel = $this->org->channels()->firstWhere('ext_id', '=', $ext_id);
203                 if (!$channel) {
204                         $channel = new Channel();
205                         $channel->ext_id = $ext_id;
206                         $channel->organization()->associate($this->org);
207                 }
208                 $channel->short_name = $sgChannel['initials'];
209                 $channel->title = $sgChannel['name'];
210                 $channel->stream_link = 'https://twitch.tv/'.strtolower($sgChannel['name']);
211                 $channel->languages = [$sgChannel['language']];
212                 $channel->save();
213                 return $channel;
214         }
215
216         private function purgeCrew(Episode $episode, $sgCrews, $prefix) {
217                 $ext_ids = [];
218                 foreach ($sgCrews as $sgCrew) {
219                         $ext_ids[] = 'sg:'.$prefix.':'.$sgCrew['id'];
220                 }
221                 $episode->crew()->where('ext_id', 'LIKE', 'sg:'.$prefix.':%')->whereNotIn('ext_id', $ext_ids)->delete();
222         }
223
224         private function syncCrew(Episode $episode, $sgCrew, $prefix, $role) {
225                 $ext_id = 'sg:'.$prefix.':'.$sgCrew['id'];
226                 $crew = $episode->crew()->firstWhere('ext_id', '=', $ext_id);
227                 if (!$crew) {
228                         $crew = new EpisodeCrew();
229                         $crew->ext_id = $ext_id;
230                         $crew->episode()->associate($episode);
231                 }
232                 $user = $this->getUserBySGPlayer($sgCrew);
233                 if ($user) {
234                         $crew->user()->associate($user);
235                 } else {
236                         $crew->user()->disassociate();
237                 }
238                 if ($role == 'commentary') {
239                         $channel = $this->getChannelByCrew($episode, $sgCrew);
240                         if ($channel) {
241                                 $crew->channel()->associate($channel);
242                         } else {
243                                 $crew->channel()->disassociate();
244                         }
245                 }
246                 $crew->role = $role;
247                 $crew->confirmed = $sgCrew['approved'] ?: false;
248                 if (!empty($sgCrew['displayName'])) {
249                         $crew->name_override = $sgCrew['displayName'];
250                 }
251                 if (!empty($sgCrew['publicStream'])) {
252                         $crew->stream_override = 'https://twitch.tv/'.strtolower($sgCrew['publicStream']);
253                 }
254                 $crew->save();
255         }
256
257         private function purgePlayers(Episode $episode, $sgEntry) {
258                 $ext_ids = [];
259                 foreach ($sgEntry['match1']['players'] as $sgPlayer) {
260                         $ext_ids[] = 'sg:'.$sgPlayer['id'];
261                 }
262                 $episode->players()->whereNotIn('ext_id', $ext_ids)->delete();
263         }
264
265         private function syncPlayer(Episode $episode, $sgPlayer) {
266                 $ext_id = 'sg:'.$sgPlayer['id'];
267                 $player = $episode->players()->firstWhere('ext_id', '=', $ext_id);
268                 if (!$player) {
269                         $player = new EpisodePlayer();
270                         $player->ext_id = $ext_id;
271                         $player->episode()->associate($episode);
272                 }
273                 $user = $this->getUserBySGPlayer($sgPlayer);
274                 if ($user) {
275                         $player->user()->associate($user);
276                 } else {
277                         $player->user()->disassociate();
278                 }
279                 if (!empty($sgPlayer['displayName'])) {
280                         $player->name_override = $sgPlayer['displayName'];
281                 }
282                 if (!empty($sgPlayer['streamingFrom'])) {
283                         $player->stream_override = 'https://twitch.tv/'.strtolower($sgPlayer['streamingFrom']);
284                 }
285                 $player->save();
286         }
287
288         private function getChannelByCrew(Episode $episode, $sgCrew) {
289                 $channel = $episode->channels()
290                   ->where('ext_id', 'LIKE', 'sg:%')
291                   ->whereJsonContains('languages', $sgCrew['language'])
292                   ->first();
293                 if ($channel) {
294                         return $channel;
295                 }
296                 return $episode->channels()
297                   ->where('ext_id', 'LIKE', 'sg:%')
298                   ->first();
299         }
300
301         private function getUserBySGPlayer($player) {
302                 if (!empty($player['discordId'])) {
303                         $user = User::find($player['discordId']);
304                         if ($user) {
305                                 if (empty($user->stream_link)) {
306                                         if (!empty($sgPlayer['publicStream'])) {
307                                                 $user->stream_link = 'https://twitch.tv/'.strtolower($sgPlayer['publicStream']);
308                                                 $user->save();
309                                         } else if (!empty($sgPlayer['streamingFrom'])) {
310                                                 $user->stream_link = 'https://twitch.tv/'.strtolower($sgPlayer['streamingFrom']);
311                                                 $user->save();
312                                         }
313                                 }
314                                 return $user;
315                         }
316                         DiscordBotCommand::syncUser($player['discordId']);
317                 }
318                 if (!empty($player['discordTag'])) {
319                         $tag = explode('#', $player['discordTag']);
320                         $user = count($tag) < 2 || $tag[1] == '0'
321                                 ? User::firstWhere([
322                                         ['username', 'LIKE', $tag[0]],
323                                 ])
324                                 : User::firstWhere([
325                                         ['username', 'LIKE', $tag[0]],
326                                         ['discriminator', '=', $tag[1]],
327                                 ]);
328                         if ($user) return $user;
329                 }
330                 return null;
331         }
332
333         private $org;
334
335 }