Sharable file

This commit is contained in:
2025-07-26 15:17:01 +08:00
parent 186e9c00aa
commit cf9903e500
8 changed files with 127 additions and 72 deletions

View File

@@ -8,7 +8,7 @@ pnpm-debug.log*
lerna-debug.log* lerna-debug.log*
node_modules node_modules
node_modules/highlight.js **/node_modules/highlight.js/
.DS_Store .DS_Store
dist dist
dist-ssr dist-ssr

View File

@@ -2,7 +2,7 @@
<html lang=""> <html lang="">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Solar Network Drive</title> <title>Solar Network Drive</title>
<app-data /> <app-data />

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

View File

@@ -12,7 +12,8 @@
</n-alert> </n-alert>
</div> </div>
<div v-else> <div v-else>
<n-image v-if="fileType === 'image'" :src="fileSource" /> <n-image v-if="fileType === 'image'" :src="fileSource" class="w-full" />
<video v-else-if="fileType === 'video'" :src="fileSource" controls class="w-full" />
</div> </div>
</n-gi> </n-gi>
@@ -83,7 +84,25 @@
v-model:value="filePass" v-model:value="filePass"
type="password" type="password"
/> />
<n-button @click="downloadFile">Download</n-button> <div class="flex gap-2">
<n-button class="flex-grow-1" @click="downloadFile">Download</n-button>
<n-popover placement="bottom" trigger="hover">
<template #trigger>
<n-button>
<n-icon>
<qr-code-round />
</n-icon>
</n-button>
</template>
<n-qr-code
type="svg"
:value="currentUrl"
:size="160"
icon-src="/favicon.png"
error-correction-level="H"
/>
</n-popover>
</div>
</div> </div>
<div v-else> <div v-else>
<n-progress processing :percentage="progress" /> <n-progress processing :percentage="progress" />
@@ -109,9 +128,17 @@ import {
NCode, NCode,
NGrid, NGrid,
NGi, NGi,
NPopover,
NQrCode,
useMessage, useMessage,
} from 'naive-ui' } from 'naive-ui'
import { DataUsageRound, InfoRound, DetailsRound, FileUploadOutlined } from '@vicons/material' import {
DataUsageRound,
InfoRound,
DetailsRound,
FileUploadOutlined,
QrCodeRound,
} from '@vicons/material'
import { useRoute } from 'vue-router' import { useRoute } from 'vue-router'
import { computed, onMounted, ref } from 'vue' import { computed, onMounted, ref } from 'vue'
@@ -135,6 +162,8 @@ const showTechDetails = ref<boolean>(false)
const messageDisplay = useMessage() const messageDisplay = useMessage()
const currentUrl = window.location.href
const fileInfo = ref<any>(null) const fileInfo = ref<any>(null)
async function fetchFileInfo() { async function fetchFileInfo() {
try { try {
@@ -161,10 +190,11 @@ function downloadFile() {
return return
} }
if (fileInfo.value.is_encrypted) { if (fileInfo.value.is_encrypted) {
downloadAndDecryptFile(fileSource.value, filePass.value, (p: number) => { downloadAndDecryptFile(fileSource.value, filePass.value, fileInfo.value.name, (p: number) => {
progress.value = p * 100 progress.value = p * 100
}).catch((err) => { }).catch((err) => {
messageDisplay.error('Download failed: ' + err.message, { closable: true, duration: 10000 }) messageDisplay.error('Download failed: ' + err.message, { closable: true, duration: 10000 })
progress.value = undefined
}) })
} else { } else {
window.open(fileSource.value, '_blank') window.open(fileSource.value, '_blank')

View File

@@ -60,8 +60,11 @@
with-credentials with-credentials
show-preview-button show-preview-button
list-type="image" list-type="image"
show-download-button
:custom-request="customRequest" :custom-request="customRequest"
:custom-download="customDownload"
:create-thumbnail-url="createThumbnailUrl" :create-thumbnail-url="createThumbnailUrl"
@preview="customPreview"
> >
<n-upload-dragger> <n-upload-dragger>
<div style="margin-bottom: 12px"> <div style="margin-bottom: 12px">
@@ -102,11 +105,11 @@ import {
NSelect, NSelect,
NTag, NTag,
NCollapseTransition, NCollapseTransition,
NFormItem,
type UploadCustomRequestOptions, type UploadCustomRequestOptions,
type UploadSettledFileInfo, type UploadSettledFileInfo,
type SelectOption, type SelectOption,
type SelectRenderTag, type SelectRenderTag,
type UploadFileInfo,
} from 'naive-ui' } from 'naive-ui'
import { computed, h, onMounted, ref } from 'vue' import { computed, h, onMounted, ref } from 'vue'
import { CloudUploadRound } from '@vicons/material' import { CloudUploadRound } from '@vicons/material'
@@ -283,4 +286,18 @@ function createThumbnailUrl(
if (!fileInfo) return undefined if (!fileInfo) return undefined
return fileInfo.url ?? undefined return fileInfo.url ?? undefined
} }
function customDownload(file: UploadFileInfo) {
const { url, name } = file
if (!url)
return
window.open(url.replace('/api', ''), '_blank')
}
function customPreview(file: UploadFileInfo, detail: { event: MouseEvent }) {
detail.event.preventDefault()
const { url, type } = file
if (!url) return
window.open(url.replace('/api', ''), '_blank')
}
</script> </script>

View File

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

View File

@@ -126,7 +126,7 @@ public class FileService(
contentType = "application/octet-stream"; contentType = "application/octet-stream";
} }
var hash = await HashFileAsync(stream, fileSize: fileSize); var hash = await HashFileAsync(ogFilePath);
var file = new CloudFile var file = new CloudFile
{ {
@@ -136,7 +136,7 @@ public class FileService(
Size = fileSize, Size = fileSize,
Hash = hash, Hash = hash,
AccountId = Guid.Parse(account.Id), AccountId = Guid.Parse(account.Id),
IsEncrypted = !string.IsNullOrWhiteSpace(encryptPassword) IsEncrypted = !string.IsNullOrWhiteSpace(encryptPassword) && pool.AllowEncryption
}; };
var existingFile = await db.Files.AsNoTracking().FirstOrDefaultAsync(f => f.Hash == hash); var existingFile = await db.Files.AsNoTracking().FirstOrDefaultAsync(f => f.Hash == hash);
@@ -274,7 +274,7 @@ public class FileService(
} }
/// <summary> /// <summary>
/// Handles file optimization (image compression, video thumbnailing) and uploads to remote storage in the background. /// Handles file optimization (image compression, video thumbnail) and uploads to remote storage in the background.
/// </summary> /// </summary>
private async Task ProcessAndUploadInBackgroundAsync( private async Task ProcessAndUploadInBackgroundAsync(
string fileId, string fileId,
@@ -350,15 +350,23 @@ public class FileService(
var snapshotTime = mediaInfo.Duration > TimeSpan.FromSeconds(5) var snapshotTime = mediaInfo.Duration > TimeSpan.FromSeconds(5)
? TimeSpan.FromSeconds(5) ? TimeSpan.FromSeconds(5)
: TimeSpan.FromSeconds(1); : TimeSpan.FromSeconds(1);
await FFMpeg.SnapshotAsync(originalFilePath, thumbnailPath, captureTime: snapshotTime); await FFMpeg.SnapshotAsync(originalFilePath, thumbnailPath, captureTime: snapshotTime);
if (File.Exists(thumbnailPath))
{
uploads.Add((thumbnailPath, ".thumbnail.webp", "image/webp", true)); uploads.Add((thumbnailPath, ".thumbnail.webp", "image/webp", true));
hasThumbnail = true; hasThumbnail = true;
} }
else
{
logger.LogWarning("FFMpeg did not produce thumbnail for video {FileId}", fileId);
}
}
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "Failed to generate thumbnail for video {FileId}", fileId); logger.LogError(ex, "Failed to generate thumbnail for video {FileId}", fileId);
} }
break; break;
default: default:
@@ -405,11 +413,12 @@ public class FileService(
} }
} }
private static async Task<string> HashFileAsync(Stream stream, int chunkSize = 1024 * 1024, long? fileSize = null) private static async Task<string> HashFileAsync(string filePath, int chunkSize = 1024 * 1024)
{ {
fileSize ??= stream.Length; using var stream = File.OpenRead(filePath);
var fileSize = stream.Length;
if (fileSize > chunkSize * 1024 * 5) if (fileSize > chunkSize * 1024 * 5)
return await HashFastApproximateAsync(stream, chunkSize); return await HashFastApproximateAsync(filePath, chunkSize);
using var md5 = MD5.Create(); using var md5 = MD5.Create();
var hashBytes = await md5.ComputeHashAsync(stream); var hashBytes = await md5.ComputeHashAsync(stream);
@@ -417,8 +426,10 @@ public class FileService(
return Convert.ToHexString(hashBytes).ToLowerInvariant(); return Convert.ToHexString(hashBytes).ToLowerInvariant();
} }
private static async Task<string> HashFastApproximateAsync(Stream stream, int chunkSize = 1024 * 1024) private static async Task<string> HashFastApproximateAsync(string filePath, int chunkSize = 1024 * 1024)
{ {
await using var stream = File.OpenRead(filePath);
// Scale the chunk size to kB level // Scale the chunk size to kB level
chunkSize *= 1024; chunkSize *= 1024;

View File

@@ -1,5 +0,0 @@
{
"dependencies": {
"highlight.js": "^11.11.1"
}
}