Skip to content

Commit

Permalink
Merge pull request #110 from ControlPanel-gg/development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
AVMG20 authored Jul 5, 2021
2 parents daecd53 + 7744449 commit 40ee71d
Show file tree
Hide file tree
Showing 8 changed files with 186 additions and 33 deletions.
13 changes: 8 additions & 5 deletions app/Classes/Pterodactyl.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Classes;

use App\Models\Configuration;
use App\Models\Egg;
use App\Models\Nest;
use App\Models\Node;
Expand Down Expand Up @@ -113,7 +114,8 @@ public static function getLocations()
*/
public static function getFreeAllocationId(Node $node)
{
return self::getFreeAllocations($node)[0]['attributes']['id'];

return self::getFreeAllocations($node)[0]['attributes']['id'] ?? null;
}


Expand All @@ -123,7 +125,8 @@ public static function getFreeAllocationId(Node $node)
*/
public static function getAllocations(Node $node)
{
$response = self::client()->get("/application/nodes/{$node->id}/allocations");
$per_page = Configuration::getValueByKey('ALLOCATION_LIMIT' , 200);
$response = self::client()->get("/application/nodes/{$node->id}/allocations?per_page={$per_page}");
if ($response->failed()) throw self::getException();
return $response->json();
}
Expand All @@ -141,10 +144,10 @@ public static function url(string $route): string
/**
* @param Server $server
* @param Egg $egg
* @param Node $node
* @param int $allocationId
* @return Response
*/
public static function createServer(Server $server, Egg $egg, Node $node)
public static function createServer(Server $server, Egg $egg, int $allocationId)
{
return self::client()->post("/application/servers", [
"name" => $server->name,
Expand All @@ -167,7 +170,7 @@ public static function createServer(Server $server, Egg $egg, Node $node)
"allocations" => 1
],
"allocation" => [
"default" => Pterodactyl::getFreeAllocationId($node)
"default" => $allocationId
]
]);
}
Expand Down
123 changes: 123 additions & 0 deletions app/Console/Commands/ImportUsersFromPteroCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class ImportUsersFromPteroCommand extends Command
{
/**
* @var string
*/
private $importFileName = 'users.json';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'import:users {--initial_credits=} {--initial_server_limit=} {--confirm=}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';

/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}

/**
* Execute the console command.
*
* @return boolean
*/
public function handle()
{

//check if json file exists
if (!Storage::disk('local')->exists('users.json')) {
$this->error('[ERROR] ' . storage_path('app') . '/' . $this->importFileName . ' is missing');
return false;
}

//check if json file is valid
$json = json_decode(Storage::disk('local')->get('users.json'));
if (!array_key_exists(2, $json)) {
$this->error('[ERROR] Invalid json file');
return false;
}
if (!$json[2]->data) {
$this->error('[ERROR] Invalid json file / No users found!');
return false;
}

//ask questions :)
$initial_credits = $this->option('initial_credits') ?? $this->ask('Please specify the amount of starting credits users should get. ');
$initial_server_limit = $this->option('initial_server_limit') ?? $this->ask('Please specify the initial server limit users should get.');
$confirm = strtolower($this->option('confirm') ?? $this->ask('[y/n] Are you sure you want to remove all existing users from the database continue importing?'));

//cancel
if ($confirm !== 'y') {
$this->error('[ERROR] Stopped import script!');
return false;
}

//import users
$this->deleteCurrentUserBase();
$this->importUsingJsonFile($json, $initial_credits, $initial_server_limit);
return true;
}

/**
* @return void
*/
private function deleteCurrentUserBase()
{
$currentUserCount = User::count();
if ($currentUserCount == 0) return;

$this->line("Deleting ({$currentUserCount}) users..");
foreach (User::all() as $user) {
$user->delete();
}
}

/**
* @param $json
* @param $initial_credits
* @param $initial_server_limit
* @return void
*/
private function importUsingJsonFile($json, $initial_credits, $initial_server_limit)
{
$this->withProgressBar($json[2]->data, function ($user) use ($initial_server_limit, $initial_credits) {
$role = $user->root_admin == '0' ? 'member' : 'admin';

User::create([
"pterodactyl_id" => $user->id,
"name" => $user->name_first,
"email" => $user->email,
"password" => $user->password,
"role" => $role,
"credits" => $initial_credits,
"server_limit" => $initial_server_limit,
"created_at" => $user->created_at,
"updated_at" => $user->updated_at,
]);
});

$this->newLine();
$this->line("Done importing, you can now login using your pterodactyl credentials.");
$this->newLine();
}
}
4 changes: 2 additions & 2 deletions app/Http/Controllers/Admin/ProductController.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public function store(Request $request)
"memory" => "required|numeric|max:1000000|min:5",
"cpu" => "required|numeric|max:1000000|min:0",
"swap" => "required|numeric|max:1000000|min:0",
"description" => "required",
"description" => "required|string|max:191",
"disk" => "required|numeric|max:1000000|min:5",
"io" => "required|numeric|max:1000000|min:0",
"databases" => "required|numeric|max:1000000|min:0",
Expand Down Expand Up @@ -105,7 +105,7 @@ public function update(Request $request, Product $product): RedirectResponse
"memory" => "required|numeric|max:1000000|min:5",
"cpu" => "required|numeric|max:1000000|min:0",
"swap" => "required|numeric|max:1000000|min:0",
"description" => "required",
"description" => "required|string|max:191",
"disk" => "required|numeric|max:1000000|min:5",
"io" => "required|numeric|max:1000000|min:0",
"databases" => "required|numeric|max:1000000|min:0",
Expand Down
2 changes: 1 addition & 1 deletion app/Http/Controllers/Admin/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public function update(Request $request, User $user)
"name" => "required|string|min:4|max:30",
"pterodactyl_id" => "required|numeric|unique:users,pterodactyl_id,{$user->id}",
"email" => "required|string|email",
"credits" => "required|numeric|min:0|max:1000000",
"credits" => "required|numeric|min:0|max:999999",
"server_limit" => "required|numeric|min:0|max:1000000",
"role" => Rule::in(['admin', 'mod', 'client', 'member']),
]);
Expand Down
8 changes: 2 additions & 6 deletions app/Http/Controllers/HomeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@
namespace App\Http\Controllers;

use App\Models\UsefulLink;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
Expand All @@ -20,15 +18,13 @@ public function index(Request $request)
{
$usage = 0;

foreach (Auth::user()->Servers as $server){
foreach (Auth::user()->servers as $server){
$usage += $server->product->price;
}

$useful_links = DB::table('useful_links')->get();

return view('home')->with([
'useage' => $usage,
'useful_links' => $useful_links
'useful_links' => UsefulLink::all()->sortBy('id')
]);
}
}
56 changes: 38 additions & 18 deletions app/Http/Controllers/ServerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use App\Models\Server;
use App\Notifications\ServerCreationError;
use Exception;
use Illuminate\Http\Client\Response;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
Expand Down Expand Up @@ -44,6 +45,8 @@ public function create()
/** Store a newly created resource in storage. */
public function store(Request $request)
{
if (!is_null($this->validateConfigurationRules())) return $this->validateConfigurationRules();

$request->validate([
"name" => "required|max:191",
"description" => "nullable|max:191",
Expand All @@ -52,18 +55,18 @@ public function store(Request $request)
"product_id" => "required|exists:products,id",
]);

if (!is_null($this->validateConfigurationRules())) return $this->validateConfigurationRules();

//create server
//get required resources
$egg = Egg::findOrFail($request->input('egg_id'));
$server = Auth::user()->servers()->create($request->all());
$node = Node::findOrFail($request->input('node_id'));
$server = Auth::user()->servers()->create($request->all());

//create server on pterodactyl
$response = Pterodactyl::createServer($server, $egg, $node);
//get free allocation ID
$allocationId = Pterodactyl::getFreeAllocationId($node);
if (!$allocationId) return $this->noAllocationsError($server);

if (is_null($response)) return $this->serverCreationFailed($server);
if ($response->failed()) return $this->serverCreationFailed($server);
//create server on pterodactyl
$response = Pterodactyl::createServer($server, $egg, $allocationId);
if ($response->failed()) return $this->serverCreationFailed($response, $server);

//update server with pterodactyl_id
$server->update([
Expand All @@ -74,16 +77,6 @@ public function store(Request $request)
return redirect()->route('servers.index')->with('success', 'server created');
}

/** Quick Fix */
private function serverCreationFailed(Server $server)
{
$server->delete();

Auth::user()->notify(new ServerCreationError($server));
return redirect()->route('servers.index')->with('error', 'No allocations satisfying the requirements for automatic deployment were found.');
}


/**
* @return null|RedirectResponse
*/
Expand Down Expand Up @@ -121,4 +114,31 @@ public function destroy(Server $server)
return redirect()->route('servers.index')->with('error', 'An exception has occurred while trying to remove a resource');
}
}


/**
* return redirect with error
* @param Server $server
* @return RedirectResponse
*/
private function noAllocationsError(Server $server)
{
$server->delete();

Auth::user()->notify(new ServerCreationError($server));
return redirect()->route('servers.index')->with('error', 'No allocations satisfying the requirements for automatic deployment were found.');
}

/**
* return redirect with error
* @param Response $response
* @param Server $server
* @return RedirectResponse
*/
private function serverCreationFailed(Response $response , Server $server)
{
$server->delete();

return redirect()->route('servers.index')->with('error', json_encode($response->json()));
}
}
11 changes: 11 additions & 0 deletions database/seeders/Seeds/ConfigurationSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,5 +109,16 @@ public function run()
'type' => 'boolean',
'description' => 'Prevent users from making multiple accounts using the same IP address'
]);

//per_page on allocations request
Configuration::firstOrCreate([
'key' => 'ALLOCATION_LIMIT',
], [
'value' => '200',
'type' => 'integer',
'description' => 'The maximum amount of allocations to pull per node for automatic deployment, if more allocations are being used than this limit is set to, no new servers can be created!'
]);


}
}
2 changes: 1 addition & 1 deletion routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@
Route::resource('configurations', ConfigurationController::class);
Route::resource('configurations', ConfigurationController::class);

Route::patch('settings/update/icons', [SettingsController::class , 'updateIcons'])->name('settings.update.icons');
Route::patch('settings/update/icons', [SettingsController::class, 'updateIcons'])->name('settings.update.icons');
Route::resource('settings', SettingsController::class)->only('index');

Route::get('usefullinks/datatable', [UsefulLinkController::class, 'datatable'])->name('usefullinks.datatable');
Expand Down

0 comments on commit 40ee71d

Please sign in to comment.