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);
  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, GeneralSettings $general_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. 'credits_display_name' => $general_settings->credits_display_name
  100. ]);
  101. }
  102. /**
  103. * @return null|RedirectResponse
  104. */
  105. private function validateConfigurationRules(UserSettings $user_settings, ServerSettings $server_settings)
  106. {
  107. //limit validation
  108. if (Auth::user()->servers()->count() >= Auth::user()->server_limit) {
  109. return redirect()->route('servers.index')->with('error', __('Server limit reached!'));
  110. }
  111. // minimum credits && Check for Allocation
  112. if (FacadesRequest::has('product')) {
  113. $product = Product::findOrFail(FacadesRequest::input('product'));
  114. // Get node resource allocation info
  115. $node = $product->nodes()->findOrFail(FacadesRequest::input('node'));
  116. $nodeName = $node->name;
  117. // Check if node has enough memory and disk space
  118. $checkResponse = $this->pterodactyl->checkNodeResources($node, $product->memory, $product->disk);
  119. if ($checkResponse == false) {
  120. return redirect()->route('servers.index')->with('error', __("The node '".$nodeName."' doesn't have the required memory or disk left to allocate this product."));
  121. }
  122. // Min. Credits
  123. if (Auth::user()->credits < ($product->minimum_credits == -1
  124. ? $user_settings->min_credits_to_make_server
  125. : $product->minimum_credits)) {
  126. return redirect()->route('servers.index')->with('error', 'You do not have the required amount of '.CREDITS_DISPLAY_NAME.' to use this product!');
  127. }
  128. }
  129. //Required Verification for creating an server
  130. if ($user_settings->force_email_verification && !Auth::user()->hasVerifiedEmail()) {
  131. return redirect()->route('profile.index')->with('error', __('You are required to verify your email address before you can create a server.'));
  132. }
  133. //Required Verification for creating an server
  134. if (!$server_settings->creation_enabled && Auth::user()->role != 'admin') {
  135. return redirect()->route('servers.index')->with('error', __('The system administrator has blocked the creation of new servers.'));
  136. }
  137. //Required Verification for creating an server
  138. if ($user_settings->force_discord_verification && !Auth::user()->discordUser) {
  139. return redirect()->route('profile.index')->with('error', __('You are required to link your discord account before you can create a server.'));
  140. }
  141. return null;
  142. }
  143. /** Store a newly created resource in storage. */
  144. public function store(Request $request, UserSettings $user_settings, ServerSettings $server_settings)
  145. {
  146. /** @var Node $node */
  147. /** @var Egg $egg */
  148. /** @var Product $product */
  149. $validate_configuration = $this->validateConfigurationRules($user_settings, $server_settings);
  150. if (!is_null($validate_configuration)) {
  151. return $validate_configuration;
  152. }
  153. $request->validate([
  154. 'name' => 'required|max:191',
  155. 'node' => 'required|exists:nodes,id',
  156. 'egg' => 'required|exists:eggs,id',
  157. 'product' => 'required|exists:products,id',
  158. ]);
  159. //get required resources
  160. $product = Product::query()->findOrFail($request->input('product'));
  161. $egg = $product->eggs()->findOrFail($request->input('egg'));
  162. $node = $product->nodes()->findOrFail($request->input('node'));
  163. $server = $request->user()->servers()->create([
  164. 'name' => $request->input('name'),
  165. 'product_id' => $request->input('product'),
  166. ]);
  167. //get free allocation ID
  168. $allocationId = $this->pterodactyl->getFreeAllocationId($node);
  169. if (! $allocationId) {
  170. return $this->noAllocationsError($server);
  171. }
  172. //create server on pterodactyl
  173. $response = $this->pterodactyl->createServer($server, $egg, $allocationId);
  174. if ($response->failed()) {
  175. return $this->serverCreationFailed($response, $server);
  176. }
  177. $serverAttributes = $response->json()['attributes'];
  178. //update server with pterodactyl_id
  179. $server->update([
  180. 'pterodactyl_id' => $serverAttributes['id'],
  181. 'identifier' => $serverAttributes['identifier'],
  182. ]);
  183. if ($server_settings->charge_first_hour) {
  184. if ($request->user()->credits >= $server->product->getHourlyPrice()) {
  185. $request->user()->decrement('credits', $server->product->getHourlyPrice());
  186. }
  187. }
  188. return redirect()->route('servers.index')->with('success', __('Server created'));
  189. }
  190. /**
  191. * return redirect with error
  192. *
  193. * @param Server $server
  194. * @return RedirectResponse
  195. */
  196. private function noAllocationsError(Server $server)
  197. {
  198. $server->delete();
  199. Auth::user()->notify(new ServerCreationError($server));
  200. return redirect()->route('servers.index')->with('error', __('No allocations satisfying the requirements for automatic deployment on this node were found.'));
  201. }
  202. /**
  203. * return redirect with error
  204. *
  205. * @param Response $response
  206. * @param Server $server
  207. * @return RedirectResponse
  208. */
  209. private function serverCreationFailed(Response $response, Server $server)
  210. {
  211. $server->delete();
  212. return redirect()->route('servers.index')->with('error', json_encode($response->json()));
  213. }
  214. /** Remove the specified resource from storage. */
  215. public function destroy(Server $server)
  216. {
  217. try {
  218. $server->delete();
  219. return redirect()->route('servers.index')->with('success', __('Server removed'));
  220. } catch (Exception $e) {
  221. return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to remove a resource "').$e->getMessage().'"');
  222. }
  223. }
  224. /** Show Server Settings */
  225. public function show(Server $server, ServerSettings $server_settings, GeneralSettings $general_settings)
  226. {
  227. if ($server->user_id != Auth::user()->id) {
  228. return back()->with('error', __('This is not your Server!'));
  229. }
  230. $serverAttributes = $this->pterodactyl->getServerAttributes($server->pterodactyl_id);
  231. $serverRelationships = $serverAttributes['relationships'];
  232. $serverLocationAttributes = $serverRelationships['location']['attributes'];
  233. //Get current product
  234. $currentProduct = Product::where('id', $server->product_id)->first();
  235. //Set server infos
  236. $server->location = $serverLocationAttributes['long'] ?
  237. $serverLocationAttributes['long'] :
  238. $serverLocationAttributes['short'];
  239. $server->node = $serverRelationships['node']['attributes']['name'];
  240. $server->name = $serverAttributes['name'];
  241. $server->egg = $serverRelationships['egg']['attributes']['name'];
  242. $pteroNode = $this->pterodactyl->getNode($serverRelationships['node']['attributes']['id']);
  243. $products = Product::orderBy('created_at')
  244. ->whereHas('nodes', function (Builder $builder) use ($serverRelationships) { //Only show products for that node
  245. $builder->where('id', '=', $serverRelationships['node']['attributes']['id']);
  246. })
  247. ->get();
  248. // Set the each product eggs array to just contain the eggs name
  249. foreach ($products as $product) {
  250. $product->eggs = $product->eggs->pluck('name')->toArray();
  251. 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']) {
  252. $product->doesNotFit = true;
  253. }
  254. }
  255. return view('servers.settings')->with([
  256. 'server' => $server,
  257. 'products' => $products,
  258. 'server_enable_upgrade' => $server_settings->enable_upgrade,
  259. 'credits_display_name' => $general_settings->credits_display_name
  260. ]);
  261. }
  262. public function upgrade(Server $server, Request $request)
  263. {
  264. if ($server->user_id != Auth::user()->id) {
  265. return redirect()->route('servers.index');
  266. }
  267. if (! isset($request->product_upgrade)) {
  268. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('this product is the only one'));
  269. }
  270. $user = Auth::user();
  271. $oldProduct = Product::where('id', $server->product->id)->first();
  272. $newProduct = Product::where('id', $request->product_upgrade)->first();
  273. $serverAttributes = $this->pterodactyl->getServerAttributes($server->pterodactyl_id);
  274. $serverRelationships = $serverAttributes['relationships'];
  275. // Get node resource allocation info
  276. $nodeId = $serverRelationships['node']['attributes']['id'];
  277. $node = Node::where('id', $nodeId)->firstOrFail();
  278. $nodeName = $node->name;
  279. // Check if node has enough memory and disk space
  280. $requireMemory = $newProduct->memory - $oldProduct->memory;
  281. $requiredisk = $newProduct->disk - $oldProduct->disk;
  282. $checkResponse = $this->pterodactyl->checkNodeResources($node, $requireMemory, $requiredisk);
  283. if ($checkResponse == false) {
  284. return redirect()->route('servers.index')->with('error', __("The node '".$nodeName."' doesn't have the required memory or disk left to upgrade the server."));
  285. }
  286. $priceupgrade = $newProduct->getHourlyPrice();
  287. if ($priceupgrade < $oldProduct->getHourlyPrice()) {
  288. $priceupgrade = 0;
  289. }
  290. if ($user->credits >= $priceupgrade && $user->credits >= $newProduct->minimum_credits) {
  291. $server->product_id = $request->product_upgrade;
  292. $server->update();
  293. $server->allocation = $serverAttributes['allocation'];
  294. $response = $this->pterodactyl->updateServer($server, $newProduct);
  295. if ($response->failed()) return redirect()->route('servers.index')->with('error', __("The system was unable to update your server product. Please try again later or contact support."));
  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. }