Line data Source code
1 : import {
2 : findOutputAsset,
3 : isAssetPreviewSupported
4 : } from '@/platform/assets/utils/assetPreviewUtil'
5 : import { api } from '@/scripts/api'
6 : import { getFilenameDetails, getPathDetails } from '@/utils/formatUtil'
7 :
8 : import type { FetchedAssetDownload } from '@/platform/assets/composables/useAssetDownload'
9 : import type { ReplyAsset } from './replyAssets'
10 :
11 0 : function preserveExtension(name: string, filename: string): string {
12 0 : const { suffix } = getFilenameDetails(filename)
13 0 : return name.includes('.') || suffix === null ? name : `${name}.${suffix}`
14 : }
15 :
16 0 : async function displayFilename(asset: ReplyAsset): Promise<string> {
17 0 : const fallback = preserveExtension(
18 : asset.label ?? asset.filename,
19 : asset.filename
20 : )
21 0 : if (!isAssetPreviewSupported()) return fallback
22 0 : const record = await findOutputAsset(asset.filename).catch(() => undefined)
23 0 : const name = record && getPathDetails(record.name).fullFilename
24 0 : return name ? preserveExtension(name, asset.filename) : fallback
25 : }
26 :
27 : /** Authenticates only the exact same-origin API view route; every other URL is fetched without credentials. */
28 0 : export async function resolveReplyAssetDownload(
29 : asset: ReplyAsset
30 : ): Promise<FetchedAssetDownload> {
31 0 : const candidate = new URL(asset.url, window.location.origin)
32 0 : const apiBase = new URL(api.apiURL(''), window.location.origin)
33 0 : const viewPath = `${apiBase.pathname.replace(/\/$/, '')}/view`
34 0 : const trusted =
35 : candidate.origin === apiBase.origin && candidate.pathname === viewPath
36 0 : return {
37 : url: trusted
38 : ? `${candidate.pathname.slice(apiBase.pathname.length)}${candidate.search}`
39 : : asset.url,
40 : filename: await displayFilename(asset),
41 : fetch: trusted
42 : ? (url: string) => api.fetchApi(url)
43 : : (url: string) => fetch(url, { credentials: 'omit' }),
44 : mode: 'fetch',
45 : preferResponseFilename: false
46 : }
47 : }
|