chg: usr: make fancy og tags - and create a special one for battle sharing #4
This commit is contained in:
@@ -10,21 +10,31 @@
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Entity\PlayedGame;
|
||||
use App\Entity\User;
|
||||
use App\Repository\PlayedGameRepository;
|
||||
use App\Service\BattleCardGenerator;
|
||||
use App\Service\WebAuthnService;
|
||||
use DateTime;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use League\Flysystem\FilesystemException;
|
||||
use League\Flysystem\FilesystemOperator;
|
||||
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use RuntimeException;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\File\UploadedFile;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
|
||||
use Symfony\Component\HttpKernel\Attribute\AsController;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
use Throwable;
|
||||
use function count;
|
||||
|
||||
/**
|
||||
* Class ProfileController
|
||||
@@ -41,7 +51,8 @@ class ProfileController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PlayedGameRepository $repo,
|
||||
private readonly WebAuthnService $webAuthnService
|
||||
private readonly WebAuthnService $webAuthnService,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -57,15 +68,15 @@ class ProfileController extends AbstractController
|
||||
$losses = $this->repo->countLossesForUser($user);
|
||||
$draws = $this->repo->countDrawsForUser($user);
|
||||
|
||||
// Build monthly buckets for the last 6 months
|
||||
/** Build monthly buckets for the last 6 months */
|
||||
$monthlyData = [];
|
||||
for ($i = 5; $i >= 0; $i--) {
|
||||
$dt = new \DateTime("first day of -$i months midnight");
|
||||
$dt = new DateTime("first day of -$i months midnight");
|
||||
$key = $dt->format('Y-m');
|
||||
$monthlyData[$key] = ['label' => $dt->format('M'), 'wins' => 0, 'losses' => 0, 'draws' => 0];
|
||||
}
|
||||
|
||||
$since = new \DateTime('first day of -5 months midnight');
|
||||
$since = new DateTime('first day of -5 months midnight');
|
||||
$recentGames = $this->repo->findFinishedForUserSince($user, $since);
|
||||
$userId = $user->getId();
|
||||
|
||||
@@ -113,7 +124,7 @@ class ProfileController extends AbstractController
|
||||
'bestScore' => $this->repo->findBestScoreForUser($user),
|
||||
],
|
||||
'recent' => ($recent = $this->repo->findRecentFinishedForUser($user)),
|
||||
'gamesData' => array_map(static function (\App\Entity\PlayedGame $game) use ($userId): array {
|
||||
'gamesData' => array_map(static function (PlayedGame $game) use ($userId): array {
|
||||
$isRed = $game->getRed()?->getId() === $userId;
|
||||
$resign = $game->getResign();
|
||||
$myColor = $isRed ? 'red' : 'blue';
|
||||
@@ -131,6 +142,7 @@ class ProfileController extends AbstractController
|
||||
|
||||
return [
|
||||
'id' => $game->getId(),
|
||||
'uuid' => $game->getUuid()?->toRfc4122(),
|
||||
'redName' =>
|
||||
$game->getRed()?->getUsername() ?? $game->getRedAnon()?->getUserName() ?? 'Guest',
|
||||
'blueName' =>
|
||||
@@ -160,16 +172,21 @@ class ProfileController extends AbstractController
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route('/battle/{id}', name: 'MineSeekerBundle_battle_share', requirements: ['id' => '\d+'], methods: ['GET'])]
|
||||
public function battleShare(int $id): Response
|
||||
#[Route(
|
||||
'/battle/{uuid}',
|
||||
name: 'MineSeekerBundle_battle_share',
|
||||
requirements: ['uuid' => '[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}'],
|
||||
methods: ['GET'],
|
||||
)]
|
||||
public function battleShare(Uuid $uuid): Response
|
||||
{
|
||||
$game = $this->repo->find($id);
|
||||
$game = $this->repo->findOneBy(['uuid' => $uuid]);
|
||||
if (!$game) {
|
||||
throw $this->createNotFoundException('Battle not found.');
|
||||
}
|
||||
|
||||
$redName = $game->getRed()?->getUsername() ?? $game->getRedAnon()?->getUserName() ?? 'Guest';
|
||||
$blueName = $game->getBlue()?->getUsername() ?? $game->getBlueAnon()?->getUserName() ?? 'Guest';
|
||||
$redName = $game->getRed()?->getUsername() ?? ($game->getRedAnon() !== null ? 'Anonymous' : 'Guest');
|
||||
$blueName = $game->getBlue()?->getUsername() ?? ($game->getBlueAnon() !== null ? 'Anonymous' : 'Guest');
|
||||
$redPts = $game->getRedPoints();
|
||||
$bluePts = $game->getBluePoints();
|
||||
$resign = $game->getResign();
|
||||
@@ -202,6 +219,29 @@ class ProfileController extends AbstractController
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route(
|
||||
'/og/battle/{uuid}.png',
|
||||
name: 'MineSeekerBundle_og_battle',
|
||||
requirements: ['uuid' => '[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}'],
|
||||
methods: ['GET'],
|
||||
)]
|
||||
public function battleOgImage(Uuid $uuid, BattleCardGenerator $generator): BinaryFileResponse
|
||||
{
|
||||
$game = $this->repo->findOneBy(['uuid' => $uuid]);
|
||||
if (!$game) {
|
||||
throw $this->createNotFoundException();
|
||||
}
|
||||
|
||||
$path = $generator->generate($game);
|
||||
$response = new BinaryFileResponse($path);
|
||||
$response->headers->set('Content-Type', 'image/png');
|
||||
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE);
|
||||
$response->setMaxAge(86400 * 30);
|
||||
$response->setPublic();
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
#[Route('/profile/avatar', name: 'MineSeekerBundle_profile_avatar', methods: ['POST'])]
|
||||
public function uploadAvatar(
|
||||
Request $request,
|
||||
@@ -232,18 +272,24 @@ class ProfileController extends AbstractController
|
||||
$newPath = sprintf('avatar/%s.%s', Uuid::v4()->toRfc4122(), $ext);
|
||||
$oldPath = $user->getAvatarPath();
|
||||
|
||||
// Remove old file and any cached thumbnails
|
||||
/** Remove old file and any cached thumbnails */
|
||||
if ($oldPath) {
|
||||
try {
|
||||
$mediaStorage->delete($oldPath);
|
||||
} catch (\Throwable) {
|
||||
} catch (Throwable) {
|
||||
$this->logger->error('Unable to delete old avatar: ' . $oldPath);
|
||||
}
|
||||
$cacheManager->remove($oldPath, 'avatar_thumb');
|
||||
}
|
||||
|
||||
// Upload original to MinIO media/avatar/
|
||||
$stream = fopen($file->getPathname(), 'r');
|
||||
$mediaStorage->writeStream($newPath, $stream);
|
||||
/** Upload original to MinIO media/avatar/ */
|
||||
$stream = fopen($file->getPathname(), 'rb');
|
||||
try {
|
||||
$mediaStorage->writeStream($newPath, $stream);
|
||||
} catch (FilesystemException $e) {
|
||||
$this->logger->error('Unable to write new avatar: ' . $e->getMessage());
|
||||
throw new RuntimeException('Unable to write new avatar: ' . $e->getMessage());
|
||||
}
|
||||
fclose($stream);
|
||||
|
||||
$user->setAvatarPath($newPath);
|
||||
@@ -274,7 +320,7 @@ class ProfileController extends AbstractController
|
||||
return $this->render('Security/profile_security.html.twig', [
|
||||
'credentials' => $credentialsData,
|
||||
'isTotpEnabled' => $user->isTotpAuthenticationEnabled(),
|
||||
'backupCodesCount' => \count($user->getBackupCodes()),
|
||||
'backupCodesCount' => count($user->getBackupCodes()),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ use Doctrine\ORM\Mapping\JoinColumn;
|
||||
use Doctrine\ORM\Mapping\ManyToOne;
|
||||
use Doctrine\ORM\Mapping\OneToMany;
|
||||
use Doctrine\ORM\Mapping\OneToOne;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
/**
|
||||
* Class PlayedGame
|
||||
@@ -40,6 +41,9 @@ class PlayedGame
|
||||
#[Id, GeneratedValue, Column]
|
||||
private ?int $id = null;
|
||||
|
||||
#[Column(type: 'uuid', unique: true)]
|
||||
private ?Uuid $uuid = null;
|
||||
|
||||
#[Column(length: 50)]
|
||||
private ?string $gameAssoc = null;
|
||||
|
||||
@@ -90,6 +94,7 @@ class PlayedGame
|
||||
public function __construct()
|
||||
{
|
||||
$this->steps = new ArrayCollection();
|
||||
$this->uuid = Uuid::v4();
|
||||
}
|
||||
|
||||
public function getId(): ?int
|
||||
@@ -97,6 +102,16 @@ class PlayedGame
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getUuid(): ?Uuid
|
||||
{
|
||||
return $this->uuid;
|
||||
}
|
||||
|
||||
public function setUuid(?Uuid $uuid): void
|
||||
{
|
||||
$this->uuid = $uuid;
|
||||
}
|
||||
|
||||
public function getGameAssoc(): ?string
|
||||
{
|
||||
return $this->gameAssoc;
|
||||
|
||||
47
src/Migrations/2026/04/Version20260414000000.php
Normal file
47
src/Migrations/2026/04/Version20260414000000.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php declare(strict_types=1);
|
||||
/*
|
||||
* This file is part of the SplendidBear Websites' projects.
|
||||
*
|
||||
* Copyright (c) 2026 @ www.splendidbear.org
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace App\Migrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* Class Version20260414000000
|
||||
*
|
||||
* @package App\Migrations
|
||||
* @author Lang <https://www.splendidbear.org>
|
||||
* @category Class
|
||||
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html GNU Lesser General Public License
|
||||
* @link www.splendidbear.org
|
||||
* @since 2026. 04. 14.
|
||||
*/
|
||||
final class Version20260414000000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Add uuid column to played_game for shareable URLs';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE played_game ADD uuid UUID DEFAULT NULL');
|
||||
$this->addSql('UPDATE played_game SET uuid = gen_random_uuid() WHERE uuid IS NULL');
|
||||
$this->addSql('ALTER TABLE played_game ADD CONSTRAINT played_game_uuid_unique UNIQUE (uuid)');
|
||||
$this->addSql('ALTER TABLE played_game ALTER COLUMN uuid SET NOT NULL');
|
||||
$this->addSql('COMMENT ON COLUMN played_game.uuid IS \'(DC2Type:uuid)\'');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE played_game DROP uuid');
|
||||
}
|
||||
}
|
||||
|
||||
180
src/Service/BattleCardGenerator.php
Normal file
180
src/Service/BattleCardGenerator.php
Normal file
@@ -0,0 +1,180 @@
|
||||
<?php declare(strict_types=1);
|
||||
/*
|
||||
* This file is part of the SplendidBear Websites' projects.
|
||||
*
|
||||
* Copyright (c) 2026 @ www.splendidbear.org
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Entity\PlayedGame;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
/**
|
||||
* Class BattleCardGenerator
|
||||
*
|
||||
* Generates a 1200x630 PNG battle card for Open Graph sharing.
|
||||
*
|
||||
* @package App\Service
|
||||
* @author Lang <https://www.splendidbear.org>
|
||||
* @category Class
|
||||
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html GNU Lesser General Public License
|
||||
* @link www.splendidbear.org
|
||||
* @since 2026. 04. 14.
|
||||
*/
|
||||
class BattleCardGenerator
|
||||
{
|
||||
private const W = 1200;
|
||||
private const H = 630;
|
||||
private const FONT = '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf';
|
||||
|
||||
public function __construct(private readonly string $cacheDir) { }
|
||||
|
||||
/** Returns a deterministic UUID v5 for the given battle ID — same battle always maps to the same filename. */
|
||||
public function cachePath(int $battleId): string
|
||||
{
|
||||
$uuid = Uuid::v5(Uuid::fromString(Uuid::NAMESPACE_URL), 'mineseeker-battle-' . $battleId);
|
||||
|
||||
return $this->cacheDir . '/' . $uuid->toRfc4122() . '.png';
|
||||
}
|
||||
|
||||
public function generate(PlayedGame $game): string
|
||||
{
|
||||
$path = $this->cachePath((int)$game->getId());
|
||||
|
||||
if (is_file($path)) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
if (!is_dir($this->cacheDir)) {
|
||||
mkdir($this->cacheDir, 0755, true);
|
||||
}
|
||||
|
||||
$this->render($game, $path);
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
private function render(PlayedGame $game, string $dest): void
|
||||
{
|
||||
$im = imagecreatetruecolor(self::W, self::H);
|
||||
|
||||
// Palette
|
||||
$bg = imagecolorallocate($im, 13, 13, 28);
|
||||
$dot = imagecolorallocate($im, 30, 30, 55);
|
||||
$divider = imagecolorallocate($im, 40, 40, 70);
|
||||
$white = imagecolorallocate($im, 230, 230, 240);
|
||||
$muted = imagecolorallocate($im, 90, 90, 115);
|
||||
$red = imagecolorallocate($im, 246, 125, 82);
|
||||
$blue = imagecolorallocate($im, 149, 207, 245);
|
||||
$gold = imagecolorallocate($im, 255, 200, 50);
|
||||
|
||||
// Background
|
||||
imagefill($im, 0, 0, $bg);
|
||||
|
||||
// Dot-grid texture
|
||||
for ($x = 40; $x < self::W; $x += 40) {
|
||||
for ($y = 40; $y < self::H; $y += 40) {
|
||||
imagesetpixel($im, $x, $y, $dot);
|
||||
}
|
||||
}
|
||||
|
||||
// Horizontal accent lines
|
||||
imageline($im, 0, 90, self::W, 90, $divider);
|
||||
imageline($im, 0, self::H - 60, self::W, self::H - 60, $divider);
|
||||
|
||||
// Vertical centre divider
|
||||
imageline($im, self::W / 2, 110, self::W / 2, self::H - 80, $divider);
|
||||
|
||||
// Resolve names
|
||||
$redName = $game->getRed()?->getUsername()
|
||||
?? ($game->getRedAnon() !== null ? 'Anonymous' : 'Guest');
|
||||
$blueName = $game->getBlue()?->getUsername()
|
||||
?? ($game->getBlueAnon() !== null ? 'Anonymous' : 'Guest');
|
||||
$redPts = $game->getRedPoints();
|
||||
$bluePts = $game->getBluePoints();
|
||||
$resign = $game->getResign();
|
||||
|
||||
// Winner
|
||||
$winner = null;
|
||||
if ($resign === 'red') {
|
||||
$winner = 'blue';
|
||||
} elseif ($resign === 'blue') {
|
||||
$winner = 'red';
|
||||
} elseif ($redPts !== null && $bluePts !== null) {
|
||||
if ($redPts > $bluePts) $winner = 'red';
|
||||
elseif ($bluePts > $redPts) $winner = 'blue';
|
||||
else $winner = 'draw';
|
||||
}
|
||||
|
||||
$this->centeredText($im, 'MineSeeker', 20, self::W / 2, 58, $muted);
|
||||
|
||||
$this->centeredText($im, 'RED', 16, self::W / 4, 130, $red);
|
||||
$this->centeredText($im, 'BLUE', 16, self::W * 3 / 4, 130, $blue);
|
||||
|
||||
$redColor = $winner === 'red' ? $gold : ($winner === 'draw' ? $white : $red);
|
||||
$blueColor = $winner === 'blue' ? $gold : ($winner === 'draw' ? $white : $blue);
|
||||
|
||||
$this->centeredTextFit($im, $redName, 48, self::W / 4, 265, $redColor, self::W / 2 - 80);
|
||||
$this->centeredTextFit($im, $blueName, 48, self::W * 3 / 4, 265, $blueColor, self::W / 2 - 80);
|
||||
|
||||
$scoreText = $redPts !== null && $bluePts !== null ? $redPts . ' : ' . $bluePts : 'VS';
|
||||
$this->centeredText($im, $scoreText, 72, self::W / 2, 390, $white);
|
||||
|
||||
if ($winner === 'red') {
|
||||
$resultText = $redName . ' wins';
|
||||
$resultColor = $gold;
|
||||
} elseif ($winner === 'blue') {
|
||||
$resultText = $blueName . ' wins';
|
||||
$resultColor = $gold;
|
||||
} elseif ($winner === 'draw') {
|
||||
$resultText = 'Draw';
|
||||
$resultColor = $muted;
|
||||
} else {
|
||||
$resultText = '';
|
||||
$resultColor = $muted;
|
||||
}
|
||||
|
||||
if ($resultText !== '') {
|
||||
$this->centeredText($im, $resultText, 30, self::W / 2, 460, $resultColor);
|
||||
}
|
||||
|
||||
if ($resign) {
|
||||
$this->centeredText($im, ucfirst($resign) . ' resigned', 18, self::W / 2, 498, $muted);
|
||||
}
|
||||
|
||||
$this->centeredText($im, 'mineseeker.hu', 16, self::W / 2, self::H - 20, $muted);
|
||||
|
||||
imagepng($im, $dest);
|
||||
imagedestroy($im);
|
||||
}
|
||||
|
||||
/** Render text centered on $cx. */
|
||||
private function centeredText(\GdImage $im, string $text, int $size, int $cx, int $y, int $color): void
|
||||
{
|
||||
$bbox = imagettfbbox($size, 0, self::FONT, $text);
|
||||
$w = $bbox[2] - $bbox[0];
|
||||
imagettftext($im, $size, 0, (int)($cx - $w / 2), $y, $color, self::FONT, $text);
|
||||
}
|
||||
|
||||
/** Render text centered on $cx, shrinking font size to fit $maxWidth. */
|
||||
private function centeredTextFit(
|
||||
\GdImage $im,
|
||||
string $text,
|
||||
int $size,
|
||||
int $cx,
|
||||
int $y,
|
||||
int $color,
|
||||
int $maxWidth
|
||||
): void {
|
||||
$bbox = imagettfbbox($size, 0, self::FONT, $text);
|
||||
$w = $bbox[2] - $bbox[0];
|
||||
if ($w > $maxWidth) {
|
||||
$size = (int)($size * $maxWidth / $w);
|
||||
}
|
||||
$this->centeredText($im, $text, $size, $cx, $y, $color);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user