ServerController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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\Notifications\ServerCreationError;
  11. use Exception;
  12. use Illuminate\Database\Eloquent\Builder;
  13. use Illuminate\Http\Client\Response;
  14. use Illuminate\Http\RedirectResponse;
  15. use Illuminate\Http\Request;
  16. use Illuminate\Support\Facades\Auth;
  17. use Illuminate\Support\Facades\Request as FacadesRequest;
  18. class ServerController extends Controller
  19. {
  20. /** Display a listing of the resource. */
  21. public function index()
  22. {
  23. $servers = Auth::user()->servers;
  24. //Get and set server infos each server
  25. foreach ($servers as $server) {
  26. //Get server infos from ptero
  27. $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id, true);
  28. if (! $serverAttributes) {
  29. continue;
  30. }
  31. $serverRelationships = $serverAttributes['relationships'];
  32. $serverLocationAttributes = $serverRelationships['location']['attributes'];
  33. //Set server infos
  34. $server->location = $serverLocationAttributes['long'] ?
  35. $serverLocationAttributes['long'] :
  36. $serverLocationAttributes['short'];
  37. $server->egg = $serverRelationships['egg']['attributes']['name'];
  38. $server->nest = $serverRelationships['nest']['attributes']['name'];
  39. $server->node = $serverRelationships['node']['attributes']['name'];
  40. //Check if a server got renamed on Pterodactyl
  41. $savedServer = Server::query()->where('id', $server->id)->first();
  42. if ($savedServer->name != $serverAttributes['name']) {
  43. $savedServer->name = $serverAttributes['name'];
  44. $server->name = $serverAttributes['name'];
  45. $savedServer->save();
  46. }
  47. //get productname by product_id for server
  48. $product = Product::find($server->product_id);
  49. $server->product = $product;
  50. }
  51. return view('servers.index')->with([
  52. 'servers' => $servers,
  53. ]);
  54. }
  55. /** Show the form for creating a new resource. */
  56. public function create()
  57. {
  58. if (! is_null($this->validateConfigurationRules())) {
  59. return $this->validateConfigurationRules();
  60. }
  61. $productCount = Product::query()->where('disabled', '=', false)->count();
  62. $locations = Location::all();
  63. $nodeCount = Node::query()
  64. ->whereHas('products', function (Builder $builder) {
  65. $builder->where('disabled', '=', false);
  66. })->count();
  67. $eggs = Egg::query()
  68. ->whereHas('products', function (Builder $builder) {
  69. $builder->where('disabled', '=', false);
  70. })->get();
  71. $nests = Nest::query()
  72. ->whereHas('eggs', function (Builder $builder) {
  73. $builder->whereHas('products', function (Builder $builder) {
  74. $builder->where('disabled', '=', false);
  75. });
  76. })->get();
  77. return view('servers.create')->with([
  78. 'productCount' => $productCount,
  79. 'nodeCount' => $nodeCount,
  80. 'nests' => $nests,
  81. 'locations' => $locations,
  82. 'eggs' => $eggs,
  83. 'user' => Auth::user(),
  84. ]);
  85. }
  86. /**
  87. * @return null|RedirectResponse
  88. */
  89. private function validateConfigurationRules()
  90. {
  91. //limit validation
  92. if (Auth::user()->servers()->count() >= Auth::user()->server_limit) {
  93. return redirect()->route('servers.index')->with('error', __('Server limit reached!'));
  94. }
  95. // minimum credits && Check for Allocation
  96. if (FacadesRequest::has('product')) {
  97. $product = Product::findOrFail(FacadesRequest::input('product'));
  98. // Get node resource allocation info
  99. $node = $product->nodes()->findOrFail(FacadesRequest::input('node'));
  100. $nodeName = $node->name;
  101. // Check if node has enough memory and disk space
  102. $checkResponse = Pterodactyl::checkNodeResources($node, $product->memory, $product->disk);
  103. if ($checkResponse == false) {
  104. return redirect()->route('servers.index')->with('error', __("The node '".$nodeName."' doesn't have the required memory or disk left to allocate this product."));
  105. }
  106. // Min. Credits
  107. if (
  108. Auth::user()->credits <
  109. ($product->minimum_credits == -1
  110. ? config('SETTINGS::USER:MINIMUM_REQUIRED_CREDITS_TO_MAKE_SERVER', 50)
  111. : $product->minimum_credits)
  112. ) {
  113. return redirect()->route('servers.index')->with('error', 'You do not have the required amount of '.CREDITS_DISPLAY_NAME.' to use this product!');
  114. }
  115. }
  116. //Required Verification for creating an server
  117. if (config('SETTINGS::USER:FORCE_EMAIL_VERIFICATION', 'false') === 'true' && ! Auth::user()->hasVerifiedEmail()) {
  118. return redirect()->route('profile.index')->with('error', __('You are required to verify your email address before you can create a server.'));
  119. }
  120. //Required Verification for creating an server
  121. if (! config('SETTINGS::SYSTEM:CREATION_OF_NEW_SERVERS', 'true') && Auth::user()->role != 'admin') {
  122. return redirect()->route('servers.index')->with('error', __('The system administrator has blocked the creation of new servers.'));
  123. }
  124. //Required Verification for creating an server
  125. if (config('SETTINGS::USER:FORCE_DISCORD_VERIFICATION', 'false') === 'true' && ! Auth::user()->discordUser) {
  126. return redirect()->route('profile.index')->with('error', __('You are required to link your discord account before you can create a server.'));
  127. }
  128. return null;
  129. }
  130. /** Store a newly created resource in storage. */
  131. public function store(Request $request)
  132. {
  133. /** @var Node $node */
  134. /** @var Egg $egg */
  135. /** @var Product $product */
  136. if (! is_null($this->validateConfigurationRules())) {
  137. return $this->validateConfigurationRules();
  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 = Pterodactyl::getFreeAllocationId($node);
  155. if (! $allocationId) {
  156. return $this->noAllocationsError($server);
  157. }
  158. //create server on pterodactyl
  159. $response = 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 (config('SETTINGS::SYSTEM:SERVER_CREATE_CHARGE_FIRST_HOUR', 'true') == 'true') {
  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 = 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 = 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 = 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 = 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 = 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 = 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. }