Files
shumai/packages/webui/components/file-viewer-right-sidebar.tsx
T
Yiling-J 65e2ac1383 fix(security): improve access control and storage security (#518)
* fix(security): improve access control and storage security

* fix(security): set NODE_ENV in dockerfiles and sign local storage get urls with lru cache
2026-11-05 20:49:38 +08:00

527 lines
18 KiB
TypeScript

import type { AssetInfo, CommentExportFormat, CommentInfo, FieldValueInfo } from '@shumai/dtos'
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import type { MemberInfo } from '@/ui/stores/members'
import { client } from '@/ui/api/client'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
import { useFieldStore } from '@/ui/stores/fields'
import type { Annotation } from '@/ui/types'
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import React, { useEffect, useMemo, useState } from 'react'
import { useInView } from 'react-intersection-observer'
import { MessageCard } from './chat/message-card'
import { ChatInput } from './chat/message-input'
import FieldRenderer from './field-renderer'
import { GuestIdentityPopup } from './guest-identity-popup'
import { ScrollArea } from './ui/scroll-area'
import { Button } from './ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from './ui/dropdown-menu'
import { MoreHorizontal } from 'lucide-react'
import { toast } from 'sonner'
import { m } from '@/ui/paraglide/messages.js'
import { getViewerForFile } from '@/ui/components/viewers/registry'
interface FileViewerRightSidebarProps {
teamId: string
projectId: string
file: AssetInfo | null
onSaveField: (fieldId: string, value: unknown) => void
members: MemberInfo[]
onCommentSelect?: (comment: CommentInfo) => void
hideAnnotationControl?: boolean
readOnly?: boolean
publicFields?: MetadataFieldInfo[]
isPublic?: boolean
shareId?: string
currentTime?: number
onTyping?: () => void
selectedCommentId?: string | null
}
const COMMENT_EXPORT_OPTIONS: {
format: CommentExportFormat
label: string
ext: string
}[] = [
{ format: 'fcp-fiojson', label: 'FCP 10.4.0+', ext: 'FIOJSON' },
{ format: 'media-composer-xml', label: 'Media Composer', ext: 'XML' },
{ format: 'premiere-xml', label: 'Premiere Pro', ext: 'XML' },
{ format: 'resolve-edl', label: 'Resolve', ext: 'EDL' },
]
export function FileViewerRightSidebar({
teamId,
projectId,
file,
onSaveField,
members,
onCommentSelect,
hideAnnotationControl = false,
readOnly = false,
publicFields,
isPublic = false,
shareId,
currentTime,
onTyping,
selectedCommentId,
}: FileViewerRightSidebarProps) {
const { canEdit } = usePermissions(projectId)
const { fields, setFields } = useFieldStore()
const queryClient = useQueryClient()
const { ref, inView } = useInView()
const [replyingTo, setReplyingTo] = useState<CommentInfo | null>(null)
const [isGuestPopupOpen, setIsGuestPopupOpen] = useState(false)
const [isExporting, setIsExporting] = useState(false)
const [pendingComment, setPendingComment] = useState<{
text: string
attachmentIds: string[]
annotations?: Annotation[]
replyToId?: string | null
second?: number | null
} | null>(null)
const handleExportComments = async (format: CommentExportFormat) => {
if (!file?.id || isExporting) return
try {
setIsExporting(true)
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone
const res = await client.api.files[':fileId'].comments.export.$post({
param: { fileId: file.id },
json: { format, timeZone },
})
if (!res.ok) {
throw new Error('Failed to export comments')
}
const disposition = res.headers.get('content-disposition')
let filename = `${file.name || 'comments'}_comments`
if (disposition) {
const utf8Match = /filename\*=UTF-8''([^;]+)/i.exec(disposition)
const basicMatch = /filename="?([^";]+)"?/i.exec(disposition)
if (utf8Match?.[1]) {
filename = decodeURIComponent(utf8Match[1])
} else if (basicMatch?.[1]) {
filename = basicMatch[1]
}
}
const blob = await res.blob()
const downloadUrl = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = downloadUrl
link.download = filename
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(downloadUrl)
} catch (error) {
console.error('Failed to export comments:', error)
toast.error(m.failed_to_export_comments())
} finally {
setIsExporting(false)
}
}
const { data: apiFields } = useQuery({
queryKey: ['fields', projectId],
queryFn: async () => {
const res = await client.api.projects[':projectId'].fields.$get({
param: { projectId: projectId },
})
if (!res.ok) throw new Error('Failed to fetch fields')
return await res.json()
},
enabled: !!projectId && !publicFields,
})
const viewerDef = getViewerForFile(file)
useEffect(() => {
if (publicFields) {
setFields(publicFields, projectId)
} else if (apiFields) {
setFields(apiFields as unknown as MetadataFieldInfo[], projectId)
}
}, [apiFields, publicFields, projectId, setFields])
const {
data: commentsData,
fetchNextPage,
hasNextPage,
} = useInfiniteQuery({
queryKey: isPublic
? ['shares', shareId, 'files', file?.id, 'comments']
: ['files', file?.id, 'comments'],
queryFn: async ({ pageParam }) => {
if (isPublic) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
const res = await client.api.shares[':shareId'].files[':fileId'].comments.$get(
{
param: { shareId: shareId!, fileId: file!.id! },
query: { after: pageParam as string },
},
{
headers: {
'x-share-password': password,
},
},
)
if (!res.ok) throw new Error('Failed to fetch comments')
return await res.json()
} else {
const res = await client.api.files[':fileId'].comments.$get({
param: { fileId: file!.id! },
query: { after: pageParam as string },
})
if (!res.ok) throw new Error('Failed to fetch comments')
return await res.json()
}
},
enabled: !!file?.id && (!isPublic || !!shareId),
initialPageParam: '',
refetchInterval: 2000,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getNextPageParam: (lastPage: any) => lastPage.pageInfo?.cursor || undefined,
})
const { mutate: createComment } = useMutation({
mutationFn: async ({
text,
attachmentIds,
annotations,
replyToId,
second,
}: {
text: string
attachmentIds: string[]
annotations?: Annotation[]
replyToId?: string | null
second?: number | null
}) => {
if (isPublic) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
const res = await client.api.shares[':shareId'].files[':fileId'].comments.$post(
{
param: { shareId: shareId!, fileId: file!.id! },
json: {
message: text,
attachmentIds: attachmentIds,
replyToId: replyToId ?? undefined,
annotations: annotations,
second: second ?? undefined,
},
},
{
headers: {
'x-share-password': password,
},
},
)
if (!res.ok) throw new Error('Failed to create comment')
return await res.json()
} else {
const res = await client.api.files[':fileId'].comments.$post({
param: { fileId: file!.id! },
json: {
message: text,
attachmentIds: attachmentIds,
replyToId: replyToId ?? undefined,
annotations: annotations,
second: second ?? undefined,
},
})
if (!res.ok) throw new Error('Failed to create comment')
return await res.json()
}
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: isPublic
? ['shares', shareId, 'files', file?.id, 'comments']
: ['files', file?.id, 'comments'],
})
},
})
React.useEffect(() => {
if (inView && hasNextPage) {
fetchNextPage()
}
}, [inView, fetchNextPage, hasNextPage])
const itemFieldValueMap = useMemo(() => {
return (file?.fieldValues || []).reduce(
(acc: Record<string, FieldValueInfo>, val: FieldValueInfo) => {
acc[val.fieldId!] = val
return acc
},
{},
)
}, [file?.fieldValues])
const sortedFields = useMemo(() => {
return [...fields].sort((a, b) => {
const nameA = a.config?.name?.toLowerCase() || ''
const nameB = b.config?.name?.toLowerCase() || ''
if (nameA < nameB) return -1
if (nameA > nameB) return 1
return 0
})
}, [fields])
const comments =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(commentsData?.pages.flatMap((page: any) => page.data ?? []) as CommentInfo[]) ?? []
const handleSendMessage = async (
text: string,
attachmentIds: string[],
annotations?: Annotation[],
replyToId?: string | null,
second?: number | null,
) => {
if (!file?.id) return
if (isPublic) {
// Check if logged in
console.log('[handleSendMessage] checking auth status')
const meRes = await client.api.me.$get()
const { id: loggedInUserId } = await meRes.json()
console.log('[handleSendMessage] loggedInUserId:', loggedInUserId)
if (!loggedInUserId) {
const guestUserId = localStorage.getItem('guest_user_id')
console.log('[handleSendMessage] guestUserId from storage:', guestUserId)
if (!guestUserId) {
console.log('[handleSendMessage] no guest ID, opening popup')
setPendingComment({ text, attachmentIds, annotations, replyToId, second })
setIsGuestPopupOpen(true)
return
}
createComment({ text, attachmentIds, annotations, replyToId, second })
} else {
createComment({ text, attachmentIds, annotations, replyToId, second })
}
} else {
createComment({ text, attachmentIds, annotations, replyToId, second })
}
setReplyingTo(null)
}
const handleGuestSuccess = () => {
if (pendingComment) {
createComment({ ...pendingComment })
setPendingComment(null)
setReplyingTo(null)
}
}
const getUser = (id: string): MemberInfo => {
const member = members.find((m) => m.id === id)
if (member) {
return member
}
return {
id: 'unknown',
name: 'Unknown',
role: 'unknown',
}
}
if (!file) {
return (
<div className="flex h-full items-center justify-center p-8 text-center bg-background">
<div className="space-y-2">
<p className="text-sm font-medium text-foreground">{m.no_item_selected()}</p>
<p className="text-xs text-muted-foreground">{m.select_file_to_view_details()}</p>
</div>
</div>
)
}
return (
<div className="bg-background h-full flex flex-col overflow-hidden">
<Tabs defaultValue="comments" className="p-1 flex-1 flex flex-col px-2 min-h-0">
<TabsList className="w-full shrink-0">
<TabsTrigger value="comments" className="flex-1">
{m.comments()}
</TabsTrigger>
<TabsTrigger value="fields" className="flex-1">
{m.fields()}
</TabsTrigger>
</TabsList>
<TabsContent value="comments" className="flex-1 flex flex-col overflow-hidden min-h-0 mt-0">
{!isPublic && (
<div className="flex items-center justify-between px-1 py-1.5 shrink-0 border-b border-border/50">
<span className="text-xs font-semibold text-foreground">{m.all_comments()}</span>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 text-muted-foreground hover:text-foreground cursor-pointer"
aria-label={m.more_options()}
>
<MoreHorizontal className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuSub>
<DropdownMenuSubTrigger className="cursor-pointer">
<span>{m.export_comments()}</span>
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-56">
{COMMENT_EXPORT_OPTIONS.map((opt) => (
<DropdownMenuItem
key={opt.format}
className="flex items-center justify-between cursor-pointer"
disabled={isExporting}
onClick={() => handleExportComments(opt.format)}
>
<span>{opt.label}</span>
<span className="text-xs text-muted-foreground ml-auto pl-4">
{opt.ext}
</span>
</DropdownMenuItem>
))}
</DropdownMenuSubContent>
</DropdownMenuSub>
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
<ScrollArea className="flex-1 min-h-0 [&>div>div]:block!">
<div className="space-y-4 pt-2">
{comments.map((comment) => (
<div key={comment.id}>
<MessageCard
teamId={teamId}
message={comment}
getUser={getUser}
onReply={setReplyingTo}
hasReplies={!!comment.replies?.length}
formatTimestamp={viewerDef?.commentsConfig?.formatTimestamp}
frameRate={
viewerDef?.commentsConfig?.hasTimestamp
? file?.media?.metadata?.frameRate || 30
: undefined
}
startTimecode={
viewerDef?.commentsConfig?.hasTimestamp
? file?.media?.metadata?.startTimecode
: undefined
}
isSelected={selectedCommentId === comment.id}
onSelect={() => {
onCommentSelect?.(comment)
}}
readOnly={readOnly}
isPublic={isPublic}
/>
{comment.replies?.map((reply, index) => (
<div key={reply.id}>
<MessageCard
teamId={teamId}
isReply={true}
message={reply}
getUser={getUser}
onReply={setReplyingTo}
hasReplies={false}
isLastReply={index === (comment.replies?.length ?? 0) - 1}
formatTimestamp={viewerDef?.commentsConfig?.formatTimestamp}
frameRate={
viewerDef?.commentsConfig?.hasTimestamp
? file?.media?.metadata?.frameRate || 30
: undefined
}
startTimecode={
viewerDef?.commentsConfig?.hasTimestamp
? file?.media?.metadata?.startTimecode
: undefined
}
isSelected={selectedCommentId === reply.id}
onSelect={() => {
onCommentSelect?.(reply)
}}
readOnly={readOnly}
isPublic={isPublic}
/>
</div>
))}
</div>
))}
<div ref={ref} />
</div>
</ScrollArea>
{(!readOnly || isPublic) && (
<div className="mt-4 shrink-0">
<GuestIdentityPopup
isOpen={isGuestPopupOpen}
onClose={() => setIsGuestPopupOpen(false)}
onSuccess={handleGuestSuccess}
shareId={shareId || undefined}
>
<ChatInput
projectId={projectId}
onSendMessage={handleSendMessage}
replyingTo={replyingTo}
onCancelReply={() => setReplyingTo(null)}
hideAnnotationControl={hideAnnotationControl}
disableMentions={isPublic}
currentTime={viewerDef?.commentsConfig?.hasTimestamp ? currentTime : undefined}
formatTimestamp={viewerDef?.commentsConfig?.formatTimestamp}
frameRate={
viewerDef?.commentsConfig?.hasTimestamp
? file?.media?.metadata?.frameRate || 30
: undefined
}
startTimecode={
viewerDef?.commentsConfig?.hasTimestamp
? file?.media?.metadata?.startTimecode
: undefined
}
onTyping={onTyping}
/>
</GuestIdentityPopup>
</div>
)}
</TabsContent>
<TabsContent value="fields" className="flex-1 flex flex-col overflow-hidden min-h-0 mt-4">
<ScrollArea className="flex-1 px-4 min-h-0 [&>div>div]:block!">
{sortedFields && sortedFields.length > 0 && (
<div className="space-y-4 pb-4">
{sortedFields.map((field) => (
<div key={field.id} className="space-y-1">
<label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
{field.config?.name}
</label>
<div className="min-h-[28px]">
<FieldRenderer
fieldId={field.id}
config={field.config}
value={itemFieldValueMap[field.id!]?.value}
onSave={canEdit ? (val) => onSaveField(field.id!, val) : undefined}
readOnly={readOnly || field.readOnly || !canEdit}
/>
</div>
</div>
))}
</div>
)}
</ScrollArea>
</TabsContent>
</Tabs>
</div>
)
}