Updating code style to PSR-2

This commit is contained in:
ilumos 2017-08-21 21:38:32 +01:00
parent 5498ff1a30
commit 800034651c
11 changed files with 141 additions and 147 deletions

View file

@ -1,19 +1,23 @@
#!/usr/bin/env php
<?php
use Dotenv\Dotenv;
use Illuminate\Console\Application;
use Illuminate\Container\Container;
use Illuminate\Events\Dispatcher;
use Illuminate\Database\Capsule\Manager as Capsule;
use Dotenv\Dotenv;
use Zeropingheroes\LancacheAutofill\Console\Commands\Steam\{UpdateAppList, SearchApps, QueueApp, ShowQueue, Dequeue, Requeue, AuthoriseAccount, StartDownloading};
use Zeropingheroes\LancacheAutofill\Console\Commands\{InitialiseDatabase, InitialiseDownloadsDirectory};
use Illuminate\Events\Dispatcher;
use Zeropingheroes\LancacheAutofill\Console\Commands\{
InitialiseDatabase, InitialiseDownloadsDirectory
};
use Zeropingheroes\LancacheAutofill\Console\Commands\Steam\{
AuthoriseAccount, Dequeue, QueueApp, Requeue, SearchApps, ShowQueue, StartDownloading, UpdateAppList
};
// Load Composer's autoloader
if (file_exists($a = __DIR__.'/../../autoload.php')) {
require_once $a;
} else {
}
else {
require_once __DIR__.'/vendor/autoload.php';
}
@ -22,7 +26,7 @@ $dotenv = new Dotenv(__DIR__);
$dotenv->load();
$dotenv->required(['DOWNLOADS_DIRECTORY', 'STEAMCMD_PATH', 'DEFAULT_STEAM_USER']);
if ( ! file_exists(getenv('STEAMCMD_PATH')) ) {
if (!file_exists(getenv('STEAMCMD_PATH'))) {
die('SteamCMD not found - please check the STEAMCMD_PATH environment variable is set correctly');
}
@ -32,8 +36,8 @@ $app = new Application(new Container, new Dispatcher, '5.4');
// Set up the SQLite database connection
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'sqlite',
'database' => 'database.sqlite'
'driver' => 'sqlite',
'database' => 'database.sqlite',
]);
$capsule->setAsGlobal();

View file

@ -33,7 +33,8 @@ class InitialiseDatabase extends Command
$this->info('Removing existing database tables');
Capsule::schema()->dropIfExists('steam_apps');
Capsule::schema()->dropIfExists('steam_queue');
} else {
}
else {
die();
}

View file

@ -3,9 +3,7 @@
namespace Zeropingheroes\LancacheAutofill\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Database\Capsule\Manager as Capsule;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
class InitialiseDownloadsDirectory extends Command
{
@ -29,14 +27,15 @@ class InitialiseDownloadsDirectory extends Command
* @return mixed
*/
public function handle()
{
{
if ($this->confirm('Are you sure you wish to remove all files and folders in "'.getenv('DOWNLOADS_DIRECTORY').'"?')) {
$remove = new Process('rm -r '.getenv('DOWNLOADS_DIRECTORY'));
$remove->run(function ($type, $buffer) {
if (Process::ERR === $type) {
$this->error(str_replace(["\r", "\n"], '', $buffer));
} else {
}
else {
$this->line(str_replace(["\r", "\n"], '', $buffer));
}
@ -45,7 +44,7 @@ class InitialiseDownloadsDirectory extends Command
$create = new Process('mkdir -p '.getenv('DOWNLOADS_DIRECTORY'));
$create->run();
if( $remove->isSuccessful() && $create->isSuccessful() ) {
if ($remove->isSuccessful() && $create->isSuccessful()) {
$this->info('Successfully removed all files and folders in "'.getenv('DOWNLOADS_DIRECTORY').'"');
die();
}

View file

@ -3,9 +3,7 @@
namespace Zeropingheroes\LancacheAutofill\Console\Commands\Steam;
use Illuminate\Console\Command;
use Illuminate\Database\Capsule\Manager as Capsule;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
class AuthoriseAccount extends Command
{
@ -32,15 +30,15 @@ class AuthoriseAccount extends Command
{
$account = $this->argument('account') ?? getenv('DEFAULT_STEAM_USER');
$this->info('Authorising account '. $account);
$this->info('Authorising account '.$account);
$password = $this->secret('Please enter your password');
$steamGuardCode = $this->ask('Please enter your Steam Guard code', false);
// Start SteamCMD with the arguments, using "unbuffer"
// as SteamCMD buffers output when it is not run in a
// tty, which prevents us showing output line by line
$process = new Process('unbuffer '. getenv('STEAMCMD_PATH') . ' +login ' . $account . ' ' . $password . ' '. $steamGuardCode .' +quit');
$process = new Process('unbuffer '.getenv('STEAMCMD_PATH').' +login '.$account.' '.$password.' '.$steamGuardCode.' +quit');
// Set a short timeout for this interactive login prompt
$process->setTimeout(120);
@ -50,9 +48,9 @@ class AuthoriseAccount extends Command
});
if (!$process->isSuccessful()) {
$this->error('Failed to authorise Steam account ' . $account);
$this->error('Failed to authorise Steam account '.$account);
die();
}
$this->info('Successfully authorised Steam account ' . $account);
$this->info('Successfully authorised Steam account '.$account);
}
}

View file

@ -44,44 +44,47 @@ class Dequeue extends Command
* @return mixed
*/
public function handle()
{
if( $this->option('platform') && ! in_array($this->option('platform'), $this::PLATFORMS))
{
$this->error('Invalid platform specified. Available platforms are: '. implode(' ', $this::PLATFORMS));
{
if ($this->option('platform') && !in_array($this->option('platform'), $this::PLATFORMS)) {
$this->error('Invalid platform specified. Available platforms are: '.implode(' ', $this::PLATFORMS));
die();
}
if( $this->option('status') && ! in_array($this->option('status'), $this::STATUSES))
{
$this->error('Invalid status specified. Available statuses are: '. implode(' ', $this::STATUSES));
if ($this->option('status') && !in_array($this->option('status'), $this::STATUSES)) {
$this->error('Invalid status specified. Available statuses are: '.implode(' ', $this::STATUSES));
die();
}
$query = Capsule::table('steam_queue');
if( $this->option('app_id') )
if ($this->option('app_id')) {
$query->where('appid', $this->option('app_id'));
}
if( $this->option('platform') )
if ($this->option('platform')) {
$query->where('platform', $this->option('platform'));
}
if( $this->option('account') )
if ($this->option('account')) {
$query->where('account', $this->option('account'));
}
if( $this->option('status') )
if ($this->option('status')) {
$query->where('status', $this->option('status'));
}
// If no options were specified, ask for confirmation
if( ! array_filter($this->options()) && ! $this->confirm('Are you sure you want to clear the download queue?') )
if (!array_filter($this->options()) && !$this->confirm('Are you sure you want to clear the download queue?')) {
die();
}
$affected = $query->delete();
if( ! $affected ) {
if (!$affected) {
$this->error('No items in the queue match the provided criteria');
die();
}
$this->info('Removed ' . $affected .' item(s) from the download queue');
$this->info('Removed '.$affected.' item(s) from the download queue');
}
}

View file

@ -40,53 +40,49 @@ class QueueApp extends Command
{
// If no platforms are specified, default to windows
$platforms = explode(',', $this->argument('platforms')) ?? ['windows'];
// If no account is specified, default to the account set in the .env file
$account = $this->option('account') ?? getenv('DEFAULT_STEAM_USER');
if( array_diff($platforms, $this::PLATFORMS))
{
$this->error('Invalid platform(s) specified. Available platforms are: '. implode(' ', $this::PLATFORMS));
if (array_diff($platforms, $this::PLATFORMS)) {
$this->error('Invalid platform(s) specified. Available platforms are: '.implode(' ', $this::PLATFORMS));
die();
}
// Check if app with specified ID exists
$app = Capsule::table('steam_apps')
->where('appid', $this->argument('app_id'))
->first();
if( ! $app ) {
->where('appid', $this->argument('app_id'))
->first();
if (!$app) {
$this->error('Steam app with ID '.$this->argument('app_id').' not found');
die();
}
// Queue each platform separately
foreach( $platforms as $platform )
{
foreach ($platforms as $platform) {
$alreadyQueued = Capsule::table('steam_queue')
->where('appid', $app->appid)
->where('platform', $platform)
->count();
if( $alreadyQueued )
{
$this->error('Steam app "' . $app->name .'" on platform "'.$platform.'" already in download queue');
continue;
->where('appid', $app->appid)
->where('platform', $platform)
->count();
if ($alreadyQueued) {
$this->error('Steam app "'.$app->name.'" on platform "'.$platform.'" already in download queue');
continue;
}
// Add the app to the download queue, specifying the platform and account
Capsule::table('steam_queue')->insert([
'appid' => $app->appid,
'name' => $app->name,
'platform' => $platform,
'account' => $account,
'status'=> 'queued'
'name' => $app->name,
'platform' => $platform,
'account' => $account,
'status' => 'queued',
]);
$this->info('Added Steam app "' . $app->name .'" on platform "'.$platform.'" from Steam account "'.$account.'" to download queue');
}
$this->info('Added Steam app "'.$app->name.'" on platform "'.$platform.'" from Steam account "'.$account.'" to download queue');
}
}

View file

@ -34,29 +34,29 @@ class Requeue extends Command
* @return mixed
*/
public function handle()
{
if( $this->argument('status') && ! in_array($this->argument('status'), $this::STATUSES))
{
$this->error('Invalid status specified. Available statuses are: '. implode(' ', $this::STATUSES));
{
if ($this->argument('status') && !in_array($this->argument('status'), $this::STATUSES)) {
$this->error('Invalid status specified. Available statuses are: '.implode(' ', $this::STATUSES));
die();
}
$query = Capsule::table('steam_queue')
->where('status','<>','queued');
->where('status', '<>', 'queued');
if( $this->argument('status') )
if ($this->argument('status')) {
$query->where('status', $this->argument('status'));
}
$affected = $query->update([
'status' => 'queued',
'message' => null,
]);
if( ! $affected ) {
if (!$affected) {
$this->error('No items in the queue match the provided criteria');
die();
}
$this->info('Requeued ' . $affected .' item(s) in the download queue');
$this->info('Requeued '.$affected.' item(s) in the download queue');
}
}

View file

@ -27,14 +27,13 @@ class SearchApps extends Command
* @return mixed
*/
public function handle()
{
{
$apps = Capsule::table('steam_apps')
->where('name', 'like', '%' . $this->argument('name') . '%')
->get();
foreach($apps as $app)
{
$this->info($app->appid ."\t". $app->name);
->where('name', 'like', '%'.$this->argument('name').'%')
->get();
foreach ($apps as $app) {
$this->info($app->appid."\t".$app->name);
}
}
}

View file

@ -34,30 +34,26 @@ class ShowQueue extends Command
* @return mixed
*/
public function handle()
{
if( $this->argument('status') && ! in_array($this->argument('status'), $this::STATUSES))
{
$this->error('Invalid status specified. Available statuses are: '. implode(' ', $this::STATUSES));
{
if ($this->argument('status') && !in_array($this->argument('status'), $this::STATUSES)) {
$this->error('Invalid status specified. Available statuses are: '.implode(' ', $this::STATUSES));
die();
}
// If a status is specified, display only apps of that status
if( $this->argument('status') )
{
$this->displayAppsWithStatus( $this->argument('status') );
if ($this->argument('status')) {
$this->displayAppsWithStatus($this->argument('status'));
die();
}
foreach($this::STATUSES as $status)
{
foreach ($this::STATUSES as $status) {
$this->displayAppsWithStatus($status);
}
}
private function displayAppsWithStatus( $status )
private function displayAppsWithStatus($status)
{
switch($status)
{
switch ($status) {
case 'queued':
$messageStyle = 'comment';
break;
@ -72,19 +68,19 @@ class ShowQueue extends Command
}
$apps = Capsule::table('steam_queue')
->where('status', $status)
->orderBy('message')
->get();
->where('status', $status)
->orderBy('message')
->get();
if ( ! count($apps) )
if (!count($apps)) {
return;
}
$this->{$messageStyle}(ucfirst($status) . ':');
$this->{$messageStyle}(ucfirst($status).':');
$this->{$messageStyle}( "DB ID\tApp ID\tApp Name\tPlatform\tSteam Account\tMessage" );
foreach( $apps as $app )
{
$this->{$messageStyle}( $app->id ."\t". $app->appid ."\t". $app->name . "\t" . $app->platform . "\t" . $app->account . "\t" . $app->message );
$this->{$messageStyle}("DB ID\tApp ID\tApp Name\tPlatform\tSteam Account\tMessage");
foreach ($apps as $app) {
$this->{$messageStyle}($app->id."\t".$app->appid."\t".$app->name."\t".$app->platform."\t".$app->account."\t".$app->message);
}
}

View file

@ -4,8 +4,8 @@ namespace Zeropingheroes\LancacheAutofill\Console\Commands\Steam;
use Illuminate\Console\Command;
use Illuminate\Database\Capsule\Manager as Capsule;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
class StartDownloading extends Command
{
@ -30,58 +30,58 @@ class StartDownloading extends Command
*/
public function handle()
{
if ( $this->queuedItems() == 0 ) {
if ($this->queuedItems() == 0) {
$this->error('Nothing to download');
$this->info('Run "./lancache-autofill steam:show-queue" to see the queue');
die();
}
// Check all Steam accounts specified in the queue are authorised
foreach ($this->accountsInQueue() as $account ) {
$process = new Process('unbuffer '. getenv('STEAMCMD_PATH') . ' +@NoPromptForPassword 1 +login ' . $account . ' +quit');
foreach ($this->accountsInQueue() as $account) {
$process = new Process('unbuffer '.getenv('STEAMCMD_PATH').' +@NoPromptForPassword 1 +login '.$account.' +quit');
// Show SteamCMD output line by line
$process->run(function ($type, $buffer) {
$this->line(str_replace(["\r", "\n"], '', $buffer));
});
});
if (!$process->isSuccessful()) {
$this->error('Steam account ' . $account . ' is not authorised');
$this->error('Steam account '.$account.' is not $process authorised');
$this->comment('Please run "./lancache-autofill steam:authorise-account '.$account.'"');
die();
}
$this->info('Steam account ' . $account . ' is authorised');
$this->info('Steam account '.$account.' is authorised');
}
// Loop through all apps in the queue
while( $app = $this->nextApp() ) {
$this->info('Starting download of ' . $app->name . ' for ' . $app->platform . ' from Steam account '. $app->account);
while ($app = $this->nextApp()) {
$this->info('Starting download of '.$app->name.' for '.$app->platform.' from Steam account '.$app->account);
try {
$arguments =
[
'login' => $app->account,
'@sSteamCmdForcePlatformType' => $app->platform,
'@NoPromptForPassword' => 1,
'force_install_dir' => getenv('DOWNLOADS_DIRECTORY').'/'.$app->platform.'/'.$app->appid,
'app_license_request' => $app->appid,
'app_update' => $app->appid,
'quit' => null,
];
$arguments =
[
'login' => $app->account,
'@sSteamCmdForcePlatformType' => $app->platform,
'@NoPromptForPassword' => 1,
'force_install_dir' => getenv('DOWNLOADS_DIRECTORY').'/'.$app->platform.'/'.$app->appid,
'app_license_request' => $app->appid,
'app_update' => $app->appid,
'quit' => null,
];
$argumentString = null;
// Build argument string
foreach($arguments as $argument => $value) {
foreach ($arguments as $argument => $value) {
$argumentString .= "+$argument $value ";
}
// Start SteamCMD with the arguments, using "unbuffer"
// as SteamCMD buffers output when it is not run in a
// tty, which prevents us showing output line by line
$process = new Process('unbuffer '. getenv('STEAMCMD_PATH') . ' ' . $argumentString);
$process = new Process('unbuffer '.getenv('STEAMCMD_PATH').' '.$argumentString);
// Set a long timeout as downloading could take a while
$process->setTimeout(14400);
$process->setIdleTimeout(60);
@ -91,22 +91,23 @@ class StartDownloading extends Command
$this->line(str_replace(["\r", "\n"], '', $buffer));
});
if (!$process->isSuccessful())
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
$this->info('Successfully completed download of ' . $app->name . ' for ' . $app->platform . ' from Steam account '. $app->account);
$this->info('Successfully completed download of '.$app->name.' for '.$app->platform.' from Steam account '.$app->account);
$this->updateQueueItemStatus($app->id, 'completed');
} catch (ProcessFailedException $e) {
// Create an array of SteamCMD's output (removing excess newlines)
$lines = explode(PHP_EOL,trim($process->getOutput()));
$lines = explode(PHP_EOL, trim($process->getOutput()));
// Get the last line (removing ANSI codes)
$lastLine = preg_replace('#\x1b\[[0-9;]*[a-zA-Z]#', '', end($lines));
$this->error('Failed to download ' . $app->name . ' for ' . $app->platform. ' from Steam account '. $app->account);
$this->updateQueueItemStatus($app->id, 'failed', $lastLine );
$this->error('Failed to download '.$app->name.' for '.$app->platform.' from Steam account '.$app->account);
$this->updateQueueItemStatus($app->id, 'failed', $lastLine);
}
}
}
@ -114,29 +115,29 @@ class StartDownloading extends Command
private function nextApp()
{
return Capsule::table('steam_queue')
->where('status', 'queued')
->first();
->where('status', 'queued')
->first();
}
private function updateQueueItemStatus( $id, $status, $message = null )
private function updateQueueItemStatus($id, $status, $message = null)
{
return Capsule::table('steam_queue')
->where('id', $id)
->update(['status' => $status, 'message' => $message]);
->where('id', $id)
->update(['status' => $status, 'message' => $message]);
}
private function queuedItems()
{
return Capsule::table('steam_queue')
->where('status', 'queued')
->count();
->where('status', 'queued')
->count();
}
private function accountsInQueue()
{
return Capsule::table('steam_queue')
->where('status', 'queued')
->distinct('account')
->pluck('account');
->where('status', 'queued')
->distinct('account')
->pluck('account');
}
}

View file

@ -2,10 +2,9 @@
namespace Zeropingheroes\LancacheAutofill\Console\Commands\Steam;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Database\Capsule\Manager as Capsule;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
class UpdateAppList extends Command
{
@ -39,21 +38,20 @@ class UpdateAppList extends Command
{
$this->info('Clearing apps from database');
Capsule::table('steam_apps')->truncate();
$this->info('Downloading app list from Steam Web API');
$client = new Client();
$result = $client->request('GET', self::STEAM_APP_LIST_URL);
if ( $result->getStatusCode() != 200 )
{
if ($result->getStatusCode() != 200) {
$this->error('Steam Web API unreachable');
die();
}
$response = json_decode($result->getBody(), TRUE);
$response = json_decode($result->getBody(), true);
$apps = $response['applist']['apps'];
// Laravel's SQLite driver can only insert a maximum of 500 records
// at a time in one compound INSERT statements, so we chunk the list
// of ~50,000 apps into chunks of 500
@ -63,13 +61,12 @@ class UpdateAppList extends Command
$bar->setFormat("%bar% %percent%%");
$this->info('Inserting records into database');
foreach($appsChunked as $appChunk)
{
foreach ($appsChunked as $appChunk) {
Capsule::table('steam_apps')->insert($appChunk);
$bar->advance();
}
$bar->finish();
$this->info(PHP_EOL . 'Done');
$this->info(PHP_EOL.'Done');
}
}