Skip to content

Commit

Permalink
Merge pull request #245 from thanhdanh27600/dev
Browse files Browse the repository at this point in the history
upgrade donate
  • Loading branch information
thanhdanh27600 authored Mar 20, 2024
2 parents 984649f + 10a2c0e commit ad24b3f
Show file tree
Hide file tree
Showing 16 changed files with 104 additions and 24 deletions.
Binary file added public/assets/wise-bank.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 2 additions & 1 deletion public/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -125,5 +125,6 @@
"clicksByCountry": "Clicks by Country",
"otherCountry": "Others",
"file": "File",
"uploadFile": "Upload file"
"uploadFile": "Upload file",
"donateDetail": "I personally spend $10 per day to maintain my server. Your help would be greatly appreciated. 🙏"
}
3 changes: 2 additions & 1 deletion public/locales/fr/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,5 +126,6 @@
"uploadFile": "Charger un fichier",
"fileSuccess": "C'était rapide ! Le fichier a été téléchargé avec succès.",
"generateNoteMore": "Créer une autre note",
"generateFileMore": "Télécharger un autre fichier"
"generateFileMore": "Télécharger un autre fichier",
"donateDetail": "Je dépense personnellement 10 $ par jour pour maintenir mon serveur. Votre aide serait grandement appréciée. 🙏"
}
3 changes: 2 additions & 1 deletion public/locales/hi/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,5 +126,6 @@
"uploadFile": "फ़ाइल अपलोड करें",
"fileSuccess": "इतनी तेज़ी! फ़ाइल सफलतापूर्वक अपलोड हो गई है।",
"generateNoteMore": "एक और नोट बनाएं",
"generateFileMore": "एक और फ़ाइल अपलोड करें"
"generateFileMore": "एक और फ़ाइल अपलोड करें",
"donateDetail": "मैं व्यक्तिगत रूप से अपने सर्वर को बनाए रखने के लिए प्रतिदिन 10 डॉलर खर्च करता हूं। आपकी मदद को बहुत प्रासंगिक माना जाएगा। 🙏"
}
3 changes: 2 additions & 1 deletion public/locales/ja/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,5 +126,6 @@
"uploadFile": "ファイルをアップロードする",
"fileSuccess": "早いですね!ファイルのアップロードが成功しました。",
"generateNoteMore": "別のメモを作成する",
"generateFileMore": "別のファイルをアップロードする"
"generateFileMore": "別のファイルをアップロードする",
"donateDetail": "私は個人的にサーバーの維持に1日10ドルを費やしています。ご協力いただけると大変ありがたいです。🙏"
}
3 changes: 2 additions & 1 deletion public/locales/vi/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,5 +126,6 @@
"clicksByCountry": "Clicks theo quốc gia",
"otherCountry": "Khác",
"file": "File",
"uploadFile": "Upload file"
"uploadFile": "Upload file",
"donateDetail": "Duy trì server 100k/ngày, ai đó gánh chung không 🙏"
}
3 changes: 2 additions & 1 deletion public/locales/zh/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,5 +126,6 @@
"uploadFile": "上传文件",
"fileSuccess": "太快了!文件已成功上传。",
"generateNoteMore": "创建另一个笔记",
"generateFileMore": "上传另一个文件"
"generateFileMore": "上传另一个文件",
"donateDetail": "我每天个人花费10美元来维护我的服务器。非常感谢您的帮助。🙏"
}
44 changes: 37 additions & 7 deletions src/components/layouts/Footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ import { useTrans } from 'utils/i18next';
export const Footer = ({ className }: { className?: string }) => {
const { t, locale } = useTrans();
const [open, setOpen] = useState(false);
const { shortenSlice } = useBearStore();
const [timeoutButton, setTimeoutButton] = useState(0);
const { shortenSlice, utilitySlice } = useBearStore();

const [shortenHistory] = shortenSlice((state) => [state.shortenHistory]);
const [country] = utilitySlice((state) => [state.country]);

const reportLink = useFeedbackTemplate(FeedbackTemplate.REPORT_LINK);

Expand All @@ -25,36 +27,64 @@ export const Footer = ({ className }: { className?: string }) => {
if (isLocal) return;
const timeout = setTimeout(() => {
setOpen(true);
setTimeoutButton(6);
}, 2000);

return () => {
clearTimeout(timeout);
};
}, [shortenHistory]);

useEffect(() => {
if (!open) return;
const interval = setInterval(() => {
setTimeoutButton((state) => {
if (state === 0) clearInterval(interval);
return state === 0 ? 0 : state - 1;
});
}, 1000);
return () => {
clearInterval(interval);
};
}, [open]);

if (!locale) return null;

return (
<footer className={clsx('gap-4 border-y border-gray-200 px-4 py-4 pt-4 sm:py-8', className)}>
<Modal
id="donate"
title="Donate 🙏"
confirmText={"No, I'm sorry :("}
confirmText={`No, I'm sorry :( ${timeoutButton > 0 ? timeoutButton : ''}`}
hideDismissButton
ConfirmButtonProps={{ ['data-te-modal-dismiss']: true } as any}
ConfirmButtonProps={{ ['data-te-modal-dismiss']: true, disabled: timeoutButton > 0 } as any}
open={open}
blockDismiss>
<p className="text-center text-sm">Duy trì server 10k/ngày, ai đó gánh chung không 🙏🙏🙏</p>
<div className="flex justify-center">
<Image alt="Qr-Bank" src={'/assets/qr-bank.jpg'} width={200} height={0} />
<p className="text-center text-red-500">{t('donateDetail')}</p>
{country === 'VN' && (
<>
<div className="mt-2 flex justify-center">
<Image alt="Qr-Bank" src={'/assets/qr-bank.jpg'} width={200} height={0} />
</div>
<p className="my-4 text-center text-xl font-bold">{`or`}</p>
</>
)}
<div className="mt-2 flex justify-center gap-2">
<a
target="_blank"
href="https://wise.com/pay/r/WERUX911k7Un7LM"
className="inline-flex items-center font-medium hover:text-cyan-600 hover:underline">
<Image className="mr-2" alt="Wise-Bank" src={'/assets/wise-bank.png'} width={120} height={0} /> {`Wise`}
<ArrowUpRight className="mb-2 w-4" />
</a>
</div>
<p className="my-4 text-center text-xl font-bold">{`or`}</p>
<div className="mt-2 flex justify-center">
<a
target="_blank"
href="https://paypal.me/dolph2k"
className="inline-flex items-center font-medium hover:text-cyan-600 hover:underline">
<Image alt="Qr-Momo" src={'/assets/paypal.png'} width={50} height={0} />
<Image className="mr-2" alt="Qr-Paypal" src={'/assets/paypal.png'} width={50} height={0} />
{`Paypal`}
<ArrowUpRight className="mb-2 w-4" />
</a>
Expand Down
1 change: 1 addition & 0 deletions src/controllers/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export * as file from './file';
export * as forward from './forward';
export * as h from './h';
export * as i from './i';
export * as l from './l';
export * as note from './note';
export * as og from './og';
export * as password from './password';
Expand Down
13 changes: 13 additions & 0 deletions src/controllers/l.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import requestIp from 'request-ip';
import { ipLookup } from '../utils/agent';
import { api, originGuard } from '../utils/axios';

export const handler = api(
async (req, res) => {
originGuard(req, res);
const ip = requestIp.getClientIp(req) || '';
const lookupIp = ipLookup(ip) || undefined;
return res.send({ country: lookupIp?.country || '' });
},
['POST'],
);
18 changes: 9 additions & 9 deletions src/pages/[...hash].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { stringify } from 'querystring';
import { useEffect } from 'react';
import { useMutation } from 'react-query';
import requestIp from 'request-ip';
import { getForwardUrl } from 'requests';
import { forwardUrl } from 'requests';
import { BASE_URL_OG, Window, isProduction } from 'types/constants';
import { EVENTS_STATUS, FIREBASE_ANALYTICS_EVENT, MIXPANEL_EVENT } from 'types/utils';
import { encodeBase64 } from 'utils/crypto';
Expand All @@ -28,8 +28,8 @@ interface Props {

const ForwardURL = ({ history, ip, error }: Props) => {
const { t } = useTrans();
const forwardUrl = useMutation(QueryKey.FORWARD, getForwardUrl);
const loading = forwardUrl.isLoading && !forwardUrl.isError;
const mutation = useMutation(QueryKey.FORWARD, forwardUrl);
const loading = mutation.isLoading && !mutation.isError;

const hash = history?.hash;
const url = history?.url;
Expand All @@ -46,7 +46,7 @@ const ForwardURL = ({ history, ip, error }: Props) => {
// start client-side forward
setTimeout(
() => {
forwardUrl.mutate({
mutation.mutate({
hash: hash,
userAgent: navigator.userAgent,
ip,
Expand All @@ -61,7 +61,7 @@ const ForwardURL = ({ history, ip, error }: Props) => {
if (!Window()) {
return;
}
if (forwardUrl.isIdle) {
if (mutation.isIdle) {
return;
}
if (loading) {
Expand All @@ -82,7 +82,7 @@ const ForwardURL = ({ history, ip, error }: Props) => {
hash,
});
location.replace(`${url.includes('http') ? '' : '//'}${url}`);
}, [forwardUrl]);
}, [mutation]);

const encodeTitle = encodeBase64(ogTitle);

Expand Down Expand Up @@ -134,18 +134,18 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
const ip = requestIp.getClientIp(context.req) || '';
const userAgent = context.req.headers['user-agent'] || 'Unknown';
// start server-side forward
const forwardUrl = await getForwardUrl({
const mutation = await forwardUrl({
hash: hash ? (hash[0] as string) : '',
userAgent,
ip,
fromClientSide: false,
});

if (!forwardUrl.history) throw new Error('Cannot found history to forward');
if (!mutation.history) throw new Error('Cannot found history to forward');

return {
props: {
history: forwardUrl.history,
history: mutation.history,
ip,
...(await serverSideTranslations(locale, ['common'])),
},
Expand Down
17 changes: 17 additions & 0 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import axios from 'axios';
import ErrorBoundary from 'components/gadgets/shared/ErrorBoundary';
import mixpanel from 'mixpanel-browser';
import { SessionProvider } from 'next-auth/react';
Expand All @@ -6,15 +7,28 @@ import type { AppProps } from 'next/app';
import { useEffect } from 'react';
import { Toaster } from 'react-hot-toast';
import { QueryClient, QueryClientProvider } from 'react-query';
import { useBearStore } from 'store';
import { MIX_PANEL_TOKEN, Window, isProduction } from 'types/constants';
import { trackLanded } from 'types/utils';
import '../styles/common.scss';
import '../styles/globals.css';

const getLocation = (callback: Function) => async () => {
try {
const response = await axios.post('api/l');
const data = response.data;
callback(data);
} catch (error) {
console.error('Error:', error);
}
};

const queryClient = new QueryClient();

function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps) {
// const { locale } = useTrans();
const { utilitySlice } = useBearStore();
const [setCountry] = utilitySlice((state) => [state.setCountry]);

if (!MIX_PANEL_TOKEN) {
console.error('Mix panel Not found');
Expand All @@ -37,6 +51,9 @@ function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps) {
function gtag(...a: any[]) {
(window as any).dataLayer.push(a);
}
getLocation(({ country }: { country: string }) => {
setCountry(country || 'VN');
})();
gtag('js', new Date());
gtag('config', 'G-LE8KPBMBMD');
}, []);
Expand Down
3 changes: 3 additions & 0 deletions src/pages/api/l.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { l } from 'controllers';
// l = location
export default l.handler;
2 changes: 1 addition & 1 deletion src/requests/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export const updateShortenUrlRequest = async ({
return data as ShortenUrl;
};

export const getForwardUrl = async ({ hash, userAgent, ip, fromClientSide }: ForwardSchema) => {
export const forwardUrl = async ({ hash, userAgent, ip, fromClientSide }: ForwardSchema) => {
const rs = await API.post(`/api/forward`, { hash, userAgent, ip, fromClientSide });
const data = rs.data;
return data as Forward;
Expand Down
4 changes: 4 additions & 0 deletions src/store/utilitySlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@ export enum FeatureTabKey {
export interface UtilitySlice {
featureTab: FeatureTabKey;
setFeatureTab: (tab: string) => void;
country: string;
setCountry: (value: string) => void;
}

const slice: StateCreator<UtilitySlice> = (set, get) => ({
featureTab: '' as any,
setFeatureTab: (tab) => set({ featureTab: tab as FeatureTabKey }),
country: '',
setCountry: (value) => set({ country: value }),
});

const utilitySlice = create(withDevTools(slice, { anonymousActionType: 'UtilitySlice' }));
Expand Down
8 changes: 7 additions & 1 deletion src/utils/axios.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next';
import { Session, getServerSession } from 'next-auth';
import { z } from 'zod';
import { isDebug, isProduction, isTest } from '../types/constants';
import { allowedDomains, isDebug, isProduction, isTest } from '../types/constants';
import HttpStatusCode from './statusCode';

export type Response =
Expand Down Expand Up @@ -67,3 +67,9 @@ export const badRequest = (res: NextApiResponse, message?: string) =>
errorMessage: message ?? 'You have submitted wrong data, please try again',
errorCode: 'BAD_REQUEST',
});

export const originGuard = (req: NextApiRequest, res: NextApiResponse) => {
if (!req.headers.origin || !allowedDomains.includes(req.headers.origin)) {
return res.status(HttpStatusCode.FORBIDDEN).json({ errorMessage: 'Origin Not Allowed' });
}
};

0 comments on commit ad24b3f

Please sign in to comment.