ServerController.php 18 KB

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