ServerController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Classes\Pterodactyl;
  4. use App\Models\Egg;
  5. use App\Models\Location;
  6. use App\Models\Nest;
  7. use App\Models\Node;
  8. use App\Models\Product;
  9. use App\Models\Server;
  10. use App\Models\Settings;
  11. use App\Notifications\ServerCreationError;
  12. use Exception;
  13. use Illuminate\Database\Eloquent\Builder;
  14. use Illuminate\Http\Client\Response;
  15. use Illuminate\Http\RedirectResponse;
  16. use Illuminate\Http\Request;
  17. use Illuminate\Support\Facades\Auth;
  18. use Illuminate\Support\Facades\Request as FacadesRequest;
  19. class ServerController extends Controller
  20. {
  21. /** Display a listing of the resource. */
  22. public function index()
  23. {
  24. $servers = Auth::user()->servers;
  25. //Get and set server infos each server
  26. foreach ($servers as $server) {
  27. //Get server infos from ptero
  28. $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id, true);
  29. if(!$serverAttributes) continue;
  30. $serverRelationships = $serverAttributes['relationships'];
  31. $serverLocationAttributes = $serverRelationships['location']['attributes'];
  32. //Set server infos
  33. $server->location = $serverLocationAttributes['long'] ?
  34. $serverLocationAttributes['long'] :
  35. $serverLocationAttributes['short'];
  36. $server->egg = $serverRelationships['egg']['attributes']['name'];
  37. $server->nest = $serverRelationships['nest']['attributes']['name'];
  38. $server->node = $serverRelationships['node']['attributes']['name'];
  39. //Check if a server got renamed on Pterodactyl
  40. $savedServer = Server::query()->where('id', $server->id)->first();
  41. if($savedServer->name != $serverAttributes['name']){
  42. $savedServer->name = $serverAttributes['name'];
  43. $server->name = $serverAttributes['name'];
  44. $savedServer->save();
  45. }
  46. //get productname by product_id for server
  47. $product = Product::find($server->product_id);
  48. $server->product = $product;
  49. }
  50. return view('servers.index')->with([
  51. 'servers' => $servers
  52. ]);
  53. }
  54. /** Show the form for creating a new resource. */
  55. public function create()
  56. {
  57. if (!is_null($this->validateConfigurationRules())) return $this->validateConfigurationRules();
  58. $productCount = Product::query()->where('disabled', '=', false)->count();
  59. $locations = Location::all();
  60. $nodeCount = Node::query()
  61. ->whereHas('products', function (Builder $builder) {
  62. $builder->where('disabled', '=', false);
  63. })->count();
  64. $eggs = Egg::query()
  65. ->whereHas('products', function (Builder $builder) {
  66. $builder->where('disabled', '=', false);
  67. })->get();
  68. $nests = Nest::query()
  69. ->whereHas('eggs', function (Builder $builder) {
  70. $builder->whereHas('products', function (Builder $builder) {
  71. $builder->where('disabled', '=', false);
  72. });
  73. })->get();
  74. return view('servers.create')->with([
  75. 'productCount' => $productCount,
  76. 'nodeCount' => $nodeCount,
  77. 'nests' => $nests,
  78. 'locations' => $locations,
  79. 'eggs' => $eggs,
  80. 'user' => Auth::user(),
  81. ]);
  82. }
  83. /**
  84. * @return null|RedirectResponse
  85. */
  86. private function validateConfigurationRules()
  87. {
  88. //limit validation
  89. if (Auth::user()->servers()->count() >= Auth::user()->server_limit) {
  90. return redirect()->route('servers.index')->with('error', __('Server limit reached!'));
  91. }
  92. // minimum credits && Check for Allocation
  93. if (FacadesRequest::has("product")) {
  94. $product = Product::findOrFail(FacadesRequest::input("product"));
  95. // Get node resource allocation info
  96. $node = $product->nodes()->findOrFail(FacadesRequest::input('node'));
  97. $nodeName = $node->name;
  98. // Check if node has enough memory and disk space
  99. $checkResponse = Pterodactyl::checkNodeResources($node, $product->memory, $product->disk);
  100. if ($checkResponse == False) return redirect()->route('servers.index')->with('error', __("The node '" . $nodeName . "' doesn't have the required memory or disk left to allocate this product."));
  101. // Min. Credits
  102. if (
  103. Auth::user()->credits <
  104. ($product->minimum_credits == -1
  105. ? config('SETTINGS::USER:MINIMUM_REQUIRED_CREDITS_TO_MAKE_SERVER', 50)
  106. : $product->minimum_credits)
  107. ) {
  108. return redirect()->route('servers.index')->with('error', "You do not have the required amount of " . CREDITS_DISPLAY_NAME . " to use this product!");
  109. }
  110. }
  111. //Required Verification for creating an server
  112. if (config('SETTINGS::USER:FORCE_EMAIL_VERIFICATION', 'false') === 'true' && !Auth::user()->hasVerifiedEmail()) {
  113. return redirect()->route('profile.index')->with('error', __("You are required to verify your email address before you can create a server."));
  114. }
  115. //Required Verification for creating an server
  116. if (!config('SETTINGS::SYSTEM:CREATION_OF_NEW_SERVERS', 'true') && Auth::user()->role != "admin") {
  117. return redirect()->route('servers.index')->with('error', __("The system administrator has blocked the creation of new servers."));
  118. }
  119. //Required Verification for creating an server
  120. if (config('SETTINGS::USER:FORCE_DISCORD_VERIFICATION', 'false') === 'true' && !Auth::user()->discordUser) {
  121. return redirect()->route('profile.index')->with('error', __("You are required to link your discord account before you can create a server."));
  122. }
  123. return null;
  124. }
  125. /** Store a newly created resource in storage. */
  126. public function store(Request $request)
  127. {
  128. /** @var Node $node */
  129. /** @var Egg $egg */
  130. /** @var Product $product */
  131. if (!is_null($this->validateConfigurationRules())) return $this->validateConfigurationRules();
  132. $request->validate([
  133. "name" => "required|max:191",
  134. "node" => "required|exists:nodes,id",
  135. "egg" => "required|exists:eggs,id",
  136. "product" => "required|exists:products,id"
  137. ]);
  138. //get required resources
  139. $product = Product::query()->findOrFail($request->input('product'));
  140. $egg = $product->eggs()->findOrFail($request->input('egg'));
  141. $node = $product->nodes()->findOrFail($request->input('node'));
  142. $server = $request->user()->servers()->create([
  143. 'name' => $request->input('name'),
  144. 'product_id' => $request->input('product'),
  145. ]);
  146. //get free allocation ID
  147. $allocationId = Pterodactyl::getFreeAllocationId($node);
  148. if (!$allocationId) return $this->noAllocationsError($server);
  149. //create server on pterodactyl
  150. $response = Pterodactyl::createServer($server, $egg, $allocationId);
  151. if ($response->failed()) return $this->serverCreationFailed($response, $server);
  152. $serverAttributes = $response->json()['attributes'];
  153. //update server with pterodactyl_id
  154. $server->update([
  155. 'pterodactyl_id' => $serverAttributes['id'],
  156. 'identifier' => $serverAttributes['identifier']
  157. ]);
  158. if (config('SETTINGS::SYSTEM:SERVER_CREATE_CHARGE_FIRST_HOUR', 'true') == 'true') {
  159. if ($request->user()->credits >= $server->product->getHourlyPrice()) {
  160. $request->user()->decrement('credits', $server->product->getHourlyPrice());
  161. }
  162. }
  163. return redirect()->route('servers.index')->with('success', __('Server created'));
  164. }
  165. /**
  166. * return redirect with error
  167. * @param Server $server
  168. * @return RedirectResponse
  169. */
  170. private function noAllocationsError(Server $server)
  171. {
  172. $server->delete();
  173. Auth::user()->notify(new ServerCreationError($server));
  174. return redirect()->route('servers.index')->with('error', __('No allocations satisfying the requirements for automatic deployment on this node were found.'));
  175. }
  176. /**
  177. * return redirect with error
  178. * @param Response $response
  179. * @param Server $server
  180. * @return RedirectResponse
  181. */
  182. private function serverCreationFailed(Response $response, Server $server)
  183. {
  184. $server->delete();
  185. return redirect()->route('servers.index')->with('error', json_encode($response->json()));
  186. }
  187. /** Remove the specified resource from storage. */
  188. public function destroy(Server $server)
  189. {
  190. try {
  191. $server->delete();
  192. return redirect()->route('servers.index')->with('success', __('Server removed'));
  193. } catch (Exception $e) {
  194. return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to remove a resource "') . $e->getMessage() . '"');
  195. }
  196. }
  197. /** Show Server Settings */
  198. public function show(Server $server)
  199. {
  200. if($server->user_id != Auth::user()->id){ return back()->with('error', __('´This is not your Server!'));}
  201. $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id);
  202. $serverRelationships = $serverAttributes['relationships'];
  203. $serverLocationAttributes = $serverRelationships['location']['attributes'];
  204. //Get current product
  205. $currentProduct = Product::where('id', $server->product_id)->first();
  206. //Set server infos
  207. $server->location = $serverLocationAttributes['long'] ?
  208. $serverLocationAttributes['long'] :
  209. $serverLocationAttributes['short'];
  210. $server->node = $serverRelationships['node']['attributes']['name'];
  211. $server->name = $serverAttributes['name'];
  212. $server->egg = $serverRelationships['egg']['attributes']['name'];
  213. $pteroNode = Pterodactyl::getNode($serverRelationships['node']['attributes']['id']);
  214. $products = Product::orderBy("created_at")
  215. ->whereHas('nodes', function (Builder $builder) use ($serverRelationships) { //Only show products for that node
  216. $builder->where('id', '=', $serverRelationships['node']['attributes']['id']);
  217. })
  218. ->get();
  219. // Set the each product eggs array to just contain the eggs name
  220. foreach ($products as $product) {
  221. $product->eggs = $product->eggs->pluck('name')->toArray();
  222. if($product->memory-$currentProduct->memory>($pteroNode['memory']*($pteroNode['memory_overallocate']+100)/100)-$pteroNode['allocated_resources']['memory']||$product->disk-$currentProduct->disk>($pteroNode['disk']*($pteroNode['disk_overallocate']+100)/100)-$pteroNode['allocated_resources']['disk']) $product->doesNotFit = true;
  223. }
  224. return view('servers.settings')->with([
  225. 'server' => $server,
  226. 'products' => $products
  227. ]);
  228. }
  229. public function upgrade(Server $server, Request $request)
  230. {
  231. if($server->user_id != Auth::user()->id) return redirect()->route('servers.index');
  232. if(!isset($request->product_upgrade))
  233. {
  234. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('this product is the only one'));
  235. }
  236. $user = Auth::user();
  237. $oldProduct = Product::where('id', $server->product->id)->first();
  238. $newProduct = Product::where('id', $request->product_upgrade)->first();
  239. $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id);
  240. $serverRelationships = $serverAttributes['relationships'];
  241. // Get node resource allocation info
  242. $nodeId = $serverRelationships['node']['attributes']['id'];
  243. $node = Node::where('id', $nodeId)->firstOrFail();
  244. $nodeName = $node->name;
  245. // Check if node has enough memory and disk space
  246. $requireMemory = $newProduct->memory - $oldProduct->memory;
  247. $requiredisk = $newProduct->disk - $oldProduct->disk;
  248. $checkResponse = Pterodactyl::checkNodeResources($node, $requireMemory, $requiredisk);
  249. if ($checkResponse == False) return redirect()->route('servers.index')->with('error', __("The node '" . $nodeName . "' doesn't have the required memory or disk left to upgrade the server."));
  250. $priceupgrade = $newProduct->getHourlyPrice();
  251. if ($priceupgrade < $oldProduct->getHourlyPrice()) {
  252. $priceupgrade = 0;
  253. }
  254. if ($user->credits >= $priceupgrade && $user->credits >= $newProduct->minimum_credits)
  255. {
  256. $server->product_id = $request->product_upgrade;
  257. $server->update();
  258. $server->allocation = $serverAttributes['allocation'];
  259. $response = Pterodactyl::updateServer($server, $newProduct);
  260. if ($response->failed()) return $this->serverCreationFailed($response, $server);
  261. //update user balance
  262. $user->decrement('credits', $priceupgrade);
  263. //restart the server
  264. $response = Pterodactyl::powerAction($server, "restart");
  265. if ($response->failed()) return redirect()->route('servers.index')->with('error', $response->json()['errors'][0]['detail']);
  266. return redirect()->route('servers.show', ['server' => $server->id])->with('success', __('Server Successfully Upgraded'));
  267. }
  268. else
  269. {
  270. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('Not Enough Balance for Upgrade'));
  271. }
  272. }
  273. }