ServerController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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 Carbon\Carbon;
  11. use App\Settings\UserSettings;
  12. use App\Settings\ServerSettings;
  13. use App\Settings\PterodactylSettings;
  14. use App\Classes\PterodactylClient;
  15. use App\Settings\GeneralSettings;
  16. use Exception;
  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, $general_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, GeneralSettings $generalSettings)
  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 ' . $generalSettings->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()->cannot("admin.servers.bypass_creation_enabled")) {
  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, GeneralSettings $generalSettings)
  149. {
  150. /** @var Node $node */
  151. /** @var Egg $egg */
  152. /** @var Product $product */
  153. $validate_configuration = $this->validateConfigurationRules($user_settings, $server_settings, $generalSettings);
  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. 'last_billed' => Carbon::now()->toDateTimeString(),
  171. ]);
  172. //get free allocation ID
  173. $allocationId = $this->pterodactyl->getFreeAllocationId($node);
  174. if (!$allocationId) {
  175. return $this->noAllocationsError($server);
  176. }
  177. //create server on pterodactyl
  178. $response = $this->pterodactyl->createServer($server, $egg, $allocationId);
  179. if ($response->failed()) {
  180. return $this->serverCreationFailed($response, $server);
  181. }
  182. $serverAttributes = $response->json()['attributes'];
  183. //update server with pterodactyl_id
  184. $server->update([
  185. 'pterodactyl_id' => $serverAttributes['id'],
  186. 'identifier' => $serverAttributes['identifier'],
  187. ]);
  188. // Charge first billing cycle
  189. $request->user()->decrement('credits', $server->product->price);
  190. return redirect()->route('servers.index')->with('success', __('Server created'));
  191. }
  192. /**
  193. * return redirect with error
  194. *
  195. * @param Server $server
  196. * @return RedirectResponse
  197. */
  198. private function noAllocationsError(Server $server)
  199. {
  200. $server->delete();
  201. Auth::user()->notify(new ServerCreationError($server));
  202. return redirect()->route('servers.index')->with('error', __('No allocations satisfying the requirements for automatic deployment on this node were found.'));
  203. }
  204. /**
  205. * return redirect with error
  206. *
  207. * @param Response $response
  208. * @param Server $server
  209. * @return RedirectResponse
  210. */
  211. private function serverCreationFailed(Response $response, Server $server)
  212. {
  213. return redirect()->route('servers.index')->with('error', json_encode($response->json()));
  214. }
  215. /** Remove the specified resource from storage. */
  216. public function destroy(Server $server)
  217. {
  218. try {
  219. $server->delete();
  220. return redirect()->route('servers.index')->with('success', __('Server removed'));
  221. } catch (Exception $e) {
  222. return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to remove a resource"') . $e->getMessage() . '"');
  223. }
  224. }
  225. /** Cancel Server */
  226. public function cancel(Server $server)
  227. {
  228. if ($server->user_id != Auth::user()->id) {
  229. return back()->with('error', __('This is not your Server!'));
  230. }
  231. try {
  232. $server->update([
  233. 'canceled' => now(),
  234. ]);
  235. return redirect()->route('servers.index')->with('success', __('Server canceled'));
  236. } catch (Exception $e) {
  237. return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to cancel the server"') . $e->getMessage() . '"');
  238. }
  239. }
  240. /** Show Server Settings */
  241. public function show(Server $server, ServerSettings $server_settings, GeneralSettings $general_settings)
  242. {
  243. if ($server->user_id != Auth::user()->id) {
  244. return back()->with('error', __('This is not your Server!'));
  245. }
  246. $serverAttributes = $this->pterodactyl->getServerAttributes($server->pterodactyl_id);
  247. $serverRelationships = $serverAttributes['relationships'];
  248. $serverLocationAttributes = $serverRelationships['location']['attributes'];
  249. //Get current product
  250. $currentProduct = Product::where('id', $server->product_id)->first();
  251. //Set server infos
  252. $server->location = $serverLocationAttributes['long'] ?
  253. $serverLocationAttributes['long'] :
  254. $serverLocationAttributes['short'];
  255. $server->node = $serverRelationships['node']['attributes']['name'];
  256. $server->name = $serverAttributes['name'];
  257. $server->egg = $serverRelationships['egg']['attributes']['name'];
  258. $pteroNode = $this->pterodactyl->getNode($serverRelationships['node']['attributes']['id']);
  259. $products = Product::orderBy('created_at')
  260. ->whereHas('nodes', function (Builder $builder) use ($serverRelationships) { //Only show products for that node
  261. $builder->where('id', '=', $serverRelationships['node']['attributes']['id']);
  262. })
  263. ->get();
  264. // Set the each product eggs array to just contain the eggs name
  265. foreach ($products as $product) {
  266. $product->eggs = $product->eggs->pluck('name')->toArray();
  267. 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']) {
  268. $product->doesNotFit = true;
  269. }
  270. }
  271. return view('servers.settings')->with([
  272. 'server' => $server,
  273. 'products' => $products,
  274. 'server_enable_upgrade' => $server_settings->enable_upgrade,
  275. 'credits_display_name' => $general_settings->credits_display_name
  276. ]);
  277. }
  278. public function upgrade(Server $server, Request $request)
  279. {
  280. $this->checkPermission(self::UPGRADE_PERMISSION);
  281. if ($server->user_id != Auth::user()->id) {
  282. return redirect()->route('servers.index');
  283. }
  284. if (!isset($request->product_upgrade)) {
  285. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('this product is the only one'));
  286. }
  287. $user = Auth::user();
  288. $oldProduct = Product::where('id', $server->product->id)->first();
  289. $newProduct = Product::where('id', $request->product_upgrade)->first();
  290. $serverAttributes = $this->pterodactyl->getServerAttributes($server->pterodactyl_id);
  291. $serverRelationships = $serverAttributes['relationships'];
  292. // Get node resource allocation info
  293. $nodeId = $serverRelationships['node']['attributes']['id'];
  294. $node = Node::where('id', $nodeId)->firstOrFail();
  295. $nodeName = $node->name;
  296. // Check if node has enough memory and disk space
  297. $requireMemory = $newProduct->memory - $oldProduct->memory;
  298. $requiredisk = $newProduct->disk - $oldProduct->disk;
  299. $checkResponse = $this->pterodactyl->checkNodeResources($node, $requireMemory, $requiredisk);
  300. if ($checkResponse == false) {
  301. return redirect()->route('servers.index')->with('error', __("The node '" . $nodeName . "' doesn't have the required memory or disk left to upgrade the server."));
  302. }
  303. // calculate the amount of credits that the user overpayed for the old product when canceling the server right now
  304. // billing periods are hourly, daily, weekly, monthly, quarterly, half-annually, annually
  305. $billingPeriod = $oldProduct->billing_period;
  306. // seconds
  307. $billingPeriods = [
  308. 'hourly' => 3600,
  309. 'daily' => 86400,
  310. 'weekly' => 604800,
  311. 'monthly' => 2592000,
  312. 'quarterly' => 7776000,
  313. 'half-annually' => 15552000,
  314. 'annually' => 31104000
  315. ];
  316. // Get the amount of hours the user has been using the server
  317. $billingPeriodMultiplier = $billingPeriods[$billingPeriod];
  318. $timeDifference = now()->diffInSeconds($server->last_billed);
  319. // Calculate the price for the time the user has been using the server
  320. $overpayedCredits = $oldProduct->price - $oldProduct->price * ($timeDifference / $billingPeriodMultiplier);
  321. if ($user->credits >= $newProduct->price && $user->credits >= $newProduct->minimum_credits) {
  322. $server->allocation = $serverAttributes['allocation'];
  323. $response = $this->pterodactyl->updateServer($server, $newProduct);
  324. 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."));
  325. //restart the server
  326. $response = $this->pterodactyl->powerAction($server, 'restart');
  327. if ($response->failed()) return redirect()->route('servers.index')->with('error', 'Upgrade Failed! Could not restart the server: ' . $response->json()['errors'][0]['detail']);
  328. // Remove the allocation property from the server object as it is not a column in the database
  329. unset($server->allocation);
  330. // Update the server on controlpanel
  331. $server->update([
  332. 'product_id' => $newProduct->id,
  333. 'updated_at' => now(),
  334. 'last_billed' => now(),
  335. 'canceled' => null,
  336. ]);
  337. // Refund the user the overpayed credits
  338. if ($overpayedCredits > 0) $user->increment('credits', $overpayedCredits);
  339. // Withdraw the credits for the new product
  340. $user->decrement('credits', $newProduct->price);
  341. return redirect()->route('servers.show', ['server' => $server->id])->with('success', __('Server Successfully Upgraded'));
  342. } else {
  343. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('Not Enough Balance for Upgrade'));
  344. }
  345. }
  346. }