Files
OpenFrame/lib/video-assets.ts
yusufipek b9e2006e34 feat(comments): carry a batch of screenshots on one comment
A comment held one image, and the paste handler took the first item off the
clipboard and dropped the rest. Reviewing a cut usually means several
screenshots about the same moment, which meant one comment per screenshot or
one screenshot and a paragraph describing the others. Editing a comment could
not attach anything at all: the edit box had no paste handler, no file picker
and no way to remove what was already there.

A comment now carries up to five images, in the composer, in a reply and in
the editor. One paste stages every image on the clipboard, the file picker
takes a multiple selection, and a drop lands on whichever editor is open. Over
the cap the extras are refused out loud rather than dropped quietly. A single
image still fills the width; several tile into a grid, and either opens full
screen on click.

The images move into their own table. `comments.imageUrl` stays and follows the
first of them, so a reader that has not been updated keeps working, and the
migration copies the existing attachments across so the new table is complete
from the first read. Every path that resolves a URL back to a comment now asks
the new table: R2 cleanup, the orphan sweep, the storage accounting and the
reference checks that decide whether an object can be deleted. Left on the old
column they would have treated images two through five as unreferenced and
swept them.

Detaching an image while editing only breaks the link. The file stays in R2 and
in the assets pane, which is where it is deleted from and where its bytes are
already billed.
2026-08-20 11:01:33 +03:00

215 lines
6.9 KiB
TypeScript

import type { NextRequest } from 'next/server';
import type { VideoAsset } from '@prisma/client';
import { auth, checkProjectAccess } from '@/lib/auth';
import { db } from '@/lib/db';
import { getGuestIdentityFromRequest } from '@/lib/guest-identity';
import { getShareSessionFromRequest } from '@/lib/share-session';
import { validateShareLinkAccess } from '@/lib/share-links';
import { canDownloadProjectMedia } from '@/lib/project-download';
import { SAFE_IMAGE_PROXY_PATH } from '@/lib/image-upload-validation';
export { SAFE_IMAGE_PROXY_PATH };
const IMAGE_PROXY_PREFIX = '/api/upload/image/';
const AUDIO_PROXY_PREFIX = '/api/upload/audio/';
const VIDEO_PROXY_PREFIX = '/api/upload/video/';
export const SAFE_AUDIO_PROXY_PATH =
/^\/api\/upload\/audio\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[a-z0-9]+$/i;
export const SAFE_VIDEO_PROXY_PATH =
/^\/api\/upload\/video\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[a-z0-9]+$/i;
export const SAFE_BUNNY_VIDEO_ID = /^[A-Za-z0-9_-]{8,128}$/;
export type VideoAssetAccessContext = {
video: {
id: string;
title: string;
projectId: string;
project: {
id: string;
name: string;
ownerId: string;
workspaceId: string;
visibility: string;
allowDownloads: boolean;
workspace: {
id: string;
ownerId: string;
};
};
};
hasViewAccess: boolean;
/**
* Whether the viewer has any relationship to the project: owner, project member,
* workspace member, or a valid share link. Distinguishes "you may not" from "there is
* no such thing", so a route can answer 404 for another tenant's id without answering
* 404 to somebody whose access merely lapsed.
*/
viewerBelongsToProject: boolean;
canUploadAssets: boolean;
canDownloadAssets: boolean;
canManageAssets: boolean;
viewerUserId: string | null;
viewerGuestIdentityId: string | null;
};
export function sanitizeAssetDisplayName(
value: string | null | undefined,
fallback: string
): string {
const raw = typeof value === 'string' ? value : '';
const normalized = raw
.replace(/[\u0000-\u001F\u007F]/g, '')
.replace(/[\[\]\(\)]/g, '')
.replace(/\s+/g, ' ')
.trim();
if (normalized.length === 0) return fallback;
return normalized.slice(0, 200);
}
/**
* A voice comment's display name is the generated file name, extension and all,
* so blindly appending the extension named the download `<uuid>.webm.webm`.
*/
export function withFileExtension(name: string, extension: string): string {
return name.toLowerCase().endsWith(extension.toLowerCase()) ? name : `${name}${extension}`;
}
export function extractImageKeyFromProxyUrl(url: string): string | null {
if (!SAFE_IMAGE_PROXY_PATH.test(url)) return null;
const filename = url.slice(IMAGE_PROXY_PREFIX.length);
if (!filename) return null;
return `images/${filename}`;
}
export function extractImageFileNameFromProxyUrl(url: string): string | null {
if (!SAFE_IMAGE_PROXY_PATH.test(url)) return null;
const filename = url.slice(IMAGE_PROXY_PREFIX.length);
return filename || null;
}
export function extractAudioKeyFromProxyUrl(url: string): string | null {
if (!SAFE_AUDIO_PROXY_PATH.test(url)) return null;
const filename = url.slice(AUDIO_PROXY_PREFIX.length);
if (!filename) return null;
return `voice/${filename}`;
}
export function extractAudioFileNameFromProxyUrl(url: string): string | null {
if (!SAFE_AUDIO_PROXY_PATH.test(url)) return null;
const filename = url.slice(AUDIO_PROXY_PREFIX.length);
return filename || null;
}
export function extractVideoKeyFromProxyUrl(url: string): string | null {
if (!SAFE_VIDEO_PROXY_PATH.test(url)) return null;
const filename = url.slice(VIDEO_PROXY_PREFIX.length);
if (!filename) return null;
return `videos/${filename}`;
}
export function extractVideoFileNameFromProxyUrl(url: string): string | null {
if (!SAFE_VIDEO_PROXY_PATH.test(url)) return null;
const filename = url.slice(VIDEO_PROXY_PREFIX.length);
return filename || null;
}
export function canDeleteAssetForViewer(
asset: Pick<VideoAsset, 'uploadedByUserId' | 'uploadedByGuestIdentityId'>,
viewer: Pick<
VideoAssetAccessContext,
'canManageAssets' | 'viewerUserId' | 'viewerGuestIdentityId'
>
): boolean {
if (viewer.canManageAssets) return true;
if (viewer.viewerUserId && asset.uploadedByUserId === viewer.viewerUserId) return true;
if (
!viewer.viewerUserId &&
viewer.viewerGuestIdentityId &&
asset.uploadedByGuestIdentityId &&
asset.uploadedByGuestIdentityId === viewer.viewerGuestIdentityId
) {
return true;
}
return false;
}
export async function getVideoAssetAccessContext(
request: NextRequest,
videoId: string,
requiredPermission: 'VIEW' | 'COMMENT' = 'VIEW'
): Promise<VideoAssetAccessContext | null> {
const session = await auth();
const video = await db.video.findUnique({
where: { id: videoId },
select: {
id: true,
title: true,
projectId: true,
project: {
select: {
id: true,
name: true,
ownerId: true,
workspaceId: true,
visibility: true,
allowDownloads: true,
workspace: {
select: {
id: true,
ownerId: true,
},
},
},
},
},
});
if (!video) return null;
const access = await checkProjectAccess(video.project, session?.user?.id);
const shareSession = getShareSessionFromRequest(request, video.id);
const shareAccess = shareSession
? await validateShareLinkAccess({
token: shareSession.token,
projectId: video.projectId,
videoId: video.id,
requiredPermission,
passwordVerified: shareSession.passwordVerified,
})
: {
hasAccess: false,
canComment: false,
canDownload: false,
allowGuests: false,
requiresPassword: false,
link: null,
};
const hasViewAccess = access.hasAccess || shareAccess.hasAccess;
const canCommentWithMembership = !!session?.user?.id && access.hasAccess;
const canCommentWithShare =
shareAccess.canComment && (session?.user?.id ? true : shareAccess.allowGuests);
const canUploadAssets = canCommentWithMembership || canCommentWithShare;
const canDownloadWithMembership = canDownloadProjectMedia(video.project, access);
const canDownloadWithShare = shareAccess.hasAccess && shareAccess.canDownload;
const canDownloadAssets = hasViewAccess && (canDownloadWithMembership || canDownloadWithShare);
const viewerUserId = session?.user?.id ?? null;
const viewerGuestIdentityId = viewerUserId ? null : getGuestIdentityFromRequest(request);
const viewerBelongsToProject =
access.isOwner || access.isProjectMember || access.isWorkspaceMember || shareAccess.hasAccess;
return {
video,
hasViewAccess,
viewerBelongsToProject,
canUploadAssets,
canDownloadAssets,
canManageAssets: access.canEdit,
viewerUserId,
viewerGuestIdentityId,
};
}