--- /dev/null
+<?php
+
+namespace App\Console\Commands;
+
+use App\Models\Channel;
+use App\Models\DiscordBotCommand;
+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;
+use Illuminate\Support\Str;
+
+class SyncTFL extends Command {
+
+ /**
+ * The name and signature of the console command.
+ *
+ * @var string
+ */
+ protected $signature = 'sync:tfl';
+
+ /**
+ * The console command description.
+ *
+ * @var string
+ */
+ protected $description = 'Synchronize TryForce League schedule';
+
+ /**
+ * Execute the console command.
+ *
+ * @return int
+ */
+ public function handle() {
+ $events = Event::where('external_schedule', 'LIKE', 'tfl:%')
+ ->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) {
+ $tflSchedule = Http::get('https://tfl-discord-api.onrender.com/api/upcoming?n=20')->json();
+ if (!$tflSchedule) {
+ return;
+ }
+ $this->purgeSchedule($event, $tflSchedule['items']);
+ foreach ($tflSchedule['items'] as $tflEntry) {
+ try {
+ $this->syncSchedule($event, $tflEntry);
+ } catch (\Exception $e) {
+ $this->error('error syncing episode '.$tflEntry['id'].': '.$e->getMessage());
+ }
+ }
+ }
+
+ private function purgeSchedule(Event $event, $tflSchedule): void {
+ $ext_ids = [];
+ foreach ($tflSchedule as $tflEntry) {
+ $ext_ids[] = 'tfl:'.$tflEntry['id'];
+ }
+ $to_purge = $event->episodes()
+ ->whereNotIn('ext_id', $ext_ids)
+ ->where('ext_id', 'LIKE', 'tfl:%')
+ ->where('start', '>', 'NOW()');
+ foreach ($to_purge->get() as $episode) {
+ $episode->callOff();
+ }
+ $to_purge->delete();
+ }
+
+ private function syncSchedule(Event $event, $tflEntry): void {
+ $ext_id = 'tfl:'.$tflEntry['id'];
+ $episode = $event->episodes()->firstWhere('ext_id', '=', $ext_id);
+ if (!$episode) {
+ $episode = new Episode();
+ $episode->ext_id = $ext_id;
+ $episode->event()->associate($event);
+ }
+ $episode->title = $tflEntry['name'];
+ $start = Carbon::createFromFormat('Y-m-d\\T H:i:sP', $tflEntry['start']);
+ if (!$episode->start || $start->ne($episode->start)) {
+ $episode->start = $start;
+ $episode->estimate = $start->diffInSeconds(Carbon::createFromFormat('Y-m-d\\T H:i:sP', $tflEntry['end']));
+ }
+ $episode->confirmed = true;
+ $episode->save();
+
+ if (!preg_match('/\\| (.*) vs\\. (.*) \\|/', $tflEntry['name'], $matches)) {
+ return;
+ }
+ $tflPlayers = [$matches[1], $matches[2]];
+
+ $this->purgePlayers($episode, $tflPlayers);
+ foreach ($tflPlayers as $tflPlayer) {
+ $this->syncPlayer($episode, $tflPlayer);
+ }
+
+ if (strpos($tflEntry['location'], 'twitch.tv/') !== false) {
+ $channel = $this->syncChannel($episode, $tflEntry['location']);
+ $episode->channels()->syncWithoutDetaching([$channel->id]);
+ }
+ }
+
+ private function purgePlayers(Episode $episode, $tflPlayers): void {
+ $ext_ids = [];
+ foreach ($tflPlayers as $tflPlayer) {
+ $ext_ids[] = 'tfl:'.$tflPlayer;
+ }
+ $episode->players()->whereNotIn('ext_id', $ext_ids)->delete();
+ }
+
+ private function syncPlayer(Episode $episode, $tflPlayer) {
+ $ext_id = 'tfl:'.$tflPlayer;
+ $player = $episode->players()->firstWhere('ext_id', '=', $ext_id);
+ if (!$player) {
+ $player = new EpisodePlayer();
+ $player->ext_id = $ext_id;
+ $player->name_override = $tflPlayer;
+ $player->episode()->associate($episode);
+ }
+ $user = $this->getUser($tflPlayer);
+ if ($user) {
+ $player->user()->associate($user);
+ } else {
+ $player->user()->disassociate();
+ }
+ $player->save();
+ }
+
+ private function syncChannel(Episode $episode, string $channel_url): Channel {
+ $normalized_url = Str::rtrim(Str::lower($channel_url), '/');
+ $normalized_url = str_replace('http://', 'https://', $normalized_url);
+ $normalized_url = str_replace('www.twitch.tv', 'twitch.tv', $normalized_url);
+ $channel = Channel::query()->firstWhere('stream_link', 'LIKE', $normalized_url);
+ if (!$channel) {
+ $channel = new Channel();
+ $channel->stream_link = $normalized_url;
+ $channel->title = Str::afterLast($normalized_url, '/');
+ $channel->languages = ['de'];
+ $channel->twitch_chat = '#'.Str::afterLast($normalized_url, '/');
+ $channel->access_key = Str::uuid();
+ $channel->save();
+ }
+ return $channel;
+ }
+
+ private function getUser(string $codename): User|null {
+ if (isset($this->codename_table[$codename])) {
+ $user = User::query()->firstWhere('username', 'LIKE', $this->codename_table[$codename]);
+ if ($user) {
+ return $user;
+ }
+ }
+ $user = User::query()->firstWhere('discord_nickname', 'LIKE', $codename);
+ if ($user) {
+ return $user;
+ }
+ $user = User::query()->firstWhere('username', 'LIKE', $codename);
+ if ($user) {
+ return $user;
+ }
+ $user = User::query()->firstWhere('stream_link', 'LIKE', '%/'.$codename);
+ if ($user) {
+ return $user;
+ }
+ return null;
+ }
+
+ private $codename_table = [
+ ];
+
+}