seria/src/Users/ProfileRoutes.php
2024-03-30 00:38:44 +00:00

94 lines
2.9 KiB
PHP

<?php
namespace Seria\Users;
use RuntimeException;
use Index\Http\Routing\{HttpGet,RouteHandler};
use Sasae\SasaeEnvironment;
use Seria\Auth\AuthInfo;
use Seria\Torrents\{TorrentsContext,TorrentInfo,TorrentPeerInfo};
class ProfileRoutes extends RouteHandler {
public function __construct(
private AuthInfo $authInfo,
private TorrentsContext $torrentsCtx,
private UsersContext $usersCtx,
private ?SasaeEnvironment $templating
) {}
#[HttpGet('/profile/([a-zA-Z0-9\-_]+)')]
public function getProfile($response, $request, string $name) {
if(!$this->authInfo->isLoggedIn())
return 403;
$users = $this->usersCtx->getUsers();
$torrents = $this->torrentsCtx->getTorrents();
$peers = $this->torrentsCtx->getPeers();
try {
$userInfo = $users->getUser($name, 'name');
} catch(RuntimeException $ex) {
return 404;
}
$submissions = [];
$torrentInfos = $torrents->getTorrents(approved: true, userInfo: $userInfo, take: 3);
foreach($torrentInfos as $torrentInfo) {
$submissions[] = [
'info' => $torrentInfo,
'complete_peers' => $peers->countCompletePeers($torrentInfo),
'incomplete_peers' => $peers->countIncompletePeers($torrentInfo),
];
}
$uploading = $peers->countUserUploading($userInfo);
$downloading = $peers->countUserDownloading($userInfo);
return $this->templating->render('profile', [
'profile_user' => $userInfo,
'profile_submissions' => $submissions,
'profile_uploading' => $uploading,
'profile_downloading' => $downloading,
]);
}
#[HttpGet('/profile/([a-zA-Z0-9\-_]+)/history')]
public function getHistory($response, $request, string $name) {
if(!$this->authInfo->isLoggedIn())
return 403;
$users = $this->usersCtx->getUsers();
try {
$userInfo = $users->getUser($name, 'name');
} catch(RuntimeException $ex) {
return 404;
}
return $this->templating->render('history', [
'history_user_info' => $userInfo,
]);
}
#[HttpGet('/profile.php')]
public function getProfilePHP($response, $request): void {
$response->redirect(sprintf('/profile/%s', (string)$request->getParam('name')), true);
}
#[HttpGet('/history.php')]
public function getHistoryPHP($response, $request) {
$userName = (string)$request->getParam('name');
if($userName === '' && $this->authInfo->isLoggedIn())
$userName = $this->authInfo->getUserName();
if($userName === '')
return 404;
$url = sprintf('/profile/%s/history', $userName);
$filter = (string)$request->getParam('filter');
if($filter !== '')
$url .= '?filter=' . $filter;
$response->redirect($url, true);
}
}