Route registration with attributes!

This commit is contained in:
flash 2023-09-08 00:13:30 +00:00
parent 506d32d210
commit c5a284f360
9 changed files with 177 additions and 202 deletions

4
composer.lock generated
View file

@ -348,7 +348,7 @@
"source": { "source": {
"type": "git", "type": "git",
"url": "https://git.flash.moe/flash/index.git", "url": "https://git.flash.moe/flash/index.git",
"reference": "2b8b31289d2f4b27c1bc8355348e529cb2177ebc" "reference": "923484c7accc1b6c3c829c791944c1611aec3834"
}, },
"require": { "require": {
"ext-mbstring": "*", "ext-mbstring": "*",
@ -386,7 +386,7 @@
], ],
"description": "Composer package for the common library for my projects.", "description": "Composer package for the common library for my projects.",
"homepage": "https://railgun.sh/index", "homepage": "https://railgun.sh/index",
"time": "2023-09-06T11:49:54+00:00" "time": "2023-09-08T00:09:23+00:00"
}, },
{ {
"name": "flashwave/sasae", "name": "flashwave/sasae",

View file

@ -3,8 +3,8 @@ namespace Misuzu\Changelog;
use ErrorException; use ErrorException;
use RuntimeException; use RuntimeException;
use Index\Routing\IRouter; use Index\Routing\Route;
use Index\Routing\IRouteHandler; use Index\Routing\RouteHandler;
use Misuzu\Pagination; use Misuzu\Pagination;
use Misuzu\Template; use Misuzu\Template;
use Misuzu\Auth\AuthInfo; use Misuzu\Auth\AuthInfo;
@ -17,7 +17,7 @@ use Misuzu\Feeds\AtomFeedSerializer;
use Misuzu\Feeds\RssFeedSerializer; use Misuzu\Feeds\RssFeedSerializer;
use Misuzu\Users\UsersContext; use Misuzu\Users\UsersContext;
final class ChangelogRoutes implements IRouteHandler { final class ChangelogRoutes extends RouteHandler {
public function __construct( public function __construct(
private IConfig $config, private IConfig $config,
private Changelog $changelog, private Changelog $changelog,
@ -26,31 +26,12 @@ final class ChangelogRoutes implements IRouteHandler {
private Comments $comments private Comments $comments
) {} ) {}
public function registerRoutes(IRouter $router): void {
$router->get('/changelog', $this->getIndex(...));
$router->get('/changelog.rss', $this->getFeedRSS(...));
$router->get('/changelog.atom', $this->getFeedAtom(...));
$router->get('/changelog/change/:id', $this->getChange(...));
$router->get('/changelog.php', function($response, $request) {
$changeId = $request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
if($changeId) {
$response->redirect(url('changelog-change', ['change' => $changeId]), true);
return;
}
$response->redirect(url('changelog-index', [
'date' => $request->getParam('d'),
'user' => $request->getParam('u', FILTER_SANITIZE_NUMBER_INT),
]), true);
});
}
private function getCommentsInfo(string $categoryName): object { private function getCommentsInfo(string $categoryName): object {
$comments = new CommentsEx($this->authInfo, $this->comments, $this->usersCtx); $comments = new CommentsEx($this->authInfo, $this->comments, $this->usersCtx);
return $comments->getCommentsForLayout($categoryName); return $comments->getCommentsForLayout($categoryName);
} }
#[Route('GET', '/changelog')]
public function getIndex($response, $request) { public function getIndex($response, $request) {
$filterDate = (string)$request->getParam('date'); $filterDate = (string)$request->getParam('date');
$filterUser = (string)$request->getParam('user', FILTER_SANITIZE_NUMBER_INT); $filterUser = (string)$request->getParam('user', FILTER_SANITIZE_NUMBER_INT);
@ -114,6 +95,7 @@ final class ChangelogRoutes implements IRouteHandler {
]); ]);
} }
#[Route('GET', '/changelog/change/:id')]
public function getChange($response, $request, string $changeId) { public function getChange($response, $request, string $changeId) {
try { try {
$changeInfo = $this->changelog->getChange($changeId); $changeInfo = $this->changelog->getChange($changeId);
@ -160,13 +142,29 @@ final class ChangelogRoutes implements IRouteHandler {
return $feed; return $feed;
} }
#[Route('GET', '/changelog.rss')]
public function getFeedRSS($response) { public function getFeedRSS($response) {
$response->setContentType('application/rss+xml; charset=utf-8'); $response->setContentType('application/rss+xml; charset=utf-8');
return (new RssFeedSerializer)->serializeFeed($this->createFeed('rss')); return (new RssFeedSerializer)->serializeFeed($this->createFeed('rss'));
} }
#[Route('GET', '/changelog.atom')]
public function getFeedAtom($response) { public function getFeedAtom($response) {
$response->setContentType('application/atom+xml; charset=utf-8'); $response->setContentType('application/atom+xml; charset=utf-8');
return (new AtomFeedSerializer)->serializeFeed($this->createFeed('atom')); return (new AtomFeedSerializer)->serializeFeed($this->createFeed('atom'));
} }
#[Route('GET', '/changelog.php')]
public static function getChangelogPHP($response, $request) {
$changeId = $request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
if($changeId) {
$response->redirect(url('changelog-change', ['change' => $changeId]), true);
return;
}
$response->redirect(url('changelog-index', [
'date' => $request->getParam('d'),
'user' => $request->getParam('u', FILTER_SANITIZE_NUMBER_INT),
]), true);
}
} }

View file

@ -5,8 +5,8 @@ use RuntimeException;
use Index\DateTime; use Index\DateTime;
use Index\Data\DbTools; use Index\Data\DbTools;
use Index\Data\IDbConnection; use Index\Data\IDbConnection;
use Index\Routing\IRouter; use Index\Routing\Route;
use Index\Routing\IRouteHandler; use Index\Routing\RouteHandler;
use Misuzu\Pagination; use Misuzu\Pagination;
use Misuzu\Template; use Misuzu\Template;
use Misuzu\Auth\AuthInfo; use Misuzu\Auth\AuthInfo;
@ -17,7 +17,7 @@ use Misuzu\Counters\Counters;
use Misuzu\News\News; use Misuzu\News\News;
use Misuzu\Users\UsersContext; use Misuzu\Users\UsersContext;
class HomeRoutes implements IRouteHandler { class HomeRoutes extends RouteHandler {
public function __construct( public function __construct(
private IConfig $config, private IConfig $config,
private IDbConnection $dbConn, private IDbConnection $dbConn,
@ -29,17 +29,6 @@ class HomeRoutes implements IRouteHandler {
private UsersContext $usersCtx private UsersContext $usersCtx
) {} ) {}
public function registerRoutes(IRouter $router): void {
$router->get('/', $this->getIndex(...));
if(MSZ_DEBUG)
$router->get('/dev-landing', $this->getLanding(...));
$router->get('/index.php', function($response) {
$response->redirect(url('index'), true);
});
}
private function getStats(): array { private function getStats(): array {
return $this->counters->get([ return $this->counters->get([
'users:active', 'users:active',
@ -162,6 +151,7 @@ class HomeRoutes implements IRouteHandler {
return $topics; return $topics;
} }
#[Route('GET', '/')]
public function getIndex(...$args) { public function getIndex(...$args) {
return $this->authInfo->isLoggedIn() return $this->authInfo->isLoggedIn()
? $this->getHome(...$args) ? $this->getHome(...$args)
@ -207,7 +197,8 @@ class HomeRoutes implements IRouteHandler {
]); ]);
} }
public function getLanding() { #[Route('GET', '/_landing')]
public function getLanding($response, $request) {
$config = $this->config->getValues([ $config = $this->config->getValues([
['social.embed_linked:b'], ['social.embed_linked:b'],
['landing.forum_categories:a'], ['landing.forum_categories:a'],
@ -245,4 +236,9 @@ class HomeRoutes implements IRouteHandler {
'forum_active' => $activeTopics, 'forum_active' => $activeTopics,
]); ]);
} }
#[Route('GET', '/index.php')]
public static function getIndexPHP($response) {
$response->redirect(url('index'), true);
}
} }

View file

@ -1,12 +1,12 @@
<?php <?php
namespace Misuzu\Info; namespace Misuzu\Info;
use Index\Routing\IRouter; use Index\Routing\Route;
use Index\Routing\IRouteHandler; use Index\Routing\RouteHandler;
use Misuzu\Template; use Misuzu\Template;
use Misuzu\Parsers\Parser; use Misuzu\Parsers\Parser;
class InfoRoutes implements IRouteHandler { class InfoRoutes extends RouteHandler {
private const DOCS_PATH = MSZ_ROOT . '/docs'; private const DOCS_PATH = MSZ_ROOT . '/docs';
private const PROJECT_PATHS = [ private const PROJECT_PATHS = [
'misuzu' => MSZ_ROOT, 'misuzu' => MSZ_ROOT,
@ -17,30 +17,16 @@ class InfoRoutes implements IRouteHandler {
'index' => 'Index Project » %s', 'index' => 'Index Project » %s',
]; ];
public function registerRoutes(IRouter $router): void {
$router->get('/info', $this->getIndex(...));
$router->get('/info/:name', $this->getDocsPage(...));
$router->get('/info/:project/:name', $this->getProjectPage(...));
$router->get('/info.php', function($response) {
$response->redirect(url('info'), true);
});
$router->get('/info.php/:name', function($response, $request, string $name) {
$response->redirect(url('info', ['title' => $name]), true);
});
$router->get('/info.php/:project/:name', function($response, $request, string $project, string $name) {
$response->redirect(url('info', ['title' => $project . '/' . $name]), true);
});
}
private static function checkName(string $name): bool { private static function checkName(string $name): bool {
return preg_match('#^([A-Za-z0-9_]+)$#', $name) === 1; return preg_match('#^([A-Za-z0-9_]+)$#', $name) === 1;
} }
#[Route('GET', '/info')]
public function getIndex() { public function getIndex() {
return Template::renderRaw('info.index'); return Template::renderRaw('info.index');
} }
#[Route('GET', '/info/:name')]
public function getDocsPage($response, $request, string $name) { public function getDocsPage($response, $request, string $name) {
if(!self::checkName($name)) if(!self::checkName($name))
return 404; return 404;
@ -50,6 +36,7 @@ class InfoRoutes implements IRouteHandler {
); );
} }
#[Route('GET', '/info/:project/:name')]
public function getProjectPage($response, $request, string $project, string $name) { public function getProjectPage($response, $request, string $project, string $name) {
if(!array_key_exists($project, self::PROJECT_PATHS)) if(!array_key_exists($project, self::PROJECT_PATHS))
return 404; return 404;
@ -120,4 +107,19 @@ class InfoRoutes implements IRouteHandler {
], ],
]); ]);
} }
#[Route('GET', '/info.php')]
public static function getInfoPHP($response) {
$response->redirect(url('info'), true);
}
#[Route('GET', '/info.php/:name')]
public static function getInfoDocsPHP($response, $request, string $name) {
$response->redirect(url('info', ['title' => $name]), true);
}
#[Route('GET', '/info.php/:project/:name')]
public static function getInfoProjectPHP($response, $request, string $project, string $name) {
$response->redirect(url('info', ['title' => $project . '/' . $name]), true);
}
} }

View file

@ -5,8 +5,8 @@ use RuntimeException;
use Index\DateTime; use Index\DateTime;
use Index\Data\DbTools; use Index\Data\DbTools;
use Index\Data\IDbConnection; use Index\Data\IDbConnection;
use Index\Routing\IRouter; use Index\Routing\Route;
use Index\Routing\IRouteHandler; use Index\Routing\RouteHandler;
use Misuzu\Pagination; use Misuzu\Pagination;
use Misuzu\Template; use Misuzu\Template;
use Misuzu\Auth\AuthInfo; use Misuzu\Auth\AuthInfo;
@ -23,7 +23,7 @@ use Misuzu\News\NewsCategoryInfo;
use Misuzu\Users\UsersContext; use Misuzu\Users\UsersContext;
use Misuzu\Parsers\Parser; use Misuzu\Parsers\Parser;
class NewsRoutes implements IRouteHandler { class NewsRoutes extends RouteHandler {
public function __construct( public function __construct(
private IConfig $config, private IConfig $config,
private AuthInfo $authInfo, private AuthInfo $authInfo,
@ -32,76 +32,6 @@ class NewsRoutes implements IRouteHandler {
private Comments $comments private Comments $comments
) {} ) {}
public function registerRoutes(IRouter $router): void {
$router->get('/news', $this->getIndex(...));
$router->get('/news.rss', $this->getFeedRss(...));
$router->get('/news.atom', $this->getFeedAtom(...));
$router->get('/news/:category', $this->getCategory(...));
$router->get('/news/post/:id', $this->getPost(...));
$router->get('/news.php', function($response, $request) {
$postId = $request->getParam('n', FILTER_SANITIZE_NUMBER_INT)
?? $request->getParam('p', FILTER_SANITIZE_NUMBER_INT);
if($postId > 0)
$location = url('news-post', ['post' => $postId]);
else {
$catId = $request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$pageId = $request->getParam('page', FILTER_SANITIZE_NUMBER_INT);
$location = url($catId > 0 ? 'news-category' : 'news-index', ['category' => $catId, 'page' => $pageId]);
}
$response->redirect($location, true);
});
$router->get('/news.php/rss', function($response, $request) {
$catId = $request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$location = url($catId > 0 ? 'news-category-feed-rss' : 'news-feed-rss', ['category' => $catId]);
$response->redirect($location, true);
});
$router->get('/news.php/atom', function($response, $request) {
$catId = $request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$location = url($catId > 0 ? 'news-category-feed-atom' : 'news-feed-atom', ['category' => $catId]);
$response->redirect($location, true);
});
$router->get('/news/index.php', function($response, $request) {
$response->redirect(url('news-index', [
'page' => $request->getParam('page', FILTER_SANITIZE_NUMBER_INT),
]), true);
});
$router->get('/news/category.php', function($response, $request) {
$response->redirect(url('news-category', [
'category' => $request->getParam('c', FILTER_SANITIZE_NUMBER_INT),
'page' => $request->getParam('p', FILTER_SANITIZE_NUMBER_INT),
]), true);
});
$router->get('/news/post.php', function($response, $request) {
$response->redirect(url('news-post', [
'post' => $request->getParam('p', FILTER_SANITIZE_NUMBER_INT),
]), true);
});
$router->get('/news/feed.php/rss', function($response, $request) {
$catId = (int)$request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$response->redirect(url(
$catId > 0 ? 'news-category-feed-rss' : 'news-feed-rss',
['category' => $catId]
), true);
});
$router->get('/news/feed.php/atom', function($response, $request) {
$catId = (int)$request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$response->redirect(url(
$catId > 0 ? 'news-category-feed-atom' : 'news-feed-atom',
['category' => $catId]
), true);
});
}
private array $categoryInfos = []; private array $categoryInfos = [];
private function getNewsPostsForView(Pagination $pagination, ?NewsCategoryInfo $categoryInfo = null): array { private function getNewsPostsForView(Pagination $pagination, ?NewsCategoryInfo $categoryInfo = null): array {
@ -160,6 +90,7 @@ class NewsRoutes implements IRouteHandler {
return $posts; return $posts;
} }
#[Route('GET', '/news')]
public function getIndex() { public function getIndex() {
$categories = $this->news->getCategories(hidden: false); $categories = $this->news->getCategories(hidden: false);
@ -176,14 +107,17 @@ class NewsRoutes implements IRouteHandler {
]); ]);
} }
#[Route('GET', '/news.rss')]
public function getFeedRss($response) { public function getFeedRss($response) {
return $this->getFeed($response, 'rss'); return $this->getFeed($response, 'rss');
} }
#[Route('GET', '/news.atom')]
public function getFeedAtom($response) { public function getFeedAtom($response) {
return $this->getFeed($response, 'atom'); return $this->getFeed($response, 'atom');
} }
#[Route('GET', '/news/:category')]
public function getCategory($response, $request, string $fileName) { public function getCategory($response, $request, string $fileName) {
$categoryId = pathinfo($fileName, PATHINFO_FILENAME); $categoryId = pathinfo($fileName, PATHINFO_FILENAME);
$type = pathinfo($fileName, PATHINFO_EXTENSION); $type = pathinfo($fileName, PATHINFO_EXTENSION);
@ -222,6 +156,7 @@ class NewsRoutes implements IRouteHandler {
return $this->getFeed($response, 'atom', $categoryInfo); return $this->getFeed($response, 'atom', $categoryInfo);
} }
#[Route('GET', '/news/post/:id')]
public function getPost($response, $request, string $postId) { public function getPost($response, $request, string $postId) {
try { try {
$postInfo = $this->news->getPost($postId); $postInfo = $this->news->getPost($postId);
@ -308,4 +243,74 @@ class NewsRoutes implements IRouteHandler {
return $serialiser->serializeFeed($feed); return $serialiser->serializeFeed($feed);
} }
#[Route('GET', '/news.php')]
public static function getNewsPHP($response, $request) {
$postId = $request->getParam('n', FILTER_SANITIZE_NUMBER_INT)
?? $request->getParam('p', FILTER_SANITIZE_NUMBER_INT);
if($postId > 0)
$location = url('news-post', ['post' => $postId]);
else {
$catId = $request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$pageId = $request->getParam('page', FILTER_SANITIZE_NUMBER_INT);
$location = url($catId > 0 ? 'news-category' : 'news-index', ['category' => $catId, 'page' => $pageId]);
}
$response->redirect($location, true);
}
#[Route('GET', '/news.php/rss')]
public static function getNewsRssPHP($response, $request) {
$catId = $request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$location = url($catId > 0 ? 'news-category-feed-rss' : 'news-feed-rss', ['category' => $catId]);
$response->redirect($location, true);
}
#[Route('GET', '/news.php/atom')]
public static function getNewsAtomPHP($response, $request) {
$catId = $request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$location = url($catId > 0 ? 'news-category-feed-atom' : 'news-feed-atom', ['category' => $catId]);
$response->redirect($location, true);
}
#[Route('GET', '/news/index.php')]
public static function getNewsIndexPHP($response, $request) {
$response->redirect(url('news-index', [
'page' => $request->getParam('page', FILTER_SANITIZE_NUMBER_INT),
]), true);
}
#[Route('GET', '/news/category.php')]
public static function getNewsCategoryPHP($response, $request) {
$response->redirect(url('news-category', [
'category' => $request->getParam('c', FILTER_SANITIZE_NUMBER_INT),
'page' => $request->getParam('p', FILTER_SANITIZE_NUMBER_INT),
]), true);
}
#[Route('GET', '/news/post.php')]
public static function getNewsPostPHP($response, $request) {
$response->redirect(url('news-post', [
'post' => $request->getParam('p', FILTER_SANITIZE_NUMBER_INT),
]), true);
}
#[Route('GET', '/news/feed.php/rss')]
public static function getNewsFeedRssPHP($response, $request) {
$catId = (int)$request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$response->redirect(url(
$catId > 0 ? 'news-category-feed-rss' : 'news-feed-rss',
['category' => $catId]
), true);
}
#[Route('GET', '/news/feed.php/atom')]
public static function getNewsFeedAtomPHP($response, $request) {
$catId = (int)$request->getParam('c', FILTER_SANITIZE_NUMBER_INT);
$response->redirect(url(
$catId > 0 ? 'news-category-feed-atom' : 'news-feed-atom',
['category' => $catId]
), true);
}
} }

View file

@ -3,10 +3,11 @@ namespace Misuzu\Satori;
use RuntimeException; use RuntimeException;
use Index\Colour\Colour; use Index\Colour\Colour;
use Index\Http\HttpFx;
use Index\Routing\IRouter; use Index\Routing\IRouter;
use Index\Routing\IRouteHandler; use Index\Routing\IRouteHandler;
use Index\Routing\Route;
use Misuzu\Pagination; use Misuzu\Pagination;
use Misuzu\Tools;
use Misuzu\Config\IConfig; use Misuzu\Config\IConfig;
use Misuzu\Forum\Forum; use Misuzu\Forum\Forum;
use Misuzu\Profile\ProfileFields; use Misuzu\Profile\ProfileFields;
@ -21,32 +22,11 @@ final class SatoriRoutes implements IRouteHandler {
) {} ) {}
public function registerRoutes(IRouter $router): void { public function registerRoutes(IRouter $router): void {
// Simplify default error pages Tools::simplifyErrorPages($router, '/_satori');
if($router instanceof HttpFx) Route::handleAttributes($router, $this);
$router->use('/_satori', function() use($router) {
$router->addErrorHandler(400, function($response) {
$response->setContent('HTTP 400');
});
$router->addErrorHandler(403, function($response) {
$response->setContent('HTTP 403');
});
$router->addErrorHandler(404, function($response) {
$response->setContent('HTTP 404');
});
$router->addErrorHandler(500, function($response) {
$response->setContent('HTTP 500');
});
$router->addErrorHandler(503, function($response) {
$response->setContent('HTTP 503');
});
});
$router->use('/_satori', $this->verifyRequest(...));
$router->get('/_satori/get-profile-field', $this->getProfileField(...));
$router->get('/_satori/get-recent-forum-posts', $this->getRecentForumPosts(...));
$router->get('/_satori/get-recent-registrations', $this->getRecentRegistrations(...));
} }
#[Route('/_satori')]
public function verifyRequest($response, $request) { public function verifyRequest($response, $request) {
$secretKey = $this->config->getString('secret'); $secretKey = $this->config->getString('secret');
@ -66,6 +46,7 @@ final class SatoriRoutes implements IRouteHandler {
} }
} }
#[Route('GET', '/_satori/get-profile-field')]
public function getProfileField($response, $request): array { public function getProfileField($response, $request): array {
$userId = (string)$request->getParam('user', FILTER_SANITIZE_NUMBER_INT); $userId = (string)$request->getParam('user', FILTER_SANITIZE_NUMBER_INT);
$fieldId = (string)$request->getParam('field', FILTER_SANITIZE_NUMBER_INT); $fieldId = (string)$request->getParam('field', FILTER_SANITIZE_NUMBER_INT);
@ -81,6 +62,7 @@ final class SatoriRoutes implements IRouteHandler {
]; ];
} }
#[Route('GET', '/_satori/get-recent-forum-posts')]
public function getRecentForumPosts($response, $request): array { public function getRecentForumPosts($response, $request): array {
$categoryIds = $this->config->getArray('forum.categories'); $categoryIds = $this->config->getArray('forum.categories');
if(empty($categoryIds)) if(empty($categoryIds))
@ -122,6 +104,7 @@ final class SatoriRoutes implements IRouteHandler {
return $posts; return $posts;
} }
#[Route('GET', '/_satori/get-recent-registrations')]
public function getRecentRegistrations($response, $request) { public function getRecentRegistrations($response, $request) {
$batchSize = $this->config->getInteger('users.batch', 10); $batchSize = $this->config->getInteger('users.batch', 10);
$backlogDays = $this->config->getInteger('users.backlog', 7); $backlogDays = $this->config->getInteger('users.backlog', 7);

View file

@ -6,7 +6,8 @@ use RuntimeException;
use Index\Colour\Colour; use Index\Colour\Colour;
use Index\Routing\IRouter; use Index\Routing\IRouter;
use Index\Routing\IRouteHandler; use Index\Routing\IRouteHandler;
use Index\Http\HttpFx; use Index\Routing\Route;
use Misuzu\Tools;
use Misuzu\Auth\AuthInfo; use Misuzu\Auth\AuthInfo;
use Misuzu\Auth\Sessions; use Misuzu\Auth\Sessions;
use Misuzu\Config\IConfig; use Misuzu\Config\IConfig;
@ -31,41 +32,11 @@ final class SharpChatRoutes implements IRouteHandler {
} }
public function registerRoutes(IRouter $router): void { public function registerRoutes(IRouter $router): void {
// Simplify default error pages Tools::simplifyErrorPages($router, '/_sockchat');
if($router instanceof HttpFx) Route::handleAttributes($router, $this);
$router->use('/_sockchat', function() use($router) {
$router->addErrorHandler(400, function($response) {
$response->setContent('HTTP 400');
});
$router->addErrorHandler(403, function($response) {
$response->setContent('HTTP 403');
});
$router->addErrorHandler(404, function($response) {
$response->setContent('HTTP 404');
});
$router->addErrorHandler(500, function($response) {
$response->setContent('HTTP 500');
});
$router->addErrorHandler(503, function($response) {
$response->setContent('HTTP 503');
});
});
// Public endpoints
$router->get('/_sockchat/emotes', $this->getEmotes(...));
$router->get('/_sockchat/login', $this->getLogin(...));
$router->options('/_sockchat/token', $this->getToken(...));
$router->get('/_sockchat/token', $this->getToken(...));
// Private endpoints
$router->post('/_sockchat/bump', $this->postBump(...));
$router->post('/_sockchat/verify', $this->postVerify(...));
$router->get('/_sockchat/bans/list', $this->getBanList(...));
$router->get('/_sockchat/bans/check', $this->getBanCheck(...));
$router->post('/_sockchat/bans/create', $this->postBanCreate(...));
$router->delete('/_sockchat/bans/revoke', $this->deleteBanRevoke(...));
} }
#[Route('GET', '/_sockchat/emotes')]
public function getEmotes($response, $request): array { public function getEmotes($response, $request): array {
$response->setHeader('Access-Control-Allow-Origin', '*'); $response->setHeader('Access-Control-Allow-Origin', '*');
$response->setHeader('Access-Control-Allow-Methods', 'GET'); $response->setHeader('Access-Control-Allow-Methods', 'GET');
@ -89,6 +60,7 @@ final class SharpChatRoutes implements IRouteHandler {
return $out; return $out;
} }
#[Route('GET', '/_sockchat/login')]
public function getLogin($response, $request): void { public function getLogin($response, $request): void {
if(!$this->authInfo->isLoggedIn()) { if(!$this->authInfo->isLoggedIn()) {
$response->redirect(url('auth-login')); $response->redirect(url('auth-login'));
@ -101,6 +73,8 @@ final class SharpChatRoutes implements IRouteHandler {
)); ));
} }
#[Route('OPTIONS', '/_sockchat/token')]
#[Route('GET', '/_sockchat/token')]
public function getToken($response, $request) { public function getToken($response, $request) {
$host = $request->hasHeader('Host') ? $request->getHeaderFirstLine('Host') : ''; $host = $request->hasHeader('Host') ? $request->getHeaderFirstLine('Host') : '';
$origin = $request->hasHeader('Origin') ? $request->getHeaderFirstLine('Origin') : ''; $origin = $request->hasHeader('Origin') ? $request->getHeaderFirstLine('Origin') : '';
@ -154,6 +128,7 @@ final class SharpChatRoutes implements IRouteHandler {
]; ];
} }
#[Route('POST', '/_sockchat/bump')]
public function postBump($response, $request) { public function postBump($response, $request) {
if(!$request->hasHeader('X-SharpChat-Signature')) if(!$request->hasHeader('X-SharpChat-Signature'))
return 400; return 400;
@ -183,6 +158,7 @@ final class SharpChatRoutes implements IRouteHandler {
$this->usersCtx->getUsers()->recordUserActivity($userId, remoteAddr: $ipAddr); $this->usersCtx->getUsers()->recordUserActivity($userId, remoteAddr: $ipAddr);
} }
#[Route('POST', '/_sockchat/verify')]
public function postVerify($response, $request) { public function postVerify($response, $request) {
if(!$request->hasHeader('X-SharpChat-Signature')) if(!$request->hasHeader('X-SharpChat-Signature'))
return 400; return 400;
@ -262,6 +238,7 @@ final class SharpChatRoutes implements IRouteHandler {
]; ];
} }
#[Route('GET', '/_sockchat/bans/list')]
public function getBanList($response, $request) { public function getBanList($response, $request) {
if(!$request->hasHeader('X-SharpChat-Signature')) if(!$request->hasHeader('X-SharpChat-Signature'))
return 400; return 400;
@ -296,6 +273,7 @@ final class SharpChatRoutes implements IRouteHandler {
return $list; return $list;
} }
#[Route('GET', '/_sockchat/bans/check')]
public function getBanCheck($response, $request) { public function getBanCheck($response, $request) {
if(!$request->hasHeader('X-SharpChat-Signature')) if(!$request->hasHeader('X-SharpChat-Signature'))
return 400; return 400;
@ -333,6 +311,7 @@ final class SharpChatRoutes implements IRouteHandler {
]; ];
} }
#[Route('POST', '/_sockchat/bans/create')]
public function postBanCreate($response, $request): int { public function postBanCreate($response, $request): int {
if(!$request->hasHeader('X-SharpChat-Signature') || !$request->isFormContent()) if(!$request->hasHeader('X-SharpChat-Signature') || !$request->isFormContent())
return 400; return 400;
@ -406,6 +385,7 @@ final class SharpChatRoutes implements IRouteHandler {
return 201; return 201;
} }
#[Route('DELETE', '/_sockchat/bans/revoke')]
public function deleteBanRevoke($response, $request): int { public function deleteBanRevoke($response, $request): int {
if(!$request->hasHeader('X-SharpChat-Signature')) if(!$request->hasHeader('X-SharpChat-Signature'))
return 400; return 400;

View file

@ -1,6 +1,9 @@
<?php <?php
namespace Misuzu; namespace Misuzu;
use Index\Routing\IRouter;
use Index\Http\HttpFx;
final class Tools { final class Tools {
public static function isLeapYear(int $year): bool { public static function isLeapYear(int $year): bool {
return (($year % 4) === 0 && ($year % 100) !== 0) return (($year % 4) === 0 && ($year % 100) !== 0)
@ -25,6 +28,17 @@ final class Tools {
return $day <= $days; return $day <= $days;
} }
public static function simplifyErrorPages(IRouter $router, string $path): void {
if($router instanceof HttpFx)
$router->use($path, function() use($router) {
$router->addErrorHandler(400, fn($resp) => $resp->setContent('HTTP 400'));
$router->addErrorHandler(403, fn($resp) => $resp->setContent('HTTP 403'));
$router->addErrorHandler(404, fn($resp) => $resp->setContent('HTTP 404'));
$router->addErrorHandler(500, fn($resp) => $resp->setContent('HTTP 500'));
$router->addErrorHandler(503, fn($resp) => $resp->setContent('HTTP 503'));
});
}
// for your own sanity and the sanity of others, keep this one at the bottom // for your own sanity and the sanity of others, keep this one at the bottom
public static function countryName(string $code): string { public static function countryName(string $code): string {
return match(strtoupper($code)) { return match(strtoupper($code)) {

View file

@ -3,27 +3,19 @@ namespace Misuzu\Users\Assets;
use InvalidArgumentException; use InvalidArgumentException;
use RuntimeException; use RuntimeException;
use Index\Routing\IRouter; use Index\Routing\Route;
use Index\Routing\IRouteHandler; use Index\Routing\RouteHandler;
use Misuzu\Perm; use Misuzu\Perm;
use Misuzu\Auth\AuthInfo; use Misuzu\Auth\AuthInfo;
use Misuzu\Users\UsersContext; use Misuzu\Users\UsersContext;
use Misuzu\Users\UserInfo; use Misuzu\Users\UserInfo;
class AssetsRoutes implements IRouteHandler { class AssetsRoutes extends RouteHandler {
public function __construct( public function __construct(
private AuthInfo $authInfo, private AuthInfo $authInfo,
private UsersContext $usersCtx private UsersContext $usersCtx
) {} ) {}
public function registerRoutes(IRouter $router): void {
$router->get('/assets/avatar', $this->getAvatar(...));
$router->get('/assets/avatar/:filename', $this->getAvatar(...));
$router->get('/assets/profile-background', $this->getProfileBackground(...));
$router->get('/assets/profile-background/:filename', $this->getProfileBackground(...));
$router->get('/user-assets.php', $this->getUserAssets(...));
}
private function canViewAsset($request, UserInfo $assetUser): bool { private function canViewAsset($request, UserInfo $assetUser): bool {
if($this->usersCtx->getBans()->countActiveBans($assetUser)) if($this->usersCtx->getBans()->countActiveBans($assetUser))
// allow staff viewing profile to still see banned user assets // allow staff viewing profile to still see banned user assets
@ -33,6 +25,8 @@ class AssetsRoutes implements IRouteHandler {
return true; return true;
} }
#[Route('GET', '/assets/avatar')]
#[Route('GET', '/assets/avatar/:filename')]
public function getAvatar($response, $request, string $fileName = '') { public function getAvatar($response, $request, string $fileName = '') {
$userId = pathinfo($fileName, PATHINFO_FILENAME); $userId = pathinfo($fileName, PATHINFO_FILENAME);
$assetInfo = new StaticUserImageAsset(MSZ_PUBLIC . '/images/no-avatar.png', MSZ_PUBLIC); $assetInfo = new StaticUserImageAsset(MSZ_PUBLIC . '/images/no-avatar.png', MSZ_PUBLIC);
@ -53,6 +47,8 @@ class AssetsRoutes implements IRouteHandler {
$this->serveAsset($response, $request, $assetInfo); $this->serveAsset($response, $request, $assetInfo);
} }
#[Route('GET', '/assets/profile-background')]
#[Route('GET', '/assets/profile-background/:filename')]
public function getProfileBackground($response, $request, string $fileName = '') { public function getProfileBackground($response, $request, string $fileName = '') {
$userId = pathinfo($fileName, PATHINFO_FILENAME); $userId = pathinfo($fileName, PATHINFO_FILENAME);
@ -76,6 +72,7 @@ class AssetsRoutes implements IRouteHandler {
$this->serveAsset($response, $request, $assetInfo); $this->serveAsset($response, $request, $assetInfo);
} }
#[Route('GET', '/user-assets.php')]
public function getUserAssets($response, $request) { public function getUserAssets($response, $request) {
$userId = (string)$request->getParam('u', FILTER_SANITIZE_NUMBER_INT); $userId = (string)$request->getParam('u', FILTER_SANITIZE_NUMBER_INT);
$mode = (string)$request->getParam('m'); $mode = (string)$request->getParam('m');