ServerController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. 'store_enabled' => $general_settings->store_enabled
  105. ]);
  106. }
  107. /**
  108. * @return null|RedirectResponse
  109. */
  110. private function validateConfigurationRules(UserSettings $user_settings, ServerSettings $server_settings, GeneralSettings $generalSettings)
  111. {
  112. //limit validation
  113. if (Auth::user()->servers()->count() >= Auth::user()->server_limit) {
  114. return redirect()->route('servers.index')->with('error', __('Server limit reached!'));
  115. }
  116. // minimum credits && Check for Allocation
  117. if (FacadesRequest::has('product')) {
  118. $product = Product::findOrFail(FacadesRequest::input('product'));
  119. // Get node resource allocation info
  120. $node = $product->nodes()->findOrFail(FacadesRequest::input('node'));
  121. $nodeName = $node->name;
  122. // Check if node has enough memory and disk space
  123. $checkResponse = $this->pterodactyl->checkNodeResources($node, $product->memory, $product->disk);
  124. if ($checkResponse == false) {
  125. return redirect()->route('servers.index')->with('error', __("The node '" . $nodeName . "' doesn't have the required memory or disk left to allocate this product."));
  126. }
  127. // Min. Credits
  128. if (Auth::user()->credits < ($product->minimum_credits == -1
  129. ? $user_settings->min_credits_to_make_server
  130. : $product->minimum_credits)) {
  131. return redirect()->route('servers.index')->with('error', 'You do not have the required amount of ' . $generalSettings->credits_display_name . ' to use this product!');
  132. }
  133. }
  134. //Required Verification for creating an server
  135. if ($user_settings->force_email_verification && !Auth::user()->hasVerifiedEmail()) {
  136. return redirect()->route('profile.index')->with('error', __('You are required to verify your email address before you can create a server.'));
  137. }
  138. //Required Verification for creating an server
  139. if (!$server_settings->creation_enabled && Auth::user()->cannot("admin.servers.bypass_creation_enabled")) {
  140. return redirect()->route('servers.index')->with('error', __('The system administrator has blocked the creation of new servers.'));
  141. }
  142. //Required Verification for creating an server
  143. if ($user_settings->force_discord_verification && !Auth::user()->discordUser) {
  144. return redirect()->route('profile.index')->with('error', __('You are required to link your discord account before you can create a server.'));
  145. }
  146. return null;
  147. }
  148. /** Store a newly created resource in storage. */
  149. public function store(Request $request, UserSettings $user_settings, ServerSettings $server_settings, GeneralSettings $generalSettings)
  150. {
  151. /** @var Node $node */
  152. /** @var Egg $egg */
  153. /** @var Product $product */
  154. $validate_configuration = $this->validateConfigurationRules($user_settings, $server_settings, $generalSettings);
  155. if (!is_null($validate_configuration)) {
  156. return $validate_configuration;
  157. }
  158. $request->validate([
  159. 'name' => 'required|max:191',
  160. 'node' => 'required|exists:nodes,id',
  161. 'egg' => 'required|exists:eggs,id',
  162. 'product' => 'required|exists:products,id',
  163. ]);
  164. //get required resources
  165. $product = Product::query()->findOrFail($request->input('product'));
  166. $egg = $product->eggs()->findOrFail($request->input('egg'));
  167. $node = $product->nodes()->findOrFail($request->input('node'));
  168. $server = $request->user()->servers()->create([
  169. 'name' => $request->input('name'),
  170. 'product_id' => $request->input('product'),
  171. 'last_billed' => Carbon::now()->toDateTimeString(),
  172. ]);
  173. //get free allocation ID
  174. $allocationId = $this->pterodactyl->getFreeAllocationId($node);
  175. if (!$allocationId) {
  176. return $this->noAllocationsError($server);
  177. }
  178. //create server on pterodactyl
  179. $response = $this->pterodactyl->createServer($server, $egg, $allocationId);
  180. if ($response->failed()) {
  181. return $this->serverCreationFailed($response, $server);
  182. }
  183. $serverAttributes = $response->json()['attributes'];
  184. //update server with pterodactyl_id
  185. $server->update([
  186. 'pterodactyl_id' => $serverAttributes['id'],
  187. 'identifier' => $serverAttributes['identifier'],
  188. ]);
  189. // Charge first billing cycle
  190. $request->user()->decrement('credits', $server->product->price);
  191. return redirect()->route('servers.index')->with('success', __('Server created'));
  192. }
  193. /**
  194. * return redirect with error
  195. *
  196. * @param Server $server
  197. * @return RedirectResponse
  198. */
  199. private function noAllocationsError(Server $server)
  200. {
  201. $server->delete();
  202. Auth::user()->notify(new ServerCreationError($server));
  203. return redirect()->route('servers.index')->with('error', __('No allocations satisfying the requirements for automatic deployment on this node were found.'));
  204. }
  205. /**
  206. * return redirect with error
  207. *
  208. * @param Response $response
  209. * @param Server $server
  210. * @return RedirectResponse
  211. */
  212. private function serverCreationFailed(Response $response, Server $server)
  213. {
  214. return redirect()->route('servers.index')->with('error', json_encode($response->json()));
  215. }
  216. /** Remove the specified resource from storage. */
  217. public function destroy(Server $server)
  218. {
  219. try {
  220. $server->delete();
  221. return redirect()->route('servers.index')->with('success', __('Server removed'));
  222. } catch (Exception $e) {
  223. return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to remove a resource"') . $e->getMessage() . '"');
  224. }
  225. }
  226. /** Cancel Server */
  227. public function cancel(Server $server)
  228. {
  229. if ($server->user_id != Auth::user()->id) {
  230. return back()->with('error', __('This is not your Server!'));
  231. }
  232. try {
  233. $server->update([
  234. 'canceled' => now(),
  235. ]);
  236. return redirect()->route('servers.index')->with('success', __('Server canceled'));
  237. } catch (Exception $e) {
  238. return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to cancel the server"') . $e->getMessage() . '"');
  239. }
  240. }
  241. /** Show Server Settings */
  242. public function show(Server $server, ServerSettings $server_settings, GeneralSettings $general_settings)
  243. {
  244. if ($server->user_id != Auth::user()->id) {
  245. return back()->with('error', __('This is not your Server!'));
  246. }
  247. $serverAttributes = $this->pterodactyl->getServerAttributes($server->pterodactyl_id);
  248. $serverRelationships = $serverAttributes['relationships'];
  249. $serverLocationAttributes = $serverRelationships['location']['attributes'];
  250. //Get current product
  251. $currentProduct = Product::where('id', $server->product_id)->first();
  252. //Set server infos
  253. $server->location = $serverLocationAttributes['long'] ?
  254. $serverLocationAttributes['long'] :
  255. $serverLocationAttributes['short'];
  256. $server->node = $serverRelationships['node']['attributes']['name'];
  257. $server->name = $serverAttributes['name'];
  258. $server->egg = $serverRelationships['egg']['attributes']['name'];
  259. $pteroNode = $this->pterodactyl->getNode($serverRelationships['node']['attributes']['id']);
  260. $products = Product::orderBy('created_at')
  261. ->whereHas('nodes', function (Builder $builder) use ($serverRelationships) { //Only show products for that node
  262. $builder->where('id', '=', $serverRelationships['node']['attributes']['id']);
  263. })
  264. ->get();
  265. // Set the each product eggs array to just contain the eggs name
  266. foreach ($products as $product) {
  267. $product->eggs = $product->eggs->pluck('name')->toArray();
  268. 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']) {
  269. $product->doesNotFit = true;
  270. }
  271. }
  272. return view('servers.settings')->with([
  273. 'server' => $server,
  274. 'products' => $products,
  275. 'server_enable_upgrade' => $server_settings->enable_upgrade,
  276. 'credits_display_name' => $general_settings->credits_display_name
  277. ]);
  278. }
  279. public function upgrade(Server $server, Request $request)
  280. {
  281. $this->checkPermission(self::UPGRADE_PERMISSION);
  282. if ($server->user_id != Auth::user()->id) {
  283. return redirect()->route('servers.index');
  284. }
  285. if (!isset($request->product_upgrade)) {
  286. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('this product is the only one'));
  287. }
  288. $user = Auth::user();
  289. $oldProduct = Product::where('id', $server->product->id)->first();
  290. $newProduct = Product::where('id', $request->product_upgrade)->first();
  291. $serverAttributes = $this->pterodactyl->getServerAttributes($server->pterodactyl_id);
  292. $serverRelationships = $serverAttributes['relationships'];
  293. // Get node resource allocation info
  294. $nodeId = $serverRelationships['node']['attributes']['id'];
  295. $node = Node::where('id', $nodeId)->firstOrFail();
  296. $nodeName = $node->name;
  297. // Check if node has enough memory and disk space
  298. $requireMemory = $newProduct->memory - $oldProduct->memory;
  299. $requiredisk = $newProduct->disk - $oldProduct->disk;
  300. $checkResponse = $this->pterodactyl->checkNodeResources($node, $requireMemory, $requiredisk);
  301. if ($checkResponse == false) {
  302. return redirect()->route('servers.index')->with('error', __("The node '" . $nodeName . "' doesn't have the required memory or disk left to upgrade the server."));
  303. }
  304. // calculate the amount of credits that the user overpayed for the old product when canceling the server right now
  305. // billing periods are hourly, daily, weekly, monthly, quarterly, half-annually, annually
  306. $billingPeriod = $oldProduct->billing_period;
  307. // seconds
  308. $billingPeriods = [
  309. 'hourly' => 3600,
  310. 'daily' => 86400,
  311. 'weekly' => 604800,
  312. 'monthly' => 2592000,
  313. 'quarterly' => 7776000,
  314. 'half-annually' => 15552000,
  315. 'annually' => 31104000
  316. ];
  317. // Get the amount of hours the user has been using the server
  318. $billingPeriodMultiplier = $billingPeriods[$billingPeriod];
  319. $timeDifference = now()->diffInSeconds($server->last_billed);
  320. // Calculate the price for the time the user has been using the server
  321. $overpayedCredits = $oldProduct->price - $oldProduct->price * ($timeDifference / $billingPeriodMultiplier);
  322. if ($user->credits >= $newProduct->price && $user->credits >= $newProduct->minimum_credits) {
  323. $server->allocation = $serverAttributes['allocation'];
  324. $response = $this->pterodactyl->updateServer($server, $newProduct);
  325. 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."));
  326. //restart the server
  327. $response = $this->pterodactyl->powerAction($server, 'restart');
  328. if ($response->failed()) return redirect()->route('servers.index')->with('error', 'Upgrade Failed! Could not restart the server: ' . $response->json()['errors'][0]['detail']);
  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. 'canceled' => 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. return redirect()->route('servers.show', ['server' => $server->id])->with('success', __('Server Successfully Upgraded'));
  343. } else {
  344. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('Not Enough Balance for Upgrade'));
  345. }
  346. }
  347. }