Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore: Use `react-query` cache for file previews (#23398)

Ivan Vasilov8f90c8605036
diff --git a/apps/studio/components/to-be-cleaned/Storage/Storage.constants.ts b/apps/studio/components/to-be-cleaned/Storage/Storage.constants.ts
index 1eef8024d15..0ef1aac67aa 100644
--- a/apps/studio/components/to-be-cleaned/Storage/Storage.constants.ts
+++ b/apps/studio/components/to-be-cleaned/Storage/Storage.constants.ts
@@ -1,7 +1,7 @@
-export const URL_EXPIRY_DURATION = {
- WEEK: 60 * 60 * 24 * 7,
- MONTH: 60 * 60 * 24 * 30,
- YEAR: 60 * 60 * 24 * 365,
+export enum URL_EXPIRY_DURATION {
+ WEEK = 60 * 60 * 24 * 7,
+ MONTH = 60 * 60 * 24 * 30,
+ YEAR = 60 * 60 * 24 * 365,
}
export enum STORAGE_VIEWS {
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/CustomExpiryModal.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/CustomExpiryModal.tsx
index 7c054875a92..9ed960b2130 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/CustomExpiryModal.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/CustomExpiryModal.tsx
@@ -15,8 +15,8 @@ const unitMap = {
const CustomExpiryModal = () => {
const storageExplorerStore = useStorageStore()
- const { onCopyUrl } = useCopyUrl(storageExplorerStore.projectRef)
- const { getFileUrl, selectedFileCustomExpiry, setSelectedFileCustomExpiry } = storageExplorerStore
+ const { onCopyUrl } = useCopyUrl()
+ const { selectedFileCustomExpiry, setSelectedFileCustomExpiry } = storageExplorerStore
const visible = selectedFileCustomExpiry !== undefined
const onClose = () => setSelectedFileCustomExpiry(undefined)
@@ -38,10 +38,7 @@ const CustomExpiryModal = () => {
setSubmitting(true)
await onCopyUrl(
selectedFileCustomExpiry!.name,
- getFileUrl(
- selectedFileCustomExpiry!,
- values.expiresIn * unitMap[values.units as 'days' | 'weeks' | 'months' | 'years']
- )
+ values.expiresIn * unitMap[values.units as 'days' | 'weeks' | 'months' | 'years']
)
setSubmitting(false)
onClose()
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorer.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorer.tsx
index 85135c5b0ec..fde79b07903 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorer.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorer.tsx
@@ -14,7 +14,6 @@ export interface FileExplorerProps {
columns: StorageColumn[]
openedFolders: StorageItem[]
selectedItems: StorageItemWithColumn[]
- selectedFilePreview: (StorageItemWithColumn & { previewUrl: string | undefined }) | null
itemSearchString: string
onFilesUpload: (event: any, index: number) => void
onSelectAllItemsInColumn: (index: number) => void
@@ -27,7 +26,6 @@ const FileExplorer = ({
columns = [],
openedFolders = [],
selectedItems = [],
- selectedFilePreview,
itemSearchString,
onFilesUpload = noop,
onSelectAllItemsInColumn = noop,
@@ -63,7 +61,6 @@ const FileExplorer = ({
column={column}
openedFolders={openedFolders}
selectedItems={selectedItems}
- selectedFilePreview={selectedFilePreview}
itemSearchString={itemSearchString}
onFilesUpload={onFilesUpload}
onSelectAllItemsInColumn={onSelectAllItemsInColumn}
@@ -81,7 +78,6 @@ const FileExplorer = ({
view={view}
column={columns[columns.length - 1]}
selectedItems={selectedItems}
- selectedFilePreview={selectedFilePreview}
itemSearchString={itemSearchString}
onFilesUpload={onFilesUpload}
onSelectAllItemsInColumn={onSelectAllItemsInColumn}
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerColumn.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerColumn.tsx
index 29d3e83ac51..45f095e15ed 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerColumn.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerColumn.tsx
@@ -60,7 +60,6 @@ export interface FileExplorerColumnProps {
fullWidth?: boolean
openedFolders?: StorageItem[]
selectedItems: StorageItemWithColumn[]
- selectedFilePreview: (StorageItemWithColumn & { previewUrl: string | undefined }) | null
itemSearchString: string
onFilesUpload: (event: any, index: number) => void
onSelectAllItemsInColumn: (index: number) => void
@@ -75,7 +74,6 @@ const FileExplorerColumn = ({
fullWidth = false,
openedFolders = [],
selectedItems = [],
- selectedFilePreview,
itemSearchString,
onFilesUpload = noop,
onSelectAllItemsInColumn = noop,
@@ -221,7 +219,6 @@ const FileExplorerColumn = ({
columnIndex: index,
selectedItems,
openedFolders,
- selectedFilePreview,
}}
ItemComponent={FileExplorerRow}
getItemSize={(index) => (index !== 0 && index === columnItems.length ? 85 : 37)}
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRow.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRow.tsx
index 0355528e972..2126874a4f1 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRow.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRow.tsx
@@ -1,13 +1,5 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { find, isEmpty, isEqual } from 'lodash'
-import { useContextMenu } from 'react-contexify'
-import SVG from 'react-inlinesvg'
-
-import type { ItemRenderer } from 'components/ui/InfiniteList'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { BASE_PATH } from 'lib/constants'
-import { formatBytes } from 'lib/helpers'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
import {
AlertCircle,
Clipboard,
@@ -22,6 +14,14 @@ import {
Music,
Trash2,
} from 'lucide-react'
+import { useContextMenu } from 'react-contexify'
+import SVG from 'react-inlinesvg'
+
+import type { ItemRenderer } from 'components/ui/InfiniteList'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { BASE_PATH } from 'lib/constants'
+import { formatBytes } from 'lib/helpers'
+import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
import {
Checkbox,
DropdownMenu,
@@ -101,7 +101,6 @@ export interface FileExplorerRowProps {
columnIndex: number
selectedItems: StorageItemWithColumn[]
openedFolders: StorageItem[]
- selectedFilePreview: (StorageItemWithColumn & { previewUrl: string | undefined }) | null
}
const FileExplorerRow: ItemRenderer<StorageItem, FileExplorerRowProps> = ({
@@ -111,11 +110,9 @@ const FileExplorerRow: ItemRenderer<StorageItem, FileExplorerRowProps> = ({
columnIndex = 0,
selectedItems = [],
openedFolders = [],
- selectedFilePreview,
}) => {
const storageExplorerStore = useStorageStore()
const {
- getFileUrl,
popColumnAtIndex,
pushOpenedFolderAtIndex,
popOpenedFoldersAtIndex,
@@ -132,8 +129,9 @@ const FileExplorerRow: ItemRenderer<StorageItem, FileExplorerRowProps> = ({
downloadFile,
downloadFolder,
selectRangeItems,
+ selectedFilePreview,
} = storageExplorerStore
- const { onCopyUrl } = useCopyUrl(storageExplorerStore.projectRef)
+ const { onCopyUrl } = useCopyUrl()
const isPublic = selectedBucket.public
const itemWithColumnIndex = { ...item, columnIndex }
@@ -217,8 +215,7 @@ const FileExplorerRow: ItemRenderer<StorageItem, FileExplorerRowProps> = ({
{
name: 'Get URL',
icon: <Clipboard size={14} strokeWidth={1} />,
- onClick: () =>
- onCopyUrl(itemWithColumnIndex.name, getFileUrl(itemWithColumnIndex)),
+ onClick: () => onCopyUrl(itemWithColumnIndex.name),
},
]
: [
@@ -229,30 +226,21 @@ const FileExplorerRow: ItemRenderer<StorageItem, FileExplorerRowProps> = ({
{
name: 'Expire in 1 week',
onClick: () =>
- onCopyUrl(
- itemWithColumnIndex.name,
- getFileUrl(itemWithColumnIndex, URL_EXPIRY_DURATION.WEEK)
- ),
+ onCopyUrl(itemWithColumnIndex.name, URL_EXPIRY_DURATION.WEEK),
},
{
name: 'Expire in 1 month',
onClick: () =>
- onCopyUrl(
- itemWithColumnIndex.name,
- getFileUrl(itemWithColumnIndex, URL_EXPIRY_DURATION.MONTH)
- ),
+ onCopyUrl(itemWithColumnIndex.name, URL_EXPIRY_DURATION.MONTH),
},
{
name: 'Expire in 1 year',
onClick: () =>
- onCopyUrl(
- itemWithColumnIndex.name,
- getFileUrl(itemWithColumnIndex, URL_EXPIRY_DURATION.YEAR)
- ),
+ onCopyUrl(itemWithColumnIndex.name, URL_EXPIRY_DURATION.YEAR),
},
{
name: 'Custom expiry',
- onClick: async () => setSelectedFileCustomExpiry(itemWithColumnIndex),
+ onClick: () => setSelectedFileCustomExpiry(itemWithColumnIndex),
},
],
},
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ItemContextMenu.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ItemContextMenu.tsx
index 89c772ab182..084290a93e1 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ItemContextMenu.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ItemContextMenu.tsx
@@ -17,7 +17,6 @@ interface ItemContextMenuProps {
const ItemContextMenu = ({ id = '' }: ItemContextMenuProps) => {
const storageExplorerStore = useStorageStore()
const {
- getFileUrl,
downloadFile,
selectedBucket,
setSelectedItemsToDelete,
@@ -25,7 +24,7 @@ const ItemContextMenu = ({ id = '' }: ItemContextMenuProps) => {
setSelectedItemsToMove,
setSelectedFileCustomExpiry,
} = storageExplorerStore
- const { onCopyUrl } = useCopyUrl(storageExplorerStore.projectRef)
+ const { onCopyUrl } = useCopyUrl()
const isPublic = selectedBucket.public
const canUpdateFiles = useCheckPermissions(PermissionAction.STORAGE_WRITE, '*')
@@ -34,7 +33,7 @@ const ItemContextMenu = ({ id = '' }: ItemContextMenuProps) => {
switch (event) {
case 'copy':
if (expiresIn !== undefined && expiresIn < 0) return setSelectedFileCustomExpiry(item)
- else return onCopyUrl(item.name, getFileUrl(item, expiresIn))
+ else return onCopyUrl(item.name, expiresIn)
case 'rename':
return setSelectedItemToRename(item)
case 'move':
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/PreviewPane.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/PreviewPane.tsx
index fb248fa7abc..0f89945c81c 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/PreviewPane.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/PreviewPane.tsx
@@ -17,27 +17,36 @@ import {
DropdownMenuTrigger,
} from 'ui'
import { URL_EXPIRY_DURATION } from '../Storage.constants'
+import { StorageItem } from '../Storage.types'
import { useCopyUrl } from './useCopyUrl'
+import { useFetchFileUrlQuery } from './useFetchFileUrlQuery'
-const PreviewFile = ({ mimeType, previewUrl }: { mimeType?: string; previewUrl?: string }) => {
- if (!mimeType || !previewUrl) {
- return (
- <SVG
- src={`${BASE_PATH}/img/file-filled.svg`}
- preProcessor={(code) =>
- code.replace(/svg/, 'svg class="mx-auto w-32 h-32 text-color-inherit opacity-75"')
- }
- />
- )
- }
- if (previewUrl === 'loading') {
+const PREVIEW_SIZE_LIMIT = 10 * 1024 * 1024 // 10MB
+
+const PreviewFile = ({ item }: { item: StorageItem }) => {
+ const storageExplorerStore = useStorageStore()
+ const { projectRef, selectedBucket } = storageExplorerStore
+
+ const { data: previewUrl, isLoading } = useFetchFileUrlQuery({
+ file: item,
+ projectRef: projectRef,
+ bucket: selectedBucket,
+ })
+
+ // if the size is not available, we set it to be greater than the max size
+ const size = +(item.metadata?.size ?? PREVIEW_SIZE_LIMIT + 1)
+ const mimeType = item.metadata?.mimetype
+
+ const isSkipped = !!mimeType && !!size && size > PREVIEW_SIZE_LIMIT
+
+ if (isLoading) {
return (
<div className="flex h-full w-full items-center justify-center text-foreground-lighter">
<Loader size={14} strokeWidth={2} className="animate-spin" />
</div>
)
}
- if (previewUrl === 'skipped') {
+ if (isSkipped) {
return (
<div className="flex h-full w-full flex-col items-center justify-center">
<SVG
@@ -52,6 +61,17 @@ const PreviewFile = ({ mimeType, previewUrl }: { mimeType?: string; previewUrl?:
</div>
)
}
+ if (!mimeType || !previewUrl) {
+ return (
+ <SVG
+ src={`${BASE_PATH}/img/file-filled.svg`}
+ preProcessor={(code) =>
+ code.replace(/svg/, 'svg class="mx-auto w-32 h-32 text-color-inherit opacity-75"')
+ }
+ />
+ )
+ }
+
if (mimeType.includes('image')) {
return (
<div
@@ -97,7 +117,6 @@ const PreviewFile = ({ mimeType, previewUrl }: { mimeType?: string; previewUrl?:
const PreviewPane = () => {
const storageExplorerStore = useStorageStore()
const {
- getFileUrl,
downloadFile,
selectedBucket,
selectedFilePreview: file,
@@ -105,7 +124,7 @@ const PreviewPane = () => {
setSelectedItemsToDelete,
setSelectedFileCustomExpiry,
} = storageExplorerStore
- const { onCopyUrl } = useCopyUrl(storageExplorerStore.projectRef)
+ const { onCopyUrl } = useCopyUrl()
const canUpdateFiles = useCheckPermissions(PermissionAction.STORAGE_WRITE, '*')
@@ -150,7 +169,7 @@ const PreviewPane = () => {
{/* Preview Thumbnail*/}
<div className="my-4 border border-overlay">
<div className="flex h-56 w-full items-center 2xl:h-72">
- <PreviewFile mimeType={mimeType} previewUrl={file.previewUrl} />
+ <PreviewFile item={file} />
</div>
</div>
@@ -200,7 +219,7 @@ const PreviewPane = () => {
<Button
type="outline"
icon={<Clipboard size={16} strokeWidth={2} />}
- onClick={() => onCopyUrl(file.name, getFileUrl(file))}
+ onClick={() => onCopyUrl(file.name)}
disabled={file.isCorrupted}
>
Get URL
@@ -220,25 +239,19 @@ const PreviewPane = () => {
<DropdownMenuContent side="bottom" align="center">
<DropdownMenuItem
key="expires-one-week"
- onClick={() =>
- onCopyUrl(file.name, getFileUrl(file, URL_EXPIRY_DURATION.WEEK))
- }
+ onClick={() => onCopyUrl(file.name, URL_EXPIRY_DURATION.WEEK)}
>
Expire in 1 week
</DropdownMenuItem>
<DropdownMenuItem
key="expires-one-month"
- onClick={() =>
- onCopyUrl(file.name, getFileUrl(file, URL_EXPIRY_DURATION.MONTH))
- }
+ onClick={() => onCopyUrl(file.name, URL_EXPIRY_DURATION.MONTH)}
>
Expire in 1 month
</DropdownMenuItem>
<DropdownMenuItem
key="expires-one-year"
- onClick={() =>
- onCopyUrl(file.name, getFileUrl(file, URL_EXPIRY_DURATION.YEAR))
- }
+ onClick={() => onCopyUrl(file.name, URL_EXPIRY_DURATION.YEAR)}
>
Expire in 1 year
</DropdownMenuItem>
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsx
index edd72f26b09..0328879006c 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsx
@@ -201,7 +201,6 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
columns={columns}
openedFolders={openedFolders}
selectedItems={selectedItems}
- selectedFilePreview={selectedFilePreview}
itemSearchString={itemSearchString}
onFilesUpload={onFilesUpload}
onSelectAllItemsInColumn={onSelectAllItemsInColumn}
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useCopyUrl.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useCopyUrl.tsx
index 9cdf41fd815..16eed0c7f2a 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useCopyUrl.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useCopyUrl.tsx
@@ -1,28 +1,57 @@
+import { useCallback } from 'react'
import { toast } from 'sonner'
import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
import { copyToClipboard } from 'lib/helpers'
+import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
+import { URL_EXPIRY_DURATION } from '../Storage.constants'
+import { fetchFileUrl } from './useFetchFileUrlQuery'
-export const useCopyUrl = (ref: string) => {
- const { data: customDomainData } = useCustomDomainsQuery({ projectRef: ref })
- const { data: settings } = useProjectSettingsV2Query({ projectRef: ref })
+export const useCopyUrl = () => {
+ const { projectRef, selectedBucket, getPathAlongOpenedFolders } = useStorageStore()
+ const { data: customDomainData } = useCustomDomainsQuery({ projectRef: projectRef })
+ const { data: settings } = useProjectSettingsV2Query({ projectRef: projectRef })
const protocol = settings?.app_config?.protocol ?? 'https'
const endpoint = settings?.app_config?.endpoint
const apiUrl = `${protocol}://${endpoint ?? '-'}`
- const onCopyUrl = (name: string, url: string | Promise<string>) => {
- const formattedUrl = Promise.resolve(url).then((url) => {
- return customDomainData?.customDomain?.status === 'active'
- ? url.replace(apiUrl, `https://${customDomainData.customDomain.hostname}`)
- : url
- })
-
- return copyToClipboard(formattedUrl, () => {
- toast.success(`Copied URL for ${name} to clipboard.`)
- })
- }
+ const getFileUrl = useCallback(
+ (fileName: string, expiresIn?: URL_EXPIRY_DURATION) => {
+ const pathToFile = getPathAlongOpenedFolders(false)
+ const formattedPathToFile = [pathToFile, fileName].join('/')
+
+ return fetchFileUrl(
+ formattedPathToFile,
+ projectRef,
+ selectedBucket.id,
+ selectedBucket.public,
+ expiresIn
+ )
+ },
+ [projectRef, selectedBucket.id, selectedBucket.public, getPathAlongOpenedFolders]
+ )
+
+ const onCopyUrl = useCallback(
+ (name: string, expiresIn?: URL_EXPIRY_DURATION) => {
+ const formattedUrl = getFileUrl(name, expiresIn).then((url) => {
+ return customDomainData?.customDomain?.status === 'active'
+ ? url.replace(apiUrl, `https://${customDomainData.customDomain.hostname}`)
+ : url
+ })
+
+ return copyToClipboard(formattedUrl, () => {
+ toast.success(`Copied URL for ${name} to clipboard.`)
+ })
+ },
+ [
+ apiUrl,
+ customDomainData?.customDomain?.hostname,
+ customDomainData?.customDomain?.status,
+ getFileUrl,
+ ]
+ )
return { onCopyUrl }
}
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useFetchFileUrlQuery.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useFetchFileUrlQuery.tsx
new file mode 100644
index 00000000000..19b5d043d3d
--- /dev/null
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useFetchFileUrlQuery.tsx
@@ -0,0 +1,57 @@
+import { UseQueryOptions, useQuery } from '@tanstack/react-query'
+import { getPublicUrlForBucketObject } from 'data/storage/bucket-object-get-public-url-mutation'
+import { signBucketObject } from 'data/storage/bucket-object-sign-mutation'
+import { Bucket } from 'data/storage/buckets-query'
+import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
+import { ResponseError } from 'types'
+import { StorageItem } from '../Storage.types'
+
+const DEFAULT_EXPIRY = 7 * 24 * 60 * 60 // in seconds, default to 1 week
+
+export const fetchFileUrl = async (
+ pathToFile: string,
+ projectRef: string,
+ bucketId: string,
+ isBucketPublic: boolean,
+ expiresIn?: number
+) => {
+ if (isBucketPublic) {
+ const data = await getPublicUrlForBucketObject({
+ projectRef: projectRef,
+ bucketId: bucketId,
+ path: pathToFile,
+ })
+ return data.publicUrl
+ } else {
+ const data = await signBucketObject({
+ projectRef: projectRef,
+ bucketId: bucketId,
+ path: pathToFile,
+ expiresIn: expiresIn ?? DEFAULT_EXPIRY,
+ })
+ return data.signedUrl
+ }
+}
+
+type UseFileUrlQueryVariables = {
+ file: StorageItem
+ projectRef: string
+ bucket: Bucket
+}
+
+export const useFetchFileUrlQuery = (
+ { file, projectRef, bucket }: UseFileUrlQueryVariables,
+ { ...options }: UseQueryOptions<string, ResponseError> = {}
+) => {
+ const { getPathAlongOpenedFolders } = useStorageStore()
+ const pathToFile = getPathAlongOpenedFolders(false)
+ const formattedPathToFile = [pathToFile, file?.name].join('/')
+
+ return useQuery({
+ queryKey: [projectRef, 'buckets', bucket.public, bucket.id, 'file', formattedPathToFile],
+ queryFn: () =>
+ fetchFileUrl(formattedPathToFile, projectRef, bucket.id, bucket.public, DEFAULT_EXPIRY),
+ staleTime: DEFAULT_EXPIRY * 1000,
+ ...options,
+ })
+}
diff --git a/apps/studio/data/storage/bucket-object-download-mutation.ts b/apps/studio/data/storage/bucket-object-download-mutation.ts
index 896e5faac4a..81d5992d219 100644
--- a/apps/studio/data/storage/bucket-object-download-mutation.ts
+++ b/apps/studio/data/storage/bucket-object-download-mutation.ts
@@ -12,7 +12,6 @@ type DownloadBucketObjectParams = {
path: string
options?: components['schemas']['DownloadObjectOptions']
}
-
export const downloadBucketObject = async (
{ projectRef, bucketId, path, options }: DownloadBucketObjectParams,
signal?: AbortSignal
diff --git a/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx b/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
index 271633b06e9..02876ca58de 100644
--- a/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
+++ b/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
@@ -35,8 +35,6 @@ import { ProjectStorageConfigResponse } from 'data/config/project-storage-config
import { getQueryClient } from 'data/query-client'
import { deleteBucketObject } from 'data/storage/bucket-object-delete-mutation'
import { downloadBucketObject } from 'data/storage/bucket-object-download-mutation'
-import { getPublicUrlForBucketObject } from 'data/storage/bucket-object-get-public-url-mutation'
-import { signBucketObject } from 'data/storage/bucket-object-sign-mutation'
import { StorageObject, listBucketObjects } from 'data/storage/bucket-objects-list-mutation'
import { Bucket } from 'data/storage/buckets-query'
import { moveStorageObject } from 'data/storage/object-move-mutation'
@@ -44,7 +42,6 @@ import { IS_PLATFORM } from 'lib/constants'
import { lookupMime } from 'lib/mime'
import Link from 'next/link'
import { Button, SONNER_DEFAULT_DURATION, SonnerProgress } from 'ui'
-import { PROJECT_ENDPOINT_PROTOCOL } from 'pages/api/constants'
type CachedFile = { id: string; fetchedAt: number; expiresIn: number; url: string }
@@ -87,7 +84,7 @@ class StorageExplorerStore {
selectedItems: StorageItemWithColumn[] = []
selectedItemsToDelete: StorageItemWithColumn[] = []
selectedItemsToMove: StorageItemWithColumn[] = []
- selectedFilePreview: (StorageItemWithColumn & { previewUrl: string | undefined }) | null = null
+ selectedFilePreview: StorageItemWithColumn | null = null
selectedFileCustomExpiry: StorageItem | undefined = undefined
private DEFAULT_OPTIONS = {
@@ -106,9 +103,6 @@ class StorageExplorerStore {
any
>
- /* FE Cacheing for file previews */
- private filePreviewCache: CachedFile[] = []
-
/* For file uploads, from 0 to 1 */
private uploadProgresses: UploadProgress[] = []
@@ -162,19 +156,6 @@ class StorageExplorerStore {
)
}
- private updateFileInPreviewCache = (fileCache: CachedFile) => {
- const updatedFilePreviewCache = this.filePreviewCache.map((file) => {
- if (file.id === fileCache.id) return fileCache
- return file
- })
- this.filePreviewCache = updatedFilePreviewCache
- }
-
- private addFileToPreviewCache = (fileCache: CachedFile) => {
- const updatedFilePreviewCache = this.filePreviewCache.concat([fileCache])
- this.filePreviewCache = updatedFilePreviewCache
- }
-
private getLocalStorageKey = () => {
return `supabase-storage-${this.projectRef}`
}
@@ -184,7 +165,7 @@ class StorageExplorerStore {
}
// Probably refactor this to ignore bucket by default
- private getPathAlongOpenedFolders = (includeBucket = true) => {
+ getPathAlongOpenedFolders = (includeBucket = true) => {
if (includeBucket) {
return this.openedFolders.length > 0
? `${this.selectedBucket.name}/${this.openedFolders.map((folder) => folder.name).join('/')}`
@@ -342,82 +323,13 @@ class StorageExplorerStore {
}
setFilePreview = async (file: StorageItemWithColumn) => {
- const size = file.metadata?.size
- const mimeType = file.metadata?.mimetype
-
- if (mimeType && size) {
- // Skip fetching of file preview if file is too big
- if (size > PREVIEW_SIZE_LIMIT) {
- this.selectedFilePreview = { ...file, previewUrl: 'skipped' }
- return
- }
-
- // Either retrieve file preview from FE cache or retrieve signed url
- this.selectedFilePreview = { ...file, previewUrl: 'loading' }
- const cachedPreview = this.filePreviewCache.find((cache) => cache.id === file.id)
-
- const fetchedAt = cachedPreview?.fetchedAt ?? null
- const expiresIn = cachedPreview?.expiresIn ?? null
- const existsInCache = fetchedAt !== null && expiresIn !== null
- const isExpired = existsInCache ? fetchedAt + expiresIn * 1000 < Date.now() : true
-
- if (!isExpired) {
- this.selectedFilePreview = { ...file, previewUrl: cachedPreview?.url }
- } else {
- const previewUrl = await this.fetchFilePreview(file.name)
- const formattedPreviewUrl = this.selectedBucket.public
- ? `${previewUrl}?t=${new Date().toISOString()}`
- : previewUrl
- this.selectedFilePreview = { ...file, previewUrl: formattedPreviewUrl }
-
- const fileCache: CachedFile = {
- id: file.id as string,
- url: previewUrl,
- expiresIn: DEFAULT_EXPIRY,
- fetchedAt: Date.now(),
- }
- if (!existsInCache) {
- this.addFileToPreviewCache(fileCache)
- } else {
- this.updateFileInPreviewCache(fileCache)
- }
- }
- } else {
- this.selectedFilePreview = { ...file, previewUrl: undefined }
- }
+ this.selectedFilePreview = file
}
closeFilePreview = () => {
this.selectedFilePreview = null
}
- getFileUrl = async (file: StorageItem, expiresIn = 0) => {
- const filePreview = this.filePreviewCache.find((cache) => cache.id === file.id)
- if (filePreview !== undefined && expiresIn === 0) {
- return filePreview.url
- } else {
- const signedUrl = await this.fetchFilePreview(file.name, expiresIn)
- try {
- const formattedUrl = new URL(signedUrl!)
- formattedUrl.searchParams.set('t', new Date().toISOString())
- const fileUrl = formattedUrl.toString()
-
- // Also save it to cache
- const fileCache: CachedFile = {
- id: file.id as string,
- url: fileUrl,
- expiresIn: DEFAULT_EXPIRY,
- fetchedAt: Date.now(),
- }
- this.addFileToPreviewCache(fileCache)
- return fileUrl
- } catch (error) {
- console.error('Failed to get file URL', error)
- return ''
- }
- }
- }
-
/* Methods that involve the storage client library */
/* Bucket CRUD */
openBucket = async (bucket: Bucket) => {
@@ -932,49 +844,11 @@ class StorageExplorerStore {
toast.dismiss(toastId)
- // Clear file preview cache if moved files exist in cache
- const idsOfItemsToMove = this.selectedItemsToMove.map((item) => item.id)
- const updatedFilePreviewCache = this.filePreviewCache.filter(
- (file) => !idsOfItemsToMove.includes(file.id)
- )
- this.filePreviewCache = updatedFilePreviewCache
-
+ // TODO: invalidate the file preview cache when moving files
await this.refetchAllOpenedFolders()
this.clearSelectedItemsToMove()
}
- private fetchFilePreview = async (fileName: string, expiresIn: number = 0) => {
- const includeBucket = false
- const pathToFile = this.getPathAlongOpenedFolders(includeBucket)
- const formattedPathToFile = pathToFile.length > 0 ? `${pathToFile}/${fileName}` : fileName
-
- if (this.selectedBucket.public) {
- try {
- const data = await getPublicUrlForBucketObject({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- path: formattedPathToFile,
- })
- return data.publicUrl
- } catch (error: any) {
- toast.error(`Failed to fetch public file preview: ${error.message}`)
- }
- } else {
- try {
- const data = await signBucketObject({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- path: formattedPathToFile,
- expiresIn: expiresIn || DEFAULT_EXPIRY,
- })
- return data.signedUrl
- } catch (error: any) {
- toast.error(`Failed to fetch signed url preview: ${error.message}`)
- }
- }
- return ''
- }
-
// the method accepts either files with column index or with prefix.
deleteFiles = async (
files: (StorageItemWithColumn & { prefix?: string })[],
@@ -1027,13 +901,6 @@ class StorageExplorerStore {
)
}, Promise.resolve())
- // Clear file preview cache if deleted files exist in cache
- const idsOfFilesDeleted = files.map((file) => file.id)
- const updatedFilePreviewCache = this.filePreviewCache.filter(
- (file) => !idsOfFilesDeleted.includes(file.id)
- )
- this.filePreviewCache = updatedFilePreviewCache
-
if (!isDeleteFolder) {
// If parent folders are empty, reinstate .emptyFolderPlaceholder to persist them
const parentFolderPrefixes = uniq(
@@ -1310,11 +1177,7 @@ class StorageExplorerStore {
toast.success(`Successfully renamed "${originalName}" to "${newName}"`)
- // Clear file preview cache if the renamed file exists in the cache
- const updatedFilePreviewCache = this.filePreviewCache.filter(
- (fileCache) => fileCache.id !== file.id
- )
- this.filePreviewCache = updatedFilePreviewCache
+ // TODO: Should we invalidate the file preview cache when renaming files?
if (this.selectedFilePreview?.name === originalName) {
const { previewUrl, ...fileData } = file as any
@@ -1646,12 +1509,7 @@ class StorageExplorerStore {
}
await this.refetchAllOpenedFolders()
- // Clear file preview cache if the moved file exists in the cache
- const fileIds = files.map((file) => file.id)
- const updatedFilePreviewCache = this.filePreviewCache.filter(
- (fileCache) => !fileIds.includes(fileCache.id)
- )
- this.filePreviewCache = updatedFilePreviewCache
+ // TODO: Should we invalidate the file preview cache when renaming folders?
} catch (e: any) {
toast.error(`Failed to rename folder to ${newName}: ${e.message}`, {
id: toastId,
@@ -1841,6 +1699,7 @@ class StorageExplorerStore {
setSelectedItemToRename = (file: { name: string; columnIndex: number }) => {
this.updateRowStatus(file.name, STORAGE_ROW_STATUS.EDITING, file.columnIndex)
}
+
private updateRowStatus = (
name: string,
status: STORAGE_ROW_STATUS,