feat(stories): support 30s video uploads, mirroring normal video posts

Story gains mediaType (IMAGE/VIDEO) plus the same Mux fields as
VideoPost (muxUploadId/AssetId/PlaybackId, videoStatus, durationSecs,
aspectRatio); storageKey becomes optional since video stories don't
use Supabase Storage.

- 30s duration cap (deliberately shorter than the 180s normal-post
  cap) enforced client-side before upload (reads the file's own
  duration) and again server-side in the mux webhook and
  stories.getVideoStatus's self-heal path, so a bypassed client check
  or a direct API call can't produce an oversized story video.
- MAX_STORY_VIDEO_DURATION_SECS lives in a new client-safe
  src/lib/story-video-limits.ts rather than stories.ts, which is
  server-only — importing from a server-only module into StoryForm
  (a client component) pulled the pg driver into the client bundle
  and broke the build.
- Mux webhook now resolves an asset to either a VideoPost or a Story;
  video stories never fan out to the feed (mirrors the normal-post
  webhook branch, minus fanOutPost).
- StoryViewer: video stories autoplay muted (tap to unmute — browsers
  block autoplay-with-sound past the story that was directly clicked
  open) with a real playback-time progress bar (image stories keep
  the fixed 5s bar), rendered via object-contain to correctly handle
  the ~9:16 portrait ratio typical of phone-shot story videos instead
  of a fixed 16:9 box.
This commit is contained in:
admin committed 2026-08-16 14:36:44 +02:00
1 parent 9c55e18d4e
commit 8186c36b9a
9 files changed
+538 -126

No files matched your search

+12 -5
View File
@@ -452,17 +452,21 @@
"noPhoto": "Bitte füge mindestens ein Foto hinzu."
},
"StoryForm": {
"addPhoto": "Foto hinzufügen",
"addMedia": "Foto oder Video hinzufügen",
"disappearsNote": "Storys verschwinden nach 24 Stunden",
"changePhoto": "Foto ändern",
"changeMedia": "Ändern",
"postCta": "Story posten",
"posting": "Wird gepostet…",
"successToast": "Story gepostet",
"errorToast": "Deine Story konnte nicht gepostet werden. Bitte versuch es erneut.",
"noPetSelected": "Kein aktives Tier ausgewählt.",
"fileTooLarge": "Foto muss unter 10 MB sein.",
"invalidType": "Lade ein JPG-, PNG- oder WebP-Bild hoch.",
"uploadFailed": "Upload fehlgeschlagen — bitte versuch es erneut."
"invalidType": "Lade ein JPG-, PNG-, WebP-Bild oder ein MP4-, MOV-, WebM-Video hoch.",
"uploadFailed": "Upload fehlgeschlagen — bitte versuch es erneut.",
"videoLengthHint": "Video max. {max} Sekunden",
"videoTooLarge": "Video muss unter 500 MB sein.",
"videoTooLong": "Story-Videos dürfen höchstens {max} Sekunden lang sein.",
"videoUnreadable": "Videolänge konnte nicht gelesen werden — bitte versuch eine andere Datei."
},
"MilestoneForm": {
"questionLabel": "Was ist der Meilenstein?",
@@ -508,7 +512,10 @@
"sheetTitleZero": "Noch keine Aufrufe",
"sheetTitleSingular": "Von 1 Tier gesehen",
"sheetTitlePlural": "Von {count} Tieren gesehen",
"noViewersYet": "Noch niemand hat diese Story angesehen."
"noViewersYet": "Noch niemand hat diese Story angesehen.",
"mute": "Stummschalten",
"unmute": "Ton einschalten",
"videoError": "Video konnte nicht verarbeitet werden."
},
"StoryTray": {
"storiesAriaLabel": "Storys",
+12 -5
View File
@@ -452,17 +452,21 @@
"noPhoto": "Please add at least one photo."
},
"StoryForm": {
"addPhoto": "Add a photo",
"addMedia": "Add a photo or video",
"disappearsNote": "Stories disappear after 24 hours",
"changePhoto": "Change photo",
"changeMedia": "Change",
"postCta": "Post Story",
"posting": "Posting…",
"successToast": "Story posted",
"errorToast": "Couldn't post your story. Please try again.",
"noPetSelected": "No active pet selected.",
"fileTooLarge": "Photo must be under 10 MB.",
"invalidType": "Upload a JPG, PNG, or WebP image.",
"uploadFailed": "Upload failed — please try again."
"invalidType": "Upload a JPG, PNG, WebP image, or an MP4, MOV, WebM video.",
"uploadFailed": "Upload failed — please try again.",
"videoLengthHint": "Video up to {max} seconds",
"videoTooLarge": "Video must be under 500 MB.",
"videoTooLong": "Story videos can be at most {max} seconds long.",
"videoUnreadable": "Couldn't read the video length — please try a different file."
},
"MilestoneForm": {
"questionLabel": "What's the milestone?",
@@ -508,7 +512,10 @@
"sheetTitleZero": "No views yet",
"sheetTitleSingular": "Seen by 1 pet",
"sheetTitlePlural": "Seen by {count} pets",
"noViewersYet": "No one has viewed this story yet."
"noViewersYet": "No one has viewed this story yet.",
"mute": "Mute",
"unmute": "Unmute",
"videoError": "Video could not be processed."
},
"StoryTray": {
"storiesAriaLabel": "Stories",
+24 -4
View File
@@ -339,19 +339,39 @@ model Milestone {
}
model Story {
id String @id @default(cuid())
pet Pet @relation(fields: [petId], references: [id], onDelete: Cascade)
id String @id @default(cuid())
pet Pet @relation(fields: [petId], references: [id], onDelete: Cascade)
petId String
storageKey String // Supabase Storage object key
mediaType StoryMediaType @default(IMAGE)
storageKey String? // Supabase Storage object key — IMAGE stories only
blurhash String? // computed client-side at upload (src/lib/blurhash.ts), decoded as a loading placeholder
expiresAt DateTime // set to NOW() + 24 hours on create (D-07)
views StoryView[]
createdAt DateTime @default(now())
createdAt DateTime @default(now())
// VIDEO stories — mirrors VideoPost. Typically 9:16 (phone-shot, portrait),
// unlike normal feed videos which skew 16:9 — aspectRatio drives rendering,
// never assume landscape. Duration capped at 30s (see
// MAX_STORY_VIDEO_DURATION_SECS in stories.ts), enforced client-side
// before upload and again server-side when the asset becomes ready.
muxUploadId String?
muxAssetId String?
muxPlaybackId String?
videoStatus VideoStatus?
durationSecs Float?
aspectRatio String? // e.g. "9:16" from Mux
// Gitea #18 — legal AI-content disclosure, set once at creation.
aiDisclosure AiDisclosure @default(NONE)
@@index([petId, expiresAt]) // supports lazy-delete filter query
@@index([muxUploadId])
@@index([muxAssetId])
}
enum StoryMediaType {
IMAGE
VIDEO
}
model StoryView {
+50 -18
View File
@@ -3,6 +3,7 @@ import { prisma } from "@/lib/prisma";
import { mux, MUX_WEBHOOK_SECRET } from "@/lib/mux";
import { redis } from "@/lib/redis";
import { fanOutPost } from "@/lib/feed-helpers";
import { MAX_STORY_VIDEO_DURATION_SECS } from "@/lib/story-video-limits";
/**
* POST /api/webhooks/mux
@@ -53,6 +54,10 @@ export async function POST(req: NextRequest) {
where: { muxUploadId: uploadId },
data: { muxAssetId: assetId },
});
await prisma.story.updateMany({
where: { muxUploadId: uploadId },
data: { muxAssetId: assetId },
});
break;
}
@@ -70,26 +75,49 @@ export async function POST(req: NextRequest) {
where: { muxAssetId: assetId },
include: { post: { select: { id: true, petId: true, createdAt: true } } },
});
if (!videoPost) break;
await prisma.videoPost.update({
where: { id: videoPost.id },
data: {
muxPlaybackId: playbackId,
status: "READY",
durationSecs: durationSecs ?? null,
aspectRatio: aspectRatio ?? null,
},
if (videoPost) {
await prisma.videoPost.update({
where: { id: videoPost.id },
data: {
muxPlaybackId: playbackId,
status: "READY",
durationSecs: durationSecs ?? null,
aspectRatio: aspectRatio ?? null,
},
});
// Fan-out to followers now that the video is playable
await fanOutPost(
redis,
videoPost.post.id,
videoPost.post.petId,
videoPost.post.createdAt,
prisma
).catch((err) => console.error("[mux-webhook] fanOutPost failed", err));
break;
}
const story = await prisma.story.findFirst({ where: { muxAssetId: assetId } });
if (!story) break;
// Server-side safety net for the 30s story-video cap — the client
// already rejects oversized files before upload, but a video that
// slips through (or an upload made outside the app) must not become
// playable in a story just because it made it to Mux.
const overStoryLimit = (durationSecs ?? 0) > MAX_STORY_VIDEO_DURATION_SECS;
await prisma.story.update({
where: { id: story.id },
data: overStoryLimit
? { videoStatus: "ERROR" }
: {
muxPlaybackId: playbackId,
videoStatus: "READY",
durationSecs: durationSecs ?? null,
aspectRatio: aspectRatio ?? null,
},
});
// Fan-out to followers now that the video is playable
await fanOutPost(
redis,
videoPost.post.id,
videoPost.post.petId,
videoPost.post.createdAt,
prisma
).catch((err) => console.error("[mux-webhook] fanOutPost failed", err));
break;
}
@@ -101,6 +129,10 @@ export async function POST(req: NextRequest) {
where: { muxAssetId: assetId },
data: { status: "ERROR" },
});
await prisma.story.updateMany({
where: { muxAssetId: assetId },
data: { videoStatus: "ERROR" },
});
break;
}
+198 -63
View File
@@ -1,7 +1,7 @@
"use client";
import { useState, useRef, useCallback } from "react";
import { Camera, Loader2, ImagePlus } from "lucide-react";
import { Camera, Loader2, ImagePlus, Video } from "lucide-react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { useMutation, useQueryClient } from "@tanstack/react-query";
@@ -10,26 +10,60 @@ import { useActivePet } from "@/context/ActivePetContext";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { computeBlurhash } from "@/lib/blurhash";
import { uploadFileWithProgress } from "@/lib/upload-xhr";
import { AiDisclosureSelect, type AiDisclosureValue } from "@/components/content/AiDisclosureSelect";
import { MAX_STORY_VIDEO_DURATION_SECS } from "@/lib/story-video-limits";
const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp"] as const;
type AllowedContentType = (typeof ALLOWED_TYPES)[number];
const MAX_FILE_SIZE = 10 * 1024 * 1024;
const ALLOWED_IMAGE_TYPES = ["image/jpeg", "image/png", "image/webp"] as const;
type AllowedImageType = (typeof ALLOWED_IMAGE_TYPES)[number];
const MAX_IMAGE_SIZE = 10 * 1024 * 1024;
const ALLOWED_VIDEO_TYPES = ["video/mp4", "video/quicktime", "video/webm"] as const;
const MAX_VIDEO_SIZE = 500 * 1024 * 1024; // same as normal video posts (VideoUploadForm.tsx)
const ACCEPT_ATTR = [...ALLOWED_IMAGE_TYPES, ...ALLOWED_VIDEO_TYPES].join(",");
interface StoryFormProps {
onClose: () => void;
}
type UploadState = "idle" | "uploading" | "ready" | "submitting";
type MediaKind = "image" | "video";
/** Reads a video File's duration via a throwaway <video> element. */
function readVideoDuration(file: File): Promise<number> {
return new Promise((resolve, reject) => {
const video = document.createElement("video");
video.preload = "metadata";
video.onloadedmetadata = () => {
URL.revokeObjectURL(video.src);
resolve(video.duration);
};
video.onerror = () => {
URL.revokeObjectURL(video.src);
reject(new Error("duration-read-failed"));
};
video.src = URL.createObjectURL(file);
});
}
/**
* StoryForm — single-photo upload for 24-hour stories.
* StoryForm — photo or short video upload for 24-hour stories.
*
* Upload flow mirrors AvatarUpload / MultiImageUpload:
* Photo flow mirrors AvatarUpload / MultiImageUpload:
* 1. File validated (size, type)
* 2. stories.getPresignedUrl → signed URL
* 3. XHR PUT directly to Supabase Storage
* 4. stories.create({ petId, storageKey }) commits the story
*
* Video flow mirrors VideoUploadForm, but nothing is created or uploaded
* until "Post" is clicked — only client-side validation (type, size, and
* the 30s duration cap, MAX_STORY_VIDEO_DURATION_SECS) runs on file select,
* so the confirm step behaves the same as the photo flow:
* 1. File validated locally, incl. reading duration from the file itself
* 2. On submit: stories.createVideoUpload → Mux upload URL + Story row (PROCESSING)
* 3. XHR PUT directly to Mux
* 4. Form closes — StoryViewer polls stories.getVideoStatus until READY
*/
export function StoryForm({ onClose }: StoryFormProps) {
const t = useTranslations("StoryForm");
@@ -38,6 +72,8 @@ export function StoryForm({ onClose }: StoryFormProps) {
const { activePetId } = useActivePet();
const fileInputRef = useRef<HTMLInputElement>(null);
const [mediaKind, setMediaKind] = useState<MediaKind | null>(null);
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [uploadState, setUploadState] = useState<UploadState>("idle");
const [uploadProgress, setUploadProgress] = useState(0);
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
@@ -69,6 +105,52 @@ export function StoryForm({ onClose }: StoryFormProps) {
})
);
const createVideoUploadMutation = useMutation(
trpc.stories.createVideoUpload.mutationOptions()
);
const invalidateStoryQueries = useCallback(() => {
queryClient.invalidateQueries(
trpc.stories.hasActiveStory.queryOptions({ petId: activePetId ?? "" })
);
queryClient.invalidateQueries(
trpc.stories.listActive.queryOptions({ petId: activePetId ?? "" })
);
}, [queryClient, trpc, activePetId]);
const handleImageFile = useCallback(
async (file: File) => {
const [{ presignedUrl, key }, blurhash] = await Promise.all([
getPresignedUrlMutation.mutateAsync({
petId: activePetId as string,
contentType: file.type as AllowedImageType,
fileSize: file.size,
}),
computeBlurhash(file),
]);
await new Promise<void>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) {
setUploadProgress(Math.round((e.loaded / e.total) * 100));
}
};
xhr.onload = () =>
xhr.status >= 200 && xhr.status < 300 ? resolve() : reject();
xhr.onerror = () => reject(new Error("Network error"));
xhr.open("PUT", presignedUrl);
xhr.setRequestHeader("Content-Type", file.type);
xhr.send(file);
});
setUploadedKey(key);
setUploadedBlurhash(blurhash);
setUploadState("ready");
},
[activePetId, getPresignedUrlMutation]
);
const handleFile = useCallback(
async (file: File) => {
if (!activePetId) {
@@ -77,55 +159,59 @@ export function StoryForm({ onClose }: StoryFormProps) {
}
setErrorMessage(null);
const isVideo = (ALLOWED_VIDEO_TYPES as readonly string[]).includes(file.type);
const isImage = (ALLOWED_IMAGE_TYPES as readonly string[]).includes(file.type);
if (file.size > MAX_FILE_SIZE) {
setErrorMessage(t("fileTooLarge"));
return;
}
if (!ALLOWED_TYPES.includes(file.type as AllowedContentType)) {
if (!isVideo && !isImage) {
setErrorMessage(t("invalidType"));
return;
}
if (isImage && file.size > MAX_IMAGE_SIZE) {
setErrorMessage(t("fileTooLarge"));
return;
}
if (isVideo && file.size > MAX_VIDEO_SIZE) {
setErrorMessage(t("videoTooLarge"));
return;
}
if (isVideo) {
try {
const duration = await readVideoDuration(file);
if (duration > MAX_STORY_VIDEO_DURATION_SECS) {
setErrorMessage(t("videoTooLong", { max: MAX_STORY_VIDEO_DURATION_SECS }));
return;
}
} catch {
setErrorMessage(t("videoUnreadable"));
return;
}
setMediaKind("video");
setSelectedFile(file);
setPreviewUrl(URL.createObjectURL(file));
setUploadState("ready");
return;
}
// Image — upload starts immediately, "Post" only commits the Story row.
setMediaKind("image");
setSelectedFile(file);
setPreviewUrl(URL.createObjectURL(file));
setUploadState("uploading");
setUploadProgress(0);
try {
const [{ presignedUrl, key }, blurhash] = await Promise.all([
getPresignedUrlMutation.mutateAsync({
petId: activePetId,
contentType: file.type as AllowedContentType,
fileSize: file.size,
}),
computeBlurhash(file),
]);
await new Promise<void>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) {
setUploadProgress(Math.round((e.loaded / e.total) * 100));
}
};
xhr.onload = () =>
xhr.status >= 200 && xhr.status < 300 ? resolve() : reject();
xhr.onerror = () => reject(new Error("Network error"));
xhr.open("PUT", presignedUrl);
xhr.setRequestHeader("Content-Type", file.type);
xhr.send(file);
});
setUploadedKey(key);
setUploadedBlurhash(blurhash);
setUploadState("ready");
await handleImageFile(file);
} catch {
setErrorMessage(t("uploadFailed"));
setUploadState("idle");
setPreviewUrl(null);
setMediaKind(null);
}
},
[activePetId, getPresignedUrlMutation, t]
[activePetId, handleImageFile, t]
);
const handleFileChange = useCallback(
@@ -137,16 +223,52 @@ export function StoryForm({ onClose }: StoryFormProps) {
[handleFile]
);
const handleSubmit = useCallback(() => {
if (!activePetId || !uploadedKey) return;
setUploadState("submitting");
createStoryMutation.mutate({
petId: activePetId,
storageKey: uploadedKey,
blurhash: uploadedBlurhash,
aiDisclosure,
});
}, [activePetId, uploadedKey, uploadedBlurhash, aiDisclosure, createStoryMutation]);
const handleSubmit = useCallback(async () => {
if (!activePetId) return;
if (mediaKind === "image") {
if (!uploadedKey) return;
setUploadState("submitting");
createStoryMutation.mutate({
petId: activePetId,
storageKey: uploadedKey,
blurhash: uploadedBlurhash,
aiDisclosure,
});
return;
}
if (mediaKind === "video" && selectedFile) {
setUploadState("submitting");
try {
const { uploadUrl } = await createVideoUploadMutation.mutateAsync({
petId: activePetId,
aiDisclosure,
});
await uploadFileWithProgress(uploadUrl ?? "", selectedFile, {
onProgress: setUploadProgress,
});
invalidateStoryQueries();
toast.success(t("successToast"));
onClose();
} catch {
toast.error(t("errorToast"));
setUploadState("ready");
}
}
}, [
activePetId,
mediaKind,
uploadedKey,
uploadedBlurhash,
aiDisclosure,
selectedFile,
createStoryMutation,
createVideoUploadMutation,
invalidateStoryQueries,
onClose,
t,
]);
return (
<div className="px-4 pb-6 space-y-5">
@@ -162,11 +284,11 @@ export function StoryForm({ onClose }: StoryFormProps) {
if ((e.key === "Enter" || e.key === " ") && uploadState === "idle")
fileInputRef.current?.click();
}}
aria-label={t("addPhoto")}
aria-label={t("addMedia")}
>
<input
type="file"
accept="image/jpeg,image/png,image/webp"
accept={ACCEPT_ATTR}
className="hidden"
ref={fileInputRef}
onChange={handleFileChange}
@@ -174,24 +296,37 @@ export function StoryForm({ onClose }: StoryFormProps) {
{!previewUrl ? (
<>
<ImagePlus className="h-10 w-10 text-muted-foreground" aria-hidden="true" />
<div className="flex items-center gap-3 text-muted-foreground">
<ImagePlus className="h-8 w-8" aria-hidden="true" />
<Video className="h-8 w-8" aria-hidden="true" />
</div>
<div className="text-center">
<p className="text-sm font-medium">{t("addPhoto")}</p>
<p className="text-sm font-medium">{t("addMedia")}</p>
<p className="text-xs text-muted-foreground mt-0.5">
{t("disappearsNote")}
{t("videoLengthHint", { max: MAX_STORY_VIDEO_DURATION_SECS })}
</p>
</div>
</>
) : (
<>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={previewUrl}
alt="Story preview"
className="w-full max-h-[360px] object-contain rounded-xl"
/>
{mediaKind === "video" ? (
<video
src={previewUrl}
controls
muted
className="w-full max-h-[420px] object-contain rounded-xl"
/>
) : (
// eslint-disable-next-line @next/next/no-img-element
<img
src={previewUrl}
alt="Story preview"
className="w-full max-h-[360px] object-contain rounded-xl"
/>
)}
{/* Progress overlay during upload */}
{uploadState === "uploading" && (
{(uploadState === "uploading" ||
(uploadState === "submitting" && mediaKind === "video")) && (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-3 bg-black/50 rounded-xl">
<Loader2 className="h-8 w-8 text-white animate-spin" />
<Progress
@@ -210,7 +345,7 @@ export function StoryForm({ onClose }: StoryFormProps) {
}}
>
<Camera className="h-3 w-3 inline mr-1" aria-hidden="true" />
{t("changePhoto")}
{t("changeMedia")}
</button>
)}
</>
@@ -231,7 +366,7 @@ export function StoryForm({ onClose }: StoryFormProps) {
<Button
className="w-full bg-orange-500 hover:bg-orange-600 text-white"
disabled={uploadState !== "ready" || !uploadedKey}
disabled={uploadState !== "ready" || (mediaKind === "image" && !uploadedKey)}
onClick={handleSubmit}
>
{uploadState === "submitting" ? (
+129 -29
View File
@@ -1,7 +1,8 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { X, Eye } from "lucide-react";
import { useState, useEffect, useCallback, useRef } from "react";
import dynamic from "next/dynamic";
import { X, Eye, Volume2, VolumeX, Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTRPC } from "@/trpc/client";
@@ -18,6 +19,13 @@ import { getMediaUrl } from "@/lib/media-url";
import { BlurImage } from "@/components/ui/blur-image";
import { AiDisclosureBadge } from "@/components/content/AiDisclosureBadge";
// Same lazy-load rationale as VideoCard.tsx — keep the HLS.js player runtime
// out of the main bundle, only load it when a video story actually renders.
const MuxPlayer = dynamic(() => import("@mux/mux-player-react"), {
ssr: false,
loading: () => <div className="w-full h-full bg-black" />,
});
interface StoryViewerProps {
petId: string;
petName: string;
@@ -26,13 +34,17 @@ interface StoryViewerProps {
onOpenChange: (open: boolean) => void;
}
const STORY_DURATION_MS = 5000;
const IMAGE_STORY_DURATION_MS = 5000;
/**
* StoryViewer — full-screen story viewer with 5-second progress bar.
* StoryViewer — full-screen story viewer with per-story progress bar.
*
* - Records a deduplicated view via stories.recordView on open (STORY-03)
* - Progress bar: orange fill transitioning 0→100% over 5s, auto-advances/closes
* - Image stories: fixed 5s progress bar, auto-advances/closes
* - Video stories: autoplay (muted, tap to unmute — most browsers block
* autoplay-with-sound on anything but the story that was directly
* clicked open), progress bar tracks real playback time, advances on
* the video's own "ended" event instead of a fixed timer
* - Viewer list: owner-only Sheet showing who has seen each story
*/
export function StoryViewer({
@@ -50,6 +62,8 @@ export function StoryViewer({
const [currentIndex, setCurrentIndex] = useState(0);
const [progress, setProgress] = useState(0);
const [viewerSheetOpen, setViewerSheetOpen] = useState(false);
const [isMuted, setIsMuted] = useState(true);
const advancedRef = useRef(false);
const { data: stories = [] } = useQuery(
trpc.stories.listActive.queryOptions({ petId })
@@ -57,6 +71,18 @@ export function StoryViewer({
const currentStory = stories[currentIndex];
const isOwnPet = activePetId === petId;
const isVideo = currentStory?.mediaType === "VIDEO";
// Poll while a video story is still processing — same self-heal pattern
// as VideoCard, scoped to just the story currently on screen.
const { data: videoStatusData } = useQuery({
...trpc.stories.getVideoStatus.queryOptions({ storyId: currentStory?.id ?? "" }),
enabled: !!currentStory && isVideo && currentStory.videoStatus === "PROCESSING",
refetchInterval: (query) => (query.state.data?.videoStatus === "PROCESSING" ? 3000 : false),
});
const videoStatus = videoStatusData?.videoStatus ?? currentStory?.videoStatus;
const videoPlaybackId = videoStatusData?.muxPlaybackId ?? currentStory?.muxPlaybackId;
const recordViewMutation = useMutation(
trpc.stories.recordView.mutationOptions()
@@ -79,40 +105,70 @@ export function StoryViewer({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, currentStory?.id, activePetId]);
// Progress bar + auto-advance
const advance = useCallback(() => {
if (advancedRef.current) return;
advancedRef.current = true;
if (currentIndex < stories.length - 1) {
setCurrentIndex((i) => i + 1);
} else {
onOpenChange(false);
}
}, [currentIndex, stories.length, onOpenChange]);
// Image progress bar — fixed duration, unused for video stories (those
// advance on the player's "ended" event instead, see onVideoEnded below).
useEffect(() => {
if (!open || !currentStory) return;
if (!open || !currentStory || isVideo) return;
setProgress(0);
advancedRef.current = false;
const startTime = Date.now();
let rafId: number;
function tick() {
const elapsed = Date.now() - startTime;
const pct = Math.min((elapsed / STORY_DURATION_MS) * 100, 100);
const pct = Math.min((elapsed / IMAGE_STORY_DURATION_MS) * 100, 100);
setProgress(pct);
if (pct < 100) {
rafId = requestAnimationFrame(tick);
} else {
// advance to next story or close
if (currentIndex < stories.length - 1) {
setCurrentIndex((i) => i + 1);
} else {
onOpenChange(false);
}
advance();
}
}
rafId = requestAnimationFrame(tick);
return () => cancelAnimationFrame(rafId);
}, [open, currentStory, currentIndex, stories.length, onOpenChange]);
}, [open, currentStory, isVideo, advance]);
// Reset progress/advance-guard when a video story becomes current.
useEffect(() => {
if (isVideo) {
setProgress(0);
advancedRef.current = false;
}
}, [isVideo, currentStory?.id]);
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/
// duration like a native HTMLVideoElement.
const video = e.target as HTMLVideoElement;
if (video.duration > 0) {
setProgress((video.currentTime / video.duration) * 100);
}
}, []);
const handleVideoEnded = useCallback(() => {
setProgress(100);
advance();
}, [advance]);
// Reset index when viewer opens
useEffect(() => {
if (open) {
setCurrentIndex(0);
setProgress(0);
setIsMuted(true);
}
}, [open]);
@@ -123,7 +179,7 @@ export function StoryViewer({
if (!currentStory) return null;
const mediaUrl = getMediaUrl(currentStory.storageKey);
const mediaUrl = currentStory.storageKey ? getMediaUrl(currentStory.storageKey) : null;
return (
<>
@@ -136,7 +192,7 @@ export function StoryViewer({
aria-label={t("storyAriaLabel", { petName })}
>
{/* Progress bars */}
<div className="absolute top-0 left-0 right-0 flex gap-1 px-3 pt-3">
<div className="absolute top-0 left-0 right-0 flex gap-1 px-3 pt-3 z-10">
{stories.map((s, i) => (
<div key={s.id} className="flex-1 h-0.5 bg-white/30 rounded-full overflow-hidden">
<div
@@ -155,7 +211,7 @@ export function StoryViewer({
))}
</div>
{/* Story image — wrapper fills the full-screen overlay and
{/* Story media — wrapper fills the full-screen overlay and
object-contain does all the aspect-ratio scaling/centering
itself. A previous "shrink-wrap to the image's own rendered
box" approach relied on percentage max-height/max-width
@@ -163,21 +219,65 @@ export function StoryViewer({
parent, which CSS treats as unresolvable — portrait images
would render at full natural size (clipped) or lose centering
depending on which axis' ambiguity won. Filling a definite-size
parent sidesteps that class of bug entirely. */}
{mediaUrl && (
parent sidesteps that class of bug entirely. Video stories are
typically 9:16 (phone-shot portrait, unlike the mostly-16:9
normal feed videos) — object-contain here matters even more:
no fixed aspect-video box like VideoCard uses. */}
{isVideo ? (
<div className="relative w-full h-full">
<BlurImage
src={mediaUrl}
blurhash={currentStory.blurhash}
alt={t("storyAriaLabel", { petName })}
className="block w-full h-full object-contain"
wrapperClassName="relative block w-full h-full"
/>
{videoStatus === "READY" && videoPlaybackId ? (
<MuxPlayer
playbackId={videoPlaybackId}
streamType="on-demand"
autoPlay
muted={isMuted}
style={{ width: "100%", height: "100%", objectFit: "contain" }}
onTimeUpdate={handleVideoTimeUpdate}
onEnded={handleVideoEnded}
/>
) : videoStatus === "ERROR" ? (
<div className="flex h-full w-full items-center justify-center text-white/70 text-sm">
{t("videoError")}
</div>
) : (
<div className="flex h-full w-full items-center justify-center">
<Loader2 className="h-8 w-8 text-white animate-spin" />
</div>
)}
{videoStatus === "READY" && (
<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>
)}
<AiDisclosureBadge
value={currentStory.aiDisclosure}
className="top-auto left-auto bottom-3 right-3 h-10"
className="top-auto left-auto bottom-3 right-16 h-10"
/>
</div>
) : (
mediaUrl && (
<div className="relative w-full h-full">
<BlurImage
src={mediaUrl}
blurhash={currentStory.blurhash}
alt={t("storyAriaLabel", { petName })}
className="block w-full h-full object-contain"
wrapperClassName="relative block w-full h-full"
/>
<AiDisclosureBadge
value={currentStory.aiDisclosure}
className="top-auto left-auto bottom-3 right-3 h-10"
/>
</div>
)
)}
{/* Pet info — bottom left */}
+1 -1
View File
@@ -32,7 +32,7 @@ export async function deleteOwnerAccount(prisma: PrismaClient, ownerId: string):
}
}
for (const story of pet.stories) {
storageKeys.push(story.storageKey);
if (story.storageKey) storageKeys.push(story.storageKey);
}
}
+13
View File
@@ -0,0 +1,13 @@
/**
* Shared between StoryForm.tsx (client) and stories.ts / the mux webhook
* (server). Deliberately NOT in stories.ts — that file is marked
* "server-only", and importing anything from it into a client component
* pulls the whole server module graph (Prisma, the pg driver, Mux SDK)
* into the client bundle, which fails at build time.
*
* Shorter than the 180s cap on normal video posts (videos.ts) — stories
* are a quick, ephemeral format. Enforced client-side before upload
* (StoryForm.tsx) and again server-side (stories.ts + the mux webhook) so
* a direct API call or a slipped-through upload can't bypass it.
*/
export const MAX_STORY_VIDEO_DURATION_SECS = 30;
+99 -1
View File
@@ -9,9 +9,11 @@ import {
} from "@/lib/supabase-storage";
import { randomUUID } from "crypto";
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
import { mux } from "@/lib/mux";
import { MAX_STORY_VIDEO_DURATION_SECS } from "@/lib/story-video-limits";
/**
* Stories tRPC router — 24-hour photo stories with lazy-delete expiry (D-07).
* Stories tRPC router — 24-hour photo/video stories with lazy-delete expiry (D-07).
*
* Security (T-02-40 to T-02-44):
* - create asserts pet ownership before write (T-02-40)
@@ -73,6 +75,102 @@ export const storiesRouter = router({
});
}),
/**
* Create a Mux direct upload URL + a PROCESSING video Story row.
* The client PUTs the video file directly to Mux — never through our
* server. Client-side duration check (StoryForm.tsx) happens before this
* is even called; the mux webhook re-checks MAX_STORY_VIDEO_DURATION_SECS
* 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") }))
.mutation(async ({ ctx, input }) => {
await assertPetOwnership(ctx.prisma, input.petId, ctx.userId);
if (!process.env.MUX_TOKEN_ID || !process.env.MUX_TOKEN_SECRET) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Video upload is not configured. Add MUX_TOKEN_ID and MUX_TOKEN_SECRET to .env.local.",
});
}
const upload = await mux.video.uploads.create({
cors_origin:
process.env.NODE_ENV === "production" ? (process.env.NEXT_PUBLIC_APP_URL ?? "*") : "*",
new_asset_settings: {
playback_policy: ["public"],
max_resolution_tier: "1080p",
},
});
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
const story = await ctx.prisma.story.create({
data: {
petId: input.petId,
mediaType: "VIDEO",
muxUploadId: upload.id,
videoStatus: "PROCESSING",
aiDisclosure: input.aiDisclosure,
expiresAt,
},
});
return { uploadUrl: upload.url, storyId: story.id };
}),
/**
* Get a video story's status — used to poll while PROCESSING.
* Self-heals like videos.getByPostId (checks Mux directly if the webhook
* hasn't landed yet) — but unlike posts, stories never fan out to a feed,
* so there's no equivalent side effect to replicate here.
*/
getVideoStatus: protectedProcedure
.input(z.object({ storyId: z.string().min(1) }))
.query(async ({ ctx, input }) => {
const story = await ctx.prisma.story.findUnique({ where: { id: input.storyId } });
if (!story) throw new TRPCError({ code: "NOT_FOUND" });
if (story.videoStatus === "PROCESSING" && process.env.MUX_TOKEN_ID) {
try {
let assetId = story.muxAssetId;
if (!assetId && story.muxUploadId) {
const upload = await mux.video.uploads.retrieve(story.muxUploadId);
if (upload.asset_id) assetId = upload.asset_id;
}
if (assetId) {
const asset = await mux.video.assets.retrieve(assetId);
if (asset.status === "ready" && asset.playback_ids?.[0]) {
const overLimit = (asset.duration ?? 0) > MAX_STORY_VIDEO_DURATION_SECS;
return await ctx.prisma.story.update({
where: { id: input.storyId },
data: overLimit
? { videoStatus: "ERROR", muxAssetId: assetId }
: {
videoStatus: "READY",
muxAssetId: assetId,
muxPlaybackId: asset.playback_ids[0].id,
durationSecs: asset.duration ?? null,
aspectRatio: asset.aspect_ratio ?? null,
},
});
} else if (asset.status === "errored") {
return await ctx.prisma.story.update({
where: { id: input.storyId },
data: { videoStatus: "ERROR", muxAssetId: assetId },
});
}
}
} catch {
// Mux check failed — return current DB state unchanged
}
}
return story;
}),
/**
* List active (non-expired) stories for a pet (D-07 lazy-delete pattern).
*/