102 lines
3.1 KiB
PHP
102 lines
3.1 KiB
PHP
<?php
|
|
namespace Seria\Torrents;
|
|
|
|
use Exception;
|
|
use RuntimeException;
|
|
use Index\Data\IDbTransactions;
|
|
use Index\Http\Routing\{HttpGet,HttpMiddleware,HttpPost,RouteHandler};
|
|
use Index\Security\CSRFP;
|
|
use Sasae\SasaeEnvironment;
|
|
use Seria\Auth\AuthInfo;
|
|
use Seria\Users\UsersContext;
|
|
|
|
class TorrentCreateRouting extends RouteHandler {
|
|
public function __construct(
|
|
private IDbTransactions $dbConn,
|
|
private AuthInfo $authInfo,
|
|
private TorrentsContext $torrentsCtx,
|
|
private CSRFP $csrfp,
|
|
private ?SasaeEnvironment $templating
|
|
) {}
|
|
|
|
#[HttpMiddleware('/create')]
|
|
public function checkAccess() {
|
|
if(!$this->authInfo->isLoggedIn())
|
|
return 403;
|
|
if(!$this->authInfo->getUserInfo()->canCreateTorrents())
|
|
return 403;
|
|
}
|
|
|
|
#[HttpGet('/create')]
|
|
public function getCreate($response, $request) {
|
|
$template = $this->templating->load('create');
|
|
|
|
if($request->hasParam('error'))
|
|
$template->setVar('error', match((string)$request->getParam('error')) {
|
|
'file' => 'No file supplied.',
|
|
'verify' => 'Request verification failed.',
|
|
'size' => 'File is too large.',
|
|
'format' => 'Supplied file is not a valid .torrent file.',
|
|
default => 'An unknown error occurred.',
|
|
});
|
|
|
|
return $template;
|
|
}
|
|
|
|
#[HttpPost('/create')]
|
|
public function postCreate($response, $request) {
|
|
if(!$request->isFormContent())
|
|
return 400;
|
|
|
|
$content = $request->getContent();
|
|
if(!$content->hasUploadedFile('torrent')) {
|
|
$response->redirect('/create?error=file');
|
|
return;
|
|
}
|
|
|
|
if(!$this->csrfp->verifyToken((string)$content->getParam('_csrfp'))) {
|
|
$response->redirect('/create?error=verify');
|
|
return;
|
|
}
|
|
|
|
$torrent = $content->getUploadedFile('torrent');
|
|
|
|
$error = $torrent->getErrorCode();
|
|
if($error !== UPLOAD_ERR_OK) {
|
|
$response->redirect('/create?error=' . match($error) {
|
|
UPLOAD_ERR_NO_FILE => 'file',
|
|
UPLOAD_ERR_INI_SIZE => 'size',
|
|
UPLOAD_ERR_FORM_SIZE => 'size',
|
|
default => 'error',
|
|
});
|
|
return;
|
|
}
|
|
|
|
$path = $torrent->getLocalFileName();
|
|
if($path === null || !is_file($path)) {
|
|
$response->redirect('/create?error=file');
|
|
return;
|
|
}
|
|
|
|
$file = fopen($path, 'rb');
|
|
try {
|
|
$torrentBuilder = TorrentBuilder::decode($file);
|
|
$torrentBuilder->setUser($this->authInfo->getUserInfo());
|
|
$torrentId = $torrentBuilder->create($this->dbConn, $this->torrentsCtx);
|
|
} catch(Exception $ex) {
|
|
$response->redirect('/create?error=format');
|
|
return;
|
|
} finally {
|
|
if(is_resource($file))
|
|
fclose($file);
|
|
}
|
|
|
|
$response->redirect(sprintf('/info/%s', $torrentId));
|
|
}
|
|
|
|
#[HttpGet('/create.php')]
|
|
public function getCreatePHP($response, $request) {
|
|
$response->redirect('/create', true);
|
|
}
|
|
}
|