refactor: modularize frontend flows

This commit is contained in:
Lan committed 2026-06-03 02:01:57 +08:00
1 parent 9300607f96
commit a11e7900b4
85 files changed
+4654 -4363

No files matched your search

+2 -74
View File
@@ -1,74 +1,2 @@
import axios from 'axios'
import { TIME_CONSTANTS } from '@/constants'
// 从环境变量中获取 API 基础 URL
const baseURL =
import.meta.env.MODE === 'production'
? import.meta.env.VITE_API_BASE_URL_PROD
: import.meta.env.VITE_API_BASE_URL_DEV
// 确保 baseURL 是一个有效的字符串
const sanitizedBaseURL = typeof baseURL === 'string' ? baseURL : ''
// 创建 axios 实例
const api = axios.create({
baseURL: sanitizedBaseURL,
timeout: TIME_CONSTANTS.REQUEST_TIMEOUT, // 30秒超时
headers: {
'Content-Type': 'application/json'
}
})
// 请求拦截器
api.interceptors.request.use(
(config) => {
// 从 localStorage 获取 token
const token = localStorage.getItem('token')
if (token) {
config.headers['Authorization'] = `Bearer ${token}`
}
// 确保 URL 是有效的
if (config.url && !config.url.startsWith('http')) {
config.url = `${sanitizedBaseURL}/${config.url.replace(/^\//, '')}`
}
return config
},
(error) => {
return Promise.reject(error)
}
)
// 响应拦截器
api.interceptors.response.use(
(response) => {
return response.data
},
(error) => {
// 处理错误响应
if (error.response) {
const { status } = error.response
switch (status) {
case 401:
localStorage.removeItem('token')
// 使用 router 进行导航而不是直接修改 location
if (window.location.hash !== '#/login') {
window.location.href = '/#/login'
}
break
case 403:
case 404:
case 500:
default:
// 错误信息通过Promise.reject传递给调用方处理
break
}
} else if (error.request) {
// 网络错误,通过Promise.reject传递给调用方处理
} else {
// 请求配置错误,通过Promise.reject传递给调用方处理
}
return Promise.reject(error)
}
)
export default api
export { apiBaseURL, rawApiClient } from '@/services/client'
export { default } from '@/services/client'
+26
View File
@@ -0,0 +1,26 @@
import { STORAGE_KEYS } from '@/constants'
export function readStoredAdminPassword(): string {
return localStorage.getItem(STORAGE_KEYS.ADMIN_PASSWORD) || ''
}
export function writeStoredAdminPassword(password: string) {
localStorage.setItem(STORAGE_KEYS.ADMIN_PASSWORD, password)
}
export function readStoredToken(): string {
return localStorage.getItem(STORAGE_KEYS.TOKEN) || ''
}
export function writeStoredToken(token: string) {
localStorage.setItem(STORAGE_KEYS.TOKEN, token)
}
export function clearStoredAuth() {
localStorage.removeItem(STORAGE_KEYS.ADMIN_PASSWORD)
localStorage.removeItem(STORAGE_KEYS.TOKEN)
}
export function clearStoredToken() {
localStorage.removeItem(STORAGE_KEYS.TOKEN)
}
+40
View File
@@ -0,0 +1,40 @@
export const getClipboardFile = (items: DataTransferItemList): File | null => {
for (let index = 0; index < items.length; index++) {
const item = items[index]
if (item.kind !== 'file') {
continue
}
const file = item.getAsFile()
if (file) {
return file
}
}
return null
}
export type TextInsertionInput = {
text: string
insertText: string
selectionStart: number
selectionEnd: number
}
export type TextInsertionResult = {
value: string
cursor: number
}
export const insertTextAtSelection = ({
text,
insertText,
selectionStart,
selectionEnd
}: TextInsertionInput): TextInsertionResult => {
const beforeSelection = text.substring(0, selectionStart)
const afterSelection = text.substring(selectionEnd)
return {
value: beforeSelection + insertText + afterSelection,
cursor: selectionStart + insertText.length
}
}
+45 -50
View File
@@ -2,11 +2,15 @@
* 剪贴板工具函数
*/
import { useAlertStore } from '@/stores/alertStore'
import { buildRetrieveUrl, buildWgetCommand } from '@/utils/share-url'
type CopyNotifyType = 'success' | 'error'
interface CopyOptions {
successMsg?: string
errorMsg?: string
showMsg?: boolean
notify?: (message: string, type: CopyNotifyType) => void
}
/**
@@ -19,13 +23,24 @@ export const copyToClipboard = async (
text: string,
options: CopyOptions = {}
): Promise<boolean> => {
const { successMsg = '复制成功', errorMsg = '复制失败,请手动复制', showMsg = true } = options
const alertStore = useAlertStore()
const {
successMsg = '复制成功',
errorMsg = '复制失败,请手动复制',
showMsg = true,
notify
} = options
const showCopyMessage = (message: string, type: CopyNotifyType) => {
if (showMsg) {
notify?.(message, type)
}
}
try {
// 优先使用 Clipboard API
if (document.hasFocus() && navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(text)
if (showMsg) alertStore.showAlert(successMsg, 'success')
showCopyMessage(successMsg, 'success')
return true
}
// 后备方案:使用传统的复制方法
@@ -38,14 +53,14 @@ export const copyToClipboard = async (
const success = document.execCommand('copy')
document.body.removeChild(textarea)
if (success) {
if (showMsg) alertStore.showAlert(successMsg, 'success')
showCopyMessage(successMsg, 'success')
return true
} else {
throw new Error('execCommand copy failed')
}
} catch (err) {
console.error('复制失败:', err)
if (showMsg) alertStore.showAlert(errorMsg, 'error')
showCopyMessage(errorMsg, 'error')
return false
}
}
@@ -55,11 +70,15 @@ export const copyToClipboard = async (
* @param code 取件码
* @returns Promise<boolean> 是否复制成功
*/
export const copyRetrieveLink = async (code: string): Promise<boolean> => {
const link = `${window.location.origin}/#/?code=${code}`
export const copyRetrieveLink = async (
code: string,
options: Pick<CopyOptions, 'notify' | 'showMsg'> = {}
): Promise<boolean> => {
const link = buildRetrieveUrl(code)
return copyToClipboard(link, {
successMsg: '取件链接已复制到剪贴板',
errorMsg: '复制失败,请手动复制取件链接'
errorMsg: '复制失败,请手动复制取件链接',
...options
})
}
@@ -68,50 +87,26 @@ export const copyRetrieveLink = async (code: string): Promise<boolean> => {
* @param code 取件码
* @returns Promise<boolean> 是否复制成功
*/
export const copyRetrieveCode = async (code: string): Promise<boolean> => {
export const copyRetrieveCode = async (
code: string,
options: Pick<CopyOptions, 'notify' | 'showMsg'> = {}
): Promise<boolean> => {
return copyToClipboard(code, {
successMsg: '取件码已复制到剪贴板',
errorMsg: '复制失败,请手动复制取件码'
errorMsg: '复制失败,请手动复制取件码',
...options
})
}
const baseUrl = window.location.origin + '/'
export const copyWgetCommand = (retrieveCode: string, fileName: string) => {
const command = `wget ${baseUrl}share/select?code=${retrieveCode} -O "${fileName}"`
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard
.writeText(command)
.then(() => {
console.log('命令已复制到剪贴板!')
})
.catch((err) => {
console.error('复制失败,使用回退方法:', err)
fallbackCopyTextToClipboard(command)
})
} else {
console.warn('Clipboard API 不可用,使用回退方法。')
fallbackCopyTextToClipboard(command)
}
}
function fallbackCopyTextToClipboard(command: string) {
const textArea = document.createElement('textarea')
textArea.value = command
textArea.style.position = 'fixed' // 避免滚动
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
try {
const successful = document.execCommand('copy')
console.log('回退复制操作成功:', successful)
if (document.hasFocus() && navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(command)
} else {
console.error('回退复制操作失败')
}
} catch (err) {
console.error('回退复制操作失败:', err)
}
document.body.removeChild(textArea)
export const copyWgetCommand = (
retrieveCode: string,
fileName: string,
options: Pick<CopyOptions, 'notify' | 'showMsg'> = {}
) => {
const command = buildWgetCommand(retrieveCode, fileName)
void copyToClipboard(command, {
successMsg: '命令已复制到剪贴板',
errorMsg: '复制失败,请手动复制命令',
...options
})
}
+23 -31
View File
@@ -1,6 +1,7 @@
/**
* 通用工具函数
*/
import type { ApiErrorPayload } from '@/types'
/**
* 格式化时间戳为可读格式
@@ -74,36 +75,6 @@ export function formatDuration(seconds: number, t?: (key: string) => string): st
return `${seconds}${secondName}`
}
/**
* 复制文本到剪贴板
* @param text 要复制的文本
* @returns Promise<boolean> 是否复制成功
*/
export async function copyToClipboard(text: string): Promise<boolean> {
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text)
return true
} else {
// 降级方案
const textArea = document.createElement('textarea')
textArea.value = text
textArea.style.position = 'fixed'
textArea.style.left = '-999999px'
textArea.style.top = '-999999px'
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
const result = document.execCommand('copy')
textArea.remove()
return result
}
} catch (error) {
console.error('Copy failed:', error)
return false
}
}
/**
* 防抖函数
* @param func 要防抖的函数
@@ -241,4 +212,25 @@ export function isMobile(): boolean {
*/
export function formatNumber(num: number): string {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
}
type ErrorWithResponse = {
response?: {
data?: ApiErrorPayload
}
message?: string
}
export function getErrorMessage(error: unknown, fallback: string): string {
if (!error || typeof error !== 'object') {
return fallback
}
const errorWithResponse = error as ErrorWithResponse
return (
errorWithResponse.response?.data?.detail ||
errorWithResponse.response?.data?.message ||
errorWithResponse.message ||
fallback
)
}
+107
View File
@@ -0,0 +1,107 @@
import type { ConfigState } from '@/types'
export type FileSizeUnit = 'KB' | 'MB' | 'GB'
export type SaveTimeUnit = '秒' | '分' | '时' | '天'
export type FileSizeForm = {
value: number
unit: FileSizeUnit
}
export type SaveTimeForm = {
value: number
unit: SaveTimeUnit
}
const FILE_SIZE_UNITS: Record<FileSizeUnit, number> = {
KB: 1024,
MB: 1024 * 1024,
GB: 1024 * 1024 * 1024
}
const SAVE_TIME_UNITS: Record<SaveTimeUnit, number> = {
秒: 1,
分: 60,
时: 3600,
天: 86400
}
export function bytesToFileSizeForm(bytes: number): FileSizeForm {
if (bytes >= FILE_SIZE_UNITS.GB) {
return {
value: Math.round(bytes / FILE_SIZE_UNITS.GB),
unit: 'GB'
}
}
if (bytes >= FILE_SIZE_UNITS.MB) {
return {
value: Math.round(bytes / FILE_SIZE_UNITS.MB),
unit: 'MB'
}
}
return {
value: Math.round(bytes / FILE_SIZE_UNITS.KB),
unit: 'KB'
}
}
export function fileSizeFormToBytes(value: number, unit: FileSizeUnit): number {
return value * FILE_SIZE_UNITS[unit]
}
export function secondsToSaveTimeForm(seconds: number): SaveTimeForm {
if (seconds === 0) {
return {
value: 7,
unit: '天'
}
}
if (seconds % SAVE_TIME_UNITS.天 === 0 && seconds >= SAVE_TIME_UNITS.天) {
return {
value: seconds / SAVE_TIME_UNITS.天,
unit: '天'
}
}
if (seconds % SAVE_TIME_UNITS.时 === 0 && seconds >= SAVE_TIME_UNITS.时) {
return {
value: seconds / SAVE_TIME_UNITS.时,
unit: '时'
}
}
if (seconds % SAVE_TIME_UNITS.分 === 0 && seconds >= SAVE_TIME_UNITS.分) {
return {
value: seconds / SAVE_TIME_UNITS.分,
unit: '分'
}
}
return {
value: seconds,
unit: '秒'
}
}
export function saveTimeFormToSeconds(value: number, unit: SaveTimeUnit): number {
if (value === 0) {
return 7 * SAVE_TIME_UNITS.天
}
return value * SAVE_TIME_UNITS[unit]
}
export function buildConfigSubmitPayload(
config: ConfigState,
fileSize: FileSizeForm,
saveTime: SaveTimeForm
): ConfigState {
return {
...config,
uploadSize: fileSizeFormToBytes(fileSize.value, fileSize.unit),
max_save_seconds: saveTimeFormToSeconds(saveTime.value, saveTime.unit)
}
}
+107
View File
@@ -0,0 +1,107 @@
import { DEFAULT_CONFIG, FILE_SIZE_LIMITS, STORAGE_KEYS } from '@/constants'
import type { ConfigState, SystemConfig } from '@/types'
export type PublicConfig = SystemConfig & {
uploadSize: number
expireStyle: string[]
openUpload: number
max_save_seconds: number
enableChunk: number
notify_title?: string
notify_content?: string
page_explain?: string
showAdminAddr?: number
themesSelect?: string
background?: string
opacity?: number
}
export const DEFAULT_PUBLIC_CONFIG: PublicConfig = {
...DEFAULT_CONFIG,
uploadSize: FILE_SIZE_LIMITS.MAX_FILE_SIZE,
expireStyle: ['day'],
openUpload: 1,
max_save_seconds: 0,
enableChunk: 0
}
export const DEFAULT_CONFIG_STATE: ConfigState = {
name: DEFAULT_PUBLIC_CONFIG.name,
description: DEFAULT_PUBLIC_CONFIG.description || '',
file_storage: '',
themesChoices: [],
expireStyle: DEFAULT_PUBLIC_CONFIG.expireStyle,
admin_token: '',
robotsText: '',
keywords: '',
notify_title: '',
notify_content: '',
openUpload: DEFAULT_PUBLIC_CONFIG.openUpload,
uploadSize: DEFAULT_PUBLIC_CONFIG.uploadSize,
storage_path: '',
uploadMinute: 1,
max_save_seconds: DEFAULT_PUBLIC_CONFIG.max_save_seconds,
opacity: 0.9,
enableChunk: DEFAULT_PUBLIC_CONFIG.enableChunk,
s3_access_key_id: '',
background: '',
showAdminAddr: 0,
page_explain: '',
s3_secret_access_key: '',
aws_session_token: '',
s3_signature_version: '',
s3_region_name: '',
s3_bucket_name: '',
s3_endpoint_url: '',
s3_hostname: '',
uploadCount: 1,
errorMinute: 1,
errorCount: 1,
s3_proxy: 0,
themesSelect: '',
webdav_url: '',
webdav_username: '',
webdav_password: ''
}
export function readStoredConfig<T extends object = Partial<ConfigState>>(): T | null {
try {
const rawConfig = localStorage.getItem(STORAGE_KEYS.CONFIG)
return rawConfig ? (JSON.parse(rawConfig) as T) : null
} catch {
return null
}
}
export function toPublicConfig(config: Partial<ConfigState> | null | undefined): Partial<PublicConfig> {
if (!config) return {}
return {
name: config.name,
description: config.description,
uploadSize: config.uploadSize,
expireStyle: config.expireStyle,
openUpload: config.openUpload,
max_save_seconds: config.max_save_seconds,
enableChunk: config.enableChunk,
notify_title: config.notify_title,
notify_content: config.notify_content,
page_explain: config.page_explain,
showAdminAddr: config.showAdminAddr,
themesSelect: config.themesSelect,
background: config.background,
opacity: config.opacity
}
}
export function writeStoredConfig(config: object) {
localStorage.setItem(STORAGE_KEYS.CONFIG, JSON.stringify(toPublicConfig(config as Partial<ConfigState>)))
}
export function readNotifyKey(): string | null {
return localStorage.getItem(STORAGE_KEYS.NOTIFY)
}
export function writeNotifyKey(notifyKey: string) {
localStorage.setItem(STORAGE_KEYS.NOTIFY, notifyKey)
}
+41
View File
@@ -0,0 +1,41 @@
import { marked } from 'marked'
import DOMPurify from 'dompurify'
const MARKDOWN_ALLOWED_TAGS = [
'p',
'br',
'strong',
'em',
'u',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'ul',
'ol',
'li',
'blockquote',
'code',
'pre',
'a',
'img'
]
const MARKDOWN_ALLOWED_ATTR = ['href', 'src', 'alt', 'title', 'class']
export async function renderMarkdownPreview(content: string): Promise<string> {
try {
const rawHtml = await marked(content)
return DOMPurify.sanitize(rawHtml, {
ALLOWED_TAGS: MARKDOWN_ALLOWED_TAGS,
ALLOWED_ATTR: MARKDOWN_ALLOWED_ATTR,
ALLOWED_URI_REGEXP:
/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|xxx):|[^a-z]|[a-z+.-]+(?:[^a-z+.-:]|$))/i
})
} catch (error) {
console.error('Markdown 渲染失败:', error)
return content
}
}
+15
View File
@@ -0,0 +1,15 @@
import { saveAs } from 'file-saver'
import type { ReceivedFileRecord } from '@/types'
import { buildDownloadUrl } from '@/utils/share-url'
export function downloadReceivedRecord(record: ReceivedFileRecord): void {
if (record.downloadUrl) {
window.open(buildDownloadUrl(record.downloadUrl), '_blank')
return
}
if (record.content) {
const blob = new Blob([record.content], { type: 'text/plain;charset=utf-8' })
saveAs(blob, `${record.filename}.txt`)
}
}
+60
View File
@@ -0,0 +1,60 @@
import JSZip from 'jszip'
const SMALL_FILE_HASH_LIMIT = 10 * 1024 * 1024
const LARGE_FILE_HASH_CHUNK_SIZE = 5 * 1024 * 1024
const generateFallbackHash = (file: File): string => {
const fileInfo = `${file.name}-${file.size}-${file.lastModified}`
let hash = 0
for (let i = 0; i < fileInfo.length; i++) {
const char = fileInfo.charCodeAt(i)
hash = (hash << 5) - hash + char
hash = hash & hash
}
return Math.abs(hash).toString(16).padStart(64, '0')
}
const createSha256Hash = async (data: BufferSource): Promise<string> => {
const hashBuffer = await crypto.subtle.digest('SHA-256', data)
const hashArray = Array.from(new Uint8Array(hashBuffer))
return hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('')
}
export const calculateFileHash = async (file: File): Promise<string> => {
try {
if (file.size <= SMALL_FILE_HASH_LIMIT) {
const buffer = await file.arrayBuffer()
return window.isSecureContext ? createSha256Hash(buffer) : generateFallbackHash(file)
}
const firstChunk = file.slice(0, LARGE_FILE_HASH_CHUNK_SIZE)
const lastChunk = file.slice(-LARGE_FILE_HASH_CHUNK_SIZE)
const [firstBuffer, lastBuffer] = await Promise.all([
firstChunk.arrayBuffer(),
lastChunk.arrayBuffer()
])
const combined = new Uint8Array(firstBuffer.byteLength + lastBuffer.byteLength + 16)
combined.set(new Uint8Array(firstBuffer), 0)
combined.set(new Uint8Array(lastBuffer), firstBuffer.byteLength)
const sizeBytes = new TextEncoder().encode(file.size.toString())
combined.set(sizeBytes, firstBuffer.byteLength + lastBuffer.byteLength)
return window.isSecureContext ? createSha256Hash(combined) : generateFallbackHash(file)
} catch (error) {
console.error('File hash calculation failed:', error)
return generateFallbackHash(file)
}
}
export const packFilesAsZip = async (files: File[]): Promise<File> => {
const zip = new JSZip()
for (const file of files) {
zip.file(file.name, file)
}
const blob = await zip.generateAsync({
type: 'blob',
compression: 'DEFLATE',
compressionOptions: { level: 6 }
})
return new File([blob], `files_${Date.now()}.zip`, { type: 'application/zip' })
}
+20
View File
@@ -0,0 +1,20 @@
import { STORAGE_KEYS } from '@/constants'
import type { ThemeMode } from '@/types'
const LOCALE_STORAGE_KEY = 'locale'
export function readStoredThemeMode(): string | null {
return localStorage.getItem(STORAGE_KEYS.COLOR_MODE)
}
export function writeStoredThemeMode(mode: ThemeMode) {
localStorage.setItem(STORAGE_KEYS.COLOR_MODE, mode)
}
export function readStoredLocale(): string | null {
return localStorage.getItem(LOCALE_STORAGE_KEY)
}
export function writeStoredLocale(locale: string) {
localStorage.setItem(LOCALE_STORAGE_KEY, locale)
}
+99
View File
@@ -0,0 +1,99 @@
import type { ApiResponse, SendType, SentFileRecord } from '@/types'
type Translate = (key: string, params?: Record<string, string | number>) => string
type BuildSentRecordInput = {
response: ApiResponse
sendType: SendType
textContent: string
selectedFile: File | null
selectedFiles: File[]
expirationMethod: string
expirationValue: string
translate: Translate
getUnit: (method: string) => string
}
const expirationSecondsByMethod: Record<string, number> = {
minute: 60,
hour: 3600,
day: 86400
}
export function isExpirationWithinLimit(
method: string,
value: string,
maxSaveSeconds: number
): boolean {
if (method === 'forever' || method === 'count') return true
if (maxSaveSeconds === 0) return true
const multiplier = expirationSecondsByMethod[method]
if (!multiplier) return false
return parseInt(value) * multiplier <= maxSaveSeconds
}
export function formatExpirationTime(
method: string,
value: string,
translate: Translate,
getUnit: (method: string) => string
): string {
if (method === 'forever') return translate('send.expiration.units.forever')
if (method === 'count') return translate('send.messages.expiresAfterCount', { count: value })
const now = new Date()
const expireValue = parseInt(value)
switch (method) {
case 'minute':
now.setMinutes(now.getMinutes() + expireValue)
break
case 'hour':
now.setHours(now.getHours() + expireValue)
break
case 'day':
now.setDate(now.getDate() + expireValue)
break
default:
return translate('send.messages.expiresAfter', { value, unit: getUnit(method) })
}
const year = now.getFullYear()
const month = (now.getMonth() + 1).toString().padStart(2, '0')
const day = now.getDate().toString().padStart(2, '0')
const hours = now.getHours().toString().padStart(2, '0')
const minutes = now.getMinutes().toString().padStart(2, '0')
return translate('send.messages.expiresAt', { date: `${year}-${month}-${day} ${hours}:${minutes}` })
}
export function buildSentRecord(input: BuildSentRecordInput): SentFileRecord {
const retrieveCode = (input.response.detail as { code?: string } | undefined)?.code || ''
const fileName = (input.response.detail as { name?: string } | undefined)?.name || ''
const totalSelectedSize = input.selectedFiles.reduce((total, file) => total + file.size, 0)
const displaySize =
input.sendType === 'text'
? `${(input.textContent.length / 1024).toFixed(2)} KB`
: input.selectedFiles.length > 0
? `${(totalSelectedSize / (1024 * 1024)).toFixed(1)} MB`
: `${((input.selectedFile?.size || 0) / (1024 * 1024)).toFixed(1)} MB`
return {
id: Date.now(),
filename: fileName,
date: new Date().toISOString().split('T')[0],
size: displaySize,
expiration:
input.expirationMethod === 'forever'
? input.translate('send.expiration.forever')
: formatExpirationTime(
input.expirationMethod,
input.expirationValue,
input.translate,
input.getUnit
),
retrieveCode
}
}
+17
View File
@@ -0,0 +1,17 @@
import type { SentFileRecord } from '@/types'
import { copyRetrieveCode, copyRetrieveLink, copyWgetCommand } from '@/utils/clipboard'
import { buildSentRecordQrValue } from '@/utils/share-url'
type CopyNotify = (message: string, type: 'success' | 'error') => void
export function createSentRecordActions(notify: CopyNotify) {
return {
copyLink: (record: SentFileRecord) =>
copyRetrieveLink(record.retrieveCode, { notify }),
copyCode: (record: SentFileRecord) =>
copyRetrieveCode(record.retrieveCode, { notify }),
copyWgetCommand: (record: SentFileRecord) =>
copyWgetCommand(record.retrieveCode, record.filename, { notify }),
getQRCodeValue: (record: SentFileRecord) => buildSentRecordQrValue(record)
}
}
+38
View File
@@ -0,0 +1,38 @@
import { apiBaseURL } from '@/services/client'
const getApiOrigin = () => {
if (!apiBaseURL) return window.location.origin
return new URL(apiBaseURL, window.location.origin).origin
}
export function buildAbsoluteUrl(path: string): string {
if (/^https?:\/\//i.test(path)) {
return path
}
const normalizedPath = path.startsWith('/') ? path : `/${path}`
return `${getApiOrigin()}${normalizedPath}`
}
export function buildRetrieveUrl(code: string): string {
return `${window.location.origin}/#/?code=${code}`
}
export function buildDownloadUrl(downloadUrl: string | null): string {
return downloadUrl ? buildAbsoluteUrl(downloadUrl) : ''
}
export function buildReceivedRecordQrValue(record: {
code: string
downloadUrl: string | null
}): string {
return record.downloadUrl ? buildDownloadUrl(record.downloadUrl) : buildRetrieveUrl(record.code)
}
export function buildSentRecordQrValue(record: { retrieveCode: string }): string {
return buildRetrieveUrl(record.retrieveCode)
}
export function buildWgetCommand(retrieveCode: string, fileName: string): string {
return `wget ${buildAbsoluteUrl(`/share/select?code=${retrieveCode}`)} -O "${fileName}"`
}