I LOVE WOMEN

This commit is contained in:
WaveringAna 2025-01-25 23:01:12 -05:00
parent 49b01984ab
commit 3932b48a64
10 changed files with 233 additions and 150 deletions

1
.gitignore vendored
View file

@ -2,4 +2,3 @@
**/node_modules **/node_modules
node_modules node_modules
.env .env
.sqlx

2
.preludeignore Normal file
View file

@ -0,0 +1,2 @@
.sqlx
.env

50
Cargo.lock generated
View file

@ -2,31 +2,6 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "SimpleLink"
version = "0.1.0"
dependencies = [
"actix-cors",
"actix-web",
"anyhow",
"argon2",
"base62",
"chrono",
"clap",
"dotenv",
"jsonwebtoken",
"lazy_static",
"regex",
"serde",
"serde_json",
"sqlx",
"thiserror 1.0.69",
"tokio",
"tracing",
"tracing-subscriber",
"uuid",
]
[[package]] [[package]]
name = "actix-codec" name = "actix-codec"
version = "0.5.2" version = "0.5.2"
@ -2039,6 +2014,31 @@ dependencies = [
"time", "time",
] ]
[[package]]
name = "simplelink"
version = "0.1.0"
dependencies = [
"actix-cors",
"actix-web",
"anyhow",
"argon2",
"base62",
"chrono",
"clap",
"dotenv",
"jsonwebtoken",
"lazy_static",
"regex",
"serde",
"serde_json",
"sqlx",
"thiserror 1.0.69",
"tokio",
"tracing",
"tracing-subscriber",
"uuid",
]
[[package]] [[package]]
name = "slab" name = "slab"
version = "0.4.9" version = "0.4.9"

View file

@ -1,10 +1,10 @@
[package] [package]
name = "SimpleLink" name = "simplelink"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
[lib] [lib]
name = "simple_link" name = "simplelink"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]

45
Dockerfile Normal file
View file

@ -0,0 +1,45 @@
# Build stage
FROM rust:latest as builder
# Install PostgreSQL client libraries and SSL dependencies
RUN apt-get update && \
apt-get install -y pkg-config libssl-dev libpq-dev && \
rm -rf /var/lib/apt/lists/*
WORKDIR /usr/src/app
# Copy manifests first (better layer caching)
COPY Cargo.toml Cargo.lock ./
# Copy source code and SQLx prepared queries
COPY src/ src/
COPY migrations/ migrations/
COPY .sqlx/ .sqlx/
# Build your application
RUN cargo build --release
# Runtime stage
FROM debian:bookworm-slim
# Install runtime dependencies
RUN apt-get update && \
apt-get install -y libpq5 ca-certificates openssl libssl3 && \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Copy the binary from builder
COPY --from=builder /usr/src/app/target/release/simplelink /app/simplelink
# Copy migrations folder for SQLx
COPY --from=builder /usr/src/app/migrations /app/migrations
# Expose the port (this is just documentation)
EXPOSE 8080
# Set default network configuration
ENV SERVER_HOST=0.0.0.0
ENV SERVER_PORT=8080
# Run the binary
CMD ["./simplelink"]

View file

@ -1,51 +1,56 @@
import { ThemeProvider } from "@/components/theme-provider" import { ThemeProvider } from "@/components/theme-provider"
import { Button } from './components/ui/button'
import { LinkForm } from './components/LinkForm' import { LinkForm } from './components/LinkForm'
import { LinkList } from './components/LinkList' import { LinkList } from './components/LinkList'
import { AuthForms } from './components/AuthForms' import { AuthForms } from './components/AuthForms'
import { AuthProvider, useAuth } from './context/AuthContext' import { AuthProvider, useAuth } from './context/AuthContext'
import { useState } from 'react' import { Button } from "@/components/ui/button"
import { Toaster } from './components/ui/toaster' import { Toaster } from './components/ui/toaster'
import { ModeToggle } from './components/mode-toggle'
import { useState } from 'react'
function AppContent() { function AppContent() {
const { user, logout } = useAuth() const { user, logout } = useAuth()
const [refreshCounter, setRefreshCounter] = useState(0) const [refreshCounter, setRefreshCounter] = useState(0)
const handleLinkCreated = () => { const handleLinkCreated = () => {
// Increment refresh counter to trigger list refresh
setRefreshCounter(prev => prev + 1) setRefreshCounter(prev => prev + 1)
} }
return ( return (
<div className="min-h-screen flex flex-col"> <div className="min-h-screen bg-background flex flex-col">
<div className="container max-w-6xl mx-auto py-8 flex-1 flex flex-col"> <header className="border-b">
<div className="space-y-8 flex-1 flex flex-col justify-center"> <div className="container max-w-6xl mx-auto flex h-16 items-center justify-between px-4">
<div className="flex items-center justify-between"> <h1 className="text-2xl font-bold">SimpleLink</h1>
<h1 className="text-3xl font-bold">SimpleLink</h1> <div className="flex items-center gap-4">
{user ? ( {user ? (
<div className="flex items-center gap-4"> <>
<p className="text-sm text-muted-foreground">Welcome, {user.email}</p> <span className="text-sm text-muted-foreground">Welcome, {user.email}</span>
<Button variant="outline" onClick={logout}> <Button variant="outline" size="sm" onClick={logout}>
Logout Logout
</Button> </Button>
</div> </>
) : ( ) : (
<div className="flex items-center gap-4"> <span className="text-sm text-muted-foreground">A link shortening and tracking service</span>
<p className="text-sm text-muted-foreground">A link shortening and tracking service</p> )}
</div> <ModeToggle />
</div>
</div>
</header>
<main className="flex-1 flex flex-col">
<div className="container max-w-6xl mx-auto px-4 py-8 flex-1 flex flex-col">
<div className="space-y-8 flex-1 flex flex-col justify-center">
{user ? (
<>
<LinkForm onSuccess={handleLinkCreated} />
<LinkList refresh={refreshCounter} />
</>
) : (
<AuthForms />
)} )}
</div> </div>
{user ? (
<>
<LinkForm onSuccess={handleLinkCreated} />
<LinkList refresh={refreshCounter} />
</>
) : (
<AuthForms />
)}
</div> </div>
</div> </main>
</div> </div>
) )
} }

View file

@ -56,7 +56,7 @@ export function AuthForms() {
return ( return (
<Card className="w-full max-w-md mx-auto p-6"> <Card className="w-full max-w-md mx-auto p-6">
<Tabs value={activeTab} onValueChange={(value: 'login' | 'register') => setActiveTab(value)}> <Tabs value={activeTab} onValueChange={(value: string) => setActiveTab(value as 'login' | 'register')}>
<TabsList className="grid w-full grid-cols-2"> <TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="login">Login</TabsTrigger> <TabsTrigger value="login">Login</TabsTrigger>
<TabsTrigger value="register">Register</TabsTrigger> <TabsTrigger value="register">Register</TabsTrigger>

View file

@ -2,18 +2,19 @@ import { useState } from 'react'
import { useForm } from 'react-hook-form' import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod' import { zodResolver } from '@hookform/resolvers/zod'
import * as z from 'zod' import * as z from 'zod'
import { CreateLinkRequest, Link } from '../types/api' import { CreateLinkRequest } from '../types/api'
import { createShortLink } from '../api/client' import { createShortLink } from '../api/client'
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { LinkIcon } from "lucide-react"
import { import {
Form, Form,
FormControl, FormControl,
FormField, FormField,
FormItem,
FormLabel, FormLabel,
FormMessage, FormMessage,
} from "@/components/ui/form" } from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { useToast } from "@/hooks/use-toast" import { useToast } from "@/hooks/use-toast"
const formSchema = z.object({ const formSchema = z.object({
@ -29,7 +30,7 @@ const formSchema = z.object({
}) })
interface LinkFormProps { interface LinkFormProps {
onSuccess: (link: Link) => void onSuccess: () => void;
} }
export function LinkForm({ onSuccess }: LinkFormProps) { export function LinkForm({ onSuccess }: LinkFormProps) {
@ -47,9 +48,9 @@ export function LinkForm({ onSuccess }: LinkFormProps) {
const onSubmit = async (values: z.infer<typeof formSchema>) => { const onSubmit = async (values: z.infer<typeof formSchema>) => {
try { try {
setLoading(true) setLoading(true)
const link = await createShortLink(values as CreateLinkRequest) await createShortLink(values as CreateLinkRequest)
form.reset() form.reset()
onSuccess(link) onSuccess() // Call the onSuccess callback to trigger refresh
toast({ toast({
description: "Short link created successfully", description: "Short link created successfully",
}) })
@ -65,45 +66,51 @@ export function LinkForm({ onSuccess }: LinkFormProps) {
} }
return ( return (
<div className="max-w-[500px] mx-auto"> <Card className="mb-8">
<Form {...form}> <CardHeader>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6"> <CardTitle>Create Short Link</CardTitle>
<FormField <CardDescription>Enter a URL to generate a shortened link</CardDescription>
control={form.control} </CardHeader>
name="url" <CardContent>
render={({ field }) => ( <Form {...form}>
<FormItem> <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4 md:flex-row md:items-end">
<FormLabel>URL</FormLabel> <FormField
<FormControl> control={form.control}
<Input placeholder="https://example.com" {...field} /> name="url"
</FormControl> render={({ field }) => (
<FormMessage /> <div className="flex-1 space-y-2">
</FormItem> <FormLabel>URL</FormLabel>
)} <FormControl>
/> <div className="relative">
<LinkIcon className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input placeholder="https://example.com" className="pl-9" {...field} />
</div>
</FormControl>
<FormMessage />
</div>
)}
/>
<FormField <FormField
control={form.control} control={form.control}
name="custom_code" name="custom_code"
render={({ field }) => ( render={({ field }) => (
<FormItem> <div className="w-full md:w-1/4 space-y-2">
<FormLabel>Custom Code (optional)</FormLabel> <FormLabel>Custom Code <span className="text-muted-foreground">(optional)</span></FormLabel>
<FormControl> <FormControl>
<Input placeholder="example" {...field} /> <Input placeholder="custom-code" {...field} />
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </div>
)} )}
/> />
<div className="flex justify-end"> <Button type="submit" disabled={loading} className="md:w-auto">
<Button type="submit" disabled={loading}>
{loading ? "Creating..." : "Create Short Link"} {loading ? "Creating..." : "Create Short Link"}
</Button> </Button>
</div> </form>
</form> </Form>
</Form> </CardContent>
</div> </Card>
) )
} }

View file

@ -1,6 +1,7 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { Link } from '../types/api' import { Link } from '../types/api'
import { getAllLinks, deleteLink } from '../api/client' import { getAllLinks, deleteLink } from '../api/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { import {
Table, Table,
TableBody, TableBody,
@ -9,6 +10,9 @@ import {
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table" } from "@/components/ui/table"
import { Button } from "@/components/ui/button"
import { useToast } from "@/hooks/use-toast"
import { Copy, Trash2 } from "lucide-react"
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
@ -17,14 +21,12 @@ import {
DialogDescription, DialogDescription,
DialogFooter, DialogFooter,
} from "@/components/ui/dialog" } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { useToast } from "@/hooks/use-toast"
interface LinkListProps { interface LinkListProps {
refresh: number refresh?: number;
} }
export function LinkList({ refresh }: LinkListProps) { export function LinkList({ refresh = 0 }: LinkListProps) {
const [links, setLinks] = useState<Link[]>([]) const [links, setLinks] = useState<Link[]>([])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [deleteModal, setDeleteModal] = useState<{ isOpen: boolean; linkId: number | null }>({ const [deleteModal, setDeleteModal] = useState<{ isOpen: boolean; linkId: number | null }>({
@ -51,7 +53,7 @@ export function LinkList({ refresh }: LinkListProps) {
useEffect(() => { useEffect(() => {
fetchLinks() fetchLinks()
}, [refresh]) }, [refresh]) // Re-fetch when refresh counter changes
const handleDelete = async () => { const handleDelete = async () => {
if (!deleteModal.linkId) return if (!deleteModal.linkId) return
@ -61,8 +63,7 @@ export function LinkList({ refresh }: LinkListProps) {
await fetchLinks() await fetchLinks()
setDeleteModal({ isOpen: false, linkId: null }) setDeleteModal({ isOpen: false, linkId: null })
toast({ toast({
title: "Link deleted", description: "Link deleted successfully",
description: "The link has been successfully deleted.",
}) })
} catch (err) { } catch (err) {
toast({ toast({
@ -73,12 +74,19 @@ export function LinkList({ refresh }: LinkListProps) {
} }
} }
const handleCopy = (shortCode: string) => {
navigator.clipboard.writeText(`http://localhost:8080/${shortCode}`)
toast({
description: "Link copied to clipboard",
})
}
if (loading && !links.length) { if (loading && !links.length) {
return <div className="text-center py-4">Loading...</div> return <div className="text-center py-4">Loading...</div>
} }
return ( return (
<div className="space-y-4"> <>
<Dialog open={deleteModal.isOpen} onOpenChange={(open) => setDeleteModal({ isOpen: open, linkId: null })}> <Dialog open={deleteModal.isOpen} onOpenChange={(open) => setDeleteModal({ isOpen: open, linkId: null })}>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
@ -98,48 +106,63 @@ export function LinkList({ refresh }: LinkListProps) {
</DialogContent> </DialogContent>
</Dialog> </Dialog>
<Table> <Card>
<TableHeader> <CardHeader>
<TableRow> <CardTitle>Your Links</CardTitle>
<TableHead>Short Code</TableHead> <CardDescription>Manage and track your shortened links</CardDescription>
<TableHead>Original URL</TableHead> </CardHeader>
<TableHead>Clicks</TableHead> <CardContent>
<TableHead>Created</TableHead> <div className="rounded-md border">
<TableHead>Actions</TableHead> <Table>
</TableRow> <TableHeader>
</TableHeader> <TableRow>
<TableBody> <TableHead>Short Code</TableHead>
{links.map((link) => ( <TableHead className="hidden md:table-cell">Original URL</TableHead>
<TableRow key={link.id}> <TableHead>Clicks</TableHead>
<TableCell>{link.short_code}</TableCell> <TableHead className="hidden md:table-cell">Created</TableHead>
<TableCell className="max-w-[300px] truncate">{link.original_url}</TableCell> <TableHead>Actions</TableHead>
<TableCell>{link.clicks}</TableCell> </TableRow>
<TableCell>{new Date(link.created_at).toLocaleDateString()}</TableCell> </TableHeader>
<TableCell> <TableBody>
<div className="flex gap-2"> {links.map((link) => (
<Button <TableRow key={link.id}>
variant="secondary" <TableCell className="font-medium">{link.short_code}</TableCell>
size="sm" <TableCell className="hidden md:table-cell max-w-[300px] truncate">
onClick={() => { {link.original_url}
navigator.clipboard.writeText(`http://localhost:8080/${link.short_code}`) </TableCell>
toast({ description: "Link copied to clipboard" }) <TableCell>{link.clicks}</TableCell>
}} <TableCell className="hidden md:table-cell">
> {new Date(link.created_at).toLocaleDateString()}
Copy </TableCell>
</Button> <TableCell>
<Button <div className="flex gap-2">
variant="destructive" <Button
size="sm" variant="ghost"
onClick={() => setDeleteModal({ isOpen: true, linkId: link.id })} size="icon"
> className="h-8 w-8"
Delete onClick={() => handleCopy(link.short_code)}
</Button> >
</div> <Copy className="h-4 w-4" />
</TableCell> <span className="sr-only">Copy link</span>
</TableRow> </Button>
))} <Button
</TableBody> variant="ghost"
</Table> size="icon"
</div> className="h-8 w-8 text-destructive"
onClick={() => setDeleteModal({ isOpen: true, linkId: link.id })}
>
<Trash2 className="h-4 w-4" />
<span className="sr-only">Delete link</span>
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</CardContent>
</Card>
</>
) )
} }

View file

@ -28,7 +28,9 @@ async fn main() -> Result<()> {
let state = AppState { db: pool }; let state = AppState { db: pool };
info!("Starting server at http://127.0.0.1:8080"); let host = std::env::var("SERVER_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
let port = std::env::var("SERVER_PORT").unwrap_or_else(|_| "8080".to_string());
info!("Starting server at http://{}:{}", host, port);
// Start HTTP server // Start HTTP server
HttpServer::new(move || { HttpServer::new(move || {
@ -54,7 +56,7 @@ async fn main() -> Result<()> {
}) })
.workers(2) .workers(2)
.backlog(10_000) .backlog(10_000)
.bind("127.0.0.1:8080")? .bind(format!("{}:{}", host, port))?
.run() .run()
.await?; .await?;