ServerController.php 14 KB

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