]> git.localhorst.tv Git - alttp.git/blobdiff - app/Console/Commands/TwitchChannelInfo.php
endpoint for twitch leaderboard
[alttp.git] / app / Console / Commands / TwitchChannelInfo.php
diff --git a/app/Console/Commands/TwitchChannelInfo.php b/app/Console/Commands/TwitchChannelInfo.php
new file mode 100644 (file)
index 0000000..09dc718
--- /dev/null
@@ -0,0 +1,70 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Models\Channel;
+use App\Models\TwitchToken;
+use Illuminate\Console\Command;
+use Illuminate\Http\Client\RequestException;
+use Illuminate\Support\Facades\Http;
+
+class TwitchChannelInfo extends Command {
+
+       /**
+        * The name and signature of the console command.
+        *
+        * @var string
+        */
+       protected $signature = 'twitch:channel-info';
+
+       /**
+        * The console command description.
+        *
+        * @var string
+        */
+       protected $description = 'Refresh twitch channel info';
+
+       /**
+        * Execute the console command.
+        *
+        * @return int
+        */
+       public function handle()
+       {
+               $this->token = TwitchToken::firstWhere('nick', 'localhorsttv');
+               if (!$this->token) {
+                       $this->line('please acquire a token for localhorsttv first');
+                       return 1;
+               }
+               $channels = Channel::where('twitch_chat', '!=', '')->where('twitch_id', '=', '')->get();
+               foreach ($channels as $channel) {
+                       try {
+                               $this->updateChannel($channel);
+                       } catch (RequestException $e) {
+                               if ($e->response->status() == 401) {
+                                       $this->token->refresh();
+                                       $this->updateChannel($channel);
+                               }
+                       }
+               }
+               return Command::SUCCESS;
+       }
+
+       private function updateChannel(Channel $channel) {
+               $this->line($channel->twitch_chat);
+               $login = substr($channel->twitch_chat, 1);
+               $rsp = $this->token->request()
+                       ->get('/users', [
+                               'login' => $login,
+                       ])
+                       ->throw();
+               foreach ($rsp['data'] as $user) {
+                       if ($user['login'] != $login) continue;
+                       $channel->twitch_id = $user['id'];
+                       $channel->save();
+               }
+       }
+
+       private $token;
+
+}