ServerController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 Carbon\Carbon;
  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) {
  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()
  58. {
  59. if (! is_null($this->validateConfigurationRules())) {
  60. return $this->validateConfigurationRules();
  61. }
  62. $productCount = Product::query()->where('disabled', '=', false)->count();
  63. $locations = Location::all();
  64. $nodeCount = Node::query()
  65. ->whereHas('products', function (Builder $builder) {
  66. $builder->where('disabled', '=', false);
  67. })->count();
  68. $eggs = Egg::query()
  69. ->whereHas('products', function (Builder $builder) {
  70. $builder->where('disabled', '=', false);
  71. })->get();
  72. $nests = Nest::query()
  73. ->whereHas('eggs', function (Builder $builder) {
  74. $builder->whereHas('products', function (Builder $builder) {
  75. $builder->where('disabled', '=', false);
  76. });
  77. })->get();
  78. return view('servers.create')->with([
  79. 'productCount' => $productCount,
  80. 'nodeCount' => $nodeCount,
  81. 'nests' => $nests,
  82. 'locations' => $locations,
  83. 'eggs' => $eggs,
  84. 'user' => Auth::user(),
  85. ]);
  86. }
  87. /**
  88. * @return null|RedirectResponse
  89. */
  90. private function validateConfigurationRules()
  91. {
  92. //limit validation
  93. if (Auth::user()->servers()->count() >= Auth::user()->server_limit) {
  94. return redirect()->route('servers.index')->with('error', __('Server limit reached!'));
  95. }
  96. // minimum credits && Check for Allocation
  97. if (FacadesRequest::has('product')) {
  98. $product = Product::findOrFail(FacadesRequest::input('product'));
  99. // Get node resource allocation info
  100. $node = $product->nodes()->findOrFail(FacadesRequest::input('node'));
  101. $nodeName = $node->name;
  102. // Check if node has enough memory and disk space
  103. $checkResponse = Pterodactyl::checkNodeResources($node, $product->memory, $product->disk);
  104. if ($checkResponse == false) {
  105. return redirect()->route('servers.index')->with('error', __("The node '".$nodeName."' doesn't have the required memory or disk left to allocate this product."));
  106. }
  107. // Min. Credits
  108. if (
  109. Auth::user()->credits < $product->minimum_credits ||
  110. Auth::user()->credits < $product->price
  111. ) {
  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 (config('SETTINGS::USER:FORCE_EMAIL_VERIFICATION', 'false') === 'true' && ! 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 (! config('SETTINGS::SYSTEM:CREATION_OF_NEW_SERVERS', 'true') && 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 (config('SETTINGS::USER:FORCE_DISCORD_VERIFICATION', 'false') === 'true' && ! 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)
  131. {
  132. /** @var Node $node */
  133. /** @var Egg $egg */
  134. /** @var Product $product */
  135. if (! is_null($this->validateConfigurationRules())) {
  136. return $this->validateConfigurationRules();
  137. }
  138. $request->validate([
  139. 'name' => 'required|max:191',
  140. 'node' => 'required|exists:nodes,id',
  141. 'egg' => 'required|exists:eggs,id',
  142. 'product' => 'required|exists:products,id',
  143. ]);
  144. //get required resources
  145. $product = Product::query()->findOrFail($request->input('product'));
  146. $egg = $product->eggs()->findOrFail($request->input('egg'));
  147. $node = $product->nodes()->findOrFail($request->input('node'));
  148. $server = $request->user()->servers()->create([
  149. 'name' => $request->input('name'),
  150. 'product_id' => $request->input('product'),
  151. 'last_billed' => Carbon::now()->toDateTimeString(),
  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. // Charge first billing cycle
  170. $request->user()->decrement('credits', $server->product->price);
  171. return redirect()->route('servers.index')->with('success', __('Server created'));
  172. }
  173. /**
  174. * return redirect with error
  175. *
  176. * @param Server $server
  177. * @return RedirectResponse
  178. */
  179. private function noAllocationsError(Server $server)
  180. {
  181. $server->delete();
  182. Auth::user()->notify(new ServerCreationError($server));
  183. return redirect()->route('servers.index')->with('error', __('No allocations satisfying the requirements for automatic deployment on this node were found.'));
  184. }
  185. /**
  186. * return redirect with error
  187. *
  188. * @param Response $response
  189. * @param Server $server
  190. * @return RedirectResponse
  191. */
  192. private function serverCreationFailed(Response $response, Server $server)
  193. {
  194. $server->delete();
  195. return redirect()->route('servers.index')->with('error', json_encode($response->json()));
  196. }
  197. /** Remove the specified resource from storage. */
  198. public function destroy(Server $server)
  199. {
  200. try {
  201. $server->delete();
  202. return redirect()->route('servers.index')->with('success', __('Server removed'));
  203. } catch (Exception $e) {
  204. return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to remove a resource"') . $e->getMessage() . '"');
  205. }
  206. }
  207. /** Cancel Server */
  208. public function cancel (Server $server)
  209. {
  210. try {
  211. error_log($server->update([
  212. 'cancelled' => now(),
  213. ]));
  214. return redirect()->route('servers.index')->with('success', __('Server cancelled'));
  215. } catch (Exception $e) {
  216. return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to cancel the server"') . $e->getMessage() . '"');
  217. }
  218. }
  219. /** Show Server Settings */
  220. public function show(Server $server)
  221. {
  222. if ($server->user_id != Auth::user()->id) {
  223. return back()->with('error', __('´This is not your Server!'));
  224. }
  225. $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id);
  226. $serverRelationships = $serverAttributes['relationships'];
  227. $serverLocationAttributes = $serverRelationships['location']['attributes'];
  228. //Get current product
  229. $currentProduct = Product::where('id', $server->product_id)->first();
  230. //Set server infos
  231. $server->location = $serverLocationAttributes['long'] ?
  232. $serverLocationAttributes['long'] :
  233. $serverLocationAttributes['short'];
  234. $server->node = $serverRelationships['node']['attributes']['name'];
  235. $server->name = $serverAttributes['name'];
  236. $server->egg = $serverRelationships['egg']['attributes']['name'];
  237. $pteroNode = Pterodactyl::getNode($serverRelationships['node']['attributes']['id']);
  238. $products = Product::orderBy('created_at')
  239. ->whereHas('nodes', function (Builder $builder) use ($serverRelationships) { //Only show products for that node
  240. $builder->where('id', '=', $serverRelationships['node']['attributes']['id']);
  241. })
  242. ->get();
  243. // Set the each product eggs array to just contain the eggs name
  244. foreach ($products as $product) {
  245. $product->eggs = $product->eggs->pluck('name')->toArray();
  246. 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']) {
  247. $product->doesNotFit = true;
  248. }
  249. }
  250. return view('servers.settings')->with([
  251. 'server' => $server,
  252. 'products' => $products,
  253. ]);
  254. }
  255. public function upgrade(Server $server, Request $request)
  256. {
  257. if ($server->user_id != Auth::user()->id) {
  258. return redirect()->route('servers.index');
  259. }
  260. if (! isset($request->product_upgrade)) {
  261. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('this product is the only one'));
  262. }
  263. $user = Auth::user();
  264. $oldProduct = Product::where('id', $server->product->id)->first();
  265. $newProduct = Product::where('id', $request->product_upgrade)->first();
  266. $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id);
  267. $serverRelationships = $serverAttributes['relationships'];
  268. // Get node resource allocation info
  269. $nodeId = $serverRelationships['node']['attributes']['id'];
  270. $node = Node::where('id', $nodeId)->firstOrFail();
  271. $nodeName = $node->name;
  272. // Check if node has enough memory and disk space
  273. $requireMemory = $newProduct->memory - $oldProduct->memory;
  274. $requiredisk = $newProduct->disk - $oldProduct->disk;
  275. $checkResponse = Pterodactyl::checkNodeResources($node, $requireMemory, $requiredisk);
  276. if ($checkResponse == false) {
  277. return redirect()->route('servers.index')->with('error', __("The node '".$nodeName."' doesn't have the required memory or disk left to upgrade the server."));
  278. }
  279. $priceupgrade = $newProduct->getHourlyPrice();
  280. if ($priceupgrade < $oldProduct->getHourlyPrice()) {
  281. $priceupgrade = 0;
  282. }
  283. if ($user->credits >= $priceupgrade && $user->credits >= $newProduct->minimum_credits) {
  284. $server->product_id = $request->product_upgrade;
  285. $server->update();
  286. $server->allocation = $serverAttributes['allocation'];
  287. $response = Pterodactyl::updateServer($server, $newProduct);
  288. if ($response->failed()) {
  289. return $this->serverCreationFailed($response, $server);
  290. }
  291. //update user balance
  292. $user->decrement('credits', $priceupgrade);
  293. //restart the server
  294. $response = Pterodactyl::powerAction($server, 'restart');
  295. if ($response->failed()) {
  296. return redirect()->route('servers.index')->with('error', $response->json()['errors'][0]['detail']);
  297. }
  298. return redirect()->route('servers.show', ['server' => $server->id])->with('success', __('Server Successfully Upgraded'));
  299. } else {
  300. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('Not Enough Balance for Upgrade'));
  301. }
  302. }
  303. }