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