Skip to content

Commit

Permalink
Revamp the koel:init command
Browse files Browse the repository at this point in the history
  • Loading branch information
phanan committed Dec 3, 2017
1 parent edc33f9 commit e1b68cc
Show file tree
Hide file tree
Showing 8 changed files with 218 additions and 24 deletions.
17 changes: 7 additions & 10 deletions app/Console/Commands/GenerateJWTSecret.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Jackiedo\DotenvEditor\Facades\DotenvEditor;

class GenerateJWTSecret extends Command
{
Expand All @@ -26,19 +27,15 @@ class GenerateJWTSecret extends Command
*
* @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');
$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");
return;
}

$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();
}
}
136 changes: 126 additions & 10 deletions app/Console/Commands/Init.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@

namespace App\Console\Commands;

use App\Models\Setting;
use App\Models\User;
use DB;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Hash;
use Jackiedo\DotenvEditor\Facades\DotenvEditor;
use MediaCache;

class Init extends Command
Expand All @@ -32,15 +35,6 @@ class Init extends Command
*/
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('Remember, you can always install/upgrade manually following the guide here:');
$this->info('📙 '.config('koel.misc.docs_url').PHP_EOL);
Expand All @@ -59,24 +53,146 @@ public function handle()
$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');
Artisan::call('migrate', ['--force' => true]);
// Clean the media cache, just in case we did any media-related migration
MediaCache::clear();

if (!User::count()) {
$this->setUpAdminAccount();
$this->info('Seeding initial data');
Artisan::call('db:seed', ['--force' => true]);
} else {
$this->comment('Data seeded -- skipping');
}

if (!Setting::get('media_path')) {
$this->setMediaPath();
}

$this->info('Compiling front-end stuff');
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->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!');
}

/**
* 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.');
}
}
}
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"aws/aws-sdk-php-laravel": "^3.1",
"pusher/pusher-php-server": "^2.6",
"predis/predis": "~1.0",
"doctrine/dbal": "^2.5"
"doctrine/dbal": "^2.5",
"jackiedo/dotenv-editor": "^1.0"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
Expand Down
51 changes: 50 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion config/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@
App\Providers\DownloadServiceProvider::class,
App\Providers\BroadcastServiceProvider::class,
App\Providers\iTunesServiceProvider::class,

Jackiedo\DotenvEditor\DotenvEditorServiceProvider::class,
],

/*
Expand Down Expand Up @@ -203,6 +203,7 @@
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
'DotenvEditor' => Jackiedo\DotenvEditor\Facades\DotenvEditor::class,

'Media' => App\Facades\Media::class,
'MediaCache' => App\Facades\MediaCache::class,
Expand Down
27 changes: 27 additions & 0 deletions config/dotenv-editor.php
Original file line number Diff line number Diff line change
@@ -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/')

);
2 changes: 1 addition & 1 deletion database/seeds/DatabaseSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public function run()
Model::unguard();

// This must be run first, to check for dependencies
$this->call(UserTableSeeder::class);
// $this->call(UserTableSeeder::class);

$this->call(ArtistTableSeeder::class);
$this->call(AlbumTableSeeder::class);
Expand Down
3 changes: 3 additions & 0 deletions storage/dotenv-editor/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/backups
*
!.gitignore

0 comments on commit e1b68cc

Please sign in to comment.