ServerController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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, $general_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, GeneralSettings $generalSettings)
  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 ' . $generalSettings->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, GeneralSettings $generalSettings)
  152. {
  153. /** @var Node $node */
  154. /** @var Egg $egg */
  155. /** @var Product $product */
  156. $validate_configuration = $this->validateConfigurationRules($user_settings, $server_settings, $generalSettings);
  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. if ($server->user_id != Auth::user()->id) {
  232. return back()->with('error', __('This is not your Server!'));
  233. }
  234. try {
  235. $server->update([
  236. 'cancelled' => now(),
  237. ]);
  238. return redirect()->route('servers.index')->with('success', __('Server cancelled'));
  239. } catch (Exception $e) {
  240. return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to cancel the server"') . $e->getMessage() . '"');
  241. }
  242. }
  243. /** Show Server Settings */
  244. public function show(Server $server, ServerSettings $server_settings, GeneralSettings $general_settings)
  245. {
  246. if ($server->user_id != Auth::user()->id) {
  247. return back()->with('error', __('This is not your Server!'));
  248. }
  249. $serverAttributes = $this->pterodactyl->getServerAttributes($server->pterodactyl_id);
  250. $serverRelationships = $serverAttributes['relationships'];
  251. $serverLocationAttributes = $serverRelationships['location']['attributes'];
  252. //Get current product
  253. $currentProduct = Product::where('id', $server->product_id)->first();
  254. //Set server infos
  255. $server->location = $serverLocationAttributes['long'] ?
  256. $serverLocationAttributes['long'] :
  257. $serverLocationAttributes['short'];
  258. $server->node = $serverRelationships['node']['attributes']['name'];
  259. $server->name = $serverAttributes['name'];
  260. $server->egg = $serverRelationships['egg']['attributes']['name'];
  261. $pteroNode = $this->pterodactyl->getNode($serverRelationships['node']['attributes']['id']);
  262. $products = Product::orderBy('created_at')
  263. ->whereHas('nodes', function (Builder $builder) use ($serverRelationships) { //Only show products for that node
  264. $builder->where('id', '=', $serverRelationships['node']['attributes']['id']);
  265. })
  266. ->get();
  267. // Set the each product eggs array to just contain the eggs name
  268. foreach ($products as $product) {
  269. $product->eggs = $product->eggs->pluck('name')->toArray();
  270. 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']) {
  271. $product->doesNotFit = true;
  272. }
  273. }
  274. return view('servers.settings')->with([
  275. 'server' => $server,
  276. 'products' => $products,
  277. 'server_enable_upgrade' => $server_settings->enable_upgrade,
  278. 'credits_display_name' => $general_settings->credits_display_name
  279. ]);
  280. }
  281. public function upgrade(Server $server, Request $request)
  282. {
  283. $this->checkPermission(self::UPGRADE_PERMISSION);
  284. if ($server->user_id != Auth::user()->id) {
  285. return redirect()->route('servers.index');
  286. }
  287. if (!isset($request->product_upgrade)) {
  288. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('this product is the only one'));
  289. }
  290. $user = Auth::user();
  291. $oldProduct = Product::where('id', $server->product->id)->first();
  292. $newProduct = Product::where('id', $request->product_upgrade)->first();
  293. $serverAttributes = $this->pterodactyl->getServerAttributes($server->pterodactyl_id);
  294. $serverRelationships = $serverAttributes['relationships'];
  295. // Get node resource allocation info
  296. $nodeId = $serverRelationships['node']['attributes']['id'];
  297. $node = Node::where('id', $nodeId)->firstOrFail();
  298. $nodeName = $node->name;
  299. // Check if node has enough memory and disk space
  300. $requireMemory = $newProduct->memory - $oldProduct->memory;
  301. $requiredisk = $newProduct->disk - $oldProduct->disk;
  302. $checkResponse = $this->pterodactyl->checkNodeResources($node, $requireMemory, $requiredisk);
  303. if ($checkResponse == false) {
  304. return redirect()->route('servers.index')->with('error', __("The node '" . $nodeName . "' doesn't have the required memory or disk left to upgrade the server."));
  305. }
  306. // calculate the amount of credits that the user overpayed for the old product when canceling the server right now
  307. // billing periods are hourly, daily, weekly, monthly, quarterly, half-annually, annually
  308. $billingPeriod = $oldProduct->billing_period;
  309. // seconds
  310. $billingPeriods = [
  311. 'hourly' => 3600,
  312. 'daily' => 86400,
  313. 'weekly' => 604800,
  314. 'monthly' => 2592000,
  315. 'quarterly' => 7776000,
  316. 'half-annually' => 15552000,
  317. 'annually' => 31104000
  318. ];
  319. // Get the amount of hours the user has been using the server
  320. $billingPeriodMultiplier = $billingPeriods[$billingPeriod];
  321. $timeDifference = now()->diffInSeconds($server->last_billed);
  322. // Calculate the price for the time the user has been using the server
  323. $overpayedCredits = $oldProduct->price - $oldProduct->price * ($timeDifference / $billingPeriodMultiplier);
  324. if ($user->credits >= $newProduct->price && $user->credits >= $newProduct->minimum_credits) {
  325. $server->allocation = $serverAttributes['allocation'];
  326. $response = $this->pterodactyl->updateServer($server, $newProduct);
  327. 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."));
  328. //update user balance
  329. $user->decrement('credits', $priceupgrade);
  330. //restart the server
  331. $response = $this->pterodactyl->powerAction($server, 'restart');
  332. if ($response->failed()) {
  333. return redirect()->route('servers.index')->with('error', $response->json()['errors'][0]['detail']);
  334. }
  335. // Remove the allocation property from the server object as it is not a column in the database
  336. unset($server->allocation);
  337. // Update the server on controlpanel
  338. $server->update([
  339. 'product_id' => $newProduct->id,
  340. 'updated_at' => now(),
  341. 'last_billed' => now(),
  342. 'cancelled' => null,
  343. ]);
  344. // Refund the user the overpayed credits
  345. if ($overpayedCredits > 0) $user->increment('credits', $overpayedCredits);
  346. // Withdraw the credits for the new product
  347. $user->decrement('credits', $newProduct->price);
  348. //restart the server
  349. $response = Pterodactyl::powerAction($server, "restart");
  350. if ($response->failed()) return redirect()->route('servers.index')->with('error', 'Server upgraded successfully! Could not restart the server: ' . $response->json()['errors'][0]['detail']);
  351. return redirect()->route('servers.show', ['server' => $server->id])->with('success', __('Server Successfully Upgraded'));
  352. } else {
  353. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('Not Enough Balance for Upgrade'));
  354. }
  355. }
  356. }