]> git.localhorst.tv Git - alttp.git/blob - app/Console/Commands/SyncSpeedGaming.php
4d2cb9cb27cb9a4a9195f21c93f3851238a6f9c2
[alttp.git] / app / Console / Commands / SyncSpeedGaming.php
1 <?php
2
3 namespace App\Console\Commands;
4
5 use App\Models\Channel;
6 use App\Models\Episode;
7 use App\Models\EpisodePlayer;
8 use App\Models\Event;
9 use App\Models\Organization;
10 use App\Models\User;
11 use Carbon\Carbon;
12 use Illuminate\Console\Command;
13 use Illuminate\Database\Eloquent\Builder;
14 use Illuminate\Support\Facades\Http;
15
16 class SyncSpeedGaming extends Command {
17
18         /**
19          * The name and signature of the console command.
20          *
21          * @var string
22          */
23         protected $signature = 'sync:speedgaming';
24
25         /**
26          * The console command description.
27          *
28          * @var string
29          */
30         protected $description = 'Synchronize SpeedGaming schedule';
31
32         /**
33          * Execute the console command.
34          *
35          * @return int
36          */
37         public function handle() {
38                 $this->org = Organization::where('name', '=', 'sg')->firstOrFail();
39
40                 $events = Event::where('external_schedule', 'LIKE', 'sg:%')
41                         ->where(function (Builder $query) {
42                                 $query->whereNull('end');
43                                 $query->orWhere('end', '<', now());
44                         })
45                         ->get();
46
47                 foreach ($events as $event) {
48                         try {
49                                 $this->line('syncing '.$event->name);
50                                 $this->syncEvent($event);
51                         } catch (\Exception $e) {
52                                 $this->error('error syncing event '.$event->name.': '.$e->getMessage());
53                         }
54                 }
55
56                 return 0;
57         }
58
59         private function syncEvent(Event $event) {
60                 $sgHandle = substr($event->external_schedule, 3);
61                 $from = now()->sub(1, 'day');
62                 $to = now()->add(6, 'day');
63                 $sgSchedule = HTTP::get('https://speedgaming.org/api/schedule/', [
64                         'event' => $sgHandle,
65                         'from' => $from->toIso8601String(),
66                         'to' => $to->toIso8601String(),
67                 ])->json();
68                 $this->purgeSchedule($event, $from, $to, $sgSchedule);
69                 foreach ($sgSchedule as $sgEntry) {
70                         try {
71                                 $this->syncSchedule($event, $sgEntry);
72                         } catch (Exception $e) {
73                                 $this->error('error syncing episode '.$sgEntry['id'].': '.$e->getMessage());
74                         }
75                 }
76         }
77
78         private function purgeSchedule(Event $event, $from, $to, $sgSchedule) {
79                 $ext_ids = [];
80                 foreach ($sgSchedule as $sgEntry) {
81                         $ext_ids[] = 'sg:'.$sgEntry['id'];
82                 }
83                 $to_purge = $event->episodes()
84                         ->where('start', '>=', $from)
85                         ->where('start', '<=', $to)
86                         ->whereNotIn('ext_id', $ext_ids);
87                 foreach ($to_purge->get() as $episode) {
88                         $episode->players()->delete();
89                 }
90                 $to_purge->delete();
91         }
92
93         private function syncSchedule(Event $event, $sgEntry) {
94                 $ext_id = 'sg:'.$sgEntry['id'];
95                 $episode = Episode::firstWhere('ext_id', '=', $ext_id);
96                 if (!$episode) {
97                         $episode = new Episode();
98                         $episode->ext_id = $ext_id;
99                 }
100                 $episode->event()->associate($event);
101                 $episode->title = $sgEntry['match1']['title'];
102                 $start = Carbon::createFromFormat('Y-m-d\TH:i:sP', $sgEntry['when']);
103                 if ($start->ne($episode->start)) {
104                         $episode->start = $start;
105                 }
106                 $episode->estimate = $sgEntry['length'] * 60;
107                 $episode->confirmed = $sgEntry['approved'];
108                 $episode->comment = $sgEntry['match1']['note'];
109                 $episode->save();
110
111                 $this->purgeChannels($episode, $sgEntry);
112                 $channelIds = [];
113                 foreach ($sgEntry['channels'] as $sgChannel) {
114                         if ($sgChannel['initials'] == 'NONE') continue;
115                         try {
116                                 $channel = $this->syncChannel($episode, $sgChannel);
117                                 $channelIds[] = $channel->id;
118                         } catch (Exception $e) {
119                                 $this->error('error syncing channel '.$sgChannel['id'].': '.$e->getMessage());
120                         }
121                 }
122                 if (!empty($channelIds)) {
123                         $episode->channels()->syncWithoutDetaching($channelIds);
124                 }
125
126                 $this->purgePlayers($episode, $sgEntry);
127                 foreach ($sgEntry['match1']['players'] as $sgPlayer) {
128                         try {
129                                 $this->syncPlayer($episode, $sgPlayer);
130                         } catch (Exception $e) {
131                                 $this->error('error syncing player '.$sgPlayer['id'].': '.$e->getMessage());
132                         }
133                 }
134         }
135
136         private function purgeChannels(Episode $episode, $sgEntry) {
137                 $ext_ids = [];
138                 foreach ($sgEntry['channels'] as $sgChannel) {
139                         $ext_ids[] = 'sg:'.$sgChannel['id'];
140                 }
141                 $episode->channels()
142                   ->where('ext_id', 'LIKE', 'sg:%')
143                   ->whereNotIn('ext_id', $ext_ids)
144                   ->detach();
145         }
146
147         private function syncChannel(Episode $episode, $sgChannel) {
148                 $ext_id = 'sg:'.$sgChannel['id'];
149                 $channel = $this->org->channels()->firstWhere('ext_id', '=', $ext_id);
150                 if (!$channel) {
151                         $channel = new Channel();
152                         $channel->ext_id = $ext_id;
153                         $channel->organization()->associate($this->org);
154                 }
155                 $channel->short_name = $sgChannel['initials'];
156                 $channel->title = $sgChannel['name'];
157                 $channel->stream_link = 'https://twitch.tv/'.strtolower($sgChannel['name']);
158                 $channel->languages = [$sgChannel['language']];
159                 $channel->save();
160                 return $channel;
161         }
162
163         private function purgePlayers(Episode $episode, $sgEntry) {
164                 $ext_ids = [];
165                 foreach ($sgEntry['match1']['players'] as $sgPlayer) {
166                         $ext_ids[] = 'sg:'.$sgPlayer['id'];
167                 }
168                 $episode->players()->whereNotIn('ext_id', $ext_ids)->delete();
169         }
170
171         private function syncPlayer(Episode $episode, $sgPlayer) {
172                 $ext_id = 'sg:'.$sgPlayer['id'];
173                 $player = $episode->players()->firstWhere('ext_id', '=', $ext_id);
174                 if (!$player) {
175                         $player = new EpisodePlayer();
176                         $player->ext_id = $ext_id;
177                         $player->episode()->associate($episode);
178                 }
179                 $user = $this->getUserBySGPlayer($sgPlayer);
180                 if ($user) {
181                         $player->user()->associate($user);
182                 } else {
183                         $player->user()->disassociate();
184                 }
185                 if (!empty($sgPlayer['displayName'])) {
186                         $player->name_override = $sgPlayer['displayName'];
187                 }
188                 if (!empty($sgPlayer['streamingFrom'])) {
189                         $player->stream_override = strtolower($sgPlayer['streamingFrom']);
190                 }
191                 $player->save();
192         }
193
194         private function getUserBySGPlayer($player) {
195                 if (!empty($player['discordId'])) {
196                         $user = User::find($player['discordId']);
197                         if ($user) return $user;
198                 }
199                 if (!empty($player['discordTag'])) {
200                         $tag = explode('#', $player['discordTag']);
201                         $user = User::firstWhere([
202                                 ['username', 'LIKE', $tag[0]],
203                                 ['username', 'LIKE', $tag[1]],
204                         ]);
205                         if ($user) return $user;
206                 }
207                 return null;
208         }
209
210         private $org;
211
212 }