src/Controller/TinyKnightGames/UserController.php line 328
<?php
namespace App\Controller\TinyKnightGames;
use App\Entity\InventoryEquipment;
use App\Entity\MarketItem;
use App\Entity\MarketOffer;
use App\Entity\NftMetadata;
use App\Entity\PlayerRank;
use App\Entity\ThetaWallet;
use App\Entity\User;
use App\Entity\UserGear;
use Doctrine\Persistence\ManagerRegistry;
use Proxies\__CG__\App\Entity\TemplateCategory;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class UserController extends AbstractController
{
public function __construct(private ManagerRegistry $doctrine) {}
#[Route('/user', name: 'user')]
public function index(): Response
{
return $this->render('user/index.html.twig', [
'controller_name' => 'UserController',
]);
}
#[Route('/api/user/rank', name: 'user')]
public function getRank(Request $request): Response
{
$em = $this->doctrine->getManager();
$params = $request->query->all();
$user = $em->getRepository(User::class)->findOneBy(['id' => $params['user_id']]);
$currentRank = $em->getRepository(PlayerRank::class)->findPlayerCurrentRank($user->getExperience());
$nextRank = $em->getRepository(PlayerRank::class)->findPlayerNextRank($user->getExperience());
// {rank: Trained 0, nextRank: Trained 1, currentXP: 660, nextLevelXP: 1160, salvageTime: 8, afkFishingTime: 2, recipeHint: 4}
$json = $currentRank->getPerks();
$json['rank'] = $currentRank->getTitle();
$json['nextRank'] = $nextRank->getTitle();
$json['prevXpTier'] = $currentRank->getRequiredExp();
$json['currentExp'] = $user->getExperience();
$json['nextXpTier'] = $nextRank->getRequiredExp();
return new Response (
json_encode($json),
Response::HTTP_OK,
['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
);
}
#[Route('/api/user/authenticated', name: 'user_authenticated')]
public function getAuthenticatedUser()
{
// Verify User is authenticated
$response = new Response();
if($user = $this->getUser()) {
$response->setContent("true");
return $response;
} else {
$response->setContent("false");
return $response;
}
}
#[Route('/api/user/token', name: 'user_token')]
public function getAuthenticatedUserToken()
{
$em = $this->doctrine->getManager();
$userInfo = array();
$user = $this->getUser();
// Verify User is authenticated
if($user) {
// Set a new game token on login
$gameToken = hash('sha256', $this->generateRandomString() . $user->getEmail());
$user->setGameToken($gameToken);
$em->persist($user);
$em->flush();
$userInfo['token'] = $user->getGameToken();
$userInfo['id'] = $user->getId();
$userInfo['username'] = $user->getUsername();
$userInfo['serverTime'] = time();
}
return new Response (
json_encode($userInfo),
Response::HTTP_OK,
['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
);
}
#[Route('/api/ooto/user/token', name: 'ooto_user_token')]
public function getOotoAuthenticatedUserToken()
{
$em = $this->doctrine->getManager();
$userInfo = array();
$user = $this->getUser();
// Verify User is authenticated
if($user) {
// Set a new game token on login
$gameToken = hash('sha256', $this->generateRandomString() . $user->getEmail());
$user->setGameToken2($gameToken);
$em->persist($user);
$em->flush();
$userInfo['token'] = $user->getGameToken2();
$userInfo['id'] = $user->getId();
$userInfo['username'] = $user->getUsername();
$userInfo['serverTime'] = time();
}
return new Response (
json_encode($userInfo),
Response::HTTP_OK,
['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
);
}
#[Route('/api/user/{userId}/gear', name: 'api_user_gear')]
public function getUserGear(Request $request, string $userId): Response
{
$params = $request->query->all();
$headers = $request->headers->all();
$em = $this->doctrine->getManager();
$user = $em->getRepository(User::class)->find($userId);
// Verify hash
$userGameToken = hash('sha256', $user->getGameToken().$this->getParameter('app.secret'));
$apiGameToken = $headers['gametoken'][0];
// Authenticate request
if ($userGameToken != $apiGameToken) {
return new Response("Authentication failed.");
}
$userInventoryEquipment = $em->getRepository(UserGear::class)->findInventoryEquipmentByUser($user);
$userNftEquipment = $em->getRepository(UserGear::class)->findNftEquipmentByUser($user);
// $userNftCatchable = $em->getRepository(UserGear::class)->findNftCatchableByUser($user);
foreach ($userInventoryEquipment as $key => $equipment) {
$userInventoryEquipment[$key]['isNft'] = false;
}
foreach ($userNftEquipment as $key => $nftEquipment) {
$userNftEquipment[$key]['isNft'] = true;
}
// if(!empty($userNftCatchable)) {
// $userNftCatchable['isNft'] = true;
// $userNftCatchable['category'] = 'Charm';
// }
$userGear = array_merge($userInventoryEquipment, $userNftEquipment);
// Include Charm if equipped
// $userCharm = array($userNftCatchable); // Needs to be in an array to format the JSON properly
// if(isset($userCharm[0])) {
// $userGear = array_merge($userGear, $userCharm);
// }
return new Response (
json_encode($userGear),
Response::HTTP_OK,
['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
);
}
#[Route('/api/inventory/{userId}/equipment/{equipmentId}/update/status', name: 'inventory_equipment_update_status')]
public function updateInventoryEquipmentStatus(Request $request, string $userId, string $equipmentId): Response
{
// method [equip, unequip], hash, isNft, isCharm
$params = $request->query->all();
$headers = $request->headers->all();
// TODO: Verify that we have all required parameters
$em = $this->doctrine->getManager();
$user = $em->getRepository(User::class)->find($userId);
// Verify Hash
// $userGameToken = hash('sha256', $user->getGameToken().$this->getParameter('app.secret'));
// $apiGameToken = $headers['gametoken'][0];
//
// // Authenticate request
// if ($userGameToken != $apiGameToken) {
// return new Response("Authentication failed.");
// }
if (array_key_exists('isNft',$params) && $params['isNft'] == "true") {
if (array_key_exists('isCharm',$params) && $params['isCharm'] == 'true')
{
// Verify that the User has the NFT Equipment (Charm)
$nftCatchable = $em->getRepository(NftMetadata::class)->verifyOwnership($user, $equipmentId);
if (empty($nftCatchable)) {
return new Response ("This User does not possess this piece of NFT equipment. ( ID: " . $equipmentId . " )");
}
$category = $em->getRepository(TemplateCategory::class)->findOneBy(array('name' => 'Charm'));
$userGear = $em->getRepository(UserGear::class)->findOneBy(array('user' => $user, 'templateCategory' => $category));
// Equip / Unequip
if ($params['method'] == 'equip') {
$userGear->setInventoryEquipment(null); // Make sure we don't also have regular equipment equipped
$userGear->setNftMetadata($nftCatchable);
} elseif($params['method'] == 'unequip') {
$userGear->setNftMetadata(null);
}
} else {
// Otherwise we are just equipping normal NFT Equipment
// Verify that the User has the NFT Equipment
$nftEquipment = $em->getRepository(NftMetadata::class)->verifyOwnership($user, $equipmentId);
if (empty($nftEquipment)) {
return new Response ("This User does not possess this piece of NFT equipment. ( ID: " . $equipmentId . " )");
}
$category = $nftEquipment->getTemplate()->getCategory();
$userGear = $em->getRepository(UserGear::class)->findOneBy(array('user' => $user, 'templateCategory' => $category));
// Equip / Unequip
if ($params['method'] == 'equip') {
$userGear->setInventoryEquipment(null); // Make sure we don't also have regular equipment equipped
$userGear->setNftMetadata($nftEquipment);
} elseif($params['method'] == 'unequip') {
$userGear->setNftMetadata(null);
}
}
} elseif(!array_key_exists('isNft',$params) || $params['isNft'] == "false") {
// Verify that User has Equipment
$inventoryEquipment = $em->getRepository(InventoryEquipment::class)
->findOneBy(array('user' => $userId, 'id' => $equipmentId));
if (empty($inventoryEquipment)) {
return new Response ("User does not possess this piece of equipment. ( ID: " . $equipmentId . " )");
}
$category = $inventoryEquipment->getTemplate()->getCategory();
$userGear = $em->getRepository(UserGear::class)->findOneBy(array('user' => $user, 'templateCategory' => $category));
// Equip / Unequip
if ($params['method'] == 'equip') {
$userGear->setInventoryEquipment($inventoryEquipment);
$userGear->setNftMetadata(null); // Make sure we don't also have NFT equipment equipped
} elseif ($params['method'] == 'unequip') {
$userGear->setInventoryEquipment(null);
}
}
$em->persist($userGear);
$em->flush();
return new Response (
json_encode(array('response' => 'Equipment updated successfully')),
Response::HTTP_OK,
['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
);
}
#[Route('/api/user/wallet/update', name: 'api_user_wallet_update')]
public function updateConnectedWallet(Request $request)
{
$em = $this->doctrine->getManager();
$user = $this->getUser();
// get Address from request
$address = $request->get('address');
if($address !== '') {
// See if wallet exists in database
$wallet = $em->getRepository(ThetaWallet::class)->findOneBy(array('address' => $address));
if ($wallet === null) {
$newWallet = new ThetaWallet();
$newWallet->setAddress($address);
$user->setActiveWallet($newWallet);
$em->persist($user);
$em->persist($newWallet);
} else {
$existingUser = $em->getRepository(User::class)->findOneBy(array('activeWallet' => $wallet));
if($existingUser !== null) {
$existingUser->setActiveWallet(null);
$em->persist($existingUser);
$em->flush();
}
$user->setActiveWallet($wallet);
}
if ($request->get('extension') === 'thetawallet') {
$user->setWalletExtension(1);
} elseif ($request->get('extension') === 'metamask') {
$user->setWalletExtension(2);
}
} else {
$user->setActiveWallet(null);
}
$em->persist($user);
$em->flush();
return new Response(json_encode($address));
}
#[Route('/api/user/wallet', name: 'api_user_wallet')]
public function getConnectedWallet()
{
$user = $this->getUser();
if($user->getActiveWallet()) {
$address = $user->getActiveWallet()->getAddress();
return new Response($address);
} else {
return new Response("Unauthorized");
}
}
// Save User config settings
#[Route('/api/user/{userId}/config', name: 'api_user_config')]
public function saveUserConfig(Request $request, $userId)
{
$em = $this->doctrine->getManager();
$user = $em->getRepository(User::class)->findOneBy(array('id' => $userId));
$config = $user->getConfig();
// If new parameters are passed
$newConfig = json_decode($request->getContent(), true);
if($newConfig) {
$user->setConfig($newConfig);
$em->persist($user);
$em->flush();
$config = $newConfig;
}
return new Response (
json_encode($config),
Response::HTTP_OK,
['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
);
}
#[Route('/user/notifications', name: 'user_notifications')]
function getNotifications() {
$em = $this->doctrine->getManager();
$user = $this->getUser();
$marketItemNotifications = $em->getRepository(MarketItem::class)->findAllByUser($user, true, true);
$marketOfferNotifications = $em->getRepository(MarketOffer::class)->findAllByUser($user, false, true);
$index = 0;
$response = [];
for($i=0; $i<count($marketItemNotifications); $i++)
{
$response[$index]['type'] = 'new-sale';
$response[$index]['id'] = $marketItemNotifications[$i]->getId();
$response[$index]['price'] = $marketItemNotifications[$i]->getPrice();
$response[$index]['date'] = $marketItemNotifications[$i]->getUpdatedAt();
$response[$index]['nft'] = $marketItemNotifications[$i]->getNftHub()->getNftMetadata()->getTemplate()->getName();
$response[$index]['nftId'] = $marketItemNotifications[$i]->getNftHub()->getId();
$index += 1;
}
for($i=0; $i<count($marketOfferNotifications); $i++)
{
$response[$index]['type'] = 'new-offer';
$response[$index]['id'] = $marketOfferNotifications[$i]->getId();
$response[$index]['price'] = $marketOfferNotifications[$i]->getPrice();
$response[$index]['date'] = $marketOfferNotifications[$i]->getUpdatedAt();
$response[$index]['nft'] = $marketOfferNotifications[$i]->getNftHub()->getNftMetadata()->getTemplate()->getName();
$response[$index]['nftId'] = $marketOfferNotifications[$i]->getNftHub()->getId();
$index += 1;
}
return new Response (
json_encode($response),
Response::HTTP_OK,
['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
);
}
#[Route('/user/notifications/clear', name: 'user_notifications_clear')]
function clearAllNotifications() {
$em = $this->doctrine->getManager();
$user = $this->getUser();
$clearStatus = $em->getRepository(MarketItem::class)->clearAllMarketNotifications($user);
$em->getRepository(MarketOffer::class)->clearAllMarketOfferNotifications($user);
return new Response (
json_encode($clearStatus),
Response::HTTP_OK,
['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
);
}
#[Route('/api/user/update-thetadrop-wallet', name: 'api_user_update_thetadrop_wallet')]
function updateThetaDropWallet(Request $request) {
$em = $this->doctrine->getManager();
$params = $request->request->all();
$user = $this->getUser();
$thetaWallet = $em->getRepository(ThetaWallet::class)->findOneBy(['address' => $params['walletAddress']]);
// If wallet not found in database, create
if($thetaWallet === null) {
$thetaWallet = new ThetaWallet();
$thetaWallet->setAddress($params['walletAddress']);
}
$user->setThetaDropWallet($thetaWallet);
$em->persist($thetaWallet);
$em->persist($user);
$em->flush();
return new Response (
json_encode('success'),
Response::HTTP_OK,
['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
);
}
function generateRandomString($length = 25): string
{
$characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
}