channel = Channel::where('ext_id', '=', 'sra:SRA')->firstOrFail(); $this->org = Organization::where('name', '=', 'sra')->firstOrFail(); $events = Event::where('external_schedule', 'LIKE', 'sra:%') ->where(function (Builder $query) { $query->whereNull('end'); $query->orWhere('end', '>', now()); }) ->get(); $schedule = Http::get('https://sheets.googleapis.com/v4/spreadsheets/1J6iczoFRxG-NKCMqFugFqkvLSpPssegpIEMiNmFjwvI/values/Races', [ 'alt' => 'json', 'key' => config('google.api_key'), ])->json(); foreach ($events as $event) { try { $this->line('syncing '.$event->name); $this->syncEvent($event, $schedule['values']); } catch (\Exception $e) { $this->error('error syncing event '.$event->name.': '.$e->getMessage()); } } return Command::SUCCESS; } private function syncEvent(Event $event, $schedule) { $tag = substr($event->external_schedule, 4); for ($i = 3; $i < count($schedule); ++$i) { if (!Str::startsWith($schedule[$i][2], $tag)) continue; $this->syncSchedule($event, $schedule[$i]); } } private function syncSchedule(Event $event, $row) { $ext_id = 'sra:'.$row[0].'-'.$row[1]; $episode = Episode::firstWhere('ext_id', '=', $ext_id); if (!$episode) { $episode = new Episode(); $episode->ext_id = $ext_id; } $episode->event()->associate($event); if (strlen($row[2]) > (strlen($event->external_schedule) - 1)) { $episode->title = substr($row[2], strlen($event->external_schedule) - 1); } else { $episode->title = $row[2]; } $start = Carbon::createFromFormat('m/d/Y H:i', $row[0].' '.$row[1], 'America/Detroit')->setTimezone('UTC'); if (!$episode->start || $start->ne($episode->start)) { $episode->start = $start; } $episode->estimate = 90 * 60; $episode->confirmed = true; $episode->save(); $episode->channels()->syncWithoutDetaching([$this->channel->id]); } private $channel; private $org; }