This commit is contained in:
mei 2024-11-27 13:10:36 +08:00
parent 03c76dae5c
commit 0a343b8b35
8 changed files with 287 additions and 149 deletions

0
Dockerfile Normal file
View File

View File

@ -1,17 +1,27 @@
import { NextResponse } from 'next/server';
import { getLongUrl, getUrlStats } from '@/lib/db';
import { NextResponse } from 'next/server'
import { getLongUrl, getUrlStats } from '@/lib/db'
export async function GET(
request: Request,
{ params }: { params: { shortCode: string } }
) {
const { longUrl, expired } = getLongUrl(params.shortCode);
const stats = getUrlStats(params.shortCode);
try {
const { longUrl, expired } = getLongUrl(params.shortCode)
const stats = getUrlStats(params.shortCode)
if (longUrl) {
return NextResponse.json({ longUrl, expired, stats });
} else {
return NextResponse.json({ longUrl: null, expired, stats: null }, { status: 404 });
}
if (!longUrl) {
return NextResponse.json(
{ error: 'URL not found', expired },
{ status: 404 }
)
}
return NextResponse.json({ longUrl, expired, stats })
} catch (error) {
console.error('Error fetching URL:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}

View File

@ -14,8 +14,8 @@ const geistMono = localFont({
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
title: "Url Shortener",
description: "缩短你的长链接!",
};
export default function RootLayout({
@ -24,7 +24,7 @@ export default function RootLayout({
children: React.ReactNode;
}>) {
return (
<html lang="en">
<html lang="zh-Hans">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>

View File

@ -7,11 +7,12 @@ export default function Home() {
<h1 className="mb-8 text-center text-4xl font-bold text-white">URL Shortener</h1>
<ShortUrlForm />
<div className="mt-8 text-center text-sm text-white">
<p>Short links now include visit tracking and expiration!</p>
<p>使<a href="https://www.rainyun.com/cat_"></a></p>
<p> cat ,</p>
<p className="mt-2">
Report abusive content to:{' '}
<a href="mailto:report@example.com" className="underline">
report@example.com
{' '}
<a href="mailto:i@mei.lv" className="underline">
i@mei.lv
</a>
</p>
</div>

View File

@ -1,130 +1,190 @@
import { getLongUrl, getUrlStats } from '@/lib/db'
import Redirect from '@/components/Redirect'
'use client'
import { useEffect, useState } from 'react'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Progress } from "@/components/ui/progress"
import { Clock, Link, BarChart2, AlertTriangle } from 'lucide-react'
import { Clock, Link, BarChart2, AlertTriangle, ExternalLink } from 'lucide-react'
import { Skeleton } from "@/components/ui/skeleton"
export default async function RedirectPage({ params }: { params: { shortCode: string } }) {
const { longUrl, expired } = getLongUrl(params.shortCode)
const stats = getUrlStats(params.shortCode)
if (longUrl && stats) {
return (
<>
<Redirect url={longUrl} />
<LandingPage
longUrl={longUrl}
shortCode={params.shortCode}
visits={stats.visits}
expiresAt={stats.expiresAt}
/>
</>
)
interface UrlData {
longUrl: string
expired: boolean
stats: {
visits: number
expiresAt: string | null
}
}
export default function RedirectPage({ params }: { params: { shortCode: string } }) {
const [data, setData] = useState<UrlData | null>(null)
const [error, setError] = useState<string | null>(null)
const [progress, setProgress] = useState(0)
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(`/api/url/${params.shortCode}`)
const json = await response.json()
if (!response.ok) {
setError(json.error || 'Failed to fetch URL data')
return
}
setData(json)
} catch (err) {
setError('Failed to load URL data')
console.error('Error fetching data:', err);
} finally {
setIsLoading(false)
}
}
fetchData()
}, [params.shortCode])
useEffect(() => {
if (data?.longUrl) {
const interval = setInterval(() => {
setProgress(prev => {
if (prev >= 100) {
clearInterval(interval)
window.location.href = data.longUrl
return 100
}
return prev + 2
})
}, 100)
return () => clearInterval(interval)
}
}, [data?.longUrl])
if (isLoading) {
return <LoadingSkeleton />
}
if (error || !data) {
return (
<div className="min-h-screen bg-gradient-to-br from-gray-100 to-gray-200 flex items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle className="text-2xl text-center text-red-600">
{expired ? 'Link Expired' : 'Link Not Found'}
{error || 'URL Not Found'}
</CardTitle>
</CardHeader>
<CardContent>
<p className="text-center text-gray-600 mb-6">
{expired
? 'Sorry, this short link has expired.'
: 'The requested short link does not exist.'}
</p>
<div className="text-center">
<a
href="/"
className="inline-block bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded transition duration-300 transform hover:scale-105"
>
Create a New Short Link
</a>
</div>
</CardContent>
<CardFooter className="justify-center">
<p className="text-sm text-gray-500">
Report abusive content:{' '}
<a href="mailto:report@example.com" className="text-blue-500 hover:underline">
report@example.com
</a>
</p>
</CardFooter>
</Card>
</div>
)
}
function LandingPage({ longUrl, shortCode, visits, expiresAt }: {
longUrl: string
shortCode: string
visits: number
expiresAt: string | null
}) {
return (
<div className="min-h-screen bg-gradient-to-br from-blue-100 to-indigo-200 flex items-center justify-center p-4">
<Card className="w-full max-w-2xl">
<CardHeader>
<CardTitle className="text-2xl font-bold text-center text-blue-800">
You are being redirected
...
</CardTitle>
<CardDescription className="text-center text-gray-600">
You will be redirected to your destination in 5 seconds.
{Math.ceil((100 - progress) / 20)}
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<Progress value={100} className="w-full h-2 bg-blue-200" />
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="flex items-center space-x-2">
<Link className="text-blue-600" />
<p className="text-sm text-gray-600">
Short URL: <span className="font-medium">{`${process.env.NEXT_PUBLIC_BASE_URL}/s/${shortCode}`}</span>
<Card className="bg-blue-50 border-blue-200">
<CardContent className="p-4">
<Progress value={progress} className="w-full h-2 mb-2" />
<p className="text-sm text-blue-600 text-center">
...
</p>
</CardContent>
</Card>
<div className="grid grid-cols-2 gap-4">
<Card>
<CardContent className="p-4 flex items-center space-x-2">
<Link className="text-blue-600 w-5 h-5" />
<div>
<p className="text-sm font-semibold text-gray-700"></p>
<p className="text-xs text-gray-500 break-all">{`${process.env.NEXT_PUBLIC_BASE_URL}/s/${params.shortCode}`}</p>
</div>
<div className="flex items-center space-x-2">
<BarChart2 className="text-green-600" />
<p className="text-sm text-gray-600">
Visits: <span className="font-medium">{visits}</span>
</p>
</CardContent>
</Card>
<Card>
<CardContent className="p-4 flex items-center space-x-2">
<BarChart2 className="text-green-600 w-5 h-5" />
<div>
<p className="text-sm font-semibold text-gray-700">访</p>
<p className="text-xs text-gray-500">{data.stats.visits}</p>
</div>
<div className="flex items-center space-x-2">
<Link className="text-purple-600" />
<p className="text-sm text-gray-600">
Destination: <span className="font-medium">{longUrl}</span>
</p>
</CardContent>
</Card>
<Card>
<CardContent className="p-4 flex items-center space-x-2">
<ExternalLink className="text-purple-600 w-5 h-5" />
<div>
<p className="text-sm font-semibold text-gray-700"></p>
<p className="text-xs text-gray-500 truncate max-w-[180px]">{data.longUrl}</p>
</div>
<div className="flex items-center space-x-2">
<Clock className="text-orange-600" />
<p className="text-sm text-gray-600">
Expires at: <span className="font-medium">{expiresAt ? new Date(expiresAt).toLocaleString() : 'Never'}</span>
</p>
</div>
</div>
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
<div className="flex items-center space-x-2 mb-2">
<AlertTriangle className="text-yellow-600" />
<h2 className="font-bold text-yellow-800">Disclaimer</h2>
</div>
<p className="text-sm text-yellow-800">
This link will take you to an external website. We are not responsible for the content
of external sites. Please proceed with caution.
</p>
</div>
<div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
<h2 className="font-bold text-gray-800 mb-2">Advertisement</h2>
<p className="text-sm text-gray-600">
This could be your ad! Contact us for advertising opportunities.
</CardContent>
</Card>
<Card>
<CardContent className="p-4 flex items-center space-x-2">
<Clock className="text-orange-600 w-5 h-5" />
<div>
<p className="text-sm font-semibold text-gray-700"></p>
<p className="text-xs text-gray-500">
{data.stats.expiresAt ? new Date(data.stats.expiresAt).toLocaleString() : 'Never'}
</p>
</div>
</CardContent>
</Card>
</div>
<Card className="bg-yellow-50 border-yellow-200">
<CardHeader className="pb-2">
<div className="flex items-center space-x-2">
<AlertTriangle className="text-yellow-600 w-5 h-5" />
<CardTitle className="text-lg font-bold text-yellow-800"></CardTitle>
</div>
</CardHeader>
<CardContent>
<p className="text-sm text-yellow-800">
访
</p>
</CardContent>
</Card>
<Card className="bg-gradient-to-r from-purple-400 to-pink-500 text-white">
<CardHeader className="pb-2">
<CardTitle className="text-lg font-bold">广</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm">
<a href="https://www.rainyun.com/cat_" className="underline ml-1 font-semibold"></a>
</p>
</CardContent>
</Card>
</CardContent>
<CardFooter className="justify-center">
<p className="text-sm text-gray-500">
Report abusive content:{' '}
<a href="mailto:report@example.com" className="text-blue-500 hover:underline">
report@example.com
{' '}
<a href="mailto:i@mei.lv" className="text-blue-500 hover:underline">
i@mei.lv
</a>
</p>
</CardFooter>
@ -133,3 +193,58 @@ function LandingPage({ longUrl, shortCode, visits, expiresAt }: {
)
}
function LoadingSkeleton() {
return (
<div className="min-h-screen bg-gradient-to-br from-blue-100 to-indigo-200 flex items-center justify-center p-4">
<Card className="w-full max-w-2xl">
<CardHeader>
<Skeleton className="h-8 w-3/4 mx-auto mb-2" />
<Skeleton className="h-4 w-1/2 mx-auto" />
</CardHeader>
<CardContent className="space-y-6">
<Card className="bg-blue-50 border-blue-200">
<CardContent className="p-4">
<Skeleton className="h-2 w-full mb-2" />
<Skeleton className="h-4 w-1/2 mx-auto" />
</CardContent>
</Card>
<div className="grid grid-cols-2 gap-4">
{[...Array(4)].map((_, i) => (
<Card key={i}>
<CardContent className="p-4 flex items-center space-x-2">
<Skeleton className="h-5 w-5" />
<div className="flex-1">
<Skeleton className="h-4 w-3/4 mb-1" />
<Skeleton className="h-3 w-1/2" />
</div>
</CardContent>
</Card>
))}
</div>
<Card className="bg-yellow-50 border-yellow-200">
<CardHeader className="pb-2">
<Skeleton className="h-6 w-1/4" />
</CardHeader>
<CardContent>
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4 mt-2" />
</CardContent>
</Card>
<Card className="bg-gradient-to-r from-purple-400 to-pink-500">
<CardHeader className="pb-2">
<Skeleton className="h-6 w-1/4 bg-white/50" />
</CardHeader>
<CardContent>
<Skeleton className="h-4 w-full bg-white/50" />
<Skeleton className="h-4 w-3/4 mt-2 bg-white/50" />
</CardContent>
</Card>
</CardContent>
</Card>
</div>
)
}

View File

@ -1,29 +1,25 @@
'use client'
import { useEffect, useState } from 'react'
import { Progress } from "@/components/ui/progress"
import { useEffect, useState, useCallback } from 'react'
export default function Redirect({ url }: { url: string }) {
const [progress, setProgress] = useState(0)
useEffect(() => {
const timer = setInterval(() => {
setProgress((oldProgress) => {
if (oldProgress === 100) {
clearInterval(timer)
const updateProgress = useCallback(() => {
setProgress(oldProgress => {
if (oldProgress >= 100) {
window.location.href = url
return 100
}
const diff = 100 / 50 // 50 steps for 5 seconds
return Math.min(oldProgress + diff, 100)
return oldProgress + 2 // 每 100ms 增加 2%
})
}, 100)
return () => clearInterval(timer)
}, [url])
return (
<Progress value={progress} className="w-full h-2 bg-blue-200 fixed top-0 left-0 z-50" />
)
useEffect(() => {
const timer = setInterval(updateProgress, 100)
return () => clearInterval(timer)
}, [updateProgress])
return progress
}

View File

@ -42,7 +42,7 @@ export default function ShortUrlForm() {
<form onSubmit={generateShortUrl} className="space-y-4">
<div>
<label htmlFor="longUrl" className="block text-sm font-medium text-gray-700">
Enter your long URL
</label>
<input
type="url"
@ -51,12 +51,12 @@ export default function ShortUrlForm() {
onChange={(e) => setLongUrl(e.target.value)}
required
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
placeholder="https://example.com/very/long/url"
placeholder="https://www.rainyun.com/cat_"
/>
</div>
<div>
<label htmlFor="expiresIn" className="block text-sm font-medium text-gray-700">
Link expiration time
</label>
<select
id="expiresIn"
@ -64,12 +64,12 @@ export default function ShortUrlForm() {
onChange={(e) => setExpiresIn(e.target.value)}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
>
<option value="3600">1 hour</option>
<option value="86400">1 day</option>
<option value="604800">1 week</option>
<option value="2592000">1 month</option>
<option value="31536000">1 year</option>
<option value="0">Never (permanent)</option>
<option value="3600">1 </option>
<option value="86400">1 </option>
<option value="604800">1 </option>
<option value="2592000">1 </option>
<option value="31536000">1 </option>
<option value="315360000000">(10000)</option>
</select>
</div>
<button
@ -87,7 +87,7 @@ export default function ShortUrlForm() {
)}
{shortUrl && (
<div className="mt-6">
<h2 className="text-lg font-semibold text-gray-700">Your shortened URL:</h2>
<h2 className="text-lg font-semibold text-gray-700">,</h2>
<div className="mt-2 p-4 bg-gray-100 rounded-md">
<a
href={shortUrl}

View File

@ -0,0 +1,16 @@
import { cn } from "@/lib/utils"
function Skeleton({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn("animate-pulse rounded-md bg-muted", className)}
{...props}
/>
)
}
export { Skeleton }