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>
<div className={"flex flex-col gap-2"}>
<FormLabel
label={"Разрешить скачивание"}
labelClassName={"flex"}
formLabelAddon={
<Checkbox
onClick={() => rootStore.setAllowDwnld(!rootStore.allowDwnld)}
checked={rootStore.allowDwnld}
/>
}
/>
<FormLabel
label={"Разрешить обложку"}
labelClassName={"flex"}

View File

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

View File

@ -1,15 +1,15 @@
import ReactPlayer from "react-player/lazy";
import { useTonConnectUI } from "@tonconnect/ui-react";
import { useWebApp } from "@vkruglikov/react-telegram-web-app";
import ReactPlayer from 'react-player/lazy';
import { useTonConnectUI } from '@tonconnect/ui-react';
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, useEffect, useMemo, useState} from "react";
import { AudioPlayer } from "~/shared/ui/audio-player";
import {useAuth} from "~/shared/services/auth";
import { CongratsModal } from "./components/congrats-modal";
import { ErrorModal } from "./components/error-modal";
import { Button } from '~/shared/ui/button';
import { usePurchaseContent, useViewContent } from '~/shared/services/content';
import { fromNanoTON } from '~/shared/utils';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { AudioPlayer } from '~/shared/ui/audio-player';
import { useAuth } from '~/shared/services/auth';
import { CongratsModal } from './components/congrats-modal';
import { ErrorModal } from './components/error-modal';
type InvoiceStatus = 'paid' | 'failed' | 'cancelled' | 'pending';
@ -19,37 +19,67 @@ interface InvoiceEvent {
status: InvoiceStatus;
}
export const ViewContentPage = () => {
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 [tonConnectUI] = useTonConnectUI();
const auth = useAuth();
const [isCongratsModal, setIsCongratsModal] = useState(false);
const [isErrorModal, setIsErrorModal] = useState(false);
const handleBuyContentTON = useCallback(async () => {
try {
if (!tonConnectUI.connected) {
await tonConnectUI.openModal();
await auth.mutateAsync();
return
} else {
await auth.mutateAsync()
// Helper function to wait for wallet connection
const waitForConnection = async (timeoutMs = 30000, intervalMs = 500) => {
const startTime = Date.now();
while (Date.now() - startTime < timeoutMs) {
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({
content_address: WebApp.initDataUnsafe?.start_param,
license_type: "resale",
license_type: 'resale',
});
const transactionResponse = await tonConnectUI.sendTransaction({
validUntil: Math.floor(Date.now() / 1000) + 120,
validUntil: Math.floor(Date.now() / 1000) + 86400, // 24 hours
messages: [
{
amount: contentResponse.data.amount,
@ -60,18 +90,18 @@ export const ViewContentPage = () => {
});
if (transactionResponse.boc) {
void refetchContent()
void refetchContent();
setIsCongratsModal(true);
console.log(transactionResponse.boc, "PURCHASED")
console.log(transactionResponse.boc, 'PURCHASED');
} else {
setIsErrorModal(true);
console.error("Transaction failed:", transactionResponse);
console.error('Transaction failed:', transactionResponse);
}
} catch (error) {
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 () => {
try {
@ -94,9 +124,7 @@ export const ViewContentPage = () => {
WebApp.onEvent('invoiceClosed', handleInvoiceClosed);
await WebApp.openInvoice(
content.data.invoice.url,
(status: InvoiceStatus) => {
await WebApp.openInvoice(content.data.invoice.url, (status: InvoiceStatus) => {
console.log('Invoice status:', status);
if (status === 'paid') {
void refetchContent();
@ -104,8 +132,7 @@ export const ViewContentPage = () => {
} 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
}
}
);
});
return () => {
WebApp.offEvent('invoiceClosed', handleInvoiceClosed);
@ -118,15 +145,18 @@ export const ViewContentPage = () => {
const haveLicense = useMemo(() => {
document.title = content?.data?.display_options?.metadata?.name;
return content?.data?.have_licenses?.includes("listen") || content?.data?.have_licenses?.includes("resale");
}, [content])
return (
content?.data?.have_licenses?.includes('listen') ||
content?.data?.have_licenses?.includes('resale')
);
}, [content]);
useEffect(() => {
const interval = setInterval(() => {
void refetchContent()
}, 5000)
void refetchContent();
}, 5000);
return () => clearInterval(interval)
return () => clearInterval(interval);
}, []);
const handleConfirmCongrats = () => {
@ -135,71 +165,99 @@ export const ViewContentPage = () => {
const handleErrorModal = () => {
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 (
<main className={"min-h-screen flex w-full flex-col gap-[50px] px-4 "}>
{isCongratsModal && <CongratsModal
onConfirm={handleConfirmCongrats}/>}
{isErrorModal && <ErrorModal
onConfirm={handleErrorModal}/>}
{content?.data?.content_type.startsWith("audio") && content?.data?.display_options?.metadata?.image && (
<div className={"mt-[30px] h-[314px] w-full"}>
<main className={'min-h-screen flex w-full flex-col gap-[50px] px-4 '}>
{isCongratsModal && <CongratsModal onConfirm={handleConfirmCongrats} />}
{isErrorModal && <ErrorModal onConfirm={handleErrorModal} />}
{content?.data?.content_type.startsWith('audio') &&
content?.data?.display_options?.metadata?.image && (
<div className={'mt-[30px] h-[314px] w-full'}>
<img
alt={"content_image"}
className={"h-full w-full object-cover object-center"}
alt={'content_image'}
className={'h-full w-full object-cover object-center'}
src={content?.data?.display_options?.metadata?.image}
/>
</div>
)}
{content?.data?.content_type.startsWith("audio") ? (
{content?.data?.content_type.startsWith('audio') ? (
<AudioPlayer src={content?.data?.display_options?.content_url} />
) : (
<ReactPlayer
playsinline={true}
controls={true}
width="100%"
config={{ file: { attributes: {
playsInline: true, autoplay: true,
poster: content?.data?.display_options?.metadata?.image || undefined,
} }, }}
config={{
file: {
attributes: {
playsInline: true,
autoPlay: true,
poster:
content?.data?.display_options?.metadata?.image || undefined,
},
},
}}
url={content?.data?.display_options?.content_url}
/>
)}
<section className={"flex flex-col"}>
<h1 className={"text-[20px] font-bold"}>
<section className={'flex flex-col'}>
<h1 className={'text-[20px] font-bold'}>
{content?.data?.display_options?.metadata?.name}
</h1>
{/*<h2>Russian</h2>*/}
{/*<h2>2022</h2>*/}
<p className={"mt-2 text-[12px]"}>
<p className={'mt-2 text-[12px]'}>
{content?.data?.display_options?.metadata?.description}
</p>
</section>
<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
onClick={handleBuyContentTON}
className={"mb-4 h-[48px] px-2"}
className={'mb-4 h-[48px] px-2'}
label={`Купить за ${fromNanoTON(content?.data?.encrypted?.license?.resale?.price)} ТОН`}
includeArrows={content?.data?.invoice ? false : true}
/>
{content?.data?.invoice && (
<Button
onClick={handleBuyContentStars}
className={"mb-4 h-[48px] px-2"}
className={'mb-4 h-[48px] px-2'}
label={`Купить за ${content?.data?.invoice?.amount} ⭐️`}
/>
)}
</div>
}
)}
<Button
onClick={() => {
WebApp.openTelegramLink(`https://t.me/MY_UploaderRobot`);
}}
className={"h-[48px] bg-darkred"}
className={'h-[48px] bg-darkred'}
label={`Загрузить свой контент`}
/>
{tonConnectUI.connected && (
@ -207,7 +265,7 @@ export const ViewContentPage = () => {
onClick={() => {
tonConnectUI.disconnect();
}}
className={"h-[48px] bg-darkred mt-4"}
className={'h-[48px] bg-darkred mt-4'}
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;
@ -7,7 +7,7 @@ export const request = axios.create({
});
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) {
config.headers.Authorization = auth_v1_token;

View File

@ -1,10 +1,10 @@
import { useRef } from "react";
import { useTonConnectUI } from "@tonconnect/ui-react";
import { useMutation } from "react-query";
import { request } from "~/shared/libs";
import { useWebApp } from "@vkruglikov/react-telegram-web-app";
import { useRef } from 'react';
import { useTonConnectUI } from '@tonconnect/ui-react';
import { useMutation } from 'react-query';
import { request } from '~/shared/libs';
import { useWebApp } from '@vkruglikov/react-telegram-web-app';
const sessionStorageKey = "auth_v1_token";
const sessionStorageKey = 'auth_v1_token';
const payloadTTLMS = 1000 * 60 * 20;
export const useAuth = () => {
@ -15,12 +15,12 @@ export const useAuth = () => {
const waitForWalletProof = async () => {
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 currentWallet = tonConnectUI.wallet;
if (
currentWallet?.connectItems?.tonProof &&
!("error" in currentWallet.connectItems.tonProof)
!('error' in currentWallet.connectItems.tonProof)
) {
clearInterval(checkProof);
clearTimeout(timeout);
@ -44,34 +44,40 @@ export const useAuth = () => {
ton_balance: string;
};
auth_v1_token: string;
}>("/auth.twa", params);
}>('/auth.twa', params);
if (res?.data?.auth_v1_token) {
localStorage.setItem(sessionStorageKey, res.data.auth_v1_token);
} else {
throw new Error("Failed to get auth token");
throw new Error('Failed to get auth token');
}
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);
console.log("DEBUG: Starting auth flow");
let authResult;
console.log('DEBUG: Starting auth flow');
// Case 1: Not connected - need to connect and get proof
if (!tonConnectUI.connected) {
console.log("DEBUG: No wallet connection, starting flow");
console.log('DEBUG: No wallet connection, starting flow');
localStorage.removeItem(sessionStorageKey);
const refreshPayload = async () => {
tonConnectUI.setConnectRequestParameters({ state: "loading" });
const value = await request.post<{ auth_v1_token: string }>("/auth.twa", {
tonConnectUI.setConnectRequestParameters({ state: 'loading' });
const value = await request.post<{ auth_v1_token: string }>('/auth.twa', {
twa_data: WebApp.initData,
});
if (value?.data?.auth_v1_token) {
tonConnectUI.setConnectRequestParameters({
state: "ready",
state: 'ready',
value: { tonProof: value.data.auth_v1_token },
});
} else {
@ -83,17 +89,30 @@ export const useAuth = () => {
interval.current = setInterval(refreshPayload, payloadTTLMS);
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,
ton_proof: {
account: tonConnectUI.wallet!.account,
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:
// 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
@ -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;
authors: string[];
royaltyParams: Royalty[];
downloadable: boolean;
};
export const useCreateNewContent = () => {

View File

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