koel/resources/assets/js/composables/useUpload.ts

63 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-01-05 16:42:50 +00:00
import isMobile from 'ismobilejs'
2024-01-04 11:35:36 +00:00
import { computed } from 'vue'
import { commonStore } from '@/stores'
import { acceptedMediaTypes } from '@/config'
import { UploadFile, uploadService } from '@/services'
2022-11-18 18:44:20 +00:00
import { getAllFileEntries, pluralize } from '@/utils'
2024-04-04 22:20:42 +00:00
import { useMessageToaster, useRouter, usePolicies } from '@/composables'
export const useUpload = () => {
const { toastSuccess, toastWarning } = useMessageToaster()
2022-12-02 16:17:37 +00:00
const { go, isCurrentScreen } = useRouter()
2024-04-04 22:20:42 +00:00
const { currentUserCan } = usePolicies()
2024-01-05 16:42:50 +00:00
const mediaPathSetUp = computed(() => {
return commonStore.state.storage_driver !== 'local' || commonStore.state.media_path_set
})
2024-04-04 22:20:42 +00:00
const allowsUpload = computed(() => currentUserCan.uploadSongs() && !isMobile.phone)
const fileEntryToFile = async (entry: FileSystemEntry) => new Promise<File>(resolve => entry.file(resolve))
const queueFilesForUpload = (files: Array<File>) => {
const uploadCandidates = files
2024-01-24 22:39:47 +00:00
.filter(({ type }) => acceptedMediaTypes.includes(type))
.map((file): UploadFile => ({
file,
id: `${file.name}-${file.size}`, // for simplicity, a file's identity is determined by its name and size
status: 'Ready',
name: file.name,
progress: 0
}))
uploadService.queue(uploadCandidates)
return uploadCandidates
}
const handleDropEvent = async (event: DragEvent) => {
if (!event.dataTransfer) {
return
}
const fileEntries = await getAllFileEntries(event.dataTransfer.items)
2023-04-16 22:00:27 +00:00
const files = await Promise.all(fileEntries.map(entry => fileEntryToFile(entry)))
const queuedFiles = queueFilesForUpload(files)
if (queuedFiles.length) {
toastSuccess(`Queued ${pluralize(queuedFiles, 'file')} for upload`)
2022-12-02 16:17:37 +00:00
isCurrentScreen('Upload') || go('upload')
} else {
toastWarning('No files applicable for upload')
}
}
return {
mediaPathSetUp,
allowsUpload,
handleDropEvent,
queueFilesForUpload
}
}