Skip to content

Instantly share code, notes, and snippets.

@bishwajitcadhikary
Created March 9, 2025 07:27
Show Gist options
  • Save bishwajitcadhikary/45cd7929450ebfb465bcfebdd9c16a62 to your computer and use it in GitHub Desktop.
Save bishwajitcadhikary/45cd7929450ebfb465bcfebdd9c16a62 to your computer and use it in GitHub Desktop.
<?php
namespace App\Jobs;
use App\Models\DatabaseUpgrade;
use App\Models\Website;
use App\Models\User;
use App\Notifications\DatabaseCreated;
use App\Notifications\DatabaseCreateFailed;
use App\Notifications\SendWebsiteCreationConfirmation;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Throwable;
class ImportWebsiteDatabase implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private string $url;
private array $headers;
public function __construct(private string $databaseName, private Website $website, private $hasDomain = false)
{
$this->url = config('wovo.cpanel.domain') . ':' . config('wovo.cpanel.port');
$this->headers = [
'Authorization' => 'cpanel ' . config('wovo.cpanel.username') . ':' . config('wovo.cpanel.api_token'),
'cache-control' => 'no-cache'
];
}
/**
* @throws Exception
*/
public function handle(): void
{
try {
// Create Database
$this->createDatabase();
// Update Privileges
$this->updatePrivileges();
// Import Database
$this->importDatabase();
// Import Upgrades
$this->importUpgrades();
// Create access token for tokenized authentication
//$this->createAccessToken();
// Create domain
//$this->createDomain();
DB::connection('website')->disconnect();
$this->website->update([
'database_created' => 1,
'is_active' => true
]);
User::whereRole('admin')->get()
->map(fn($admin) => $admin->notify(new DatabaseCreated($this->website)));
$this->website->customer->notify(new SendWebsiteCreationConfirmation($this->website));
} catch (Exception $e) {
$this->website->update([
'database_created' => 2,
'is_active' => false
]);
$this->deleteDatabase();
throw new Exception($e->getMessage());
}
}
/**
* @throws Exception
*/
public function failed(Throwable $exception): void
{
try {
$this->deleteDatabase();
$this->website->update([
'database_created' => 2,
'is_active' => false
]);
User::whereRole('admin')->first()?->notify(new DatabaseCreateFailed($this->website, $exception->getMessage()));
} catch (Throwable $e) {
logger('Message: '. $e->getMessage());
throw new Exception($e->getMessage());
}
}
/**
* @throws Exception
*/
private function createDatabase(): bool
{
$response = Http::withHeaders($this->headers)->get($this->url . '/execute/Mysql/create_database', [
'name' => $this->databaseName
]);
if ($response->json('status')) {
return true;
} else {
logger('Database Creation Failed: '. $response->json('errors')[0] ?? $response->json('message') ?? 'Unknown Error');
throw new Exception($response->json('errors')[0] ?? $response->json('message') ?? 'Unknown Error');
}
}
/**
* @throws Exception
*/
private function updatePrivileges(): bool
{
$response = Http::withHeaders($this->headers)->get($this->url . '/execute/Mysql/set_privileges_on_database', [
'user' => config('wovo.cpanel.database_username'),
'database' => $this->databaseName,
'privileges' => 'ALL PRIVILEGES'
]);
if ($response->json('status')) {
return true;
} else {
logger('Database Privileges Update Failed: '. $response->json('errors')[0] ?? $response->json('message') ?? 'Unknown Error');
throw new Exception($response->json('errors')[0] ?? $response->json('message') ?? 'Unknown Error');
}
}
/**
* @throws Exception
*/
private function importDatabase(): bool
{
try {
$this->setDatabaseConnection();
$path = base_path(config('wovo.saas_database_path'));
$content = file_get_contents($path);
// Replace Website Name, Admin Email and Admin Password
$content = str($content)->replace([
'REPLACE_WEBSITE_NAME',
'REPLACE_ADMIN_NAME',
'REPLACE_ADMIN_EMAIL',
'REPLACE_ADMIN_PASSWORD',
], [
$this->website->name,
$this->website->admin_name,
$this->website->admin_email,
$this->website->admin_password,
]);
DB::connection('website')->unprepared($content->value());
return true;
} catch (Exception $e) {
logger('Database Import Failed: '. $e->getMessage());
throw new Exception($e->getMessage());
}
return true;
}
/**
* @throws Exception
*/
private function importUpgrades(): void
{
try {
$this->setDatabaseConnection();
$upgrades = DatabaseUpgrade::all();
foreach ($upgrades as $upgrade) {
$path = 'database/' . $upgrade->database;
if ($upgrade->query) {
try {
DB::connection('website')->select($upgrade->query);
} catch (Throwable $e) {
continue;
}
} else if (Storage::exists($path)) {
$sql = Storage::get($path);
try {
DB::connection('website')->select($sql);
} catch (Throwable $e) {
continue;
}
}
}
} catch (Exception $e) {
logger('Database Upgrade Failed: '. $e->getMessage());
throw new Exception($e->getMessage());
}
DB::connection('website')->disconnect();
}
/**
* @throws Exception
*/
private function deleteDatabase(): bool
{
$response = Http::withHeaders($this->headers)->get($this->url . '/execute/Mysql/delete_database', [
'name' => $this->databaseName
]);
if ($response->json('status')) {
return true;
} else {
logger('Database Deletion Failed: '. $response->json('errors')[0] ?? $response->json('message') ?? 'Unknown Error');
throw new Exception($response->json('errors')[0] ?? $response->json('message') ?? 'Unknown Error');
}
}
/**
* @throws Exception
*/
private function createAccessToken(): void
{
try {
$this->setDatabaseConnection();
$token = $this->website->customer->createToken('loginThroughAccessToken')->plainTextToken;
DB::connection('website')->table('saas_config')->insert([
'access_token' => $token,
]);
}catch (Exception $e) {
logger('Access Token Creation Failed: '. $e->getMessage());
//throw new Exception($e->getMessage());
}
}
private function setDatabaseConnection(): void
{
Config::set([
'database.connections.website.host' => $this->website->host,
'database.connections.website.port' => $this->website->port,
'database.connections.website.username' => $this->website->username,
'database.connections.website.password' => $this->website->password,
'database.connections.website.database' => $this->website->database,
]);
DB::connection('website')->disconnect();
}
private function createDomain()
{
if ($this->hasDomain){
$response = Http::withHeaders($this->whmHeaders)->get($this->whmUrl . '/json-api/create_parked_domain_for_user', [
'api.version' => 1,
'domain' => $this->website->domain,
'username' => config('wovo.cpanel.username'),
'web_vhost_domain' => config('wovo.main_domain')
]);
if ($response->json('status')) {
return true;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment