ServerController.php 15 KB

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