src/Controller/TinyKnightGames/UserController.php line 328

  1. <?php
  2. namespace App\Controller\TinyKnightGames;
  3. use App\Entity\InventoryEquipment;
  4. use App\Entity\MarketItem;
  5. use App\Entity\MarketOffer;
  6. use App\Entity\NftMetadata;
  7. use App\Entity\PlayerRank;
  8. use App\Entity\ThetaWallet;
  9. use App\Entity\User;
  10. use App\Entity\UserGear;
  11. use Doctrine\Persistence\ManagerRegistry;
  12. use Proxies\__CG__\App\Entity\TemplateCategory;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. class UserController extends AbstractController
  18. {
  19.     public function __construct(private ManagerRegistry $doctrine) {}
  20.     #[Route('/user'name'user')]
  21.     public function index(): Response
  22.     {
  23.         return $this->render('user/index.html.twig', [
  24.             'controller_name' => 'UserController',
  25.         ]);
  26.     }
  27.     #[Route('/api/user/rank'name'user')]
  28.     public function getRank(Request $request): Response
  29.     {
  30.         $em $this->doctrine->getManager();
  31.         $params $request->query->all();
  32.         $user $em->getRepository(User::class)->findOneBy(['id' => $params['user_id']]);
  33.         $currentRank $em->getRepository(PlayerRank::class)->findPlayerCurrentRank($user->getExperience());
  34.         $nextRank $em->getRepository(PlayerRank::class)->findPlayerNextRank($user->getExperience());
  35.         // {rank: Trained 0, nextRank: Trained 1, currentXP: 660, nextLevelXP: 1160, salvageTime: 8, afkFishingTime: 2, recipeHint: 4}
  36.         $json $currentRank->getPerks();
  37.         $json['rank'] = $currentRank->getTitle();
  38.         $json['nextRank'] = $nextRank->getTitle();
  39.         $json['prevXpTier'] = $currentRank->getRequiredExp();
  40.         $json['currentExp'] = $user->getExperience();
  41.         $json['nextXpTier'] = $nextRank->getRequiredExp();
  42.         return new Response (
  43.             json_encode($json),
  44.             Response::HTTP_OK,
  45.             ['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
  46.         );
  47.     }
  48.     #[Route('/api/user/authenticated'name'user_authenticated')]
  49.     public function getAuthenticatedUser()
  50.     {
  51.         // Verify User is authenticated
  52.         $response = new Response();
  53.         if($user $this->getUser()) {
  54.             $response->setContent("true");
  55.             return $response;
  56.         } else {
  57.             $response->setContent("false");
  58.             return $response;
  59.         }
  60.     }
  61.     #[Route('/api/user/token'name'user_token')]
  62.     public function getAuthenticatedUserToken()
  63.     {
  64.         $em $this->doctrine->getManager();
  65.         $userInfo = array();
  66.         $user $this->getUser();
  67.         // Verify User is authenticated
  68.         if($user) {
  69.             // Set a new game token on login
  70.             $gameToken hash('sha256'$this->generateRandomString() . $user->getEmail());
  71.             $user->setGameToken($gameToken);
  72.             $em->persist($user);
  73.             $em->flush();
  74.             $userInfo['token'] = $user->getGameToken();
  75.             $userInfo['id'] = $user->getId();
  76.             $userInfo['username'] = $user->getUsername();
  77.             $userInfo['serverTime'] = time();
  78.         }
  79.         return new Response (
  80.             json_encode($userInfo),
  81.             Response::HTTP_OK,
  82.             ['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
  83.         );
  84.     }
  85.     #[Route('/api/ooto/user/token'name'ooto_user_token')]
  86.     public function getOotoAuthenticatedUserToken()
  87.     {
  88.         $em $this->doctrine->getManager();
  89.         $userInfo = array();
  90.         $user $this->getUser();
  91.         // Verify User is authenticated
  92.         if($user) {
  93.             // Set a new game token on login
  94.             $gameToken hash('sha256'$this->generateRandomString() . $user->getEmail());
  95.             $user->setGameToken2($gameToken);
  96.             $em->persist($user);
  97.             $em->flush();
  98.             $userInfo['token'] = $user->getGameToken2();
  99.             $userInfo['id'] = $user->getId();
  100.             $userInfo['username'] = $user->getUsername();
  101.             $userInfo['serverTime'] = time();
  102.         }
  103.         return new Response (
  104.             json_encode($userInfo),
  105.             Response::HTTP_OK,
  106.             ['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
  107.         );
  108.     }
  109.     #[Route('/api/user/{userId}/gear'name'api_user_gear')]
  110.     public function getUserGear(Request $requeststring $userId): Response
  111.     {
  112.         $params $request->query->all();
  113.         $headers $request->headers->all();
  114.         $em $this->doctrine->getManager();
  115.         $user $em->getRepository(User::class)->find($userId);
  116.         // Verify hash
  117.         $userGameToken hash('sha256'$user->getGameToken().$this->getParameter('app.secret'));
  118.         $apiGameToken $headers['gametoken'][0];
  119.         // Authenticate request
  120.         if ($userGameToken != $apiGameToken) {
  121.             return new Response("Authentication failed.");
  122.         }
  123.         $userInventoryEquipment $em->getRepository(UserGear::class)->findInventoryEquipmentByUser($user);
  124.         $userNftEquipment $em->getRepository(UserGear::class)->findNftEquipmentByUser($user);
  125. //        $userNftCatchable = $em->getRepository(UserGear::class)->findNftCatchableByUser($user);
  126.         foreach ($userInventoryEquipment as $key => $equipment) {
  127.             $userInventoryEquipment[$key]['isNft'] = false;
  128.         }
  129.         foreach ($userNftEquipment as $key => $nftEquipment) {
  130.             $userNftEquipment[$key]['isNft'] = true;
  131.         }
  132. //        if(!empty($userNftCatchable)) {
  133. //            $userNftCatchable['isNft'] = true;
  134. //            $userNftCatchable['category'] = 'Charm';
  135. //        }
  136.         $userGear array_merge($userInventoryEquipment$userNftEquipment);
  137.         // Include Charm if equipped
  138. //        $userCharm = array($userNftCatchable); // Needs to be in an array to format the JSON properly
  139. //        if(isset($userCharm[0])) {
  140. //            $userGear = array_merge($userGear, $userCharm);
  141. //        }
  142.         return new Response (
  143.             json_encode($userGear),
  144.             Response::HTTP_OK,
  145.             ['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
  146.         );
  147.     }
  148.     #[Route('/api/inventory/{userId}/equipment/{equipmentId}/update/status'name'inventory_equipment_update_status')]
  149.     public function updateInventoryEquipmentStatus(Request $requeststring $userIdstring $equipmentId): Response
  150.     {
  151.         // method [equip, unequip], hash, isNft, isCharm
  152.         $params $request->query->all();
  153.         $headers $request->headers->all();
  154.         // TODO: Verify that we have all required parameters
  155.         $em $this->doctrine->getManager();
  156.         $user $em->getRepository(User::class)->find($userId);
  157.         // Verify Hash
  158. //        $userGameToken = hash('sha256', $user->getGameToken().$this->getParameter('app.secret'));
  159. //        $apiGameToken = $headers['gametoken'][0];
  160. //
  161. //        // Authenticate request
  162. //        if ($userGameToken != $apiGameToken) {
  163. //            return new Response("Authentication failed.");
  164. //        }
  165.         if (array_key_exists('isNft',$params) && $params['isNft'] == "true") {
  166.             if (array_key_exists('isCharm',$params) && $params['isCharm'] == 'true')
  167.             {
  168.                 // Verify that the User has the NFT Equipment (Charm)
  169.                 $nftCatchable $em->getRepository(NftMetadata::class)->verifyOwnership($user$equipmentId);
  170.                 if (empty($nftCatchable)) {
  171.                     return new Response ("This User does not possess this piece of NFT equipment. ( ID: " $equipmentId " )");
  172.                 }
  173.                 $category $em->getRepository(TemplateCategory::class)->findOneBy(array('name' => 'Charm'));
  174.                 $userGear $em->getRepository(UserGear::class)->findOneBy(array('user' => $user'templateCategory' => $category));
  175.                 // Equip / Unequip
  176.                 if ($params['method'] == 'equip') {
  177.                     $userGear->setInventoryEquipment(null); // Make sure we don't also have regular equipment equipped
  178.                     $userGear->setNftMetadata($nftCatchable);
  179.                 } elseif($params['method'] == 'unequip') {
  180.                     $userGear->setNftMetadata(null);
  181.                 }
  182.             } else {
  183.                 // Otherwise we are just equipping normal NFT Equipment
  184.                 // Verify that the User has the NFT Equipment
  185.                 $nftEquipment $em->getRepository(NftMetadata::class)->verifyOwnership($user$equipmentId);
  186.                 if (empty($nftEquipment)) {
  187.                     return new Response ("This User does not possess this piece of NFT equipment. ( ID: " $equipmentId " )");
  188.                 }
  189.                 $category $nftEquipment->getTemplate()->getCategory();
  190.                 $userGear $em->getRepository(UserGear::class)->findOneBy(array('user' => $user'templateCategory' => $category));
  191.                 // Equip / Unequip
  192.                 if ($params['method'] == 'equip') {
  193.                     $userGear->setInventoryEquipment(null); // Make sure we don't also have regular equipment equipped
  194.                     $userGear->setNftMetadata($nftEquipment);
  195.                 } elseif($params['method'] == 'unequip') {
  196.                     $userGear->setNftMetadata(null);
  197.                 }
  198.             }
  199.         } elseif(!array_key_exists('isNft',$params) || $params['isNft'] == "false") {
  200.             // Verify that User has Equipment
  201.             $inventoryEquipment $em->getRepository(InventoryEquipment::class)
  202.                 ->findOneBy(array('user' => $userId'id' => $equipmentId));
  203.             if (empty($inventoryEquipment)) {
  204.                 return new Response ("User does not possess this piece of equipment. ( ID: " $equipmentId " )");
  205.             }
  206.             $category $inventoryEquipment->getTemplate()->getCategory();
  207.             $userGear $em->getRepository(UserGear::class)->findOneBy(array('user' => $user'templateCategory' => $category));
  208.             // Equip / Unequip
  209.             if ($params['method'] == 'equip') {
  210.                 $userGear->setInventoryEquipment($inventoryEquipment);
  211.                 $userGear->setNftMetadata(null); // Make sure we don't also have NFT equipment equipped
  212.             } elseif ($params['method'] == 'unequip') {
  213.                 $userGear->setInventoryEquipment(null);
  214.             }
  215.         }
  216.         $em->persist($userGear);
  217.         $em->flush();
  218.         return new Response (
  219.             json_encode(array('response' => 'Equipment updated successfully')),
  220.             Response::HTTP_OK,
  221.             ['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
  222.         );
  223.     }
  224.     #[Route('/api/user/wallet/update'name'api_user_wallet_update')]
  225.     public function updateConnectedWallet(Request $request)
  226.     {
  227.         $em $this->doctrine->getManager();
  228.         $user $this->getUser();
  229.         // get Address from request
  230.         $address $request->get('address');
  231.         if($address !== '') {
  232.             // See if wallet exists in database
  233.             $wallet $em->getRepository(ThetaWallet::class)->findOneBy(array('address' => $address));
  234.             if ($wallet === null) {
  235.                 $newWallet = new ThetaWallet();
  236.                 $newWallet->setAddress($address);
  237.                 $user->setActiveWallet($newWallet);
  238.                 $em->persist($user);
  239.                 $em->persist($newWallet);
  240.             } else {
  241.                 $existingUser $em->getRepository(User::class)->findOneBy(array('activeWallet' => $wallet));
  242.                 if($existingUser !== null) {
  243.                     $existingUser->setActiveWallet(null);
  244.                     $em->persist($existingUser);
  245.                     $em->flush();
  246.                 }
  247.                  $user->setActiveWallet($wallet);
  248.             }
  249.             if ($request->get('extension') === 'thetawallet') {
  250.                 $user->setWalletExtension(1);
  251.             } elseif ($request->get('extension') === 'metamask') {
  252.                 $user->setWalletExtension(2);
  253.             }
  254.         } else {
  255.             $user->setActiveWallet(null);
  256.         }
  257.         $em->persist($user);
  258.         $em->flush();
  259.         return new Response(json_encode($address));
  260.     }
  261.     #[Route('/api/user/wallet'name'api_user_wallet')]
  262.     public function getConnectedWallet()
  263.     {
  264.         $user $this->getUser();
  265.         if($user->getActiveWallet()) {
  266.             $address $user->getActiveWallet()->getAddress();
  267.             return new Response($address);
  268.         } else {
  269.             return new Response("Unauthorized");
  270.         }
  271.     }
  272.     // Save User config settings
  273.     #[Route('/api/user/{userId}/config'name'api_user_config')]
  274.     public function saveUserConfig(Request $request$userId)
  275.     {
  276.         $em $this->doctrine->getManager();
  277.         $user $em->getRepository(User::class)->findOneBy(array('id' => $userId));
  278.         $config $user->getConfig();
  279.         // If new parameters are passed
  280.         $newConfig json_decode($request->getContent(), true);
  281.         if($newConfig) {
  282.             $user->setConfig($newConfig);
  283.             $em->persist($user);
  284.             $em->flush();
  285.             $config $newConfig;
  286.         }
  287.         return new Response (
  288.             json_encode($config),
  289.             Response::HTTP_OK,
  290.             ['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
  291.         );
  292.     }
  293.     #[Route('/user/notifications'name'user_notifications')]
  294.     function getNotifications() {
  295.         $em $this->doctrine->getManager();
  296.         $user $this->getUser();
  297.         $marketItemNotifications $em->getRepository(MarketItem::class)->findAllByUser($usertruetrue);
  298.         $marketOfferNotifications $em->getRepository(MarketOffer::class)->findAllByUser($userfalsetrue);
  299.         $index 0;
  300.         $response = [];
  301.         for($i=0$i<count($marketItemNotifications); $i++)
  302.         {
  303.             $response[$index]['type'] = 'new-sale';
  304.             $response[$index]['id'] = $marketItemNotifications[$i]->getId();
  305.             $response[$index]['price'] = $marketItemNotifications[$i]->getPrice();
  306.             $response[$index]['date'] = $marketItemNotifications[$i]->getUpdatedAt();
  307.             $response[$index]['nft'] = $marketItemNotifications[$i]->getNftHub()->getNftMetadata()->getTemplate()->getName();
  308.             $response[$index]['nftId'] = $marketItemNotifications[$i]->getNftHub()->getId();
  309.             $index += 1;
  310.         }
  311.         for($i=0$i<count($marketOfferNotifications); $i++)
  312.         {
  313.             $response[$index]['type'] = 'new-offer';
  314.             $response[$index]['id'] = $marketOfferNotifications[$i]->getId();
  315.             $response[$index]['price'] = $marketOfferNotifications[$i]->getPrice();
  316.             $response[$index]['date'] = $marketOfferNotifications[$i]->getUpdatedAt();
  317.             $response[$index]['nft'] = $marketOfferNotifications[$i]->getNftHub()->getNftMetadata()->getTemplate()->getName();
  318.             $response[$index]['nftId'] = $marketOfferNotifications[$i]->getNftHub()->getId();
  319.             $index += 1;
  320.         }
  321.         return new Response (
  322.             json_encode($response),
  323.             Response::HTTP_OK,
  324.             ['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
  325.         );
  326.     }
  327.     #[Route('/user/notifications/clear'name'user_notifications_clear')]
  328.     function clearAllNotifications() {
  329.         $em $this->doctrine->getManager();
  330.         $user $this->getUser();
  331.         $clearStatus $em->getRepository(MarketItem::class)->clearAllMarketNotifications($user);
  332.         $em->getRepository(MarketOffer::class)->clearAllMarketOfferNotifications($user);
  333.         return new Response (
  334.             json_encode($clearStatus),
  335.             Response::HTTP_OK,
  336.             ['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
  337.         );
  338.     }
  339.     #[Route('/api/user/update-thetadrop-wallet'name'api_user_update_thetadrop_wallet')]
  340.     function updateThetaDropWallet(Request $request) {
  341.         $em $this->doctrine->getManager();
  342.         $params $request->request->all();
  343.         $user $this->getUser();
  344.         $thetaWallet $em->getRepository(ThetaWallet::class)->findOneBy(['address' => $params['walletAddress']]);
  345.         // If wallet not found in database, create
  346.         if($thetaWallet === null) {
  347.             $thetaWallet = new ThetaWallet();
  348.             $thetaWallet->setAddress($params['walletAddress']);
  349.         }
  350.         $user->setThetaDropWallet($thetaWallet);
  351.         $em->persist($thetaWallet);
  352.         $em->persist($user);
  353.         $em->flush();
  354.         return new Response (
  355.             json_encode('success'),
  356.             Response::HTTP_OK,
  357.             ['Access-Control-Allow-Origin: https://fishersquest.tinyknightgames.com/unity']
  358.         );
  359.     }
  360.     function generateRandomString($length 25): string
  361.     {
  362.         $characters "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  363.         $charactersLength strlen($characters);
  364.         $randomString '';
  365.         for ($i 0$i $length$i++) {
  366.             $randomString .= $characters[rand(0$charactersLength 1)];
  367.         }
  368.         return $randomString;
  369.     }
  370. }