ServerController.php 15 KB

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