]> git.localhorst.tv Git - alttp.git/blob - app/Console/Commands/TwitchChannelInfo.php
09dc7180e55e5a84e97cd303df96a65cfa49ffce
[alttp.git] / app / Console / Commands / TwitchChannelInfo.php
1 <?php
2
3 namespace App\Console\Commands;
4
5 use App\Models\Channel;
6 use App\Models\TwitchToken;
7 use Illuminate\Console\Command;
8 use Illuminate\Http\Client\RequestException;
9 use Illuminate\Support\Facades\Http;
10
11 class TwitchChannelInfo extends Command {
12
13         /**
14          * The name and signature of the console command.
15          *
16          * @var string
17          */
18         protected $signature = 'twitch:channel-info';
19
20         /**
21          * The console command description.
22          *
23          * @var string
24          */
25         protected $description = 'Refresh twitch channel info';
26
27         /**
28          * Execute the console command.
29          *
30          * @return int
31          */
32         public function handle()
33         {
34                 $this->token = TwitchToken::firstWhere('nick', 'localhorsttv');
35                 if (!$this->token) {
36                         $this->line('please acquire a token for localhorsttv first');
37                         return 1;
38                 }
39                 $channels = Channel::where('twitch_chat', '!=', '')->where('twitch_id', '=', '')->get();
40                 foreach ($channels as $channel) {
41                         try {
42                                 $this->updateChannel($channel);
43                         } catch (RequestException $e) {
44                                 if ($e->response->status() == 401) {
45                                         $this->token->refresh();
46                                         $this->updateChannel($channel);
47                                 }
48                         }
49                 }
50                 return Command::SUCCESS;
51         }
52
53         private function updateChannel(Channel $channel) {
54                 $this->line($channel->twitch_chat);
55                 $login = substr($channel->twitch_chat, 1);
56                 $rsp = $this->token->request()
57                         ->get('/users', [
58                                 'login' => $login,
59                         ])
60                         ->throw();
61                 foreach ($rsp['data'] as $user) {
62                         if ($user['login'] != $login) continue;
63                         $channel->twitch_id = $user['id'];
64                         $channel->save();
65                 }
66         }
67
68         private $token;
69
70 }