Revamp the koel:init command

This commit is contained in:
Phan An 2017-12-03 17:54:11 +01:00
parent edc33f99ae
commit e1b68cc53f
8 changed files with 218 additions and 24 deletions

View file

@ -4,6 +4,7 @@ namespace App\Console\Commands;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Jackiedo\DotenvEditor\Facades\DotenvEditor;
class GenerateJWTSecret extends Command class GenerateJWTSecret extends Command
{ {
@ -26,19 +27,15 @@ class GenerateJWTSecret extends Command
* *
* @throws \RuntimeException * @throws \RuntimeException
*/ */
public function fire() public function handle()
{ {
$key = Str::random(32); if (config('jwt.secret')) {
$this->comment('JWT secret exists -- skipping');
$path = base_path('.env'); return;
$content = file_get_contents($path);
if (strpos($content, 'JWT_SECRET=') !== false) {
file_put_contents($path, str_replace('JWT_SECRET=', "JWT_SECRET=$key", $content));
} else {
file_put_contents($path, $content.PHP_EOL."JWT_SECRET=$key");
} }
$this->info('JWT secret key generated. Look for `JWT_SECRET` in .env.'); $this->info('Generating JWT secret');
DotenvEditor::setKey('JWT_SECRET', Str::random(32))->save();
} }
} }

View file

@ -2,11 +2,14 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\Setting;
use App\Models\User; use App\Models\User;
use DB; use DB;
use Exception; use Exception;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Hash;
use Jackiedo\DotenvEditor\Facades\DotenvEditor;
use MediaCache; use MediaCache;
class Init extends Command class Init extends Command
@ -32,15 +35,6 @@ class Init extends Command
*/ */
public function handle() public function handle()
{ {
try {
DB::connection();
} catch (Exception $e) {
$this->error('Unable to connect to database.');
$this->error('Please fill valid database credentials into .env and rerun this command.');
return;
}
$this->comment('Attempting to install or upgrade Koel.'); $this->comment('Attempting to install or upgrade Koel.');
$this->comment('Remember, you can always install/upgrade manually following the guide here:'); $this->comment('Remember, you can always install/upgrade manually following the guide here:');
$this->info('📙 '.config('koel.misc.docs_url').PHP_EOL); $this->info('📙 '.config('koel.misc.docs_url').PHP_EOL);
@ -59,24 +53,146 @@ class Init extends Command
$this->comment('JWT secret exists -- skipping'); $this->comment('JWT secret exists -- skipping');
} }
$dbSetUp = false;
while (!$dbSetUp) {
try {
// Make sure the config cache is cleared before another attempt.
Artisan::call('config:clear');
DB::reconnect()->getPdo();
$dbSetUp = true;
} catch (Exception $e) {
$this->error($e->getMessage());
$this->warn(PHP_EOL.'Koel cannot connect to the database. Let\'s set it up.');
$this->setUpDatabase();
}
}
$this->info('Migrating database'); $this->info('Migrating database');
Artisan::call('migrate', ['--force' => true]); Artisan::call('migrate', ['--force' => true]);
// Clean the media cache, just in case we did any media-related migration // Clean the media cache, just in case we did any media-related migration
MediaCache::clear(); MediaCache::clear();
if (!User::count()) { if (!User::count()) {
$this->setUpAdminAccount();
$this->info('Seeding initial data'); $this->info('Seeding initial data');
Artisan::call('db:seed', ['--force' => true]); Artisan::call('db:seed', ['--force' => true]);
} else { } else {
$this->comment('Data seeded -- skipping'); $this->comment('Data seeded -- skipping');
} }
if (!Setting::get('media_path')) {
$this->setMediaPath();
}
$this->info('Compiling front-end stuff'); $this->info('Compiling front-end stuff');
system('yarn install'); system('yarn install');
$this->comment(PHP_EOL.'🎆 Success! You can now run Koel from localhost with `php artisan serve`.'); $this->comment(PHP_EOL.'🎆 Success! Koel can now be run from localhost with `php artisan serve`.');
if (Setting::get('media_path')) {
$this->comment('You can also scan for media with `php artisan koel:sync`.');
}
$this->comment('Again, for more configuration guidance, refer to'); $this->comment('Again, for more configuration guidance, refer to');
$this->info('📙 '.config('koel.misc.docs_url')); $this->info('📙 '.config('koel.misc.docs_url'));
$this->comment('or open the .env file in the root installation folder.');
$this->comment('Thanks for using Koel. You rock!'); $this->comment('Thanks for using Koel. You rock!');
} }
/**
* Prompt user for valid database credentials and set up the database.
*/
private function setUpDatabase()
{
$config = [
'DB_CONNECTION' => '',
'DB_HOST' => '',
'DB_PORT' => '',
'DB_DATABASE' => '',
'DB_USERNAME' => '',
'DB_PASSWORD' => ''
];
$config['DB_CONNECTION'] = $this->choice(
'Your DB driver of choice',
[
'mysql' => 'MySQL/MariaDB',
'pqsql' => 'PostgreSQL',
'sqlsrv' => 'SQL Server',
'sqlite-e2e' => 'SQLite'
],
'mysql'
);
if ($config['DB_CONNECTION'] === 'sqlite-e2e') {
$config['DB_DATABASE'] = $this->ask('Absolute path to the DB file');
} else {
$config['DB_HOST'] = $this->anticipate('DB host', ['127.0.0.1', 'localhost']);
$config['DB_PORT'] = (string) $this->ask('DB port (leave empty for default)', false);
$config['DB_DATABASE'] = $this->anticipate('DB name', ['koel']);
$config['DB_USERNAME'] = $this->anticipate('DB user', ['koel']);
$config['DB_PASSWORD'] = (string) $this->ask('DB password', false);
}
foreach ($config as $key => $value) {
DotenvEditor::setKey($key, $value);
}
DotenvEditor::save();
// Set the config so that the next DB attempt uses refreshed credentials
config([
'database.default' => $config['DB_CONNECTION'],
"database.connections.{$config['DB_CONNECTION']}.host" => $config['DB_HOST'],
"database.connections.{$config['DB_CONNECTION']}.port" => $config['DB_PORT'],
"database.connections.{$config['DB_CONNECTION']}.database" => $config['DB_DATABASE'],
"database.connections.{$config['DB_CONNECTION']}.username" => $config['DB_USERNAME'],
"database.connections.{$config['DB_CONNECTION']}.password" => $config['DB_PASSWORD'],
]);
}
/**
* Set up the admin account.
*/
private function setUpAdminAccount()
{
$this->info("Let's create the admin account.");
$name = $this->ask("Your name");
$email = $this->ask('Your email address');
$passwordConfirmed = false;
while (!$passwordConfirmed) {
$password = $this->secret('Your desired password');
$confirmation = $this->secret('Again, just to make sure');
if ($confirmation !== $password) {
$this->error('That doesn\'t match. Let\'s try again.');
} else {
$passwordConfirmed = true;
}
}
User::create([
'name' => $name,
'email' => $email,
'password' => Hash::make($password),
'is_admin' => true,
]);
}
/**
* Set the media path via the console.
*/
private function setMediaPath()
{
$this->info('The absolute path to your media directory. If this is skipped (left blank) now, you can set it later via the web interface.');
while (true) {
$path = $this->ask('Media path', false);
if ($path === false) {
return;
}
if (is_dir($path) && is_readable($path)) {
Setting::set('media_path', $path);
return;
}
$this->error('The path does not exist or not readable. Try again.');
}
}
} }

View file

@ -13,7 +13,8 @@
"aws/aws-sdk-php-laravel": "^3.1", "aws/aws-sdk-php-laravel": "^3.1",
"pusher/pusher-php-server": "^2.6", "pusher/pusher-php-server": "^2.6",
"predis/predis": "~1.0", "predis/predis": "~1.0",
"doctrine/dbal": "^2.5" "doctrine/dbal": "^2.5",
"jackiedo/dotenv-editor": "^1.0"
}, },
"require-dev": { "require-dev": {
"fzaninotto/faker": "~1.4", "fzaninotto/faker": "~1.4",

51
composer.lock generated
View file

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "50bc88073f0fb11c1ceeb7041bd2de66", "content-hash": "ac5c20677ba19b8a4e7f4a30592cc77d",
"packages": [ "packages": [
{ {
"name": "aws/aws-sdk-php", "name": "aws/aws-sdk-php",
@ -838,6 +838,55 @@
], ],
"time": "2017-03-20T17:10:46+00:00" "time": "2017-03-20T17:10:46+00:00"
}, },
{
"name": "jackiedo/dotenv-editor",
"version": "1.0.7",
"source": {
"type": "git",
"url": "https://github.com/JackieDo/Laravel-Dotenv-Editor.git",
"reference": "d27e12b8b120d49234d6759810ad06f076ee52cc"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/JackieDo/Laravel-Dotenv-Editor/zipball/d27e12b8b120d49234d6759810ad06f076ee52cc",
"reference": "d27e12b8b120d49234d6759810ad06f076ee52cc",
"shasum": ""
},
"require": {
"illuminate/config": ">=5.0",
"illuminate/container": ">=5.0",
"illuminate/support": ">=5.0",
"php": ">=5.4.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0-dev"
}
},
"autoload": {
"psr-4": {
"Jackiedo\\DotenvEditor\\": "src/Jackiedo/DotenvEditor"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jackie Do",
"email": "anhvudo@gmail.com"
}
],
"description": "The .env file editor tool for Laravel 5+",
"keywords": [
"dotenv",
"dotenv-editor",
"laravel"
],
"time": "2017-06-26T06:36:42+00:00"
},
{ {
"name": "james-heinrich/getid3", "name": "james-heinrich/getid3",
"version": "v1.9.15", "version": "v1.9.15",

View file

@ -156,7 +156,7 @@ return [
App\Providers\DownloadServiceProvider::class, App\Providers\DownloadServiceProvider::class,
App\Providers\BroadcastServiceProvider::class, App\Providers\BroadcastServiceProvider::class,
App\Providers\iTunesServiceProvider::class, App\Providers\iTunesServiceProvider::class,
Jackiedo\DotenvEditor\DotenvEditorServiceProvider::class,
], ],
/* /*
@ -203,6 +203,7 @@ return [
'URL' => Illuminate\Support\Facades\URL::class, 'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class, 'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class, 'View' => Illuminate\Support\Facades\View::class,
'DotenvEditor' => Jackiedo\DotenvEditor\Facades\DotenvEditor::class,
'Media' => App\Facades\Media::class, 'Media' => App\Facades\Media::class,
'MediaCache' => App\Facades\MediaCache::class, 'MediaCache' => App\Facades\MediaCache::class,

27
config/dotenv-editor.php Normal file
View file

@ -0,0 +1,27 @@
<?php
return array(
/*
|----------------------------------------------------------------------
| Auto backup mode
|----------------------------------------------------------------------
|
| This value is used when you save your file content. If value is true,
| the original file will be backed up before save.
*/
'autoBackup' => true,
/*
|----------------------------------------------------------------------
| Backup location
|----------------------------------------------------------------------
|
| This value is used when you backup your file. This value is the sub
| path from root folder of project application.
*/
'backupPath' => base_path('storage/dotenv-editor/backups/')
);

View file

@ -13,7 +13,7 @@ class DatabaseSeeder extends Seeder
Model::unguard(); Model::unguard();
// This must be run first, to check for dependencies // This must be run first, to check for dependencies
$this->call(UserTableSeeder::class); // $this->call(UserTableSeeder::class);
$this->call(ArtistTableSeeder::class); $this->call(ArtistTableSeeder::class);
$this->call(AlbumTableSeeder::class); $this->call(AlbumTableSeeder::class);

3
storage/dotenv-editor/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
/backups
*
!.gitignore