+<?php
+
+namespace App\Console\Commands;
+
+use App\Models\Episode;
+use App\Models\EpisodePlayer;
+use App\Models\Event;
+use App\Models\User;
+use Carbon\Carbon;
+use Illuminate\Console\Command;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Support\Facades\Http;
+
+class SyncSpeedGaming extends Command {
+
+ /**
+ * The name and signature of the console command.
+ *
+ * @var string
+ */
+ protected $signature = 'sync:speedgaming';
+
+ /**
+ * The console command description.
+ *
+ * @var string
+ */
+ protected $description = 'Synchronize SpeedGaming schedule';
+
+ /**
+ * Execute the console command.
+ *
+ * @return int
+ */
+ public function handle() {
+ $events = Event::where('external_schedule', 'LIKE', 'sg:%')
+ ->where(function (Builder $query) {
+ $query->whereNull('end');
+ $query->orWhere('end', '<', now());
+ })
+ ->get();
+ foreach ($events as $event) {
+ try {
+ $this->line('syncing '.$event->name);
+ $this->syncEvent($event);
+ } catch (\Exception $e) {
+ $this->error('error syncing event '.$event->name.': '.$e->getMessage());
+ }
+ }
+ return 0;
+ }
+
+ private function syncEvent(Event $event) {
+ $sgHandle = substr($event->external_schedule, 3);
+ $from = now()->sub(1, 'day');
+ $to = now()->add(6, 'day');
+ $sgSchedule = HTTP::get('https://speedgaming.org/api/schedule/', [
+ 'event' => $sgHandle,
+ 'from' => $from->toIso8601String(),
+ 'to' => $to->toIso8601String(),
+ ])->json();
+ $this->purgeSchedule($event, $sgSchedule);
+ foreach ($sgSchedule as $sgEntry) {
+ try {
+ $this->syncSchedule($event, $sgEntry);
+ } catch (Exception $e) {
+ $this->error('error syncing episode '.$sgEntry['id'].': '.$e->getMessage());
+ }
+ }
+ }
+
+ private function purgeSchedule(Event $event, $sgSchedule) {
+ $ext_ids = [];
+ foreach ($sgSchedule as $sgEntry) {
+ $ext_ids[] = 'sg:'.$sgEntry['id'];
+ }
+ $event->episodes()->whereNotIn('ext_id', $ext_ids)->delete();
+ }
+
+ private function syncSchedule(Event $event, $sgEntry) {
+ $ext_id = 'sg:'.$sgEntry['id'];
+ $episode = Episode::firstWhere('ext_id', '=', $ext_id);
+ if (!$episode) {
+ $episode = new Episode();
+ $episode->ext_id = $ext_id;
+ }
+ $episode->event()->associate($event);
+ $episode->title = $sgEntry['match1']['title'];
+ $start = Carbon::parse($sgEntry['when']);
+ if ($start->ne($episode->start)) {
+ $episode->start = $start;
+ }
+ $episode->estimate = $sgEntry['length'] * 60;
+ $episode->confirmed = $sgEntry['approved'];
+ $episode->comment = $sgEntry['match1']['note'];
+ $episode->save();
+ $this->purgePlayers($episode, $sgEntry);
+ foreach ($sgEntry['match1']['players'] as $sgPlayer) {
+ try {
+ $this->syncPlayer($episode, $sgPlayer);
+ } catch (Exception $e) {
+ $this->error('error syncing player '.$sgPlayer['id'].': '.$e->getMessage());
+ }
+ }
+ }
+
+ private function purgePlayers(Episode $episode, $sgEntry) {
+ $ext_ids = [];
+ foreach ($sgEntry['match1']['players'] as $sgPlayer) {
+ $ext_ids[] = 'sg:'.$sgPlayer['id'];
+ }
+ $episode->players()->whereNotIn('ext_id', $ext_ids)->delete();
+ }
+
+ private function syncPlayer(Episode $episode, $sgPlayer) {
+ $ext_id = 'sg:'.$sgPlayer['id'];
+ $player = $episode->players()->firstWhere('ext_id', '=', $ext_id);
+ if (!$player) {
+ $player = new EpisodePlayer();
+ $player->ext_id = $ext_id;
+ $player->episode()->associate($episode);
+ }
+ $user = $this->getUserBySGPlayer($sgPlayer);
+ if ($user) {
+ $player->user()->associate($user);
+ } else {
+ $player->user()->disassociate();
+ }
+ if (!empty($sgPlayer['displayName'])) {
+ $player->name_override = $sgPlayer['displayName'];
+ }
+ if (!empty($sgPlayer['streamingFrom'])) {
+ $player->stream_override = $sgPlayer['streamingFrom'];
+ }
+ $player->save();
+ }
+
+ private function getUserBySGPlayer($player) {
+ if (!empty($player['discordId'])) {
+ $user = User::find($player['discordId']);
+ if ($user) return $user;
+ }
+ if (!empty($player['discordTag'])) {
+ $tag = explode('#', $player['discordTag']);
+ $user = User::firstWhere([
+ ['username', 'LIKE', $tag[0]],
+ ['username', 'LIKE', $tag[1]],
+ ]);
+ if ($user) return $user;
+ }
+ return null;
+ }
+
+}