3 namespace App\Console\Commands;
5 use App\Models\Channel;
6 use App\Models\Episode;
8 use App\Models\Organization;
10 use Illuminate\Console\Command;
11 use Illuminate\Database\Eloquent\Builder;
12 use Illuminate\Support\Facades\Http;
13 use Illuminate\Support\Str;
15 class SyncSRA extends Command {
18 * The name and signature of the console command.
22 protected $signature = 'sync:sra';
25 * The console command description.
29 protected $description = 'Synchronize Speed Runners Area schedule';
32 * Execute the console command.
36 public function handle() {
37 $this->channel = Channel::where('ext_id', '=', 'sra:SRA')->firstOrFail();
38 $this->org = Organization::where('name', '=', 'sra')->firstOrFail();
40 $events = Event::where('external_schedule', 'LIKE', 'sra:%')
41 ->where(function (Builder $query) {
42 $query->whereNull('end');
43 $query->orWhere('end', '<', now());
47 $schedule = Http::get('https://sheets.googleapis.com/v4/spreadsheets/1J6iczoFRxG-NKCMqFugFqkvLSpPssegpIEMiNmFjwvI/values/Races', [
49 'key' => config('google.api_key'),
52 foreach ($events as $event) {
54 $this->line('syncing '.$event->name);
55 $this->syncEvent($event, $schedule['values']);
56 } catch (\Exception $e) {
57 $this->error('error syncing event '.$event->name.': '.$e->getMessage());
61 return Command::SUCCESS;
64 private function syncEvent(Event $event, $schedule) {
65 $tag = substr($event->external_schedule, 4);
66 for ($i = 3; $i < count($schedule); ++$i) {
67 if (!Str::startsWith($schedule[$i][2], $tag)) continue;
68 $this->syncSchedule($event, $schedule[$i]);
73 private function syncSchedule(Event $event, $row) {
74 $ext_id = 'sra:'.$row[0].'-'.$row[1];
75 $episode = Episode::firstWhere('ext_id', '=', $ext_id);
77 $episode = new Episode();
78 $episode->ext_id = $ext_id;
80 $episode->event()->associate($event);
81 if (strlen($row[2]) > (strlen($event->external_schedule) - 1)) {
82 $episode->title = substr($row[2], strlen($event->external_schedule) - 1);
84 $episode->title = $row[2];
86 $start = Carbon::createFromFormat('m/d/Y H:i', $row[0].' '.$row[1], 'America/Detroit')->setTimezone('UTC');
87 if (!$episode->start || $start->ne($episode->start)) {
88 $episode->start = $start;
90 $episode->estimate = 90 * 60;
91 $episode->confirmed = true;
93 $episode->channels()->syncWithoutDetaching([$this->channel->id]);