t3xbu10dr: Publish video posts through the media pipeline and upgrade thumbnails to the player
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { SESSION_COOKIE } from "@/lib/cookie";
|
||||
import { createTextPost } from "@/lib/post-create";
|
||||
import { createImagePost } from "@/lib/post-media";
|
||||
import { createMediaPost } from "@/lib/post-media";
|
||||
|
||||
// POST /api/posts
|
||||
// - JSON { content } -> public text post
|
||||
// - multipart/form-data content+file -> public image post (one file)
|
||||
// - multipart/form-data content+file -> public image or video post (one file)
|
||||
// Both create a public draft on the feed, then publish it, and return { id }.
|
||||
// For an image the server also uploads the bytes to a presigned URL and confirms
|
||||
// the upload; the browser never receives the feed token. The create call can
|
||||
@@ -31,7 +31,7 @@ export async function POST(req: NextRequest) {
|
||||
} catch {
|
||||
return NextResponse.json({ error: "bad_file" }, { status: 400 });
|
||||
}
|
||||
const result = await createImagePost(sessionId, content, file);
|
||||
const result = await createMediaPost(sessionId, content, file);
|
||||
if (!result.ok) {
|
||||
return NextResponse.json({ error: result.error }, { status: result.status });
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.post-text { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.5; }
|
||||
.post-media img { display: block; width: 100%; height: auto; border-radius: 8px; }
|
||||
.post-video { background: #000; border-radius: 8px; overflow: hidden; }
|
||||
.post-video-pending { color: #fff; padding: 48px 12px; text-align: center; }
|
||||
.post-video video { display: block; width: 100%; max-height: 520px; background: #000; }
|
||||
.post-stats { display: flex; gap: 16px; color: var(--grey); font-size: 14px; }
|
||||
.heart { color: var(--red); }
|
||||
@@ -52,6 +53,7 @@ button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.composer-image span { padding: 6px 12px; border: 1px solid #999; background: #fafafa; }
|
||||
.composer-image input[type="file"] { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); border: 0; }
|
||||
.composer-preview { display: flex; align-items: center; gap: 10px; }
|
||||
.composer-preview video { width: 96px; height: 64px; object-fit: cover; border: 1px solid var(--line); background: #000; }
|
||||
.composer-preview img { width: 64px; height: 64px; object-fit: cover; border: 1px solid var(--line); }
|
||||
.composer-filename { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.composer-remove { margin: 0; padding: 6px 12px; border-radius: 0; }
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from "react";
|
||||
import { useEffect, useState, type ChangeEvent, type FormEvent } from "react";
|
||||
|
||||
export interface ComposerProps {
|
||||
value: string;
|
||||
busy: boolean;
|
||||
error: boolean;
|
||||
/** The selected image file, when the image picker is wired. */
|
||||
/** The selected image or video file, when the pickers are wired. */
|
||||
file?: File | null;
|
||||
onChange: (value: string) => void;
|
||||
/** When present, the composer shows an image picker and reports the choice. */
|
||||
/** When present, the composer shows image and video pickers and reports the choice. */
|
||||
onFile?: (file: File | null) => void;
|
||||
onSubmit: () => void;
|
||||
}
|
||||
|
||||
// Content types the picker offers (spec: allowed image types).
|
||||
const IMAGE_ACCEPT = "image/jpeg,image/jpg,image/png,image/gif,image/webp,image/heic";
|
||||
const VIDEO_ACCEPT = "video/mp4,video/quicktime,video/webm";
|
||||
|
||||
export function Composer({ value, busy, error, file = null, onChange, onFile, onSubmit }: ComposerProps) {
|
||||
const empty = value.trim().length === 0;
|
||||
// A post needs either text or an image.
|
||||
// A post needs either text or a file.
|
||||
const canSubmit = (!empty || !!file) && !busy;
|
||||
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||
const [preview, setPreview] = useState<string | null>(null);
|
||||
|
||||
// Build a preview URL client-side only, and revoke it when the file changes.
|
||||
@@ -42,11 +42,13 @@ export function Composer({ value, busy, error, file = null, onChange, onFile, on
|
||||
function pick(e: ChangeEvent<HTMLInputElement>) {
|
||||
const chosen = e.target.files && e.target.files[0] ? e.target.files[0] : null;
|
||||
onFile?.(chosen);
|
||||
// One file per post: picking one kind clears the other input.
|
||||
e.target.value = "";
|
||||
}
|
||||
function remove() {
|
||||
onFile?.(null);
|
||||
if (inputRef.current) inputRef.current.value = "";
|
||||
}
|
||||
const isVideo = !!file && file.type.startsWith("video/");
|
||||
|
||||
return (
|
||||
<form className="composer" onSubmit={submit}>
|
||||
@@ -64,16 +66,21 @@ export function Composer({ value, busy, error, file = null, onChange, onFile, on
|
||||
<label className="composer-image">
|
||||
<span>Add image</span>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept={IMAGE_ACCEPT}
|
||||
disabled={busy}
|
||||
onChange={pick}
|
||||
/>
|
||||
</label>
|
||||
<label className="composer-image composer-video">
|
||||
<span>Add video</span>
|
||||
<input type="file" accept={VIDEO_ACCEPT} disabled={busy} onChange={pick} />
|
||||
</label>
|
||||
{file ? (
|
||||
<div className="composer-preview">
|
||||
{preview ? (
|
||||
{preview && isVideo ? (
|
||||
<video src={preview} muted playsInline preload="metadata" aria-label={`Selected video: ${file.name}`} />
|
||||
) : preview ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={preview} alt={`Selected image: ${file.name}`} />
|
||||
) : null}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { fetchFeedPage, FeedLoadError } from "@/lib/feed-client";
|
||||
import { applyLikeOutcome, LikeError, sendLike } from "@/lib/like-client";
|
||||
import { mergePosts, toCardPosts, type CardPost } from "@/lib/feed-model";
|
||||
import { mergePosts, toCardPosts, upgradeVideos, type CardPost } from "@/lib/feed-model";
|
||||
import { PostError, publishAndConfirm } from "@/lib/post-client";
|
||||
import { DeleteError, sendDelete } from "@/lib/delete-client";
|
||||
import { FeedView, type FeedStatus } from "./FeedView";
|
||||
@@ -106,7 +106,9 @@ export function Feed({ onSignedOut, feedUserId }: { onSignedOut: () => void; fee
|
||||
const poll = async () => {
|
||||
try {
|
||||
const page = await fetchFeedPage(null);
|
||||
const fresh = toCardPosts(page.items).filter((p) => !shown.current.has(p.key));
|
||||
const all = toCardPosts(page.items);
|
||||
setPosts((cur) => upgradeVideos(cur, all));
|
||||
const fresh = all.filter((p) => !shown.current.has(p.key));
|
||||
if (fresh.length) setPending((cur) => mergePosts(cur, fresh));
|
||||
} catch (e) {
|
||||
fail(e);
|
||||
@@ -188,7 +190,7 @@ export function Feed({ onSignedOut, feedUserId }: { onSignedOut: () => void; fee
|
||||
|
||||
const publish = useCallback(async () => {
|
||||
const text = draft.trim();
|
||||
// A post needs either text or an image.
|
||||
// A post needs either text or a file.
|
||||
if ((!text && !file) || posting) return;
|
||||
setPosting(true);
|
||||
setPostFailed(false);
|
||||
|
||||
@@ -96,6 +96,10 @@ export function PostCard({ post, now, onToggleLike, likeBusy, likeError, onSigne
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={m.src} alt={m.kind === "video" ? "Video thumbnail" : ""} loading="lazy" />
|
||||
</div>
|
||||
) : m.kind === "video" ? (
|
||||
<div className="post-media post-video post-video-pending" key={i} role="img" aria-label="Video is processing">
|
||||
<span>Video is processing</span>
|
||||
</div>
|
||||
) : null,
|
||||
)}
|
||||
<footer className="post-stats">
|
||||
|
||||
+23
-1
@@ -76,7 +76,8 @@ function toMedia(raw: unknown): CardMedia[] {
|
||||
if (m.mediaType === "video") {
|
||||
const thumb = str(m.thumbnailUrl);
|
||||
const hls = muxHlsUrl(m.hlsUrl);
|
||||
if (thumb || hls) out.push({ kind: "video", src: thumb, hlsUrl: hls });
|
||||
// Keep a video even with no thumbnail or hlsUrl yet (just published).
|
||||
out.push({ kind: "video", src: thumb, hlsUrl: hls });
|
||||
continue;
|
||||
}
|
||||
const src = str(m.imageMediumWebpUrl) ?? str(m.imageMediumUrl) ?? str(m.imageUrl);
|
||||
@@ -142,6 +143,27 @@ export function mergePosts(...lists: CardPost[][]): CardPost[] {
|
||||
return sortByPublishedDesc(all);
|
||||
}
|
||||
|
||||
const hasHls = (p: CardPost) => p.media.some((m) => m.kind === "video" && m.hlsUrl);
|
||||
|
||||
/**
|
||||
* Swap in the media of shown posts whose video gained an hlsUrl on a refresh
|
||||
* (transcoding finished), so the thumbnail upgrades to the player in place.
|
||||
* Returns the same array when nothing changed.
|
||||
*/
|
||||
export function upgradeVideos(current: CardPost[], fresh: CardPost[]): CardPost[] {
|
||||
const byKey = new Map(fresh.map((p) => [p.key, p]));
|
||||
let changed = false;
|
||||
const next = current.map((p) => {
|
||||
const f = byKey.get(p.key);
|
||||
if (f && !hasHls(p) && hasHls(f)) {
|
||||
changed = true;
|
||||
return { ...p, media: f.media };
|
||||
}
|
||||
return p;
|
||||
});
|
||||
return changed ? next : current;
|
||||
}
|
||||
|
||||
export function relativeTime(publishedAt: string | null, now: number = Date.now()): string {
|
||||
const t = publishedAt ? Date.parse(publishedAt) : NaN;
|
||||
if (!Number.isFinite(t)) return "";
|
||||
|
||||
+46
-2
@@ -9,8 +9,8 @@ import type { SessionData } from "./session-store";
|
||||
// 3. the SERVER PUTs the bytes to that URL (the browser never gets the token)
|
||||
// 4. confirm the upload (image confirmation blocks until processing finishes)
|
||||
// 5. publish with the same {content} publish call as a text post
|
||||
// The pipeline is media-type agnostic so the video task can reuse it; only the
|
||||
// allowed-type gate and the public entry point here are image-specific.
|
||||
// The pipeline is media-type agnostic; the allowed-type gates and entry points
|
||||
// (createImagePost, createVideoPost) are per kind.
|
||||
// Neither the feed token nor the file bytes are ever logged.
|
||||
|
||||
export type MediaKind = "image" | "video";
|
||||
@@ -25,6 +25,12 @@ export const ALLOWED_IMAGE_TYPES: readonly string[] = [
|
||||
"image/heic",
|
||||
];
|
||||
|
||||
/** Video content types the feed accepts. */
|
||||
export const ALLOWED_VIDEO_TYPES: readonly string[] = ["video/mp4", "video/quicktime", "video/webm"];
|
||||
|
||||
/** Upper bound on an uploaded video, enforced before any feed call. */
|
||||
export const MAX_VIDEO_BYTES = 200 * 1024 * 1024;
|
||||
|
||||
/** Upper bound on an uploaded image, enforced before any feed call. */
|
||||
export const MAX_IMAGE_BYTES = 15 * 1024 * 1024;
|
||||
|
||||
@@ -112,6 +118,44 @@ export function isAllowedImageType(type: string): boolean {
|
||||
return ALLOWED_IMAGE_TYPES.includes(type.trim().toLowerCase());
|
||||
}
|
||||
|
||||
/** True when the type is an accepted video content type (case-insensitive). */
|
||||
export function isAllowedVideoType(type: string): boolean {
|
||||
return ALLOWED_VIDEO_TYPES.includes(type.trim().toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a public video post: same pipeline as an image with type "video".
|
||||
* Video confirmation may return while transcoding continues; the post is
|
||||
* published anyway and the card shows the thumbnail until hlsUrl appears.
|
||||
*/
|
||||
export async function createVideoPost(
|
||||
sessionId: string | undefined,
|
||||
content: unknown,
|
||||
file: MediaUpload["file"] | null,
|
||||
options: RefreshOptions = {},
|
||||
): Promise<CreateMediaPostResult> {
|
||||
if (!file || typeof file.size !== "number" || file.size <= 0 || file.size > MAX_VIDEO_BYTES) {
|
||||
return { ok: false, status: 400, error: "bad_file" };
|
||||
}
|
||||
if (typeof file.type !== "string" || !isAllowedVideoType(file.type)) {
|
||||
return { ok: false, status: 400, error: "bad_file" };
|
||||
}
|
||||
return runMediaPipeline(sessionId, content, { file, mediaType: "video" }, options);
|
||||
}
|
||||
|
||||
/** Route entry point: picks image or video from the file type; anything else is a 400. */
|
||||
export async function createMediaPost(
|
||||
sessionId: string | undefined,
|
||||
content: unknown,
|
||||
file: MediaUpload["file"] | null,
|
||||
options: RefreshOptions = {},
|
||||
): Promise<CreateMediaPostResult> {
|
||||
if (file && typeof file.type === "string" && isAllowedVideoType(file.type)) {
|
||||
return createVideoPost(sessionId, content, file, options);
|
||||
}
|
||||
return createImagePost(sessionId, content, file, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a public image post from a caption and one file: draft -> presigned URL
|
||||
* -> server-side PUT -> confirm -> publish. Returns the post id so the caller can
|
||||
|
||||
Reference in New Issue
Block a user