Complete move from old repository to new repository structure!

This commit is contained in:
Dane Everitt 2017-08-26 18:08:11 -05:00
parent 2cabb61b54
commit 72735c24f7
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
27 changed files with 964 additions and 730 deletions

View file

@ -29,16 +29,47 @@ use Illuminate\Foundation\Application;
use Pterodactyl\Contracts\Repository\NodeRepositoryInterface;
use Illuminate\Contracts\Config\Repository as ConfigRepository;
use Pterodactyl\Contracts\Repository\Daemon\BaseRepositoryInterface;
use Webmozart\Assert\Assert;
class BaseRepository implements BaseRepositoryInterface
{
/**
* @var \Illuminate\Foundation\Application
*/
protected $app;
/**
* @var
*/
protected $accessServer;
/**
* @var
*/
protected $accessToken;
/**
* @var
*/
protected $node;
/**
* @var \Illuminate\Contracts\Config\Repository
*/
protected $config;
/**
* @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface
*/
protected $nodeRepository;
/**
* BaseRepository constructor.
*
* @param \Illuminate\Foundation\Application $app
* @param \Illuminate\Contracts\Config\Repository $config
* @param \Pterodactyl\Contracts\Repository\NodeRepositoryInterface $nodeRepository
*/
public function __construct(
Application $app,
ConfigRepository $config,
@ -49,44 +80,70 @@ class BaseRepository implements BaseRepositoryInterface
$this->nodeRepository = $nodeRepository;
}
/**
* {@inheritdoc}
*/
public function setNode($id)
{
// @todo accept a model
Assert::numeric($id, 'The first argument passed to setNode must be numeric, received %s.');
$this->node = $this->nodeRepository->find($id);
return $this;
}
/**
* {@inheritdoc}
*/
public function getNode()
{
return $this->node;
}
/**
* {@inheritdoc}
*/
public function setAccessServer($server = null)
{
Assert::nullOrString($server, 'The first argument passed to setAccessServer must be null or a string, received %s.');
$this->accessServer = $server;
return $this;
}
/**
* {@inheritdoc}
*/
public function getAccessServer()
{
return $this->accessServer;
}
/**
* {@inheritdoc}
*/
public function setAccessToken($token = null)
{
Assert::nullOrString($token, 'The first argument passed to setAccessToken must be null or a string, received %s.');
$this->accessToken = $token;
return $this;
}
/**
* {@inheritdoc}
*/
public function getAccessToken()
{
return $this->accessToken;
}
public function getHttpClient($headers = [])
/**
* {@inheritdoc}
*/
public function getHttpClient(array $headers = [])
{
if (! is_null($this->accessServer)) {
$headers['X-Access-Server'] = $this->getAccessServer();

View file

@ -0,0 +1,45 @@
<?php
/*
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Pterodactyl\Repositories\Daemon;
use Webmozart\Assert\Assert;
use Pterodactyl\Contracts\Repository\Daemon\CommandRepositoryInterface;
class CommandRepository extends BaseRepository implements CommandRepositoryInterface
{
/**
* {@inheritdoc}
*/
public function send($command)
{
Assert::stringNotEmpty($command, 'First argument passed to send must be a non-empty string, received %s.');
return $this->getHttpClient()->request('POST', '/server/command', [
'json' => [
'command' => $command,
],
]);
}
}

View file

@ -0,0 +1,126 @@
<?php
/*
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Pterodactyl\Repositories\Daemon;
use Pterodactyl\Contracts\Repository\Daemon\FileRepositoryInterface;
use Webmozart\Assert\Assert;
class FileRepository extends BaseRepository implements FileRepositoryInterface
{
public function getFileStat($path)
{
Assert::stringNotEmpty($path, 'First argument passed to getStat must be a non-empty string, received %s.');
$file = pathinfo($path);
$file['dirname'] = in_array($file['dirname'], ['.', './', '/']) ? null : trim($file['dirname'], '/') . '/';
$response = $this->getHttpClient()->request('GET', sprintf(
'/server/file/stat/%s',
rawurlencode($file['dirname'] . $file['basename'])
));
return json_decode($response->getBody());
}
/**
* {@inheritdoc}
*/
public function getContent($path)
{
Assert::stringNotEmpty($path, 'First argument passed to getContent must be a non-empty string, received %s.');
$file = pathinfo($path);
$file['dirname'] = in_array($file['dirname'], ['.', './', '/']) ? null : trim($file['dirname'], '/') . '/';
$response = $this->getHttpClient()->request('GET', sprintf(
'/server/file/f/%s',
rawurlencode($file['dirname'] . $file['basename'])
));
return json_decode($response->getBody());
}
/**
* {@inheritdoc}
*/
public function putContent($path, $content)
{
Assert::stringNotEmpty($path, 'First argument passed to putContent must be a non-empty string, received %s.');
Assert::string($content, 'Second argument passed to putContent must be a string, received %s.');
$file = pathinfo($path);
$file['dirname'] = in_array($file['dirname'], ['.', './', '/']) ? null : trim($file['dirname'], '/') . '/';
return $this->getHttpClient()->request('POST', '/server/file/save', [
'json' => [
'path' => rawurlencode($file['dirname'] . $file['basename']),
'content' => $content,
],
]);
}
/**
* {@inheritdoc}
*/
public function getDirectory($path)
{
Assert::string($path, 'First argument passed to getDirectory must be a string, received %s.');
$response = $this->getHttpClient()->request('GET', sprintf(
'/server/directory/%s',
rawurlencode($path)
));
$contents = json_decode($response->getBody());
$files = [];
$folders = [];
foreach ($contents as $value) {
if ($value->directory) {
array_push($folders, [
'entry' => $value->name,
'directory' => trim($path, '/'),
'size' => null,
'date' => strtotime($value->modified),
'mime' => $value->mime,
]);
} elseif ($value->file) {
array_push($files, [
'entry' => $value->name,
'directory' => trim($path, '/'),
'extension' => pathinfo($value->name, PATHINFO_EXTENSION),
'size' => human_readable($value->size),
'date' => strtotime($value->modified),
'mime' => $value->mime,
]);
}
}
return [
'files' => $files,
'folders' => $folders,
];
}
}

View file

@ -0,0 +1,55 @@
<?php
/*
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Pterodactyl\Repositories\Daemon;
use Webmozart\Assert\Assert;
use Pterodactyl\Contracts\Repository\Daemon\PowerRepositoryInterface;
use Pterodactyl\Exceptions\Repository\Daemon\InvalidPowerSignalException;
class PowerRepository extends BaseRepository implements PowerRepositoryInterface
{
/**
* {@inheritdoc}
*/
public function sendSignal($signal)
{
Assert::stringNotEmpty($signal, 'The first argument passed to sendSignal must be a non-empty string, received %s.');
switch ($signal) {
case self::SIGNAL_START:
case self::SIGNAL_STOP:
case self::SIGNAL_RESTART:
case self::SIGNAL_KILL:
return $this->getHttpClient()->request('PUT', '/server/power', [
'json' => [
'action' => $signal,
],
]);
break;
default:
throw new InvalidPowerSignalException('The signal ' . $signal . ' is not defined and could not be processed.');
}
}
}

View file

@ -27,6 +27,7 @@ namespace Pterodactyl\Repositories\Daemon;
use Pterodactyl\Services\Servers\EnvironmentService;
use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface as DatabaseServerRepositoryInterface;
use Webmozart\Assert\Assert;
class ServerRepository extends BaseRepository implements ServerRepositoryInterface
{
@ -35,8 +36,11 @@ class ServerRepository extends BaseRepository implements ServerRepositoryInterfa
/**
* {@inheritdoc}
*/
public function create($id, $overrides = [], $start = false)
public function create($id, array $overrides = [], $start = false)
{
Assert::numeric($id, 'First argument passed to create must be numeric, received %s.');
Assert::boolean($start, 'Third argument passed to create must be boolean, received %s.');
$repository = $this->app->make(DatabaseServerRepositoryInterface::class);
$environment = $this->app->make(EnvironmentService::class);
@ -89,6 +93,8 @@ class ServerRepository extends BaseRepository implements ServerRepositoryInterfa
*/
public function setSubuserKey($key, array $permissions)
{
Assert::stringNotEmpty($key, 'First argument passed to setSubuserKey must be a non-empty string, received %s.');
return $this->getHttpClient()->request('PATCH', '/server', [
'json' => [
'keys' => [
@ -113,6 +119,8 @@ class ServerRepository extends BaseRepository implements ServerRepositoryInterfa
*/
public function reinstall($data = null)
{
Assert::nullOrIsArray($data, 'First argument passed to reinstall must be null or an array, received %s.');
if (is_null($data)) {
return $this->getHttpClient()->request('POST', '/server/reinstall');
}

View file

@ -39,6 +39,21 @@ class SubuserRepository extends EloquentRepository implements SubuserRepositoryI
return Subuser::class;
}
/**
* {@inheritdoc}
*/
public function getWithServer($id)
{
Assert::numeric($id, 'First argument passed to getWithServer must be numeric, received %s.');
$instance = $this->getBuilder()->with('server')->find($id, $this->getColumns());
if (! $instance) {
throw new RecordNotFoundException;
}
return $instance;
}
/**
* {@inheritdoc}
*/

View file

@ -1,262 +0,0 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Pterodactyl\Repositories;
use DB;
use Validator;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Subuser;
use Pterodactyl\Models\Permission;
use Pterodactyl\Services\UuidService;
use GuzzleHttp\Exception\TransferException;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Exceptions\DisplayValidationException;
class SubuserRepository
{
/**
* Core permissions required for every subuser on the daemon.
* Without this we cannot connect the websocket or get basic
* information about the server.
*
* @var array
*/
protected $coreDaemonPermissions = [
's:get',
's:console',
];
/**
* Creates a new subuser on the server.
*
* @param int $sid
* @param array $data
* @return \Pterodactyl\Models\Subuser
*
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\DisplayValidationException
*/
public function create($sid, array $data)
{
$server = Server::with('node')->findOrFail($sid);
$validator = Validator::make($data, [
'permissions' => 'required|array',
'email' => 'required|email',
]);
if ($validator->fails()) {
throw new DisplayValidationException(json_encode($validator->errors()));
}
DB::beginTransaction();
try {
// Determine if this user exists or if we need to make them an account.
$user = User::where('email', $data['email'])->first();
if (! $user) {
try {
$repo = new oldUserRepository;
$user = $repo->create([
'email' => $data['email'],
'username' => str_random(8),
'name_first' => 'Unassigned',
'name_last' => 'Name',
'root_admin' => false,
]);
} catch (\Exception $ex) {
throw $ex;
}
} elseif ($server->owner_id === $user->id) {
throw new DisplayException('You cannot add the owner of a server as a subuser.');
} elseif (Subuser::select('id')->where('user_id', $user->id)->where('server_id', $server->id)->first()) {
throw new DisplayException('A subuser with that email already exists for this server.');
}
$uuid = new UuidService;
$subuser = Subuser::create([
'user_id' => $user->id,
'server_id' => $server->id,
'daemonSecret' => (string) $uuid->generate('servers', 'uuid'),
]);
$perms = Permission::listPermissions(true);
$daemonPermissions = $this->coreDaemonPermissions;
foreach ($data['permissions'] as $permission) {
if (array_key_exists($permission, $perms)) {
// Build the daemon permissions array for sending.
if (! is_null($perms[$permission])) {
array_push($daemonPermissions, $perms[$permission]);
}
Permission::create([
'subuser_id' => $subuser->id,
'permission' => $permission,
]);
}
}
// Contact Daemon
// We contact even if they don't have any daemon permissions to overwrite
// if they did have them previously.
$server->node->guzzleClient([
'X-Access-Server' => $server->uuid,
'X-Access-Token' => $server->node->daemonSecret,
])->request('PATCH', '/server', [
'json' => [
'keys' => [
$subuser->daemonSecret => $daemonPermissions,
],
],
]);
DB::commit();
return $subuser;
} catch (TransferException $ex) {
DB::rollBack();
throw new DisplayException('There was an error attempting to connect to the daemon to add this user.', $ex);
} catch (\Exception $ex) {
DB::rollBack();
throw $ex;
}
return false;
}
/**
* Revokes a users permissions on a server.
*
* @param int $id
*
* @throws \Pterodactyl\Exceptions\DisplayException
*/
public function delete($id)
{
$subuser = Subuser::with('server.node')->findOrFail($id);
$server = $subuser->server;
DB::beginTransaction();
try {
$server->node->guzzleClient([
'X-Access-Server' => $server->uuid,
'X-Access-Token' => $server->node->daemonSecret,
])->request('PATCH', '/server', [
'json' => [
'keys' => [
$subuser->daemonSecret => [],
],
],
]);
foreach ($subuser->permissions as &$permission) {
$permission->delete();
}
$subuser->delete();
DB::commit();
} catch (TransferException $ex) {
DB::rollBack();
throw new DisplayException('There was an error attempting to connect to the daemon to delete this subuser.', $ex);
} catch (\Exception $ex) {
DB::rollBack();
throw $ex;
}
}
/**
* Updates permissions for a given subuser.
*
* @param int $id
* @param array $data
*
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \Pterodactyl\Exceptions\DisplayValidationException
*/
public function update($id, array $data)
{
$validator = Validator::make($data, [
'permissions' => 'required|array',
'user' => 'required|exists:users,id',
'server' => 'required|exists:servers,id',
]);
if ($validator->fails()) {
throw new DisplayValidationException(json_encode($validator->all()));
}
$subuser = Subuser::with('server.node')->findOrFail($id);
$server = $subuser->server;
DB::beginTransaction();
try {
foreach ($subuser->permissions as &$permission) {
$permission->delete();
}
$perms = Permission::listPermissions(true);
$daemonPermissions = $this->coreDaemonPermissions;
foreach ($data['permissions'] as $permission) {
if (array_key_exists($permission, $perms)) {
// Build the daemon permissions array for sending.
if (! is_null($perms[$permission])) {
array_push($daemonPermissions, $perms[$permission]);
}
Permission::create([
'subuser_id' => $subuser->id,
'permission' => $permission,
]);
}
}
// Contact Daemon
// We contact even if they don't have any daemon permissions to overwrite
// if they did have them previously.
$server->node->guzzleClient([
'X-Access-Server' => $server->uuid,
'X-Access-Token' => $server->node->daemonSecret,
])->request('PATCH', '/server', [
'json' => [
'keys' => [
$subuser->daemonSecret => $daemonPermissions,
],
],
]);
DB::commit();
} catch (TransferException $ex) {
DB::rollBack();
throw new DisplayException('There was an error attempting to connect to the daemon to update permissions.', $ex);
} catch (\Exception $ex) {
DB::rollBack();
throw $ex;
}
}
}

View file

@ -1,90 +0,0 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Pterodactyl\Repositories\old_Daemon;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Server;
use GuzzleHttp\Exception\ConnectException;
use Pterodactyl\Exceptions\DisplayException;
class CommandRepository
{
/**
* The Eloquent Model associated with the requested server.
*
* @var \Pterodactyl\Models\Server
*/
protected $server;
/**
* The Eloquent Model associated with the user to run the request as.
*
* @var \Pterodactyl\Models\User|null
*/
protected $user;
/**
* Constuctor for repository.
*
* @param \Pterodactyl\Models\Server $server
* @param \Pterodactyl\Models\User|null $user
*/
public function __construct(Server $server, User $user = null)
{
$this->server = $server;
$this->user = $user;
}
/**
* Sends a command to the daemon.
*
* @param string $command
* @return string
*
* @throws \Pterodactyl\Exceptions\DisplayException
* @throws \GuzzleHttp\Exception\RequestException
*/
public function send($command)
{
// We don't use the user's specific daemon secret here since we
// are assuming that a call to this function has been validated.
try {
$response = $this->server->guzzleClient($this->user)->request('POST', '/server/command', [
'http_errors' => false,
'json' => [
'command' => $command,
],
]);
if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) {
throw new DisplayException('Command sending responded with a non-200 error code (HTTP/' . $response->getStatusCode() . ').');
}
return $response->getBody();
} catch (ConnectException $ex) {
throw $ex;
}
}
}

View file

@ -1,192 +0,0 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Pterodactyl\Repositories\old_Daemon;
use Exception;
use GuzzleHttp\Client;
use Pterodactyl\Models\Server;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Repositories\HelperRepository;
class FileRepository
{
/**
* The Eloquent Model associated with the requested server.
*
* @var \Pterodactyl\Models\Server
*/
protected $server;
/**
* Constructor.
*
* @param string $uuid
*/
public function __construct($uuid)
{
$this->server = Server::byUuid($uuid);
}
/**
* Get the contents of a requested file for the server.
*
* @param string $file
* @return array
*
* @throws \GuzzleHttp\Exception\RequestException
* @throws \Pterodactyl\Exceptions\DisplayException
*/
public function returnFileContents($file)
{
if (empty($file)) {
throw new Exception('Not all parameters were properly passed to the function.');
}
$file = (object) pathinfo($file);
$file->dirname = (in_array($file->dirname, ['.', './', '/'])) ? null : trim($file->dirname, '/') . '/';
$res = $this->server->guzzleClient()->request('GET', '/server/file/stat/' . rawurlencode($file->dirname . $file->basename));
$stat = json_decode($res->getBody());
if ($res->getStatusCode() !== 200 || ! isset($stat->size)) {
throw new DisplayException('The daemon provided a non-200 error code on stat lookup: HTTP\\' . $res->getStatusCode());
}
if (! in_array($stat->mime, HelperRepository::editableFiles())) {
throw new DisplayException('You cannot edit that type of file (' . $stat->mime . ') through the panel.');
}
if ($stat->size > 5000000) {
throw new DisplayException('That file is too large to open in the browser, consider using a SFTP client.');
}
$res = $this->server->guzzleClient()->request('GET', '/server/file/f/' . rawurlencode($file->dirname . $file->basename));
$json = json_decode($res->getBody());
if ($res->getStatusCode() !== 200 || ! isset($json->content)) {
throw new DisplayException('The daemon provided a non-200 error code: HTTP\\' . $res->getStatusCode());
}
return [
'file' => $json,
'stat' => $stat,
];
}
/**
* Save the contents of a requested file on the daemon.
*
* @param string $file
* @param string $content
* @return bool
*
* @throws \GuzzleHttp\Exception\RequestException
* @throws \Pterodactyl\Exceptions\DisplayException
*/
public function saveFileContents($file, $content)
{
if (empty($file)) {
throw new Exception('A valid file and path must be specified to save a file.');
}
$file = (object) pathinfo($file);
$file->dirname = (in_array($file->dirname, ['.', './', '/'])) ? null : trim($file->dirname, '/') . '/';
$res = $this->server->guzzleClient()->request('POST', '/server/file/save', [
'json' => [
'path' => rawurlencode($file->dirname . $file->basename),
'content' => $content,
],
]);
if ($res->getStatusCode() !== 204) {
throw new DisplayException('An error occured while attempting to save this file. ' . $res->getBody());
}
return true;
}
/**
* Returns a listing of all files and folders within a specified directory on the daemon.
*
* @param string $directory
* @return object
*
* @throws \GuzzleHttp\Exception\RequestException
* @throws \Pterodactyl\Exceptions\DisplayException
*/
public function returnDirectoryListing($directory)
{
if (empty($directory)) {
throw new Exception('A valid directory must be specified in order to list its contents.');
}
try {
$res = $this->server->guzzleClient()->request('GET', '/server/directory/' . rawurlencode($directory));
} catch (\GuzzleHttp\Exception\ClientException $ex) {
$json = json_decode($ex->getResponse()->getBody());
throw new DisplayException($json->error);
} catch (\GuzzleHttp\Exception\ServerException $ex) {
throw new DisplayException('A remote server error was encountered while attempting to display this directory.');
} catch (\GuzzleHttp\Exception\ConnectException $ex) {
throw new DisplayException('A ConnectException was encountered: unable to contact daemon.');
} catch (\Exception $ex) {
throw $ex;
}
$json = json_decode($res->getBody());
// Iterate through results
$files = [];
$folders = [];
foreach ($json as &$value) {
if ($value->directory) {
// @TODO Handle Symlinks
$folders[] = [
'entry' => $value->name,
'directory' => trim($directory, '/'),
'size' => null,
'date' => strtotime($value->modified),
'mime' => $value->mime,
];
} elseif ($value->file) {
$files[] = [
'entry' => $value->name,
'directory' => trim($directory, '/'),
'extension' => pathinfo($value->name, PATHINFO_EXTENSION),
'size' => HelperRepository::bytesToHuman($value->size),
'date' => strtotime($value->modified),
'mime' => $value->mime,
];
}
}
return (object) [
'files' => $files,
'folders' => $folders,
];
}
}

View file

@ -1,120 +0,0 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Pterodactyl\Repositories\old_Daemon;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Server;
use GuzzleHttp\Exception\ConnectException;
use Pterodactyl\Exceptions\DisplayException;
class PowerRepository
{
/**
* The Eloquent Model associated with the requested server.
*
* @var \Pterodactyl\Models\Server
*/
protected $server;
/**
* The Eloquent Model associated with the user to run the request as.
*
* @var \Pterodactyl\Models\User|null
*/
protected $user;
/**
* Constuctor for repository.
*
* @param \Pterodactyl\Models\Server $server
* @param \Pterodactyl\Models\User|null $user
*/
public function __construct(Server $server, User $user = null)
{
$this->server = $server;
$this->user = $user;
}
/**
* Sends a power option to the daemon.
*
* @param string $action
* @return string
*
* @throws \GuzzleHttp\Exception\RequestException
* @throws \Pterodactyl\Exceptions\DisplayException
*/
public function do($action)
{
try {
$response = $this->server->guzzleClient($this->user)->request('PUT', '/server/power', [
'http_errors' => false,
'json' => [
'action' => $action,
],
]);
if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) {
throw new DisplayException('Power toggle endpoint responded with a non-200 error code (HTTP/' . $response->getStatusCode() . ').');
}
return $response->getBody();
} catch (ConnectException $ex) {
throw $ex;
}
}
/**
* Starts a server.
*/
public function start()
{
$this->do('start');
}
/**
* Stops a server.
*/
public function stop()
{
$this->do('stop');
}
/**
* Restarts a server.
*/
public function restart()
{
$this->do('restart');
}
/**
* Kills a server.
*/
public function kill()
{
$this->do('kill');
}
}