3 namespace App\Console\Commands;
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;
11 use App\Models\Organization;
14 use Illuminate\Console\Command;
15 use Illuminate\Database\Eloquent\Builder;
16 use Illuminate\Support\Facades\Http;
18 class SyncSpeedGaming extends Command {
21 * The name and signature of the console command.
25 protected $signature = 'sync:speedgaming';
28 * The console command description.
32 protected $description = 'Synchronize SpeedGaming schedule';
35 * Execute the console command.
39 public function handle() {
40 $this->org = Organization::where('name', '=', 'sg')->firstOrFail();
42 $events = Event::where('external_schedule', 'LIKE', 'sg:%')
43 ->where(function (Builder $query) {
44 $query->whereNull('end');
45 $query->orWhere('end', '>', now());
49 foreach ($events as $event) {
51 $this->line('syncing '.$event->name);
52 $this->syncEvent($event);
53 } catch (\Exception $e) {
54 $this->error('error syncing event '.$event->name.': '.$e->getMessage());
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/', [
67 'from' => $from->toIso8601String(),
68 'to' => $to->toIso8601String(),
70 $this->purgeSchedule($event, $from, $to, $sgSchedule);
71 foreach ($sgSchedule as $sgEntry) {
73 $this->syncSchedule($event, $sgEntry);
74 } catch (Exception $e) {
75 $this->error('error syncing episode '.$sgEntry['id'].': '.$e->getMessage());
80 private function purgeSchedule(Event $event, $from, $to, $sgSchedule) {
82 foreach ($sgSchedule as $sgEntry) {
83 $ext_ids[] = 'sg:'.$sgEntry['id'];
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();
97 private function syncSchedule(Event $event, $sgEntry) {
98 $ext_id = 'sg:'.$sgEntry['id'];
99 $episode = Episode::firstWhere('ext_id', '=', $ext_id);
101 $episode = new Episode();
102 $episode->ext_id = $ext_id;
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');
117 if (!$episode->start || $start->ne($episode->start)) {
118 $episode->start = $start;
120 $episode->estimate = $sgEntry['length'] * 60;
121 $episode->confirmed = $sgEntry['approved'];
122 $episode->comment = $sgEntry['match1']['note'];
125 $this->purgeChannels($episode, $sgEntry);
127 foreach ($sgEntry['channels'] as $sgChannel) {
128 if ($sgChannel['initials'] == 'NONE' || $sgChannel['name'] == 'Undecided, Not SG') continue;
130 $channel = $this->syncChannel($episode, $sgChannel);
131 $channelIds[] = $channel->id;
132 } catch (Exception $e) {
133 $this->error('error syncing channel '.$sgChannel['id'].': '.$e->getMessage());
136 if (!empty($channelIds)) {
137 $episode->channels()->syncWithoutDetaching($channelIds);
140 $this->purgeCrew($episode, $sgEntry['broadcasters'], 'brd');
141 foreach ($sgEntry['broadcasters'] as $sgCrew) {
143 $this->syncCrew($episode, $sgCrew, 'brd', 'setup');
144 } catch (Exception $e) {
145 $this->error('error syncing broadcaster '.$sgCrew['id'].': '.$e->getMessage());
149 $this->purgeCrew($episode, $sgEntry['commentators'], 'comm');
150 foreach ($sgEntry['commentators'] as $sgCrew) {
152 $this->syncCrew($episode, $sgCrew, 'comm', 'commentary');
153 } catch (Exception $e) {
154 $this->error('error syncing commentator '.$sgCrew['id'].': '.$e->getMessage());
158 $this->purgeCrew($episode, $sgEntry['helpers'], 'help');
159 foreach ($sgEntry['helpers'] as $sgCrew) {
161 $this->syncCrew($episode, $sgCrew, 'help', 'setup');
162 } catch (Exception $e) {
163 $this->error('error syncing helper '.$sgCrew['id'].': '.$e->getMessage());
167 $this->purgeCrew($episode, $sgEntry['trackers'], 'track');
168 foreach ($sgEntry['trackers'] as $sgCrew) {
170 $this->syncCrew($episode, $sgCrew, 'track', 'tracking');
171 } catch (Exception $e) {
172 $this->error('error syncing tracker '.$sgCrew['id'].': '.$e->getMessage());
176 $this->purgePlayers($episode, $sgEntry);
177 foreach ($sgEntry['match1']['players'] as $sgPlayer) {
179 $this->syncPlayer($episode, $sgPlayer);
180 } catch (Exception $e) {
181 $this->error('error syncing player '.$sgPlayer['id'].': '.$e->getMessage());
186 private function purgeChannels(Episode $episode, $sgEntry) {
188 foreach ($sgEntry['channels'] as $sgChannel) {
189 $ext_ids[] = 'sg:'.$sgChannel['id'];
191 $channels = $episode->channels()
192 ->where('ext_id', 'LIKE', 'sg:%')
193 ->whereNotIn('ext_id', $ext_ids)
195 if (!$channels->isEmpty()) {
196 $episode->channels()->detach($channels->pluck('id'));
200 private function syncChannel(Episode $episode, $sgChannel) {
201 $ext_id = 'sg:'.$sgChannel['id'];
202 $channel = $this->org->channels()->firstWhere('ext_id', '=', $ext_id);
204 $channel = new Channel();
205 $channel->ext_id = $ext_id;
206 $channel->organization()->associate($this->org);
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']];
216 private function purgeCrew(Episode $episode, $sgCrews, $prefix) {
218 foreach ($sgCrews as $sgCrew) {
219 $ext_ids[] = 'sg:'.$prefix.':'.$sgCrew['id'];
221 $episode->crew()->where('ext_id', 'LIKE', 'sg:'.$prefix.':%')->whereNotIn('ext_id', $ext_ids)->delete();
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);
228 $crew = new EpisodeCrew();
229 $crew->ext_id = $ext_id;
230 $crew->episode()->associate($episode);
232 $user = $this->getUserBySGPlayer($sgCrew);
234 $crew->user()->associate($user);
236 $crew->user()->disassociate();
238 if ($role == 'commentary') {
239 $channel = $this->getChannelByCrew($episode, $sgCrew);
241 $crew->channel()->associate($channel);
243 $crew->channel()->disassociate();
247 $crew->confirmed = $sgCrew['approved'] ?: false;
248 if (!empty($sgCrew['displayName'])) {
249 $crew->name_override = $sgCrew['displayName'];
251 if (!empty($sgCrew['publicStream'])) {
252 $crew->stream_override = 'https://twitch.tv/'.strtolower($sgCrew['publicStream']);
257 private function purgePlayers(Episode $episode, $sgEntry) {
259 foreach ($sgEntry['match1']['players'] as $sgPlayer) {
260 $ext_ids[] = 'sg:'.$sgPlayer['id'];
262 $episode->players()->whereNotIn('ext_id', $ext_ids)->delete();
265 private function syncPlayer(Episode $episode, $sgPlayer) {
266 $ext_id = 'sg:'.$sgPlayer['id'];
267 $player = $episode->players()->firstWhere('ext_id', '=', $ext_id);
269 $player = new EpisodePlayer();
270 $player->ext_id = $ext_id;
271 $player->episode()->associate($episode);
273 $user = $this->getUserBySGPlayer($sgPlayer);
275 $player->user()->associate($user);
277 $player->user()->disassociate();
279 if (!empty($sgPlayer['displayName'])) {
280 $player->name_override = $sgPlayer['displayName'];
282 if (!empty($sgPlayer['streamingFrom'])) {
283 $player->stream_override = 'https://twitch.tv/'.strtolower($sgPlayer['streamingFrom']);
288 private function getChannelByCrew(Episode $episode, $sgCrew) {
289 $channel = $episode->channels()
290 ->where('ext_id', 'LIKE', 'sg:%')
291 ->whereJsonContains('languages', $sgCrew['language'])
296 return $episode->channels()
297 ->where('ext_id', 'LIKE', 'sg:%')
301 private function getUserBySGPlayer($player) {
302 if (!empty($player['discordId'])) {
303 $user = User::find($player['discordId']);
305 if (empty($user->stream_link)) {
306 if (!empty($sgPlayer['publicStream'])) {
307 $user->stream_link = 'https://twitch.tv/'.strtolower($sgPlayer['publicStream']);
309 } else if (!empty($sgPlayer['streamingFrom'])) {
310 $user->stream_link = 'https://twitch.tv/'.strtolower($sgPlayer['streamingFrom']);
316 DiscordBotCommand::syncUser($player['discordId']);
318 if (!empty($player['discordTag'])) {
319 $tag = explode('#', $player['discordTag']);
320 $user = count($tag) < 2 || $tag[1] == '0'
322 ['username', 'LIKE', $tag[0]],
325 ['username', 'LIKE', $tag[0]],
326 ['discriminator', '=', $tag[1]],
328 if ($user) return $user;