LCOV - code coverage report
Current view: top level - src/base/common - downloadUtil.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 44.7 % 47 21
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : /**
       2              :  * Utility functions for downloading files
       3              :  */
       4              : import { t } from '@/i18n'
       5              : // oxlint-disable-next-line comfy/no-restricted-paths
       6              : import { isCloud } from '@/platform/distribution/types'
       7              : import { useToast } from '@/components/ui/toast/toastStore'
       8              : import { getErrorMessage } from '@comfyorg/shared-frontend-utils/errorUtil'
       9              : 
      10              : // Constants
      11         2356 : const DEFAULT_DOWNLOAD_FILENAME = 'download.png'
      12              : 
      13              : /**
      14              :  * Trigger a download by creating a temporary anchor element
      15              :  * @param href - The URL or blob URL to download
      16              :  * @param filename - The filename to suggest to the browser
      17              :  */
      18           11 : function triggerLinkDownload(href: string, filename: string): void {
      19           11 :   const link = document.createElement('a')
      20           11 :   link.href = href
      21           11 :   link.download = filename
      22           11 :   link.style.display = 'none'
      23              : 
      24           11 :   document.body.appendChild(link)
      25           11 :   link.click()
      26           11 :   document.body.removeChild(link)
      27              : }
      28              : 
      29              : /**
      30              :  * Download a file from a URL by creating a temporary anchor element
      31              :  * @param url - The URL of the file to download (must be a valid URL string)
      32              :  * @param filename - Optional filename override (will use URL filename or default if not provided)
      33              :  * @throws {Error} If the URL is invalid or empty
      34              :  */
      35            4 : export function downloadFile(url: string, filename?: string): void {
      36            4 :   if (!url || typeof url !== 'string' || url.trim().length === 0) {
      37            0 :     throw new Error('Invalid URL provided for download')
      38              :   }
      39              : 
      40              :   const inferredFilename =
      41              :     filename || extractFilenameFromUrl(url) || DEFAULT_DOWNLOAD_FILENAME
      42              : 
      43              :   if (isCloud) {
      44              :     // Assets from cross-origin (e.g., GCS) cannot be downloaded this way
      45              :     void downloadFileAsBlob(url, { filename: inferredFilename }).catch(
      46              :       (error) => {
      47              :         console.error('Failed to download file', error)
      48              :       }
      49              :     )
      50              :     return
      51              :   }
      52              : 
      53            4 :   triggerLinkDownload(url, inferredFilename)
      54              : }
      55              : 
      56              : /**
      57              :  * Download a Blob by creating a temporary object URL and anchor element
      58              :  * @param filename - The filename to suggest to the browser
      59              :  * @param blob - The Blob to download
      60              :  */
      61            7 : export function downloadBlob(filename: string, blob: Blob): void {
      62            7 :   const url = URL.createObjectURL(blob)
      63              : 
      64            7 :   triggerLinkDownload(url, filename)
      65              : 
      66              :   // Revoke on the next microtask to give the browser time to start the download
      67            7 :   queueMicrotask(() => URL.revokeObjectURL(url))
      68              : }
      69              : 
      70              : /**
      71              :  * Extract filename from a URL's query parameters
      72              :  * @param url - The URL to extract filename from
      73              :  * @returns The extracted filename or null if not found
      74              :  */
      75         2356 : const extractFilenameFromUrl = (url: string): string | null => {
      76            4 :   try {
      77              :     const urlObj = new URL(url, window.location.origin)
      78            4 :     return urlObj.searchParams.get('filename')
      79              :   } catch {
      80            0 :     return null
      81              :   }
      82              : }
      83              : 
      84              : /**
      85              :  * Extract filename from Content-Disposition header
      86              :  * Handles both simple format: attachment; filename="name.png"
      87              :  * And RFC 5987 format: attachment; filename="fallback.png"; filename*=UTF-8''encoded%20name.png
      88              :  * @param header - The Content-Disposition header value
      89              :  * @returns The extracted filename or null if not found
      90              :  */
      91            0 : export function extractFilenameFromContentDisposition(
      92              :   header: string | null
      93              : ): string | null {
      94            0 :   if (!header) return null
      95              : 
      96              :   // Try RFC 5987 extended format first (filename*=UTF-8''...)
      97            0 :   const extendedMatch = header.match(/filename\*=UTF-8''([^;]+)/i)
      98            0 :   if (extendedMatch?.[1]) {
      99            0 :     try {
     100            0 :       return decodeURIComponent(extendedMatch[1])
     101              :     } catch {
     102              :       // Fall through to simple format
     103              :     }
     104              :   }
     105              : 
     106              :   // Try simple quoted format: filename="..."
     107            0 :   const quotedMatch = header.match(/filename="([^"]+)"/i)
     108            0 :   if (quotedMatch?.[1]) {
     109            0 :     return quotedMatch[1]
     110              :   }
     111              : 
     112              :   // Try unquoted format: filename=...
     113            0 :   const unquotedMatch = header.match(/filename=([^;\s]+)/i)
     114            0 :   if (unquotedMatch?.[1]) {
     115            0 :     return unquotedMatch[1]
     116              :   }
     117              : 
     118            0 :   return null
     119              : }
     120              : 
     121              : /**
     122              :  * Fetch a URL and return its body as a Blob.
     123              :  * Shared by download and open-in-new-tab cloud paths.
     124              :  */
     125            0 : async function fetchAsBlob(
     126              :   url: string,
     127              :   fetchFile: (url: string) => Promise<Response> = fetch
     128              : ): Promise<Response> {
     129            0 :   const response = await fetchFile(url)
     130            0 :   if (!response.ok) {
     131            0 :     throw new Error(`Failed to fetch ${url}: ${response.status}`)
     132              :   }
     133            0 :   return response
     134              : }
     135              : 
     136            0 : export async function downloadFileAsBlob(
     137              :   url: string,
     138              :   {
     139              :     filename,
     140              :     fetch: fetchFile = fetch,
     141              :     preferResponseFilename = true
     142              :   }: {
     143              :     filename?: string
     144              :     fetch?: (url: string) => Promise<Response>
     145              :     preferResponseFilename?: boolean
     146              :   } = {}
     147              : ): Promise<void> {
     148            0 :   const fallbackFilename =
     149              :     filename || extractFilenameFromUrl(url) || DEFAULT_DOWNLOAD_FILENAME
     150            0 :   const response = await fetchAsBlob(url, fetchFile)
     151              : 
     152              :   // Try to get filename from Content-Disposition header (set by backend)
     153              :   const contentDisposition = response.headers.get('Content-Disposition')
     154            0 :   const headerFilename =
     155              :     extractFilenameFromContentDisposition(contentDisposition)
     156              : 
     157            0 :   const blob = await response.blob()
     158            0 :   downloadBlob(
     159              :     preferResponseFilename
     160              :       ? (headerFilename ?? fallbackFilename)
     161              :       : fallbackFilename,
     162              :     blob
     163              :   )
     164              : }
     165              : 
     166              : /**
     167              :  * Open a file URL in a new browser tab.
     168              :  * On cloud, fetches the resource as a blob first to avoid GCS redirects
     169              :  * that would trigger an auto-download instead of displaying the file.
     170              :  *
     171              :  * Opens the tab synchronously to preserve the user-gesture context
     172              :  * (browsers block window.open after an await), then navigates it to
     173              :  * the blob URL once the fetch completes.
     174              :  */
     175              : const RENDERABLE_MEDIA_TYPES = new Set([
     176              :   'image/apng',
     177              :   'image/avif',
     178              :   'image/bmp',
     179              :   'image/gif',
     180              :   'image/jpeg',
     181              :   'image/png',
     182              :   'image/webp',
     183              :   'audio/mpeg',
     184              :   'audio/ogg',
     185              :   'audio/wav',
     186              :   'audio/webm',
     187              :   'video/mp4',
     188              :   'video/ogg',
     189              :   'video/webm'
     190              : ])
     191              : 
     192              : function isRenderableMediaType(blobType: string): boolean {
     193              :   return RENDERABLE_MEDIA_TYPES.has(blobType.split(';')[0].trim().toLowerCase())
     194              : }
     195              : 
     196            2 : export async function openFileInNewTab(url: string): Promise<void> {
     197              :   if (!isCloud) {
     198            2 :     window.open(url, '_blank')
     199              :     return
     200              :   }
     201              : 
     202              :   // Open immediately to preserve user-gesture activation.
     203              :   const tab = window.open('', '_blank')
     204              : 
     205              :   try {
     206              :     const response = await fetchAsBlob(url)
     207              :     const fetched = await response.blob()
     208              :     const blob = isRenderableMediaType(fetched.type)
     209              :       ? fetched
     210              :       : new Blob([fetched], { type: 'application/octet-stream' })
     211              :     const blobUrl = URL.createObjectURL(blob)
     212              : 
     213              :     if (tab && !tab.closed) {
     214              :       tab.location.href = blobUrl
     215              :       // Revoke after the tab has had time to load the blob.
     216              :       setTimeout(() => URL.revokeObjectURL(blobUrl), 60_000)
     217              :     } else {
     218              :       URL.revokeObjectURL(blobUrl)
     219              :     }
     220              :   } catch (error) {
     221              :     tab?.close()
     222              :     console.error('Failed to open image:', error)
     223              :     useToast().warning(
     224              :       t('toastMessages.errorOpenImage', {
     225              :         error: getErrorMessage(error) ?? t('g.unknownError')
     226              :       })
     227              :     )
     228              :   }
     229              : }
        

Generated by: LCOV version 2.0-1