ServerController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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\Settings;
  11. use App\Notifications\ServerCreationError;
  12. use Exception;
  13. use Illuminate\Database\Eloquent\Builder;
  14. use Illuminate\Http\Client\Response;
  15. use Illuminate\Http\RedirectResponse;
  16. use Illuminate\Http\Request;
  17. use Illuminate\Support\Facades\Auth;
  18. use Illuminate\Support\Facades\Request as FacadesRequest;
  19. class ServerController extends Controller
  20. {
  21. /** Display a listing of the resource. */
  22. public function index()
  23. {
  24. $servers = Auth::user()->servers;
  25. //Get and set server infos each server
  26. foreach ($servers as $server) {
  27. //Get server infos from ptero
  28. $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id);
  29. $serverRelationships = $serverAttributes['relationships'];
  30. $serverLocationAttributes = $serverRelationships['location']['attributes'];
  31. //Set server infos
  32. $server->location = $serverLocationAttributes['long'] ?
  33. $serverLocationAttributes['long'] :
  34. $serverLocationAttributes['short'];
  35. $server->egg = $serverRelationships['egg']['attributes']['name'];
  36. $server->nest = $serverRelationships['nest']['attributes']['name'];
  37. $server->node = $serverRelationships['node']['attributes']['name'];
  38. //get productname by product_id for server
  39. $product = Product::find($server->product_id);
  40. $server->product = $product;
  41. }
  42. return view('servers.index')->with([
  43. 'servers' => $servers
  44. ]);
  45. }
  46. /** Show the form for creating a new resource. */
  47. public function create()
  48. {
  49. if (!is_null($this->validateConfigurationRules())) return $this->validateConfigurationRules();
  50. $productCount = Product::query()->where('disabled', '=', false)->count();
  51. $locations = Location::all();
  52. $nodeCount = Node::query()
  53. ->whereHas('products', function (Builder $builder) {
  54. $builder->where('disabled', '=', false);
  55. })->count();
  56. $eggs = Egg::query()
  57. ->whereHas('products', function (Builder $builder) {
  58. $builder->where('disabled', '=', false);
  59. })->get();
  60. $nests = Nest::query()
  61. ->whereHas('eggs', function (Builder $builder) {
  62. $builder->whereHas('products', function (Builder $builder) {
  63. $builder->where('disabled', '=', false);
  64. });
  65. })->get();
  66. return view('servers.create')->with([
  67. 'productCount' => $productCount,
  68. 'nodeCount' => $nodeCount,
  69. 'nests' => $nests,
  70. 'locations' => $locations,
  71. 'eggs' => $eggs,
  72. 'user' => Auth::user(),
  73. ]);
  74. }
  75. /**
  76. * @return null|RedirectResponse
  77. */
  78. private function validateConfigurationRules()
  79. {
  80. //limit validation
  81. if (Auth::user()->servers()->count() >= Auth::user()->server_limit) {
  82. return redirect()->route('servers.index')->with('error', __('Server limit reached!'));
  83. }
  84. // minimum credits && Check for Allocation
  85. if (FacadesRequest::has("product")) {
  86. $product = Product::findOrFail(FacadesRequest::input("product"));
  87. // Get node resource allocation info
  88. $node = $product->nodes()->findOrFail(FacadesRequest::input('node'));
  89. $nodeName = $node->name;
  90. // Check if node has enough memory and disk space
  91. $checkResponse = Pterodactyl::checkNodeResources($node, $product->memory, $product->disk);
  92. 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."));
  93. // Min. Credits
  94. if (
  95. Auth::user()->credits <
  96. ($product->minimum_credits == -1
  97. ? config('SETTINGS::USER:MINIMUM_REQUIRED_CREDITS_TO_MAKE_SERVER', 50)
  98. : $product->minimum_credits)
  99. ) {
  100. return redirect()->route('servers.index')->with('error', "You do not have the required amount of " . CREDITS_DISPLAY_NAME . " to use this product!");
  101. }
  102. }
  103. //Required Verification for creating an server
  104. if (config('SETTINGS::USER:FORCE_EMAIL_VERIFICATION', 'false') === 'true' && !Auth::user()->hasVerifiedEmail()) {
  105. return redirect()->route('profile.index')->with('error', __("You are required to verify your email address before you can create a server."));
  106. }
  107. //Required Verification for creating an server
  108. if (config('SETTINGS::USER:FORCE_DISCORD_VERIFICATION', 'false') === 'true' && !Auth::user()->discordUser) {
  109. return redirect()->route('profile.index')->with('error', __("You are required to link your discord account before you can create a server."));
  110. }
  111. return null;
  112. }
  113. /** Store a newly created resource in storage. */
  114. public function store(Request $request)
  115. {
  116. /** @var Node $node */
  117. /** @var Egg $egg */
  118. /** @var Product $product */
  119. if (!is_null($this->validateConfigurationRules())) return $this->validateConfigurationRules();
  120. $request->validate([
  121. "name" => "required|max:191",
  122. "node" => "required|exists:nodes,id",
  123. "egg" => "required|exists:eggs,id",
  124. "product" => "required|exists:products,id"
  125. ]);
  126. //get required resources
  127. $product = Product::query()->findOrFail($request->input('product'));
  128. $egg = $product->eggs()->findOrFail($request->input('egg'));
  129. $node = $product->nodes()->findOrFail($request->input('node'));
  130. $server = $request->user()->servers()->create([
  131. 'name' => $request->input('name'),
  132. 'product_id' => $request->input('product'),
  133. ]);
  134. //get free allocation ID
  135. $allocationId = Pterodactyl::getFreeAllocationId($node);
  136. if (!$allocationId) return $this->noAllocationsError($server);
  137. //create server on pterodactyl
  138. $response = Pterodactyl::createServer($server, $egg, $allocationId);
  139. if ($response->failed()) return $this->serverCreationFailed($response, $server);
  140. $serverAttributes = $response->json()['attributes'];
  141. //update server with pterodactyl_id
  142. $server->update([
  143. 'pterodactyl_id' => $serverAttributes['id'],
  144. 'identifier' => $serverAttributes['identifier']
  145. ]);
  146. if (config('SETTINGS::SYSTEM:SERVER_CREATE_CHARGE_FIRST_HOUR', 'true') == 'true') {
  147. if ($request->user()->credits >= $server->product->getHourlyPrice()) {
  148. $request->user()->decrement('credits', $server->product->getHourlyPrice());
  149. }
  150. }
  151. return redirect()->route('servers.index')->with('success', __('Server created'));
  152. }
  153. /**
  154. * return redirect with error
  155. * @param Server $server
  156. * @return RedirectResponse
  157. */
  158. private function noAllocationsError(Server $server)
  159. {
  160. $server->delete();
  161. Auth::user()->notify(new ServerCreationError($server));
  162. return redirect()->route('servers.index')->with('error', __('No allocations satisfying the requirements for automatic deployment on this node were found.'));
  163. }
  164. /**
  165. * return redirect with error
  166. * @param Response $response
  167. * @param Server $server
  168. * @return RedirectResponse
  169. */
  170. private function serverCreationFailed(Response $response, Server $server)
  171. {
  172. $server->delete();
  173. return redirect()->route('servers.index')->with('error', json_encode($response->json()));
  174. }
  175. /** Remove the specified resource from storage. */
  176. public function destroy(Server $server)
  177. {
  178. try {
  179. $server->delete();
  180. return redirect()->route('servers.index')->with('success', __('Server removed'));
  181. } catch (Exception $e) {
  182. return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to remove a resource "') . $e->getMessage() . '"');
  183. }
  184. }
  185. /** Show Server Settings */
  186. public function show(Server $server)
  187. {
  188. if($server->user_id != Auth::user()->id){ return back()->with('error', __('´This is not your Server!'));}
  189. $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id);
  190. $serverRelationships = $serverAttributes['relationships'];
  191. $serverLocationAttributes = $serverRelationships['location']['attributes'];
  192. //Set server infos
  193. $server->location = $serverLocationAttributes['long'] ?
  194. $serverLocationAttributes['long'] :
  195. $serverLocationAttributes['short'];
  196. $server->node = $serverRelationships['node']['attributes']['name'];
  197. $server->name = $serverAttributes['name'];
  198. $server->egg = $serverRelationships['egg']['attributes']['name'];
  199. $products = Product::orderBy("created_at")->get();
  200. // Set the each product eggs array to just contain the eggs name
  201. foreach ($products as $product) {
  202. $product->eggs = $product->eggs->pluck('name')->toArray();
  203. }
  204. return view('servers.settings')->with([
  205. 'server' => $server,
  206. 'products' => $products
  207. ]);
  208. }
  209. public function upgrade(Server $server, Request $request)
  210. {
  211. if($server->user_id != Auth::user()->id) return redirect()->route('servers.index');
  212. if(!isset($request->product_upgrade))
  213. {
  214. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('this product is the only one'));
  215. }
  216. $user = Auth::user();
  217. $oldProduct = Product::where('id', $server->product->id)->first();
  218. $newProduct = Product::where('id', $request->product_upgrade)->first();
  219. $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id);
  220. $priceupgrade = $newProduct->getHourlyPrice();
  221. if ($priceupgrade < $oldProduct->getHourlyPrice()) {
  222. $priceupgrade = 0;
  223. }
  224. if ($user->credits >= $priceupgrade)
  225. {
  226. $server->product_id = $request->product_upgrade;
  227. $server->update();
  228. $server->allocation = $serverAttributes['allocation'];
  229. $response = Pterodactyl::updateServer($server, $newProduct);
  230. if ($response->failed()) return $this->serverCreationFailed($response, $server);
  231. //update user balance
  232. $user->decrement('credits', $priceupgrade);
  233. //restart the server
  234. $response = Pterodactyl::powerAction($server, "restart");
  235. if ($response->failed()) return $this->serverCreationFailed($response, $server);
  236. return redirect()->route('servers.show', ['server' => $server->id])->with('success', __('Server Successfully Upgraded'));
  237. }
  238. else
  239. {
  240. return redirect()->route('servers.show', ['server' => $server->id])->with('error', __('Not Enough Balance for Upgrade'));
  241. }
  242. }
  243. }