Merge Feed browser: Image and video posts into develop
Server-side upload pipeline (draft -> presigned -> PUT -> confirm -> publish) for image and video posts. Tasks mgply09ox, t3xbu10dr.
This commit is contained in:
@@ -1,17 +1,43 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { SESSION_COOKIE } from "@/lib/cookie";
|
||||
import { createTextPost } from "@/lib/post-create";
|
||||
import { createMediaPost } from "@/lib/post-media";
|
||||
|
||||
// POST /api/posts { content }
|
||||
// Creates a public text draft on the feed, then publishes it. Returns { id }.
|
||||
// The create call can report status "draft" for a post already on the home
|
||||
// feed, so the browser reloads the first page and confirms the id there.
|
||||
// POST /api/posts
|
||||
// - JSON { content } -> public text post
|
||||
// - 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
|
||||
// report status "draft" for a post already on the home feed, so the browser
|
||||
// reloads the first page and confirms the id there.
|
||||
// 401 { error: "sign_in" } without a session.
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const sessionId = req.cookies.get(SESSION_COOKIE)?.value;
|
||||
const contentType = req.headers.get("content-type") ?? "";
|
||||
|
||||
if (contentType.includes("multipart/form-data")) {
|
||||
let content = "";
|
||||
let file: File | null = null;
|
||||
try {
|
||||
const form = await req.formData();
|
||||
const c = form.get("content");
|
||||
content = typeof c === "string" ? c : "";
|
||||
const f = form.get("file");
|
||||
file = f instanceof File ? f : null;
|
||||
} catch {
|
||||
return NextResponse.json({ error: "bad_file" }, { status: 400 });
|
||||
}
|
||||
const result = await createMediaPost(sessionId, content, file);
|
||||
if (!result.ok) {
|
||||
return NextResponse.json({ error: result.error }, { status: result.status });
|
||||
}
|
||||
return NextResponse.json({ id: result.id });
|
||||
}
|
||||
|
||||
let content: unknown = null;
|
||||
try {
|
||||
content = ((await req.json()) as { content?: unknown }).content;
|
||||
|
||||
@@ -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); }
|
||||
@@ -47,6 +48,15 @@ button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.composer textarea { font: inherit; width: 100%; padding: 12px; border: 1px solid #999; border-radius: 0; resize: vertical; background: #fff; color: var(--ink); }
|
||||
.composer textarea:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
|
||||
.composer .composer-post { align-self: flex-end; margin: 0; padding: 10px 24px; border-radius: 0; }
|
||||
.composer-media { display: flex; flex-direction: column; gap: 8px; }
|
||||
.composer-image { display: inline-flex; align-items: center; gap: 8px; align-self: flex-start; cursor: pointer; }
|
||||
.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; }
|
||||
|
||||
.comments { display: flex; flex-direction: column; gap: 10px; padding-top: 10px; border-top: 1px solid #eee; }
|
||||
.comment-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
|
||||
@@ -1,19 +1,55 @@
|
||||
import type { FormEvent } from "react";
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, type ChangeEvent, type FormEvent } from "react";
|
||||
|
||||
export interface ComposerProps {
|
||||
value: string;
|
||||
busy: boolean;
|
||||
error: boolean;
|
||||
/** The selected image or video file, when the pickers are wired. */
|
||||
file?: File | null;
|
||||
onChange: (value: string) => void;
|
||||
/** When present, the composer shows image and video pickers and reports the choice. */
|
||||
onFile?: (file: File | null) => void;
|
||||
onSubmit: () => void;
|
||||
}
|
||||
|
||||
export function Composer({ value, busy, error, onChange, onSubmit }: ComposerProps) {
|
||||
// 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 a file.
|
||||
const canSubmit = (!empty || !!file) && !busy;
|
||||
const [preview, setPreview] = useState<string | null>(null);
|
||||
|
||||
// Build a preview URL client-side only, and revoke it when the file changes.
|
||||
useEffect(() => {
|
||||
if (!file) {
|
||||
setPreview(null);
|
||||
return;
|
||||
}
|
||||
const url = URL.createObjectURL(file);
|
||||
setPreview(url);
|
||||
return () => URL.revokeObjectURL(url);
|
||||
}, [file]);
|
||||
|
||||
function submit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!empty && !busy) onSubmit();
|
||||
if (canSubmit) onSubmit();
|
||||
}
|
||||
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);
|
||||
}
|
||||
const isVideo = !!file && file.type.startsWith("video/");
|
||||
|
||||
return (
|
||||
<form className="composer" onSubmit={submit}>
|
||||
<label htmlFor="composer-text" className="composer-label">New post</label>
|
||||
@@ -25,10 +61,41 @@ export function Composer({ value, busy, error, onChange, onSubmit }: ComposerPro
|
||||
disabled={busy}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
{onFile ? (
|
||||
<div className="composer-media">
|
||||
<label className="composer-image">
|
||||
<span>Add image</span>
|
||||
<input
|
||||
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 && 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}
|
||||
<span className="composer-filename">{file.name}</span>
|
||||
<button type="button" className="composer-remove" onClick={remove} disabled={busy}>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{error ? (
|
||||
<p className="error" role="alert">Publishing the post failed. Your text is still here.</p>
|
||||
) : null}
|
||||
<button type="submit" className="composer-post" disabled={empty || busy}>
|
||||
<button type="submit" className="composer-post" disabled={!canSubmit}>
|
||||
{busy ? "Posting" : "Post"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
+17
-6
@@ -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";
|
||||
@@ -22,6 +22,7 @@ export function Feed({ onSignedOut, feedUserId }: { onSignedOut: () => void; fee
|
||||
const [deleteBusy, setDeleteBusy] = useState<ReadonlySet<string>>(new Set());
|
||||
const [deleteErrors, setDeleteErrors] = useState<ReadonlySet<string>>(new Set());
|
||||
const [draft, setDraft] = useState("");
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [posting, setPosting] = useState(false);
|
||||
const [postFailed, setPostFailed] = useState(false);
|
||||
// Id of a post already created but not yet seen on the first page. A retry
|
||||
@@ -105,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);
|
||||
@@ -187,22 +190,24 @@ export function Feed({ onSignedOut, feedUserId }: { onSignedOut: () => void; fee
|
||||
|
||||
const publish = useCallback(async () => {
|
||||
const text = draft.trim();
|
||||
if (!text || posting) return;
|
||||
// A post needs either text or a file.
|
||||
if ((!text && !file) || posting) return;
|
||||
setPosting(true);
|
||||
setPostFailed(false);
|
||||
try {
|
||||
const page = await publishAndConfirm(text, unconfirmed.current);
|
||||
const page = await publishAndConfirm(text, file, unconfirmed.current);
|
||||
setPosts(mergePosts(toCardPosts(page.items)));
|
||||
setNextCursor(page.nextCursor);
|
||||
setPending([]);
|
||||
setDraft("");
|
||||
setFile(null);
|
||||
} catch (e) {
|
||||
if (e instanceof PostError && e.signedOut) onSignedOut();
|
||||
setPostFailed(true);
|
||||
} finally {
|
||||
setPosting(false);
|
||||
}
|
||||
}, [draft, posting, onSignedOut]);
|
||||
}, [draft, file, posting, onSignedOut]);
|
||||
|
||||
function changeDraft(v: string) {
|
||||
// New text is a new post; forget a stale unconfirmed id.
|
||||
@@ -210,6 +215,12 @@ export function Feed({ onSignedOut, feedUserId }: { onSignedOut: () => void; fee
|
||||
setDraft(v);
|
||||
}
|
||||
|
||||
function changeFile(f: File | null) {
|
||||
// A different attachment is a new post; forget a stale unconfirmed id.
|
||||
unconfirmed.current = { id: null };
|
||||
setFile(f);
|
||||
}
|
||||
|
||||
function showNew() {
|
||||
setPosts((cur) => mergePosts(cur, pending));
|
||||
setPending([]);
|
||||
@@ -233,7 +244,7 @@ export function Feed({ onSignedOut, feedUserId }: { onSignedOut: () => void; fee
|
||||
deleteBusy={deleteBusy}
|
||||
deleteErrors={deleteErrors}
|
||||
onSignedOut={onSignedOut}
|
||||
composer={{ value: draft, busy: posting, error: postFailed, onChange: changeDraft, onSubmit: () => void publish() }}
|
||||
composer={{ value: draft, busy: posting, error: postFailed, file, onChange: changeDraft, onFile: changeFile, onSubmit: () => void publish() }}
|
||||
sentinelRef={sentinel}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -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 "";
|
||||
|
||||
+30
-13
@@ -9,15 +9,30 @@ export class PostError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendPost(content: string, fetchImpl: typeof fetch = fetch): Promise<string> {
|
||||
export async function sendPost(
|
||||
content: string,
|
||||
file: File | null = null,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<string> {
|
||||
let res: Response;
|
||||
// A file is sent as multipart form-data so the server can upload the bytes;
|
||||
// text-only posts stay JSON. The content type is left to FormData for the
|
||||
// multipart case so the boundary is set correctly.
|
||||
const init: RequestInit = file
|
||||
? (() => {
|
||||
const form = new FormData();
|
||||
form.append("content", content);
|
||||
form.append("file", file, file.name);
|
||||
return { method: "POST", credentials: "same-origin", body: form };
|
||||
})()
|
||||
: {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ content }),
|
||||
};
|
||||
try {
|
||||
res = await fetchImpl("/api/posts", {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ content }),
|
||||
});
|
||||
res = await fetchImpl("/api/posts", init);
|
||||
} catch {
|
||||
throw new PostError(false);
|
||||
}
|
||||
@@ -56,22 +71,24 @@ export async function confirmOnFirstPage(
|
||||
}
|
||||
|
||||
export interface PublishDeps {
|
||||
send?: (content: string) => Promise<string>;
|
||||
send?: (content: string, file: File | null) => Promise<string>;
|
||||
fetchPage?: (cursor: string | null) => Promise<FeedPage>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish text and confirm it on the reloaded first page. Returns that page
|
||||
* only when the post id is on it. `unconfirmed` holds an id that was created
|
||||
* earlier but not yet seen, so a retry re-checks the feed and does not create
|
||||
* a duplicate. Throws PostError otherwise; the caller keeps the composer text.
|
||||
* Publish a post (text, or text plus one image file) and confirm it on the
|
||||
* reloaded first page. Returns that page only when the post id is on it.
|
||||
* `unconfirmed` holds an id that was created earlier but not yet seen, so a
|
||||
* retry re-checks the feed and does not create a duplicate. Throws PostError
|
||||
* otherwise; the caller keeps the composer text and the selected file.
|
||||
*/
|
||||
export async function publishAndConfirm(
|
||||
content: string,
|
||||
file: File | null,
|
||||
unconfirmed: { id: string | null },
|
||||
deps: PublishDeps = {},
|
||||
): Promise<FeedPage> {
|
||||
const id = unconfirmed.id ?? (await (deps.send ?? sendPost)(content));
|
||||
const id = unconfirmed.id ?? (await (deps.send ?? sendPost)(content, file));
|
||||
unconfirmed.id = id;
|
||||
const page = await confirmOnFirstPage(id, deps.fetchPage);
|
||||
if (!page) throw new PostError(false);
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
import { FEED_BASE_URL } from "./env";
|
||||
import { MAX_POST_LENGTH } from "./post-create";
|
||||
import { ensureFreshSession, refreshSession, type RefreshOptions } from "./session-refresh";
|
||||
import type { SessionData } from "./session-store";
|
||||
|
||||
// Media-post creation proxy. Unlike a text post this needs five feed steps:
|
||||
// 1. create an image/video draft
|
||||
// 2. ask the feed for a presigned upload URL
|
||||
// 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; 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";
|
||||
|
||||
/** Image content types the feed accepts (spec: "Create a post with an image or video"). */
|
||||
export const ALLOWED_IMAGE_TYPES: readonly string[] = [
|
||||
"image/jpeg",
|
||||
"image/jpg",
|
||||
"image/png",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
"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;
|
||||
|
||||
export type CreateMediaPostResult =
|
||||
| { ok: true; id: string; status: string | null }
|
||||
| {
|
||||
ok: false;
|
||||
status: 400 | 401 | 502;
|
||||
error: "sign_in" | "too_long" | "bad_file" | "post_failed";
|
||||
};
|
||||
|
||||
export interface MediaUpload {
|
||||
/** The file to upload. */
|
||||
file: { name: string; type: string; size: number; arrayBuffer: () => Promise<ArrayBuffer> };
|
||||
/** Draft type and confirm mediaType. */
|
||||
mediaType: MediaKind;
|
||||
}
|
||||
|
||||
type Fetch = typeof fetch;
|
||||
|
||||
function rec(v: unknown): Record<string, unknown> {
|
||||
return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
|
||||
}
|
||||
|
||||
function str(v: unknown): string | undefined {
|
||||
return typeof v === "string" && v.length > 0 ? v : undefined;
|
||||
}
|
||||
|
||||
function readCreated(body: unknown): { id: string; status: string | null } | null {
|
||||
const root = rec(body);
|
||||
const data = rec(root.data);
|
||||
const post = rec(data.post);
|
||||
for (const v of [data.id, post.id, root.id]) {
|
||||
if ((typeof v === "string" && v) || typeof v === "number") {
|
||||
const status = [data.status, post.status, root.status].find((s) => typeof s === "string");
|
||||
return { id: String(v), status: (status as string | undefined) ?? null };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Tolerant reader for the presigned-urls response (field names are not pinned by the spec). */
|
||||
function readPresigned(
|
||||
body: unknown,
|
||||
): { uploadUrl: string; attachmentId: string; s3Key: string } | null {
|
||||
const root = rec(body);
|
||||
const data = root.data;
|
||||
// The entry may be the first element of an array, the first element of a
|
||||
// named list, or the data object itself.
|
||||
const candidates: unknown[] = [];
|
||||
if (Array.isArray(data)) candidates.push(...data);
|
||||
else if (Array.isArray(body)) candidates.push(...(body as unknown[]));
|
||||
else {
|
||||
const d = rec(data);
|
||||
for (const key of ["files", "urls", "attachments", "presignedUrls"]) {
|
||||
if (Array.isArray(d[key])) candidates.push(...(d[key] as unknown[]));
|
||||
}
|
||||
candidates.push(d);
|
||||
}
|
||||
for (const c of candidates) {
|
||||
const e = rec(c);
|
||||
const uploadUrl =
|
||||
str(e.uploadUrl) ?? str(e.url) ?? str(e.presignedUrl) ?? str(e.signedUrl) ?? str(e.putUrl);
|
||||
const attachmentId = str(e.attachmentId) ?? str(e.id);
|
||||
const s3Key = str(e.s3Key) ?? str(e.key) ?? str(e.objectKey);
|
||||
if (uploadUrl && attachmentId && s3Key) return { uploadUrl, attachmentId, s3Key };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function sendJson(token: string, path: string, payload: unknown, doFetch: Fetch) {
|
||||
return doFetch(`${FEED_BASE_URL}${path}`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
/** True when the type is an accepted image content type (case-insensitive). */
|
||||
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
|
||||
* confirm it on the reloaded first page. The video task reuses `runMediaPipeline`
|
||||
* with `mediaType: "video"` and its own type gate.
|
||||
*/
|
||||
export async function createImagePost(
|
||||
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_IMAGE_BYTES) {
|
||||
return { ok: false, status: 400, error: "bad_file" };
|
||||
}
|
||||
if (typeof file.type !== "string" || !isAllowedImageType(file.type)) {
|
||||
return { ok: false, status: 400, error: "bad_file" };
|
||||
}
|
||||
return runMediaPipeline(sessionId, content, { file, mediaType: "image" }, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Media-type agnostic upload-and-publish pipeline. Callers validate the file
|
||||
* first (type, size) for their media kind. A caption may be empty for a media
|
||||
* post; only an over-length caption is rejected.
|
||||
*/
|
||||
export async function runMediaPipeline(
|
||||
sessionId: string | undefined,
|
||||
content: unknown,
|
||||
upload: MediaUpload,
|
||||
options: RefreshOptions = {},
|
||||
): Promise<CreateMediaPostResult> {
|
||||
const signIn = { ok: false, status: 401, error: "sign_in" } as const;
|
||||
const failed = { ok: false, status: 502, error: "post_failed" } as const;
|
||||
const doFetch = options.fetchImpl ?? fetch;
|
||||
const { file, mediaType } = upload;
|
||||
|
||||
let session: SessionData | null = await ensureFreshSession(sessionId, options);
|
||||
if (!session || !sessionId) return signIn;
|
||||
|
||||
const caption = typeof content === "string" ? content : "";
|
||||
if (caption.length > MAX_POST_LENGTH) {
|
||||
return { ok: false, status: 400, error: "too_long" };
|
||||
}
|
||||
|
||||
// One feed call with a single refresh-and-retry on a 401 token rejection.
|
||||
const call = async (path: string, payload: unknown): Promise<Response | "sign_in"> => {
|
||||
let res = await sendJson(session!.feedAccessToken, path, payload, doFetch);
|
||||
if (res.status === 401) {
|
||||
session = await refreshSession(sessionId, options);
|
||||
if (!session) return "sign_in";
|
||||
res = await sendJson(session.feedAccessToken, path, payload, doFetch);
|
||||
if (res.status === 401) return "sign_in";
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
try {
|
||||
// 1. Draft.
|
||||
const created = await call("/api/v1/posts", {
|
||||
content: caption,
|
||||
type: mediaType,
|
||||
status: "draft",
|
||||
visibility: "public",
|
||||
});
|
||||
if (created === "sign_in") return signIn;
|
||||
if (created.status !== 200 && created.status !== 201) return failed;
|
||||
const info = readCreated(await created.json().catch(() => null));
|
||||
if (!info) return failed;
|
||||
|
||||
// 2. Presigned URL for the one file.
|
||||
const presignedRes = await call("/api/v1/attachments/presigned-urls", {
|
||||
postId: info.id,
|
||||
files: [{ name: file.name, type: file.type, size: file.size }],
|
||||
});
|
||||
if (presignedRes === "sign_in") return signIn;
|
||||
if (presignedRes.status < 200 || presignedRes.status > 299) return failed;
|
||||
const slot = readPresigned(await presignedRes.json().catch(() => null));
|
||||
if (!slot) return failed;
|
||||
|
||||
// 3. The server PUTs the bytes. No Authorization header: the presigned URL
|
||||
// is pre-authorized, and the feed token must never reach S3 or the browser.
|
||||
const bytes = await file.arrayBuffer();
|
||||
const put = await doFetch(slot.uploadUrl, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": file.type },
|
||||
body: bytes,
|
||||
});
|
||||
if (!put.ok) return failed;
|
||||
|
||||
// 4. Confirm (image confirmation blocks until processing finishes).
|
||||
const confirmed = await call("/api/v1/attachments/confirm-uploads", {
|
||||
postId: info.id,
|
||||
uploads: [
|
||||
{
|
||||
attachmentId: slot.attachmentId,
|
||||
s3Key: slot.s3Key,
|
||||
mediaType,
|
||||
filename: file.name,
|
||||
},
|
||||
],
|
||||
});
|
||||
if (confirmed === "sign_in") return signIn;
|
||||
if (confirmed.status < 200 || confirmed.status > 299) return failed;
|
||||
|
||||
// 5. Publish, same call as a text post.
|
||||
const published = await call(`/api/v1/posts/${encodeURIComponent(info.id)}/publish`, {
|
||||
content: caption,
|
||||
});
|
||||
if (published === "sign_in") return signIn;
|
||||
if (published.status < 200 || published.status > 299) return failed;
|
||||
|
||||
return { ok: true, id: info.id, status: info.status };
|
||||
} catch {
|
||||
return failed;
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import { exchangeFeedToken, refreshProfileTokens, revokeToken } from "./minnect"
|
||||
/** Refresh when a token expires within this window (spec: two minutes). */
|
||||
export const REFRESH_WINDOW_MS = 2 * 60 * 1000;
|
||||
|
||||
interface RefreshOptions {
|
||||
export interface RefreshOptions {
|
||||
/** Injectable fetch, for testing. Defaults to the global fetch. */
|
||||
fetchImpl?: typeof fetch;
|
||||
/** Injectable clock for the expiry decision, for testing. Defaults to Date.now(). */
|
||||
|
||||
+33
-1
@@ -3,7 +3,7 @@ import { createElement } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { FeedView, type FeedViewProps } from "@/components/FeedView";
|
||||
import { fetchFeedPage, FeedLoadError } from "@/lib/feed-client";
|
||||
import { mergePosts, relativeTime, toCardPosts } from "@/lib/feed-model";
|
||||
import { mergePosts, relativeTime, toCardPosts, upgradeVideos } from "@/lib/feed-model";
|
||||
|
||||
const NOW = Date.parse("2026-10-19T12:00:00Z");
|
||||
const post = (id: string, publishedAt: string, extra: Record<string, unknown> = {}) => ({
|
||||
@@ -137,3 +137,35 @@ describe("fetchFeedPage", () => {
|
||||
await expect(fetchFeedPage(null, mk(500))).rejects.toMatchObject({ signedOut: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("video transcoding", () => {
|
||||
const vid = (hls: unknown) =>
|
||||
toCardPosts([post("7", "2026-10-19T10:00:00Z", { mediaItems: [{ mediaType: "video", thumbnailUrl: "https://i/t.jpg", hlsUrl: hls }] })]);
|
||||
|
||||
it("keeps a just-published video as a thumbnail with no hlsUrl", () => {
|
||||
const [p] = vid(null);
|
||||
expect(p.media).toEqual([{ kind: "video", src: "https://i/t.jpg", hlsUrl: null }]);
|
||||
});
|
||||
|
||||
it("keeps a video with neither thumbnail nor hlsUrl as a pending card", () => {
|
||||
const [p] = toCardPosts([post("8", "2026-10-19T10:00:00Z", { mediaItems: [{ mediaType: "video" }] })]);
|
||||
expect(p.media).toHaveLength(1);
|
||||
expect(p.media[0].src).toBeNull();
|
||||
});
|
||||
|
||||
it("upgrades the shown thumbnail to the player when hlsUrl appears", () => {
|
||||
const shown = vid(null);
|
||||
const next = upgradeVideos(shown, vid("https://stream.mux.com/abc"));
|
||||
expect(next[0].media[0].hlsUrl).toContain("stream.mux.com");
|
||||
expect(upgradeVideos(next, vid("https://stream.mux.com/abc"))).toBe(next);
|
||||
expect(upgradeVideos(shown, vid(null))).toBe(shown);
|
||||
});
|
||||
|
||||
it("renders the thumbnail while transcoding and the player once hlsUrl is present", () => {
|
||||
const html = render({ posts: vid(null) });
|
||||
expect(html).toContain("https://i/t.jpg");
|
||||
expect(html).not.toContain("<video");
|
||||
const live = render({ posts: vid("https://stream.mux.com/abc") });
|
||||
expect(live).toContain("<video");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { POST } from "@/app/api/posts/route";
|
||||
import { createImagePost, createVideoPost } from "@/lib/post-media";
|
||||
import { createSession } from "@/lib/session-store";
|
||||
|
||||
// Server-side image-post pipeline, with a fully mocked feed. The browser sends
|
||||
// multipart content + one file to POST /api/posts; the server runs
|
||||
// draft -> presigned -> PUT -> confirm -> publish and returns only { id }.
|
||||
|
||||
function session() {
|
||||
return createSession({
|
||||
profileAccessToken: "p", profileAccessTokenExpiresAt: null, profileRefreshToken: "r",
|
||||
feedAccessToken: "T", feedAccessTokenExpiresAt: null,
|
||||
person: { userId: "u", name: "A", email: "a@b.co", pictureUrl: null }, createdAt: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
function jsonRes(body: unknown, status: number) {
|
||||
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
||||
}
|
||||
|
||||
function multipart(content: string, file: File | null, sid?: string) {
|
||||
const form = new FormData();
|
||||
form.append("content", content);
|
||||
if (file) form.append("file", file, file.name);
|
||||
return new NextRequest("http://localhost/api/posts", {
|
||||
method: "POST",
|
||||
headers: sid ? { cookie: `mfb_session=${sid}` } : {},
|
||||
body: form,
|
||||
});
|
||||
}
|
||||
|
||||
async function withFetch<T>(fn: typeof fetch, run: () => Promise<T>) {
|
||||
const orig = globalThis.fetch;
|
||||
globalThis.fetch = fn;
|
||||
try {
|
||||
return await run();
|
||||
} finally {
|
||||
globalThis.fetch = orig;
|
||||
}
|
||||
}
|
||||
|
||||
const imageFile = (name = "photo.jpg", type = "image/jpeg") =>
|
||||
new File([new Uint8Array([1, 2, 3])], name, { type });
|
||||
|
||||
describe("POST /api/posts (image)", () => {
|
||||
it("runs draft -> presigned -> PUT -> confirm -> publish and returns only the id", async () => {
|
||||
const sid = session();
|
||||
const calls: { url: string; method: string; auth: string | null }[] = [];
|
||||
const bodies: Record<string, unknown> = {};
|
||||
const fn = vi.fn(async (url: string | URL, init?: RequestInit) => {
|
||||
const u = String(url);
|
||||
calls.push({ url: u, method: String(init?.method ?? "GET"), auth: new Headers(init?.headers).get("authorization") });
|
||||
if (u.includes("/api/v1/") && typeof init?.body === "string") {
|
||||
bodies[new URL(u).pathname] = JSON.parse(init.body);
|
||||
}
|
||||
if (u.endsWith("/api/v1/posts")) return jsonRes({ data: { id: "p9", status: "draft" } }, 201);
|
||||
if (u.endsWith("/attachments/presigned-urls"))
|
||||
return jsonRes({ data: [{ attachmentId: "a1", s3Key: "k/1.jpg", url: "https://s3.example/put?sig=1" }] }, 200);
|
||||
if (u === "https://s3.example/put?sig=1") return new Response(null, { status: 200 });
|
||||
if (u.endsWith("/attachments/confirm-uploads")) return jsonRes({ data: { success: true } }, 200);
|
||||
if (u.includes("/publish")) return jsonRes({ data: { success: true } }, 200);
|
||||
return new Response("{}", { status: 404 });
|
||||
});
|
||||
|
||||
const res = await withFetch(fn as unknown as typeof fetch, () =>
|
||||
POST(multipart("look at this", imageFile(), sid)),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ id: "p9" });
|
||||
|
||||
const feedPaths = calls.filter((c) => c.url.includes("/api/v1/")).map((c) => new URL(c.url).pathname);
|
||||
expect(feedPaths).toEqual([
|
||||
"/api/v1/posts",
|
||||
"/api/v1/attachments/presigned-urls",
|
||||
"/api/v1/attachments/confirm-uploads",
|
||||
"/api/v1/posts/p9/publish",
|
||||
]);
|
||||
expect(bodies["/api/v1/posts"]).toEqual({
|
||||
content: "look at this",
|
||||
type: "image",
|
||||
status: "draft",
|
||||
visibility: "public",
|
||||
});
|
||||
expect(bodies["/api/v1/attachments/presigned-urls"]).toEqual({
|
||||
postId: "p9",
|
||||
files: [{ name: "photo.jpg", type: "image/jpeg", size: 3 }],
|
||||
});
|
||||
expect(bodies["/api/v1/attachments/confirm-uploads"]).toEqual({
|
||||
postId: "p9",
|
||||
uploads: [{ attachmentId: "a1", s3Key: "k/1.jpg", mediaType: "image", filename: "photo.jpg" }],
|
||||
});
|
||||
expect(bodies["/api/v1/posts/p9/publish"]).toEqual({ content: "look at this" });
|
||||
|
||||
// The server PUTs the bytes with no token; every feed call carries Bearer T.
|
||||
const put = calls.find((c) => c.method === "PUT");
|
||||
expect(put?.url).toBe("https://s3.example/put?sig=1");
|
||||
expect(put?.auth).toBeNull();
|
||||
expect(calls.filter((c) => c.url.includes("/api/v1/")).every((c) => c.auth === "Bearer T")).toBe(true);
|
||||
});
|
||||
|
||||
it("never returns the feed token to the browser", async () => {
|
||||
const sid = session();
|
||||
const fn = vi.fn(async (url: string | URL) => {
|
||||
const u = String(url);
|
||||
if (u.endsWith("/api/v1/posts")) return jsonRes({ data: { id: "p9" } }, 201);
|
||||
if (u.endsWith("/attachments/presigned-urls"))
|
||||
return jsonRes({ data: [{ attachmentId: "a1", s3Key: "k", url: "https://s3.example/put" }] }, 200);
|
||||
if (u === "https://s3.example/put") return new Response(null, { status: 200 });
|
||||
return jsonRes({ data: { success: true } }, 200);
|
||||
});
|
||||
const res = await withFetch(fn as unknown as typeof fetch, () => POST(multipart("hi", imageFile(), sid)));
|
||||
const text = await res.text();
|
||||
expect(text).toBe(JSON.stringify({ id: "p9" }));
|
||||
expect(text).not.toContain("T");
|
||||
});
|
||||
|
||||
it("rejects a disallowed type with 400 bad_file and makes no feed call", async () => {
|
||||
const sid = session();
|
||||
const fn = vi.fn();
|
||||
const res = await withFetch(fn as unknown as typeof fetch, () =>
|
||||
POST(multipart("x", imageFile("doc.pdf", "application/pdf"), sid)),
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.json()).toEqual({ error: "bad_file" });
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a missing file with 400 bad_file", async () => {
|
||||
const sid = session();
|
||||
const fn = vi.fn();
|
||||
const res = await withFetch(fn as unknown as typeof fetch, () => POST(multipart("x", null, sid)));
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.json()).toEqual({ error: "bad_file" });
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("401 sign_in for a multipart post without a session", async () => {
|
||||
const fn = vi.fn();
|
||||
const res = await withFetch(fn as unknown as typeof fetch, () => POST(multipart("x", imageFile())));
|
||||
expect(res.status).toBe(401);
|
||||
expect(await res.json()).toEqual({ error: "sign_in" });
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("502 post_failed when the server upload PUT fails after the draft was created", async () => {
|
||||
const sid = session();
|
||||
const fn = vi.fn(async (url: string | URL) => {
|
||||
const u = String(url);
|
||||
if (u.endsWith("/api/v1/posts")) return jsonRes({ data: { id: "p9" } }, 201);
|
||||
if (u.endsWith("/attachments/presigned-urls"))
|
||||
return jsonRes({ data: [{ attachmentId: "a1", s3Key: "k", url: "https://s3.example/put" }] }, 200);
|
||||
if (u === "https://s3.example/put") return new Response("denied", { status: 403 });
|
||||
return jsonRes({ data: { success: true } }, 200);
|
||||
});
|
||||
const res = await withFetch(fn as unknown as typeof fetch, () => POST(multipart("x", imageFile(), sid)));
|
||||
expect(res.status).toBe(502);
|
||||
expect(await res.json()).toEqual({ error: "post_failed" });
|
||||
});
|
||||
|
||||
it("accepts every allowed image type and rejects others (unit)", async () => {
|
||||
const sid = session();
|
||||
const ok = vi.fn(async (url: string | URL) => {
|
||||
const u = String(url);
|
||||
if (u.endsWith("/api/v1/posts")) return jsonRes({ data: { id: "p9" } }, 201);
|
||||
if (u.endsWith("/attachments/presigned-urls"))
|
||||
return jsonRes({ data: [{ attachmentId: "a1", s3Key: "k", url: "https://s3.example/put" }] }, 200);
|
||||
if (u === "https://s3.example/put") return new Response(null, { status: 200 });
|
||||
return jsonRes({ data: { success: true } }, 200);
|
||||
}) as unknown as typeof fetch;
|
||||
for (const type of ["image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp", "image/heic"]) {
|
||||
const r = await createImagePost(sid, "c", imageFile(`f.${type.split("/")[1]}`, type), { fetchImpl: ok });
|
||||
expect(r.ok).toBe(true);
|
||||
}
|
||||
const bad = await createImagePost(sid, "c", imageFile("a.svg", "image/svg+xml"), {
|
||||
fetchImpl: (() => {
|
||||
throw new Error("should not be called");
|
||||
}) as unknown as typeof fetch,
|
||||
});
|
||||
expect(bad).toEqual({ ok: false, status: 400, error: "bad_file" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/posts (video)", () => {
|
||||
const videoFile = (name = "clip.mp4", type = "video/mp4") =>
|
||||
new File([new Uint8Array([1, 2, 3])], name, { type });
|
||||
|
||||
function videoFeed(bodies: Record<string, unknown>, calls: string[]) {
|
||||
return vi.fn(async (url: string | URL, init?: RequestInit) => {
|
||||
const u = String(url);
|
||||
calls.push(u);
|
||||
if (u.includes("/api/v1/") && typeof init?.body === "string") bodies[new URL(u).pathname] = JSON.parse(init.body);
|
||||
if (u.endsWith("/api/v1/posts")) return jsonRes({ data: { id: "v1", status: "draft" } }, 201);
|
||||
if (u.endsWith("/attachments/presigned-urls"))
|
||||
return jsonRes({ data: [{ attachmentId: "a1", s3Key: "k/1.mp4", url: "https://s3.example/put" }] }, 200);
|
||||
if (u === "https://s3.example/put") return new Response(null, { status: 200 });
|
||||
// Confirmation returns while transcoding continues: no hlsUrl.
|
||||
if (u.endsWith("/confirm-uploads")) return jsonRes({ data: { status: "processing" } }, 200);
|
||||
return jsonRes({ data: { success: true } }, 200);
|
||||
});
|
||||
}
|
||||
|
||||
it("uses draft type video, confirms mediaType video, and publishes without hlsUrl", async () => {
|
||||
const sid = session();
|
||||
const bodies: Record<string, unknown> = {};
|
||||
const calls: string[] = [];
|
||||
const fn = videoFeed(bodies, calls);
|
||||
const res = await withFetch(fn as unknown as typeof fetch, () => POST(multipart("hi", videoFile("c.mov", "video/quicktime"), sid)));
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ id: "v1" });
|
||||
expect((bodies["/api/v1/posts"] as { type: string }).type).toBe("video");
|
||||
const uploads = (bodies["/api/v1/attachments/confirm-uploads"] as { uploads: { mediaType: string }[] }).uploads;
|
||||
expect(uploads[0].mediaType).toBe("video");
|
||||
expect(calls.some((u) => u.endsWith("/api/v1/posts/v1/publish"))).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts mp4, quicktime and webm; rejects other video types before any feed call", async () => {
|
||||
const sid = session();
|
||||
const ok = videoFeed({}, []) as unknown as typeof fetch;
|
||||
for (const t of ["video/mp4", "video/quicktime", "video/webm"]) {
|
||||
expect((await createVideoPost(sid, "c", videoFile("f", t), { fetchImpl: ok })).ok).toBe(true);
|
||||
}
|
||||
const fn = vi.fn();
|
||||
const res = await withFetch(fn as unknown as typeof fetch, () =>
|
||||
POST(multipart("x", videoFile("a.avi", "video/x-msvideo"), sid)),
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.json()).toEqual({ error: "bad_file" });
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+21
-5
@@ -79,7 +79,7 @@ describe("publishAndConfirm", () => {
|
||||
it("returns the reloaded page only when the id is on the first page", async () => {
|
||||
const state = { id: null as string | null };
|
||||
const page = { items: [item("p9"), item("p1")], nextCursor: null };
|
||||
const got = await publishAndConfirm("hi", state, { send: async () => "p9", fetchPage: async () => page });
|
||||
const got = await publishAndConfirm("hi", null, state, { send: async () => "p9", fetchPage: async () => page });
|
||||
expect(got).toBe(page);
|
||||
expect(state.id).toBeNull();
|
||||
});
|
||||
@@ -88,17 +88,17 @@ describe("publishAndConfirm", () => {
|
||||
const state = { id: null as string | null };
|
||||
const send = vi.fn(async () => "p9");
|
||||
const miss = async () => ({ items: [item("p1")], nextCursor: null });
|
||||
await expect(publishAndConfirm("hi", state, { send, fetchPage: miss })).rejects.toBeInstanceOf(PostError);
|
||||
await expect(publishAndConfirm("hi", null, state, { send, fetchPage: miss })).rejects.toBeInstanceOf(PostError);
|
||||
expect(state.id).toBe("p9");
|
||||
const hit = async () => ({ items: [item("p9")], nextCursor: null });
|
||||
await publishAndConfirm("hi", state, { send, fetchPage: hit });
|
||||
await publishAndConfirm("hi", null, state, { send, fetchPage: hit });
|
||||
expect(send).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("sendPost maps 401 to signed out and other failures to publish_failed", async () => {
|
||||
const f = (status: number) => (async () => new Response("{}", { status })) as unknown as typeof fetch;
|
||||
await expect(sendPost("x", f(401))).rejects.toMatchObject({ signedOut: true });
|
||||
await expect(sendPost("x", f(500))).rejects.toMatchObject({ signedOut: false });
|
||||
await expect(sendPost("x", null, f(401))).rejects.toMatchObject({ signedOut: true });
|
||||
await expect(sendPost("x", null, f(500))).rejects.toMatchObject({ signedOut: false });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -124,4 +124,20 @@ describe("Composer", () => {
|
||||
expect(html).toContain("No posts yet.");
|
||||
expect(html).toContain("composer-text");
|
||||
});
|
||||
it("shows an image picker and enables Post with a file but no text", () => {
|
||||
const f = new File(["x"], "photo.jpg", { type: "image/jpeg" });
|
||||
const html = renderToStaticMarkup(createElement(Composer, { ...base, file: f, onFile: () => {} }));
|
||||
expect(html).toContain("Add image");
|
||||
expect(html).toContain("photo.jpg");
|
||||
expect(html).not.toMatch(/<button[^>]*class="composer-post"[^>]*disabled/);
|
||||
});
|
||||
it("keeps the text and the image name on a publish failure", () => {
|
||||
const f = new File(["x"], "sunset.png", { type: "image/png" });
|
||||
const html = renderToStaticMarkup(
|
||||
createElement(Composer, { ...base, value: "my draft", file: f, error: true, onFile: () => {} }),
|
||||
);
|
||||
expect(html).toContain("Publishing the post failed");
|
||||
expect(html).toContain("my draft");
|
||||
expect(html).toContain("sunset.png");
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user