From 8f99b01825d670ee00abed867bebb4b2121d86bb Mon Sep 17 00:00:00 2001 From: Wing-Kam Wong Date: Thu, 9 Feb 2023 14:35:18 +0800 Subject: [PATCH] refactor(nc-gui): getPossibleAttachmentSrc & openAttachment --- packages/nc-gui/composables/useAttachment.ts | 41 +++++++++++--------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/packages/nc-gui/composables/useAttachment.ts b/packages/nc-gui/composables/useAttachment.ts index dc46ad7f86..637c2666a4 100644 --- a/packages/nc-gui/composables/useAttachment.ts +++ b/packages/nc-gui/composables/useAttachment.ts @@ -1,34 +1,39 @@ -import fileNotFoundImgSrc from '~/assets/img/file-not-found.png' +import { mimeTypes, openLink, useGlobal } from '#imports' const useAttachment = () => { const { appInfo } = useGlobal() - const getAttachmentSrc = (item: Record) => { + const getPossibleAttachmentSrc = (item: Record) => { + const res: string[] = [] + if (item?.path) res.push(`${appInfo.value.ncSiteUrl}/${item.path}`) + if (item?.url) res.push(item.url) + return res + } + + const getAttachmentSrc = async (item: Record) => { if (item?.data) { return item.data - } else if (item?.path) { - return `${appInfo.value.ncSiteUrl}/${item.path}` - } else if (item?.url) { - return item.url } - return fileNotFoundImgSrc + const sources = getPossibleAttachmentSrc(item) + const mimeType = mimeTypes[item?.mimetype?.split('/')?.pop() || 'txt'] + for (const source of sources) { + // test if the source is accessible or not + const res = await fetch(source) + if (res.ok && res.headers.get('Content-Type') === mimeType) { + return source + } + } + return null } - // try `${appInfo.value.ncSiteUrl}/${item.path}` - // if it fails -> try item.url - // if it fails -> use default image - const showFallback = async (evt: any, item: Record) => { - const possibleSources = [`${appInfo.value.ncSiteUrl}/${item.path}`, item.url, fileNotFoundImgSrc] - evt.onerror = null - const i = possibleSources.indexOf(evt.target.getAttribute('src')) - if (i === -1) return - evt.target.src = possibleSources[i + 1] + const openAttachment = async (item: Record) => { + openLink(await getAttachmentSrc(item)) } return { getAttachmentSrc, - fileNotFoundImgSrc, - showFallback, + getPossibleAttachmentSrc, + openAttachment, } }