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 { NextResponse } from 'next/server'
import { getLongUrl, getUrlStats } from '@/lib/db'; import { getLongUrl, getUrlStats } from '@/lib/db'
export async function GET( export async function GET(
request: Request, request: Request,
{ params }: { params: { shortCode: string } } { params }: { params: { shortCode: string } }
) { ) {
const { longUrl, expired } = getLongUrl(params.shortCode); try {
const stats = getUrlStats(params.shortCode); const { longUrl, expired } = getLongUrl(params.shortCode)
const stats = getUrlStats(params.shortCode)
if (longUrl) { if (!longUrl) {
return NextResponse.json({ longUrl, expired, stats }); return NextResponse.json(
} else { { error: 'URL not found', expired },
return NextResponse.json({ longUrl: null, expired, stats: null }, { status: 404 }); { 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 = { export const metadata: Metadata = {
title: "Create Next App", title: "Url Shortener",
description: "Generated by create next app", description: "缩短你的长链接!",
}; };
export default function RootLayout({ export default function RootLayout({
@ -24,7 +24,7 @@ export default function RootLayout({
children: React.ReactNode; children: React.ReactNode;
}>) { }>) {
return ( return (
<html lang="en"> <html lang="zh-Hans">
<body <body
className={`${geistSans.variable} ${geistMono.variable} antialiased`} 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> <h1 className="mb-8 text-center text-4xl font-bold text-white">URL Shortener</h1>
<ShortUrlForm /> <ShortUrlForm />
<div className="mt-8 text-center text-sm text-white"> <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"> <p className="mt-2">
Report abusive content to:{' '} {' '}
<a href="mailto:report@example.com" className="underline"> <a href="mailto:i@mei.lv" className="underline">
report@example.com i@mei.lv
</a> </a>
</p> </p>
</div> </div>

View File

@ -1,130 +1,190 @@
import { getLongUrl, getUrlStats } from '@/lib/db' 'use client'
import Redirect from '@/components/Redirect'
import { useEffect, useState } from 'react'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Progress } from "@/components/ui/progress" 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 } }) { interface UrlData {
const { longUrl, expired } = getLongUrl(params.shortCode) longUrl: string
const stats = getUrlStats(params.shortCode) expired: boolean
stats: {
visits: number
expiresAt: string | null
}
}
if (longUrl && stats) { 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 ( return (
<> <div className="min-h-screen bg-gradient-to-br from-gray-100 to-gray-200 flex items-center justify-center p-4">
<Redirect url={longUrl} /> <Card className="w-full max-w-md">
<LandingPage <CardHeader>
longUrl={longUrl} <CardTitle className="text-2xl text-center text-red-600">
shortCode={params.shortCode} {error || 'URL Not Found'}
visits={stats.visits} </CardTitle>
expiresAt={stats.expiresAt} </CardHeader>
/> <CardContent>
</> <p className="text-center text-gray-600 mb-6">
</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"
>
</a>
</div>
</CardContent>
</Card>
</div>
) )
} }
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'}
</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 ( return (
<div className="min-h-screen bg-gradient-to-br from-blue-100 to-indigo-200 flex items-center justify-center p-4"> <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"> <Card className="w-full max-w-2xl">
<CardHeader> <CardHeader>
<CardTitle className="text-2xl font-bold text-center text-blue-800"> <CardTitle className="text-2xl font-bold text-center text-blue-800">
You are being redirected ...
</CardTitle> </CardTitle>
<CardDescription className="text-center text-gray-600"> <CardDescription className="text-center text-gray-600">
You will be redirected to your destination in 5 seconds. {Math.ceil((100 - progress) / 20)}
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-6"> <CardContent className="space-y-6">
<Progress value={100} className="w-full h-2 bg-blue-200" /> <Card className="bg-blue-50 border-blue-200">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <CardContent className="p-4">
<div className="flex items-center space-x-2"> <Progress value={progress} className="w-full h-2 mb-2" />
<Link className="text-blue-600" /> <p className="text-sm text-blue-600 text-center">
<p className="text-sm text-gray-600"> ...
Short URL: <span className="font-medium">{`${process.env.NEXT_PUBLIC_BASE_URL}/s/${shortCode}`}</span>
</p> </p>
</div> </CardContent>
<div className="flex items-center space-x-2"> </Card>
<BarChart2 className="text-green-600" />
<p className="text-sm text-gray-600"> <div className="grid grid-cols-2 gap-4">
Visits: <span className="font-medium">{visits}</span> <Card>
</p> <CardContent className="p-4 flex items-center space-x-2">
</div> <Link className="text-blue-600 w-5 h-5" />
<div className="flex items-center space-x-2"> <div>
<Link className="text-purple-600" /> <p className="text-sm font-semibold text-gray-700"></p>
<p className="text-sm text-gray-600"> <p className="text-xs text-gray-500 break-all">{`${process.env.NEXT_PUBLIC_BASE_URL}/s/${params.shortCode}`}</p>
Destination: <span className="font-medium">{longUrl}</span> </div>
</p> </CardContent>
</div> </Card>
<div className="flex items-center space-x-2"> <Card>
<Clock className="text-orange-600" /> <CardContent className="p-4 flex items-center space-x-2">
<p className="text-sm text-gray-600"> <BarChart2 className="text-green-600 w-5 h-5" />
Expires at: <span className="font-medium">{expiresAt ? new Date(expiresAt).toLocaleString() : 'Never'}</span> <div>
</p> <p className="text-sm font-semibold text-gray-700">访</p>
</div> <p className="text-xs text-gray-500">{data.stats.visits}</p>
</div> </div>
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4"> </CardContent>
<div className="flex items-center space-x-2 mb-2"> </Card>
<AlertTriangle className="text-yellow-600" /> <Card>
<h2 className="font-bold text-yellow-800">Disclaimer</h2> <CardContent className="p-4 flex items-center space-x-2">
</div> <ExternalLink className="text-purple-600 w-5 h-5" />
<p className="text-sm text-yellow-800"> <div>
This link will take you to an external website. We are not responsible for the content <p className="text-sm font-semibold text-gray-700"></p>
of external sites. Please proceed with caution. <p className="text-xs text-gray-500 truncate max-w-[180px]">{data.longUrl}</p>
</p> </div>
</div> </CardContent>
<div className="bg-gray-50 border border-gray-200 rounded-lg p-4"> </Card>
<h2 className="font-bold text-gray-800 mb-2">Advertisement</h2> <Card>
<p className="text-sm text-gray-600"> <CardContent className="p-4 flex items-center space-x-2">
This could be your ad! Contact us for advertising opportunities. <Clock className="text-orange-600 w-5 h-5" />
</p> <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> </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> </CardContent>
<CardFooter className="justify-center"> <CardFooter className="justify-center">
<p className="text-sm text-gray-500"> <p className="text-sm text-gray-500">
Report abusive content:{' '} {' '}
<a href="mailto:report@example.com" className="text-blue-500 hover:underline"> <a href="mailto:i@mei.lv" className="text-blue-500 hover:underline">
report@example.com i@mei.lv
</a> </a>
</p> </p>
</CardFooter> </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' 'use client'
import { useEffect, useState } from 'react' import { useEffect, useState, useCallback } from 'react'
import { Progress } from "@/components/ui/progress"
export default function Redirect({ url }: { url: string }) { export default function Redirect({ url }: { url: string }) {
const [progress, setProgress] = useState(0) const [progress, setProgress] = useState(0)
useEffect(() => { const updateProgress = useCallback(() => {
const timer = setInterval(() => { setProgress(oldProgress => {
setProgress((oldProgress) => { if (oldProgress >= 100) {
if (oldProgress === 100) { window.location.href = url
clearInterval(timer) return 100
window.location.href = url }
return 100 return oldProgress + 2 // 每 100ms 增加 2%
} })
const diff = 100 / 50 // 50 steps for 5 seconds
return Math.min(oldProgress + diff, 100)
})
}, 100)
return () => clearInterval(timer)
}, [url]) }, [url])
return ( useEffect(() => {
<Progress value={progress} className="w-full h-2 bg-blue-200 fixed top-0 left-0 z-50" /> 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"> <form onSubmit={generateShortUrl} className="space-y-4">
<div> <div>
<label htmlFor="longUrl" className="block text-sm font-medium text-gray-700"> <label htmlFor="longUrl" className="block text-sm font-medium text-gray-700">
Enter your long URL
</label> </label>
<input <input
type="url" type="url"
@ -51,12 +51,12 @@ export default function ShortUrlForm() {
onChange={(e) => setLongUrl(e.target.value)} onChange={(e) => setLongUrl(e.target.value)}
required 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" 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>
<div> <div>
<label htmlFor="expiresIn" className="block text-sm font-medium text-gray-700"> <label htmlFor="expiresIn" className="block text-sm font-medium text-gray-700">
Link expiration time
</label> </label>
<select <select
id="expiresIn" id="expiresIn"
@ -64,12 +64,12 @@ export default function ShortUrlForm() {
onChange={(e) => setExpiresIn(e.target.value)} 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" 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="3600">1 </option>
<option value="86400">1 day</option> <option value="86400">1 </option>
<option value="604800">1 week</option> <option value="604800">1 </option>
<option value="2592000">1 month</option> <option value="2592000">1 </option>
<option value="31536000">1 year</option> <option value="31536000">1 </option>
<option value="0">Never (permanent)</option> <option value="315360000000">(10000)</option>
</select> </select>
</div> </div>
<button <button
@ -87,7 +87,7 @@ export default function ShortUrlForm() {
)} )}
{shortUrl && ( {shortUrl && (
<div className="mt-6"> <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"> <div className="mt-2 p-4 bg-gray-100 rounded-md">
<a <a
href={shortUrl} 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 }