feat: apply UI/storage/share optimizations and quota improvements

This commit is contained in:
2026-02-12 18:02:57 +08:00
parent 1fcc60b9aa
commit 12859cbb20
13 changed files with 4476 additions and 828 deletions

View File

@@ -2,6 +2,8 @@ const jwt = require('jsonwebtoken');
const crypto = require('crypto'); const crypto = require('crypto');
const { UserDB } = require('./database'); const { UserDB } = require('./database');
const { decryptSecret } = require('./utils/encryption'); const { decryptSecret } = require('./utils/encryption');
const DEFAULT_LOCAL_STORAGE_QUOTA_BYTES = 1024 * 1024 * 1024; // 1GB
const DEFAULT_OSS_STORAGE_QUOTA_BYTES = 1024 * 1024 * 1024; // 1GB
// JWT密钥必须在环境变量中设置 // JWT密钥必须在环境变量中设置
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production'; const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
@@ -169,6 +171,11 @@ function authMiddleware(req, res, next) {
}); });
} }
const rawOssQuota = Number(user.oss_storage_quota);
const effectiveOssQuota = Number.isFinite(rawOssQuota) && rawOssQuota > 0
? rawOssQuota
: DEFAULT_OSS_STORAGE_QUOTA_BYTES;
// 将用户信息附加到请求对象(包含所有存储相关字段) // 将用户信息附加到请求对象(包含所有存储相关字段)
req.user = { req.user = {
id: user.id, id: user.id,
@@ -187,8 +194,10 @@ function authMiddleware(req, res, next) {
// 存储相关字段 // 存储相关字段
storage_permission: user.storage_permission || 'oss_only', storage_permission: user.storage_permission || 'oss_only',
current_storage_type: user.current_storage_type || 'oss', current_storage_type: user.current_storage_type || 'oss',
local_storage_quota: user.local_storage_quota || 1073741824, local_storage_quota: user.local_storage_quota || DEFAULT_LOCAL_STORAGE_QUOTA_BYTES,
local_storage_used: user.local_storage_used || 0, local_storage_used: user.local_storage_used || 0,
oss_storage_quota: effectiveOssQuota,
storage_used: user.storage_used || 0,
// 主题偏好 // 主题偏好
theme_preference: user.theme_preference || null theme_preference: user.theme_preference || null
}; };

View File

@@ -37,6 +37,8 @@ console.log(`[数据库] 路径: ${dbPath}`);
// 创建或连接数据库 // 创建或连接数据库
const db = new Database(dbPath); const db = new Database(dbPath);
const DEFAULT_LOCAL_STORAGE_QUOTA_BYTES = 1024 * 1024 * 1024; // 1GB
const DEFAULT_OSS_STORAGE_QUOTA_BYTES = 1024 * 1024 * 1024; // 1GB
// ===== 性能优化配置P0 优先级修复) ===== // ===== 性能优化配置P0 优先级修复) =====
@@ -525,7 +527,8 @@ const UserDB = {
'has_oss_config': 'number', 'has_oss_config': 'number',
'is_verified': 'number', 'is_verified': 'number',
'local_storage_quota': 'number', 'local_storage_quota': 'number',
'local_storage_used': 'number' 'local_storage_used': 'number',
'oss_storage_quota': 'number'
}; };
const expectedType = FIELD_TYPES[fieldName]; const expectedType = FIELD_TYPES[fieldName];
@@ -585,6 +588,7 @@ const UserDB = {
'current_storage_type': 'current_storage_type', 'current_storage_type': 'current_storage_type',
'local_storage_quota': 'local_storage_quota', 'local_storage_quota': 'local_storage_quota',
'local_storage_used': 'local_storage_used', 'local_storage_used': 'local_storage_used',
'oss_storage_quota': 'oss_storage_quota',
// 偏好设置 // 偏好设置
'theme_preference': 'theme_preference' 'theme_preference': 'theme_preference'
@@ -665,6 +669,7 @@ const UserDB = {
'current_storage_type': 'current_storage_type', 'current_storage_type': 'current_storage_type',
'local_storage_quota': 'local_storage_quota', 'local_storage_quota': 'local_storage_quota',
'local_storage_used': 'local_storage_used', 'local_storage_used': 'local_storage_used',
'oss_storage_quota': 'oss_storage_quota',
// 偏好设置 // 偏好设置
'theme_preference': 'theme_preference' 'theme_preference': 'theme_preference'
@@ -717,7 +722,8 @@ const UserDB = {
'current_storage_type': 'string', 'theme_preference': 'string', 'current_storage_type': 'string', 'theme_preference': 'string',
'is_admin': 'number', 'is_active': 'number', 'is_banned': 'number', 'is_admin': 'number', 'is_active': 'number', 'is_banned': 'number',
'has_oss_config': 'number', 'is_verified': 'number', 'has_oss_config': 'number', 'is_verified': 'number',
'local_storage_quota': 'number', 'local_storage_used': 'number' 'local_storage_quota': 'number', 'local_storage_used': 'number',
'oss_storage_quota': 'number'
}[key]; }[key];
console.warn(`[类型检查] 字段 ${key} 值类型不符: 期望 ${expectedType}, 实际 ${typeof value}, 值: ${JSON.stringify(value)}`); console.warn(`[类型检查] 字段 ${key} 值类型不符: 期望 ${expectedType}, 实际 ${typeof value}, 值: ${JSON.stringify(value)}`);
@@ -883,11 +889,14 @@ const ShareDB = {
// 根据分享码查找 // 根据分享码查找
// 增强: 检查分享者是否被封禁(被封禁用户的分享不可访问) // 增强: 检查分享者是否被封禁(被封禁用户的分享不可访问)
// ===== 性能优化P0 优先级修复):只查询必要字段,避免 N+1 查询 ===== // ===== 性能优化P0 优先级修复):只查询必要字段,避免 N+1 查询 =====
// 移除了敏感字段:oss_access_key_id, oss_access_key_secret(不需要传递给分享访问者) // 不返回 oss_access_key_id / oss_access_key_secret
// share_password 仅用于服务端验证,不会透传给前端。
findByCode(shareCode) { findByCode(shareCode) {
const result = db.prepare(` const result = db.prepare(`
SELECT SELECT
s.id, s.user_id, s.share_code, s.share_path, s.share_type, s.id, s.user_id, s.share_code, s.share_path, s.share_type,
s.storage_type,
s.share_password,
s.view_count, s.download_count, s.created_at, s.expires_at, s.view_count, s.download_count, s.created_at, s.expires_at,
u.username, u.username,
-- OSS 配置(访问分享文件所需) -- OSS 配置(访问分享文件所需)
@@ -1172,8 +1181,9 @@ function migrateToV2() {
db.exec(` db.exec(`
ALTER TABLE users ADD COLUMN storage_permission TEXT DEFAULT 'sftp_only'; ALTER TABLE users ADD COLUMN storage_permission TEXT DEFAULT 'sftp_only';
ALTER TABLE users ADD COLUMN current_storage_type TEXT DEFAULT 'sftp'; ALTER TABLE users ADD COLUMN current_storage_type TEXT DEFAULT 'sftp';
ALTER TABLE users ADD COLUMN local_storage_quota INTEGER DEFAULT 1073741824; ALTER TABLE users ADD COLUMN local_storage_quota INTEGER DEFAULT ${DEFAULT_LOCAL_STORAGE_QUOTA_BYTES};
ALTER TABLE users ADD COLUMN local_storage_used INTEGER DEFAULT 0; ALTER TABLE users ADD COLUMN local_storage_used INTEGER DEFAULT 0;
ALTER TABLE users ADD COLUMN oss_storage_quota INTEGER DEFAULT ${DEFAULT_OSS_STORAGE_QUOTA_BYTES};
`); `);
console.log('[数据库迁移] ✓ 用户表已升级'); console.log('[数据库迁移] ✓ 用户表已升级');
@@ -1247,6 +1257,34 @@ function migrateToOss() {
} }
} }
// 数据库迁移 - OSS 存储配额字段
function migrateOssQuotaField() {
try {
const columns = db.prepare("PRAGMA table_info(users)").all();
const hasOssStorageQuota = columns.some(col => col.name === 'oss_storage_quota');
if (!hasOssStorageQuota) {
console.log('[数据库迁移] 添加 oss_storage_quota 字段...');
db.exec(`ALTER TABLE users ADD COLUMN oss_storage_quota INTEGER DEFAULT ${DEFAULT_OSS_STORAGE_QUOTA_BYTES}`);
console.log('[数据库迁移] ✓ oss_storage_quota 字段已添加');
}
// 统一策略:未配置或无效值默认 1GB
const backfillResult = db.prepare(`
UPDATE users
SET oss_storage_quota = ?
WHERE oss_storage_quota IS NULL OR oss_storage_quota <= 0
`).run(DEFAULT_OSS_STORAGE_QUOTA_BYTES);
if (backfillResult.changes > 0) {
console.log(`[数据库迁移] ✓ OSS 配额默认值已回填: ${backfillResult.changes} 条记录`);
}
} catch (error) {
console.error('[数据库迁移] oss_storage_quota 迁移失败:', error);
}
}
// 系统日志操作 // 系统日志操作
const SystemLogDB = { const SystemLogDB = {
// 日志级别常量 // 日志级别常量
@@ -1432,6 +1470,7 @@ initDefaultSettings();
migrateToV2(); // 执行数据库迁移 migrateToV2(); // 执行数据库迁移
migrateThemePreference(); // 主题偏好迁移 migrateThemePreference(); // 主题偏好迁移
migrateToOss(); // SFTP → OSS 迁移 migrateToOss(); // SFTP → OSS 迁移
migrateOssQuotaField(); // OSS 配额字段迁移
module.exports = { module.exports = {
db, db,

File diff suppressed because it is too large Load Diff

View File

@@ -18,6 +18,8 @@
"author": "玩玩云团队", "author": "玩玩云团队",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@aws-sdk/client-s3": "^3.985.0",
"@aws-sdk/s3-request-presigner": "^3.985.0",
"archiver": "^7.0.1", "archiver": "^7.0.1",
"bcryptjs": "^3.0.3", "bcryptjs": "^3.0.3",
"better-sqlite3": "^11.8.1", "better-sqlite3": "^11.8.1",
@@ -28,10 +30,9 @@
"express-session": "^1.18.2", "express-session": "^1.18.2",
"express-validator": "^7.3.0", "express-validator": "^7.3.0",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"lodash": "^4.17.23",
"multer": "^2.0.2", "multer": "^2.0.2",
"nodemailer": "^6.9.14", "nodemailer": "^8.0.1",
"@aws-sdk/client-s3": "^3.600.0",
"@aws-sdk/s3-request-presigner": "^3.600.0",
"svg-captcha": "^1.4.0" "svg-captcha": "^1.4.0"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -54,7 +54,7 @@
* - POST /api/share/:code/verify * - POST /api/share/:code/verify
* - POST /api/share/:code/list * - POST /api/share/:code/list
* - POST /api/share/:code/download * - POST /api/share/:code/download
* - GET /api/share/:code/download-url * - POST /api/share/:code/download-url
* - GET /api/share/:code/download-file * - GET /api/share/:code/download-file
* *
* 6. routes/admin.js - 管理员功能 * 6. routes/admin.js - 管理员功能

File diff suppressed because it is too large Load Diff

View File

@@ -1534,7 +1534,7 @@ class OssStorageClient {
*/ */
async createReadStream(filePath) { async createReadStream(filePath) {
const key = this.getObjectKey(filePath); const key = this.getObjectKey(filePath);
const bucket = this.user.oss_bucket; const bucket = this.getBucket();
const command = new GetObjectCommand({ const command = new GetObjectCommand({
Bucket: bucket, Bucket: bucket,
@@ -1589,7 +1589,7 @@ class OssStorageClient {
*/ */
async getPresignedUrl(filePath, expiresIn = 3600) { async getPresignedUrl(filePath, expiresIn = 3600) {
const key = this.getObjectKey(filePath); const key = this.getObjectKey(filePath);
const bucket = this.user.oss_bucket; const bucket = this.getBucket();
try { try {
const command = new GetObjectCommand({ const command = new GetObjectCommand({
@@ -1646,7 +1646,7 @@ class OssStorageClient {
*/ */
async getUploadPresignedUrl(filePath, expiresIn = 900, contentType = 'application/octet-stream') { async getUploadPresignedUrl(filePath, expiresIn = 900, contentType = 'application/octet-stream') {
const key = this.getObjectKey(filePath); const key = this.getObjectKey(filePath);
const bucket = this.user.oss_bucket; const bucket = this.getBucket();
try { try {
const command = new PutObjectCommand({ const command = new PutObjectCommand({

View File

@@ -448,7 +448,7 @@ async function testGetDownloadUrl() {
} }
try { try {
const res = await request('GET', `/api/share/${testShareCode}/download-url?path=/test-file.txt`); const res = await request('POST', `/api/share/${testShareCode}/download-url`, { path: '/test-file.txt' });
// 如果文件存在 // 如果文件存在
if (res.status === 200) { if (res.status === 200) {
@@ -481,7 +481,7 @@ async function testDownloadWithPassword() {
// 测试无密码 // 测试无密码
try { try {
const res1 = await request('GET', `/api/share/${passwordShareCode}/download-url?path=/test-file-password.txt`); const res1 = await request('POST', `/api/share/${passwordShareCode}/download-url`, { path: '/test-file-password.txt' });
assert(res1.status === 401, '无密码应返回 401'); assert(res1.status === 401, '无密码应返回 401');
} catch (error) { } catch (error) {
console.log(` [ERROR] 测试无密码下载: ${error.message}`); console.log(` [ERROR] 测试无密码下载: ${error.message}`);
@@ -489,7 +489,7 @@ async function testDownloadWithPassword() {
// 测试带密码 // 测试带密码
try { try {
const res2 = await request('GET', `/api/share/${passwordShareCode}/download-url?path=/test-file-password.txt&password=test123`); const res2 = await request('POST', `/api/share/${passwordShareCode}/download-url`, { path: '/test-file-password.txt', password: 'test123' });
// 密码正确,根据文件是否存在返回不同结果 // 密码正确,根据文件是否存在返回不同结果
if (res2.status === 200) { if (res2.status === 200) {
assert(res2.data.downloadUrl, '应返回下载链接'); assert(res2.data.downloadUrl, '应返回下载链接');
@@ -535,7 +535,7 @@ async function testDownloadPathValidation() {
// 测试越权访问 // 测试越权访问
try { try {
const res = await request('GET', `/api/share/${testShareCode}/download-url?path=/other-file.txt`); const res = await request('POST', `/api/share/${testShareCode}/download-url`, { path: '/other-file.txt' });
// 单文件分享应该禁止访问其他文件 // 单文件分享应该禁止访问其他文件
assert(res.status === 403 || res.status === 404, '越权访问应被拒绝'); assert(res.status === 403 || res.status === 404, '越权访问应被拒绝');
@@ -546,7 +546,7 @@ async function testDownloadPathValidation() {
// 测试路径遍历 // 测试路径遍历
try { try {
const res2 = await request('GET', `/api/share/${testShareCode}/download-url?path=/../../../etc/passwd`); const res2 = await request('POST', `/api/share/${testShareCode}/download-url`, { path: '/../../../etc/passwd' });
assert(res2.status === 403 || res2.status === 400, '路径遍历应被拒绝'); assert(res2.status === 403 || res2.status === 400, '路径遍历应被拒绝');
} catch (error) { } catch (error) {
console.log(` [ERROR] 路径遍历测试: ${error.message}`); console.log(` [ERROR] 路径遍历测试: ${error.message}`);
@@ -682,7 +682,7 @@ async function testShareNotExists() {
// 下载 // 下载
try { try {
const res3 = await request('GET', `/api/share/${nonExistentCode}/download-url?path=/test.txt`); const res3 = await request('POST', `/api/share/${nonExistentCode}/download-url`, { path: '/test.txt' });
assert(res3.status === 404, '下载不存在分享应返回 404'); assert(res3.status === 404, '下载不存在分享应返回 404');
} catch (error) { } catch (error) {
console.log(` [ERROR] ${error.message}`); console.log(` [ERROR] ${error.message}`);

View File

@@ -225,7 +225,7 @@ async function testPathTraversalAttacks() {
let blocked = 0; let blocked = 0;
for (const attackPath of attackPaths) { for (const attackPath of attackPaths) {
const res = await request('GET', `/api/share/${shareCode}/download-url?path=${encodeURIComponent(attackPath)}`); const res = await request('POST', `/api/share/${shareCode}/download-url`, { path: attackPath });
if (res.status === 403 || res.status === 400) { if (res.status === 403 || res.status === 400) {
blocked++; blocked++;

View File

@@ -53,21 +53,20 @@ class StorageUsageCache {
*/ */
static async updateUsage(userId, deltaSize) { static async updateUsage(userId, deltaSize) {
try { try {
// 使用 SQL 原子操作,避免并发问题 const numericDelta = Number(deltaSize);
const result = UserDB.update(userId, { if (!Number.isFinite(numericDelta)) {
// 使用原始 SQL因为 update 方法不支持表达式 throw new Error('deltaSize 必须是有效数字');
// 注意:这里需要在数据库层执行 UPDATE ... SET storage_used = storage_used + ? }
});
// 直接执行 SQL 更新 // 直接执行 SQL 原子更新,并保证不小于 0
const { db } = require('../database'); const { db } = require('../database');
db.prepare(` db.prepare(`
UPDATE users UPDATE users
SET storage_used = storage_used + ? SET storage_used = MAX(COALESCE(storage_used, 0) + ?, 0)
WHERE id = ? WHERE id = ?
`).run(deltaSize, userId); `).run(numericDelta, userId);
console.log(`[存储缓存] 用户 ${userId} 存储变化: ${deltaSize > 0 ? '+' : ''}${deltaSize} 字节`); console.log(`[存储缓存] 用户 ${userId} 存储变化: ${numericDelta > 0 ? '+' : ''}${numericDelta} 字节`);
return true; return true;
} catch (error) { } catch (error) {
console.error('[存储缓存] 更新失败:', error); console.error('[存储缓存] 更新失败:', error);

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,6 @@
const { createApp } = Vue; const { createApp } = Vue;
const DEFAULT_LOCAL_STORAGE_QUOTA_BYTES = 1024 * 1024 * 1024; // 1GB
const DEFAULT_OSS_STORAGE_QUOTA_BYTES = 1024 * 1024 * 1024; // 1GB
createApp({ createApp({
data() { data() {
@@ -90,18 +92,13 @@ createApp({
// 分享管理 // 分享管理
shares: [], shares: [],
showShareAllModal: false,
showShareFileModal: false, showShareFileModal: false,
creatingShare: false, // 创建分享中状态 creatingShare: false, // 创建分享中状态
shareAllForm: {
password: "",
expiryType: "never",
customDays: 7
},
shareFileForm: { shareFileForm: {
fileName: "", fileName: "",
filePath: "", filePath: "",
isDirectory: false, // 新增:标记是否为文件夹 isDirectory: false, // 新增:标记是否为文件夹
enablePassword: false,
password: "", password: "",
expiryType: "never", expiryType: "never",
customDays: 7 customDays: 7
@@ -246,12 +243,15 @@ createApp({
contextMenuX: 0, contextMenuX: 0,
contextMenuY: 0, contextMenuY: 0,
contextMenuFile: null, contextMenuFile: null,
showMobileFileActionSheet: false,
mobileActionFile: null,
// 长按检测 // 长按检测
longPressTimer: null, longPressTimer: null,
longPressStartX: 0, longPressStartX: 0,
longPressStartY: 0, longPressStartY: 0,
longPressFile: null, longPressFile: null,
longPressTriggered: false,
// 媒体预览 // 媒体预览
showImageViewer: false, showImageViewer: false,
@@ -260,15 +260,18 @@ createApp({
currentMediaUrl: '', currentMediaUrl: '',
currentMediaName: '', currentMediaName: '',
currentMediaType: '', // 'image', 'video', 'audio' currentMediaType: '', // 'image', 'video', 'audio'
longPressDuration: 500, // 长按时间(毫秒) longPressDuration: 420, // 长按时间(毫秒)
// 管理员编辑用户存储权限 // 管理员编辑用户存储权限
showEditStorageModal: false, showEditStorageModal: false,
editStorageForm: { editStorageForm: {
userId: null, userId: null,
username: '', username: '',
storage_permission: 'oss_only', storage_permission: 'oss_only',
local_storage_quota_value: 1, // 配额数值 local_storage_quota_value: 1, // 本地配额数值
quota_unit: 'GB' // 配额单位MB 或 GB quota_unit: 'GB', // 本地配额单位MB 或 GB
oss_storage_quota_value: 1, // OSS配额数值默认1GB
oss_quota_unit: 'GB', // OSS配额单位MB / GB / TB
oss_quota_unlimited: false // 兼容旧数据字段(当前固定为有限配额)
}, },
// 服务器存储统计 // 服务器存储统计
@@ -325,11 +328,82 @@ createApp({
return Math.round((this.localUsed / this.localQuota) * 100); return Math.round((this.localUsed / this.localQuota) * 100);
}, },
// OSS 配额相关(文件页展示)
ossQuotaBytes() {
const quota = Number(this.user?.oss_storage_quota || DEFAULT_OSS_STORAGE_QUOTA_BYTES);
if (!Number.isFinite(quota) || quota <= 0) {
return DEFAULT_OSS_STORAGE_QUOTA_BYTES;
}
return quota;
},
ossUsedBytes() {
const usageFromStats = Number(this.ossUsage?.totalSize);
if (Number.isFinite(usageFromStats) && usageFromStats >= 0) {
return usageFromStats;
}
const usageFromUser = Number(this.user?.storage_used || 0);
if (Number.isFinite(usageFromUser) && usageFromUser >= 0) {
return usageFromUser;
}
return 0;
},
ossQuotaFormatted() {
return this.formatBytes(this.ossQuotaBytes);
},
ossUsedFormatted() {
return this.formatBytes(this.ossUsedBytes);
},
ossQuotaPercentage() {
if (this.ossQuotaBytes <= 0) return 0;
return Math.min(100, Math.round((this.ossUsedBytes / this.ossQuotaBytes) * 100));
},
// 存储类型显示文本 // 存储类型显示文本
storageTypeText() { storageTypeText() {
return this.storageType === 'local' ? '本地存储' : 'OSS存储'; return this.storageType === 'local' ? '本地存储' : 'OSS存储';
}, },
// 文件统计信息(用于文件页工具栏)
fileStats() {
const list = Array.isArray(this.files) ? this.files : [];
let directoryCount = 0;
let fileCount = 0;
let totalFileBytes = 0;
for (const item of list) {
if (item?.isDirectory) {
directoryCount += 1;
continue;
}
fileCount += 1;
const currentSize = Number(item?.size || 0);
if (Number.isFinite(currentSize) && currentSize > 0) {
totalFileBytes += currentSize;
}
}
return {
totalCount: list.length,
directoryCount,
fileCount,
totalFileBytes
};
},
currentPathLabel() {
if (!this.currentPath || this.currentPath === '/') {
return '根目录';
}
return this.currentPath;
},
// 分享筛选+排序后的列表 // 分享筛选+排序后的列表
filteredShares() { filteredShares() {
let list = [...this.shares]; let list = [...this.shares];
@@ -344,8 +418,16 @@ createApp({
} }
if (this.shareFilters.type !== 'all') { if (this.shareFilters.type !== 'all') {
const targetType = this.shareFilters.type === 'all_files' ? 'all' : this.shareFilters.type; const selectedType = this.shareFilters.type;
list = list.filter(s => (s.share_type || 'file') === targetType); list = list.filter(s => {
if (selectedType === 'all_files') {
return this.isShareAllFiles(s);
}
if (selectedType === 'directory') {
return (s.share_type || 'file') === 'directory' && !this.isShareAllFiles(s);
}
return (s.share_type || 'file') === selectedType;
});
} }
if (this.shareFilters.status !== 'all') { if (this.shareFilters.status !== 'all') {
@@ -353,8 +435,8 @@ createApp({
if (this.shareFilters.status === 'expired') return this.isExpired(s.expires_at); if (this.shareFilters.status === 'expired') return this.isExpired(s.expires_at);
if (this.shareFilters.status === 'expiring') return this.isExpiringSoon(s.expires_at) && !this.isExpired(s.expires_at); if (this.shareFilters.status === 'expiring') return this.isExpiringSoon(s.expires_at) && !this.isExpired(s.expires_at);
if (this.shareFilters.status === 'active') return !this.isExpired(s.expires_at); if (this.shareFilters.status === 'active') return !this.isExpired(s.expires_at);
if (this.shareFilters.status === 'protected') return !!s.share_password; if (this.shareFilters.status === 'protected') return this.hasSharePassword(s);
if (this.shareFilters.status === 'public') return !s.share_password; if (this.shareFilters.status === 'public') return !this.hasSharePassword(s);
return true; return true;
}); });
} }
@@ -1125,6 +1207,7 @@ handleDragLeave(e) {
// 停止定期检查 // 停止定期检查
this.stopProfileSync(); this.stopProfileSync();
this.closeMobileFileActionSheet();
}, },
// 获取公开的系统配置(上传限制等) // 获取公开的系统配置(上传限制等)
@@ -1306,6 +1389,11 @@ handleDragLeave(e) {
// 更新用户本地存储信息(使用防抖避免频繁请求) // 更新用户本地存储信息(使用防抖避免频繁请求)
this.debouncedLoadUserProfile(); this.debouncedLoadUserProfile();
// OSS 模式下刷新一次空间统计,保证文件页配额显示实时
if (this.storageType === 'oss' && this.user?.oss_config_source !== 'none') {
this.loadOssUsage();
}
} }
} catch (error) { } catch (error) {
console.error('加载文件失败:', error); console.error('加载文件失败:', error);
@@ -1320,6 +1408,12 @@ handleDragLeave(e) {
}, },
async handleFileClick(file) { async handleFileClick(file) {
// 修复:长按后会触发一次 click需要忽略避免误打开文件/目录
if (this.longPressTriggered) {
this.longPressTriggered = false;
return;
}
if (file.isDirectory) { if (file.isDirectory) {
const newPath = this.currentPath === '/' const newPath = this.currentPath === '/'
? `/${file.name}` ? `/${file.name}`
@@ -1510,13 +1604,23 @@ handleDragLeave(e) {
// ===== 右键菜单和长按功能 ===== // ===== 右键菜单和长按功能 =====
// 显示右键菜单PC端 // 显示右键菜单PC端/ 长按菜单(移动端)
showFileContextMenu(file, event) { showFileContextMenu(file, event) {
// 文件和文件夹都可以显示右键菜单 event?.preventDefault?.();
event.preventDefault(); event?.stopPropagation?.();
const isTouchContextMenu = this.isMobileViewport()
|| event?.pointerType === 'touch'
|| Boolean(event?.sourceCapabilities?.firesTouchEvents);
if (isTouchContextMenu) {
this.openMobileFileActionSheet(file, event);
return;
}
this.contextMenuFile = file; this.contextMenuFile = file;
this.contextMenuX = event.clientX; this.contextMenuX = event?.clientX || 0;
this.contextMenuY = event.clientY; this.contextMenuY = event?.clientY || 0;
this.showContextMenu = true; this.showContextMenu = true;
// 点击其他地方关闭菜单 // 点击其他地方关闭菜单
@@ -1531,9 +1635,51 @@ handleDragLeave(e) {
this.contextMenuFile = null; this.contextMenuFile = null;
}, },
isMobileViewport() {
return window.matchMedia('(max-width: 768px)').matches;
},
setMobileSheetScrollLock(locked) {
if (!document.body) return;
document.body.style.overflow = locked ? 'hidden' : '';
},
openMobileFileActionSheet(file, event) {
if (event) {
event.preventDefault();
event.stopPropagation();
}
this.hideContextMenu();
this.mobileActionFile = file;
this.showMobileFileActionSheet = true;
this.setMobileSheetScrollLock(true);
},
closeMobileFileActionSheet() {
this.showMobileFileActionSheet = false;
this.mobileActionFile = null;
this.setMobileSheetScrollLock(false);
},
async mobileFileAction(action) {
const targetFile = this.mobileActionFile;
this.closeMobileFileActionSheet();
if (!targetFile) {
return;
}
this.contextMenuFile = targetFile;
await this.contextMenuAction(action);
},
// 长按开始(移动端) // 长按开始(移动端)
handleLongPressStart(file, event) { handleLongPressStart(file, event) {
if (file.isDirectory) return; // 文件夹不响应长按 if (!event?.touches?.length) return;
if (this.showMobileFileActionSheet) return;
this.longPressTriggered = false;
// 记录初始触摸位置,用于检测是否在滑动 // 记录初始触摸位置,用于检测是否在滑动
const touch = event.touches[0]; const touch = event.touches[0];
@@ -1542,29 +1688,39 @@ handleDragLeave(e) {
this.longPressFile = file; this.longPressFile = file;
this.longPressTimer = setTimeout(() => { this.longPressTimer = setTimeout(() => {
// 触发长按菜单 this.longPressTriggered = true;
this.contextMenuFile = file;
// 使用记录的触摸位置 if (event?.cancelable) {
this.contextMenuX = this.longPressStartX; event.preventDefault();
this.contextMenuY = this.longPressStartY; }
this.showContextMenu = true;
if (this.isMobileViewport()) {
this.openMobileFileActionSheet(file, event);
} else {
// 触发长按菜单
this.contextMenuFile = file;
// 使用记录的触摸位置
this.contextMenuX = this.longPressStartX;
this.contextMenuY = this.longPressStartY;
this.showContextMenu = true;
// 点击其他地方关闭菜单
this.$nextTick(() => {
document.addEventListener('click', this.hideContextMenu, { once: true });
});
}
// 触摸震动反馈(如果支持) // 触摸震动反馈(如果支持)
if (navigator.vibrate) { if (navigator.vibrate) {
navigator.vibrate(50); navigator.vibrate(50);
} }
// 点击其他地方关闭菜单
this.$nextTick(() => {
document.addEventListener('click', this.hideContextMenu, { once: true });
});
}, this.longPressDuration); }, this.longPressDuration);
}, },
// 长按移动检测(移动端)- 滑动时取消长按 // 长按移动检测(移动端)- 滑动时取消长按
handleLongPressMove(event) { handleLongPressMove(event) {
if (!this.longPressTimer) return; if (!this.longPressTimer || !event?.touches?.length) return;
const touch = event.touches[0]; const touch = event.touches[0];
const moveX = Math.abs(touch.clientX - this.longPressStartX); const moveX = Math.abs(touch.clientX - this.longPressStartX);
@@ -1583,6 +1739,7 @@ handleDragLeave(e) {
clearTimeout(this.longPressTimer); clearTimeout(this.longPressTimer);
this.longPressTimer = null; this.longPressTimer = null;
} }
this.longPressFile = null;
}, },
// 从菜单执行操作 // 从菜单执行操作
@@ -1768,6 +1925,7 @@ handleDragLeave(e) {
? file.name ? file.name
: `${this.currentPath}/${file.name}`; : `${this.currentPath}/${file.name}`;
this.shareFileForm.isDirectory = file.isDirectory; // 设置是否为文件夹 this.shareFileForm.isDirectory = file.isDirectory; // 设置是否为文件夹
this.shareFileForm.enablePassword = false;
this.shareFileForm.password = ''; this.shareFileForm.password = '';
this.shareFileForm.expiryType = 'never'; this.shareFileForm.expiryType = 'never';
this.shareFileForm.customDays = 7; this.shareFileForm.customDays = 7;
@@ -1775,45 +1933,76 @@ handleDragLeave(e) {
this.showShareFileModal = true; this.showShareFileModal = true;
}, },
async createShareAll() { toggleSharePassword(formType) {
if (this.creatingShare) return; // 防止重复提交 if (formType === 'file' && !this.shareFileForm.enablePassword) {
this.creatingShare = true; this.shareFileForm.password = '';
try {
const expiryDays = this.shareAllForm.expiryType === 'never' ? null :
this.shareAllForm.expiryType === 'custom' ? this.shareAllForm.customDays :
parseInt(this.shareAllForm.expiryType);
const response = await axios.post(
`${this.apiBase}/api/share/create`,
{
share_type: 'all',
password: this.shareAllForm.password || null,
expiry_days: expiryDays
},
);
if (response.data.success) {
this.shareResult = response.data;
this.showToast('success', '成功', '分享链接已创建');
this.loadShares();
}
} catch (error) {
console.error('创建分享失败:', error);
this.showToast('error', '错误', error.response?.data?.message || '创建分享失败');
} finally {
this.creatingShare = false;
} }
}, },
resolveShareExpiry(expiryType, customDays) {
if (expiryType === 'never') {
return { valid: true, value: null };
}
const days = expiryType === 'custom'
? Number(customDays)
: Number(expiryType);
if (!Number.isInteger(days) || days < 1 || days > 365) {
return {
valid: false,
message: '有效期必须是 1-365 天的整数'
};
}
return { valid: true, value: days };
},
normalizeSharePassword(enablePassword, rawPassword) {
if (!enablePassword) {
return { valid: true, value: null };
}
const password = (rawPassword || '').trim();
if (!password) {
return { valid: false, message: '已启用密码保护,请输入访问密码' };
}
if (password.length > 32) {
return { valid: false, message: '访问密码不能超过32个字符' };
}
return { valid: true, value: password };
},
buildShareResult(data, options = {}) {
return {
...data,
has_password: typeof options.hasPassword === 'boolean' ? options.hasPassword : !!data.has_password,
target_name: options.targetName || '文件',
target_type: options.targetType || 'file',
share_password_plain: options.password || ''
};
},
async createShareFile() { async createShareFile() {
if (this.creatingShare) return; // 防止重复提交 if (this.creatingShare) return; // 防止重复提交
this.creatingShare = true; this.creatingShare = true;
try { try {
const expiryDays = this.shareFileForm.expiryType === 'never' ? null : const expiryCheck = this.resolveShareExpiry(this.shareFileForm.expiryType, this.shareFileForm.customDays);
this.shareFileForm.expiryType === 'custom' ? this.shareFileForm.customDays : if (!expiryCheck.valid) {
parseInt(this.shareFileForm.expiryType); this.showToast('warning', '提示', expiryCheck.message);
return;
}
const passwordCheck = this.normalizeSharePassword(this.shareFileForm.enablePassword, this.shareFileForm.password);
if (!passwordCheck.valid) {
this.showToast('warning', '提示', passwordCheck.message);
return;
}
const expiryDays = expiryCheck.value;
const password = passwordCheck.value;
// 根据是否为文件夹决定share_type // 根据是否为文件夹决定share_type
const shareType = this.shareFileForm.isDirectory ? 'directory' : 'file'; const shareType = this.shareFileForm.isDirectory ? 'directory' : 'file';
@@ -1824,15 +2013,20 @@ handleDragLeave(e) {
share_type: shareType, // 修复文件夹使用directory类型 share_type: shareType, // 修复文件夹使用directory类型
file_path: this.shareFileForm.filePath, file_path: this.shareFileForm.filePath,
file_name: this.shareFileForm.fileName, file_name: this.shareFileForm.fileName,
password: this.shareFileForm.password || null, password,
expiry_days: expiryDays expiry_days: expiryDays
}, },
); );
if (response.data.success) { if (response.data.success) {
this.shareResult = response.data;
const itemType = this.shareFileForm.isDirectory ? '文件夹' : '文件'; const itemType = this.shareFileForm.isDirectory ? '文件夹' : '文件';
this.showToast('success', '成功', `${itemType}分享链接已创建`); this.shareResult = this.buildShareResult(response.data, {
hasPassword: this.shareFileForm.enablePassword,
targetName: this.shareFileForm.fileName,
targetType: shareType,
password
});
this.showToast('success', '成功', this.shareFileForm.enablePassword ? `${itemType}加密分享已创建` : `${itemType}分享链接已创建`);
this.loadShares(); this.loadShares();
} }
} catch (error) { } catch (error) {
@@ -1909,12 +2103,21 @@ handleDragLeave(e) {
// OSS 直连上传 // OSS 直连上传
async uploadToOSSDirect(file) { async uploadToOSSDirect(file) {
try { try {
// 预检查 OSS 配额(后端也会做强校验,未配置默认 1GB
const ossQuota = Number(this.user?.oss_storage_quota || DEFAULT_OSS_STORAGE_QUOTA_BYTES);
const currentUsage = Number(this.user?.storage_used || this.ossUsage?.totalSize || 0);
if (currentUsage + file.size > ossQuota) {
const remaining = Math.max(ossQuota - currentUsage, 0);
throw new Error(`OSS 配额不足:文件 ${this.formatBytes(file.size)},剩余 ${this.formatBytes(remaining)}(总配额 ${this.formatBytes(ossQuota)}`);
}
// 1. 获取签名 URL传递当前路径 // 1. 获取签名 URL传递当前路径
const { data: signData } = await axios.get(`${this.apiBase}/api/files/upload-signature`, { const { data: signData } = await axios.get(`${this.apiBase}/api/files/upload-signature`, {
params: { params: {
filename: file.name, filename: file.name,
path: this.currentPath, path: this.currentPath,
contentType: file.type || 'application/octet-stream' contentType: file.type || 'application/octet-stream',
size: file.size
} }
}); });
@@ -1922,6 +2125,10 @@ handleDragLeave(e) {
throw new Error(signData.message || '获取上传签名失败'); throw new Error(signData.message || '获取上传签名失败');
} }
if (!signData.completionToken) {
throw new Error('上传签名缺少完成凭证,请刷新页面后重试');
}
// 2. 直连 OSS 上传(不经过后端!) // 2. 直连 OSS 上传(不经过后端!)
await axios.put(signData.uploadUrl, file, { await axios.put(signData.uploadUrl, file, {
headers: { headers: {
@@ -1939,6 +2146,7 @@ handleDragLeave(e) {
await axios.post(`${this.apiBase}/api/files/upload-complete`, { await axios.post(`${this.apiBase}/api/files/upload-complete`, {
objectKey: signData.objectKey, objectKey: signData.objectKey,
size: file.size, size: file.size,
completionToken: signData.completionToken,
path: this.currentPath path: this.currentPath
}); });
@@ -2106,11 +2314,52 @@ handleDragLeave(e) {
return expireDate <= now; return expireDate <= now;
}, },
normalizeSharePath(sharePath) {
if (!sharePath) return '/';
const normalized = String(sharePath)
.replace(/\\/g, '/')
.replace(/\/+/g, '/');
if (!normalized || normalized === '.') {
return '/';
}
return normalized.startsWith('/') ? normalized : `/${normalized}`;
},
isShareAllFiles(share) {
if (!share) return false;
const shareType = share.share_type || 'file';
const sharePath = this.normalizeSharePath(share.share_path || '/');
return shareType === 'all' || (shareType === 'directory' && sharePath === '/');
},
hasSharePassword(share) {
if (!share) return false;
if (typeof share.has_password === 'boolean') {
return share.has_password;
}
return !!share.share_password;
},
getShareTypeIcon(share) {
if (this.isShareAllFiles(share)) return 'fa-layer-group';
if ((share?.share_type || 'file') === 'directory') return 'fa-folder';
return 'fa-file-alt';
},
// 分享类型标签 // 分享类型标签
getShareTypeLabel(type) { getShareTypeLabel(shareOrType, sharePath) {
switch (type) { const share = typeof shareOrType === 'object' && shareOrType !== null
? shareOrType
: { share_type: shareOrType, share_path: sharePath };
if (this.isShareAllFiles(share)) {
return '全部文件';
}
switch (share.share_type) {
case 'directory': return '文件夹'; case 'directory': return '文件夹';
case 'all': return '全部文件';
case 'file': case 'file':
default: return '文件'; default: return '文件';
} }
@@ -2129,7 +2378,7 @@ handleDragLeave(e) {
// 分享保护标签 // 分享保护标签
getShareProtection(share) { getShareProtection(share) {
if (share.share_password) { if (this.hasSharePassword(share)) {
return { text: '已加密', class: 'info', icon: 'fa-lock' }; return { text: '已加密', class: 'info', icon: 'fa-lock' };
} }
return { text: '公开', class: 'info', icon: 'fa-unlock' }; return { text: '公开', class: 'info', icon: 'fa-unlock' };
@@ -2202,20 +2451,32 @@ handleDragLeave(e) {
} }
}, },
copyShareLink(url) { copyTextToClipboard(text, successMessage = '已复制到剪贴板') {
// 复制分享链接到剪贴板 if (!text) {
this.showToast('warning', '提示', '没有可复制的内容');
return;
}
if (navigator.clipboard && navigator.clipboard.writeText) { if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(url).then(() => { navigator.clipboard.writeText(text).then(() => {
this.showToast('success', '成功', '分享链接已复制到剪贴板'); this.showToast('success', '成功', successMessage);
}).catch(() => { }).catch(() => {
this.fallbackCopyToClipboard(url); this.fallbackCopyToClipboard(text, successMessage);
}); });
} else { } else {
this.fallbackCopyToClipboard(url); this.fallbackCopyToClipboard(text, successMessage);
} }
}, },
fallbackCopyToClipboard(text) { copyShareLink(url) {
this.copyTextToClipboard(url, '分享链接已复制到剪贴板');
},
copySharePassword(password) {
this.copyTextToClipboard(password, '访问密码已复制到剪贴板');
},
fallbackCopyToClipboard(text, successMessage = '已复制到剪贴板') {
// 备用复制方法 // 备用复制方法
const textArea = document.createElement('textarea'); const textArea = document.createElement('textarea');
textArea.value = text; textArea.value = text;
@@ -2225,7 +2486,7 @@ handleDragLeave(e) {
textArea.select(); textArea.select();
try { try {
document.execCommand('copy'); document.execCommand('copy');
this.showToast('success', '成功', '分享链接已复制到剪贴板'); this.showToast('success', '成功', successMessage);
} catch (err) { } catch (err) {
this.showToast('error', '错误', '复制失败,请手动复制'); this.showToast('error', '错误', '复制失败,请手动复制');
} }
@@ -2247,6 +2508,7 @@ handleDragLeave(e) {
} }
}, },
async banUser(userId, banned) { async banUser(userId, banned) {
const action = banned ? '封禁' : '解封'; const action = banned ? '封禁' : '解封';
if (!confirm(`确定要${action}这个用户吗?`)) return; if (!confirm(`确定要${action}这个用户吗?`)) return;
@@ -2467,6 +2729,9 @@ handleDragLeave(e) {
if (response.data.success) { if (response.data.success) {
this.ossUsage = response.data.usage; this.ossUsage = response.data.usage;
if (this.user && this.ossUsage && Number.isFinite(Number(this.ossUsage.totalSize))) {
this.user.storage_used = Number(this.ossUsage.totalSize);
}
} }
} catch (error) { } catch (error) {
console.error('获取OSS空间使用情况失败:', error); console.error('获取OSS空间使用情况失败:', error);
@@ -2643,39 +2908,80 @@ handleDragLeave(e) {
this.editStorageForm.username = user.username; this.editStorageForm.username = user.username;
this.editStorageForm.storage_permission = user.storage_permission || 'oss_only'; this.editStorageForm.storage_permission = user.storage_permission || 'oss_only';
// 智能识别配额单位 // 智能识别本地配额单位
const quotaBytes = user.local_storage_quota || 1073741824; const localQuotaBytes = Number(user.local_storage_quota || DEFAULT_LOCAL_STORAGE_QUOTA_BYTES);
const quotaMB = quotaBytes / 1024 / 1024; const localQuotaMB = localQuotaBytes / 1024 / 1024;
const quotaGB = quotaMB / 1024; const localQuotaGB = localQuotaMB / 1024;
// 如果配额能被1024整除且大于等于1GB使用GB单位否则使用MB if (localQuotaMB >= 1024 && localQuotaMB % 1024 === 0) {
if (quotaMB >= 1024 && quotaMB % 1024 === 0) { this.editStorageForm.local_storage_quota_value = localQuotaGB;
this.editStorageForm.local_storage_quota_value = quotaGB;
this.editStorageForm.quota_unit = 'GB'; this.editStorageForm.quota_unit = 'GB';
} else { } else {
this.editStorageForm.local_storage_quota_value = Math.round(quotaMB); this.editStorageForm.local_storage_quota_value = Math.max(1, Math.round(localQuotaMB));
this.editStorageForm.quota_unit = 'MB'; this.editStorageForm.quota_unit = 'MB';
} }
// 智能识别 OSS 配额单位(未配置时默认 1GB
const ossQuotaBytes = Number(user.oss_storage_quota || DEFAULT_OSS_STORAGE_QUOTA_BYTES);
const effectiveOssQuotaBytes = Number.isFinite(ossQuotaBytes) && ossQuotaBytes > 0
? ossQuotaBytes
: DEFAULT_OSS_STORAGE_QUOTA_BYTES;
const mb = 1024 * 1024;
const gb = 1024 * 1024 * 1024;
const tb = 1024 * 1024 * 1024 * 1024;
this.editStorageForm.oss_quota_unlimited = false;
if (effectiveOssQuotaBytes >= tb && effectiveOssQuotaBytes % tb === 0) {
this.editStorageForm.oss_storage_quota_value = effectiveOssQuotaBytes / tb;
this.editStorageForm.oss_quota_unit = 'TB';
} else if (effectiveOssQuotaBytes >= gb && effectiveOssQuotaBytes % gb === 0) {
this.editStorageForm.oss_storage_quota_value = effectiveOssQuotaBytes / gb;
this.editStorageForm.oss_quota_unit = 'GB';
} else {
this.editStorageForm.oss_storage_quota_value = Math.max(1, Math.round(effectiveOssQuotaBytes / mb));
this.editStorageForm.oss_quota_unit = 'MB';
}
this.showEditStorageModal = true; this.showEditStorageModal = true;
}, },
// 管理员:更新用户存储权限 // 管理员:更新用户存储权限
async updateUserStorage() { async updateUserStorage() {
try { try {
// 根据单位计算字节 // 计算本地配额(字节
let quotaBytes; if (!this.editStorageForm.local_storage_quota_value || this.editStorageForm.local_storage_quota_value < 1) {
this.showToast('error', '参数错误', '本地配额必须大于 0');
return;
}
let localQuotaBytes;
if (this.editStorageForm.quota_unit === 'GB') { if (this.editStorageForm.quota_unit === 'GB') {
quotaBytes = this.editStorageForm.local_storage_quota_value * 1024 * 1024 * 1024; localQuotaBytes = this.editStorageForm.local_storage_quota_value * 1024 * 1024 * 1024;
} else { } else {
quotaBytes = this.editStorageForm.local_storage_quota_value * 1024 * 1024; localQuotaBytes = this.editStorageForm.local_storage_quota_value * 1024 * 1024;
}
// 计算 OSS 配额(字节)
if (!this.editStorageForm.oss_storage_quota_value || this.editStorageForm.oss_storage_quota_value < 1) {
this.showToast('error', '参数错误', 'OSS 配额必须大于 0');
return;
}
let ossQuotaBytes;
if (this.editStorageForm.oss_quota_unit === 'TB') {
ossQuotaBytes = this.editStorageForm.oss_storage_quota_value * 1024 * 1024 * 1024 * 1024;
} else if (this.editStorageForm.oss_quota_unit === 'GB') {
ossQuotaBytes = this.editStorageForm.oss_storage_quota_value * 1024 * 1024 * 1024;
} else {
ossQuotaBytes = this.editStorageForm.oss_storage_quota_value * 1024 * 1024;
} }
const response = await axios.post( const response = await axios.post(
`${this.apiBase}/api/admin/users/${this.editStorageForm.userId}/storage-permission`, `${this.apiBase}/api/admin/users/${this.editStorageForm.userId}/storage-permission`,
{ {
storage_permission: this.editStorageForm.storage_permission, storage_permission: this.editStorageForm.storage_permission,
local_storage_quota: quotaBytes local_storage_quota: localQuotaBytes,
oss_storage_quota: ossQuotaBytes
}, },
); );
@@ -2700,6 +3006,22 @@ handleDragLeave(e) {
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]; return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}, },
getAdminUserQuotaPercentage(user) {
const quota = Number(user?.local_storage_quota || 0);
const used = Number(user?.local_storage_used || 0);
if (!Number.isFinite(quota) || quota <= 0) return 0;
if (!Number.isFinite(used) || used <= 0) return 0;
return Math.round((used / quota) * 100);
},
getAdminUserOssQuotaPercentage(user) {
const quota = Number(user?.oss_storage_quota || DEFAULT_OSS_STORAGE_QUOTA_BYTES);
const used = Number(user?.storage_used || 0);
if (!Number.isFinite(quota) || quota <= 0) return 0;
if (!Number.isFinite(used) || used <= 0) return 0;
return Math.min(100, Math.round((used / quota) * 100));
},
formatDate(dateString) { formatDate(dateString) {
if (!dateString) return '-'; if (!dateString) return '-';

View File

@@ -4,9 +4,9 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件分享 - 玩玩云</title> <title>文件分享 - 玩玩云</title>
<script src="libs/vue.global.prod.js"></script> <script src="/libs/vue.global.prod.js"></script>
<script src="libs/axios.min.js"></script> <script src="/libs/axios.min.js"></script>
<link rel="stylesheet" href="libs/fontawesome/css/all.min.css"> <link rel="stylesheet" href="/libs/fontawesome/css/all.min.css">
<style> <style>
/* 防止 Vue 初始化前显示原始模板 */ /* 防止 Vue 初始化前显示原始模板 */
[v-cloak] { display: none !important; } [v-cloak] { display: none !important; }
@@ -626,14 +626,359 @@
background: rgba(255, 255, 255, 0.15); background: rgba(255, 255, 255, 0.15);
} }
</style> </style>
<style>
/* ===== Enterprise Netdisk Share UI Rebuild (Classic Cloud Disk) ===== */
body.enterprise-netdisk-share,
body.enterprise-netdisk-share.light-theme,
body.enterprise-netdisk-share:not(.light-theme) {
--bg-primary: #edf2fb;
--bg-secondary: #fbfdff;
--bg-card: #f8fbff;
--bg-card-hover: #eef3fb;
--glass-border: #d2ddec;
--glass-border-hover: #bccce2;
--text-primary: #1f2937;
--text-secondary: #5b6472;
--text-muted: #8b95a7;
--accent-1: #2563eb;
--accent-2: #1d4ed8;
--accent-3: #1e40af;
--glow: rgba(37, 99, 235, 0.14);
--danger: #dc2626;
--success: #16a34a;
--warning: #d97706;
background: linear-gradient(180deg, #eef3fb 0%, #f8fafe 42%, #edf2fb 100%) !important;
color: var(--text-primary) !important;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', Roboto, sans-serif;
line-height: 1.5;
padding: 14px 8px;
background-attachment: fixed;
}
body.enterprise-netdisk-share::before {
display: none !important;
}
body.enterprise-netdisk-share .container {
max-width: 1140px;
margin: 0 auto;
}
body.enterprise-netdisk-share .card {
border: 1px solid var(--glass-border);
border-radius: 10px;
background: var(--bg-card);
box-shadow: 0 2px 8px rgba(15, 23, 42, 0.06);
backdrop-filter: none;
padding: 18px;
margin-bottom: 0;
}
body.enterprise-netdisk-share .title {
margin-bottom: 14px;
padding-bottom: 12px;
border-bottom: 1px solid var(--glass-border);
color: var(--text-primary);
font-size: 21px;
background: none;
-webkit-text-fill-color: currentColor;
}
body.enterprise-netdisk-share .title i {
color: var(--accent-1);
-webkit-text-fill-color: currentColor;
}
body.enterprise-netdisk-share .share-back-btn {
margin-right: 6px;
}
body.enterprise-netdisk-share .share-meta-bar {
margin-bottom: 12px;
border: 1px solid var(--glass-border);
border-radius: 8px;
background: var(--bg-card-hover);
color: var(--text-secondary);
font-size: 13px;
line-height: 1.7;
padding: 10px 12px;
}
body.enterprise-netdisk-share .share-expire-time {
color: var(--success);
}
body.enterprise-netdisk-share .share-expire-time.expiring {
color: var(--warning);
}
body.enterprise-netdisk-share .share-expire-time.expired {
color: var(--danger);
}
body.enterprise-netdisk-share .share-expire-time.valid {
color: var(--success);
}
body.enterprise-netdisk-share .btn {
border-radius: 8px;
border: 1px solid transparent;
font-size: 13px;
font-weight: 600;
line-height: 1.2;
padding: 9px 14px;
box-shadow: none;
transition: all .2s ease;
}
body.enterprise-netdisk-share .btn-primary {
background: var(--accent-1);
border-color: var(--accent-1);
color: #fff;
}
body.enterprise-netdisk-share .btn-primary:hover {
background: var(--accent-2);
border-color: var(--accent-2);
transform: none;
box-shadow: none;
}
body.enterprise-netdisk-share .btn-secondary {
background: var(--bg-secondary);
border-color: var(--glass-border);
color: var(--text-primary);
}
body.enterprise-netdisk-share .btn-secondary:hover {
background: var(--bg-card-hover);
border-color: var(--glass-border-hover);
}
body.enterprise-netdisk-share .form-label {
color: var(--text-secondary);
font-size: 13px;
margin-bottom: 6px;
font-weight: 600;
}
body.enterprise-netdisk-share .form-input {
border: 1px solid var(--glass-border);
border-radius: 8px;
background: var(--bg-secondary);
color: var(--text-primary);
padding: 10px 12px;
font-size: 14px;
}
body.enterprise-netdisk-share .form-input:focus {
border-color: var(--accent-1);
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.14);
outline: none;
background: var(--bg-secondary);
}
body.enterprise-netdisk-share .alert {
border-radius: 8px;
font-size: 13px;
padding: 10px 12px;
}
body.enterprise-netdisk-share .alert-error {
background: #fef2f2;
border-color: #fca5a5;
color: #991b1b;
}
body.enterprise-netdisk-share .view-controls {
display: flex;
gap: 8px;
margin-bottom: 12px;
flex-wrap: wrap;
}
body.enterprise-netdisk-share .loading {
border: 1px solid var(--glass-border);
border-radius: 8px;
background: var(--bg-card-hover);
color: var(--text-secondary);
padding: 28px 14px;
}
body.enterprise-netdisk-share .spinner {
width: 30px;
height: 30px;
border: 3px solid rgba(148, 163, 184, 0.25);
border-top: 3px solid var(--accent-1);
margin-bottom: 10px;
}
body.enterprise-netdisk-share .file-grid {
gap: 10px;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
}
body.enterprise-netdisk-share .file-grid-item {
border: 1px solid var(--glass-border);
border-radius: 8px;
background: var(--bg-secondary);
min-height: 170px;
padding: 12px;
transition: all .2s ease;
}
body.enterprise-netdisk-share .file-grid-item:hover {
border-color: #93c5fd;
background: #f8fbff;
transform: none;
box-shadow: none;
}
body.enterprise-netdisk-share .file-grid-icon {
margin-bottom: 10px;
}
body.enterprise-netdisk-share .file-grid-name {
font-size: 13px;
line-height: 1.35;
color: var(--text-primary);
}
body.enterprise-netdisk-share .file-grid-size {
font-size: 12px;
color: var(--text-muted);
margin: 6px 0 10px;
}
body.enterprise-netdisk-share .file-list {
border: 1px solid var(--glass-border);
border-radius: 8px;
overflow: hidden;
background: var(--bg-secondary);
}
body.enterprise-netdisk-share .file-item {
padding: 10px 12px;
border-bottom: 1px solid var(--glass-border);
transition: all .2s ease;
}
body.enterprise-netdisk-share .file-item:hover {
background: var(--bg-card-hover);
}
body.enterprise-netdisk-share .file-icon {
width: 26px;
text-align: center;
flex-shrink: 0;
}
body.enterprise-netdisk-share .single-file-container {
border: 1px solid var(--glass-border);
border-radius: 8px;
background: var(--bg-card-hover);
padding: 14px;
min-height: auto;
}
body.enterprise-netdisk-share .single-file-card {
border: 1px solid var(--glass-border);
border-radius: 8px;
background: var(--bg-secondary);
box-shadow: none;
padding: 20px;
max-width: 460px;
}
body.enterprise-netdisk-share .single-file-name {
color: var(--text-primary);
font-size: 18px;
}
body.enterprise-netdisk-share .single-file-size {
color: var(--text-secondary);
font-size: 13px;
}
body.enterprise-netdisk-share .single-file-download {
padding: 10px 20px;
font-size: 14px;
}
body.enterprise-netdisk-share .share-not-found {
border: 1px solid var(--glass-border);
border-radius: 8px;
background: var(--bg-card-hover);
padding: 40px 14px;
text-align: center;
}
body.enterprise-netdisk-share .share-not-found-title {
margin-bottom: 10px;
font-size: 22px;
color: var(--text-primary);
}
body.enterprise-netdisk-share .share-not-found-message {
color: var(--text-secondary);
font-size: 14px;
line-height: 1.6;
}
body.enterprise-netdisk-share ::-webkit-scrollbar {
width: 8px;
height: 8px;
}
body.enterprise-netdisk-share ::-webkit-scrollbar-track {
background: transparent;
}
body.enterprise-netdisk-share ::-webkit-scrollbar-thumb {
background: rgba(148, 163, 184, 0.45);
border-radius: 999px;
}
@media (max-width: 900px) {
body.enterprise-netdisk-share .card {
padding: 14px;
}
body.enterprise-netdisk-share .title {
font-size: 20px;
}
body.enterprise-netdisk-share .view-controls {
flex-direction: column;
}
body.enterprise-netdisk-share .view-controls .btn {
width: 100%;
}
body.enterprise-netdisk-share .file-grid {
grid-template-columns: repeat(auto-fill, minmax(118px, 1fr));
gap: 8px;
}
body.enterprise-netdisk-share .file-grid-item {
min-height: 152px;
}
body.enterprise-netdisk-share .single-file-card {
padding: 16px;
}
}
</style>
</head> </head>
<body> <body class="enterprise-netdisk-share">
<div id="app" v-cloak> <div id="app" v-cloak>
<div class="container"> <div class="container">
<div class="card"> <div class="card">
<div class="title"> <div class="title">
<!-- 返回按钮:仅在查看单个文件详情且不是单文件分享时显示 --> <!-- 返回按钮:仅在查看单个文件详情且不是单文件分享时显示 -->
<button v-if="viewingFile && shareInfo.share_type !== 'file'" class="btn btn-secondary" @click="backToList" style="margin-right: 10px;"> <button v-if="viewingFile && shareInfo.share_type !== 'file'" class="btn btn-secondary share-back-btn" @click="backToList">
<i class="fas fa-arrow-left"></i> 返回列表 <i class="fas fa-arrow-left"></i> 返回列表
</button> </button>
<i class="fas fa-cloud"></i> <i class="fas fa-cloud"></i>
@@ -671,11 +1016,11 @@
<!-- 文件列表 --> <!-- 文件列表 -->
<div v-else-if="verified"> <div v-else-if="verified">
<p style="color: var(--text-secondary); margin-bottom: 20px;"> <p class="share-meta-bar">
分享者: <strong style="color: var(--text-primary);">{{ shareInfo.username }}</strong> | 分享者: <strong style="color: var(--text-primary);">{{ shareInfo.username }}</strong> |
创建时间: {{ formatDate(shareInfo.created_at) }} 创建时间: {{ formatDate(shareInfo.created_at) }}
<span v-if="shareInfo.expires_at"> | 到期时间: <strong :style="{color: isExpiringSoon(shareInfo.expires_at) ? '#f59e0b' : isExpired(shareInfo.expires_at) ? '#ef4444' : '#22c55e'}">{{ formatExpireTime(shareInfo.expires_at) }}</strong></span> <span v-if="shareInfo.expires_at"> | 到期时间: <strong class="share-expire-time" :class="{ expiring: isExpiringSoon(shareInfo.expires_at), expired: isExpired(shareInfo.expires_at) }">{{ formatExpireTime(shareInfo.expires_at) }}</strong></span>
<span v-else> | 有效期: <strong style="color: #22c55e;">永久有效</strong></span> <span v-else> | 有效期: <strong class="share-expire-time valid">永久有效</strong></span>
</p> </p>
<!-- 视图切换按钮 (多文件时才显示) --> <!-- 视图切换按钮 (多文件时才显示) -->
@@ -777,7 +1122,21 @@
methods: { methods: {
async init() { async init() {
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
this.shareCode = urlParams.get('code'); let shareCode = (urlParams.get('code') || '').trim();
// 兼容 /s/{code} 直链(无 query 参数)
if (!shareCode) {
const match = window.location.pathname.match(/^\/s\/([^/?#]+)/i);
if (match && match[1]) {
try {
shareCode = decodeURIComponent(match[1]).trim();
} catch (_) {
shareCode = match[1].trim();
}
}
}
this.shareCode = shareCode;
if (!this.shareCode) { if (!this.shareCode) {
this.errorMessage = '无效的分享链接'; this.errorMessage = '无效的分享链接';
@@ -906,21 +1265,20 @@
try { try {
// 获取下载 URLOSS 直连或后端代理) // 获取下载 URLOSS 直连或后端代理)
const params = { path: filePath }; const { data } = await axios.post(`${this.apiBase}/api/share/${this.shareCode}/download-url`, {
if (this.password) { path: filePath,
params.password = this.password; password: this.password || undefined
} });
const { data } = await axios.get(`${this.apiBase}/api/share/${this.shareCode}/download-url`, { params });
if (data.success) { if (data.success) {
// 记录下载次数(异步,不等待)
axios.post(`${this.apiBase}/api/share/${this.shareCode}/download`)
.catch(err => console.error('记录下载次数失败:', err));
if (data.direct) { if (data.direct) {
// OSS 直连下载:新窗口打开 // OSS 直连下载:新窗口打开
console.log("[分享下载] OSS 直连下载"); console.log("[分享下载] OSS 直连下载");
// 仅直连下载需要单独记录下载次数(本地代理下载在后端接口内已计数)
axios.post(`${this.apiBase}/api/share/${this.shareCode}/download`)
.catch(err => console.error('记录下载次数失败:', err));
window.open(data.downloadUrl, '_blank'); window.open(data.downloadUrl, '_blank');
} else { } else {
// 本地存储:通过后端下载 // 本地存储:通过后端下载
@@ -930,7 +1288,7 @@
} }
} catch (error) { } catch (error) {
console.error('[分享下载] 获取下载链接失败:', error); console.error('[分享下载] 获取下载链接失败:', error);
alert('获取下载链接失败: ' + (error.response?.data?.message || error.message)); this.errorMessage = '获取下载链接失败: ' + (error.response?.data?.message || error.message);
} }
}, },
@@ -1049,7 +1407,28 @@
} }
}, },
mounted() { async mounted() {
axios.defaults.withCredentials = true;
axios.interceptors.request.use(config => {
const csrfToken = document.cookie
.split('; ')
.find(row => row.startsWith('csrf_token='))
?.split('=')[1];
if (csrfToken && ['POST', 'PUT', 'DELETE', 'PATCH'].includes(config.method?.toUpperCase())) {
config.headers['X-CSRF-Token'] = csrfToken;
}
return config;
});
try {
await axios.get(`${this.apiBase}/api/csrf-token`);
} catch (error) {
console.warn('初始化 CSRF Token 失败:', error?.message || error);
}
this.init(); this.init();
} }
}).mount('#app'); }).mount('#app');