'use client' import { client } from '@/ui/api/client' import type { AssetInfo } from '@shumai/dtos' import { useMutation, useQueryClient } from '@tanstack/react-query' import type { InferRequestType, InferResponseType } from 'hono/client' import { useState } from 'react' import { toast } from 'sonner' import { useCopyActions } from './use-copy-actions' import { m } from '@/ui/paraglide/messages.js' interface UseFileActionsProps { teamId: string projectId: string assetId: string folders: AssetInfo[] files: AssetInfo[] selectedIds: Set isPublic?: boolean shareId?: string } export function useFileActions({ teamId, projectId, assetId, folders, files, selectedIds, isPublic, shareId, }: UseFileActionsProps) { const [editingItemId, setEditingItemId] = useState(null) const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false) const [itemsToDelete, setItemsToDelete] = useState([]) const [isDownloadDialogOpen, setIsDownloadDialogOpen] = useState(false) const [isLoadingLinks, setIsLoadingLinks] = useState(false) const [resolvedFiles, setResolvedFiles] = useState< Array<{ id: string; name: string; url: string }> >([]) const [skippedArchivedCount, setSkippedArchivedCount] = useState(0) const [archiveConfirmState, setArchiveConfirmState] = useState<{ open: boolean mode: 'archive' | 'restore' items: AssetInfo[] }>({ open: false, mode: 'archive', items: [] }) const queryClient = useQueryClient() const $createFolder = client.api.folders.$post const { mutate: createFolder } = useMutation< InferResponseType, Error, InferRequestType >({ mutationFn: async (request) => { const res = await $createFolder(request) if (!res.ok) throw new Error('Failed to create') return (await res.json()) as unknown as InferResponseType }, }) const $renameFolder = client.api.folders[':folderId'].$put const { mutate: renameFolder } = useMutation< InferResponseType, Error, InferRequestType >({ mutationFn: async (request) => { const res = await $renameFolder(request) if (!res.ok) throw new Error('Failed to rename') return (await res.json()) as unknown as InferResponseType }, }) const $renameFile = client.api.files[':fileId'].$put const { mutate: renameFile } = useMutation< InferResponseType, Error, InferRequestType >({ mutationFn: async (request) => { const res = await $renameFile(request) if (!res.ok) throw new Error('Failed to rename') return (await res.json()) as unknown as InferResponseType }, }) const $deleteFiles = client.api.files.$delete const { mutate: deleteFiles } = useMutation>({ mutationFn: async (request) => { const res = await $deleteFiles(request) if (!res.ok) throw new Error('Failed to delete') }, }) const $deleteFolders = client.api.folders.$delete const { mutate: deleteFolders } = useMutation< InferResponseType, Error, InferRequestType >({ mutationFn: async (request) => { const res = await $deleteFolders(request) if (!res.ok) throw new Error('Failed to delete') return null as unknown as InferResponseType }, }) const $restoreFiles = client.api.files.restore.$post const { mutate: restoreFiles } = useMutation>( { mutationFn: async (request) => { const res = await $restoreFiles(request) if (!res.ok) throw new Error('Failed to restore') }, }, ) const $restoreFolders = client.api.folders.restore.$post const { mutate: restoreFolders } = useMutation< InferResponseType, Error, InferRequestType >({ mutationFn: async (request) => { const res = await $restoreFolders(request) if (!res.ok) throw new Error('Failed to restore') return null as unknown as InferResponseType }, }) const $getDownloadLinks = client.api.files['download-links'].$post const { mutateAsync: getDownloadLinks } = useMutation< InferResponseType, Error, InferRequestType >({ mutationFn: async (request) => { const res = await $getDownloadLinks(request) if (!res.ok) throw new Error('Failed to get download links') return (await res.json()) as unknown as InferResponseType }, }) type ArchiveFilesPost = typeof client.api.files.archive.$post const { mutate: archiveFiles, isPending: isArchiving } = useMutation< InferResponseType, Error, InferRequestType >({ mutationFn: async (request) => { const res = await client.api.files.archive.$post(request) if (!res.ok) throw new Error(m.archive_failed_toast()) return (await res.json()) as unknown as InferResponseType }, }) type RestoreArchiveFilesPost = (typeof client.api.files)['restore-archive']['$post'] const { mutate: restoreArchiveFiles, isPending: isRestoringArchive } = useMutation< InferResponseType, Error, InferRequestType >({ mutationFn: async (request) => { const res = await client.api.files['restore-archive'].$post(request) if (!res.ok) throw new Error(m.restore_archive_failed_toast()) return (await res.json()) as unknown as InferResponseType }, }) const handleRename = (item: AssetInfo) => { setEditingItemId(item.id!) } const confirmDelete = () => { const fileIds = itemsToDelete .filter((i) => i.type === 'file' || i.type === 'version_stack') .map((i) => i.id!) const folderIds = itemsToDelete.filter((i) => i.type === 'folder').map((i) => i.id!) if (fileIds.length > 0) { deleteFiles( { json: { ids: fileIds } }, { onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId], }) }, }, ) } if (folderIds.length > 0) { deleteFolders( { json: { ids: folderIds } }, { onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId], }) queryClient.invalidateQueries({ queryKey: ['folders'], }) }, }, ) } setIsDeleteDialogOpen(false) setItemsToDelete([]) } const handleDelete = (items: AssetInfo[]) => { setItemsToDelete(items) setIsDeleteDialogOpen(true) } const handleRestore = (items: AssetInfo[]) => { const fileIds = items .filter((i) => i.type === 'file' || i.type === 'version_stack') .map((i) => i.id!) const folderIds = items.filter((i) => i.type === 'folder').map((i) => i.id!) if (fileIds.length > 0) { restoreFiles( { json: { ids: fileIds } }, { onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['projects', projectId, 'recently-deleted', 'file'], }) }, }, ) } if (folderIds.length > 0) { restoreFolders( { json: { ids: folderIds } }, { onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['projects', projectId, 'recently-deleted', 'folder'], }) }, }, ) } } const handleDownload = async (items: AssetInfo[]) => { if (items.length === 0) return setIsDownloadDialogOpen(true) setIsLoadingLinks(true) setResolvedFiles([]) setSkippedArchivedCount(0) try { if (isPublic && shareId) { const password = localStorage.getItem(`share_pwd_${shareId}`) || '' const links: Array<{ id: string; name: string; url: string }> = [] let skipped = 0 for (const item of items) { if ( item.status === 'archived' || item.status === 'archiving' || item.status === 'restoring' ) { skipped++ continue } const key = item.media?.original?.key if (!key || !item.id) continue const res = await client.api.shares[':shareId'].files[':fileId']['download-url'].$post( { param: { shareId, fileId: item.id }, json: { key }, }, { headers: { 'x-share-password': password, }, }, ) if (res.ok) { const { url } = await res.json() links.push({ id: item.id, name: item.name || 'download', url }) } } setSkippedArchivedCount(skipped) if (links.length === 0 && skipped > 0) { setIsDownloadDialogOpen(false) toast.error(m.download_all_archived_error()) return } setResolvedFiles(links) } else { const res = await getDownloadLinks({ json: { ids: items.map((i) => i.id!) }, }) const skipped = res.skippedArchivedCount ?? 0 setSkippedArchivedCount(skipped) if (res.files.length === 0 && skipped > 0) { setIsDownloadDialogOpen(false) toast.error(m.download_all_archived_error()) return } setResolvedFiles(res.files) } } catch (error) { toast.error('Failed to prepare download links') setIsDownloadDialogOpen(false) console.error(error) } finally { setIsLoadingLinks(false) } } const { handleCopy } = useCopyActions({ projectId, isPublic, shareId, getDownloadLinks: (args) => getDownloadLinks(args), }) const handleArchive = (items: AssetInfo[]) => { if (items.length === 0) return setArchiveConfirmState({ open: true, mode: 'archive', items, }) } const handleRestoreArchive = (items: AssetInfo[]) => { if (items.length === 0) return setArchiveConfirmState({ open: true, mode: 'restore', items, }) } const confirmArchiveOrRestore = () => { const ids = archiveConfirmState.items.map((i) => i.id!).filter(Boolean) if (ids.length === 0) { setArchiveConfirmState((prev) => ({ ...prev, open: false, items: [] })) return } if (archiveConfirmState.mode === 'archive') { archiveFiles( { json: { ids } }, { onSuccess: (data) => { if (data.archivedAssetIds.length > 0) { toast.success(m.archive_started_toast({ count: data.archivedAssetIds.length })) } else { toast.info(m.archive_no_eligible_assets_toast()) } queryClient.removeQueries({ queryKey: ['file', teamId] }) queryClient.invalidateQueries({ queryKey: ['search', teamId] }) setArchiveConfirmState((prev) => ({ ...prev, open: false, items: [] })) }, onError: () => { toast.error(m.archive_failed_toast()) }, }, ) } else { restoreArchiveFiles( { json: { ids } }, { onSuccess: (data) => { if (data.restoredAssetIds.length > 0) { toast.success( m.restore_archive_started_toast({ count: data.restoredAssetIds.length }), ) } else { toast.info(m.restore_archive_no_eligible_assets_toast()) } queryClient.removeQueries({ queryKey: ['file', teamId] }) queryClient.invalidateQueries({ queryKey: ['search', teamId] }) setArchiveConfirmState((prev) => ({ ...prev, open: false, items: [] })) }, onError: () => { toast.error(m.restore_archive_failed_toast()) }, }, ) } } const startDownload = () => { const files = [...resolvedFiles] setIsDownloadDialogOpen(false) if (files.length === 0) return toast.info( `Starting download of ${files.length} files. Please allow multiple downloads if prompted by your browser.`, { duration: 5000, }, ) const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) const runQueue = async () => { const batchSize = 5 for (let i = 0; i < files.length; i += batchSize) { const chunk = files.slice(i, i + batchSize) for (const file of chunk) { // Use a hidden iframe instead of an anchor with target="_blank". // Download URLs respond with Content-Disposition: attachment, so the // browser starts the download in the background: no flash of a tab // that opens and auto-closes. A failed/expired link renders inside // the hidden iframe instead of navigating the SPA tab away. const iframe = document.createElement('iframe') iframe.style.display = 'none' iframe.src = file.url document.body.appendChild(iframe) // Remove the iframe once the download has had time to start. window.setTimeout(() => iframe.remove(), 60_000) } if (i + batchSize < files.length) { await delay(600) } } toast.success('All downloads initiated successfully') } runQueue().catch((err) => { console.error('Background downloads failed:', err) toast.error('Some downloads could not be started') }) } const handleNewFolder = (name: string) => { createFolder( { json: { name, parentId: assetId } }, { onSuccess: (data) => { queryClient.invalidateQueries({ queryKey: ['search', teamId], }) queryClient.invalidateQueries({ queryKey: ['folders'], }) if (data?.id) { setEditingItemId(data.id) } }, }, ) } const onRenameSubmit = (item: AssetInfo, newName: string) => { if (item.type === 'folder') { renameFolder( { param: { folderId: item.id! }, json: { name: newName } }, { onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['search', teamId], }) queryClient.invalidateQueries({ queryKey: ['folders'], }) }, }, ) } else { renameFile( { param: { fileId: item.id! }, json: { name: newName }, }, { onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['search', teamId], }) queryClient.invalidateQueries({ queryKey: ['folders'], }) }, }, ) } } const handleAction = ( action: | 'rename' | 'delete' | 'download' | 'restore' | 'copy-name-and-download-link' | 'archive' | 'restore-archive', item: AssetInfo, ) => { const isSelected = selectedIds.has(item.id!) const targetItems = isSelected ? [...folders, ...files].filter((i) => selectedIds.has(i.id!)) : [item] switch (action) { case 'rename': handleRename(item) break case 'delete': handleDelete(targetItems) break case 'download': handleDownload(targetItems) break case 'restore': handleRestore(targetItems) break case 'copy-name-and-download-link': handleCopy('download-link', targetItems) break case 'archive': handleArchive(targetItems) break case 'restore-archive': handleRestoreArchive(targetItems) break } } return { editingItemId, setEditingItemId, handleRename, handleDelete, handleRestore, handleDownload, handleCopy, handleArchive, handleRestoreArchive, handleNewFolder, handleAction, onRenameSubmit, isDeleteDialogOpen, setIsDeleteDialogOpen, itemsToDelete, confirmDelete, isDownloadDialogOpen, setIsDownloadDialogOpen, isLoadingLinks, resolvedFiles, skippedArchivedCount, startDownload, archiveConfirmState, setArchiveConfirmState, confirmArchiveOrRestore, isArchiving, isRestoringArchive, } }