ServerController.php 15 KB

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