wip: save file

This commit is contained in:
zzs 2025-03-21 18:52:41 +08:00
parent 261932cb84
commit 68c77b35d7

View File

@ -1,43 +1,180 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useEventListener } from '@vueuse/core'
import axios from 'axios'
import { IFrame } from '@/components/IFrame'
import { isInIframe } from '@/utils/iframe'
// import { useMessage } from '@/hooks/web/useMessage'
import { useMessage } from '@/hooks/web/useMessage'
import { uploadOneFile } from '@/api/base/upload'
import { initFilePreviewUrl } from '@/utils/file/preview'
import { getConfigKey } from '@/api/infra/config'
import type { FileDO } from '@/types/axios'
import { useGlobSetting } from '@/hooks/setting'
import { getAccessToken } from '@/utils/auth'
defineOptions({ name: 'BookmarkReplace' })
const isEmbed = isInIframe()
const globSetting = useGlobSetting()
const previewUrl = ref<string | undefined>(undefined)
const frameComponent = ref<{ frameRef: HTMLIFrameElement } | null>(null)
// const { createMessage } = useMessage()
const { createMessage } = useMessage()
const wopi_client = ref(undefined)
const wopi_server = ref(undefined)
const editStatus = ref<{ Modified: boolean }>({ Modified: false })
const currentEditFile = ref<FileDO | undefined>(undefined)
onMounted(async () => {
wopi_client.value = await getConfigKey('wopi_client_addr')
wopi_server.value = await getConfigKey('wopi_server_ip_addr')
/**
* 接收消息
*/
useEventListener(window, 'message', async (e: MessageEvent) => {
logEvent(e)
const ActionId = e.data.ActionId
let data: any = null
if (typeof e.data === 'string')
data = JSON.parse(e.data)
if (typeof e.data === 'object')
data = e.data
const ActionId = data.ActionId
const MessageId = data.MessageId
// Event
switch (ActionId) {
case 'FILE_BINARY':
case 'OPEN_FILE':
await handleFileBinary(e)
break
}
console.warn(`MessageId:${MessageId}`)
// WOPI Client
switch (MessageId) {
//
case 'Doc_ModifiedStatus':
handleUpdateModifiedStatus(e)
break
//
case 'UI_Save':
console.warn('UI_Save')
handleUserSaveOp()
break
}
})
})
/**
* 更新是否编辑状态
* 保存后会更新是否编辑为否正常编辑后会更新是否编辑为是
* 用于区分是否要向第三方发送保存文件的回调
* @param e
*/
function handleUpdateModifiedStatus(e: MessageEvent) {
editStatus.value.Modified = JSON.parse(e.data).Values.Modified
}
let pollingInterval: NodeJS.Timeout | null = null
let lastCallTime: number | null = null
async function handleUserSaveOp() {
console.warn('handleUserSaveOp')
// 1:
if (!editStatus.value.Modified) {
//
downloadAndSendCurrentEditFile()
return
}
// 2: /
//
lastCallTime = Date.now()
//
if (pollingInterval) {
clearInterval(pollingInterval)
pollingInterval = null
}
//
pollingInterval = setInterval(() => {
// 2a:
if (!editStatus.value.Modified) {
downloadAndSendCurrentEditFile()
cleanup()
return
}
// 2b: 10
const currentTime = Date.now()
if (lastCallTime && currentTime - lastCallTime >= 10000) {
createMessage.error('保存操作执行超时!')
cleanup()
}
}, 500) // 500ms
}
//
function cleanup() {
if (pollingInterval) {
clearInterval(pollingInterval)
pollingInterval = null
}
lastCallTime = null
}
/**
* 下载当前编辑的文件发送给调用者
*/
async function downloadAndSendCurrentEditFile() {
console.warn('downloadAndSendCurrentEditFile')
if (!currentEditFile.value)
return
try {
// 1. responseType: 'arraybuffer'
const response = await axios.get(`${globSetting.apiUrl}/infra/file/download/${currentEditFile.value.id}`, {
responseType: 'arraybuffer', // [!code focus]
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
})
// 2.
if (response.status !== 200)
createMessage.error(`请求失败,状态码:${response.status}`)
// 3. ArrayBuffer
const arrayBuffer: ArrayBuffer = response.data
sendMessageToCaller({
ActionId: 'SAVE_FILE',
Payload: {
name: currentEditFile.value.name,
buffer: arrayBuffer,
},
})
}
catch (error) {
console.error('文件下载失败:', error)
createMessage.error('文件下载失败,请查看控制台日志')
throw error
}
}
/**
* 第三方上传文件
* @param e
*/
async function handleFileBinary(e: MessageEvent) {
const { name, type, buffer } = e.data.Payload
const blob = new Blob([buffer], { type })
@ -45,15 +182,45 @@ async function handleFileBinary(e: MessageEvent) {
filename: name,
file: new File([blob], name, { type }),
})
const fileId = uploadResult.data.data.id
previewUrl.value = await initFilePreviewUrl(fileId, wopi_client.value, wopi_server.value)
currentEditFile.value = uploadResult.data.data as FileDO
previewUrl.value = await initFilePreviewUrl(currentEditFile.value.id, wopi_client.value, wopi_server.value)
}
/**
* 发送消息给WopiClient
* 用于执行书签相关操作
*/
// function sendMessageToWopiClient(data: any) {
// if (!frameComponent.value?.frameRef.contentWindow)
// createMessage.error('WOPI Client iframe ')
// try {
// frameComponent.value?.frameRef.contentWindow?.postMessage(data, '*')
// }
// catch (e) {
// console.error(e)
// createMessage.error(``)
// }
// }
/**
* 发送消息给第三方调用者
* 用于转发部分WopiClient回调
*/
function sendMessageToCaller(data: any) {
try {
const targetWindow = window.parent
targetWindow.postMessage(data, '*')
}
catch (e) {
console.error(e)
createMessage.error(`消息发送失败,查看控制台日志!`)
}
}
function logEvent(e: MessageEvent) {
console.log('=============receive message start=======')
console.log(e.data)
console.log(e.origin)
console.log('=============receive message end==========')
}
</script>
@ -62,7 +229,7 @@ function logEvent(e: MessageEvent) {
<div class="flex flex-col" :class="{ 'p-2 pt-4': !isEmbed }">
<div class="w-full flex flex-row" :class="{ 'h-[calc(100vh)]': isEmbed, 'h-[calc(100vh-105px)]': !isEmbed }">
<div class="w-full flex flex-row bg-white dark:bg-black">
<i-frame v-if="previewUrl" class="w-full bg-white dark:bg-black" :src="previewUrl" :height="isEmbed ? 'calc(100vh)' : 'calc(100vh) - 105px'" />
<i-frame v-if="previewUrl" ref="frameComponent" class="w-full bg-white dark:bg-black" :src="previewUrl" :height="isEmbed ? 'calc(100vh)' : 'calc(100vh) - 105px'" />
</div>
</div>
</div>