ServerController.php 15 KB

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