application resources: nodes and users

This commit is contained in:
robert dennis
2026-10-12 05:18:58 -04:00
parent 0c5af8b3ca
commit e6bf9b7914
30 changed files with 94 additions and 2047 deletions
@@ -25,7 +25,6 @@ use Pterodactyl\Http\Resources\Api\ApiResource;
use Pterodactyl\Http\Resources\Api\ApiResourceCollection;
use Pterodactyl\Http\Resources\Api\Includes\IncludeSet;
use Pterodactyl\Models\User;
use Pterodactyl\Transformers\Api\Application\BaseTransformer;
use ReflectionClass;
class UsePterodactylResponseAttributes extends UseResponseAttributes
@@ -149,12 +148,6 @@ class UsePterodactylResponseAttributes extends UseResponseAttributes
throw_unless($transformer instanceof TransformerAbstract, InvalidArgumentException::class, "Transformer [$transformerClass] must extend ".TransformerAbstract::class.'.');
if (! $attribute->collection) {
// Controllers add extension field values to responses about one resource. The
// example shows the attribute without running installed extensions' code.
if ($transformer instanceof BaseTransformer) {
$transformer->withExtensionFields(read: false);
}
$resource = new Item($modelInstantiator(), $transformer, $attribute->resourceKey);
return $fractal->createData($resource)->toJson();
+1 -23
View File
@@ -5,13 +5,10 @@ declare(strict_types=1);
namespace Pterodactyl\Extensions\Spatie\Fractalistic;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection as ModelCollection;
use Illuminate\Database\Eloquent\Model;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\Scope;
use League\Fractal\TransformerAbstract;
use Pterodactyl\Extensions\League\Fractal\Serializers\PterodactylSerializer;
use Pterodactyl\Transformers\Api\Application\BaseTransformer;
use Spatie\Fractal\Fractal as SpatieFractal;
use Spatie\Fractalistic\Exceptions\InvalidTransformation;
use Spatie\Fractalistic\Exceptions\NoTransformerSpecified;
@@ -62,25 +59,6 @@ class Fractal extends SpatieFractal
$this->resourceName = $this->transformer->getResourceName();
}
$scope = parent::createData();
$data = $this->data instanceof LengthAwarePaginator ? $this->data->items() : $this->data;
if ($this->transformer instanceof BaseTransformer) {
if ($data instanceof Model) {
$this->transformer->prepareCollection(new ModelCollection([$data]), $scope);
} elseif (is_array($data) || $data instanceof \Illuminate\Support\Collection) {
$models = new ModelCollection;
foreach ($data as $model) {
if (! $model instanceof Model) {
return $scope;
}
$models->push($model);
}
$this->transformer->prepareCollection($models, $scope);
}
}
return $scope;
return parent::createData();
}
}
@@ -5,48 +5,10 @@ declare(strict_types=1);
namespace Pterodactyl\Http\Controllers\Api\Application;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\App;
use InvalidArgumentException;
use Pterodactyl\Http\Controllers\Controller;
use Pterodactyl\Transformers\Api\Application\BaseTransformer;
use UnexpectedValueException;
abstract class ApplicationApiController extends Controller
{
/**
* Return an instance of an application transformer.
*
* @template T of \Pterodactyl\Transformers\Api\Application\BaseTransformer
*
* @param class-string<T> $abstract
* @return T
*
* @noinspection PhpDocSignatureInspection
*/
public function getTransformer(string $abstract): BaseTransformer
{
return $this->makeTransformer($abstract, BaseTransformer::class);
}
/**
* Resolve a transformer through the container, asserting it extends the API's base transformer.
*
* @template T of \Pterodactyl\Transformers\Api\Application\BaseTransformer
*
* @param class-string<T> $abstract
* @param class-string<BaseTransformer> $base
* @return T
*/
protected function makeTransformer(string $abstract, string $base): BaseTransformer
{
throw_unless(is_subclass_of($abstract, $base), InvalidArgumentException::class, "Transformer [$abstract] must extend ".$base.'.');
$transformer = App::make($abstract);
throw_unless($transformer instanceof $abstract, UnexpectedValueException::class, "The container did not resolve transformer [$abstract].");
return $transformer;
}
/**
* Return an HTTP/204 response for the API.
*/
@@ -8,14 +8,13 @@ use Knuckles\Scribe\Attributes\Endpoint;
use Knuckles\Scribe\Attributes\Group;
use Knuckles\Scribe\Attributes\QueryParam;
use Knuckles\Scribe\Attributes\Subgroup;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer;
use Pterodactyl\Facades\Fractal;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromResource;
use Pterodactyl\Http\Controllers\Api\Application\ApplicationApiController;
use Pterodactyl\Http\Requests\Api\Application\Eggs\GetEggRequest;
use Pterodactyl\Http\Requests\Api\Application\Eggs\GetEggsRequest;
use Pterodactyl\Http\Resources\Api\ApiResourceCollection;
use Pterodactyl\Http\Resources\Api\Application\EggResource;
use Pterodactyl\Models\Egg;
use Pterodactyl\Transformers\Api\Application\EggTransformer;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;
@@ -25,8 +24,6 @@ class EggController extends ApplicationApiController
{
/**
* Return all eggs that exist on the panel.
*
* @return array<string, mixed>
*/
#[Endpoint('List eggs', 'Returns a paginated list of server eggs available on the panel.')]
#[QueryParam('per_page', 'integer', 'Number of eggs to return per page, up to 100.', required: false, example: 50)]
@@ -34,8 +31,8 @@ class EggController extends ApplicationApiController
#[QueryParam('filter[tag]', 'string', 'Filter eggs by tag slug. Separate several slugs with commas to return eggs that carry any of them.', required: false, example: 'minecraft')]
#[QueryParam('sort', 'string', 'Sort eggs by id or name. Prefix with "-" for descending order.', required: false, example: 'name', enum: ['id', '-id', 'name', '-name'])]
#[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "servers", "config", "script", "variables", and "tags" when the key can read those resources.', required: false, example: 'variables', enum: ['servers', 'config', 'script', 'variables', 'tags'])]
#[ResponseFromTransformer(EggTransformer::class, Egg::class, collection: true, resourceKey: 'egg', paginate: [IlluminatePaginatorAdapter::class, 50])]
public function index(GetEggsRequest $request): array
#[ResponseFromResource(EggResource::class, Egg::class, collection: true, resourceKey: 'egg', paginate: 50)]
public function index(GetEggsRequest $request): ApiResourceCollection
{
$eggs = QueryBuilder::for(Egg::query())
->allowedFilters([
@@ -45,23 +42,17 @@ class EggController extends ApplicationApiController
->allowedSorts(['id', 'name'])
->paginate($request->perPage());
return Fractal::collection($eggs)
->transformWith($this->getTransformer(EggTransformer::class))
->toResponseArray();
return EggResource::collection($eggs);
}
/**
* Return a single egg.
*
* @return array<string, mixed>
*/
#[Endpoint('Get egg', 'Returns a single egg by internal numeric ID.')]
#[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "servers", "config", "script", "variables", and "tags" when the key can read those resources.', required: false, example: 'variables', enum: ['servers', 'config', 'script', 'variables', 'tags'])]
#[ResponseFromTransformer(EggTransformer::class, Egg::class, resourceKey: 'egg')]
public function view(GetEggRequest $request, Egg $egg): array
#[ResponseFromResource(EggResource::class, Egg::class, resourceKey: 'egg')]
public function view(GetEggRequest $request, Egg $egg): EggResource
{
return Fractal::item($egg)
->transformWith($this->getTransformer(EggTransformer::class))
->toResponseArray();
return EggResource::make($egg);
}
}
@@ -11,22 +11,21 @@ use Knuckles\Scribe\Attributes\Group;
use Knuckles\Scribe\Attributes\QueryParam;
use Knuckles\Scribe\Attributes\Response as ScribeResponse;
use Knuckles\Scribe\Attributes\Subgroup;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use Pterodactyl\Contracts\Locations\CreatesLocations;
use Pterodactyl\Contracts\Locations\DeletesLocations;
use Pterodactyl\Contracts\Locations\UpdatesLocations;
use Pterodactyl\Exceptions\Service\Location\HasActiveNodesException;
use Pterodactyl\Extensions\Scribe\Attributes\ExtensionFieldsParam;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer;
use Pterodactyl\Facades\Fractal;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromResource;
use Pterodactyl\Http\Controllers\Api\Application\ApplicationApiController;
use Pterodactyl\Http\Requests\Api\Application\Locations\DeleteLocationRequest;
use Pterodactyl\Http\Requests\Api\Application\Locations\GetLocationRequest;
use Pterodactyl\Http\Requests\Api\Application\Locations\GetLocationsRequest;
use Pterodactyl\Http\Requests\Api\Application\Locations\StoreLocationRequest;
use Pterodactyl\Http\Requests\Api\Application\Locations\UpdateLocationRequest;
use Pterodactyl\Http\Resources\Api\ApiResourceCollection;
use Pterodactyl\Http\Resources\Api\Application\LocationResource;
use Pterodactyl\Models\Location;
use Pterodactyl\Transformers\Api\Application\LocationTransformer;
use Spatie\QueryBuilder\QueryBuilder;
#[Group('Application API', 'Root administrator endpoints for managing panel resources using application API tokens.')]
@@ -45,8 +44,6 @@ class LocationController extends ApplicationApiController
/**
* Return all the locations currently registered on the Panel.
*
* @return array<string, mixed>
*/
#[Endpoint('List locations', 'Returns a paginated list of all locations registered on the panel.')]
#[QueryParam('per_page', 'integer', 'Number of locations to return per page, up to 100.', required: false, example: 50)]
@@ -54,32 +51,26 @@ class LocationController extends ApplicationApiController
#[QueryParam('filter[long]', 'string', 'Filter locations by description.', required: false, example: 'US East Datacenter')]
#[QueryParam('sort', 'string', 'Sort locations by id. Prefix with "-" for descending order.', required: false, example: 'id', enum: ['id', '-id'])]
#[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "nodes" and "servers" when the key can read those resources.', required: false, example: 'nodes,servers', enum: ['nodes', 'servers', 'nodes,servers'])]
#[ResponseFromTransformer(LocationTransformer::class, Location::class, collection: true, resourceKey: 'location', paginate: [IlluminatePaginatorAdapter::class, 50])]
public function index(GetLocationsRequest $request): array
#[ResponseFromResource(LocationResource::class, Location::class, collection: true, resourceKey: 'location', paginate: 50)]
public function index(GetLocationsRequest $request): ApiResourceCollection
{
$locations = QueryBuilder::for(Location::query())
->allowedFilters(['short', 'long'])
->allowedSorts(['id'])
->paginate($request->perPage());
return Fractal::collection($locations)
->transformWith($this->getTransformer(LocationTransformer::class))
->toResponseArray();
return LocationResource::collection($locations);
}
/**
* Return a single location.
*
* @return array<string, mixed>
*/
#[Endpoint('Get location', 'Returns a single location by internal numeric ID.')]
#[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "nodes" and "servers" when the key can read those resources.', required: false, example: 'nodes,servers', enum: ['nodes', 'servers', 'nodes,servers'])]
#[ResponseFromTransformer(LocationTransformer::class, Location::class, resourceKey: 'location')]
public function view(GetLocationRequest $request, Location $location): array
#[ResponseFromResource(LocationResource::class, Location::class, resourceKey: 'location')]
public function view(GetLocationRequest $request, Location $location): LocationResource
{
return Fractal::item($location)
->transformWith($this->getTransformer(LocationTransformer::class)->withExtensionFields())
->toResponseArray();
return LocationResource::make($location)->withExtensionFields();
}
/**
@@ -87,15 +78,15 @@ class LocationController extends ApplicationApiController
* new location attached.
*/
#[Endpoint('Create location', 'Creates a new location and returns the created resource.')]
#[ResponseFromTransformer(LocationTransformer::class, Location::class, status: 201, description: 'Location created.', resourceKey: 'location', meta: ['resource' => 'https://panel.example.test/api/application/locations/1'])]
#[ResponseFromResource(LocationResource::class, Location::class, status: 201, description: 'Location created.', resourceKey: 'location', meta: ['resource' => 'https://panel.example.test/api/application/locations/1'])]
#[ExtensionFieldsParam]
public function store(StoreLocationRequest $request, CreatesLocations $locations): JsonResponse
{
$location = $locations->create($request->actionInput());
return Fractal::item($location)
->transformWith($this->getTransformer(LocationTransformer::class)->withExtensionFields())
->addMeta([
return LocationResource::make($location)
->withExtensionFields()
->withMeta([
'resource' => route('api.application.locations.view', [
'location' => $location->id,
]),
@@ -105,19 +96,15 @@ class LocationController extends ApplicationApiController
/**
* Update a location on the Panel and return the updated record to the user.
*
* @return array<string, mixed>
*/
#[Endpoint('Update location', 'Updates an existing location by internal numeric ID.')]
#[ResponseFromTransformer(LocationTransformer::class, Location::class, resourceKey: 'location')]
#[ResponseFromResource(LocationResource::class, Location::class, resourceKey: 'location')]
#[ExtensionFieldsParam]
public function update(UpdateLocationRequest $request, UpdatesLocations $locations, Location $location): array
public function update(UpdateLocationRequest $request, UpdatesLocations $locations, Location $location): LocationResource
{
$location = $locations->update($location, $request->actionInput());
return Fractal::item($location)
->transformWith($this->getTransformer(LocationTransformer::class)->withExtensionFields())
->toResponseArray();
return LocationResource::make($location)->withExtensionFields();
}
/**
@@ -11,7 +11,6 @@ use Knuckles\Scribe\Attributes\Group;
use Knuckles\Scribe\Attributes\QueryParam;
use Knuckles\Scribe\Attributes\Response as ScribeResponse;
use Knuckles\Scribe\Attributes\Subgroup;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use Pterodactyl\Contracts\Allocations\CreatesAllocations;
use Pterodactyl\Contracts\Allocations\DeletesAllocations;
use Pterodactyl\Exceptions\DisplayException;
@@ -20,15 +19,15 @@ use Pterodactyl\Exceptions\Service\Allocation\InvalidPortMappingException;
use Pterodactyl\Exceptions\Service\Allocation\PortOutOfRangeException;
use Pterodactyl\Exceptions\Service\Allocation\ServerUsingAllocationException;
use Pterodactyl\Exceptions\Service\Allocation\TooManyPortsInRangeException;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer;
use Pterodactyl\Facades\Fractal;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromResource;
use Pterodactyl\Http\Controllers\Api\Application\ApplicationApiController;
use Pterodactyl\Http\Requests\Api\Application\Allocations\DeleteAllocationRequest;
use Pterodactyl\Http\Requests\Api\Application\Allocations\GetAllocationsRequest;
use Pterodactyl\Http\Requests\Api\Application\Allocations\StoreAllocationRequest;
use Pterodactyl\Http\Resources\Api\ApiResourceCollection;
use Pterodactyl\Http\Resources\Api\Application\AllocationResource;
use Pterodactyl\Models\Allocation;
use Pterodactyl\Models\Node;
use Pterodactyl\Transformers\Api\Application\AllocationTransformer;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;
@@ -58,8 +57,6 @@ class AllocationController extends ApplicationApiController
/**
* Return all the allocations that exist for a given node.
*
* @return array<string, mixed>
*/
#[Endpoint('List node allocations', 'Returns a paginated list of allocations belonging to a node.')]
#[QueryParam('per_page', 'integer', 'Number of allocations to return per page, up to 100.', required: false, example: 50)]
@@ -68,8 +65,8 @@ class AllocationController extends ApplicationApiController
#[QueryParam('filter[ip_alias]', 'string', 'Filter allocations by IP alias.', required: false, example: 'minecraft.example.com')]
#[QueryParam('filter[server_id]', 'string', 'Filter allocations by assigned server ID. Empty or non-numeric values return unassigned allocations.', required: false, example: '1')]
#[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "node" and "server" when the key can read those resources.', required: false, example: 'server', enum: ['node', 'server', 'node,server'])]
#[ResponseFromTransformer(AllocationTransformer::class, Allocation::class, collection: true, with: ['node.location'], resourceKey: 'allocation', paginate: [IlluminatePaginatorAdapter::class, 50])]
public function index(GetAllocationsRequest $request, Node $node): array
#[ResponseFromResource(AllocationResource::class, Allocation::class, collection: true, with: ['node.location'], resourceKey: 'allocation', paginate: 50)]
public function index(GetAllocationsRequest $request, Node $node): ApiResourceCollection
{
$query = $node->allocations();
@@ -99,9 +96,7 @@ class AllocationController extends ApplicationApiController
])
->paginate($request->perPage());
return Fractal::collection($allocations)
->transformWith($this->getTransformer(AllocationTransformer::class))
->toResponseArray();
return AllocationResource::collection($allocations);
}
/**
@@ -10,22 +10,21 @@ use Knuckles\Scribe\Attributes\Group;
use Knuckles\Scribe\Attributes\QueryParam;
use Knuckles\Scribe\Attributes\Response as ScribeResponse;
use Knuckles\Scribe\Attributes\Subgroup;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use Pterodactyl\Contracts\Nodes\CreatesNodes;
use Pterodactyl\Contracts\Nodes\DeletesNodes;
use Pterodactyl\Contracts\Nodes\UpdatesNodes;
use Pterodactyl\Exceptions\Service\HasActiveServersException;
use Pterodactyl\Extensions\Scribe\Attributes\ExtensionFieldsParam;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer;
use Pterodactyl\Facades\Fractal;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromResource;
use Pterodactyl\Http\Controllers\Api\Application\ApplicationApiController;
use Pterodactyl\Http\Requests\Api\Application\Nodes\DeleteNodeRequest;
use Pterodactyl\Http\Requests\Api\Application\Nodes\GetNodeRequest;
use Pterodactyl\Http\Requests\Api\Application\Nodes\GetNodesRequest;
use Pterodactyl\Http\Requests\Api\Application\Nodes\StoreNodeRequest;
use Pterodactyl\Http\Requests\Api\Application\Nodes\UpdateNodeRequest;
use Pterodactyl\Http\Resources\Api\ApiResourceCollection;
use Pterodactyl\Http\Resources\Api\Application\NodeResource;
use Pterodactyl\Models\Node;
use Pterodactyl\Transformers\Api\Application\NodeTransformer;
use Spatie\QueryBuilder\QueryBuilder;
use Throwable;
@@ -55,8 +54,6 @@ class NodeController extends ApplicationApiController
/**
* Return all the nodes currently available on the Panel.
*
* @return array<string, mixed>
*/
#[Endpoint('List nodes', 'Returns a paginated list of Wings nodes registered on the panel.')]
#[QueryParam('per_page', 'integer', 'Number of nodes to return per page, up to 100.', required: false, example: 50)]
@@ -66,8 +63,8 @@ class NodeController extends ApplicationApiController
#[QueryParam('filter[daemon_token_id]', 'string', 'Filter nodes by daemon token identifier.', required: false, example: 'abcdefghijklmnop')]
#[QueryParam('sort', 'string', 'Sort nodes by id, uuid, memory, or disk. Prefix with "-" for descending order.', required: false, example: '-id', enum: ['id', '-id', 'uuid', '-uuid', 'memory', '-memory', 'disk', '-disk'])]
#[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "allocations", "location", and "servers" when the key can read those resources.', required: false, example: 'location,allocations', enum: ['allocations', 'location', 'servers', 'location,allocations'])]
#[ResponseFromTransformer(NodeTransformer::class, Node::class, collection: true, factoryStates: ['withLocation'], resourceKey: 'node', paginate: [IlluminatePaginatorAdapter::class, 50])]
public function index(GetNodesRequest $request): array
#[ResponseFromResource(NodeResource::class, Node::class, collection: true, factoryStates: ['withLocation'], resourceKey: 'node', paginate: 50)]
public function index(GetNodesRequest $request): ApiResourceCollection
{
$nodes = QueryBuilder::for(Node::query()
->withSum('servers as sum_memory', 'memory')
@@ -76,24 +73,18 @@ class NodeController extends ApplicationApiController
->allowedSorts(['id', 'uuid', 'memory', 'disk'])
->paginate($request->perPage());
return Fractal::collection($nodes)
->transformWith($this->getTransformer(NodeTransformer::class))
->toResponseArray();
return NodeResource::collection($nodes);
}
/**
* Return data for a single instance of a node.
*
* @return array<string, mixed>
*/
#[Endpoint('Get node', 'Returns a single Wings node by internal numeric ID.')]
#[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "allocations", "location", and "servers" when the key can read those resources.', required: false, example: 'location,allocations', enum: ['allocations', 'location', 'servers', 'location,allocations'])]
#[ResponseFromTransformer(NodeTransformer::class, Node::class, factoryStates: ['withLocation'], resourceKey: 'node')]
public function view(GetNodeRequest $request, Node $node): array
#[ResponseFromResource(NodeResource::class, Node::class, factoryStates: ['withLocation'], resourceKey: 'node')]
public function view(GetNodeRequest $request, Node $node): NodeResource
{
return Fractal::item($node)
->transformWith($this->getTransformer(NodeTransformer::class)->withExtensionFields())
->toResponseArray();
return NodeResource::make($node)->withExtensionFields();
}
/**
@@ -101,15 +92,15 @@ class NodeController extends ApplicationApiController
* status response on success.
*/
#[Endpoint('Create node', 'Creates a new Wings node and returns the created resource.')]
#[ResponseFromTransformer(NodeTransformer::class, Node::class, status: 201, description: 'Node created.', factoryStates: ['withLocation'], resourceKey: 'node', meta: ['resource' => 'https://panel.example.test/api/application/nodes/1'])]
#[ResponseFromResource(NodeResource::class, Node::class, status: 201, description: 'Node created.', factoryStates: ['withLocation'], resourceKey: 'node', meta: ['resource' => 'https://panel.example.test/api/application/nodes/1'])]
#[ExtensionFieldsParam]
public function store(StoreNodeRequest $request, CreatesNodes $nodes): JsonResponse
{
$node = $nodes->create($request->actionInput());
return Fractal::item($node)
->transformWith($this->getTransformer(NodeTransformer::class)->withExtensionFields())
->addMeta([
return NodeResource::make($node)
->withExtensionFields()
->withMeta([
'resource' => route('api.application.nodes.view', [
'node' => $node->id,
]),
@@ -120,16 +111,13 @@ class NodeController extends ApplicationApiController
/**
* Update an existing node on the Panel.
*
*
* @return array<string, mixed>
*
* @throws Throwable
*/
#[Endpoint('Update node', 'Updates an existing Wings node by internal numeric ID.')]
#[ResponseFromTransformer(NodeTransformer::class, Node::class, factoryStates: ['withLocation'], resourceKey: 'node')]
#[ResponseFromResource(NodeResource::class, Node::class, factoryStates: ['withLocation'], resourceKey: 'node')]
#[ScribeResponse(self::CONFIGURATION_NOT_PERSISTED_ERROR, status: 400, description: 'The panel saved the node changes but could not persist the configuration to Wings.')]
#[ExtensionFieldsParam]
public function update(UpdateNodeRequest $request, UpdatesNodes $nodes, Node $node): array
public function update(UpdateNodeRequest $request, UpdatesNodes $nodes, Node $node): NodeResource
{
$node = $nodes->update(
$node,
@@ -137,9 +125,7 @@ class NodeController extends ApplicationApiController
$request->boolean('reset_secret')
);
return Fractal::item($node)
->transformWith($this->getTransformer(NodeTransformer::class)->withExtensionFields())
->toResponseArray();
return NodeResource::make($node)->withExtensionFields();
}
/**
@@ -10,13 +10,13 @@ use Knuckles\Scribe\Attributes\QueryParam;
use Knuckles\Scribe\Attributes\Response as ScribeResponse;
use Knuckles\Scribe\Attributes\Subgroup;
use Pterodactyl\Exceptions\Service\Deployment\NoViableNodeException;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer;
use Pterodactyl\Facades\Fractal;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromResource;
use Pterodactyl\Http\Controllers\Api\Application\ApplicationApiController;
use Pterodactyl\Http\Requests\Api\Application\Nodes\GetDeployableNodesRequest;
use Pterodactyl\Http\Resources\Api\ApiResourceCollection;
use Pterodactyl\Http\Resources\Api\Application\NodeResource;
use Pterodactyl\Models\Node;
use Pterodactyl\Services\Deployment\FindViableNodesService;
use Pterodactyl\Transformers\Api\Application\NodeTransformer;
#[Group('Application API', 'Root administrator endpoints for managing panel resources using application API tokens.')]
#[Subgroup('Nodes', 'Create, update, retrieve, and delete Wings nodes and their allocations.')]
@@ -37,9 +37,6 @@ class NodeDeploymentController extends ApplicationApiController
* similarly to the server creation process, but allows you to pass the deployment object
* to this endpoint and get back a list of all Nodes satisfying the requirements.
*
*
* @return array<string, mixed>
*
* @throws NoViableNodeException
*/
#[Endpoint('List deployable nodes', 'Returns nodes that can satisfy the requested memory, disk, and optional location deployment constraints.')]
@@ -48,9 +45,9 @@ class NodeDeploymentController extends ApplicationApiController
#[QueryParam('location_ids', 'integer[]', 'Restrict results to these location IDs.', required: false, example: [1, 2])]
#[QueryParam('page', 'integer', 'Page number to return. When omitted, all viable nodes are returned without pagination metadata.', required: false, example: 1)]
#[QueryParam('per_page', 'integer', 'Number of nodes to return per page when page is supplied, up to 100.', required: false, example: 50)]
#[ResponseFromTransformer(NodeTransformer::class, Node::class, description: 'Deployable nodes returned.', collection: true, factoryStates: ['withLocation'], resourceKey: 'node')]
#[ResponseFromResource(NodeResource::class, Node::class, description: 'Deployable nodes returned.', collection: true, factoryStates: ['withLocation'], resourceKey: 'node')]
#[ScribeResponse(self::NO_VIABLE_NODE_ERROR, status: 400, description: 'No nodes can satisfy the requested deployment constraints.')]
public function __invoke(GetDeployableNodesRequest $request, FindViableNodesService $viableNodesService): array
public function __invoke(GetDeployableNodesRequest $request, FindViableNodesService $viableNodesService): ApiResourceCollection
{
$payload = $request->payload();
@@ -60,8 +57,6 @@ class NodeDeploymentController extends ApplicationApiController
->setDisk($payload['disk'])
->handle($payload['per_page'], $payload['page']);
return Fractal::collection($nodes)
->transformWith($this->getTransformer(NodeTransformer::class))
->toResponseArray();
return NodeResource::collection($nodes);
}
}
@@ -8,14 +8,13 @@ use Knuckles\Scribe\Attributes\Endpoint;
use Knuckles\Scribe\Attributes\Group;
use Knuckles\Scribe\Attributes\QueryParam;
use Knuckles\Scribe\Attributes\Subgroup;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer;
use Pterodactyl\Facades\Fractal;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromResource;
use Pterodactyl\Http\Controllers\Api\Application\ApplicationApiController;
use Pterodactyl\Http\Requests\Api\Application\Tags\GetTagRequest;
use Pterodactyl\Http\Requests\Api\Application\Tags\GetTagsRequest;
use Pterodactyl\Http\Resources\Api\ApiResourceCollection;
use Pterodactyl\Http\Resources\Api\Application\TagResource;
use Pterodactyl\Models\Tag;
use Pterodactyl\Transformers\Api\Application\TagTransformer;
use Spatie\QueryBuilder\QueryBuilder;
#[Group('Application API', 'Root administrator endpoints for managing panel resources using application API tokens.')]
@@ -24,8 +23,6 @@ class TagController extends ApplicationApiController
{
/**
* Return all tags that exist on the panel.
*
* @return array<string, mixed>
*/
#[Endpoint('List tags', 'Returns a paginated list of the tags that group eggs.')]
#[QueryParam('per_page', 'integer', 'Number of tags to return per page, up to 100.', required: false, example: 50)]
@@ -33,31 +30,25 @@ class TagController extends ApplicationApiController
#[QueryParam('filter[slug]', 'string', 'Filter tags by slug.', required: false, example: 'minecraft')]
#[QueryParam('sort', 'string', 'Sort tags by id, name, or slug. Prefix with "-" for descending order.', required: false, example: 'name', enum: ['id', '-id', 'name', '-name', 'slug', '-slug'])]
#[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "eggs" and "nodes" when the key can read those resources.', required: false, example: 'eggs', enum: ['eggs', 'nodes', 'eggs,nodes'])]
#[ResponseFromTransformer(TagTransformer::class, Tag::class, collection: true, resourceKey: 'tag', paginate: [IlluminatePaginatorAdapter::class, 50])]
public function index(GetTagsRequest $request): array
#[ResponseFromResource(TagResource::class, Tag::class, collection: true, resourceKey: 'tag', paginate: 50)]
public function index(GetTagsRequest $request): ApiResourceCollection
{
$tags = QueryBuilder::for(Tag::query())
->allowedFilters(['name', 'slug'])
->allowedSorts(['id', 'name', 'slug'])
->paginate($request->perPage());
return Fractal::collection($tags)
->transformWith($this->getTransformer(TagTransformer::class))
->toResponseArray();
return TagResource::collection($tags);
}
/**
* Return a single tag.
*
* @return array<string, mixed>
*/
#[Endpoint('Get tag', 'Returns a single tag by internal numeric ID.')]
#[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "eggs" and "nodes" when the key can read those resources.', required: false, example: 'eggs', enum: ['eggs', 'nodes', 'eggs,nodes'])]
#[ResponseFromTransformer(TagTransformer::class, Tag::class, resourceKey: 'tag')]
public function view(GetTagRequest $request, Tag $tag): array
#[ResponseFromResource(TagResource::class, Tag::class, resourceKey: 'tag')]
public function view(GetTagRequest $request, Tag $tag): TagResource
{
return Fractal::item($tag)
->transformWith($this->getTransformer(TagTransformer::class))
->toResponseArray();
return TagResource::make($tag);
}
}
@@ -7,12 +7,11 @@ namespace Pterodactyl\Http\Controllers\Api\Application\Users;
use Knuckles\Scribe\Attributes\Endpoint;
use Knuckles\Scribe\Attributes\Group;
use Knuckles\Scribe\Attributes\Subgroup;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer;
use Pterodactyl\Facades\Fractal;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromResource;
use Pterodactyl\Http\Controllers\Api\Application\ApplicationApiController;
use Pterodactyl\Http\Requests\Api\Application\Users\GetExternalUserRequest;
use Pterodactyl\Http\Resources\Api\Application\UserResource;
use Pterodactyl\Models\User;
use Pterodactyl\Transformers\Api\Application\UserTransformer;
#[Group('Application API', 'Root administrator endpoints for managing panel resources using application API tokens.')]
#[Subgroup('Users', 'Create, update, retrieve, and delete panel users.')]
@@ -20,17 +19,13 @@ class ExternalUserController extends ApplicationApiController
{
/**
* Retrieve a specific user from the database using their external ID.
*
* @return array<string, mixed>
*/
#[Endpoint('Get user by external ID', 'Returns a single panel user by its external identifier.')]
#[ResponseFromTransformer(UserTransformer::class, User::class, resourceKey: 'user')]
public function index(GetExternalUserRequest $request, string $external_id): array
#[ResponseFromResource(UserResource::class, User::class, resourceKey: 'user')]
public function index(GetExternalUserRequest $request, string $external_id): UserResource
{
$user = User::query()->where('external_id', $external_id)->firstOrFail();
return Fractal::item($user)
->transformWith($this->getTransformer(UserTransformer::class))
->toResponseArray();
return UserResource::make($user);
}
}
@@ -10,21 +10,20 @@ use Knuckles\Scribe\Attributes\Group;
use Knuckles\Scribe\Attributes\QueryParam;
use Knuckles\Scribe\Attributes\Response as ScribeResponse;
use Knuckles\Scribe\Attributes\Subgroup;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use Pterodactyl\Contracts\Users\CreatesUsers;
use Pterodactyl\Contracts\Users\DeletesUsers;
use Pterodactyl\Contracts\Users\UpdatesUsers;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Extensions\Scribe\Attributes\ExtensionFieldsParam;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer;
use Pterodactyl\Facades\Fractal;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromResource;
use Pterodactyl\Http\Controllers\Api\Application\ApplicationApiController;
use Pterodactyl\Http\Requests\Api\Application\Users\DeleteUserRequest;
use Pterodactyl\Http\Requests\Api\Application\Users\GetUsersRequest;
use Pterodactyl\Http\Requests\Api\Application\Users\StoreUserRequest;
use Pterodactyl\Http\Requests\Api\Application\Users\UpdateUserRequest;
use Pterodactyl\Http\Resources\Api\ApiResourceCollection;
use Pterodactyl\Http\Resources\Api\Application\UserResource;
use Pterodactyl\Models\User;
use Pterodactyl\Transformers\Api\Application\UserTransformer;
use Spatie\QueryBuilder\QueryBuilder;
use Throwable;
@@ -36,8 +35,6 @@ class UserController extends ApplicationApiController
* Handle request to list all users on the panel. Returns a JSON-API representation
* of a collection of users including any defined relations passed in
* the request.
*
* @return array<string, mixed>
*/
#[Endpoint('List users', 'Returns a paginated list of panel users visible to the application API key.')]
#[QueryParam('per_page', 'integer', 'Number of users to return per page, up to 100.', required: false, example: 50)]
@@ -47,51 +44,40 @@ class UserController extends ApplicationApiController
#[QueryParam('filter[external_id]', 'string', 'Filter users by external identifier.', required: false, example: 'billing-system-42')]
#[QueryParam('sort', 'string', 'Sort users by id or uuid. Prefix with "-" for descending order.', required: false, example: '-id', enum: ['id', '-id', 'uuid', '-uuid'])]
#[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "servers" when the key can read servers.', required: false, example: 'servers', enum: ['servers'])]
#[ResponseFromTransformer(UserTransformer::class, User::class, collection: true, resourceKey: 'user', paginate: [IlluminatePaginatorAdapter::class, 50])]
public function index(GetUsersRequest $request): array
#[ResponseFromResource(UserResource::class, User::class, collection: true, resourceKey: 'user', paginate: 50)]
public function index(GetUsersRequest $request): ApiResourceCollection
{
$users = QueryBuilder::for(User::query())
->allowedFilters(['email', 'uuid', 'username', 'external_id'])
->allowedSorts(['id', 'uuid'])
->paginate($request->perPage());
return Fractal::collection($users)
->transformWith($this->getTransformer(UserTransformer::class))
->toResponseArray();
return UserResource::collection($users);
}
/**
* Handle a request to view a single user. Includes any relations that
* were defined in the request.
*
* @return array<string, mixed>
*/
#[Endpoint('Get user', 'Returns a single panel user by internal numeric ID.')]
#[QueryParam('include', 'string', 'Comma-separated relationships to include. Supports "servers" when the key can read servers.', required: false, example: 'servers', enum: ['servers'])]
#[ResponseFromTransformer(UserTransformer::class, User::class, resourceKey: 'user')]
public function view(GetUsersRequest $request, User $user): array
#[ResponseFromResource(UserResource::class, User::class, resourceKey: 'user')]
public function view(GetUsersRequest $request, User $user): UserResource
{
return Fractal::item($user)
->transformWith($this->getTransformer(UserTransformer::class)->withExtensionFields())
->toResponseArray();
return UserResource::make($user)->withExtensionFields();
}
/**
* @return array<string, mixed>
*
* @throws Throwable
*/
#[Endpoint('Update user', 'Updates account details for an existing panel user.')]
#[ResponseFromTransformer(UserTransformer::class, User::class, resourceKey: 'user')]
#[ResponseFromResource(UserResource::class, User::class, resourceKey: 'user')]
#[ExtensionFieldsParam]
public function update(UpdateUserRequest $request, UpdatesUsers $users, User $user): array
public function update(UpdateUserRequest $request, UpdatesUsers $users, User $user): UserResource
{
$user = $users->update($user, $request->actionInput());
$response = Fractal::item($user)
->transformWith($this->getTransformer(UserTransformer::class)->withExtensionFields());
return $response->toResponseArray();
return UserResource::make($user)->withExtensionFields();
}
/**
@@ -101,15 +87,15 @@ class UserController extends ApplicationApiController
* @throws Throwable
*/
#[Endpoint('Create user', 'Creates a new panel user and returns the created resource.')]
#[ResponseFromTransformer(UserTransformer::class, User::class, status: 201, description: 'User created.', resourceKey: 'user', meta: ['resource' => 'https://panel.example.test/api/application/users/1'])]
#[ResponseFromResource(UserResource::class, User::class, status: 201, description: 'User created.', resourceKey: 'user', meta: ['resource' => 'https://panel.example.test/api/application/users/1'])]
#[ExtensionFieldsParam]
public function store(StoreUserRequest $request, CreatesUsers $users): JsonResponse
{
$user = $users->create($request->actionInput());
return Fractal::item($user)
->transformWith($this->getTransformer(UserTransformer::class)->withExtensionFields())
->addMeta([
return UserResource::make($user)
->withExtensionFields()
->withMeta([
'resource' => route('api.application.users.view', [
'user' => $user->id,
]),
@@ -1,89 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use League\Fractal\Resource\Item;
use League\Fractal\Resource\NullResource;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Models\Allocation;
use Pterodactyl\Models\Node;
use Pterodactyl\Models\Server;
use Pterodactyl\Services\Acl\Api\AdminAcl;
class AllocationTransformer extends BaseTransformer
{
protected array $includeRelations = [
'node' => ['relation' => 'node', 'transformer' => NodeTransformer::class, 'ability' => AdminAcl::RESOURCE_NODES],
'server' => ['relation' => 'server', 'transformer' => ServerTransformer::class, 'ability' => AdminAcl::RESOURCE_SERVERS],
];
/**
* Relationships that can be loaded onto allocation transformations.
*
* @var list<string>
*/
protected array $availableIncludes = ['node', 'server'];
/**
* Return the resource name for the JSONAPI output.
*/
public function getResourceName(): string
{
return Allocation::RESOURCE_NAME;
}
/**
* Return a generic transformed allocation array.
*
* @return array<string, mixed>
*/
public function transform(Allocation $allocation): array
{
return [
'id' => $allocation->id,
'ip' => $allocation->ip,
'alias' => $allocation->ip_alias,
'port' => $allocation->port,
'notes' => $allocation->notes,
'assigned' => ($allocation->server_id) !== null,
];
}
/**
* Load the node relationship onto a given transformation.
*
* @throws InvalidTransformerLevelException
*/
public function includeNode(Allocation $allocation): Item|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_NODES)) {
return $this->null();
}
return $this->item(
$allocation->node,
$this->makeTransformer(NodeTransformer::class),
Node::RESOURCE_NAME
);
}
/**
* Load the server relationship onto a given transformation.
*
* @throws InvalidTransformerLevelException
*/
public function includeServer(Allocation $allocation): Item|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_SERVERS) || ! $allocation->server) {
return $this->null();
}
return $this->item(
$allocation->server,
$this->makeTransformer(ServerTransformer::class),
Server::RESOURCE_NAME
);
}
}
@@ -1,231 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Collection as ModelCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Request as RequestFacade;
use League\Fractal\Resource\Collection as ResourceCollection;
use League\Fractal\Scope;
use League\Fractal\TransformerAbstract;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Services\Acl\Api\AdminAcl;
use Pterodactyl\Services\Extensions\ExtensionFields;
use Pterodactyl\Support\JsonEmptyObject;
use UnexpectedValueException;
/**
* @method array<string, mixed> transform(Model $model)
*/
abstract class BaseTransformer extends TransformerAbstract
{
public const string RESPONSE_TIMEZONE = 'UTC';
/** @var list<string> */
protected array $eagerLoads = [];
/** @var list<string> */
protected array $eagerLoadCounts = [];
/** @var array<string, string> relation alias => column */
protected array $eagerLoadSums = [];
/** @var array<string, array{relation: string, transformer?: class-string<BaseTransformer>, ability?: string}> */
protected array $includeRelations = [];
private ?Request $request = null;
private bool $extensionFields = false;
private bool $readExtensionFields = true;
/**
* Return the resource name for the JSONAPI output.
*/
abstract public function getResourceName(): string;
/**
* Adds the values of extension fields to the resource as its `extensions` attribute.
* Controllers ask for them on responses about one model, so a list never runs every
* extension for every row. With `$read` false the attribute is present but empty and no
* extension code runs, as in documentation examples.
*/
public function withExtensionFields(bool $read = true): static
{
$this->extensionFields = true;
$this->readExtensionFields = $read;
return $this;
}
/**
* Batch dependencies across the entire resource before Fractal visits individual models.
* Only declared includes are loaded; serialization retains its own authorization checks.
*
* @param ModelCollection<int, Model> $models
*/
public function prepareCollection(ModelCollection $models, Scope $scope): void
{
if ($models->isEmpty()) {
return;
}
$models->loadMissing($this->eagerLoads);
foreach ($this->eagerLoadCounts as $relation) {
$models->reject(fn (Model $model): bool => array_key_exists($relation.'_count', $model->getAttributes()))->loadCount($relation);
}
foreach ($this->eagerLoadSums as $relation => $column) {
$alias = explode(' as ', $relation)[1];
$models->reject(fn (Model $model): bool => array_key_exists($alias, $model->getAttributes()))->loadSum($relation, $column);
}
foreach ($this->includeRelations as $include => $definition) {
if ((! in_array($include, $this->getDefaultIncludes(), true) && ! $scope->isRequested($include)) || $scope->isExcluded($include)) {
continue;
}
if (isset($definition['ability']) && ! $this->authorize($definition['ability'])) {
continue;
}
$models->loadMissing($definition['relation']);
if (! isset($definition['transformer'])) {
continue;
}
// A relation value is a Model, a Collection of Models, or null; flattening one
// level and keeping only Models covers all three without a runtime type check.
$related = new ModelCollection(
$models->pluck($definition['relation'])->flatten(1)->whereInstanceOf(Model::class)->values()->all(),
);
$transformer = $this->makeTransformer($definition['transformer']);
$childScope = $scope->embedChildScope($include, new ResourceCollection($related, $transformer));
$transformer->prepareCollection($related, $childScope);
}
}
/**
* Sets the request on the instance.
*/
public function setRequest(Request $request): static
{
$this->request = $request;
return $this;
}
/**
* The request this transformer serializes for; the current request unless one was set.
*/
protected function request(): Request
{
return $this->request ??= RequestFacade::instance();
}
/**
* The `extensions` attribute of a model, keyed by extension id, when the controller asked
* for extension fields; empty otherwise, so the attribute is left out.
*
* @return array{extensions?: array<string, ExtensionFieldValues|JsonEmptyObject>|JsonEmptyObject}
*/
protected function extensionFields(Model $model): array
{
if (! $this->extensionFields) {
return [];
}
if (! $this->readExtensionFields) {
return ['extensions' => new JsonEmptyObject];
}
$values = array_map(
fn (array $values): array|JsonEmptyObject => $values === [] ? new JsonEmptyObject : $values,
App::make(ExtensionFields::class)->values($model, applicationApi: ! $this->exposesAllExtensionFields()),
);
return ['extensions' => $values === [] ? new JsonEmptyObject : $values];
}
/**
* Whether this API returns the values of every extension's fields, rather than only
* those marked #[ApplicationApi].
*/
protected function exposesAllExtensionFields(): bool
{
return false;
}
/**
* Determine if the API key loaded onto the transformer has permission
* to access a different resource. This is used when including other
* models on a transformation request.
*
* @deprecated - prefer $user->can/cannot methods
*/
protected function authorize(string $resource): bool
{
$allowed = [ApiKey::TYPE_ACCOUNT, ApiKey::TYPE_APPLICATION];
$token = $this->request()->user()?->currentAccessToken();
if (! $token instanceof ApiKey || ! in_array($token->key_type, $allowed)) {
return false;
}
// If this is not a deprecated application token type we can only check that
// the user is a root admin at the moment. In a future release we'll be rolling
// out more specific permissions for keys.
if ($token->key_type === ApiKey::TYPE_ACCOUNT) {
return $this->request()->user()->root_admin;
}
return AdminAcl::check($token, $resource);
}
/**
* Create a new instance of the transformer and pass along the currently
* set API key.
*
* @template T of \Pterodactyl\Transformers\Api\Application\BaseTransformer
*
* @param class-string<T> $abstract
* @return T
*
* @throws InvalidTransformerLevelException
*
* @noinspection PhpDocSignatureInspection
*/
protected function makeTransformer(string $abstract): self
{
throw_unless(is_subclass_of($abstract, self::class), InvalidTransformerLevelException::class, "Transformer [$abstract] must extend ".self::class.'.');
$transformer = App::make($abstract);
throw_unless($transformer instanceof $abstract, UnexpectedValueException::class, "The container did not resolve transformer [$abstract].");
return $transformer->setRequest($this->request());
}
/**
* Return an ISO-8601 formatted timestamp to use in the API response.
*/
protected function formatTimestamp(CarbonInterface|string|null $timestamp): string
{
throw_if($timestamp === null, UnexpectedValueException::class, 'Cannot format a missing model timestamp.');
$value = $timestamp instanceof CarbonInterface
? CarbonImmutable::instance($timestamp)
: CarbonImmutable::createFromFormat(CarbonInterface::DEFAULT_TO_STRING_FORMAT, $timestamp);
throw_unless($value instanceof CarbonImmutable, UnexpectedValueException::class, "The model timestamp does not match Laravel's storage format.");
return $value->setTimezone(self::RESPONSE_TIMEZONE)->toAtomString();
}
}
@@ -1,69 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\NullResource;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Models\Database;
use Pterodactyl\Models\DatabaseHost;
use Pterodactyl\Services\Acl\Api\AdminAcl;
class DatabaseHostTransformer extends BaseTransformer
{
protected array $includeRelations = [
'databases' => ['relation' => 'databases', 'transformer' => ServerDatabaseTransformer::class, 'ability' => AdminAcl::RESOURCE_SERVER_DATABASES],
];
/**
* @var list<string>
*/
protected array $availableIncludes = [
'databases',
];
/**
* Return the resource name for the JSONAPI output.
*/
public function getResourceName(): string
{
return DatabaseHost::RESOURCE_NAME;
}
/**
* Transform database host into a representation for the application API.
*
* @return array<string, mixed>
*/
public function transform(DatabaseHost $model): array
{
return [
'id' => $model->id,
'name' => $model->name,
'host' => $model->host,
'port' => $model->port,
'username' => $model->username,
'node' => $model->node_id,
'created_at' => $model->created_at->toAtomString(),
'updated_at' => $model->updated_at->toAtomString(),
];
}
/**
* Include the databases associated with this host.
*
* @throws InvalidTransformerLevelException
*/
public function includeDatabases(DatabaseHost $model): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_SERVER_DATABASES)) {
return $this->null();
}
$model->loadMissing('databases');
return $this->collection($model->getRelation('databases'), $this->makeTransformer(ServerDatabaseTransformer::class), Database::RESOURCE_NAME);
}
}
@@ -1,198 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use Illuminate\Support\Arr;
use JsonException;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;
use League\Fractal\Resource\NullResource;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseField;
use Pterodactyl\Models\Egg;
use Pterodactyl\Models\EggVariable;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Tag;
use Pterodactyl\Services\Acl\Api\AdminAcl;
use Pterodactyl\Support\JsonEmptyObject;
#[ResponseField('description', nullable: true)]
#[ResponseField('docker_images', schema: ['type' => 'object', 'additionalProperties' => ['type' => 'string'], 'example' => ['Java 23' => 'ghcr.io/pterodactyl/yolks:java_23']])]
#[ResponseField('config.files', schema: ['type' => 'object', 'additionalProperties' => ['type' => 'object', 'properties' => ['parser' => ['type' => 'string'], 'find' => ['type' => 'object', 'additionalProperties' => ['oneOf' => [['type' => 'string'], ['type' => 'number'], ['type' => 'boolean'], ['type' => 'object', 'additionalProperties' => ['type' => 'string']]]]]]], 'example' => ['server.properties' => ['parser' => 'properties', 'find' => ['server-port' => '{{server.build.default.port}}']]]])]
#[ResponseField('config.logs', schema: ['type' => 'object', 'nullable' => true, 'additionalProperties' => ['oneOf' => [['type' => 'string'], ['type' => 'number'], ['type' => 'boolean']]], 'example' => ['custom' => true, 'location' => 'logs/latest.log']])]
#[ResponseField('config.file_denylist', schema: ['type' => 'array', 'nullable' => true, 'items' => ['type' => 'string'], 'example' => ['secret.txt']])]
#[ResponseField('config.stop', nullable: true)]
#[ResponseField('config.startup', schema: ['type' => 'object', 'nullable' => true, 'additionalProperties' => ['oneOf' => [['type' => 'string'], ['type' => 'array', 'items' => ['type' => 'string']]]], 'example' => ['done' => ['Done']]])]
class EggTransformer extends BaseTransformer
{
protected array $includeRelations = [
'servers' => ['relation' => 'servers', 'transformer' => ServerTransformer::class, 'ability' => AdminAcl::RESOURCE_SERVERS],
'config' => ['relation' => 'configFrom'],
'script' => ['relation' => 'scriptFrom'],
'variables' => ['relation' => 'variables', 'transformer' => EggVariableTransformer::class, 'ability' => AdminAcl::RESOURCE_EGGS],
'tags' => ['relation' => 'tags', 'transformer' => TagTransformer::class, 'ability' => AdminAcl::RESOURCE_EGGS],
];
/**
* Relationships that can be loaded onto this transformation.
*
* @var list<string>
*/
protected array $availableIncludes = [
'servers',
'config',
'script',
'variables',
'tags',
];
/**
* Return the resource name for the JSONAPI output.
*/
public function getResourceName(): string
{
return Egg::RESOURCE_NAME;
}
/**
* Transform an Egg model into a representation that can be consumed by
* the application api.
*
* @return array<string, mixed>
*
* @throws JsonException
*/
public function transform(Egg $model): array
{
$files = json_decode($model->config_files ?? 'null', true, 512, JSON_THROW_ON_ERROR);
if (empty($files)) {
$files = new JsonEmptyObject;
}
return [
'id' => $model->id,
'uuid' => $model->uuid,
'name' => $model->name,
'author' => $model->author,
'description' => $model->description,
// "docker_image" is deprecated, but left here to avoid breaking too many things at once
// in external software. We'll remove it down the road once things have gotten the chance
// to upgrade to using "docker_images".
'docker_image' => count($model->docker_images) > 0 ? Arr::first($model->docker_images) : '',
'docker_images' => $model->docker_images,
'config' => [
'files' => $files,
'startup' => json_decode($model->config_startup ?? 'null', true),
'stop' => $model->config_stop,
'logs' => json_decode($model->config_logs ?? 'null', true),
'file_denylist' => $model->file_denylist,
'extends' => $model->config_from,
],
'startup' => $model->startup,
'script' => [
'privileged' => $model->script_is_privileged,
'install' => $model->script_install,
'entry' => $model->script_entry,
'container' => $model->script_container,
'extends' => $model->copy_script_from,
],
'relationships' => [],
$model->getCreatedAtColumn() => $this->formatTimestamp($model->created_at),
$model->getUpdatedAtColumn() => $this->formatTimestamp($model->updated_at),
];
}
/**
* Include the Servers relationship for the given Egg in the transformation.
*
* @throws InvalidTransformerLevelException
*/
public function includeServers(Egg $model): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_SERVERS)) {
return $this->null();
}
$model->loadMissing('servers');
return $this->collection($model->getRelation('servers'), $this->makeTransformer(ServerTransformer::class), Server::RESOURCE_NAME);
}
/**
* Include more detailed information about the configuration if this Egg is
* extending another.
*/
public function includeConfig(Egg $model): Item|NullResource
{
if (($model->config_from) === null) {
return $this->null();
}
$model->loadMissing('configFrom');
return $this->item($model, fn (Egg $model): array => [
'files' => json_decode($model->inherit_config_files ?? 'null'),
'startup' => json_decode($model->inherit_config_startup ?? 'null'),
'stop' => $model->inherit_config_stop,
'logs' => json_decode($model->inherit_config_logs ?? 'null'),
]);
}
/**
* Include more detailed information about the script configuration if the
* Egg is extending another.
*/
public function includeScript(Egg $model): Item|NullResource
{
if (($model->copy_script_from) === null) {
return $this->null();
}
$model->loadMissing('scriptFrom');
return $this->item($model, fn (Egg $model): array => [
'privileged' => $model->script_is_privileged,
'install' => $model->copy_script_install,
'entry' => $model->copy_script_entry,
'container' => $model->copy_script_container,
]);
}
/**
* Include the variables that are defined for this Egg.
*
* @throws InvalidTransformerLevelException
*/
public function includeVariables(Egg $model): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_EGGS)) {
return $this->null();
}
$model->loadMissing('variables');
return $this->collection(
$model->getRelation('variables'),
$this->makeTransformer(EggVariableTransformer::class),
EggVariable::RESOURCE_NAME
);
}
/**
* Include the tags assigned to this Egg.
*
* @throws InvalidTransformerLevelException
*/
public function includeTags(Egg $model): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_EGGS)) {
return $this->null();
}
$model->loadMissing('tags');
return $this->collection($model->getRelation('tags'), $this->makeTransformer(TagTransformer::class), Tag::RESOURCE_NAME);
}
}
@@ -1,27 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use Pterodactyl\Models\Egg;
use Pterodactyl\Models\EggVariable;
class EggVariableTransformer extends BaseTransformer
{
/**
* Return the resource name for the JSONAPI output.
*/
public function getResourceName(): string
{
return Egg::RESOURCE_NAME;
}
/**
* @return array<string, mixed>
*/
public function transform(EggVariable $model): array
{
return $model->attributesToArray();
}
}
@@ -1,82 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\NullResource;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Models\Location;
use Pterodactyl\Services\Acl\Api\AdminAcl;
class LocationTransformer extends BaseTransformer
{
protected array $includeRelations = [
'servers' => ['relation' => 'servers', 'transformer' => ServerTransformer::class, 'ability' => AdminAcl::RESOURCE_SERVERS],
'nodes' => ['relation' => 'nodes', 'transformer' => NodeTransformer::class, 'ability' => AdminAcl::RESOURCE_NODES],
];
/**
* List of resources that can be included.
*
* @var list<string>
*/
protected array $availableIncludes = ['nodes', 'servers'];
/**
* Return the resource name for the JSONAPI output.
*/
public function getResourceName(): string
{
return Location::RESOURCE_NAME;
}
/**
* Return a generic transformed location array.
*
* @return array<string, mixed>
*/
public function transform(Location $location): array
{
return [
'id' => $location->id,
'short' => $location->short,
'long' => $location->long,
'relationships' => [],
$location->getUpdatedAtColumn() => $this->formatTimestamp($location->updated_at),
$location->getCreatedAtColumn() => $this->formatTimestamp($location->created_at),
...$this->extensionFields($location),
];
}
/**
* @throws InvalidTransformerLevelException
*/
public function includeServers(Location $location): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_SERVERS)) {
return $this->null();
}
$location->loadMissing('servers');
return $this->collection($location->getRelation('servers'), $this->makeTransformer(ServerTransformer::class), 'server');
}
/**
* Return the nodes associated with this location.
*
* @throws InvalidTransformerLevelException
*/
public function includeNodes(Location $location): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_NODES)) {
return $this->null();
}
$location->loadMissing('nodes');
return $this->collection($location->getRelation('nodes'), $this->makeTransformer(NodeTransformer::class), 'node');
}
}
@@ -1,122 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use Illuminate\Support\Str;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;
use League\Fractal\Resource\NullResource;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Models\Node;
use Pterodactyl\Services\Acl\Api\AdminAcl;
class NodeTransformer extends BaseTransformer
{
protected array $eagerLoadSums = ['servers as sum_memory' => 'memory', 'servers as sum_disk' => 'disk'];
protected array $includeRelations = [
'allocations' => ['relation' => 'allocations', 'transformer' => AllocationTransformer::class, 'ability' => AdminAcl::RESOURCE_ALLOCATIONS],
'location' => ['relation' => 'location', 'transformer' => LocationTransformer::class, 'ability' => AdminAcl::RESOURCE_LOCATIONS],
'servers' => ['relation' => 'servers', 'transformer' => ServerTransformer::class, 'ability' => AdminAcl::RESOURCE_SERVERS],
];
/**
* List of resources that can be included.
*
* @var list<string>
*/
protected array $availableIncludes = ['allocations', 'location', 'servers'];
/**
* Return the resource name for the JSONAPI output.
*/
public function getResourceName(): string
{
return Node::RESOURCE_NAME;
}
/**
* Return a node transformed into a format that can be consumed by the
* external administrative API.
*
* @return array<string, mixed>
*/
public function transform(Node $node): array
{
$attributes = $node->attributesToArray();
$response = [];
foreach ($attributes as $key => $value) {
// I messed up early in 2016 when I named this column as poorly
// as I did. This is the tragic result of my mistakes.
$key = ($key === 'daemonSFTP') ? 'daemonSftp' : $key;
$response[Str::snake($key)] = $value;
}
$response[$node->getUpdatedAtColumn()] = $this->formatTimestamp($node->updated_at);
$response[$node->getCreatedAtColumn()] = $this->formatTimestamp($node->created_at);
unset($response['sum_memory'], $response['sum_disk']);
$response['allocated_resources'] = $node->allocatedResources();
$response['relationships'] = [];
return [...$response, ...$this->extensionFields($node)];
}
/**
* @throws InvalidTransformerLevelException
*/
public function includeAllocations(Node $node): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_ALLOCATIONS)) {
return $this->null();
}
$node->loadMissing('allocations');
return $this->collection(
$node->getRelation('allocations'),
$this->makeTransformer(AllocationTransformer::class),
'allocation'
);
}
/**
* @throws InvalidTransformerLevelException
*/
public function includeLocation(Node $node): Item|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_LOCATIONS)) {
return $this->null();
}
$node->loadMissing('location');
return $this->item(
$node->getRelation('location'),
$this->makeTransformer(LocationTransformer::class),
'location'
);
}
/**
* @throws InvalidTransformerLevelException
*/
public function includeServers(Node $node): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_SERVERS)) {
return $this->null();
}
$node->loadMissing('servers');
return $this->collection(
$node->getRelation('servers'),
$this->makeTransformer(ServerTransformer::class),
'server'
);
}
}
@@ -1,85 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use Illuminate\Support\Facades\Crypt;
use League\Fractal\Resource\Item;
use League\Fractal\Resource\NullResource;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseField;
use Pterodactyl\Models\Database;
use Pterodactyl\Models\DatabaseHost;
use Pterodactyl\Services\Acl\Api\AdminAcl;
#[ResponseField('max_connections', 'integer', example: 0, nullable: true)]
class ServerDatabaseTransformer extends BaseTransformer
{
protected array $includeRelations = [
'host' => ['relation' => 'host', 'transformer' => DatabaseHostTransformer::class, 'ability' => AdminAcl::RESOURCE_DATABASE_HOSTS],
];
/**
* @var list<string>
*/
protected array $availableIncludes = ['password', 'host'];
/**
* Return the resource name for the JSONAPI output.
*/
public function getResourceName(): string
{
return Database::RESOURCE_NAME;
}
/**
* Transform a database model in a representation for the application API.
*
* @return array<string, mixed>
*/
public function transform(Database $model): array
{
return [
'id' => $model->id,
'server' => $model->server_id,
'host' => $model->database_host_id,
'database' => $model->database,
'username' => $model->username,
'remote' => $model->remote,
'max_connections' => $model->max_connections,
'created_at' => $model->created_at->toAtomString(),
'updated_at' => $model->updated_at->toAtomString(),
];
}
/**
* Include the database password in the request.
*/
public function includePassword(Database $model): Item
{
return $this->item($model, fn (Database $model): array => [
'password' => Crypt::decrypt($model->password),
], 'database_password');
}
/**
* Return the database host relationship for this server database.
*
* @throws InvalidTransformerLevelException
*/
public function includeHost(Database $model): Item|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_DATABASE_HOSTS)) {
return $this->null();
}
$model->loadMissing('host');
return $this->item(
$model->getRelation('host'),
$this->makeTransformer(DatabaseHostTransformer::class),
DatabaseHost::RESOURCE_NAME
);
}
}
@@ -1,34 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use Pterodactyl\Models\ServerTransfer;
class ServerTransferTransformer extends BaseTransformer
{
public function getResourceName(): string
{
return 'server_transfer';
}
/**
* @return array<string, mixed>
*/
public function transform(ServerTransfer $model): array
{
return [
'id' => $model->id,
'server_id' => $model->server_id,
'old_node' => $model->old_node,
'new_node' => $model->new_node,
'old_allocation' => $model->old_allocation,
'new_allocation' => $model->new_allocation,
'successful' => $model->successful,
'archived' => $model->archived,
$model->getCreatedAtColumn() => $this->formatTimestamp($model->created_at),
$model->getUpdatedAtColumn() => $this->formatTimestamp($model->updated_at),
];
}
}
@@ -1,254 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;
use League\Fractal\Resource\NullResource;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseField;
use Pterodactyl\Models\Server;
use Pterodactyl\Services\Acl\Api\AdminAcl;
use Pterodactyl\Services\Servers\EnvironmentService;
#[ResponseField('description', nullable: true)]
#[ResponseField('feature_limits.databases', 'integer', example: 0, nullable: true)]
#[ResponseField('feature_limits.allocations', 'integer', example: 0, nullable: true)]
#[ResponseField('feature_limits.backups', 'integer', example: 0, nullable: true)]
#[ResponseField('container.environment', schema: ['type' => 'object', 'additionalProperties' => ['nullable' => true, 'oneOf' => [['type' => 'string'], ['type' => 'number'], ['type' => 'boolean']]], 'example' => ['SERVER_JARFILE' => 'server.jar']])]
class ServerTransformer extends BaseTransformer
{
protected array $eagerLoads = ['egg.variables', 'serverVariables', 'location'];
protected array $includeRelations = [
'allocations' => ['relation' => 'allocations', 'transformer' => AllocationTransformer::class, 'ability' => AdminAcl::RESOURCE_ALLOCATIONS],
'subusers' => ['relation' => 'subusers', 'transformer' => SubuserTransformer::class, 'ability' => AdminAcl::RESOURCE_USERS],
'user' => ['relation' => 'user', 'transformer' => UserTransformer::class, 'ability' => AdminAcl::RESOURCE_USERS],
'egg' => ['relation' => 'egg', 'transformer' => EggTransformer::class, 'ability' => AdminAcl::RESOURCE_EGGS],
'location' => ['relation' => 'location', 'transformer' => LocationTransformer::class, 'ability' => AdminAcl::RESOURCE_LOCATIONS],
'node' => ['relation' => 'node', 'transformer' => NodeTransformer::class, 'ability' => AdminAcl::RESOURCE_NODES],
'databases' => ['relation' => 'databases', 'transformer' => ServerDatabaseTransformer::class, 'ability' => AdminAcl::RESOURCE_SERVER_DATABASES],
'transfer' => ['relation' => 'transfer', 'transformer' => ServerTransferTransformer::class, 'ability' => AdminAcl::RESOURCE_SERVERS],
];
/**
* List of resources that can be included.
*
* @var list<string>
*/
protected array $availableIncludes = [
'allocations',
'user',
'subusers',
'egg',
'variables',
'location',
'node',
'databases',
'transfer',
];
public function __construct(private readonly EnvironmentService $environmentService) {}
/**
* Return the resource name for the JSONAPI output.
*/
public function getResourceName(): string
{
return Server::RESOURCE_NAME;
}
/**
* Return a generic transformed server array.
*
* @return array<string, mixed>
*/
public function transform(Server $server): array
{
return [
'id' => $server->getKey(),
'external_id' => $server->external_id,
'uuid' => $server->uuid,
'identifier' => $server->uuidShort,
'name' => $server->name,
'description' => $server->description,
'status' => $server->status,
// This field is deprecated, please use "status".
'suspended' => $server->isSuspended(),
'limits' => [
'memory' => $server->memory,
'swap' => $server->swap,
'disk' => $server->disk,
'io' => $server->io,
'cpu' => $server->cpu,
'threads' => $server->threads,
'oom_disabled' => $server->oom_disabled,
],
'feature_limits' => [
'databases' => $server->database_limit,
'allocations' => $server->allocation_limit,
'backups' => $server->backup_limit,
],
'user' => $server->owner_id,
'node' => $server->node_id,
'allocation' => $server->allocation_id,
'egg' => $server->egg_id,
'container' => [
'startup_command' => $server->startup,
'image' => $server->image,
// This field is deprecated, please use "status".
'installed' => $server->isInstalled() ? 1 : 0,
'environment' => $this->environmentService->handle($server),
'skip_scripts' => $server->skip_scripts,
],
'relationships' => [],
$server->getUpdatedAtColumn() => $this->formatTimestamp($server->updated_at),
$server->getCreatedAtColumn() => $this->formatTimestamp($server->created_at),
...$this->extensionFields($server),
];
}
/**
* Return a generic array of allocations for this server.
*
* @throws InvalidTransformerLevelException
*/
public function includeAllocations(Server $server): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_ALLOCATIONS)) {
return $this->null();
}
$server->loadMissing('allocations');
return $this->collection($server->getRelation('allocations'), $this->makeTransformer(AllocationTransformer::class), 'allocation');
}
/**
* Return a generic array of data about subusers for this server.
*
* @throws InvalidTransformerLevelException
*/
public function includeSubusers(Server $server): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_USERS)) {
return $this->null();
}
$server->loadMissing('subusers');
return $this->collection($server->getRelation('subusers'), $this->makeTransformer(SubuserTransformer::class), 'subuser');
}
/**
* @throws InvalidTransformerLevelException
*/
public function includeUser(Server $server): Item|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_USERS)) {
return $this->null();
}
$server->loadMissing('user');
return $this->item($server->getRelation('user'), $this->makeTransformer(UserTransformer::class), 'user');
}
/**
* Return a generic array with egg information for this server.
*
* @throws InvalidTransformerLevelException
*/
public function includeEgg(Server $server): Item|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_EGGS)) {
return $this->null();
}
$server->loadMissing('egg');
return $this->item($server->getRelation('egg'), $this->makeTransformer(EggTransformer::class), 'egg');
}
/**
* @throws InvalidTransformerLevelException
*/
public function includeVariables(Server $server): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_SERVERS)) {
return $this->null();
}
return $this->collection($this->environmentService->variables($server), $this->makeTransformer(ServerVariableTransformer::class), 'server_variable');
}
/**
* Return a generic array with location information for this server.
*
* @throws InvalidTransformerLevelException
*/
public function includeLocation(Server $server): Item|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_LOCATIONS)) {
return $this->null();
}
$server->loadMissing('location');
return $this->item($server->getRelation('location'), $this->makeTransformer(LocationTransformer::class), 'location');
}
/**
* Return a generic array with node information for this server.
*
* @throws InvalidTransformerLevelException
*/
public function includeNode(Server $server): Item|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_NODES)) {
return $this->null();
}
$server->loadMissing('node');
return $this->item($server->getRelation('node'), $this->makeTransformer(NodeTransformer::class), 'node');
}
/**
* Return a generic array with database information for this server.
*
* @throws InvalidTransformerLevelException
*/
public function includeDatabases(Server $server): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_SERVER_DATABASES)) {
return $this->null();
}
$server->loadMissing('databases');
return $this->collection($server->getRelation('databases'), $this->makeTransformer(ServerDatabaseTransformer::class), 'databases');
}
/**
* Return the active transfer for this server, when one exists.
*
* @throws InvalidTransformerLevelException
*/
public function includeTransfer(Server $server): Item|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_SERVERS)) {
return $this->null();
}
$server->loadMissing('transfer');
if (($server->getRelation('transfer')) === null) {
return $this->null();
}
return $this->item($server->getRelation('transfer'), $this->makeTransformer(ServerTransferTransformer::class), 'server_transfer');
}
}
@@ -1,54 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use League\Fractal\Resource\Item;
use League\Fractal\Resource\NullResource;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Models\EggVariable;
use Pterodactyl\Models\ServerVariable;
use Pterodactyl\Services\Acl\Api\AdminAcl;
class ServerVariableTransformer extends BaseTransformer
{
/**
* List of resources that can be included.
*
* @var list<string>
*/
protected array $availableIncludes = ['parent'];
/**
* Return the resource name for the JSONAPI output.
*/
public function getResourceName(): string
{
return ServerVariable::RESOURCE_NAME;
}
/**
* Return a generic transformed server variable array.
*
* @return array<string, mixed>
*/
public function transform(EggVariable $variable): array
{
return $variable->attributesToArray();
}
/**
* Return the parent service variable data.
*
* @throws InvalidTransformerLevelException
*/
public function includeParent(EggVariable $variable): Item|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_EGGS)) {
return $this->null();
}
return $this->item($variable, $this->makeTransformer(EggVariableTransformer::class), 'variable');
}
}
@@ -1,83 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use League\Fractal\Resource\Item;
use League\Fractal\Resource\NullResource;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Models\Subuser;
use Pterodactyl\Services\Acl\Api\AdminAcl;
class SubuserTransformer extends BaseTransformer
{
protected array $includeRelations = [
'user' => ['relation' => 'user', 'transformer' => UserTransformer::class, 'ability' => AdminAcl::RESOURCE_USERS],
'server' => ['relation' => 'server', 'transformer' => ServerTransformer::class, 'ability' => AdminAcl::RESOURCE_SERVERS],
];
/**
* List of resources that can be included.
*
* @var list<string>
*/
protected array $availableIncludes = ['user', 'server'];
/**
* Return the resource name for the JSONAPI output.
*/
public function getResourceName(): string
{
return Subuser::RESOURCE_NAME;
}
/**
* Return a transformed Subuser model that can be consumed by external services.
*
* @return array<string, mixed>
*/
public function transform(Subuser $subuser): array
{
return [
'id' => $subuser->id,
'user_id' => $subuser->user_id,
'server_id' => $subuser->server_id,
'permissions' => $subuser->permissions,
'created_at' => $this->formatTimestamp($subuser->created_at),
'updated_at' => $this->formatTimestamp($subuser->updated_at),
];
}
/**
* Return a generic item of user for this subuser.
*
* @throws InvalidTransformerLevelException
*/
public function includeUser(Subuser $subuser): Item|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_USERS)) {
return $this->null();
}
$subuser->loadMissing('user');
return $this->item($subuser->getRelation('user'), $this->makeTransformer(UserTransformer::class), 'user');
}
/**
* Return a generic item of server for this subuser.
*
* @throws InvalidTransformerLevelException
*/
public function includeServer(Subuser $subuser): Item|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_SERVERS)) {
return $this->null();
}
$subuser->loadMissing('server');
return $this->item($subuser->getRelation('server'), $this->makeTransformer(ServerTransformer::class), 'server');
}
}
@@ -1,93 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\NullResource;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseField;
use Pterodactyl\Models\Egg;
use Pterodactyl\Models\Node;
use Pterodactyl\Models\Tag;
use Pterodactyl\Services\Acl\Api\AdminAcl;
#[ResponseField('color', nullable: true)]
#[ResponseField('legacy_nest_id', 'integer', example: 1, nullable: true)]
class TagTransformer extends BaseTransformer
{
protected array $includeRelations = [
'eggs' => ['relation' => 'eggs', 'transformer' => EggTransformer::class, 'ability' => AdminAcl::RESOURCE_EGGS],
'nodes' => ['relation' => 'nodes', 'transformer' => NodeTransformer::class, 'ability' => AdminAcl::RESOURCE_NODES],
];
/**
* Relationships that can be loaded onto this transformation.
*
* @var list<string>
*/
protected array $availableIncludes = ['eggs', 'nodes'];
/**
* Return the resource name for the JSONAPI output.
*/
public function getResourceName(): string
{
return Tag::RESOURCE_NAME;
}
/**
* Transform a tag into its application API representation. Built-in game tags
* report the name and colour that the Panel assigns them.
*
* @return array<string, mixed>
*/
public function transform(Tag $model): array
{
return [
'id' => $model->id,
'name' => $model->effectiveName(),
'slug' => $model->slug,
'color' => $model->effectiveColor(),
'is_predefined' => $model->isPredefined(),
'legacy_nest_id' => $model->legacy_nest_id,
'relationships' => [],
$model->getCreatedAtColumn() => $this->formatTimestamp($model->created_at),
$model->getUpdatedAtColumn() => $this->formatTimestamp($model->updated_at),
];
}
/**
* Include the eggs that carry this tag.
*
* @throws InvalidTransformerLevelException
*/
public function includeEggs(Tag $model): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_EGGS)) {
return $this->null();
}
$model->loadMissing('eggs');
return $this->collection($model->getRelation('eggs'), $this->makeTransformer(EggTransformer::class), Egg::RESOURCE_NAME);
}
/**
* Include the nodes that carry this tag, either as a game they accept or as a
* deployment reservation.
*
* @throws InvalidTransformerLevelException
*/
public function includeNodes(Tag $model): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_NODES)) {
return $this->null();
}
$model->loadMissing('nodes');
return $this->collection($model->getRelation('nodes'), $this->makeTransformer(NodeTransformer::class), Node::RESOURCE_NAME);
}
}
@@ -1,74 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Transformers\Api\Application;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\NullResource;
use Pterodactyl\Exceptions\Transformer\InvalidTransformerLevelException;
use Pterodactyl\Models\User;
use Pterodactyl\Services\Acl\Api\AdminAcl;
class UserTransformer extends BaseTransformer
{
protected array $includeRelations = [
'servers' => ['relation' => 'servers', 'transformer' => ServerTransformer::class, 'ability' => AdminAcl::RESOURCE_SERVERS],
];
/**
* List of resources that can be included.
*
* @var list<string>
*/
protected array $availableIncludes = ['servers'];
/**
* Return the resource name for the JSONAPI output.
*/
public function getResourceName(): string
{
return User::RESOURCE_NAME;
}
/**
* Return a transformed User model that can be consumed by external services.
*
* @return array<string, mixed>
*/
public function transform(User $user): array
{
return [
'id' => $user->id,
'external_id' => $user->external_id,
'uuid' => $user->uuid,
'username' => $user->username,
'email' => $user->email,
'first_name' => $user->name_first,
'last_name' => $user->name_last,
'language' => $user->language,
'root_admin' => (bool) $user->root_admin,
'2fa' => (bool) $user->use_totp,
'relationships' => [],
'created_at' => $this->formatTimestamp($user->created_at),
'updated_at' => $this->formatTimestamp($user->updated_at),
...$this->extensionFields($user),
];
}
/**
* Return the servers associated with this user.
*
* @throws InvalidTransformerLevelException
*/
public function includeServers(User $user): Collection|NullResource
{
if (! $this->authorize(AdminAcl::RESOURCE_SERVERS)) {
return $this->null();
}
$user->loadMissing('servers');
return $this->collection($user->getRelation('servers'), $this->makeTransformer(ServerTransformer::class), 'server');
}
}
@@ -1,232 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Tests\Integration\Api\Parity;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Facade;
use Pterodactyl\Facades\Fractal;
use Pterodactyl\Http\Resources\Api\ApiResource;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Models\User;
use Pterodactyl\Transformers\Api\Application\BaseTransformer;
/**
* Renders a Fractal transformer and the API resource replacing it for the same request, the
* way a controller does, and asserts the two responses have the same status and the same
* bytes, and that both ran the same queries in the same order.
*
* Each render loads its data through the given closure, so both sides work on fresh model
* instances and neither can see relations the other eager loaded. Each also runs under a
* request built the same way: the same URI (so the same includes and page), and the same
* user and API key, loaded fresh as well.
*/
final class ResourceParity
{
private string $uri = '/';
private ?int $user = null;
private ?int $key = null;
/** @var list<string> */
private array $forced = [];
/** @var array<string, mixed> */
private array $meta = [];
private bool $extensionFields = false;
private ?int $status = null;
/**
* @param class-string<BaseTransformer> $transformer
* @param class-string<ApiResource<*>> $resource
* @param Closure(): mixed $data
*/
private function __construct(
private readonly string $transformer,
private readonly string $resource,
private readonly Closure $data,
private readonly bool $list,
) {}
/**
* One model, as Fractal::item($data) renders it.
*
* @param class-string<BaseTransformer> $transformer
* @param class-string<ApiResource<*>> $resource
* @param Closure(): mixed $data
*/
public static function item(string $transformer, string $resource, Closure $data): self
{
return new self($transformer, $resource, $data, false);
}
/**
* A list or a paginator, as Fractal::collection($data) renders it.
*
* @param class-string<BaseTransformer> $transformer
* @param class-string<ApiResource<*>> $resource
* @param Closure(): mixed $data
*/
public static function list(string $transformer, string $resource, Closure $data): self
{
return new self($transformer, $resource, $data, true);
}
public function request(string $uri): self
{
$this->uri = $uri;
return $this;
}
public function actingAs(User $user, ?ApiKey $key = null): self
{
$this->user = $user->id;
$this->key = $key?->id;
return $this;
}
/**
* Includes the controller always returns: parseIncludes() and withIncludes().
*/
public function forcing(string ...$includes): self
{
$this->forced = [...$this->forced, ...array_values($includes)];
return $this;
}
/**
* @param array<string, mixed> $meta
*/
public function withMeta(array $meta): self
{
$this->meta = [...$this->meta, ...$meta];
return $this;
}
public function withExtensionFields(): self
{
$this->extensionFields = true;
return $this;
}
/**
* Responds through respond($status) on both sides instead of returning the payload.
*/
public function respond(int $status): self
{
$this->status = $status;
return $this;
}
/**
* Asserts both sides render the same response with the same queries, and returns the body.
*/
public function assertSame(): string
{
$fractal = $this->render(fn (Request $request): JsonResponse => $this->fractal());
$resource = $this->render(fn (Request $request): JsonResponse => $this->resource($request));
expect($resource['body'])->toBe($fractal['body'])
->and($resource['status'])->toBe($fractal['status'])
->and($resource['queries'])->toBe($fractal['queries']);
return $fractal['body'];
}
/**
* The response a controller builds with Fractal.
*/
private function fractal(): JsonResponse
{
$transformer = App::make($this->transformer);
if ($this->extensionFields) {
$transformer->withExtensionFields();
}
$data = ($this->data)();
$fractal = ($this->list ? Fractal::collection($data) : Fractal::item($data))->transformWith($transformer);
if ($this->forced !== []) {
$fractal->parseIncludes($this->forced);
}
if ($this->meta !== []) {
$fractal->addMeta($this->meta);
}
// A controller returns the payload array and the router turns it into a JsonResponse.
return $this->status === null ? new JsonResponse($fractal->toResponseArray()) : $fractal->respond($this->status);
}
/**
* The response a controller builds with the resource.
*/
private function resource(Request $request): JsonResponse
{
$data = ($this->data)();
$resource = $this->list ? $this->resource::collection($data) : new $this->resource($data);
if ($this->extensionFields && $resource instanceof ApiResource) {
$resource->withExtensionFields();
}
if ($this->forced !== []) {
$resource->withIncludes(...$this->forced);
}
if ($this->meta !== []) {
$resource->withMeta($this->meta);
}
return $this->status === null ? $resource->toResponse($request) : $resource->respond($this->status);
}
/**
* @param Closure(Request): JsonResponse $respond
* @return array{status: int, body: string, queries: list<array{0: string, 1: array<mixed>}>}
*/
private function render(Closure $respond): array
{
// Bound as the HTTP kernel binds a request, since transformers read it through the
// Request facade. Binding resets the user resolver, so the user is set afterwards.
$request = Request::create($this->uri, server: ['HTTP_ACCEPT' => 'application/json']);
App::instance('request', $request);
App::instance(Request::class, $request);
Facade::clearResolvedInstance('request');
if ($this->user !== null) {
$user = User::query()->findOrFail($this->user);
if ($this->key !== null) {
$user->withAccessToken(ApiKey::query()->findOrFail($this->key));
}
$request->setUserResolver(fn (): User => $user);
}
DB::flushQueryLog();
DB::enableQueryLog();
try {
$response = $respond($request);
} finally {
DB::disableQueryLog();
}
return [
'status' => $response->getStatusCode(),
'body' => (string) $response->getContent(),
'queries' => array_map(fn (array $query): array => [$query['query'], $query['bindings']], DB::getQueryLog()),
];
}
}
@@ -1,61 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Tests\Pest\Integration\Api\Parity\ResourceParityTest;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\App;
use Pterodactyl\Http\Resources\Api\Application\ServerVariableResource;
use Pterodactyl\Models\ApiKey;
use Pterodactyl\Models\EggVariable;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\User;
use Pterodactyl\Services\Acl\Api\AdminAcl;
use Pterodactyl\Services\Servers\EnvironmentService;
use Pterodactyl\Tests\Integration\Api\Parity\ResourceParity;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
use Pterodactyl\Transformers\Api\Application\ServerVariableTransformer;
/*
* The pilot resources of each API against the transformers they replace, through the
* parity harness: items, lists, pages, includes the requester may and may not see,
* forced includes, meta and explicit statuses.
*/
uses(IntegrationTestCase::class, DatabaseTransactions::class);
test('application server variables render the same with forced includes, meta, a status and pages', function (): void {
$server = $this->createServerModel();
$admin = User::factory()->create(['root_admin' => true]);
$key = ApiKey::factory()->create(['user_id' => $admin->id, 'key_type' => ApiKey::TYPE_ACCOUNT]);
$one = fn () => App::make(EnvironmentService::class)->variables(Server::query()->findOrFail($server->id))->firstOrFail();
$page = fn () => EggVariable::query()->where('egg_id', $server->egg_id)->paginate(1);
expect(ResourceParity::item(ServerVariableTransformer::class, ServerVariableResource::class, $one)
->forcing('parent')
->withMeta(['resource' => 'https://panel.example.test/api/application/servers/1'])
->respond(201)
->actingAs($admin, $key)
->assertSame())->toEndWith('"meta":{"resource":"https:\/\/panel.example.test\/api\/application\/servers\/1"}}');
expect(ResourceParity::list(ServerVariableTransformer::class, ServerVariableResource::class, $page)->request('/api/application/servers/1/variables?include=parent&page=2')->actingAs($admin, $key)->assertSame())
->toContain('"links":{"previous":');
});
test('application server variables render the same for keys with and without egg access', function (int $type, int $eggs, string $parent): void {
$server = $this->createServerModel();
$admin = User::factory()->create(['root_admin' => true]);
$key = ApiKey::factory()->create(['user_id' => $admin->id, 'key_type' => $type, AdminAcl::COLUMN_IDENTIFIER.AdminAcl::RESOURCE_EGGS => $eggs]);
$variables = fn () => App::make(EnvironmentService::class)->variables(Server::query()->findOrFail($server->id));
expect(ResourceParity::list(ServerVariableTransformer::class, ServerVariableResource::class, $variables)->request('/?include=parent')->actingAs($admin, $key)->assertSame())
->toContain('"relationships":{"parent":{"object":'.$parent);
ResourceParity::item(ServerVariableTransformer::class, ServerVariableResource::class, fn () => $variables()->firstOrFail())->request('/?include=parent')->actingAs($admin, $key)->assertSame();
ResourceParity::item(ServerVariableTransformer::class, ServerVariableResource::class, fn () => $variables()->firstOrFail())->actingAs($admin, $key)->assertSame();
})->with([
'an application key that reads eggs' => [ApiKey::TYPE_APPLICATION, AdminAcl::READ, '"variable"'],
'an application key without eggs' => [ApiKey::TYPE_APPLICATION, AdminAcl::NONE, '"null_resource"'],
'a root admin account key' => [ApiKey::TYPE_ACCOUNT, AdminAcl::NONE, '"variable"'],
]);
@@ -6,19 +6,15 @@ namespace Pterodactyl\Tests\Pest\Integration\Extensions\Scribe\ResponseFromResou
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Knuckles\Scribe\Tools\DocumentationConfig;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromResource;
use Pterodactyl\Extensions\Scribe\Attributes\ResponseFromTransformer;
use Pterodactyl\Extensions\Scribe\Strategies\UsePterodactylResponseAttributes;
use Pterodactyl\Http\Resources\Api\Application\ServerVariableResource;
use Pterodactyl\Models\EggVariable;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
use Pterodactyl\Transformers\Api\Application\ServerVariableTransformer;
/*
* #[ResponseFromResource] must document a resource exactly as #[ResponseFromTransformer]
* documented the transformer it replaces. Both render the first model in the database, so
* the two examples are built from the same row.
* #[ResponseFromResource] documents a resource from the first model in the database, with
* the attribute's includes, object name, status and meta.
*/
uses(IntegrationTestCase::class, DatabaseTransactions::class);
@@ -32,36 +28,33 @@ beforeEach(function (): void {
$this->strategy = new class(new DocumentationConfig($config)) extends UsePterodactylResponseAttributes
{
/** @return array{status: int, description: string|null, content: string|false} */
public function render(ResponseFromTransformer|ResponseFromResource $attribute): array
public function render(ResponseFromResource $attribute): array
{
return $attribute instanceof ResponseFromResource ? $this->getApiResourceResponse($attribute) : $this->getTransformerResponse($attribute);
return $this->getApiResourceResponse($attribute);
}
};
});
test('resources are documented as their transformers were', function (ResponseFromTransformer $transformer, ResponseFromResource $resource, string $expected): void {
$documented = $this->strategy->render($transformer);
test('resources are documented with their includes, object name, status and meta', function (ResponseFromResource $resource, string $expected): void {
$documented = $this->strategy->render($resource);
expect($this->strategy->render($resource))->toBe($documented)
expect($documented['status'])->toBe($resource->status)
->and($documented['description'])->toBe($resource->description)
->and($documented['content'])->toContain($expected);
})->with([
'an item with an include, a status and meta' => [
new ResponseFromTransformer(ServerVariableTransformer::class, EggVariable::class, status: 201, description: 'Variable created.', resourceKey: 'server_variable', meta: ['resource' => 'https://panel.example.test/api/application/servers/1'], include: ['parent']),
new ResponseFromResource(ServerVariableResource::class, EggVariable::class, status: 201, description: 'Variable created.', resourceKey: 'server_variable', meta: ['resource' => 'https://panel.example.test/api/application/servers/1'], include: ['parent']),
'"attributes":null}}},"meta":{"resource":"https:\/\/panel.example.test\/api\/application\/servers\/1"}}',
],
'a paginated list with meta after the pagination' => [
new ResponseFromTransformer(ServerVariableTransformer::class, EggVariable::class, collection: true, resourceKey: 'server_variable', paginate: [IlluminatePaginatorAdapter::class, 50], meta: ['note' => 'example']),
new ResponseFromResource(ServerVariableResource::class, EggVariable::class, collection: true, resourceKey: 'server_variable', paginate: 50, meta: ['note' => 'example']),
'"meta":{"pagination":{"total":1,"count":1,"per_page":50,"current_page":1,"total_pages":1,"links":[]},"note":"example"}',
],
'an item without a resource key' => [
new ResponseFromTransformer(ServerVariableTransformer::class, EggVariable::class, include: ['parent']),
new ResponseFromResource(ServerVariableResource::class, EggVariable::class, include: ['parent']),
'{"object":null,"attributes":',
],
'a list with counts loaded after the model and a gated include' => [
new ResponseFromTransformer(ServerVariableTransformer::class, EggVariable::class, collection: true, resourceKey: 'server_variable', include: ['parent'], withCount: ['serverVariable']),
new ResponseFromResource(ServerVariableResource::class, EggVariable::class, collection: true, resourceKey: 'server_variable', include: ['parent'], withCount: ['serverVariable']),
'"server_variable_count":0,"relationships":{"parent":{"object":"null_resource","attributes":null}}',
],
+2 -2
View File
@@ -10,11 +10,11 @@ use Illuminate\Contracts\Foundation\Application;
use Illuminate\Filesystem\FilesystemManager;
use Illuminate\Support\Facades\Event;
use Pterodactyl\Events\ActivityLogged;
use Pterodactyl\Http\Resources\Api\ApiResource;
use Pterodactyl\Services\Helpers\AssetHashService;
use Pterodactyl\Tests\Assertions\AssertsActivityLogged;
use Pterodactyl\Tests\TestCase;
use Pterodactyl\Tests\Traits\Integration\CreatesTestModels;
use Pterodactyl\Transformers\Api\Application\BaseTransformer;
abstract class IntegrationTestCase extends TestCase
{
@@ -50,6 +50,6 @@ abstract class IntegrationTestCase extends TestCase
? CarbonImmutable::instance($timestamp)
: CarbonImmutable::createFromFormat(CarbonInterface::DEFAULT_TO_STRING_FORMAT, $timestamp);
return $value->setTimezone(BaseTransformer::RESPONSE_TIMEZONE)->toAtomString();
return $value->setTimezone(ApiResource::RESPONSE_TIMEZONE)->toAtomString();
}
}
@@ -1,17 +0,0 @@
<?php
declare(strict_types=1);
namespace Pterodactyl\Tests\Pest\Unit\Http\ApplicationApiControllerTest;
use Pterodactyl\Http\Controllers\Api\Application\ApplicationApiController;
use Pterodactyl\Tests\TestCase;
use Pterodactyl\Transformers\Api\Application\UserTransformer;
uses(TestCase::class);
test('the Application API resolves its own transformers', function (): void {
$controller = new class extends ApplicationApiController {};
expect($controller->getTransformer(UserTransformer::class))->toBeInstanceOf(UserTransformer::class);
});