276 lines
10 KiB
TypeScript
276 lines
10 KiB
TypeScript
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;
|
|
}
|
|
}
|