ServerController.php 14 KB

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