feat: pet-suggestion notifications, story music overlay, auth UX fixes
Three pieces of work from this session: - Pet-suggestion notifications: a weekly cron (species/breed affinity heuristic) suggests pets to follow, with an owner opt-out and web/mobile notification UI wiring. - Story music overlay: admin-curated royalty-free track catalog (/p/[secret]/music), attachable to stories on web (StoryForm/StoryViewer), with mute-original support for video stories. Mobile UI is deferred to the next native build (needs an audio-playback module) — tracked in mobile/PENDING-NATIVE-BUILD.md. - Auth UX fixes: sign-in/sign-up now use KeyboardAvoidingView + ScrollView and a shared PasswordField with a show/hide toggle (mobile). Web's ActivePetContext gained clearGactivePetId(), wired to sign-out via a new SignOutCleanup component, fixing a false "you do not have permission to access this pet" error after switching accounts on the same browser. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
af0cea6d3f
commit
e9bad092f2
35 files changed
+1655
-148
No files matched your search
@@ -25,6 +25,9 @@ vi.mock("@/lib/supabase-storage", () => ({
|
||||
createSignedUploadUrl: vi.fn(),
|
||||
ALLOWED_CONTENT_TYPES: ["image/jpeg", "image/png", "image/webp"],
|
||||
MAX_FILE_SIZE: 10 * 1024 * 1024,
|
||||
MUSIC_STORAGE_BUCKET: "music-tracks",
|
||||
MUSIC_ALLOWED_CONTENT_TYPES: ["audio/mpeg", "audio/mp4", "audio/aac"],
|
||||
MAX_MUSIC_FILE_SIZE: 5 * 1024 * 1024,
|
||||
}));
|
||||
vi.mock("@/lib/prisma", () => ({ prisma: {} }));
|
||||
|
||||
@@ -767,3 +770,95 @@ describe("admin.createBroadcast / admin.listBroadcasts (Gitea #10 Phase 1)", ()
|
||||
expect(mockPrisma.broadcast.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("admin music-track catalog", () => {
|
||||
it("listMusicTracks returns the catalog for a MODERATOR caller", async () => {
|
||||
vi.stubEnv("ADMIN_OWNER_ID", "admin-1");
|
||||
const { caller, mockPrisma } = await createAdminCaller();
|
||||
mockPrisma.musicTrack.findMany.mockResolvedValue([{ id: "track-1", title: "Sunny Day" }]);
|
||||
|
||||
const result = await caller.admin.listMusicTracks(undefined);
|
||||
|
||||
expect(result).toEqual([{ id: "track-1", title: "Sunny Day" }]);
|
||||
});
|
||||
|
||||
it("getMusicTrackUploadUrl requires SUPER_ADMIN, not just MODERATOR", async () => {
|
||||
vi.stubEnv("ADMIN_OWNER_ID", "someone-else");
|
||||
const { caller, mockPrisma } = await createAdminCaller();
|
||||
mockPrisma.adminRole.findUnique.mockResolvedValue({ role: "MODERATOR" });
|
||||
|
||||
await expect(
|
||||
caller.admin.getMusicTrackUploadUrl({ contentType: "audio/mpeg", fileSize: 1000 })
|
||||
).rejects.toThrow(TRPCError);
|
||||
});
|
||||
|
||||
it("createMusicTrack writes the track + a CREATE_MUSIC_TRACK moderation log in a transaction", async () => {
|
||||
vi.stubEnv("ADMIN_OWNER_ID", "admin-1");
|
||||
const { caller, mockPrisma } = await createAdminCaller();
|
||||
mockPrisma.musicTrack.create.mockResolvedValue({ id: "track-1", title: "Sunny Day" });
|
||||
mockPrisma.moderationLog.create.mockResolvedValue({ id: "log-1" });
|
||||
|
||||
const result = await caller.admin.createMusicTrack({
|
||||
title: "Sunny Day",
|
||||
artist: "Test Artist",
|
||||
licenseNote: "Royalty-free library, CC0",
|
||||
storageKey: "tracks/abc.mp3",
|
||||
durationSecs: 12.5,
|
||||
});
|
||||
|
||||
expect(mockPrisma.musicTrack.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ title: "Sunny Day", createdBy: "admin-1" }),
|
||||
});
|
||||
expect(mockPrisma.moderationLog.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ action: "CREATE_MUSIC_TRACK", targetType: "MUSIC_TRACK" }),
|
||||
});
|
||||
expect(result).toEqual({ id: "track-1", title: "Sunny Day" });
|
||||
});
|
||||
|
||||
it("createMusicTrack throws FORBIDDEN for a non-admin caller", async () => {
|
||||
vi.stubEnv("ADMIN_OWNER_ID", "someone-else");
|
||||
const { caller, mockPrisma } = await createAdminCaller();
|
||||
mockPrisma.adminRole.findUnique.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
caller.admin.createMusicTrack({
|
||||
title: "Sunny Day",
|
||||
artist: "Test Artist",
|
||||
licenseNote: "Royalty-free library, CC0",
|
||||
storageKey: "tracks/abc.mp3",
|
||||
durationSecs: 12.5,
|
||||
})
|
||||
).rejects.toThrow(TRPCError);
|
||||
expect(mockPrisma.musicTrack.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updateMusicTrack can toggle active off without touching other fields", async () => {
|
||||
vi.stubEnv("ADMIN_OWNER_ID", "admin-1");
|
||||
const { caller, mockPrisma } = await createAdminCaller();
|
||||
mockPrisma.musicTrack.update.mockResolvedValue({ id: "track-1", active: false });
|
||||
mockPrisma.moderationLog.create.mockResolvedValue({ id: "log-1" });
|
||||
|
||||
const result = await caller.admin.updateMusicTrack({ id: "track-1", active: false });
|
||||
|
||||
expect(mockPrisma.musicTrack.update).toHaveBeenCalledWith({
|
||||
where: { id: "track-1" },
|
||||
data: { active: false },
|
||||
});
|
||||
expect(result).toEqual({ id: "track-1", active: false });
|
||||
});
|
||||
|
||||
it("deleteMusicTrack wraps delete + log in a transaction", async () => {
|
||||
vi.stubEnv("ADMIN_OWNER_ID", "admin-1");
|
||||
const { caller, mockPrisma } = await createAdminCaller();
|
||||
mockPrisma.musicTrack.delete.mockResolvedValue({ id: "track-1" });
|
||||
mockPrisma.moderationLog.create.mockResolvedValue({ id: "log-1" });
|
||||
|
||||
const result = await caller.admin.deleteMusicTrack({ id: "track-1" });
|
||||
|
||||
expect(mockPrisma.musicTrack.delete).toHaveBeenCalledWith({ where: { id: "track-1" } });
|
||||
expect(mockPrisma.moderationLog.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ action: "DELETE_MUSIC_TRACK", targetType: "MUSIC_TRACK", targetId: "track-1" }),
|
||||
});
|
||||
expect(result).toEqual({ success: true });
|
||||
});
|
||||
});
|
||||
@@ -317,6 +317,14 @@ interface MockBroadcastReceiptClient {
|
||||
groupBy: MockFn;
|
||||
}
|
||||
|
||||
interface MockMusicTrackClient {
|
||||
create: MockFn;
|
||||
findMany: MockFn;
|
||||
findUnique: MockFn;
|
||||
update: MockFn;
|
||||
delete: MockFn;
|
||||
}
|
||||
|
||||
interface MockPrismaClient {
|
||||
pet: MockPetClient;
|
||||
owner: MockOwnerClient;
|
||||
@@ -362,6 +370,7 @@ interface MockPrismaClient {
|
||||
conversation: MockConversationClient;
|
||||
broadcast: MockBroadcastClient;
|
||||
broadcastReceipt: MockBroadcastReceiptClient;
|
||||
musicTrack: MockMusicTrackClient;
|
||||
$transaction: MockFn;
|
||||
$disconnect: MockFn;
|
||||
}
|
||||
@@ -632,6 +641,13 @@ export function createMockPrisma(): MockPrismaClient {
|
||||
updateMany: vi.fn(),
|
||||
groupBy: vi.fn(),
|
||||
},
|
||||
musicTrack: {
|
||||
create: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(),
|
||||
$disconnect: vi.fn(),
|
||||
};
|
||||
|
||||
@@ -95,6 +95,27 @@ describe("notify() push add-on", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("sends the PET_SUGGESTION copy with the suggested pet's name", async () => {
|
||||
const mockPrisma = createMockPrisma();
|
||||
mockPrisma.notification.create.mockResolvedValue({});
|
||||
mockPrisma.pet.findUnique
|
||||
.mockResolvedValueOnce({ ownerId: "owner-1" }) // recipient lookup
|
||||
.mockResolvedValueOnce({ name: "Luna" }); // actor (suggested pet) lookup
|
||||
mockPrisma.owner.findUnique.mockResolvedValue({ expoPushToken: "ExponentPushToken[abc]" });
|
||||
|
||||
notify(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
mockPrisma as any,
|
||||
{ recipientPetId: "pet-1", type: "PET_SUGGESTION", actorPetId: "pet-2" }
|
||||
);
|
||||
await flush();
|
||||
|
||||
expect(sendExpoPushNotification).toHaveBeenCalledWith(
|
||||
"ExponentPushToken[abc]",
|
||||
expect.objectContaining({ title: "Vorschlag für dich", body: "Luna könnte dir gefallen!" })
|
||||
);
|
||||
});
|
||||
|
||||
it("never throws from notify() even if the push request itself rejects", async () => {
|
||||
sendExpoPushNotification.mockRejectedValueOnce(new Error("Expo push down"));
|
||||
const mockPrisma = createMockPrisma();
|
||||
|
||||
@@ -126,6 +126,42 @@ describe("owner.setHideSpidersPreference", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("owner.getPetSuggestionsPreference", () => {
|
||||
it("defaults to true when the Owner row does not exist yet", async () => {
|
||||
const { caller, mockPrisma } = await createOwnerCaller();
|
||||
mockPrisma.owner.findUnique.mockResolvedValue(null);
|
||||
|
||||
const result = await caller.owner.getPetSuggestionsPreference();
|
||||
|
||||
expect(result).toEqual({ petSuggestionsEnabled: true });
|
||||
});
|
||||
|
||||
it("returns the stored preference when set", async () => {
|
||||
const { caller, mockPrisma } = await createOwnerCaller();
|
||||
mockPrisma.owner.findUnique.mockResolvedValue({ petSuggestionsEnabled: false });
|
||||
|
||||
const result = await caller.owner.getPetSuggestionsPreference();
|
||||
|
||||
expect(result).toEqual({ petSuggestionsEnabled: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("owner.setPetSuggestionsPreference", () => {
|
||||
it("upserts the preference on the calling owner (works even before the Owner row exists)", async () => {
|
||||
const { caller, mockPrisma } = await createOwnerCaller();
|
||||
mockPrisma.owner.upsert.mockResolvedValue({ id: "owner-1" });
|
||||
|
||||
const result = await caller.owner.setPetSuggestionsPreference({ petSuggestionsEnabled: false });
|
||||
|
||||
expect(mockPrisma.owner.upsert).toHaveBeenCalledWith({
|
||||
where: { id: "owner-1" },
|
||||
create: { id: "owner-1", petSuggestionsEnabled: false },
|
||||
update: { petSuggestionsEnabled: false },
|
||||
});
|
||||
expect(result).toEqual({ ok: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe("owner.registerPushToken", () => {
|
||||
it("upserts the Expo push token on the calling owner", async () => {
|
||||
const { caller, mockPrisma } = await createOwnerCaller();
|
||||
|
||||
@@ -89,6 +89,56 @@ describe("stories.create", () => {
|
||||
caller.create({ petId: "pet-2", storageKey: "stories/owner-1/pet-1/uuid.jpg" })
|
||||
).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
});
|
||||
|
||||
it("attaches a musicTrackId + musicOffsetSecs when the track is active", async () => {
|
||||
const { caller, mockPrisma } = createCaller();
|
||||
|
||||
mockPrisma.pet.findUnique.mockResolvedValue({ id: "pet-1", ownerId: "owner-1" });
|
||||
mockPrisma.musicTrack.findUnique.mockResolvedValue({ active: true });
|
||||
mockPrisma.story.create.mockResolvedValue({ id: "story-1" });
|
||||
|
||||
await caller.create({
|
||||
petId: "pet-1",
|
||||
storageKey: "stories/owner-1/pet-1/uuid.jpg",
|
||||
musicTrackId: "track-1",
|
||||
musicOffsetSecs: 3,
|
||||
});
|
||||
|
||||
expect(mockPrisma.story.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ musicTrackId: "track-1", musicOffsetSecs: 3 }),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an inactive music track with BAD_REQUEST", async () => {
|
||||
const { caller, mockPrisma } = createCaller();
|
||||
|
||||
mockPrisma.pet.findUnique.mockResolvedValue({ id: "pet-1", ownerId: "owner-1" });
|
||||
mockPrisma.musicTrack.findUnique.mockResolvedValue({ active: false });
|
||||
|
||||
await expect(
|
||||
caller.create({
|
||||
petId: "pet-1",
|
||||
storageKey: "stories/owner-1/pet-1/uuid.jpg",
|
||||
musicTrackId: "track-1",
|
||||
})
|
||||
).rejects.toMatchObject({ code: "BAD_REQUEST" });
|
||||
expect(mockPrisma.story.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a musicTrackId that doesn't exist with BAD_REQUEST", async () => {
|
||||
const { caller, mockPrisma } = createCaller();
|
||||
|
||||
mockPrisma.pet.findUnique.mockResolvedValue({ id: "pet-1", ownerId: "owner-1" });
|
||||
mockPrisma.musicTrack.findUnique.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
caller.create({
|
||||
petId: "pet-1",
|
||||
storageKey: "stories/owner-1/pet-1/uuid.jpg",
|
||||
musicTrackId: "does-not-exist",
|
||||
})
|
||||
).rejects.toMatchObject({ code: "BAD_REQUEST" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("stories.hasActiveStory", () => {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createTRPCCaller } from "@/trpc/server";
|
||||
import { Sidebar } from "@/components/layout/Sidebar";
|
||||
import { MobileNav } from "@/components/layout/MobileNav";
|
||||
import { ActivePetInitializer } from "@/components/layout/ActivePetInitializer";
|
||||
import { SignOutCleanup } from "@/components/layout/SignOutCleanup";
|
||||
import { ThemeInitializer } from "@/components/layout/ThemeInitializer";
|
||||
import { LegalUpdateBanner } from "@/components/legal/LegalUpdateBanner";
|
||||
import { BroadcastBanner } from "@/components/broadcast/BroadcastBanner";
|
||||
@@ -77,6 +78,7 @@ export default async function AppLayout({
|
||||
<ClerkThemeProvider>
|
||||
<div className="flex min-h-screen">
|
||||
<ActivePetInitializer firstPetId={pets[0].id} />
|
||||
<SignOutCleanup />
|
||||
<ThemeInitializer dbTheme={dbTheme} />
|
||||
<LegalUpdateBanner />
|
||||
<BroadcastBanner />
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Bell, UserPlus, Heart, MessageCircle, Cake, Home, AtSign, Repeat2 } from "lucide-react";
|
||||
import { Bell, UserPlus, Heart, MessageCircle, Cake, Home, AtSign, Repeat2, Sparkles } from "lucide-react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import { useActivePet } from "@/context/ActivePetContext";
|
||||
@@ -16,18 +16,19 @@ import type { PostCardPost } from "@/components/feed/PostCard";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { formatRelativeCompact } from "@/lib/format-relative-time";
|
||||
|
||||
type NotificationType = "FOLLOW" | "REACTION" | "COMMENT" | "MESSAGE" | "BIRTHDAY" | "ADOPTION_DAY" | "MENTION" | "PAW_BACK";
|
||||
type NotificationType = "FOLLOW" | "REACTION" | "COMMENT" | "MESSAGE" | "BIRTHDAY" | "ADOPTION_DAY" | "MENTION" | "PAW_BACK" | "PET_SUGGESTION";
|
||||
|
||||
function notificationIcon(type: NotificationType) {
|
||||
switch (type) {
|
||||
case "FOLLOW": return <UserPlus className="h-4 w-4 text-orange-500" />;
|
||||
case "REACTION": return <Heart className="h-4 w-4 text-orange-500" />;
|
||||
case "COMMENT": return <MessageCircle className="h-4 w-4 text-orange-500" />;
|
||||
case "MESSAGE": return <MessageCircle className="h-4 w-4 text-blue-500" />;
|
||||
case "BIRTHDAY": return <Cake className="h-4 w-4 text-pink-500" />;
|
||||
case "ADOPTION_DAY": return <Home className="h-4 w-4 text-emerald-500" />;
|
||||
case "MENTION": return <AtSign className="h-4 w-4 text-violet-500" />;
|
||||
case "PAW_BACK": return <Repeat2 className="h-4 w-4 text-orange-500" />;
|
||||
case "FOLLOW": return <UserPlus className="h-4 w-4 text-orange-500" />;
|
||||
case "REACTION": return <Heart className="h-4 w-4 text-orange-500" />;
|
||||
case "COMMENT": return <MessageCircle className="h-4 w-4 text-orange-500" />;
|
||||
case "MESSAGE": return <MessageCircle className="h-4 w-4 text-blue-500" />;
|
||||
case "BIRTHDAY": return <Cake className="h-4 w-4 text-pink-500" />;
|
||||
case "ADOPTION_DAY": return <Home className="h-4 w-4 text-emerald-500" />;
|
||||
case "MENTION": return <AtSign className="h-4 w-4 text-violet-500" />;
|
||||
case "PAW_BACK": return <Repeat2 className="h-4 w-4 text-orange-500" />;
|
||||
case "PET_SUGGESTION": return <Sparkles className="h-4 w-4 text-amber-500" />;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,6 +90,7 @@ export default function NotificationsPage() {
|
||||
function getHref(notif: (typeof notifications)[number]): string | null {
|
||||
switch (notif.type) {
|
||||
case "FOLLOW":
|
||||
case "PET_SUGGESTION":
|
||||
return notif.actorPet ? `/pets/${notif.actorPet.id}` : null;
|
||||
case "BIRTHDAY":
|
||||
case "ADOPTION_DAY":
|
||||
@@ -223,6 +225,7 @@ export default function NotificationsPage() {
|
||||
{notif.type === "PAW_BACK" && t("typePawBack")}
|
||||
{notif.type === "BIRTHDAY" && t("typeBirthday")}
|
||||
{notif.type === "ADOPTION_DAY" && t("typeAdoptionDay")}
|
||||
{notif.type === "PET_SUGGESTION" && t("typePetSuggestion")}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
|
||||
@@ -5,6 +5,7 @@ import { buttonVariants } from "@/components/ui/button";
|
||||
import { PetGrid } from "./PetGrid";
|
||||
import { DeleteAccountDialog } from "@/components/account/DeleteAccountDialog";
|
||||
import { HideSpidersToggle } from "@/components/account/HideSpidersToggle";
|
||||
import { PetSuggestionsToggle } from "@/components/account/PetSuggestionsToggle";
|
||||
|
||||
/**
|
||||
* My Pets page — /pets
|
||||
@@ -34,8 +35,9 @@ export default async function PetsPage({
|
||||
|
||||
<PetGrid pets={pets} />
|
||||
|
||||
<div className="mt-10">
|
||||
<div className="mt-10 space-y-4">
|
||||
<HideSpidersToggle />
|
||||
<PetSuggestionsToggle />
|
||||
</div>
|
||||
|
||||
<div className="mt-6 pt-4 border-t flex items-center justify-center gap-4 text-xs text-muted-foreground">
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { timingSafeStringEqual } from "@/lib/timing-safe-compare";
|
||||
import { getSpiderExclusionId } from "@/lib/spider-exclusion";
|
||||
import { sendPushForNotification } from "@/lib/notify";
|
||||
|
||||
// Same auth pattern as src/app/api/cron/anniversaries/route.ts — Vercel-style
|
||||
// cron trigger is inert on this self-hosted deployment, needs an external
|
||||
// (NAS crontab) trigger sending `Authorization: Bearer <CRON_SECRET>`.
|
||||
function authorized(req: Request): boolean {
|
||||
const secret = process.env.CRON_SECRET;
|
||||
if (!secret) return false;
|
||||
return timingSafeStringEqual(req.headers.get("authorization") ?? "", `Bearer ${secret}`);
|
||||
}
|
||||
|
||||
const SUGGESTION_COOLDOWN_MS = 30 * 24 * 60 * 60 * 1000; // don't repeat a suggestion within 30 days
|
||||
const CANDIDATE_POOL_SIZE = 20;
|
||||
|
||||
function mostCommonId(ids: (string | null)[]): string | null {
|
||||
const counts = new Map<string, number>();
|
||||
for (const id of ids) {
|
||||
if (!id) continue;
|
||||
counts.set(id, (counts.get(id) ?? 0) + 1);
|
||||
}
|
||||
let best: string | null = null;
|
||||
let bestCount = 0;
|
||||
for (const [id, count] of counts) {
|
||||
if (count > bestCount) {
|
||||
best = id;
|
||||
bestCount = count;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1 "pet suggestion" heuristic — no location/interest data exists (see root
|
||||
* CLAUDE.md), so this works purely off Species/Breed affinity inferred from
|
||||
* the pet's own Follow graph, falling back to the pet's own species/breed for
|
||||
* a pet that doesn't follow anyone yet. One query pass per pet: fine at this
|
||||
* app's current scale, revisit if the pet count grows large.
|
||||
*/
|
||||
export async function GET(req: Request) {
|
||||
if (!authorized(req)) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const suggestionCooldownStart = new Date(Date.now() - SUGGESTION_COOLDOWN_MS);
|
||||
|
||||
const pets = await prisma.pet.findMany({
|
||||
where: { owner: { petSuggestionsEnabled: true } },
|
||||
select: { id: true, speciesId: true, breedId: true, ownerId: true },
|
||||
});
|
||||
|
||||
let created = 0;
|
||||
|
||||
for (const pet of pets) {
|
||||
const spiderExclusionId = await getSpiderExclusionId(prisma, pet.ownerId);
|
||||
|
||||
const follows = await prisma.follow.findMany({
|
||||
where: { followerPetId: pet.id },
|
||||
select: { followeePetId: true, followee: { select: { speciesId: true, breedId: true } } },
|
||||
});
|
||||
|
||||
const targetSpeciesId =
|
||||
follows.length > 0 ? (mostCommonId(follows.map((f) => f.followee.speciesId)) ?? pet.speciesId) : pet.speciesId;
|
||||
const targetBreedId =
|
||||
follows.length > 0 ? mostCommonId(follows.map((f) => f.followee.breedId)) : pet.breedId;
|
||||
|
||||
const blocks = await prisma.block.findMany({
|
||||
where: { OR: [{ blockerPetId: pet.id }, { blockedPetId: pet.id }] },
|
||||
select: { blockerPetId: true, blockedPetId: true },
|
||||
});
|
||||
|
||||
const recentSuggestions = await prisma.notification.findMany({
|
||||
where: { recipientPetId: pet.id, type: "PET_SUGGESTION", createdAt: { gte: suggestionCooldownStart } },
|
||||
select: { actorPetId: true },
|
||||
});
|
||||
|
||||
const excludedPetIds = new Set<string>([
|
||||
pet.id,
|
||||
...follows.map((f) => f.followeePetId),
|
||||
...blocks.flatMap((b) => [b.blockerPetId, b.blockedPetId]),
|
||||
...recentSuggestions.map((n) => n.actorPetId).filter((id): id is string => !!id),
|
||||
]);
|
||||
|
||||
const candidates = await prisma.pet.findMany({
|
||||
where: {
|
||||
id: { notIn: Array.from(excludedPetIds) },
|
||||
speciesId: targetSpeciesId,
|
||||
owner: { shadowban: null },
|
||||
...(spiderExclusionId ? { NOT: { speciesId: spiderExclusionId } } : {}),
|
||||
},
|
||||
select: { id: true, breedId: true, _count: { select: { followers: true } } },
|
||||
take: CANDIDATE_POOL_SIZE,
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
const best = candidates.sort((a, b) => {
|
||||
const aBreedMatch = targetBreedId && a.breedId === targetBreedId ? 1 : 0;
|
||||
const bBreedMatch = targetBreedId && b.breedId === targetBreedId ? 1 : 0;
|
||||
if (aBreedMatch !== bBreedMatch) return bBreedMatch - aBreedMatch;
|
||||
return b._count.followers - a._count.followers;
|
||||
})[0];
|
||||
|
||||
if (!best) continue;
|
||||
|
||||
await prisma.notification.create({
|
||||
data: { recipientPetId: pet.id, type: "PET_SUGGESTION", actorPetId: best.id },
|
||||
});
|
||||
created++;
|
||||
|
||||
await sendPushForNotification(prisma, {
|
||||
recipientPetId: pet.id,
|
||||
type: "PET_SUGGESTION",
|
||||
actorPetId: best.id,
|
||||
}).catch((err) => console.error("[cron/pet-suggestions] push failed", err));
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true, petsScanned: pets.length, notificationsCreated: created });
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
MessageCircle,
|
||||
ArrowLeft,
|
||||
Radio,
|
||||
Music,
|
||||
} from "lucide-react";
|
||||
|
||||
interface AdminLayoutProps {
|
||||
@@ -62,6 +63,7 @@ export default async function AdminLayout({ children, params }: AdminLayoutProps
|
||||
{ href: `${base}/users`, label: "Users", Icon: Users },
|
||||
{ href: `${base}/messages`, label: "Messages", Icon: MessageCircle },
|
||||
{ href: `${base}/ads`, label: "Ads", Icon: Megaphone },
|
||||
{ href: `${base}/music`, label: "Musik-Katalog", Icon: Music },
|
||||
{ href: `${base}/moderators`, label: "Moderators", Icon: ShieldCheck },
|
||||
{ href: `${base}/legal`, label: "Legal", Icon: Scale },
|
||||
...(isModeratorOrAbove
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef, useCallback } from "react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import { getMusicUrl } from "@/lib/music-url";
|
||||
import { Plus, Pencil, Trash2, Loader2, Check, X, Music, Play, Pause } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { toast } from "sonner";
|
||||
|
||||
type TrackForm = {
|
||||
title: string;
|
||||
artist: string;
|
||||
licenseNote: string;
|
||||
storageKey: string;
|
||||
durationSecs: number;
|
||||
};
|
||||
|
||||
const emptyForm: TrackForm = { title: "", artist: "", licenseNote: "", storageKey: "", durationSecs: 0 };
|
||||
|
||||
const ALLOWED_TYPES = ["audio/mpeg", "audio/mp4", "audio/aac"] as const;
|
||||
type AllowedType = (typeof ALLOWED_TYPES)[number];
|
||||
const MAX_SIZE = 5 * 1024 * 1024;
|
||||
|
||||
/** Reads an audio file's duration client-side via a detached <audio> element. */
|
||||
function readAudioDuration(file: File): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const audio = new Audio();
|
||||
const url = URL.createObjectURL(file);
|
||||
audio.addEventListener("loadedmetadata", () => {
|
||||
URL.revokeObjectURL(url);
|
||||
resolve(audio.duration);
|
||||
});
|
||||
audio.addEventListener("error", () => {
|
||||
URL.revokeObjectURL(url);
|
||||
reject(new Error("Could not read audio duration"));
|
||||
});
|
||||
audio.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
export default function AdminMusicPage() {
|
||||
const trpc = useTRPC();
|
||||
const qc = useQueryClient();
|
||||
const [form, setForm] = useState<TrackForm>(emptyForm);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [playingId, setPlayingId] = useState<string | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
|
||||
const { data: rawTracks, isLoading } = useQuery(trpc.admin.listMusicTracks.queryOptions(undefined));
|
||||
const tracks = rawTracks ?? [];
|
||||
|
||||
const invalidate = () => void qc.invalidateQueries({ queryKey: trpc.admin.listMusicTracks.queryKey() });
|
||||
|
||||
const getUploadUrl = useMutation(trpc.admin.getMusicTrackUploadUrl.mutationOptions());
|
||||
|
||||
const createTrack = useMutation(
|
||||
trpc.admin.createMusicTrack.mutationOptions({ onSuccess: () => { invalidate(); closeDialog(); } })
|
||||
);
|
||||
const updateTrack = useMutation(
|
||||
trpc.admin.updateMusicTrack.mutationOptions({ onSuccess: () => { invalidate(); closeDialog(); } })
|
||||
);
|
||||
const deleteTrack = useMutation(
|
||||
trpc.admin.deleteMusicTrack.mutationOptions({ onSuccess: () => { invalidate(); setDeleteId(null); } })
|
||||
);
|
||||
|
||||
function openCreate() {
|
||||
setForm(emptyForm);
|
||||
setEditingId(null);
|
||||
setDialogOpen(true);
|
||||
}
|
||||
|
||||
function openEdit(track: (typeof tracks)[number]) {
|
||||
setForm({
|
||||
title: track.title,
|
||||
artist: track.artist,
|
||||
licenseNote: track.licenseNote,
|
||||
storageKey: track.storageKey,
|
||||
durationSecs: track.durationSecs,
|
||||
});
|
||||
setEditingId(track.id);
|
||||
setDialogOpen(true);
|
||||
}
|
||||
|
||||
function closeDialog() {
|
||||
setDialogOpen(false);
|
||||
setEditingId(null);
|
||||
setForm(emptyForm);
|
||||
}
|
||||
|
||||
function submitForm() {
|
||||
if (editingId) {
|
||||
updateTrack.mutate({
|
||||
id: editingId,
|
||||
title: form.title,
|
||||
artist: form.artist,
|
||||
licenseNote: form.licenseNote,
|
||||
});
|
||||
} else {
|
||||
createTrack.mutate(form);
|
||||
}
|
||||
}
|
||||
|
||||
const uploadFile = useCallback(
|
||||
async (file: File) => {
|
||||
if (file.size > MAX_SIZE) {
|
||||
toast.error("Audiodatei muss unter 5 MB sein.");
|
||||
return;
|
||||
}
|
||||
if (!ALLOWED_TYPES.includes(file.type as AllowedType)) {
|
||||
toast.error("Nur MP3, M4A oder AAC erlaubt.");
|
||||
return;
|
||||
}
|
||||
|
||||
setUploading(true);
|
||||
try {
|
||||
const durationSecs = await readAudioDuration(file);
|
||||
const { presignedUrl, key } = await getUploadUrl.mutateAsync({
|
||||
contentType: file.type as AllowedType,
|
||||
fileSize: file.size,
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.onload = () =>
|
||||
xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error(`Upload failed: ${xhr.status}`));
|
||||
xhr.onerror = () => reject(new Error("Network error"));
|
||||
xhr.open("PUT", presignedUrl);
|
||||
xhr.setRequestHeader("Content-Type", file.type);
|
||||
xhr.send(file);
|
||||
});
|
||||
|
||||
setForm((f) => ({ ...f, storageKey: key, durationSecs }));
|
||||
toast.success("Track hochgeladen");
|
||||
} catch {
|
||||
toast.error("Upload fehlgeschlagen — bitte erneut versuchen");
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
},
|
||||
[getUploadUrl]
|
||||
);
|
||||
|
||||
function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) void uploadFile(file);
|
||||
e.target.value = "";
|
||||
}
|
||||
|
||||
function togglePlay(track: (typeof tracks)[number]) {
|
||||
if (playingId === track.id) {
|
||||
audioRef.current?.pause();
|
||||
setPlayingId(null);
|
||||
return;
|
||||
}
|
||||
audioRef.current?.pause();
|
||||
const audio = new Audio(getMusicUrl(track.storageKey) ?? "");
|
||||
audio.play();
|
||||
audio.addEventListener("ended", () => setPlayingId(null));
|
||||
audioRef.current = audio;
|
||||
setPlayingId(track.id);
|
||||
}
|
||||
|
||||
const isPending = createTrack.isPending || updateTrack.isPending;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold text-zinc-100">Musik-Katalog</h1>
|
||||
<Button size="sm" onClick={openCreate} className="bg-orange-500 hover:bg-orange-600 text-white">
|
||||
<Plus className="h-4 w-4 mr-1.5" />
|
||||
Neuer Track
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex justify-center py-12">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-zinc-500" />
|
||||
</div>
|
||||
) : tracks.length === 0 ? (
|
||||
<p className="text-sm text-zinc-500 text-center py-12">Noch keine Tracks — oben hochladen</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{tracks.map((track) => (
|
||||
<div
|
||||
key={track.id}
|
||||
className="flex items-center gap-4 rounded-xl border border-zinc-800 bg-zinc-900 px-4 py-3"
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-10 w-10 rounded-full bg-zinc-800 text-zinc-300 shrink-0 p-0"
|
||||
onClick={() => togglePlay(track)}
|
||||
>
|
||||
{playingId === track.id ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
|
||||
</Button>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm font-medium text-zinc-100 truncate">{track.title}</p>
|
||||
{track.active ? (
|
||||
<Badge className="bg-green-700 text-green-100 text-[10px]">Aktiv</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-[10px]">Inaktiv</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-zinc-500 truncate mt-0.5">
|
||||
{track.artist} · {Math.round(track.durationSecs)}s
|
||||
</p>
|
||||
<p className="text-xs text-zinc-600 truncate">{track.licenseNote}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 shrink-0">
|
||||
<Button size="sm" variant="ghost" className="text-zinc-400 hover:text-zinc-100" onClick={() => openEdit(track)}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" className="text-red-400 hover:text-red-300" onClick={() => setDeleteId(track.id)}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Create / Edit dialog */}
|
||||
<Dialog open={dialogOpen} onOpenChange={(o) => { if (!o) closeDialog(); }}>
|
||||
<DialogContent className="bg-zinc-900 border-zinc-800 text-zinc-100 max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingId ? "Track bearbeiten" : "Track hochladen"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-3">
|
||||
{!editingId && (
|
||||
<div>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="audio/mpeg,audio/mp4,audio/aac"
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
{form.storageKey ? (
|
||||
<div className="flex items-center gap-2 rounded-xl border border-zinc-700 px-3 py-2 text-sm text-zinc-300">
|
||||
<Music className="h-4 w-4 text-orange-500" />
|
||||
{Math.round(form.durationSecs)}s Audiodatei bereit
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setForm((f) => ({ ...f, storageKey: "", durationSecs: 0 }))}
|
||||
className="ml-auto h-5 w-5 rounded-full bg-zinc-800 flex items-center justify-center hover:bg-zinc-700"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={uploading}
|
||||
className="w-full h-20 rounded-xl border-2 border-dashed border-zinc-700 hover:border-zinc-500 flex flex-col items-center justify-center gap-2 text-zinc-500 hover:text-zinc-300 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{uploading ? (
|
||||
<Loader2 className="h-6 w-6 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<Music className="h-6 w-6" />
|
||||
<span className="text-xs">Audio hochladen (MP3, M4A, AAC · max 5 MB)</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Input
|
||||
placeholder="Titel *"
|
||||
value={form.title}
|
||||
onChange={(e) => setForm({ ...form, title: e.target.value })}
|
||||
className="bg-zinc-800 border-zinc-700 text-zinc-100 placeholder:text-zinc-500"
|
||||
/>
|
||||
<Input
|
||||
placeholder="Künstler *"
|
||||
value={form.artist}
|
||||
onChange={(e) => setForm({ ...form, artist: e.target.value })}
|
||||
className="bg-zinc-800 border-zinc-700 text-zinc-100 placeholder:text-zinc-500"
|
||||
/>
|
||||
<Textarea
|
||||
placeholder="Lizenz/Quelle * (z.B. Name der Musikbibliothek, Lizenztyp, Link)"
|
||||
value={form.licenseNote}
|
||||
onChange={(e) => setForm({ ...form, licenseNote: e.target.value })}
|
||||
className="bg-zinc-800 border-zinc-700 text-zinc-100 placeholder:text-zinc-500 resize-none"
|
||||
rows={3}
|
||||
/>
|
||||
|
||||
{editingId && (
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch
|
||||
checked={tracks.find((t) => t.id === editingId)?.active ?? true}
|
||||
onCheckedChange={(v: boolean) => updateTrack.mutate({ id: editingId, active: v })}
|
||||
/>
|
||||
<span className="text-sm text-zinc-300">Aktiv (im Story-Picker sichtbar)</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="gap-2 mt-2">
|
||||
<Button variant="ghost" className="text-zinc-400" onClick={closeDialog}>
|
||||
<X className="h-4 w-4 mr-1.5" />
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button
|
||||
onClick={submitForm}
|
||||
disabled={
|
||||
isPending ||
|
||||
uploading ||
|
||||
!form.title.trim() ||
|
||||
!form.artist.trim() ||
|
||||
!form.licenseNote.trim() ||
|
||||
(!editingId && !form.storageKey)
|
||||
}
|
||||
className="bg-orange-500 hover:bg-orange-600 text-white"
|
||||
>
|
||||
{isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin mr-2" />
|
||||
) : (
|
||||
<Check className="h-4 w-4 mr-1.5" />
|
||||
)}
|
||||
{editingId ? "Speichern" : "Erstellen"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete confirm */}
|
||||
<Dialog open={!!deleteId} onOpenChange={(o) => { if (!o) setDeleteId(null); }}>
|
||||
<DialogContent className="bg-zinc-900 border-zinc-800 text-zinc-100 max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Track löschen</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-zinc-400">
|
||||
Diesen Track dauerhaft löschen? Stories, die ihn bereits verwenden, behalten ihn (Referenz wird nur
|
||||
entfernt) — falls unsicher, lieber oben auf „Inaktiv“ schalten statt löschen.
|
||||
</p>
|
||||
<DialogFooter className="gap-2">
|
||||
<Button variant="ghost" className="text-zinc-400" onClick={() => setDeleteId(null)}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => deleteTrack.mutate({ id: deleteId! })}
|
||||
disabled={deleteTrack.isPending}
|
||||
>
|
||||
{deleteTrack.isPending && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
Löschen
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
|
||||
/**
|
||||
* Opt-out for the PET_SUGGESTION cron notification
|
||||
* (src/app/api/cron/pet-suggestions) — on by default, always re-toggleable
|
||||
* on /pets. Mirrors HideSpidersToggle.tsx's structure exactly.
|
||||
*/
|
||||
export function PetSuggestionsToggle() {
|
||||
const t = useTranslations("PetSuggestionsToggle");
|
||||
const trpc = useTRPC();
|
||||
const qc = useQueryClient();
|
||||
|
||||
const { data } = useQuery(trpc.owner.getPetSuggestionsPreference.queryOptions());
|
||||
|
||||
const setPreferenceMutation = useMutation(
|
||||
trpc.owner.setPetSuggestionsPreference.mutationOptions({
|
||||
onSuccess: () => {
|
||||
void qc.invalidateQueries({ queryKey: trpc.owner.getPetSuggestionsPreference.queryKey() });
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
const petSuggestionsEnabled = data?.petSuggestionsEnabled ?? true;
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-4 rounded-xl border bg-card p-4">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-foreground">{t("label")}</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">{t("description")}</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={petSuggestionsEnabled}
|
||||
onCheckedChange={(checked: boolean) => setPreferenceMutation.mutate({ petSuggestionsEnabled: checked })}
|
||||
disabled={setPreferenceMutation.isPending}
|
||||
aria-label={t("label")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useAuth } from "@clerk/nextjs";
|
||||
import { useActivePet } from "@/context/ActivePetContext";
|
||||
|
||||
/**
|
||||
* Mounts invisibly in the app shell (inside ClerkThemeProvider, alongside
|
||||
* ActivePetInitializer). Clears the persisted activePetId as soon as
|
||||
* isSignedIn flips to false, so the next owner to sign in on this browser
|
||||
* (shared device, or the same person switching Clerk accounts) doesn't
|
||||
* inherit a foreign petId from localStorage — every pet-scoped mutation
|
||||
* would otherwise fail with assertPetOwnership's FORBIDDEN error (found.md:
|
||||
* "you do not have permission to access this pet"). Mirrors mobile's
|
||||
* LogoutSection, which calls the same clearActivePetId() explicitly on its
|
||||
* own sign-out button — web has no custom sign-out button (Clerk's
|
||||
* <UserButton/> handles it internally), so this watches the auth state
|
||||
* itself instead of hooking a click handler.
|
||||
*/
|
||||
export function SignOutCleanup() {
|
||||
const { isSignedIn } = useAuth();
|
||||
const { clearActivePetId } = useActivePet();
|
||||
const wasSignedIn = useRef(isSignedIn);
|
||||
|
||||
useEffect(() => {
|
||||
if (wasSignedIn.current && isSignedIn === false) {
|
||||
clearActivePetId();
|
||||
}
|
||||
wasSignedIn.current = isSignedIn;
|
||||
}, [isSignedIn, clearActivePetId]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,16 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef, useCallback } from "react";
|
||||
import { Camera, Loader2, ImagePlus, Video } from "lucide-react";
|
||||
import { Camera, Loader2, ImagePlus, Video, Music, Play, Pause, X } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { toast } from "sonner";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
import { useActivePet } from "@/context/ActivePetContext";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { computeBlurhash } from "@/lib/blurhash";
|
||||
import { uploadFileWithProgress } from "@/lib/upload-xhr";
|
||||
import { getMusicUrl } from "@/lib/music-url";
|
||||
import { AiDisclosureSelect, type AiDisclosureValue } from "@/components/content/AiDisclosureSelect";
|
||||
import { MAX_STORY_VIDEO_DURATION_SECS } from "@/lib/story-video-limits";
|
||||
|
||||
@@ -81,6 +83,26 @@ export function StoryForm({ onClose }: StoryFormProps) {
|
||||
const [uploadedBlurhash, setUploadedBlurhash] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [aiDisclosure, setAiDisclosure] = useState<AiDisclosureValue>("NONE");
|
||||
const [musicTrackId, setMusicTrackId] = useState<string | null>(null);
|
||||
const [musicMuteOriginal, setMusicMuteOriginal] = useState(false);
|
||||
const [previewingTrackId, setPreviewingTrackId] = useState<string | null>(null);
|
||||
const previewAudioRef = useRef<HTMLAudioElement | null>(null);
|
||||
|
||||
const { data: musicTracks } = useQuery(trpc.stories.listMusicTracks.queryOptions());
|
||||
|
||||
const togglePreview = useCallback((trackId: string, storageKey: string) => {
|
||||
if (previewingTrackId === trackId) {
|
||||
previewAudioRef.current?.pause();
|
||||
setPreviewingTrackId(null);
|
||||
return;
|
||||
}
|
||||
previewAudioRef.current?.pause();
|
||||
const audio = new Audio(getMusicUrl(storageKey) ?? "");
|
||||
audio.addEventListener("ended", () => setPreviewingTrackId(null));
|
||||
void audio.play();
|
||||
previewAudioRef.current = audio;
|
||||
setPreviewingTrackId(trackId);
|
||||
}, [previewingTrackId]);
|
||||
|
||||
const getPresignedUrlMutation = useMutation(
|
||||
trpc.stories.getPresignedUrl.mutationOptions()
|
||||
@@ -234,6 +256,7 @@ export function StoryForm({ onClose }: StoryFormProps) {
|
||||
storageKey: uploadedKey,
|
||||
blurhash: uploadedBlurhash,
|
||||
aiDisclosure,
|
||||
musicTrackId: musicTrackId ?? undefined,
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -244,6 +267,8 @@ export function StoryForm({ onClose }: StoryFormProps) {
|
||||
const { uploadUrl } = await createVideoUploadMutation.mutateAsync({
|
||||
petId: activePetId,
|
||||
aiDisclosure,
|
||||
musicTrackId: musicTrackId ?? undefined,
|
||||
musicMuteOriginal: musicTrackId ? musicMuteOriginal : false,
|
||||
});
|
||||
await uploadFileWithProgress(uploadUrl ?? "", selectedFile, {
|
||||
onProgress: setUploadProgress,
|
||||
@@ -262,6 +287,8 @@ export function StoryForm({ onClose }: StoryFormProps) {
|
||||
uploadedKey,
|
||||
uploadedBlurhash,
|
||||
aiDisclosure,
|
||||
musicTrackId,
|
||||
musicMuteOriginal,
|
||||
selectedFile,
|
||||
createStoryMutation,
|
||||
createVideoUploadMutation,
|
||||
@@ -360,6 +387,63 @@ export function StoryForm({ onClose }: StoryFormProps) {
|
||||
<AiDisclosureSelect value={aiDisclosure} onChange={setAiDisclosure} />
|
||||
)}
|
||||
|
||||
{uploadState === "ready" && musicTracks && musicTracks.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-1.5 text-sm font-medium">
|
||||
<Music className="h-4 w-4" aria-hidden="true" />
|
||||
{t("musicLabel")}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{musicTracks.map((track) => (
|
||||
<button
|
||||
key={track.id}
|
||||
type="button"
|
||||
onClick={() => setMusicTrackId((id) => (id === track.id ? null : track.id))}
|
||||
className={`flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs transition-colors
|
||||
${musicTrackId === track.id ? "border-orange-500 bg-orange-500/10 text-orange-600" : "border-muted text-muted-foreground hover:border-muted-foreground/50"}`}
|
||||
>
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
togglePreview(track.id, track.storageKey);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.stopPropagation();
|
||||
togglePreview(track.id, track.storageKey);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{previewingTrackId === track.id ? (
|
||||
<Pause className="h-3 w-3" aria-hidden="true" />
|
||||
) : (
|
||||
<Play className="h-3 w-3" aria-hidden="true" />
|
||||
)}
|
||||
</span>
|
||||
{track.title}
|
||||
{musicTrackId === track.id && (
|
||||
<X
|
||||
className="h-3 w-3"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setMusicTrackId(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{mediaKind === "video" && musicTrackId && (
|
||||
<label className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Switch checked={musicMuteOriginal} onCheckedChange={setMusicMuteOriginal} />
|
||||
{t("muteOriginalLabel")}
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
{t("disappearsNote")}
|
||||
</p>
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
} from "@/components/ui/sheet";
|
||||
import { getAvatarUrl } from "@/lib/avatar-url";
|
||||
import { getMediaUrl } from "@/lib/media-url";
|
||||
import { getMusicUrl } from "@/lib/music-url";
|
||||
import { BlurImage } from "@/components/ui/blur-image";
|
||||
import { AiDisclosureBadge } from "@/components/content/AiDisclosureBadge";
|
||||
import { StoryPawButton } from "@/components/stories/StoryPawButton";
|
||||
@@ -71,6 +72,7 @@ export function StoryViewer({
|
||||
const [commentsOpen, setCommentsOpen] = useState(false);
|
||||
const [isMuted, setIsMuted] = useState(true);
|
||||
const advancedRef = useRef(false);
|
||||
const musicAudioRef = useRef<HTMLAudioElement>(null);
|
||||
|
||||
// Portal target must wait for mount (document isn't available during SSR).
|
||||
const [mounted, setMounted] = useState(false);
|
||||
@@ -85,6 +87,11 @@ export function StoryViewer({
|
||||
const currentStory = stories[currentIndex];
|
||||
const isOwnPet = activePetId === petId;
|
||||
const isVideo = currentStory?.mediaType === "VIDEO";
|
||||
const musicUrl = currentStory?.musicTrack ? getMusicUrl(currentStory.musicTrack.storageKey) : null;
|
||||
// For a VIDEO story, the overlay track only plays if musicMuteOriginal was
|
||||
// chosen at creation time (see StoryForm.tsx) — otherwise the video keeps
|
||||
// its own baked-in Mux audio and the track is ignored, even if attached.
|
||||
const shouldPlayMusic = !!musicUrl && open && (!isVideo || currentStory?.musicMuteOriginal);
|
||||
|
||||
// Poll while a video story is still processing — same self-heal pattern
|
||||
// as VideoCard, scoped to just the story currently on screen.
|
||||
@@ -162,6 +169,30 @@ export function StoryViewer({
|
||||
}
|
||||
}, [isVideo, currentStory?.id]);
|
||||
|
||||
// Music overlay — (re)start whenever the current story changes, stop when
|
||||
// this story has none (or music playback isn't applicable, see
|
||||
// shouldPlayMusic above). Not tightly synced to video currentTime — a
|
||||
// simple "start together, stop on advance" is the accepted v1 tradeoff
|
||||
// for VIDEO stories (see the Feature-2 plan's music-overlay section).
|
||||
useEffect(() => {
|
||||
const audio = musicAudioRef.current;
|
||||
if (!audio) return;
|
||||
if (!shouldPlayMusic) {
|
||||
audio.pause();
|
||||
return;
|
||||
}
|
||||
audio.currentTime = currentStory?.musicOffsetSecs ?? 0;
|
||||
audio.muted = isMuted;
|
||||
void audio.play();
|
||||
return () => audio.pause();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [shouldPlayMusic, currentStory?.id]);
|
||||
|
||||
// Mute toggle also controls the music overlay, not just the video's own track.
|
||||
useEffect(() => {
|
||||
if (musicAudioRef.current) musicAudioRef.current.muted = isMuted;
|
||||
}, [isMuted]);
|
||||
|
||||
const handleVideoTimeUpdate = useCallback((e: Event) => {
|
||||
// mux-player's events are raw DOM Events, not React SyntheticEvents —
|
||||
// e.target is the <mux-player> element, which exposes currentTime/
|
||||
@@ -273,7 +304,11 @@ export function StoryViewer({
|
||||
playbackId={videoPlaybackId}
|
||||
streamType="on-demand"
|
||||
autoPlay
|
||||
muted={isMuted}
|
||||
// musicMuteOriginal forces the video's own track off
|
||||
// permanently — the mute button then controls the
|
||||
// overlay track instead (see the music-overlay effects
|
||||
// above), not this player's muted state.
|
||||
muted={currentStory.musicMuteOriginal || isMuted}
|
||||
style={{ width: "100%", height: "100%", objectFit: "contain" }}
|
||||
onTimeUpdate={handleVideoTimeUpdate}
|
||||
onEnded={handleVideoEnded}
|
||||
@@ -320,10 +355,26 @@ export function StoryViewer({
|
||||
value={currentStory.aiDisclosure}
|
||||
className="top-auto left-auto bottom-3 right-3 h-10"
|
||||
/>
|
||||
{musicUrl && (
|
||||
<button
|
||||
className="absolute bottom-3 right-3 flex h-10 w-10 items-center justify-center rounded-full bg-black/40 text-white hover:bg-black/60"
|
||||
onClick={() => setIsMuted((m) => !m)}
|
||||
aria-label={isMuted ? t("unmute") : t("mute")}
|
||||
>
|
||||
{isMuted ? (
|
||||
<VolumeX className="h-4 w-4" aria-hidden="true" />
|
||||
) : (
|
||||
<Volume2 className="h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
{/* Music overlay track — hidden, controlled entirely via musicAudioRef (see effects above). */}
|
||||
{musicUrl && <audio ref={musicAudioRef} src={musicUrl} loop={!isVideo} />}
|
||||
|
||||
{/* Pet info — bottom left */}
|
||||
<div className="absolute bottom-6 left-4 flex items-center gap-2">
|
||||
<Avatar className="w-8 h-8 border border-white/50">
|
||||
|
||||
@@ -18,6 +18,13 @@ import { createContext, useContext, useState } from "react";
|
||||
type ActivePetContextType = {
|
||||
activePetId: string | null;
|
||||
setActivePet: (id: string) => void;
|
||||
/** Call on sign-out — otherwise the next owner to sign in on this browser
|
||||
* (shared device, or the same person switching Clerk accounts) inherits
|
||||
* the previous owner's activePetId from localStorage, and every
|
||||
* pet-scoped mutation fails with assertPetOwnership's FORBIDDEN error
|
||||
* (found.md: "you do not have permission to access this pet"). Mirrors
|
||||
* mobile's ActivePetContext.tsx clearActivePetId(). */
|
||||
clearActivePetId: () => void;
|
||||
};
|
||||
|
||||
const ActivePetContext = createContext<ActivePetContextType | null>(null);
|
||||
@@ -44,8 +51,13 @@ export function ActivePetProvider({ children }: { children: React.ReactNode }) {
|
||||
localStorage.setItem(STORAGE_KEY, id);
|
||||
};
|
||||
|
||||
const clearActivePetId = () => {
|
||||
setActivePetId(null);
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
};
|
||||
|
||||
return (
|
||||
<ActivePetContext.Provider value={{ activePetId, setActivePet }}>
|
||||
<ActivePetContext.Provider value={{ activePetId, setActivePet, clearActivePetId }}>
|
||||
{children}
|
||||
</ActivePetContext.Provider>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Constructs the public CDN URL for a track in the music-tracks bucket.
|
||||
* Mirrors getMediaUrl's pattern (src/lib/media-url.ts) but for the separate
|
||||
* MUSIC_STORAGE_BUCKET — safe to use in both server and client components.
|
||||
*/
|
||||
export function getMusicUrl(key: string | null | undefined): string | null {
|
||||
if (!key) return null;
|
||||
return `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/music-tracks/${key}`;
|
||||
}
|
||||
+6
-1
@@ -38,6 +38,7 @@ const PUSH_COPY: Record<
|
||||
ADOPTION_DAY: { title: "Adoptionstag", genericBody: "Ein Adoptionstag steht an.", actorBody: (a) => `${a} feiert heute den Adoptionstag!` },
|
||||
MENTION: { title: "Erwähnung", genericBody: "Du wurdest in einem Beitrag erwähnt.", actorBody: (a) => `${a} hat dich erwähnt.` },
|
||||
PAW_BACK: { title: "Paw-Back", genericBody: "Jemand hat deinen Beitrag geteilt.", actorBody: (a) => `${a} hat deinen Beitrag geteilt.` },
|
||||
PET_SUGGESTION: { title: "Vorschlag für dich", genericBody: "Ein Tier könnte dir gefallen.", actorBody: (a) => `${a} könnte dir gefallen!` },
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -45,8 +46,12 @@ const PUSH_COPY: Record<
|
||||
* Separate from the in-app Notification row above — a missing/expired push
|
||||
* token, or the owner never having opened the mobile app, is the normal case
|
||||
* and must silently no-op rather than error.
|
||||
*
|
||||
* Exported (not just used via notify() above) so a batch cron job that needs
|
||||
* an awaited, counted prisma.notification.create (see notify()'s own doc
|
||||
* comment) can still trigger the matching push afterward.
|
||||
*/
|
||||
async function sendPushForNotification(
|
||||
export async function sendPushForNotification(
|
||||
prisma: Pick<PrismaClient, "pet" | "owner">,
|
||||
params: NotifyParams
|
||||
): Promise<void> {
|
||||
|
||||
@@ -20,13 +20,20 @@ export const STORAGE_BUCKET = "pet-avatars";
|
||||
export const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
|
||||
export const ALLOWED_CONTENT_TYPES = ["image/jpeg", "image/png", "image/webp"] as const;
|
||||
|
||||
// Music-track catalog (admin-curated, see admin.ts's music-track procedures)
|
||||
// — a separate bucket since it holds audio, not images. Must be created once
|
||||
// in the Supabase dashboard; this code assumes it already exists.
|
||||
export const MUSIC_STORAGE_BUCKET = "music-tracks";
|
||||
export const MAX_MUSIC_FILE_SIZE = 5 * 1024 * 1024; // 5 MB — short clips only
|
||||
export const MUSIC_ALLOWED_CONTENT_TYPES = ["audio/mpeg", "audio/mp4", "audio/aac"] as const;
|
||||
|
||||
/**
|
||||
* Creates a signed upload URL for direct client-to-Supabase uploads.
|
||||
* The client PUTs the file directly to this URL — bytes never pass through the API server.
|
||||
*/
|
||||
export async function createSignedUploadUrl(key: string) {
|
||||
export async function createSignedUploadUrl(key: string, bucket: string = STORAGE_BUCKET) {
|
||||
const { data, error } = await getClient().storage
|
||||
.from(STORAGE_BUCKET)
|
||||
.from(bucket)
|
||||
.createSignedUploadUrl(key);
|
||||
|
||||
if (error) throw new Error(`Storage error: ${error.message}`);
|
||||
@@ -36,8 +43,8 @@ export async function createSignedUploadUrl(key: string) {
|
||||
/**
|
||||
* Returns the public CDN URL for a stored object.
|
||||
*/
|
||||
export function getPublicUrl(key: string): string {
|
||||
const { data } = getClient().storage.from(STORAGE_BUCKET).getPublicUrl(key);
|
||||
export function getPublicUrl(key: string, bucket: string = STORAGE_BUCKET): string {
|
||||
const { data } = getClient().storage.from(bucket).getPublicUrl(key);
|
||||
return data.publicUrl;
|
||||
}
|
||||
|
||||
@@ -45,9 +52,9 @@ export function getPublicUrl(key: string): string {
|
||||
* Deletes a batch of storage objects by key. Non-throwing — storage cleanup
|
||||
* failure is logged but must never block account deletion.
|
||||
*/
|
||||
export async function deleteFiles(keys: string[]): Promise<void> {
|
||||
export async function deleteFiles(keys: string[], bucket: string = STORAGE_BUCKET): Promise<void> {
|
||||
if (keys.length === 0) return;
|
||||
const { error } = await getClient().storage.from(STORAGE_BUCKET).remove(keys);
|
||||
const { error } = await getClient().storage.from(bucket).remove(keys);
|
||||
if (error) {
|
||||
console.error("[storage] deleteFiles partial failure:", error.message);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,9 @@ import {
|
||||
createSignedUploadUrl,
|
||||
ALLOWED_CONTENT_TYPES,
|
||||
MAX_FILE_SIZE,
|
||||
MUSIC_STORAGE_BUCKET,
|
||||
MUSIC_ALLOWED_CONTENT_TYPES,
|
||||
MAX_MUSIC_FILE_SIZE,
|
||||
} from "@/lib/supabase-storage";
|
||||
import { buildDataExport } from "@/lib/gdpr-export";
|
||||
import { uploadExport } from "@/lib/data-export-storage";
|
||||
@@ -1505,6 +1508,118 @@ export const adminRouter = router({
|
||||
});
|
||||
}),
|
||||
|
||||
// ─── Music track catalog (Story music overlay) ────────────────────────────────
|
||||
// Admin-curated only — no user upload path, so copyright liability for each
|
||||
// track stays with the admin who uploaded it (licenseNote is required).
|
||||
getMusicTrackUploadUrl: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
contentType: z.enum(MUSIC_ALLOWED_CONTENT_TYPES),
|
||||
fileSize: z.number().max(MAX_MUSIC_FILE_SIZE, "Audio file must be under 5 MB"),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
const ext = input.contentType.split("/")[1]!.replace("mpeg", "mp3");
|
||||
const key = `tracks/${randomUUID()}.${ext}`;
|
||||
const { signedUrl } = await createSignedUploadUrl(key, MUSIC_STORAGE_BUCKET);
|
||||
return { presignedUrl: signedUrl, key };
|
||||
}),
|
||||
|
||||
listMusicTracks: protectedProcedure
|
||||
.input(z.object({ activeOnly: z.boolean().default(false) }).optional())
|
||||
.query(async ({ ctx, input }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
return ctx.prisma.musicTrack.findMany({
|
||||
where: input?.activeOnly ? { active: true } : undefined,
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}),
|
||||
|
||||
createMusicTrack: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
title: z.string().min(1).max(100),
|
||||
artist: z.string().min(1).max(100),
|
||||
licenseNote: z.string().min(1).max(500),
|
||||
storageKey: z.string().min(1),
|
||||
durationSecs: z.number().positive(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
return ctx.prisma.$transaction(async (tx) => {
|
||||
const track = await tx.musicTrack.create({
|
||||
data: { ...input, createdBy: ctx.userId },
|
||||
});
|
||||
await tx.moderationLog.create({
|
||||
data: {
|
||||
action: "CREATE_MUSIC_TRACK",
|
||||
targetType: "MUSIC_TRACK",
|
||||
targetId: track.id,
|
||||
reason: input.title,
|
||||
moderatorId: ctx.userId,
|
||||
moderatorRole: callerRole,
|
||||
ipAddress: ctx.ip,
|
||||
},
|
||||
});
|
||||
return track;
|
||||
});
|
||||
}),
|
||||
|
||||
updateMusicTrack: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
title: z.string().min(1).max(100).optional(),
|
||||
artist: z.string().min(1).max(100).optional(),
|
||||
licenseNote: z.string().min(1).max(500).optional(),
|
||||
active: z.boolean().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
const { id, ...rest } = input;
|
||||
const [track] = await ctx.prisma.$transaction([
|
||||
ctx.prisma.musicTrack.update({ where: { id }, data: rest }),
|
||||
ctx.prisma.moderationLog.create({
|
||||
data: {
|
||||
action: "UPDATE_MUSIC_TRACK",
|
||||
targetType: "MUSIC_TRACK",
|
||||
targetId: id,
|
||||
moderatorId: ctx.userId,
|
||||
moderatorRole: callerRole,
|
||||
ipAddress: ctx.ip,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
return track;
|
||||
}),
|
||||
|
||||
// Hard delete — only safe once no Story references the track any more
|
||||
// (Story.musicTrackId is onDelete: SetNull, so this wouldn't corrupt old
|
||||
// stories either way, but updateMusicTrack's active:false is the preferred
|
||||
// way to retire a track without breaking its own audit trail).
|
||||
deleteMusicTrack: protectedProcedure
|
||||
.input(z.object({ id: z.string().min(1) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
|
||||
await ctx.prisma.$transaction([
|
||||
ctx.prisma.musicTrack.delete({ where: { id: input.id } }),
|
||||
ctx.prisma.moderationLog.create({
|
||||
data: {
|
||||
action: "DELETE_MUSIC_TRACK",
|
||||
targetType: "MUSIC_TRACK",
|
||||
targetId: input.id,
|
||||
moderatorId: ctx.userId,
|
||||
moderatorRole: callerRole,
|
||||
ipAddress: ctx.ip,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
// ─── Moderator management (grant/revoke stay super-admin only) ───────────────
|
||||
listModerators: protectedProcedure.query(async ({ ctx }) => {
|
||||
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
|
||||
|
||||
@@ -46,6 +46,27 @@ export const ownerRouter = router({
|
||||
return { ok: true };
|
||||
}),
|
||||
|
||||
// Opt-out for the PET_SUGGESTION cron notification
|
||||
// (src/app/api/cron/pet-suggestions) — on by default.
|
||||
getPetSuggestionsPreference: protectedProcedure.query(async ({ ctx }) => {
|
||||
const owner = await ctx.prisma.owner.findUnique({
|
||||
where: { id: ctx.userId },
|
||||
select: { petSuggestionsEnabled: true },
|
||||
});
|
||||
return { petSuggestionsEnabled: owner?.petSuggestionsEnabled ?? true };
|
||||
}),
|
||||
|
||||
setPetSuggestionsPreference: protectedProcedure
|
||||
.input(z.object({ petSuggestionsEnabled: z.boolean() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await ctx.prisma.owner.upsert({
|
||||
where: { id: ctx.userId },
|
||||
create: { id: ctx.userId, petSuggestionsEnabled: input.petSuggestionsEnabled, registrationIp: ctx.ip },
|
||||
update: { petSuggestionsEnabled: input.petSuggestionsEnabled },
|
||||
});
|
||||
return { ok: true };
|
||||
}),
|
||||
|
||||
// Registers this device's Expo push token for the signed-in owner. Single
|
||||
// device only (overwrites any previous token) — good enough until a device
|
||||
// actually needs the app on two phones at once.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import "server-only";
|
||||
import { z } from "zod";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import type { PrismaClient } from "@prisma/client";
|
||||
import { router, protectedProcedure, rateLimited } from "@/trpc/init";
|
||||
import {
|
||||
createSignedUploadUrl,
|
||||
@@ -25,7 +26,30 @@ import { MAX_STORY_VIDEO_DURATION_SECS } from "@/lib/story-video-limits";
|
||||
* - All queries filter expiresAt > now — expired stories never returned (T-02-44)
|
||||
*/
|
||||
|
||||
/** Shared by create/createVideoUpload — a story can only attach a live, admin-curated track. */
|
||||
async function assertMusicTrackActive(prisma: PrismaClient, musicTrackId: string): Promise<void> {
|
||||
const track = await prisma.musicTrack.findUnique({
|
||||
where: { id: musicTrackId },
|
||||
select: { active: true },
|
||||
});
|
||||
if (!track || !track.active) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Selected music track is not available." });
|
||||
}
|
||||
}
|
||||
|
||||
export const storiesRouter = router({
|
||||
/**
|
||||
* Active tracks from the admin-curated music catalog, for the story
|
||||
* creation music picker. No user-upload path exists (see admin.ts's
|
||||
* music-track procedures) — this is read-only.
|
||||
*/
|
||||
listMusicTracks: protectedProcedure.query(async ({ ctx }) => {
|
||||
return ctx.prisma.musicTrack.findMany({
|
||||
where: { active: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}),
|
||||
|
||||
/**
|
||||
* Generate a presigned PUT URL for direct upload to Supabase Storage.
|
||||
* Key scoped to stories/{ownerId}/{petId}/{uuid}.ext (T-02-41).
|
||||
@@ -58,10 +82,13 @@ export const storiesRouter = router({
|
||||
storageKey: z.string().startsWith("stories/"),
|
||||
blurhash: z.string().max(100).nullable().optional(),
|
||||
aiDisclosure: z.enum(["NONE", "AI_MODIFIED", "AI_GENERATED"]).default("NONE"),
|
||||
musicTrackId: z.string().min(1).optional(),
|
||||
musicOffsetSecs: z.number().min(0).optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
|
||||
if (input.musicTrackId) await assertMusicTrackActive(ctx.prisma, input.musicTrackId);
|
||||
|
||||
// Pitfall 5: use explicit UTC arithmetic — avoids timezone issues
|
||||
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
|
||||
@@ -72,6 +99,8 @@ export const storiesRouter = router({
|
||||
storageKey: input.storageKey,
|
||||
blurhash: input.blurhash ?? null,
|
||||
aiDisclosure: input.aiDisclosure,
|
||||
musicTrackId: input.musicTrackId ?? null,
|
||||
musicOffsetSecs: input.musicOffsetSecs ?? 0,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
@@ -85,9 +114,18 @@ export const storiesRouter = router({
|
||||
* server-side once the asset's real duration is known.
|
||||
*/
|
||||
createVideoUpload: protectedProcedure
|
||||
.input(z.object({ petId: z.string().min(1), aiDisclosure: z.enum(["NONE", "AI_MODIFIED", "AI_GENERATED"]).default("NONE") }))
|
||||
.input(
|
||||
z.object({
|
||||
petId: z.string().min(1),
|
||||
aiDisclosure: z.enum(["NONE", "AI_MODIFIED", "AI_GENERATED"]).default("NONE"),
|
||||
musicTrackId: z.string().min(1).optional(),
|
||||
musicOffsetSecs: z.number().min(0).optional(),
|
||||
musicMuteOriginal: z.boolean().default(false),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
|
||||
if (input.musicTrackId) await assertMusicTrackActive(ctx.prisma, input.musicTrackId);
|
||||
|
||||
if (!process.env.MUX_TOKEN_ID || !process.env.MUX_TOKEN_SECRET) {
|
||||
throw new TRPCError({
|
||||
@@ -114,6 +152,9 @@ export const storiesRouter = router({
|
||||
muxUploadId: upload.id,
|
||||
videoStatus: "PROCESSING",
|
||||
aiDisclosure: input.aiDisclosure,
|
||||
musicTrackId: input.musicTrackId ?? null,
|
||||
musicOffsetSecs: input.musicOffsetSecs ?? 0,
|
||||
musicMuteOriginal: input.musicMuteOriginal,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
@@ -181,6 +222,7 @@ export const storiesRouter = router({
|
||||
.query(async ({ ctx, input }) => {
|
||||
return ctx.prisma.story.findMany({
|
||||
where: { petId: input.petId, expiresAt: { gt: new Date() } },
|
||||
include: { musicTrack: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
take: 50,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user