Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(web): add comment media helpers and Pro gate
Richie McIlroyacf7beffecd3
diff --git a/apps/web/__tests__/unit/comment-media-keys.test.ts b/apps/web/__tests__/unit/comment-media-keys.test.tsnew file mode 100644index 000000000..825bd4d99--- /dev/null+++ b/apps/web/__tests__/unit/comment-media-keys.test.ts@@ -0,0 +1,96 @@+import { describe, expect, it } from "vitest";+import {+ baseContentType,+ commentMediaExtension,+ commentMediaKeys,+ MAX_WAVEFORM_PEAKS,+ sanitizeWaveform,+} from "@/lib/comment-media";++describe("baseContentType", () => {+ it("strips MediaRecorder codec suffixes and normalizes case", () => {+ expect(baseContentType("audio/webm;codecs=opus")).toBe("audio/webm");+ expect(baseContentType("Video/MP4; codecs=avc1")).toBe("video/mp4");+ expect(baseContentType("video/mp4")).toBe("video/mp4");+ });+});++describe("commentMediaExtension", () => {+ it("never maps webm video to an audio extension", () => {+ expect(commentMediaExtension("video", "video/webm")).toBe("webm");+ expect(commentMediaExtension("audio", "audio/webm")).toBe("webm");+ // The signed-upload route's inference bug this replaces: a video kind+ // must not accept audio types at all.+ expect(commentMediaExtension("video", "audio/webm")).toBeNull();+ });++ it("rejects types outside the allowlist", () => {+ expect(commentMediaExtension("video", "image/gif")).toBeNull();+ expect(+ commentMediaExtension("audio", "application/octet-stream"),+ ).toBeNull();+ expect(commentMediaExtension("video", "video/x-matroska")).toBeNull();+ });+});++describe("commentMediaKeys", () => {+ const input = {+ ownerId: "owner-1",+ videoId: "video-1",+ commentId: "comment-1",+ };++ it("derives keys under the parent video's comments prefix", () => {+ expect(+ commentMediaKeys({+ ...input,+ kind: "video",+ contentType: "video/mp4;codecs=avc1",+ withThumbnail: true,+ }),+ ).toEqual({+ contentType: "video/mp4",+ key: "owner-1/video-1/comments/comment-1/media.mp4",+ thumbnailKey: "owner-1/video-1/comments/comment-1/thumbnail.jpg",+ });+ });++ it("only video comments get thumbnails", () => {+ expect(+ commentMediaKeys({+ ...input,+ kind: "audio",+ contentType: "audio/webm;codecs=opus",+ withThumbnail: true,+ }),+ ).toEqual({+ contentType: "audio/webm",+ key: "owner-1/video-1/comments/comment-1/media.webm",+ thumbnailKey: null,+ });+ });++ it("returns null for disallowed content types", () => {+ expect(+ commentMediaKeys({ ...input, kind: "video", contentType: "image/png" }),+ ).toBeNull();+ });+});++describe("sanitizeWaveform", () => {+ it("clamps values to 0..1 and zeroes non-finite entries", () => {+ expect(sanitizeWaveform([0.5, -1, 2, Number.NaN, Infinity])).toEqual([+ 0.5, 0, 1, 0, 0,+ ]);+ });++ it("caps the number of peaks", () => {+ const peaks = sanitizeWaveform(new Array(10_000).fill(0.5));+ expect(peaks).toHaveLength(MAX_WAVEFORM_PEAKS);+ });++ it("returns undefined for empty input", () => {+ expect(sanitizeWaveform(undefined)).toBeUndefined();+ expect(sanitizeWaveform([])).toBeUndefined();+ });+});diff --git a/apps/web/lib/comment-media.ts b/apps/web/lib/comment-media.tsnew file mode 100644index 000000000..a5c63bca1--- /dev/null+++ b/apps/web/lib/comment-media.ts@@ -0,0 +1,71 @@+/**+ * Playback/thumbnail URL for a media comment's object. /api/storage/object+ * enforces the video's view policy and asserts the key sits under the video's+ * prefix, then 302s to a signed URL (S3) or byte-proxies (Drive).+ */+export const commentMediaUrl = (videoId: string, key: string) =>+ `/api/storage/object?videoId=${encodeURIComponent(videoId)}&key=${encodeURIComponent(key)}`;++// Extensions derive from an allowlisted content type, never from a client+// filename (the signed-upload route's extension inference maps .webm to+// audio/webm, which would mislabel webm video — comment media bypasses it).+const AUDIO_EXTENSIONS: Record<string, string> = {+ "audio/webm": "webm",+ "audio/mp4": "m4a",+ "audio/mpeg": "mp3",+ "audio/aac": "aac",+ "audio/ogg": "ogg",+};+const VIDEO_EXTENSIONS: Record<string, string> = {+ "video/mp4": "mp4",+ "video/webm": "webm",+};++/** `audio/webm;codecs=opus` (MediaRecorder style) -> `audio/webm`. */+export const baseContentType = (contentType: string) =>+ contentType.split(";")[0]?.trim().toLowerCase() ?? "";++export const commentMediaExtension = (+ kind: "video" | "audio",+ contentType: string,+) =>+ (kind === "audio" ? AUDIO_EXTENSIONS : VIDEO_EXTENSIONS)[contentType] ?? null;++/**+ * Object keys for a media comment, always under the parent video's prefix so+ * serving, lifecycle, and deletion inherit from the video. Returns null for+ * content types outside the allowlist.+ */+export const commentMediaKeys = (input: {+ ownerId: string;+ videoId: string;+ commentId: string;+ kind: "video" | "audio";+ contentType: string;+ withThumbnail?: boolean;+}) => {+ const contentType = baseContentType(input.contentType);+ const ext = commentMediaExtension(input.kind, contentType);+ if (!ext) return null;+ const prefix = `${input.ownerId}/${input.videoId}/comments/${input.commentId}`;+ return {+ contentType,+ key: `${prefix}/media.${ext}`,+ thumbnailKey:+ input.kind === "video" && input.withThumbnail+ ? `${prefix}/thumbnail.jpg`+ : null,+ };+};++export const MAX_WAVEFORM_PEAKS = 256;++/** Clamp a client-supplied waveform so it can't bloat the JSON column. */+export const sanitizeWaveform = (waveform: number[] | undefined) => {+ if (!waveform?.length) return undefined;+ return waveform+ .slice(0, MAX_WAVEFORM_PEAKS)+ .map((peak) =>+ Number.isFinite(peak) ? Math.min(1, Math.max(0, peak)) : 0,+ );+};diff --git a/apps/web/lib/media-comments.ts b/apps/web/lib/media-comments.tsnew file mode 100644index 000000000..ac4055b73--- /dev/null+++ b/apps/web/lib/media-comments.ts@@ -0,0 +1,20 @@+import "server-only";++import type { users } from "@cap/database/schema";+import type { User, Video } from "@cap/web-domain";+import type { InferSelectModel } from "drizzle-orm";+import { isVideoOwnerPro } from "@/lib/org-pro";++/**+ * Recording media comments (video/voice replies on the share-page timeline) is+ * part of the VIDEO OWNER's Pro plan: any signed-in viewer can record on a Pro+ * owner's video. Viewing/playing media comments is never gated here — that+ * follows the video's normal view policy.+ */+export async function canUseMediaComments(+ user: Pick<InferSelectModel<typeof users>, "id"> | null,+ video: { ownerId: User.UserId; id: Video.VideoId },+): Promise<boolean> {+ if (!user) return false;+ return isVideoOwnerPro(video.ownerId);+}diff --git a/apps/web/lib/org-pro.ts b/apps/web/lib/org-pro.tsindex 14014cf25..e8968817e 100644--- a/apps/web/lib/org-pro.ts+++ b/apps/web/lib/org-pro.ts@@ -3,9 +3,23 @@ import "server-only";import { db } from "@cap/database";import { organizations, users } from "@cap/database/schema";import { userIsPro } from "@cap/utils";-import type { Organisation } from "@cap/web-domain";+import type { Organisation, User } from "@cap/web-domain";import { eq } from "drizzle-orm";+/** Whether a specific video's OWNER is on a Pro plan. */+export async function isVideoOwnerPro(ownerId: User.UserId): Promise<boolean> {+ const [owner] = await db()+ .select({+ stripeSubscriptionStatus: users.stripeSubscriptionStatus,+ thirdPartyStripeSubscriptionId: users.thirdPartyStripeSubscriptionId,+ })+ .from(users)+ .where(eq(users.id, ownerId))+ .limit(1);++ return userIsPro(owner ?? null);+}+/*** Whether an organization's OWNER is on a Pro plan. Public collection links are* an org-wide Pro entitlement: any manager can publish while the owner is Pro.