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