prettier config, dwnld button, dwnld content, chain login > purchase, selectWallet post in useAuth

This commit is contained in:
Verticool 2025-03-16 20:38:43 +06:00
parent 5f4b13d7ba
commit 2351ee51eb
9 changed files with 409 additions and 314 deletions

7
.prettierrc.json Normal file
View File

@ -0,0 +1,7 @@
{
"semi": true,
"singleQuote": true,
"tabWidth": 4,
"printWidth": 100,
"trailingComma": "es5"
}

View File

@ -165,6 +165,16 @@ export const DataStep = ({ nextStep }: DataStepProps) => {
</FormLabel> </FormLabel>
<div className={"flex flex-col gap-2"}> <div className={"flex flex-col gap-2"}>
<FormLabel
label={"Разрешить скачивание"}
labelClassName={"flex"}
formLabelAddon={
<Checkbox
onClick={() => rootStore.setAllowDwnld(!rootStore.allowDwnld)}
checked={rootStore.allowDwnld}
/>
}
/>
<FormLabel <FormLabel
label={"Разрешить обложку"} label={"Разрешить обложку"}
labelClassName={"flex"} labelClassName={"flex"}

View File

@ -75,7 +75,7 @@ export const PresubmitStep = ({ prevStep }: PresubmitStepProps) => {
// Откомментировать при условии того что вы принимаете много авторов // Откомментировать при условии того что вы принимаете много авторов
// следует отметить что вы должны еще откомментровать AuthorsStep в RootPage // следует отметить что вы должны еще откомментровать AuthorsStep в RootPage
// authors: rootStore.authors, // authors: rootStore.authors,
downloadable: rootStore.allowDwnld,
content: fileUploadResult.content_id_v1, content: fileUploadResult.content_id_v1,
image: coverUploadResult.content_id_v1, image: coverUploadResult.content_id_v1,
price: String(rootStore.price * 10 ** 9), price: String(rootStore.price * 10 ** 9),

View File

@ -1,15 +1,15 @@
import ReactPlayer from "react-player/lazy"; import ReactPlayer from 'react-player/lazy';
import { useTonConnectUI } from "@tonconnect/ui-react"; import { useTonConnectUI } from '@tonconnect/ui-react';
import { useWebApp } from "@vkruglikov/react-telegram-web-app"; import { useWebApp } from '@vkruglikov/react-telegram-web-app';
import { Button } from "~/shared/ui/button"; import { Button } from '~/shared/ui/button';
import { usePurchaseContent, useViewContent } from "~/shared/services/content"; import { usePurchaseContent, useViewContent } from '~/shared/services/content';
import { fromNanoTON } from "~/shared/utils"; import { fromNanoTON } from '~/shared/utils';
import {useCallback, useEffect, useMemo, useState} from "react"; import { useCallback, useEffect, useMemo, useState } from 'react';
import { AudioPlayer } from "~/shared/ui/audio-player"; import { AudioPlayer } from '~/shared/ui/audio-player';
import {useAuth} from "~/shared/services/auth"; import { useAuth } from '~/shared/services/auth';
import { CongratsModal } from "./components/congrats-modal"; import { CongratsModal } from './components/congrats-modal';
import { ErrorModal } from "./components/error-modal"; import { ErrorModal } from './components/error-modal';
type InvoiceStatus = 'paid' | 'failed' | 'cancelled' | 'pending'; type InvoiceStatus = 'paid' | 'failed' | 'cancelled' | 'pending';
@ -19,37 +19,67 @@ interface InvoiceEvent {
status: InvoiceStatus; status: InvoiceStatus;
} }
export const ViewContentPage = () => { export const ViewContentPage = () => {
const WebApp = useWebApp(); const WebApp = useWebApp();
const { data: content, refetch: refetchContent } = useViewContent(WebApp.initDataUnsafe?.start_param); const { data: content, refetch: refetchContent } = useViewContent(
WebApp.initDataUnsafe?.start_param
);
const { mutateAsync: purchaseContent } = usePurchaseContent(); const { mutateAsync: purchaseContent } = usePurchaseContent();
const [tonConnectUI] = useTonConnectUI(); const [tonConnectUI] = useTonConnectUI();
const auth = useAuth(); const auth = useAuth();
const [isCongratsModal, setIsCongratsModal] = useState(false); const [isCongratsModal, setIsCongratsModal] = useState(false);
const [isErrorModal, setIsErrorModal] = useState(false); const [isErrorModal, setIsErrorModal] = useState(false);
const handleBuyContentTON = useCallback(async () => { const handleBuyContentTON = useCallback(async () => {
try { try {
if (!tonConnectUI.connected) { // Helper function to wait for wallet connection
await tonConnectUI.openModal(); const waitForConnection = async (timeoutMs = 30000, intervalMs = 500) => {
await auth.mutateAsync(); const startTime = Date.now();
return
} else { while (Date.now() - startTime < timeoutMs) {
await auth.mutateAsync() if (tonConnectUI.connected) {
return true;
}
await new Promise((resolve) => setTimeout(resolve, intervalMs));
} }
return false; // Timed out
};
// If not connected, start connection process
if (!tonConnectUI.connected) {
console.log('DEBUG: Wallet not connected, opening modal');
// Open connection modal
await tonConnectUI.openModal();
// Wait for connection
const connected = await waitForConnection();
if (!connected) {
console.log('DEBUG: Connection timed out or was cancelled');
return;
}
console.log('DEBUG: Connection successful, authenticating');
await auth.mutateAsync();
} else {
// Already connected, just authenticate
await auth.mutateAsync();
}
// Proceed with purchase
console.log('DEBUG: Proceeding with purchase');
const contentResponse = await purchaseContent({ const contentResponse = await purchaseContent({
content_address: WebApp.initDataUnsafe?.start_param, content_address: WebApp.initDataUnsafe?.start_param,
license_type: "resale", license_type: 'resale',
}); });
const transactionResponse = await tonConnectUI.sendTransaction({ const transactionResponse = await tonConnectUI.sendTransaction({
validUntil: Math.floor(Date.now() / 1000) + 120, validUntil: Math.floor(Date.now() / 1000) + 86400, // 24 hours
messages: [ messages: [
{ {
amount: contentResponse.data.amount, amount: contentResponse.data.amount,
@ -60,18 +90,18 @@ export const ViewContentPage = () => {
}); });
if (transactionResponse.boc) { if (transactionResponse.boc) {
void refetchContent() void refetchContent();
setIsCongratsModal(true); setIsCongratsModal(true);
console.log(transactionResponse.boc, "PURCHASED") console.log(transactionResponse.boc, 'PURCHASED');
} else { } else {
setIsErrorModal(true); setIsErrorModal(true);
console.error("Transaction failed:", transactionResponse); console.error('Transaction failed:', transactionResponse);
} }
} catch (error) { } catch (error) {
setIsErrorModal(true); setIsErrorModal(true);
console.error("Error handling Ton Connect subscription:", error); console.error('Error handling Ton Connect subscription:', error);
} }
}, [content, tonConnectUI.connected]); }, [auth, purchaseContent, refetchContent, tonConnectUI, WebApp.initDataUnsafe?.start_param]);
const handleBuyContentStars = useCallback(async () => { const handleBuyContentStars = useCallback(async () => {
try { try {
@ -94,9 +124,7 @@ export const ViewContentPage = () => {
WebApp.onEvent('invoiceClosed', handleInvoiceClosed); WebApp.onEvent('invoiceClosed', handleInvoiceClosed);
await WebApp.openInvoice( await WebApp.openInvoice(content.data.invoice.url, (status: InvoiceStatus) => {
content.data.invoice.url,
(status: InvoiceStatus) => {
console.log('Invoice status:', status); console.log('Invoice status:', status);
if (status === 'paid') { if (status === 'paid') {
void refetchContent(); void refetchContent();
@ -104,8 +132,7 @@ export const ViewContentPage = () => {
} else if (status === 'failed' || status === 'cancelled') { } else if (status === 'failed' || status === 'cancelled') {
// setIsErrorModal(true); // Turn on if need in error modal. Update text in it to match both way of payment errors // setIsErrorModal(true); // Turn on if need in error modal. Update text in it to match both way of payment errors
} }
} });
);
return () => { return () => {
WebApp.offEvent('invoiceClosed', handleInvoiceClosed); WebApp.offEvent('invoiceClosed', handleInvoiceClosed);
@ -118,15 +145,18 @@ export const ViewContentPage = () => {
const haveLicense = useMemo(() => { const haveLicense = useMemo(() => {
document.title = content?.data?.display_options?.metadata?.name; document.title = content?.data?.display_options?.metadata?.name;
return content?.data?.have_licenses?.includes("listen") || content?.data?.have_licenses?.includes("resale"); return (
}, [content]) content?.data?.have_licenses?.includes('listen') ||
content?.data?.have_licenses?.includes('resale')
);
}, [content]);
useEffect(() => { useEffect(() => {
const interval = setInterval(() => { const interval = setInterval(() => {
void refetchContent() void refetchContent();
}, 5000) }, 5000);
return () => clearInterval(interval) return () => clearInterval(interval);
}, []); }, []);
const handleConfirmCongrats = () => { const handleConfirmCongrats = () => {
@ -135,71 +165,99 @@ export const ViewContentPage = () => {
const handleErrorModal = () => { const handleErrorModal = () => {
setIsErrorModal(!isErrorModal); setIsErrorModal(!isErrorModal);
};
const handleDwnldContent = async () => {
try {
const fileUrl = content?.data?.display_options?.content_url;
const fileName = content?.data?.display_options?.metadata?.name || 'content';
const fileFormat = content?.data?.content_type?.contentFormat || '';
await WebApp.downloadFile({
url: fileUrl,
file_name: fileName + fileFormat,
});
} catch (error) {
console.error('Error downloading content:', error);
} }
};
return ( return (
<main className={"min-h-screen flex w-full flex-col gap-[50px] px-4 "}> <main className={'min-h-screen flex w-full flex-col gap-[50px] px-4 '}>
{isCongratsModal && <CongratsModal {isCongratsModal && <CongratsModal onConfirm={handleConfirmCongrats} />}
onConfirm={handleConfirmCongrats}/>} {isErrorModal && <ErrorModal onConfirm={handleErrorModal} />}
{isErrorModal && <ErrorModal {content?.data?.content_type.startsWith('audio') &&
onConfirm={handleErrorModal}/>} content?.data?.display_options?.metadata?.image && (
{content?.data?.content_type.startsWith("audio") && content?.data?.display_options?.metadata?.image && ( <div className={'mt-[30px] h-[314px] w-full'}>
<div className={"mt-[30px] h-[314px] w-full"}>
<img <img
alt={"content_image"} alt={'content_image'}
className={"h-full w-full object-cover object-center"} className={'h-full w-full object-cover object-center'}
src={content?.data?.display_options?.metadata?.image} src={content?.data?.display_options?.metadata?.image}
/> />
</div> </div>
)} )}
{content?.data?.content_type.startsWith("audio") ? ( {content?.data?.content_type.startsWith('audio') ? (
<AudioPlayer src={content?.data?.display_options?.content_url} /> <AudioPlayer src={content?.data?.display_options?.content_url} />
) : ( ) : (
<ReactPlayer <ReactPlayer
playsinline={true} playsinline={true}
controls={true} controls={true}
width="100%" width="100%"
config={{ file: { attributes: { config={{
playsInline: true, autoplay: true, file: {
poster: content?.data?.display_options?.metadata?.image || undefined, attributes: {
} }, }} playsInline: true,
autoPlay: true,
poster:
content?.data?.display_options?.metadata?.image || undefined,
},
},
}}
url={content?.data?.display_options?.content_url} url={content?.data?.display_options?.content_url}
/> />
)} )}
<section className={"flex flex-col"}> <section className={'flex flex-col'}>
<h1 className={"text-[20px] font-bold"}> <h1 className={'text-[20px] font-bold'}>
{content?.data?.display_options?.metadata?.name} {content?.data?.display_options?.metadata?.name}
</h1> </h1>
{/*<h2>Russian</h2>*/} {/*<h2>Russian</h2>*/}
{/*<h2>2022</h2>*/} {/*<h2>2022</h2>*/}
<p className={"mt-2 text-[12px]"}> <p className={'mt-2 text-[12px]'}>
{content?.data?.display_options?.metadata?.description} {content?.data?.display_options?.metadata?.description}
</p> </p>
</section> </section>
<div className="mt-auto pb-2"> <div className="mt-auto pb-2">
{!haveLicense && <div className="flex flex-row gap-4"> {content?.data?.downloadable && (
<Button
onClick={() => handleDwnldContent()}
className={'h-[48px] bg-darkred mb-4'}
label={`Скачать контент`}
/>
)}
{!haveLicense && (
<div className="flex flex-row gap-4">
<Button <Button
onClick={handleBuyContentTON} onClick={handleBuyContentTON}
className={"mb-4 h-[48px] px-2"} className={'mb-4 h-[48px] px-2'}
label={`Купить за ${fromNanoTON(content?.data?.encrypted?.license?.resale?.price)} ТОН`} label={`Купить за ${fromNanoTON(content?.data?.encrypted?.license?.resale?.price)} ТОН`}
includeArrows={content?.data?.invoice ? false : true} includeArrows={content?.data?.invoice ? false : true}
/> />
{content?.data?.invoice && ( {content?.data?.invoice && (
<Button <Button
onClick={handleBuyContentStars} onClick={handleBuyContentStars}
className={"mb-4 h-[48px] px-2"} className={'mb-4 h-[48px] px-2'}
label={`Купить за ${content?.data?.invoice?.amount} ⭐️`} label={`Купить за ${content?.data?.invoice?.amount} ⭐️`}
/> />
)} )}
</div> </div>
} )}
<Button <Button
onClick={() => { onClick={() => {
WebApp.openTelegramLink(`https://t.me/MY_UploaderRobot`); WebApp.openTelegramLink(`https://t.me/MY_UploaderRobot`);
}} }}
className={"h-[48px] bg-darkred"} className={'h-[48px] bg-darkred'}
label={`Загрузить свой контент`} label={`Загрузить свой контент`}
/> />
{tonConnectUI.connected && ( {tonConnectUI.connected && (
@ -207,7 +265,7 @@ export const ViewContentPage = () => {
onClick={() => { onClick={() => {
tonConnectUI.disconnect(); tonConnectUI.disconnect();
}} }}
className={"h-[48px] bg-darkred mt-4"} className={'h-[48px] bg-darkred mt-4'}
label={`Отключить кошелек`} label={`Отключить кошелек`}
/> />
)} )}

View File

@ -1,4 +1,4 @@
import axios from "axios"; import axios from 'axios';
export const APP_API_BASE_URL = import.meta.env.VITE_API_BASE_URL; export const APP_API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
@ -7,7 +7,7 @@ export const request = axios.create({
}); });
request.interceptors.request.use((config) => { request.interceptors.request.use((config) => {
const auth_v1_token = sessionStorage.getItem("auth_v1_token"); const auth_v1_token = localStorage.getItem('auth_v1_token');
if (auth_v1_token) { if (auth_v1_token) {
config.headers.Authorization = auth_v1_token; config.headers.Authorization = auth_v1_token;

View File

@ -1,10 +1,10 @@
import { useRef } from "react"; import { useRef } from 'react';
import { useTonConnectUI } from "@tonconnect/ui-react"; import { useTonConnectUI } from '@tonconnect/ui-react';
import { useMutation } from "react-query"; import { useMutation } from 'react-query';
import { request } from "~/shared/libs"; import { request } from '~/shared/libs';
import { useWebApp } from "@vkruglikov/react-telegram-web-app"; import { useWebApp } from '@vkruglikov/react-telegram-web-app';
const sessionStorageKey = "auth_v1_token"; const sessionStorageKey = 'auth_v1_token';
const payloadTTLMS = 1000 * 60 * 20; const payloadTTLMS = 1000 * 60 * 20;
export const useAuth = () => { export const useAuth = () => {
@ -15,12 +15,12 @@ export const useAuth = () => {
const waitForWalletProof = async () => { const waitForWalletProof = async () => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error("Timeout waiting for proof")), 30000); const timeout = setTimeout(() => reject(new Error('Timeout waiting for proof')), 30000);
const checkProof = setInterval(() => { const checkProof = setInterval(() => {
const currentWallet = tonConnectUI.wallet; const currentWallet = tonConnectUI.wallet;
if ( if (
currentWallet?.connectItems?.tonProof && currentWallet?.connectItems?.tonProof &&
!("error" in currentWallet.connectItems.tonProof) !('error' in currentWallet.connectItems.tonProof)
) { ) {
clearInterval(checkProof); clearInterval(checkProof);
clearTimeout(timeout); clearTimeout(timeout);
@ -44,34 +44,40 @@ export const useAuth = () => {
ton_balance: string; ton_balance: string;
}; };
auth_v1_token: string; auth_v1_token: string;
}>("/auth.twa", params); }>('/auth.twa', params);
if (res?.data?.auth_v1_token) { if (res?.data?.auth_v1_token) {
localStorage.setItem(sessionStorageKey, res.data.auth_v1_token); localStorage.setItem(sessionStorageKey, res.data.auth_v1_token);
} else { } else {
throw new Error("Failed to get auth token"); throw new Error('Failed to get auth token');
} }
return res; return res;
}; };
return useMutation(["auth"], async () => { const makeSelectWalletRequest = async (params: { wallet_address: string }) => {
const res = await request.post('/auth.selectWallet', params);
return res;
};
return useMutation(['auth'], async () => {
clearInterval(interval.current); clearInterval(interval.current);
console.log("DEBUG: Starting auth flow"); let authResult;
console.log('DEBUG: Starting auth flow');
// Case 1: Not connected - need to connect and get proof // Case 1: Not connected - need to connect and get proof
if (!tonConnectUI.connected) { if (!tonConnectUI.connected) {
console.log("DEBUG: No wallet connection, starting flow"); console.log('DEBUG: No wallet connection, starting flow');
localStorage.removeItem(sessionStorageKey); localStorage.removeItem(sessionStorageKey);
const refreshPayload = async () => { const refreshPayload = async () => {
tonConnectUI.setConnectRequestParameters({ state: "loading" }); tonConnectUI.setConnectRequestParameters({ state: 'loading' });
const value = await request.post<{ auth_v1_token: string }>("/auth.twa", { const value = await request.post<{ auth_v1_token: string }>('/auth.twa', {
twa_data: WebApp.initData, twa_data: WebApp.initData,
}); });
if (value?.data?.auth_v1_token) { if (value?.data?.auth_v1_token) {
tonConnectUI.setConnectRequestParameters({ tonConnectUI.setConnectRequestParameters({
state: "ready", state: 'ready',
value: { tonProof: value.data.auth_v1_token }, value: { tonProof: value.data.auth_v1_token },
}); });
} else { } else {
@ -83,17 +89,30 @@ export const useAuth = () => {
interval.current = setInterval(refreshPayload, payloadTTLMS); interval.current = setInterval(refreshPayload, payloadTTLMS);
const tonProof = await waitForWalletProof(); const tonProof = await waitForWalletProof();
console.log("DEBUG: Got initial proof", tonProof); console.log('DEBUG: Got initial proof', tonProof);
return makeAuthRequest({ authResult = await makeAuthRequest({
twa_data: WebApp.initData, twa_data: WebApp.initData,
ton_proof: { ton_proof: {
account: tonConnectUI.wallet!.account, account: tonConnectUI.wallet!.account,
ton_proof: tonProof, ton_proof: tonProof,
}, },
}); });
} else {
// Case 3: Connected without proof - already authenticated
console.log('DEBUG: Connected without proof, proceeding without it');
authResult = await makeAuthRequest({
twa_data: WebApp.initData,
});
} }
if (tonConnectUI.wallet?.account?.address) {
console.log('DEBUG: Selecting wallet', tonConnectUI.wallet.account.address);
await makeSelectWalletRequest({ wallet_address: tonConnectUI.wallet.account.address });
}
return authResult;
// Commented this part for two reasons: // Commented this part for two reasons:
// 1) When we include ton_proof from the wallet it fails the call for a reason of bad ton_proof // 1) When we include ton_proof from the wallet it fails the call for a reason of bad ton_proof
// 2) This call could happen only if the first case happened and it means that the ton_proof is already have been stored once before // 2) This call could happen only if the first case happened and it means that the ton_proof is already have been stored once before
@ -108,11 +127,5 @@ export const useAuth = () => {
// }, // },
// }); // });
// } // }
// Case 3: Connected without proof - already authenticated
console.log("DEBUG: Connected without proof, proceeding without it");
return makeAuthRequest({
twa_data: WebApp.initData,
});
}); });
}; };

View File

@ -14,6 +14,7 @@ type UseCreateNewContentPayload = {
allowResale: boolean; allowResale: boolean;
authors: string[]; authors: string[];
royaltyParams: Royalty[]; royaltyParams: Royalty[];
downloadable: boolean;
}; };
export const useCreateNewContent = () => { export const useCreateNewContent = () => {

View File

@ -24,6 +24,9 @@ type RootStore = {
allowCover: boolean; allowCover: boolean;
setAllowCover: (allowCover: boolean) => void; setAllowCover: (allowCover: boolean) => void;
allowDwnld: boolean;
setAllowDwnld: (allowDwnld: boolean) => void;
cover: File | null; cover: File | null;
setCover: (cover: File | null) => void; setCover: (cover: File | null) => void;
@ -68,6 +71,9 @@ export const useRootStore = create<RootStore>((set) => ({
allowCover: false, allowCover: false,
setAllowCover: (allowCover) => set({ allowCover }), setAllowCover: (allowCover) => set({ allowCover }),
allowDwnld: false,
setAllowDwnld: (allowDwnld) => set({ allowDwnld }),
cover: null, cover: null,
setCover: (cover) => set({ cover }), setCover: (cover) => set({ cover }),