Переглянути джерело

Merge pull request #110 from ControlPanel-gg/development

Development
AVMG 4 роки тому
батько
коміт
40ee71d61b

+ 8 - 5
app/Classes/Pterodactyl.php

@@ -2,6 +2,7 @@
 
 namespace App\Classes;
 
+use App\Models\Configuration;
 use App\Models\Egg;
 use App\Models\Nest;
 use App\Models\Node;
@@ -113,7 +114,8 @@ class Pterodactyl
      */
     public static function getFreeAllocationId(Node $node)
     {
-        return self::getFreeAllocations($node)[0]['attributes']['id'];
+
+        return self::getFreeAllocations($node)[0]['attributes']['id'] ?? null;
     }
 
 
@@ -123,7 +125,8 @@ class Pterodactyl
      */
     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();
     }
@@ -141,10 +144,10 @@ class Pterodactyl
     /**
      * @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,
@@ -167,7 +170,7 @@ class Pterodactyl
                 "allocations" => 1
             ],
             "allocation"     => [
-                "default" => Pterodactyl::getFreeAllocationId($node)
+                "default" => $allocationId
             ]
         ]);
     }

+ 123 - 0
app/Console/Commands/ImportUsersFromPteroCommand.php

@@ -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();
+    }
+}

+ 2 - 2
app/Http/Controllers/Admin/ProductController.php

@@ -49,7 +49,7 @@ class ProductController extends Controller
             "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",
@@ -105,7 +105,7 @@ class ProductController extends Controller
             "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",

+ 1 - 1
app/Http/Controllers/Admin/UserController.php

@@ -78,7 +78,7 @@ class UserController extends Controller
             "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']),
         ]);

+ 2 - 6
app/Http/Controllers/HomeController.php

@@ -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
 {
@@ -20,15 +18,13 @@ class HomeController extends Controller
     {
         $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')
         ]);
     }
 }

+ 38 - 18
app/Http/Controllers/ServerController.php

@@ -12,6 +12,7 @@ use App\Models\Product;
 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;
@@ -44,6 +45,8 @@ class ServerController extends Controller
     /** 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",
@@ -52,18 +55,18 @@ class ServerController extends Controller
             "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([
@@ -74,16 +77,6 @@ class ServerController extends Controller
         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
      */
@@ -121,4 +114,31 @@ class ServerController extends Controller
             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 - 0
database/seeders/Seeds/ConfigurationSeeder.php

@@ -109,5 +109,16 @@ class ConfigurationSeeder extends Seeder
             '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!'
+        ]);
+
+
     }
 }

+ 1 - 1
routes/web.php

@@ -104,7 +104,7 @@ Route::middleware('auth')->group(function () {
         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');