vid-queue/app/Commands/TraktLogin.php

60 lines
1.8 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Commands;
use App\Services\Trakt;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Filesystem\Filesystem;
class TraktLogin extends Command
{
protected $signature = 'trakt:login';
protected $description = 'Login and get new token.';
public function handle(Trakt $trakt, Repository $config, Filesystem $files): int
{
$data = [
'client_id' => $config->get('trakt.app_id'),
];
$resp = $trakt->requestNoAuth()->post('/oauth/device/code', $data);
if (!$resp->ok()) {
$this->line('Failed to get device code: ' . $resp->status());
$this->line($resp->body());
return static::FAILURE;
}
$body = $resp->json();
$this->line("Visit {$body['verification_url']} and enter the code {$body['user_code']}");
if (!$this->confirm('Ready to continue?')) {
return static::FAILURE;
}
$this->line("TRAKT_DEVICE_RESP='" . json_encode($body) . "'");
$config->set('trakt.login.device', $body);
$data = [
'client_id' => $config->get('trakt.app_id'),
'client_secret' => $config->get('trakt.app_secret'),
'code' => $body['device_code'],
];
$resp = $trakt->requestNoAuth()->post('/oauth/device/token', $data);
if (!$resp->ok()) {
$this->line('Failed to get new token');
return static::FAILURE;
}
$body = $resp->json();
$this->line("TRAKT_OAUTH_RESP='" . json_encode($body) . "'");
$this->line('TRAKT_OAUTH_TOKEN=' . $body['access_token']);
$config->set('trakt.login.oauth', $body);
$files->put($config->get('trakt.path'), json_encode($config->get('trakt'), JSON_PRETTY_PRINT));
return static::SUCCESS;
}
}