X-Git-Url: https://git.localhorst.tv/?a=blobdiff_plain;f=app%2FConsole%2FCommands%2FTwitchChannelInfo.php;h=7b373c8c94ed54fe611280078158799e35002775;hb=f18af7cfb219ab9c07635ea8bbae80f2a9cee78e;hp=09dc7180e55e5a84e97cd303df96a65cfa49ffce;hpb=4caeac216c5e5a044d81b63a8aa5b66451162271;p=alttp.git diff --git a/app/Console/Commands/TwitchChannelInfo.php b/app/Console/Commands/TwitchChannelInfo.php index 09dc718..7b373c8 100644 --- a/app/Console/Commands/TwitchChannelInfo.php +++ b/app/Console/Commands/TwitchChannelInfo.php @@ -4,6 +4,7 @@ namespace App\Console\Commands; use App\Models\Channel; use App\Models\TwitchToken; +use GuzzleHttp\Psr7\Query; use Illuminate\Console\Command; use Illuminate\Http\Client\RequestException; use Illuminate\Support\Facades\Http; @@ -36,10 +37,14 @@ class TwitchChannelInfo extends Command { $this->line('please acquire a token for localhorsttv first'); return 1; } + if ($this->token->hasExpired()) { + $this->line('access token has expired, refreshing'); + $this->token->refresh(); + } $channels = Channel::where('twitch_chat', '!=', '')->where('twitch_id', '=', '')->get(); foreach ($channels as $channel) { try { - $this->updateChannel($channel); + $this->updateChannelId($channel); } catch (RequestException $e) { if ($e->response->status() == 401) { $this->token->refresh(); @@ -47,16 +52,24 @@ class TwitchChannelInfo extends Command { } } } + Channel::where('twitch_id', '!=', '') + ->where(function($query) { + $query->where('join', true); + $query->orWhere('chat', true); + }) + ->chunk(100, function ($channels) { + $this->updateChannelInfos($channels); + }); return Command::SUCCESS; } - private function updateChannel(Channel $channel) { + private function updateChannelId(Channel $channel) { $this->line($channel->twitch_chat); $login = substr($channel->twitch_chat, 1); $rsp = $this->token->request() - ->get('/users', [ + ->get('/users', Query::build([ 'login' => $login, - ]) + ])) ->throw(); foreach ($rsp['data'] as $user) { if ($user['login'] != $login) continue; @@ -65,6 +78,33 @@ class TwitchChannelInfo extends Command { } } + private function updateChannelInfos($channels) { + $ids = $channels->pluck('twitch_id')->toArray(); + $rsp = $this->token->request() + ->get('/streams', Query::build([ + 'user_id' => $ids, + ])) + ->throw(); + foreach ($channels as $channel) { + $data = null; + foreach ($rsp['data'] as $info) { + if ($info['user_id'] == $channel->twitch_id) { + $data = $info; + break; + } + } + if (is_null($data)) { + $channel->twitch_live = false; + $channel->twitch_viewers = 0; + } else { + $channel->twitch_live = true; + $channel->twitch_category = $data['game_id']; + $channel->twitch_viewers = $data['viewer_count']; + } + $channel->save(); + } + } + private $token; }