voice note and sticker pack and gifs

This commit is contained in:
2026-06-26 15:18:09 +02:00
parent 1f448320be
commit 827b0598e6
8 changed files with 775 additions and 59 deletions
@@ -0,0 +1,85 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
import { unlink } from "node:fs/promises"
import { join } from "node:path"
import { existsSync } from "node:fs"
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string; messageId: string }> },
) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { id: conversationId, messageId } = await params
// Verify user is a participant in this conversation
const partCheck = await query(
`SELECT 1 FROM conversation_participants WHERE conversation_id = $1 AND user_id = $2`,
[conversationId, user.id],
)
if (partCheck.rows.length === 0) {
return NextResponse.json({ error: "Not a participant" }, { status: 403 })
}
// Fetch the message to verify it belongs to the sender and check if it's a voice message
const msgResult = await query(
`SELECT id, sender_id, content FROM messages WHERE id = $1 AND conversation_id = $2 AND deleted_at IS NULL`,
[messageId, conversationId],
)
if (msgResult.rows.length === 0) {
return NextResponse.json({ error: "Message not found" }, { status: 404 })
}
const message = msgResult.rows[0]
// Only the sender can delete their own message
if (message.sender_id !== user.id) {
return NextResponse.json({ error: "Cannot delete another user's message" }, { status: 403 })
}
// Delete the associated audio file if this is a voice message
let storageDeleted = false
try {
const content = message.content
if (content?.startsWith("{")) {
const parsed = JSON.parse(content)
if (parsed.v && parsed.u) {
const filename = parsed.u.replace(/^\/uploads\/voice\//, "")
const filePath = join(process.cwd(), "public", "uploads", "voice", filename)
if (existsSync(filePath)) {
await unlink(filePath)
storageDeleted = true
}
}
}
} catch {
// If file deletion fails, log but still proceed with DB deletion
console.warn(`[voice-delete] Failed to delete audio file for message ${messageId}`)
}
// Soft-delete the message in the database
const deleteResult = await query(
`UPDATE messages SET deleted_at = NOW() WHERE id = $1 AND conversation_id = $2 RETURNING id`,
[messageId, conversationId],
)
const dbDeleted = deleteResult.rows.length > 0
console.log(
`[voice-delete] id=${messageId} conv=${conversationId} user=${user.id} db=${dbDeleted} storage=${storageDeleted}`,
)
return NextResponse.json({
success: true,
messageId,
dbDeleted,
storageDeleted,
})
} catch (error) {
console.error("[voice-delete] Error:", error)
return NextResponse.json({ error: "Unable to delete voice note. Please try again." }, { status: 500 })
}
}
+56
View File
@@ -0,0 +1,56 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
const TENOR_API_KEY = process.env.TENOR_API_KEY || ""
const TENOR_BASE = "https://tenor.googleapis.com/v2"
export async function GET(request: NextRequest) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { searchParams } = new URL(request.url)
const q = searchParams.get("q") || ""
const limit = Math.min(parseInt(searchParams.get("limit") || "20", 10), 50)
const pos = searchParams.get("pos") || ""
if (!TENOR_API_KEY) {
return NextResponse.json({
results: [],
error: "TENOR_API_KEY not configured",
noKey: true,
})
}
const endpoint = q
? `${TENOR_BASE}/search?q=${encodeURIComponent(q)}&key=${TENOR_API_KEY}&limit=${limit}&media_filter=minimal`
: `${TENOR_BASE}/featured?key=${TENOR_API_KEY}&limit=${limit}&media_filter=minimal`
const url = pos ? `${endpoint}&pos=${pos}` : endpoint
const res = await fetch(url, { signal: AbortSignal.timeout(8000) })
if (!res.ok) {
return NextResponse.json({ results: [], error: "Tenor API error" }, { status: 502 })
}
const data = await res.json()
const results = (data.results || []).map((item: any) => {
const media = item.media_formats?.gif || item.media_formats?.tinygif || {}
const preview = item.media_formats?.tinygif || item.media_formats?.gif || {}
return {
id: item.id,
title: item.title || "",
url: media.url || "",
previewUrl: preview.url || "",
width: media.dims?.[0] || 200,
height: media.dims?.[1] || 200,
}
})
return NextResponse.json({ results, next: data.next || "" })
} catch (error) {
console.error("GIF API error:", error)
return NextResponse.json({ results: [], error: "Failed to fetch GIFs" }, { status: 500 })
}
}
+29
View File
@@ -0,0 +1,29 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { writeFile } from "node:fs/promises"
import { join } from "node:path"
import crypto from "node:crypto"
export async function POST(request: NextRequest) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const formData = await request.formData()
const file = formData.get("audio") as File | null
if (!file) return NextResponse.json({ error: "No audio file" }, { status: 400 })
const duration = parseFloat(formData.get("duration")?.toString() || "0")
const ext = file.name.endsWith(".webm") ? "webm" : "webm"
const filename = `${crypto.randomUUID()}.${ext}`
const buffer = Buffer.from(await file.arrayBuffer())
const savePath = join(process.cwd(), "public", "uploads", "voice", filename)
await writeFile(savePath, buffer)
return NextResponse.json({ url: `/uploads/voice/${filename}`, duration })
} catch (error) {
console.error("Voice upload error:", error)
return NextResponse.json({ error: "Upload failed" }, { status: 500 })
}
}