Line data Source code
1 : import { useI18n } from 'vue-i18n'
2 :
3 : import { downloadFile, downloadFileAsBlob } from '@/base/common/downloadUtil'
4 : import { reportError } from '@comfyorg/telemetry/reportError'
5 : import { useToast } from '@/components/ui/toast/toastStore'
6 :
7 : interface DirectAssetDownload {
8 : mode: 'direct'
9 : url: string
10 : filename: string
11 : }
12 :
13 : export interface FetchedAssetDownload {
14 : mode: 'fetch'
15 : url: string
16 : filename: string
17 : fetch?: (url: string) => Promise<Response>
18 : preferResponseFilename?: boolean
19 : }
20 :
21 : export type AssetDownload = DirectAssetDownload | FetchedAssetDownload
22 :
23 5269 : export function useAssetDownload() {
24 5269 : const { t } = useI18n()
25 5269 : const toast = useToast()
26 :
27 0 : async function downloadFiles(files: AssetDownload[]): Promise<void> {
28 0 : const pending = files.map((file) => {
29 0 : try {
30 0 : if (file.mode === 'direct') {
31 0 : downloadFile(file.url, file.filename)
32 0 : return Promise.resolve()
33 : }
34 0 : return downloadFileAsBlob(file.url, {
35 : filename: file.filename,
36 : fetch: file.fetch,
37 : preferResponseFilename: file.preferResponseFilename
38 : })
39 : } catch (error) {
40 0 : return Promise.reject(error)
41 : }
42 : })
43 : const results = await Promise.allSettled(pending)
44 0 : const failures = results.flatMap((result, index) =>
45 : result.status === 'rejected'
46 : ? [{ cause: result.reason, filename: files[index].filename }]
47 : : []
48 : )
49 0 : const successCount = files.length - failures.length
50 :
51 0 : if (successCount > 0) {
52 0 : toast.success(t('g.success'), {
53 : description: t('mediaAsset.selection.downloadsStarted', successCount),
54 : duration: 2000
55 : })
56 : }
57 :
58 0 : if (failures.length > 0) {
59 0 : for (const failure of failures) {
60 0 : reportError(failure.cause, {
61 : surface: 'assets',
62 : errorType: 'error_downloading_asset',
63 : context: { filename: failure.filename }
64 : })
65 : }
66 0 : toast.error(t('g.error'), {
67 : description: t('progressToast.downloadsFailed', failures.length)
68 : })
69 : }
70 : }
71 :
72 5269 : return { downloadFiles }
73 : }
|