ServerController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. /**
  116. * Required Verification for creating an server
  117. * Todo: Tell the administrator that server creation has been disabled?
  118. */
  119. if (!config('SETTINGS::SYSTEM:CREATION_OF_NEW_SERVERS', 'true') && Auth::user()->role != "admin") {
  120. return redirect()->route('servers.index')->with('error', __("The system administrator has blocked the creation of new servers."));
  121. }
  122. //Required Verification for creating an server
  123. if (config('SETTINGS::USER:FORCE_DISCORD_VERIFICATION', 'false') === 'true' && !Auth::user()->discordUser) {
  124. return redirect()->route('profile.index')->with('error', __("You are required to link your discord account before you can create a server."));
  125. }
  126. return null;
  127. }
  128. /** Store a newly created resource in storage. */
  129. public function store(Request $request)
  130. {
  131. /** @var Node $node */
  132. /** @var Egg $egg */
  133. /** @var Product $product */
  134. if (!is_null($this->validateConfigurationRules())) return $this->validateConfigurationRules();
  135. $request->validate([
  136. "name" => "required|max:191",
  137. "node" => "required|exists:nodes,id",
  138. "egg" => "required|exists:eggs,id",
  139. "product" => "required|exists:products,id"
  140. ]);
  141. //get required resources
  142. $product = Product::query()->findOrFail($request->input('product'));
  143. $egg = $product->eggs()->findOrFail($request->input('egg'));
  144. $node = $product->nodes()->findOrFail($request->input('node'));
  145. $server = $request->user()->servers()->create([
  146. 'name' => $request->input('name'),
  147. 'product_id' => $request->input('product'),
  148. ]);
  149. //get free allocation ID
  150. $allocationId = Pterodactyl::getFreeAllocationId($node);
  151. if (!$allocationId) return $this->noAllocationsError($server);
  152. //create server on pterodactyl
  153. $response = Pterodactyl::createServer($server, $egg, $allocationId);
  154. if ($response->failed()) return $this->serverCreationFailed($response, $server);
  155. $serverAttributes = $response->json()['attributes'];
  156. //update server with pterodactyl_id
  157. $server->update([
  158. 'pterodactyl_id' => $serverAttributes['id'],
  159. 'identifier' => $serverAttributes['identifier']
  160. ]);
  161. if (config('SETTINGS::SYSTEM:SERVER_CREATE_CHARGE_FIRST_HOUR', 'true') == 'true') {
  162. if ($request->user()->credits >= $server->product->getHourlyPrice()) {
  163. $request->user()->decrement('credits', $server->product->getHourlyPrice());
  164. }
  165. }
  166. return redirect()->route('servers.index')->with('success', __('Server created'));
  167. }
  168. /**
  169. * return redirect with error
  170. * @param Server $server
  171. * @return RedirectResponse
  172. */
  173. private function noAllocationsError(Server $server)
  174. {
  175. $server->delete();
  176. Auth::user()->notify(new ServerCreationError($server));
  177. return redirect()->route('servers.index')->with('error', __('No allocations satisfying the requirements for automatic deployment on this node were found.'));
  178. }
  179. /**
  180. * return redirect with error
  181. * @param Response $response
  182. * @param Server $server
  183. * @return RedirectResponse
  184. */
  185. private function serverCreationFailed(Response $response, Server $server)
  186. {
  187. $server->delete();
  188. return redirect()->route('servers.index')->with('error', json_encode($response->json()));
  189. }
  190. /** Remove the specified resource from storage. */
  191. public function destroy(Server $server)
  192. {
  193. try {
  194. $server->delete();
  195. return redirect()->route('servers.index')->with('success', __('Server removed'));
  196. } catch (Exception $e) {
  197. return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to remove a resource "') . $e->getMessage() . '"');
  198. }
  199. }
  200. /** Show Server Settings */
  201. public function show(Server $server)
  202. {
  203. if($server->user_id != Auth::user()->id){ return back()->with('error', __('´This is not your Server!'));}
  204. $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id);
  205. $serverRelationships = $serverAttributes['relationships'];
  206. $serverLocationAttributes = $serverRelationships['location']['attributes'];
  207. //Get current product
  208. $currentProduct = Product::where('id', $server->product_id)->first();
  209. //Set server infos
  210. $server->location = $serverLocationAttributes['long'] ?
  211. $serverLocationAttributes['long'] :
  212. $serverLocationAttributes['short'];
  213. $server->node = $serverRelationships['node']['attributes']['name'];
  214. $server->name = $serverAttributes['name'];
  215. $server->egg = $serverRelationships['egg']['attributes']['name'];
  216. $pteroNode = Pterodactyl::getNode($serverRelationships['node']['attributes']['id']);
  217. $products = Product::orderBy("created_at")
  218. ->whereHas('nodes', function (Builder $builder) use ($serverRelationships) { //Only show products for that node
  219. $builder->where('id', '=', $serverRelationships['node']['attributes']['id']);
  220. })
  221. ->get();
  222. // Set the each product eggs array to just contain the eggs name
  223. foreach ($products as $product) {
  224. $product->eggs = $product->eggs->pluck('name')->toArray();
  225. 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;
  226. }
  227. return view('servers.settings')->with([
  228. 'server' => $server,
  229. 'products' => $products
  230. ]);
  231. }
  232. public function upgrade(Server $server, Request $request)
  233. {
  234. if($server->user_id != Auth::user()->id) return redirect()->route('servers.index');
  235. if(!isset($request->product_upgrade))
  236. {
  237. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('this product is the only one'));
  238. }
  239. $user = Auth::user();
  240. $oldProduct = Product::where('id', $server->product->id)->first();
  241. $newProduct = Product::where('id', $request->product_upgrade)->first();
  242. $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id);
  243. $serverRelationships = $serverAttributes['relationships'];
  244. // Get node resource allocation info
  245. $nodeId = $serverRelationships['node']['attributes']['id'];
  246. $node = Node::where('id', $nodeId)->firstOrFail();
  247. $nodeName = $node->name;
  248. // Check if node has enough memory and disk space
  249. $requireMemory = $newProduct->memory - $oldProduct->memory;
  250. $requiredisk = $newProduct->disk - $oldProduct->disk;
  251. $checkResponse = Pterodactyl::checkNodeResources($node, $requireMemory, $requiredisk);
  252. 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."));
  253. $priceupgrade = $newProduct->getHourlyPrice();
  254. if ($priceupgrade < $oldProduct->getHourlyPrice()) {
  255. $priceupgrade = 0;
  256. }
  257. if ($user->credits >= $priceupgrade && $user->credits >= $newProduct->minimum_credits)
  258. {
  259. $server->product_id = $request->product_upgrade;
  260. $server->update();
  261. $server->allocation = $serverAttributes['allocation'];
  262. $response = Pterodactyl::updateServer($server, $newProduct);
  263. if ($response->failed()) return $this->serverCreationFailed($response, $server);
  264. //update user balance
  265. $user->decrement('credits', $priceupgrade);
  266. //restart the server
  267. $response = Pterodactyl::powerAction($server, "restart");
  268. if ($response->failed()) return redirect()->route('servers.index')->with('error', $response->json()['errors'][0]['detail']);
  269. return redirect()->route('servers.show', ['server' => $server->id])->with('success', __('Server Successfully Upgraded'));
  270. }
  271. else
  272. {
  273. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('Not Enough Balance for Upgrade'));
  274. }
  275. }
  276. }