]> git.localhorst.tv Git - alttp.git/blob - app/Console/Commands/SyncSpeedGaming.php
d75da5078bfea496aea043793149395154959b61
[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                 $episode->channels()
180                   ->where('ext_id', 'LIKE', 'sg:%')
181                   ->whereNotIn('ext_id', $ext_ids)
182                   ->detach();
183         }
184
185         private function syncChannel(Episode $episode, $sgChannel) {
186                 $ext_id = 'sg:'.$sgChannel['id'];
187                 $channel = $this->org->channels()->firstWhere('ext_id', '=', $ext_id);
188                 if (!$channel) {
189                         $channel = new Channel();
190                         $channel->ext_id = $ext_id;
191                         $channel->organization()->associate($this->org);
192                 }
193                 $channel->short_name = $sgChannel['initials'];
194                 $channel->title = $sgChannel['name'];
195                 $channel->stream_link = 'https://twitch.tv/'.strtolower($sgChannel['name']);
196                 $channel->languages = [$sgChannel['language']];
197                 $channel->save();
198                 return $channel;
199         }
200
201         private function purgeCrew(Episode $episode, $sgCrews, $prefix) {
202                 $ext_ids = [];
203                 foreach ($sgCrews as $sgCrew) {
204                         $ext_ids[] = 'sg:'.$prefix.':'.$sgCrew['id'];
205                 }
206                 $episode->crew()->where('ext_id', 'LIKE', 'sg:'.$prefix.':%')->whereNotIn('ext_id', $ext_ids)->delete();
207         }
208
209         private function syncCrew(Episode $episode, $sgCrew, $prefix, $role) {
210                 $ext_id = 'sg:'.$prefix.':'.$sgCrew['id'];
211                 $crew = $episode->crew()->firstWhere('ext_id', '=', $ext_id);
212                 if (!$crew) {
213                         $crew = new EpisodeCrew();
214                         $crew->ext_id = $ext_id;
215                         $crew->episode()->associate($episode);
216                 }
217                 $user = $this->getUserBySGPlayer($sgCrew);
218                 if ($user) {
219                         $crew->user()->associate($user);
220                 } else {
221                         $crew->user()->disassociate();
222                 }
223                 if ($role == 'commentary') {
224                         $channel = $this->getChannelByCrew($episode, $sgCrew);
225                         if ($channel) {
226                                 $crew->channel()->associate($channel);
227                         } else {
228                                 $crew->channel()->disassociate();
229                         }
230                 }
231                 $crew->role = $role;
232                 $crew->confirmed = $sgCrew['approved'] ?: false;
233                 if (!empty($sgCrew['displayName'])) {
234                         $crew->name_override = $sgCrew['displayName'];
235                 }
236                 if (!empty($sgCrew['publicStream'])) {
237                         $crew->stream_override = 'https://twitch.tv/'.strtolower($sgCrew['publicStream']);
238                 }
239                 $crew->save();
240         }
241
242         private function purgePlayers(Episode $episode, $sgEntry) {
243                 $ext_ids = [];
244                 foreach ($sgEntry['match1']['players'] as $sgPlayer) {
245                         $ext_ids[] = 'sg:'.$sgPlayer['id'];
246                 }
247                 $episode->players()->whereNotIn('ext_id', $ext_ids)->delete();
248         }
249
250         private function syncPlayer(Episode $episode, $sgPlayer) {
251                 $ext_id = 'sg:'.$sgPlayer['id'];
252                 $player = $episode->players()->firstWhere('ext_id', '=', $ext_id);
253                 if (!$player) {
254                         $player = new EpisodePlayer();
255                         $player->ext_id = $ext_id;
256                         $player->episode()->associate($episode);
257                 }
258                 $user = $this->getUserBySGPlayer($sgPlayer);
259                 if ($user) {
260                         $player->user()->associate($user);
261                 } else {
262                         $player->user()->disassociate();
263                 }
264                 if (!empty($sgPlayer['displayName'])) {
265                         $player->name_override = $sgPlayer['displayName'];
266                 }
267                 if (!empty($sgPlayer['streamingFrom'])) {
268                         $player->stream_override = 'https://twitch.tv/'.strtolower($sgPlayer['streamingFrom']);
269                 }
270                 $player->save();
271         }
272
273         private function getChannelByCrew(Episode $episode, $sgCrew) {
274                 $channel = $episode->channels()
275                   ->where('ext_id', 'LIKE', 'sg:%')
276                   ->whereJsonContains('languages', $sgCrew['language'])
277                   ->first();
278                 if ($channel) {
279                         return $channel;
280                 }
281         }
282
283         private function getUserBySGPlayer($player) {
284                 if (!empty($player['discordId'])) {
285                         $user = User::find($player['discordId']);
286                         if ($user) {
287                                 if (empty($user->stream_link)) {
288                                         if (!empty($sgPlayer['publicStream'])) {
289                                                 $user->stream_link = 'https://twitch.tv/'.strtolower($sgPlayer['publicStream']);
290                                                 $user->save();
291                                         } else if (!empty($sgPlayer['streamingFrom'])) {
292                                                 $user->stream_link = 'https://twitch.tv/'.strtolower($sgPlayer['streamingFrom']);
293                                                 $user->save();
294                                         }
295                                 }
296                                 return $user;
297                         }
298                         DiscordBotCommand::syncUser($player['discordId']);
299                 }
300                 if (!empty($player['discordTag'])) {
301                         $tag = explode('#', $player['discordTag']);
302                         $user = User::firstWhere([
303                                 ['username', 'LIKE', $tag[0]],
304                                 ['username', 'LIKE', $tag[1]],
305                         ]);
306                         if ($user) return $user;
307                 }
308                 return null;
309         }
310
311         private $org;
312
313 }