Files

This commit is contained in:
2025-09-24 00:45:31 +08:00
parent 531a082d94
commit 7e8cdb6348
3 changed files with 348 additions and 0 deletions

246
app/pages/files/[id].vue Normal file
View File

@@ -0,0 +1,246 @@
<template>
<div class="d-flex align-center justify-center fill-height">
<v-card class="pa-6" max-width="1200" width="100%">
<v-progress-circular
v-if="!fileInfo && !error"
indeterminate
size="32"
></v-progress-circular>
<v-alert
type="error"
title="No file was found"
:text="error"
v-else-if="error"
></v-alert>
<div v-else>
<v-row>
<v-col cols="12" md="6">
<div v-if="fileInfo.isEncrypted">
<v-alert type="info" title="Encrypted file" class="mb-4">
The file has been encrypted. Preview not available. Please enter
the password to download it.
</v-alert>
</div>
<div v-else>
<v-img
v-if="fileType === 'image'"
:src="fileSource"
class="w-full"
/>
<video
v-else-if="fileType === 'video'"
:src="fileSource"
controls
class="w-full"
/>
<audio
v-else-if="fileType === 'audio'"
:src="fileSource"
controls
class="w-full"
/>
<v-alert
type="warning"
title="Preview Unavailable"
text="How can you preview this file?"
v-else
/>
</div>
</v-col>
<v-col cols="12" md="6">
<div class="mb-3">
<v-card
title="File Information"
prepend-icon="mdi-information-outline"
variant="tonal"
>
<v-card-text>
<div class="d-flex gap-2 mb-2">
<span class="flex-grow-1 d-flex align-center gap-2">
<v-icon size="18">mdi-information</v-icon>
File Type
</span>
<span>{{ fileInfo.mimeType }} ({{ fileType }})</span>
</div>
<div class="d-flex gap-2 mb-2">
<span class="flex-grow-1 d-flex align-center gap-2">
<v-icon size="18">mdi-chart-pie</v-icon>
File Size
</span>
<span>{{ formatBytes(fileInfo.size) }}</span>
</div>
<div class="d-flex gap-2 mb-2">
<span class="flex-grow-1 d-flex align-center gap-2">
<v-icon size="18">mdi-upload</v-icon>
Uploaded At
</span>
<span>{{
new Date(fileInfo.createdAt).toLocaleString()
}}</span>
</div>
<div class="d-flex gap-2 mb-2">
<span class="flex-grow-1 d-flex align-center gap-2">
<v-icon size="18">mdi-details</v-icon>
Technical Info
</span>
<v-btn
text
size="x-small"
@click="showTechDetails = !showTechDetails"
>
{{ showTechDetails ? "Hide" : "Show" }}
</v-btn>
</div>
<v-expand-transition>
<div
v-if="showTechDetails"
class="mt-2 d-flex flex-column gap-1"
>
<p class="text-caption opacity-75">#{{ fileInfo.id }}</p>
<v-card class="pa-2" variant="outlined">
<pre
class="overflow-x-auto px-2 py-1"
><code>{{ JSON.stringify(fileInfo.fileMeta, null, 4) }}</code></pre>
</v-card>
</div>
</v-expand-transition>
</v-card-text>
</v-card>
</div>
<div class="d-flex flex-column gap-3">
<v-text-field
v-if="fileInfo.isEncrypted"
label="Password"
v-model="filePass"
type="password"
/>
<v-btn class="flex-grow-1" @click="downloadFile">Download</v-btn>
</div>
<v-expand-transition>
<v-progress-linear
v-if="!!progress"
:model-value="progress"
:indeterminate="progress < 100"
class="mt-4"
/>
</v-expand-transition>
</v-col>
</v-row>
</div>
</v-card>
</div>
</template>
<script setup lang="ts">
import { useRoute } from "vue-router"
import { computed, onMounted, ref } from "vue"
import { downloadAndDecryptFile } from "./secure"
import { formatBytes } from "./format"
const route = useRoute()
const error = ref<string | null>(null)
const filePass = ref<string>("")
const fileId = route.params.id
const passcode = route.query.passcode as string | undefined
const progress = ref<number | undefined>(0)
const showTechDetails = ref<boolean>(false)
const api = useSolarNetwork()
const fileInfo = ref<any>(null)
async function fetchFileInfo() {
try {
let url = "/api/drive/files/" + fileId + "/info"
if (passcode) {
url += `?passcode=${passcode}`
}
const resp = await api(url)
fileInfo.value = resp
} catch (err) {
error.value = (err as Error).message
}
}
onMounted(() => fetchFileInfo())
const apiBase = useSolarNetworkUrl(false)
const fileType = computed(() => {
if (!fileInfo.value) return "unknown"
return fileInfo.value.mimeType?.split("/")[0] || "unknown"
})
const fileSource = computed(() => {
let url = `${apiBase}/drive/files/${fileId}`
if (passcode) {
url += `?passcode=${passcode}`
}
return url
})
async function downloadFile() {
if (fileInfo.value.isEncrypted && !filePass.value) {
alert("Please enter the password to download the file.")
return
}
if (fileInfo.value.isEncrypted) {
downloadAndDecryptFile(
fileSource.value,
filePass.value,
fileInfo.value.name,
(p: number) => {
progress.value = p * 100
}
).catch((err: any) => {
alert("Download failed: " + err.message)
progress.value = undefined
})
} else {
const res = await fetch(fileSource.value)
if (!res.ok) {
throw new Error(
`Failed to download ${fileInfo.value.name}: ${res.statusText}`
)
}
const contentLength = res.headers.get("content-length")
if (!contentLength) {
throw new Error("Content-Length response header is missing.")
}
const total = parseInt(contentLength, 10)
const reader = res.body!.getReader()
const chunks: Uint8Array[] = []
let received = 0
while (true) {
const { done, value } = await reader.read()
if (done) break
if (value) {
chunks.push(value)
received += value.length
progress.value = (received / total) * 100
}
}
const blob = new Blob(chunks as BlobPart[])
const blobUrl = window.URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = blobUrl
a.download =
fileInfo.value.fileName ||
"download." + fileInfo.value.mimeType.split("/")[1]
document.body.appendChild(a)
a.click()
a.remove()
window.URL.revokeObjectURL(blobUrl)
}
}
</script>

View File

@@ -0,0 +1,8 @@
export function formatBytes(bytes: number, decimals = 2): string {
if (bytes === 0) return '0 Bytes'
const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}

94
app/pages/files/secure.ts Normal file
View File

@@ -0,0 +1,94 @@
export async function downloadAndDecryptFile(
url: string,
password: string,
fileName: string,
onProgress?: (progress: number) => void,
): Promise<void> {
const response = await fetch(url)
if (!response.ok) throw new Error(`Failed to fetch: ${response.status}`)
const contentLength = +(response.headers.get('Content-Length') || 0)
const reader = response.body!.getReader()
const chunks: Uint8Array[] = []
let received = 0
while (true) {
const { done, value } = await reader.read()
if (done) break
if (value) {
chunks.push(value)
received += value.length
if (contentLength && onProgress) {
onProgress(received / contentLength)
}
}
}
const fullBuffer = new Uint8Array(received)
let offset = 0
for (const chunk of chunks) {
fullBuffer.set(chunk, offset)
offset += chunk.length
}
const decryptedBytes = await decryptFile(fullBuffer, password)
// Create a blob and trigger a download
const blob = new Blob([decryptedBytes])
const downloadUrl = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = downloadUrl
a.download = fileName
document.body.appendChild(a)
a.click()
a.remove()
URL.revokeObjectURL(downloadUrl)
}
export async function decryptFile(fileBuffer: Uint8Array, password: string): Promise<Uint8Array> {
const salt = fileBuffer.slice(0, 16)
const nonce = fileBuffer.slice(16, 28)
const tag = fileBuffer.slice(28, 44)
const ciphertext = fileBuffer.slice(44)
const enc = new TextEncoder()
const keyMaterial = await crypto.subtle.importKey(
'raw',
enc.encode(password),
{ name: 'PBKDF2' },
false,
['deriveKey'],
)
const key = await crypto.subtle.deriveKey(
{ name: 'PBKDF2', salt, iterations: 100000, hash: 'SHA-256' },
keyMaterial,
{ name: 'AES-GCM', length: 256 },
false,
['decrypt'],
)
const fullCiphertext = new Uint8Array(ciphertext.length + tag.length)
fullCiphertext.set(ciphertext)
fullCiphertext.set(tag, ciphertext.length)
let decrypted: ArrayBuffer
try {
decrypted = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: nonce, tagLength: 128 },
key,
fullCiphertext,
)
} catch {
throw new Error('Incorrect password or corrupted file.')
}
const magic = new TextEncoder().encode('DYSON1')
const decryptedBytes = new Uint8Array(decrypted)
for (let i = 0; i < magic.length; i++) {
if (decryptedBytes[i] !== magic[i]) {
throw new Error('Incorrect password or corrupted file.')
}
}
return decryptedBytes.slice(magic.length)
}