feat(stories): Server fuer Story-Editor (Overlays, Markierungen, Text-Storys, GIFs)

- Schema: Story.overlays/background/mediaWidth/mediaHeight, StoryMediaType.TEXT,
  StoryMention, Notification.storyId, STORY_MENTION/COMMENT/REACTION
- Markieren nach Pet.followerVisibility (Entscheidung 04.10.), Block-Pruefung,
  eigene Tiere immer erlaubt; unzulaessige Markierungen werden verworfen
- stories.createText, searchMentionable, searchGifs (GIPHY-Proxy, rating g,
  Redis-Cache), featureFlags; Kommentar/Pfote benachrichtigen den Besitzer
- Video-Storys benachrichtigen Markierte erst bei READY (Mux-Webhook)
- Notschalter Story-Editor im Admin-Dashboard (Redis, ModerationLog)
- RLS-Skript fuer StoryMention

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-04 16:27:34 +02:00
1 parent 66230a8695
commit 8c640e2837
16 files changed
+1013 -14

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
-- Story-Editor (feature/story-editor): neue Tabelle für den PostgREST-Zugriff
-- sperren, wie alle anderen Tabellen (siehe enable_rls.sql). Die App greift
-- ausschließlich über Prisma (Service-Rolle) zu.
-- Nach dem prisma db push einmal ausführen.
ALTER TABLE public."StoryMention" ENABLE ROW LEVEL SECURITY;
+36 -1
View File
@@ -323,6 +323,9 @@ model Pet {
verificationRequests VerificationRequest[]
// Story-Editor: Storys, in denen dieses Tier markiert wurde
storyMentions StoryMention[] @relation("StoryMentions")
// Gitea #18 — legal AI-content disclosure. Set once at avatar upload,
// owner-immutable afterward; only a moderator can correct it (see
// admin.setAiDisclosure). Overlay-badge only, never baked into pixels.
@@ -512,6 +515,17 @@ model Story {
musicOffsetSecs Float? @default(0) // start point within the track, since story display duration is fixed
musicMuteOriginal Boolean @default(false) // VIDEO stories only — mute the baked-in Mux audio in favor of the track
// Story-Editor (feature/story-editor): Text, Markierungen, GIFs und Sticker
// als Daten über dem Medium, nicht ins Bild gerechnet — validiert über
// storyOverlaysSchema (src/lib/story-overlays.ts). Positionen relativ zur
// Medienfläche, daher mediaWidth/-Height auch für Bilder.
overlays Json?
background String? @db.VarChar(30) // Farbverlauf-Schlüssel, nur TEXT-Storys
mediaWidth Int?
mediaHeight Int?
mentions StoryMention[]
notifications Notification[]
@@index([petId, expiresAt]) // supports lazy-delete filter query
@@index([muxUploadId])
@@index([muxAssetId])
@@ -540,6 +554,22 @@ model MusicTrack {
enum StoryMediaType {
IMAGE
VIDEO
TEXT // reine Text-Story auf Farbverlauf (Story.background), ohne Foto/Video
}
// Markierte Tiere einer Story — eigene Tabelle (nicht nur im overlays-JSON),
// damit Block-/Sichtbarkeitsregeln, Benachrichtigungen und Löschungen sauber
// greifen. Cascade in beide Richtungen.
model StoryMention {
id String @id @default(cuid())
story Story @relation(fields: [storyId], references: [id], onDelete: Cascade)
storyId String
pet Pet @relation("StoryMentions", fields: [petId], references: [id], onDelete: Cascade)
petId String
createdAt DateTime @default(now())
@@unique([storyId, petId])
@@index([petId])
}
model StoryView {
@@ -842,6 +872,9 @@ enum NotificationType {
REFERRAL_JOINED // ein Tier ist über die eigene Einladung zu PawFeed gekommen
REFERRAL_RANK_UP // eigener Empfehlungsrang aufgestiegen (actorPetId = null)
VACCINE_DUE // Impfung wird in <= 30 Tagen fällig (vaccineId gesetzt, actorPetId = null)
STORY_MENTION // Tier wurde in einer Story markiert (storyId gesetzt)
STORY_COMMENT // Kommentar auf eine eigene Story (storyId gesetzt)
STORY_REACTION // Pfote auf eine eigene Story (storyId gesetzt)
}
// ─── Phase 4 Models ──────────────────────────────────────────────────────────
@@ -859,6 +892,8 @@ model Notification {
commentId String?
vaccine Vaccine? @relation(fields: [vaccineId], references: [id], onDelete: Cascade)
vaccineId String?
story Story? @relation(fields: [storyId], references: [id], onDelete: Cascade)
storyId String?
read Boolean @default(false)
createdAt DateTime @default(now())
@@ -1004,7 +1039,7 @@ model AdRepost {
model ModerationLog {
id String @id @default(cuid())
action String @db.VarChar(50) // DELETE_POST | DELETE_COMMENT | BAN_USER | UNBAN_USER | DELETE_IMAGE | DISMISS_REPORT | CREATE_AD | UPDATE_AD | DELETE_AD | GRANT_ROLE | REVOKE_ROLE | WARN_USER | VERIFY_PET | UNVERIFY_PET | DELETE_ACCOUNT | APPROVE_VERIFICATION_REQUEST | REJECT_VERIFICATION_REQUEST | HIDE_POST | UNHIDE_POST | SHADOWBAN_USER | UNSHADOWBAN_USER | SET_AI_DISCLOSURE | ENABLE_MAINTENANCE_MODE | DISABLE_MAINTENANCE_MODE | PIN_POST | UNPIN_POST | SEND_BROADCAST | DELETE_BROADCAST | CREATE_MUSIC_TRACK | UPDATE_MUSIC_TRACK | DELETE_MUSIC_TRACK | CREATE_REFERRAL_RANK | UPDATE_REFERRAL_RANK | DEACTIVATE_REFERRAL_RANK | UPDATE_REFERRAL_SETTINGS | APPROVE_REFERRAL | REVOKE_REFERRAL | REVOKE_REFERRAL_RANK | UPDATE_CURATOR_SETTINGS | GRANT_REFERRAL_RANK | RESTORE_REFERRAL_RANK | DELETE_PET | SET_FOUNDING_MEMBER | CLEAR_PET_CONTENT
action String @db.VarChar(50) // DELETE_POST | DELETE_COMMENT | BAN_USER | UNBAN_USER | DELETE_IMAGE | DISMISS_REPORT | CREATE_AD | UPDATE_AD | DELETE_AD | GRANT_ROLE | REVOKE_ROLE | WARN_USER | VERIFY_PET | UNVERIFY_PET | DELETE_ACCOUNT | APPROVE_VERIFICATION_REQUEST | REJECT_VERIFICATION_REQUEST | HIDE_POST | UNHIDE_POST | SHADOWBAN_USER | UNSHADOWBAN_USER | SET_AI_DISCLOSURE | ENABLE_MAINTENANCE_MODE | DISABLE_MAINTENANCE_MODE | PIN_POST | UNPIN_POST | SEND_BROADCAST | DELETE_BROADCAST | CREATE_MUSIC_TRACK | UPDATE_MUSIC_TRACK | DELETE_MUSIC_TRACK | CREATE_REFERRAL_RANK | UPDATE_REFERRAL_RANK | DEACTIVATE_REFERRAL_RANK | UPDATE_REFERRAL_SETTINGS | APPROVE_REFERRAL | REVOKE_REFERRAL | REVOKE_REFERRAL_RANK | UPDATE_CURATOR_SETTINGS | GRANT_REFERRAL_RANK | RESTORE_REFERRAL_RANK | DELETE_PET | SET_FOUNDING_MEMBER | CLEAR_PET_CONTENT | ENABLE_STORY_EDITOR | DISABLE_STORY_EDITOR
targetType String @db.VarChar(20) // POST | COMMENT | USER | IMAGE | AD | REPORT | PET | SYSTEM | MUSIC_TRACK
targetId String
reason String? @db.VarChar(500)
+6
View File
@@ -372,6 +372,7 @@ interface MockPrismaClient {
postImage: MockPostImageClient;
milestone: MockMilestoneClient;
story: MockStoryClient;
storyMention: { createMany: MockFn; findMany: MockFn; deleteMany: MockFn };
storyView: MockStoryViewClient;
follow: MockFollowClient;
block: MockBlockClient;
@@ -504,6 +505,11 @@ export function createMockPrisma(): MockPrismaClient {
deleteMany: vi.fn(),
aggregate: vi.fn(),
},
storyMention: {
createMany: vi.fn().mockResolvedValue({ count: 0 }),
findMany: vi.fn().mockResolvedValue([]),
deleteMany: vi.fn(),
},
storyView: {
upsert: vi.fn(),
findMany: vi.fn(),
+4 -3
View File
@@ -234,9 +234,10 @@ describe("stories.listActive", () => {
const result = await caller.listActive({ petId: "pet-a" });
expect(result[0].reactedByViewer).toBe(false);
expect(mockPrisma.story.findMany).toHaveBeenCalledWith(
expect.objectContaining({ include: { musicTrack: true } })
);
const include = mockPrisma.story.findMany.mock.calls[0][0].include;
expect(include.musicTrack).toBe(true);
// Ohne viewerPetId keine Reaktions-Abfrage (ältere Clients)
expect(include.reactions).toBeUndefined();
});
});
+323
View File
@@ -0,0 +1,323 @@
/**
* Story-Editor (feature/story-editor): Overlays, Markierungen, Text-Storys,
* Story-Benachrichtigungen, GIF-Suche, Notschalter.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("server-only", () => ({}));
vi.mock("@/lib/supabase-storage", () => ({
createSignedUploadUrl: vi.fn(),
ALLOWED_CONTENT_TYPES: ["image/jpeg", "image/png", "image/webp"],
MAX_FILE_SIZE: 10 * 1024 * 1024,
deleteFiles: vi.fn(),
}));
vi.mock("@/lib/mux", () => ({
mux: { video: { uploads: { create: vi.fn().mockResolvedValue({ id: "up-1", url: "https://mux/up" }) }, assets: { delete: vi.fn(), retrieve: vi.fn() } } },
}));
vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn().mockResolvedValue({ success: true }) }));
vi.mock("@clerk/nextjs/server", () => ({ auth: vi.fn().mockResolvedValue({ userId: "owner-1" }) }));
vi.mock("@/lib/prisma", () => ({ prisma: {} }));
const { mockNotify, redisStore } = vi.hoisted(() => ({ mockNotify: vi.fn(), redisStore: new Map<string, string>() }));
vi.mock("@/lib/notify", () => ({ notify: (...a: unknown[]) => mockNotify(...a), sendPushForNotification: vi.fn() }));
vi.mock("@/lib/redis", () => ({
redis: {
get: vi.fn(async (k: string) => redisStore.get(k) ?? null),
set: vi.fn(async (k: string, v: string) => {
redisStore.set(k, v);
return "OK";
}),
del: vi.fn(async (k: string) => {
redisStore.delete(k);
return 1;
}),
},
}));
vi.mock("@/lib/spider-exclusion", () => ({ getSpiderExclusionId: vi.fn().mockResolvedValue(null) }));
import { storiesRouter } from "@/trpc/routers/stories";
import { createMockPrisma } from "@/__tests__/helpers/prisma-mock";
import {
containRect,
contrastTextColor,
mentionedPetIds,
parseStoredOverlays,
storyMediaSize,
storyOverlaysSchema,
} from "@/lib/story-overlays";
import { filterMentionablePetIds } from "@/lib/story-mentions";
import { isStoryEditorEnabled, setStoryEditorEnabled } from "@/lib/feature-flags";
function createCaller() {
const mockPrisma = createMockPrisma();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return { caller: storiesRouter.createCaller({ userId: "owner-1", prisma: mockPrisma as any } as any), mockPrisma };
}
const text = (extra: Record<string, unknown> = {}) => ({ kind: "text", x: 0.5, y: 0.5, scale: 1, rotation: 0, text: "Hallo", color: "#ffffff", style: "plain", font: "bold", ...extra });
const mention = (petId: string) => ({ kind: "mention", x: 0.5, y: 0.3, scale: 1, rotation: 0, petId });
const gif = (extra: Record<string, unknown> = {}) => ({ kind: "gif", x: 0.5, y: 0.7, scale: 1, rotation: 10, gifId: "abc", url: "https://media2.giphy.com/media/abc/200w.webp", width: 200, height: 150, ...extra });
const sticker = (stickerId = "paw") => ({ kind: "sticker", x: 0.2, y: 0.2, scale: 1.5, rotation: -20, stickerId });
beforeEach(() => {
vi.clearAllMocks();
redisStore.clear();
});
describe("storyOverlaysSchema", () => {
it("accepts all four overlay kinds", () => {
expect(storyOverlaysSchema.safeParse([text(), mention("p2"), gif(), sticker()]).success).toBe(true);
});
it("rejects GIF URLs outside GIPHY, unknown stickers, empty text and colors off the palette", () => {
expect(storyOverlaysSchema.safeParse([gif({ url: "https://evil.example/x.gif" })]).success).toBe(false);
expect(storyOverlaysSchema.safeParse([sticker("skull")]).success).toBe(false);
expect(storyOverlaysSchema.safeParse([text({ text: " " })]).success).toBe(false);
expect(storyOverlaysSchema.safeParse([text({ color: "#123456" })]).success).toBe(false);
});
it("rejects positions outside the media area and absurd scales", () => {
expect(storyOverlaysSchema.safeParse([text({ x: 1.2 })]).success).toBe(false);
expect(storyOverlaysSchema.safeParse([text({ scale: 50 })]).success).toBe(false);
});
it("limits overlays, GIFs and distinct mentions", () => {
expect(storyOverlaysSchema.safeParse(Array.from({ length: 16 }, () => sticker())).success).toBe(false);
expect(storyOverlaysSchema.safeParse([gif(), gif(), gif(), gif()]).success).toBe(false);
expect(storyOverlaysSchema.safeParse(Array.from({ length: 11 }, (_, i) => mention(`p${i}`))).success).toBe(false);
});
it("parses stored JSON defensively", () => {
expect(parseStoredOverlays(null)).toEqual([]);
expect(parseStoredOverlays("kaputt")).toEqual([]);
expect(parseStoredOverlays([text()])).toHaveLength(1);
expect(mentionedPetIds([mention("a"), mention("a"), mention("b")] as never)).toEqual(["a", "b"]);
});
});
describe("overlay geometry", () => {
it("fits portrait media into a taller screen with letterboxing", () => {
expect(containRect(400, 800, 1080, 1350)).toEqual({ x: 0, y: 150, width: 400, height: 500 });
});
it("derives the media size per story type", () => {
expect(storyMediaSize({ mediaType: "TEXT" })).toEqual({ width: 9, height: 16 });
expect(storyMediaSize({ mediaType: "IMAGE", mediaWidth: 1080, mediaHeight: 1920 })).toEqual({ width: 1080, height: 1920 });
expect(storyMediaSize({ mediaType: "VIDEO", aspectRatio: "9:16" })).toEqual({ width: 9, height: 16 });
expect(storyMediaSize({ mediaType: "IMAGE" })).toBeNull();
});
it("picks a readable text color on a colored box", () => {
expect(contrastTextColor("#facc15")).toBe("#171717");
expect(contrastTextColor("#3b82f6")).toBe("#ffffff");
});
});
describe("filterMentionablePetIds — „Wer darf die Follower sehen?“ regelt das Markieren", () => {
function prismaWith(targets: { id: string; ownerId: string; followerVisibility: string }[], opts: { blocks?: string[][]; follows?: string[] } = {}) {
const p = createMockPrisma();
p.pet.findUnique.mockResolvedValue({ ownerId: "owner-1" });
p.pet.findMany.mockResolvedValue(targets);
p.block.findMany.mockResolvedValue((opts.blocks ?? []).map(([blockerPetId, blockedPetId]) => ({ blockerPetId, blockedPetId })));
p.follow.findMany.mockResolvedValue((opts.follows ?? []).map((followeePetId) => ({ followeePetId })));
return p;
}
it("applies EVERYONE / FOLLOWERS_ONLY / NOBODY", async () => {
const p = prismaWith(
[
{ id: "everyone", ownerId: "o2", followerVisibility: "EVERYONE" },
{ id: "fans-followed", ownerId: "o3", followerVisibility: "FOLLOWERS_ONLY" },
{ id: "fans-not-followed", ownerId: "o4", followerVisibility: "FOLLOWERS_ONLY" },
{ id: "nobody", ownerId: "o5", followerVisibility: "NOBODY" },
],
{ follows: ["fans-followed"] }
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const allowed = await filterMentionablePetIds(p as any, "me", ["everyone", "fans-followed", "fans-not-followed", "nobody"]);
expect(allowed.sort()).toEqual(["everyone", "fans-followed"]);
});
it("always allows the owner's own pets, never self, never blocked pets", async () => {
const p = prismaWith(
[
{ id: "own-pet", ownerId: "owner-1", followerVisibility: "NOBODY" },
{ id: "blocked", ownerId: "o2", followerVisibility: "EVERYONE" },
],
{ blocks: [["blocked", "me"]] }
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const allowed = await filterMentionablePetIds(p as any, "me", ["me", "own-pet", "blocked"]);
expect(allowed).toEqual(["own-pet"]);
});
});
describe("stories.create with overlays", () => {
it("stores overlays + media size, drops disallowed mentions and notifies only allowed pets", async () => {
const { caller, mockPrisma } = createCaller();
mockPrisma.pet.findUnique.mockResolvedValue({ id: "me", ownerId: "owner-1" });
mockPrisma.pet.findMany.mockResolvedValue([
{ id: "ok", ownerId: "o2", followerVisibility: "EVERYONE" },
{ id: "private", ownerId: "o3", followerVisibility: "NOBODY" },
]);
mockPrisma.block.findMany.mockResolvedValue([]);
mockPrisma.follow.findMany.mockResolvedValue([]);
mockPrisma.story.create.mockResolvedValue({ id: "story-1" });
await caller.create({
petId: "me",
storageKey: "stories/x.jpg",
overlays: [text(), mention("ok"), mention("private")] as never,
mediaWidth: 1080,
mediaHeight: 1350,
});
const data = mockPrisma.story.create.mock.calls[0][0].data;
expect(data.mediaWidth).toBe(1080);
expect(data.overlays.map((o: { kind: string; petId?: string }) => o.petId ?? o.kind)).toEqual(["text", "ok"]);
expect(mockPrisma.storyMention.createMany).toHaveBeenCalledWith({ data: [{ storyId: "story-1", petId: "ok" }], skipDuplicates: true });
expect(mockNotify).toHaveBeenCalledTimes(1);
expect(mockNotify.mock.calls[0][1]).toMatchObject({ recipientPetId: "ok", type: "STORY_MENTION", actorPetId: "me", storyId: "story-1" });
});
it("video stories save mentions but notify only once the video is ready", async () => {
process.env.MUX_TOKEN_ID = "id";
process.env.MUX_TOKEN_SECRET = "secret";
const { caller, mockPrisma } = createCaller();
mockPrisma.pet.findUnique.mockResolvedValue({ id: "me", ownerId: "owner-1" });
mockPrisma.pet.findMany.mockResolvedValue([{ id: "ok", ownerId: "o2", followerVisibility: "EVERYONE" }]);
mockPrisma.block.findMany.mockResolvedValue([]);
mockPrisma.follow.findMany.mockResolvedValue([]);
mockPrisma.story.create.mockResolvedValue({ id: "story-v" });
await caller.createVideoUpload({ petId: "me", overlays: [mention("ok")] as never, mediaWidth: 720, mediaHeight: 1280 });
expect(mockPrisma.storyMention.createMany).toHaveBeenCalledOnce();
expect(mockNotify).not.toHaveBeenCalled();
});
});
describe("stories.createText", () => {
it("creates a TEXT story with background", async () => {
const { caller, mockPrisma } = createCaller();
mockPrisma.pet.findUnique.mockResolvedValue({ id: "me", ownerId: "owner-1" });
mockPrisma.story.create.mockResolvedValue({ id: "story-t" });
await caller.createText({ petId: "me", background: "sunset", overlays: [text()] as never });
const data = mockPrisma.story.create.mock.calls[0][0].data;
expect(data).toMatchObject({ mediaType: "TEXT", background: "sunset" });
expect(data.storageKey).toBeUndefined();
});
it("requires text and a known background", async () => {
const { caller, mockPrisma } = createCaller();
mockPrisma.pet.findUnique.mockResolvedValue({ id: "me", ownerId: "owner-1" });
await expect(caller.createText({ petId: "me", background: "sunset", overlays: [sticker()] as never })).rejects.toThrow();
await expect(caller.createText({ petId: "me", background: "rainbow", overlays: [text()] as never })).rejects.toThrow();
});
});
describe("story notifications for the owner", () => {
it("a paw on someone else's story notifies its owner, not on the own story", async () => {
const { caller, mockPrisma } = createCaller();
mockPrisma.pet.findUnique.mockResolvedValue({ id: "me", ownerId: "owner-1" });
mockPrisma.storyReaction.findUnique.mockResolvedValue(null);
mockPrisma.story.findUnique.mockResolvedValue({ petId: "other", expiresAt: new Date(Date.now() + 60_000) });
mockPrisma.$transaction.mockResolvedValue([]);
await caller.toggleReaction({ storyId: "s1", petId: "me" });
expect(mockNotify.mock.calls[0][1]).toMatchObject({ recipientPetId: "other", type: "STORY_REACTION", storyId: "s1" });
mockNotify.mockClear();
mockPrisma.story.findUnique.mockResolvedValue({ petId: "me", expiresAt: new Date(Date.now() + 60_000) });
await caller.toggleReaction({ storyId: "s2", petId: "me" });
expect(mockNotify).not.toHaveBeenCalled();
});
it("a comment notifies the story owner", async () => {
const { caller, mockPrisma } = createCaller();
mockPrisma.pet.findUnique.mockResolvedValue({ id: "me", ownerId: "owner-1" });
mockPrisma.story.findUnique.mockResolvedValue({ petId: "other", expiresAt: new Date(Date.now() + 60_000) });
mockPrisma.$transaction.mockResolvedValue([{ id: "c1" }]);
await caller.addComment({ storyId: "s1", petId: "me", body: "Süß!" });
expect(mockNotify.mock.calls[0][1]).toMatchObject({ recipientPetId: "other", type: "STORY_COMMENT", actorPetId: "me" });
});
});
describe("stories.listActive with overlays", () => {
it("returns parsed overlays and hides mentions of pets that no longer exist", async () => {
const { caller, mockPrisma } = createCaller();
mockPrisma.pet.findUnique.mockResolvedValue({ ownerId: "someone-else" });
mockPrisma.story.findMany.mockResolvedValue([
{
id: "s1",
expiresAt: new Date(Date.now() + 60_000),
overlays: [text(), mention("alive"), mention("deleted")],
mentions: [{ pet: { id: "alive", name: "Bubi" } }],
},
]);
const [story] = await caller.listActive({ petId: "p" });
expect(story.overlays.map((o: { kind: string; petId?: string }) => o.petId ?? o.kind)).toEqual(["text", "alive"]);
expect(story.mentionedPets).toEqual([{ id: "alive", name: "Bubi" }]);
});
});
describe("stories.searchMentionable", () => {
it("returns only pets the actor may mention", async () => {
const { caller, mockPrisma } = createCaller();
mockPrisma.pet.findUnique.mockResolvedValue({ id: "me", ownerId: "owner-1" });
mockPrisma.pet.findMany
.mockResolvedValueOnce([{ id: "a", name: "Anton" }, { id: "b", name: "Bella" }]) // Kandidaten
.mockResolvedValueOnce([
{ id: "a", ownerId: "o2", followerVisibility: "EVERYONE" },
{ id: "b", ownerId: "o3", followerVisibility: "NOBODY" },
]); // Regeln
mockPrisma.block.findMany.mockResolvedValue([]);
mockPrisma.follow.findMany.mockResolvedValue([]);
const result = await caller.searchMentionable({ petId: "me", query: "a" });
expect(result.map((p: { id: string }) => p.id)).toEqual(["a"]);
});
});
describe("stories.searchGifs", () => {
it("maps GIPHY results, filters rating g and caches them", async () => {
process.env.GIPHY_API_KEY = "test-key";
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
data: [
{ id: "g1", title: "Hund", images: { fixed_width: { webp: "https://media1.giphy.com/g1.webp", width: "200", height: "112" }, fixed_width_small: { webp: "https://media1.giphy.com/g1s.webp" } } },
{ id: "broken", images: {} },
],
pagination: { total_count: 50, count: 2, offset: 0 },
}),
});
vi.stubGlobal("fetch", fetchMock);
const { caller } = createCaller();
const first = await caller.searchGifs({ query: "Hund" });
expect(first.gifs).toEqual([{ id: "g1", title: "Hund", previewUrl: "https://media1.giphy.com/g1s.webp", url: "https://media1.giphy.com/g1.webp", width: 200, height: 112 }]);
expect(first.nextOffset).toBe(2);
expect(String(fetchMock.mock.calls[0][0])).toContain("rating=g");
await caller.searchGifs({ query: "hund" }); // gleiche Suche, anders geschrieben → Cache
expect(fetchMock).toHaveBeenCalledTimes(1);
vi.unstubAllGlobals();
});
});
describe("Notschalter", () => {
it("is on by default and can be switched off and on", async () => {
expect(await isStoryEditorEnabled()).toBe(true);
await setStoryEditorEnabled(false);
expect(await isStoryEditorEnabled()).toBe(false);
const { caller } = createCaller();
expect(await caller.featureFlags()).toEqual({ storyEditor: false });
await setStoryEditorEnabled(true);
expect(await isStoryEditorEnabled()).toBe(true);
});
});
+8
View File
@@ -5,6 +5,7 @@ import { redis } from "@/lib/redis";
import { fanOutPost } from "@/lib/feed-helpers";
import { MAX_STORY_VIDEO_DURATION_SECS } from "@/lib/story-video-limits";
import { maybeQualifyReferral } from "@/lib/referrals";
import { notifyStoryMentions } from "@/lib/story-mentions";
/**
* POST /api/webhooks/mux
@@ -124,6 +125,13 @@ export async function POST(req: NextRequest) {
aspectRatio: aspectRatio ?? null,
},
});
// Story-Editor: Markierungen wurden beim Upload gespeichert, aber erst
// jetzt ist die Story sichtbar → jetzt benachrichtigen.
if (!overStoryLimit) {
const mentions = await prisma.storyMention.findMany({ where: { storyId: story.id }, select: { petId: true } });
notifyStoryMentions(prisma, story.id, story.petId, mentions.map((m) => m.petId));
}
break;
}
+38 -1
View File
@@ -5,7 +5,7 @@ import Link from "next/link";
import { usePathname } from "next/navigation";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTRPC } from "@/trpc/client";
import { Flag, Clock, TriangleAlert, TrendingUp, ShieldAlert, Info, ChevronRight } from "lucide-react";
import { Flag, Clock, TriangleAlert, TrendingUp, ShieldAlert, Info, ChevronRight, Sparkles } from "lucide-react";
import { TimeSeriesChart } from "@/components/admin/TimeSeriesChart";
import { SpeciesDistributionCard } from "@/components/admin/SpeciesDistributionCard";
import { GranularityToggle, type Granularity } from "@/components/admin/GranularityToggle";
@@ -29,6 +29,13 @@ export default function AdminDashboard() {
})
);
const { data: storyEditor } = useQuery(trpc.admin.getStoryEditorEnabled.queryOptions());
const setStoryEditor = useMutation(
trpc.admin.setStoryEditorEnabled.mutationOptions({
onSuccess: () => void qc.invalidateQueries({ queryKey: trpc.admin.getStoryEditorEnabled.queryKey() }),
})
);
const [postsGranularity, setPostsGranularity] = useState<Granularity>("day");
const [ownerGranularity, setOwnerGranularity] = useState<Granularity>("day");
const [visitsGranularity, setVisitsGranularity] = useState<Granularity>("day");
@@ -90,6 +97,36 @@ export default function AdminDashboard() {
</div>
)}
{storyEditor && (
<div
className={`flex items-center justify-between gap-4 rounded-xl ring-1 px-5 py-4 ${
storyEditor.enabled ? "ring-foreground/10 bg-card" : "ring-destructive/40 bg-destructive/10"
}`}
>
<div className="flex items-center gap-3">
<Sparkles
className={`h-5 w-5 shrink-0 ${storyEditor.enabled ? "text-muted-foreground" : "text-destructive"}`}
/>
<div>
<p className="text-sm font-semibold text-foreground">Story-Editor (Notschalter)</p>
<p className="text-xs text-muted-foreground mt-0.5">
{storyEditor.enabled
? "An — Text, Markierungen, GIFs und Sticker in Storys sind aktiv."
: "Aus — App und Web blenden Editor und Overlays aus (ohne App-Update)."}
</p>
</div>
</div>
<Button
size="sm"
variant={storyEditor.enabled ? "outline" : "destructive"}
disabled={setStoryEditor.isPending}
onClick={() => setStoryEditor.mutate({ enabled: !storyEditor.enabled })}
>
{storyEditor.enabled ? "Abschalten" : "Wieder einschalten"}
</Button>
</div>
)}
{isLoading ? (
<div className="text-muted-foreground text-sm">Loading…</div>
) : (
+23
View File
@@ -0,0 +1,23 @@
import "server-only";
import { redis } from "@/lib/redis";
/**
* Notschalter für den Story-Editor (ohne Vorab-Tester live gegangen): Ist er
* aus, blenden App und Web Editor-Werkzeuge und Overlays aus — ohne neues
* OTA-Update. Standard: an (Schlüssel fehlt = an), wie der Wartungsmodus in
* Redis abgelegt.
*/
const STORY_EDITOR_DISABLED_KEY = "feature:story-editor:disabled";
export async function isStoryEditorEnabled(): Promise<boolean> {
try {
return (await redis.get(STORY_EDITOR_DISABLED_KEY)) !== "1";
} catch {
return true; // Redis nicht erreichbar → Funktion nicht wegen Infrastruktur abschalten
}
}
export async function setStoryEditorEnabled(enabled: boolean): Promise<void> {
if (enabled) await redis.del(STORY_EDITOR_DISABLED_KEY);
else await redis.set(STORY_EDITOR_DISABLED_KEY, "1");
}
+65
View File
@@ -0,0 +1,65 @@
import "server-only";
import { redis } from "@/lib/redis";
/**
* GIPHY-Suche für den Story-Editor — über unseren Server, damit der API-Schlüssel
* (GIPHY_API_KEY in docker/.env) nie in der App landet. Nur `rating=g`.
* Ergebnisse 1 h in Redis: Der Beta-Schlüssel erlaubt nur 100 Abrufe/Stunde.
* GIPHY-Bedingung: „Powered by GIPHY“ in der Auswahl anzeigen (App).
*/
const API = "https://api.giphy.com/v1/gifs";
export const GIF_PAGE_SIZE = 24;
const CACHE_TTL_SECS = 60 * 60;
export type GifResult = {
id: string;
title: string;
/** kleine animierte Vorschau für das Auswahl-Raster */
previewUrl: string;
/** Darstellung in der Story */
url: string;
width: number;
height: number;
};
type GiphyImage = { url?: string; webp?: string; width?: string; height?: string };
type GiphyGif = { id: string; title?: string; images?: Record<string, GiphyImage | undefined> };
function toResult(gif: GiphyGif): GifResult | null {
const story = gif.images?.fixed_width;
const preview = gif.images?.fixed_width_small ?? story;
const url = story?.webp ?? story?.url;
const previewUrl = preview?.webp ?? preview?.url;
const width = Number(story?.width);
const height = Number(story?.height);
if (!url || !previewUrl || !width || !height) return null;
return { id: gif.id, title: gif.title ?? "", previewUrl, url, width, height };
}
export async function searchGifs(query: string, offset: number): Promise<{ gifs: GifResult[]; nextOffset: number | null }> {
const apiKey = process.env.GIPHY_API_KEY;
if (!apiKey) throw new Error("GIPHY_API_KEY fehlt");
const q = query.trim().toLowerCase();
const cacheKey = `giphy:${q ? `search:${q}` : "trending"}:${offset}`;
try {
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
} catch {
// Redis down → direkt bei GIPHY fragen
}
const params = new URLSearchParams({ api_key: apiKey, limit: String(GIF_PAGE_SIZE), offset: String(offset), rating: "g" });
if (q) params.set("q", q);
const res = await fetch(`${API}/${q ? "search" : "trending"}?${params}`, { signal: AbortSignal.timeout(8000) });
if (!res.ok) throw new Error(`GIPHY antwortet mit ${res.status}`);
const body = (await res.json()) as { data?: GiphyGif[]; pagination?: { total_count?: number; count?: number; offset?: number } };
const gifs = (body.data ?? []).map(toResult).filter((g): g is GifResult => g !== null);
const total = body.pagination?.total_count ?? 0;
const next = offset + (body.pagination?.count ?? gifs.length);
const result = { gifs, nextOffset: gifs.length > 0 && next < total ? next : null };
redis.set(cacheKey, JSON.stringify(result), "EX", CACHE_TTL_SECS).catch(() => {});
return result;
}
+4
View File
@@ -9,6 +9,7 @@ interface NotifyParams {
postId?: string;
commentId?: string;
vaccineId?: string;
storyId?: string;
}
/**
@@ -43,6 +44,9 @@ const PUSH_COPY: Record<
REFERRAL_JOINED: { title: "Deine Einladung hat geklappt", genericBody: "Ein neues Tier ist über deine Einladung zu PawFeed gekommen.", actorBody: (a) => `${a} ist über deine Einladung zu PawFeed gekommen.` },
REFERRAL_RANK_UP: { title: "Neuer Rang", genericBody: "Du hast einen neuen Empfehlungsrang erreicht.", actorBody: () => "Du hast einen neuen Empfehlungsrang erreicht." },
VACCINE_DUE: { title: "Impfung bald fällig", genericBody: "Eine Impfung wird bald fällig.", actorBody: () => "Eine Impfung wird bald fällig." },
STORY_MENTION: { title: "In einer Story markiert", genericBody: "Du wurdest in einer Story markiert.", actorBody: (a) => `${a} hat dich in einer Story markiert.` },
STORY_COMMENT: { title: "Neuer Story-Kommentar", genericBody: "Jemand hat deine Story kommentiert.", actorBody: (a) => `${a} hat deine Story kommentiert.` },
STORY_REACTION: { title: "Neue Pfote", genericBody: "Jemand hat deiner Story eine Pfote gegeben.", actorBody: (a) => `${a} hat deiner Story eine Pfote gegeben.` },
};
/**
+88
View File
@@ -0,0 +1,88 @@
import "server-only";
import type { PrismaClient } from "@prisma/client";
import { notify } from "@/lib/notify";
/**
* Wer darf wen in einer Story markieren? Entscheidung (04.10.): Es gilt die
* bestehende Einstellung „Wer darf die Follower von {Name} sehen?“
* (Pet.followerVisibility) — keine eigene Markier-Einstellung:
* - EVERYONE → jedes Tier darf markieren
* - FOLLOWERS_ONLY → nur Tiere, die dem markierten Tier folgen
* - NOBODY → niemand
* Immer erlaubt: Tiere desselben Besitzers. Nie erlaubt: sich selbst, bei
* einer Blockierung in irgendeine Richtung.
*/
type MentionPrisma = Pick<PrismaClient, "pet" | "block" | "follow">;
export async function filterMentionablePetIds(
prisma: MentionPrisma,
actorPetId: string,
candidatePetIds: readonly string[]
): Promise<string[]> {
const ids = [...new Set(candidatePetIds)].filter((id) => id !== actorPetId);
if (ids.length === 0) return [];
const [actor, targets, blocks, follows] = await Promise.all([
prisma.pet.findUnique({ where: { id: actorPetId }, select: { ownerId: true } }),
prisma.pet.findMany({ where: { id: { in: ids } }, select: { id: true, ownerId: true, followerVisibility: true } }),
prisma.block.findMany({
where: {
OR: [
{ blockerPetId: actorPetId, blockedPetId: { in: ids } },
{ blockedPetId: actorPetId, blockerPetId: { in: ids } },
],
},
select: { blockerPetId: true, blockedPetId: true },
}),
prisma.follow.findMany({
where: { followerPetId: actorPetId, followeePetId: { in: ids } },
select: { followeePetId: true },
}),
]);
if (!actor) return [];
const blocked = new Set(blocks.flatMap((b) => [b.blockerPetId, b.blockedPetId]));
const followed = new Set(follows.map((f) => f.followeePetId));
return targets
.filter((target) => {
if (target.ownerId === actor.ownerId) return true;
if (blocked.has(target.id)) return false;
if (target.followerVisibility === "EVERYONE") return true;
if (target.followerVisibility === "FOLLOWERS_ONLY") return followed.has(target.id);
return false;
})
.map((t) => t.id);
}
/**
* Markierungen einer Story speichern und die markierten Tiere benachrichtigen.
* Erwartet bereits gefilterte IDs (filterMentionablePetIds). Benachrichtigt
* nicht die eigenen Tiere des Erstellers.
*/
export async function saveStoryMentions(
prisma: Pick<PrismaClient, "storyMention" | "notification" | "pet" | "owner">,
storyId: string,
actorPetId: string,
petIds: readonly string[],
{ sendNotifications }: { sendNotifications: boolean }
): Promise<void> {
if (petIds.length === 0) return;
await prisma.storyMention.createMany({
data: petIds.map((petId) => ({ storyId, petId })),
skipDuplicates: true,
});
if (sendNotifications) notifyStoryMentions(prisma, storyId, actorPetId, petIds);
}
/** Fire-and-forget wie notify() selbst — darf das Erstellen der Story nie scheitern lassen. */
export function notifyStoryMentions(
prisma: Pick<PrismaClient, "notification" | "pet" | "owner">,
storyId: string,
actorPetId: string,
petIds: readonly string[]
): void {
for (const petId of petIds) {
notify(prisma, { recipientPetId: petId, type: "STORY_MENTION", actorPetId, storyId });
}
}
+138
View File
@@ -0,0 +1,138 @@
import { z } from "zod";
import { STICKER_IDS } from "@/lib/story-stickers";
/**
* Story-Editor: Text, Tier-Markierungen, GIFs und Sticker liegen als Daten
* über dem Story-Medium (Story.overlays), nicht ins Bild gerechnet — wie das
* Musik-Overlay. Positionen sind relativ zur **Medienfläche** (0–1), Größen
* relativ zu deren Breite; so sitzt alles auf jedem Bildschirm (App, Web,
* Hoch-/Querformat, Letterboxing) an derselben Stelle.
*
* ⚠️ Spiegel: mobile/src/lib/story-overlays.ts — Konstanten und Geometrie
* müssen identisch bleiben (src/__tests__/story-overlays-parity.test.ts).
*/
export const MAX_OVERLAYS = 15;
export const MAX_GIFS = 3;
export const MAX_MENTIONS = 10;
export const MAX_TEXT_LENGTH = 200;
/** 8 Textfarben (Freigabe: „~8 Farben reichen“). */
export const TEXT_COLORS = ["#ffffff", "#171717", "#f97316", "#facc15", "#22c55e", "#3b82f6", "#ec4899", "#a855f7"] as const;
/** schlicht (Schatten) · Box (Farbfläche, Text kontrastierend) · weich (halbtransparente dunkle Box). */
export const TEXT_STYLES = ["plain", "box", "soft"] as const;
export const TEXT_FONTS = ["regular", "bold"] as const;
/** Farbverläufe für reine Text-Storys (von oben nach unten). */
export const STORY_BACKGROUNDS: Record<string, readonly [string, string]> = {
sunset: ["#f97316", "#ec4899"],
ocean: ["#0ea5e9", "#6366f1"],
forest: ["#22c55e", "#0f766e"],
night: ["#1e1b4b", "#7c3aed"],
peach: ["#fdba74", "#fde68a"],
ink: ["#262626", "#525252"],
};
export const STORY_BACKGROUND_KEYS = Object.keys(STORY_BACKGROUNDS);
/** Seitenverhältnis einer Text-Story (Hochformat wie ein Handy-Foto). */
export const TEXT_STORY_ASPECT = { width: 9, height: 16 } as const;
/** Basisgrößen als Anteil der Medienbreite, vor `scale`. */
export const OVERLAY_SIZES = {
textFont: 0.07,
textMaxWidth: 0.82,
mentionFont: 0.055,
sticker: 0.26,
gifWidth: 0.42,
} as const;
export const MIN_SCALE = 0.3;
export const MAX_SCALE = 4;
const GIPHY_URL = /^https:\/\/(media\d*|i)\.giphy\.com\//;
const base = {
x: z.number().min(0).max(1),
y: z.number().min(0).max(1),
scale: z.number().min(MIN_SCALE).max(MAX_SCALE),
rotation: z.number().min(-360).max(360),
};
export const storyOverlaySchema = z.discriminatedUnion("kind", [
z.object({
kind: z.literal("text"),
...base,
text: z.string().trim().min(1).max(MAX_TEXT_LENGTH),
color: z.enum(TEXT_COLORS),
style: z.enum(TEXT_STYLES),
font: z.enum(TEXT_FONTS),
}),
z.object({ kind: z.literal("mention"), ...base, petId: z.string().min(1).max(50) }),
z.object({
kind: z.literal("gif"),
...base,
gifId: z.string().min(1).max(60),
url: z.string().url().max(300).regex(GIPHY_URL, "Nur GIPHY-Adressen erlaubt"),
width: z.number().int().positive().max(4000),
height: z.number().int().positive().max(4000),
}),
z.object({ kind: z.literal("sticker"), ...base, stickerId: z.string().refine((id) => STICKER_IDS.includes(id), "Unbekannter Sticker") }),
]);
export const storyOverlaysSchema = z
.array(storyOverlaySchema)
.max(MAX_OVERLAYS)
.refine((items) => items.filter((o) => o.kind === "gif").length <= MAX_GIFS, `Höchstens ${MAX_GIFS} GIFs`)
.refine((items) => new Set(items.filter((o) => o.kind === "mention").map((o) => o.petId)).size <= MAX_MENTIONS, `Höchstens ${MAX_MENTIONS} Markierungen`);
export type StoryOverlay = z.infer<typeof storyOverlaySchema>;
/** Markierte Tiere einer Story, ohne Doppelte. */
export function mentionedPetIds(overlays: readonly StoryOverlay[] | null | undefined): string[] {
return [...new Set((overlays ?? []).flatMap((o) => (o.kind === "mention" ? [o.petId] : [])))];
}
/** Liest gespeicherte Overlays defensiv (altes/kaputtes JSON → leere Liste statt Absturz). */
export function parseStoredOverlays(value: unknown): StoryOverlay[] {
const parsed = storyOverlaysSchema.safeParse(value);
return parsed.success ? parsed.data : [];
}
export type Rect = { x: number; y: number; width: number; height: number };
/** Fläche, die ein Medium mit `contain` in einem Container einnimmt (zentriert, Seitenverhältnis bleibt). */
export function containRect(containerWidth: number, containerHeight: number, mediaWidth: number, mediaHeight: number): Rect {
if (containerWidth <= 0 || containerHeight <= 0 || mediaWidth <= 0 || mediaHeight <= 0) {
return { x: 0, y: 0, width: Math.max(containerWidth, 0), height: Math.max(containerHeight, 0) };
}
const scale = Math.min(containerWidth / mediaWidth, containerHeight / mediaHeight);
const width = mediaWidth * scale;
const height = mediaHeight * scale;
return { x: (containerWidth - width) / 2, y: (containerHeight - height) / 2, width, height };
}
/** Bildschirm-Mittelpunkt eines Overlays innerhalb der Medienfläche. */
export function overlayCenter(rect: Rect, overlay: { x: number; y: number }): { left: number; top: number } {
return { left: rect.x + overlay.x * rect.width, top: rect.y + overlay.y * rect.height };
}
/** Lesbare Textfarbe auf einer farbigen Box (Stil „box“). */
export function contrastTextColor(background: string): "#171717" | "#ffffff" {
const hex = background.replace("#", "");
const [r, g, b] = [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
return luminance > 0.6 ? "#171717" : "#ffffff";
}
/** Abmessungen, auf die sich Overlays beziehen: Medium, sonst Text-Story-Format. */
export function storyMediaSize(story: {
mediaType: string;
mediaWidth?: number | null;
mediaHeight?: number | null;
aspectRatio?: string | null;
}): { width: number; height: number } | null {
if (story.mediaType === "TEXT") return { ...TEXT_STORY_ASPECT };
if (story.mediaWidth && story.mediaHeight) return { width: story.mediaWidth, height: story.mediaHeight };
const match = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(story.aspectRatio ?? "");
if (match) return { width: Number(match[1]), height: Number(match[2]) };
return null;
}
+88
View File
@@ -0,0 +1,88 @@
/**
* Story-Sticker (Story-Editor). Reine Formdaten im 100×100-Raster, damit Web
* (DOM-SVG) und App (react-native-svg) exakt dasselbe zeichnen. Jeder Sticker
* wird zweimal gezeichnet: erst alle Teile als weißer Umriss (STICKER_OUTLINE),
* dann in Farbe — das gibt den typischen Aufkleber-Look auf jedem Hintergrund.
*
* ⚠️ Spiegel: mobile/src/lib/story-stickers.ts muss identisch bleiben
* (src/__tests__/story-overlays-parity.test.ts prüft das).
*/
export type StickerPart =
| { type: "circle"; cx: number; cy: number; r: number; fill: string }
| { type: "rect"; x: number; y: number; width: number; height: number; rx: number; fill: string }
| { type: "path"; d: string; fill: string };
export type StickerDef = { id: string; label: string; parts: StickerPart[] };
export const STICKER_OUTLINE = { color: "#ffffff", width: 8 } as const;
export const STORY_STICKERS: StickerDef[] = [
{
id: "paw",
label: "Pfote",
parts: [
{ type: "circle", cx: 50, cy: 64, r: 20, fill: "#f97316" },
{ type: "circle", cx: 22, cy: 42, r: 9, fill: "#f97316" },
{ type: "circle", cx: 38, cy: 26, r: 10, fill: "#f97316" },
{ type: "circle", cx: 62, cy: 26, r: 10, fill: "#f97316" },
{ type: "circle", cx: 78, cy: 42, r: 9, fill: "#f97316" },
],
},
{
id: "heart",
label: "Herz",
parts: [{ type: "path", d: "M50 86 C22 66 8 50 13 32 C18 15 40 12 50 29 C60 12 82 15 87 32 C92 50 78 66 50 86 Z", fill: "#ec4899" }],
},
{
id: "bone",
label: "Knochen",
parts: [
{ type: "rect", x: 24, y: 41, width: 52, height: 18, rx: 4, fill: "#fde68a" },
{ type: "circle", cx: 22, cy: 40, r: 11, fill: "#fde68a" },
{ type: "circle", cx: 22, cy: 60, r: 11, fill: "#fde68a" },
{ type: "circle", cx: 78, cy: 40, r: 11, fill: "#fde68a" },
{ type: "circle", cx: 78, cy: 60, r: 11, fill: "#fde68a" },
],
},
{
id: "star",
label: "Stern",
parts: [{ type: "path", d: "M50 8 L61 37 L93 38 L68 58 L77 90 L50 72 L23 90 L32 58 L7 38 L39 37 Z", fill: "#facc15" }],
},
{
id: "sparkle",
label: "Funkeln",
parts: [
{ type: "path", d: "M44 10 C47 34 54 41 78 44 C54 47 47 54 44 78 C41 54 34 47 10 44 C34 41 41 34 44 10 Z", fill: "#a855f7" },
{ type: "path", d: "M78 62 C79 72 82 75 92 76 C82 77 79 80 78 90 C77 80 74 77 64 76 C74 75 77 72 78 62 Z", fill: "#a855f7" },
],
},
{
id: "fish",
label: "Fisch",
parts: [
{ type: "path", d: "M74 50 L92 34 L92 66 Z", fill: "#3b82f6" },
{ type: "path", d: "M12 50 C24 28 58 26 76 50 C58 74 24 72 12 50 Z", fill: "#3b82f6" },
{ type: "circle", cx: 30, cy: 46, r: 5, fill: "#171717" },
],
},
{
id: "crown",
label: "Krone",
parts: [
{ type: "path", d: "M14 76 L18 30 L36 50 L50 22 L64 50 L82 30 L86 76 Z", fill: "#facc15" },
{ type: "circle", cx: 50, cy: 62, r: 6, fill: "#ec4899" },
],
},
{
id: "sun",
label: "Sonne",
parts: [
{ type: "path", d: "M50 4 L57 22 L43 22 Z M50 96 L43 78 L57 78 Z M4 50 L22 43 L22 57 Z M96 50 L78 57 L78 43 Z M17 17 L33 26 L26 33 Z M83 83 L67 74 L74 67 Z M83 17 L74 33 L67 26 Z M17 83 L26 67 L33 74 Z", fill: "#fb923c" },
{ type: "circle", cx: 50, cy: 50, r: 22, fill: "#facc15" },
],
},
];
export const STICKER_IDS = STORY_STICKERS.map((s) => s.id);
+26
View File
@@ -24,6 +24,7 @@ import { describeReportTarget, reportDismissedMessage, reportUpheldMessage } fro
import { matchesWordBlacklist, matchesLinkBlacklist } from "@/lib/blacklist";
import { getDailyVisitCount, getUniqueVisitorCount, lastNDays, daysInRange } from "@/lib/visit-tracking";
import { isMaintenanceModeEnabled, setMaintenanceMode } from "@/lib/maintenance";
import { isStoryEditorEnabled, setStoryEditorEnabled } from "@/lib/feature-flags";
const DATA_EXPORT_TOKEN_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
@@ -1824,6 +1825,31 @@ export const adminRouter = router({
return { success: true };
}),
/** Notschalter Story-Editor — Moderatoren dürfen ihn im Notfall abschalten. */
getStoryEditorEnabled: protectedProcedure.query(async ({ ctx }) => {
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
return { enabled: await isStoryEditorEnabled() };
}),
setStoryEditorEnabled: protectedProcedure
.input(z.object({ enabled: z.boolean() }))
.mutation(async ({ ctx, input }) => {
const callerRole = await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
await setStoryEditorEnabled(input.enabled);
await ctx.prisma.moderationLog.create({
data: {
action: input.enabled ? "ENABLE_STORY_EDITOR" : "DISABLE_STORY_EDITOR",
targetType: "SYSTEM",
targetId: "story-editor",
reason: null,
moderatorId: ctx.userId,
moderatorRole: callerRole,
ipAddress: ctx.ip,
},
});
return { success: true };
}),
pinPost: protectedProcedure
.input(z.object({ postId: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
+1
View File
@@ -31,6 +31,7 @@ export const notificationsRouter = router({
post: { select: { id: true, petId: true, images: { take: 1, orderBy: { position: "asc" } } } },
comment: { select: { id: true, body: true } },
vaccine: { select: { id: true, name: true, nextDueDate: true } },
story: { select: { id: true, petId: true, expiresAt: true, pet: { select: petIdentitySelect } } },
},
});
+160 -9
View File
@@ -23,6 +23,18 @@ import { assertPetOwnership } from "@/lib/assert-pet-ownership";
import { assertNotBlocked } from "@/lib/assert-not-blocked";
import { mux } from "@/lib/mux";
import { MAX_STORY_VIDEO_DURATION_SECS } from "@/lib/story-video-limits";
import { notify } from "@/lib/notify";
import { getSpiderExclusionId } from "@/lib/spider-exclusion";
import { isStoryEditorEnabled } from "@/lib/feature-flags";
import { searchGifs } from "@/lib/giphy";
import { filterMentionablePetIds, saveStoryMentions } from "@/lib/story-mentions";
import {
STORY_BACKGROUND_KEYS,
mentionedPetIds,
parseStoredOverlays,
storyOverlaysSchema,
type StoryOverlay,
} from "@/lib/story-overlays";
/**
* Stories tRPC router — 24-hour photo/video stories with lazy-delete expiry (D-07).
@@ -35,6 +47,44 @@ import { MAX_STORY_VIDEO_DURATION_SECS } from "@/lib/story-video-limits";
* - All queries filter expiresAt > now — expired stories never returned (T-02-44)
*/
/** Story-Editor-Felder, gemeinsam für create / createVideoUpload. */
const editorFields = {
overlays: storyOverlaysSchema.optional(),
mediaWidth: z.number().int().positive().max(20000).optional(),
mediaHeight: z.number().int().positive().max(20000).optional(),
};
/**
* Markierte Tiere prüfen (Block, „Wer darf die Follower sehen?“) und nur die
* erlaubten behalten — auch im gespeicherten overlays-JSON, damit eine
* unzulässige Markierung nirgends angezeigt wird.
*/
async function resolveMentions(
prisma: PrismaClient,
actorPetId: string,
overlays: StoryOverlay[] | undefined
): Promise<{ overlays: StoryOverlay[] | undefined; mentionIds: string[] }> {
if (!overlays?.length) return { overlays, mentionIds: [] };
const allowed = await filterMentionablePetIds(prisma, actorPetId, mentionedPetIds(overlays));
const allowedSet = new Set(allowed);
return {
overlays: overlays.filter((o) => o.kind !== "mention" || allowedSet.has(o.petId)),
mentionIds: allowed,
};
}
/** Benachrichtigung an den Story-Besitzer (Kommentar/Pfote) — nicht an sich selbst. */
function notifyStoryOwner(
prisma: PrismaClient,
type: "STORY_COMMENT" | "STORY_REACTION",
storyPetId: string,
actorPetId: string,
storyId: string
) {
if (storyPetId === actorPetId) return;
notify(prisma, { recipientPetId: storyPetId, type, actorPetId, storyId });
}
/** 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({
@@ -93,16 +143,18 @@ export const storiesRouter = router({
aiDisclosure: z.enum(["NONE", "AI_MODIFIED", "AI_GENERATED"]).default("NONE"),
musicTrackId: z.string().min(1).optional(),
musicOffsetSecs: z.number().min(0).optional(),
...editorFields,
})
)
.mutation(async ({ ctx, input }) => {
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
if (input.musicTrackId) await assertMusicTrackActive(ctx.prisma, input.musicTrackId);
const { overlays, mentionIds } = await resolveMentions(ctx.prisma, input.petId, input.overlays);
// Pitfall 5: use explicit UTC arithmetic — avoids timezone issues
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
return ctx.prisma.story.create({
const story = await ctx.prisma.story.create({
data: {
petId: input.petId,
storageKey: input.storageKey,
@@ -110,9 +162,45 @@ export const storiesRouter = router({
aiDisclosure: input.aiDisclosure,
musicTrackId: input.musicTrackId ?? null,
musicOffsetSecs: input.musicOffsetSecs ?? 0,
overlays: overlays?.length ? overlays : undefined,
mediaWidth: input.mediaWidth ?? null,
mediaHeight: input.mediaHeight ?? null,
expiresAt,
},
});
await saveStoryMentions(ctx.prisma, story.id, input.petId, mentionIds, { sendNotifications: true });
return story;
}),
/**
* Story-Editor: reine Text-Story auf Farbverlauf — kein Foto/Video, nur
* Overlays (mindestens ein Text). Läuft im Viewer wie eine Foto-Story (5 s).
*/
createText: protectedProcedure
.use(rateLimited("stories.createText", 20, 300))
.input(
z.object({
petId: z.string().min(1),
background: z.string().refine((key) => STORY_BACKGROUND_KEYS.includes(key), "Unbekannter Hintergrund"),
overlays: storyOverlaysSchema.refine((items) => items.some((o) => o.kind === "text"), "Eine Text-Story braucht Text"),
})
)
.mutation(async ({ ctx, input }) => {
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
const { overlays, mentionIds } = await resolveMentions(ctx.prisma, input.petId, input.overlays);
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
const story = await ctx.prisma.story.create({
data: {
petId: input.petId,
mediaType: "TEXT",
background: input.background,
overlays,
expiresAt,
},
});
await saveStoryMentions(ctx.prisma, story.id, input.petId, mentionIds, { sendNotifications: true });
return story;
}),
/**
@@ -130,11 +218,13 @@ export const storiesRouter = router({
musicTrackId: z.string().min(1).optional(),
musicOffsetSecs: z.number().min(0).optional(),
musicMuteOriginal: z.boolean().default(false),
...editorFields,
})
)
.mutation(async ({ ctx, input }) => {
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
if (input.musicTrackId) await assertMusicTrackActive(ctx.prisma, input.musicTrackId);
const { overlays, mentionIds } = await resolveMentions(ctx.prisma, input.petId, input.overlays);
if (!process.env.MUX_TOKEN_ID || !process.env.MUX_TOKEN_SECRET) {
throw new TRPCError({
@@ -164,9 +254,15 @@ export const storiesRouter = router({
musicTrackId: input.musicTrackId ?? null,
musicOffsetSecs: input.musicOffsetSecs ?? 0,
musicMuteOriginal: input.musicMuteOriginal,
overlays: overlays?.length ? overlays : undefined,
mediaWidth: input.mediaWidth ?? null,
mediaHeight: input.mediaHeight ?? null,
expiresAt,
},
});
// Benachrichtigt wird erst, wenn das Video fertig ist (Mux-Webhook) —
// vorher ist die Story für niemanden sichtbar.
await saveStoryMentions(ctx.prisma, story.id, input.petId, mentionIds, { sendNotifications: false });
return { uploadUrl: upload.url, storyId: story.id };
}),
@@ -244,6 +340,7 @@ export const storiesRouter = router({
: { petId: input.petId, expiresAt: { gt: now } },
include: {
musicTrack: true,
mentions: { select: { pet: { select: petIdentitySelect } } },
...(input.viewerPetId
? { reactions: { where: { petId: input.viewerPetId }, select: { petId: true }, take: 1 } }
: {}),
@@ -251,11 +348,19 @@ export const storiesRouter = router({
orderBy: { createdAt: "asc" },
take: 50,
});
return stories.map(({ reactions, ...story }: (typeof stories)[number] & { reactions?: { petId: string }[] }) => ({
...story,
reactedByViewer: (reactions?.length ?? 0) > 0,
isExpired: story.expiresAt <= now,
}));
return stories.map(({ reactions, mentions, overlays, ...story }: (typeof stories)[number] & { reactions?: { petId: string }[] }) => {
// Nur Markierungen anzeigen, die es (noch) gibt — gelöschte Tiere
// verschwinden über die Cascade aus StoryMention, nicht aus dem JSON.
const mentionedPets = (mentions ?? []).map((m) => m.pet);
const known = new Set(mentionedPets.map((p) => p.id));
return {
...story,
overlays: parseStoredOverlays(overlays).filter((o) => o.kind !== "mention" || known.has(o.petId)),
mentionedPets,
reactedByViewer: (reactions?.length ?? 0) > 0,
isExpired: story.expiresAt <= now,
};
});
}),
/**
@@ -412,6 +517,7 @@ export const storiesRouter = router({
data: { reactionCount: { increment: 1 } },
}),
]);
notifyStoryOwner(ctx.prisma, "STORY_REACTION", targetStory.petId, input.petId, input.storyId);
return { reacted: true };
}),
@@ -433,9 +539,9 @@ export const storiesRouter = router({
}),
/**
* Gitea #29 — mirrors comments.create. No mention-notification fan-out
* (unlike post comments) — stories expire in 24h and have no notify()
* wiring at all yet, matching the Advertisement engagement model.
* Gitea #29 — mirrors comments.create. Der Story-Besitzer bekommt eine
* STORY_COMMENT-Mitteilung (Story-Editor-Branch); @-Erwähnungen im
* Kommentartext werden weiterhin nicht aufgelöst.
*/
addComment: protectedProcedure
.use(rateLimited("stories.addComment", 20, 300))
@@ -474,10 +580,55 @@ export const storiesRouter = router({
data: { commentCount: { increment: 1 } },
}),
]);
notifyStoryOwner(ctx.prisma, "STORY_COMMENT", targetStory.petId, input.petId, input.storyId);
return comment;
}),
/** Notschalter (Admin → Dashboard): App und Web blenden Editor + Overlays aus, wenn aus. */
featureFlags: protectedProcedure.query(async () => ({ storyEditor: await isStoryEditorEnabled() })),
/**
* Tier-Suche für @-Markierungen: nur Tiere, die `petId` laut
* filterMentionablePetIds markieren darf (Block, „Wer darf die Follower
* sehen?“). Spinnen-Ausschluss wie bei jeder Tier-Liste (CLAUDE.md).
*/
searchMentionable: protectedProcedure
.use(rateLimited("stories.searchMentionable", 60, 60))
.input(z.object({ petId: z.string().min(1), query: z.string().trim().min(1).max(50) }))
.query(async ({ ctx, input }) => {
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
const spiderExclusionId = await getSpiderExclusionId(ctx.prisma, ctx.userId);
const candidates = await ctx.prisma.pet.findMany({
where: {
id: { not: input.petId },
OR: [
{ name: { contains: input.query, mode: "insensitive" } },
{ nickname: { contains: input.query, mode: "insensitive" } },
],
...(spiderExclusionId ? { NOT: { speciesId: spiderExclusionId } } : {}),
},
orderBy: { name: "asc" },
take: 40,
select: petIdentitySelect,
});
const allowed = new Set(await filterMentionablePetIds(ctx.prisma, input.petId, candidates.map((p) => p.id)));
return candidates.filter((p) => allowed.has(p.id)).slice(0, 20);
}),
/** GIF-Suche über GIPHY (leere Suche = Trends). Schlüssel bleibt auf dem Server. */
searchGifs: protectedProcedure
.use(rateLimited("stories.searchGifs", 30, 60))
.input(z.object({ query: z.string().trim().max(50).default(""), offset: z.number().int().min(0).max(500).default(0) }))
.query(async ({ input }) => {
try {
return await searchGifs(input.query, input.offset);
} catch (err) {
console.error("[stories.searchGifs]", err);
throw new TRPCError({ code: "SERVICE_UNAVAILABLE", message: "GIF-Suche gerade nicht verfügbar." });
}
}),
/**
* Owner löscht eine eigene Story (auch eine abgelaufene) — samt Aufrufen,
* Pfoten, Kommentaren, Bild und Mux-Asset, siehe deleteStoryWithMedia().