| Fixed price and add button to upload own content

This commit is contained in:
rakhimovkamran 2024-09-13 17:47:02 +05:00
parent 9cef81a3c1
commit 0531e60222
2 changed files with 80 additions and 44 deletions

View File

@ -5,13 +5,13 @@ import { useWebApp } from "@vkruglikov/react-telegram-web-app";
import { Button } from "~/shared/ui/button";
import { usePurchaseContent, useViewContent } from "~/shared/services/content";
import { fromNanoTON } from "~/shared/utils";
import { useCallback } from "react";
import {useCallback, useEffect, useMemo} from "react";
import { AudioPlayer } from "~/shared/ui/audio-player";
export const ViewContentPage = () => {
const WebApp = useWebApp();
const { data: content } = useViewContent(WebApp.initDataUnsafe?.start_param);
const { data: content, refetch: refetchContent } = useViewContent(WebApp.initDataUnsafe?.start_param);
const { mutateAsync: purchaseContent } = usePurchaseContent();
@ -50,6 +50,20 @@ export const ViewContentPage = () => {
}
}, [content]);
const haveLicense = useMemo(() => {
return content?.data?.have_licenses?.includes("listen") || content?.data?.have_licenses?.includes("resale")
}, [content])
useEffect(() => {
const interval = setInterval(() => {
void refetchContent()
}, 5000)
return () => clearInterval(interval)
}, []);
return (
<main className={"flex w-full flex-col gap-[50px] px-4"}>
{content?.data?.display_options?.metadata?.image && (
@ -69,7 +83,7 @@ export const ViewContentPage = () => {
playsinline={true}
controls={true}
width="100%"
config={{ file: { attributes: { playsInline: true } } }}
config={{ file: { attributes: { playsInline: true, } }, }}
url={content?.data?.display_options?.content_url}
/>
)}
@ -85,12 +99,13 @@ export const ViewContentPage = () => {
</p>
</section>
<Button
{!haveLicense && <Button
onClick={handleBuyContent}
className={"mb-4 mt-[30px] h-[48px]"}
label={`Купить за ${fromNanoTON(content?.data?.encrypted?.license?.resale?.price)} ТОН`}
includeArrows={true}
/>
}
<Button
onClick={() => {

View File

@ -4,7 +4,7 @@ import { useMutation } from "react-query";
import { request } from "~/shared/libs";
import { useWebApp } from "@vkruglikov/react-telegram-web-app";
const sessionStorageKey = "auth_v1_token";
const localStorageKey = "auth_v1_token";
const payloadTTLMS = 1000 * 60 * 20;
export const useAuth = () => {
@ -16,25 +16,32 @@ export const useAuth = () => {
return useMutation(["auth"], async () => {
clearInterval(interval.current);
// Проверяем токен в localStorage
const storedToken = localStorage.getItem(localStorageKey);
// Если нет кошелька, удаляем токен и запрашиваем новый
if (!wallet) {
sessionStorage.removeItem(sessionStorageKey);
localStorage.removeItem(localStorageKey);
const refreshPayload = async () => {
tonConnectUI.setConnectRequestParameters({ state: "loading" });
const value = await request
.post<{
auth_v1_token: string;
}>("/auth.twa", {
twa_data: WebApp.initData,
})
.catch((error: any) => {
console.error("Error in authentication request: ", error);
throw new Error("Failed to authenticate.");
});
.post<{
auth_v1_token: string;
}>("/auth.twa", {
twa_data: WebApp.initData,
})
.catch((error: any) => {
console.error("Error in authentication request: ", error);
throw new Error("Failed to authenticate.");
});
if (!value) {
tonConnectUI.setConnectRequestParameters(null);
} else {
// Сохраняем токен в localStorage
localStorage.setItem(localStorageKey, value.data.auth_v1_token);
tonConnectUI.setConnectRequestParameters({
state: "ready",
value: {
@ -44,46 +51,60 @@ export const useAuth = () => {
}
};
// Обновляем токен каждые 20 минут
void refreshPayload();
setInterval(refreshPayload, payloadTTLMS);
interval.current = setInterval(refreshPayload, payloadTTLMS);
return;
}
// Если токен уже сохранён в localStorage, пропускаем повторную авторизацию
if (storedToken) {
tonConnectUI.setConnectRequestParameters({
state: "ready",
value: {
tonProof: storedToken,
},
});
return;
}
// Логика для случая, когда есть кошелек и требуется тонProof
if (
wallet.connectItems?.tonProof &&
!("error" in wallet.connectItems.tonProof)
wallet.connectItems?.tonProof &&
!("error" in wallet.connectItems.tonProof)
) {
const tonProof = wallet.connectItems.tonProof.proof;
console.log("DEBUG TON-PROOF", tonProof);
request
.post<{
connected_wallet: null | {
version: string;
address: string;
ton_balance: string;
};
auth_v1_token: string;
}>("/auth.twa", {
twa_data: WebApp.initData,
ton_proof: {
account: wallet.account,
ton_proof: tonProof,
},
})
.then((res) => {
if (res?.data?.auth_v1_token) {
sessionStorage.setItem(sessionStorageKey, res?.data?.auth_v1_token);
} else {
alert("Please try another wallet");
}
})
.catch((error: any) => {
console.error("Error in authentication request: ", error);
throw new Error("Failed to authenticate.");
});
.post<{
connected_wallet: null | {
version: string;
address: string;
ton_balance: string;
};
auth_v1_token: string;
}>("/auth.twa", {
twa_data: WebApp.initData,
ton_proof: {
account: wallet.account,
ton_proof: tonProof,
},
})
.then((res) => {
if (res?.data?.auth_v1_token) {
// Сохраняем токен в localStorage
localStorage.setItem(localStorageKey, res?.data?.auth_v1_token);
} else {
alert("Please try another wallet");
}
})
.catch((error: any) => {
console.error("Error in authentication request: ", error);
throw new Error("Failed to authenticate.");
});
}
});
};