ServerController.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 Carbon\Carbon;
  13. use Exception;
  14. use Illuminate\Database\Eloquent\Builder;
  15. use Illuminate\Http\Client\Response;
  16. use Illuminate\Http\RedirectResponse;
  17. use Illuminate\Http\Request;
  18. use Illuminate\Support\Facades\Auth;
  19. use Illuminate\Support\Facades\Request as FacadesRequest;
  20. class ServerController extends Controller
  21. {
  22. /** Display a listing of the resource. */
  23. public function index()
  24. {
  25. $servers = Auth::user()->servers;
  26. //Get and set server infos each server
  27. foreach ($servers as $server) {
  28. //Get server infos from ptero
  29. $serverAttributes = Pterodactyl::getServerAttributes($server->pterodactyl_id);
  30. $serverRelationships = $serverAttributes['relationships'];
  31. $serverLocationAttributes = $serverRelationships['location']['attributes'];
  32. //Set server infos
  33. $server->location = $serverLocationAttributes['long'] ?
  34. $serverLocationAttributes['long'] :
  35. $serverLocationAttributes['short'];
  36. $server->egg = $serverRelationships['egg']['attributes']['name'];
  37. $server->nest = $serverRelationships['nest']['attributes']['name'];
  38. $server->node = $serverRelationships['node']['attributes']['name'];
  39. //get productname by product_id for server
  40. $product = Product::find($server->product_id);
  41. $server->product = $product;
  42. }
  43. return view('servers.index')->with([
  44. 'servers' => $servers
  45. ]);
  46. }
  47. /** Show the form for creating a new resource. */
  48. public function create()
  49. {
  50. if (!is_null($this->validateConfigurationRules())) return $this->validateConfigurationRules();
  51. $productCount = Product::query()->where('disabled', '=', false)->count();
  52. $locations = Location::all();
  53. $nodeCount = Node::query()
  54. ->whereHas('products', function (Builder $builder) {
  55. $builder->where('disabled', '=', false);
  56. })->count();
  57. $eggs = Egg::query()
  58. ->whereHas('products', function (Builder $builder) {
  59. $builder->where('disabled', '=', false);
  60. })->get();
  61. $nests = Nest::query()
  62. ->whereHas('eggs', function (Builder $builder) {
  63. $builder->whereHas('products', function (Builder $builder) {
  64. $builder->where('disabled', '=', false);
  65. });
  66. })->get();
  67. return view('servers.create')->with([
  68. 'productCount' => $productCount,
  69. 'nodeCount' => $nodeCount,
  70. 'nests' => $nests,
  71. 'locations' => $locations,
  72. 'eggs' => $eggs,
  73. 'user' => Auth::user(),
  74. ]);
  75. }
  76. /**
  77. * @return null|RedirectResponse
  78. */
  79. private function validateConfigurationRules()
  80. {
  81. //limit validation
  82. if (Auth::user()->servers()->count() >= Auth::user()->server_limit) {
  83. return redirect()->route('servers.index')->with('error', __('Server limit reached!'));
  84. }
  85. // minimum credits
  86. if (FacadesRequest::has("product")) {
  87. $product = Product::findOrFail(FacadesRequest::input("product"));
  88. if (
  89. Auth::user()->credits <
  90. ($product->minimum_credits == -1
  91. ? config('SETTINGS::USER:MINIMUM_REQUIRED_CREDITS_TO_MAKE_SERVER', 50)
  92. : $product->minimum_credits)
  93. ) {
  94. return redirect()->route('servers.index')->with('error', "You do not have the required amount of " . CREDITS_DISPLAY_NAME . " to use this product!");
  95. }
  96. }
  97. //Required Verification for creating an server
  98. if (config('SETTINGS::USER:FORCE_EMAIL_VERIFICATION', 'false') === 'true' && !Auth::user()->hasVerifiedEmail()) {
  99. return redirect()->route('profile.index')->with('error', __("You are required to verify your email address before you can create a server."));
  100. }
  101. //Required Verification for creating an server
  102. if (config('SETTINGS::USER:FORCE_DISCORD_VERIFICATION', 'false') === 'true' && !Auth::user()->discordUser) {
  103. return redirect()->route('profile.index')->with('error', __("You are required to link your discord account before you can create a server."));
  104. }
  105. return null;
  106. }
  107. /** Store a newly created resource in storage. */
  108. public function store(Request $request)
  109. {
  110. /** @var Node $node */
  111. /** @var Egg $egg */
  112. /** @var Product $product */
  113. if (!is_null($this->validateConfigurationRules())) return $this->validateConfigurationRules();
  114. $request->validate([
  115. "name" => "required|max:191",
  116. "node" => "required|exists:nodes,id",
  117. "egg" => "required|exists:eggs,id",
  118. "product" => "required|exists:products,id"
  119. ]);
  120. //get required resources
  121. $product = Product::query()->findOrFail($request->input('product'));
  122. $egg = $product->eggs()->findOrFail($request->input('egg'));
  123. $node = $product->nodes()->findOrFail($request->input('node'));
  124. $server = $request->user()->servers()->create([
  125. 'name' => $request->input('name'),
  126. 'product_id' => $request->input('product'),
  127. 'last_billed' => Carbon::now()->toDateTimeString(),
  128. ]);
  129. //get free allocation ID
  130. $allocationId = Pterodactyl::getFreeAllocationId($node);
  131. if (!$allocationId) return $this->noAllocationsError($server);
  132. //create server on pterodactyl
  133. $response = Pterodactyl::createServer($server, $egg, $allocationId);
  134. if ($response->failed()) return $this->serverCreationFailed($response, $server);
  135. $serverAttributes = $response->json()['attributes'];
  136. //update server with pterodactyl_id
  137. $server->update([
  138. 'pterodactyl_id' => $serverAttributes['id'],
  139. 'identifier' => $serverAttributes['identifier'],
  140. ]);
  141. // Charge first billing cycle
  142. $request->user()->decrement('credits', $server->product->price);
  143. return redirect()->route('servers.index')->with('success', __('Server created'));
  144. }
  145. /**
  146. * return redirect with error
  147. * @param Server $server
  148. * @return RedirectResponse
  149. */
  150. private function noAllocationsError(Server $server)
  151. {
  152. $server->delete();
  153. Auth::user()->notify(new ServerCreationError($server));
  154. return redirect()->route('servers.index')->with('error', __('No allocations satisfying the requirements for automatic deployment on this node were found.'));
  155. }
  156. /**
  157. * return redirect with error
  158. * @param Response $response
  159. * @param Server $server
  160. * @return RedirectResponse
  161. */
  162. private function serverCreationFailed(Response $response, Server $server)
  163. {
  164. $server->delete();
  165. return redirect()->route('servers.index')->with('error', json_encode($response->json()));
  166. }
  167. /** Remove the specified resource from storage. */
  168. public function destroy(Server $server)
  169. {
  170. try {
  171. $server->delete();
  172. return redirect()->route('servers.index')->with('success', __('Server removed'));
  173. } catch (Exception $e) {
  174. return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to remove a resource"') . $e->getMessage() . '"');
  175. }
  176. }
  177. /** Cancel Server */
  178. public function cancel (Server $server)
  179. {
  180. try {
  181. error_log($server->update([
  182. 'cancelled' => now(),
  183. ]));
  184. return redirect()->route('servers.index')->with('success', __('Server cancelled'));
  185. } catch (Exception $e) {
  186. return redirect()->route('servers.index')->with('error', __('An exception has occurred while trying to cancel the server"') . $e->getMessage() . '"');
  187. }
  188. }
  189. }