19 Commits

Author SHA1 Message Date
keven1024
668a2dd4d8 fix: adjust alreadyUploadSize computation to prevent exceeding total file size 2025-07-02 10:38:59 +08:00
keven1024
695395ba6a feat: set staleTime to Infinity in TextShareResult component for persistent query data 2025-07-01 14:26:24 +08:00
keven1024
a0cff53901 feat: enhance TextShareView component with copy functionality for preview text and update share data structure 2025-07-01 12:53:18 +08:00
keven1024
7d8075277d feat: enhance TextShareResult component with download count, expiration time, and pickup code display 2025-07-01 12:45:05 +08:00
keven1024
862b381e65 feat: update .env.example to include frontend configuration options for site title, description, and URL 2025-07-01 11:38:13 +08:00
keven1024
745ae94c49 feat: add .env.example file with configuration options for download secret, upload path, Redis URL, and admin information 2025-07-01 11:22:23 +08:00
keven
8c60d32ac0 feat: 更新 README 和新增中文文档,详细介绍 015 文件分享平台的功能、技术架构及快速开始指南 2025-06-30 08:28:51 +08:00
keven
2f5388d0a8 feat: 更新 useSeo 以添加网站图标和社交媒体元数据,删除旧的 favicon 文件 2025-06-22 13:42:19 +08:00
keven
88b8daa5df feat: 修改 useSeo 以支持从环境变量获取 SEO 元数据,增强服务器端渲染能力 2025-06-22 12:41:51 +08:00
keven1024
7a3d03c41f feat: update primary color in CSS and enhance about page with relative time display and progress component 2025-06-22 01:07:09 +08:00
keven1024
0bdea93726 chore: add js-md5 dependency to pnpm-lock.yaml for file hashing 2025-06-22 00:49:14 +08:00
keven1024
f4740f4373 fix: improve max storage size handling in CreateUploadTask by using GetFileSize for better error management 2025-06-22 00:48:53 +08:00
keven1024
1ac21b3dd0 docs: update README to include new features and todos for file upload service 2025-06-22 00:47:32 +08:00
keven1024
76457a6e88 feat: replace SparkMD5 with js-md5 for file hash calculation and clean up unused code 2025-06-22 00:41:18 +08:00
keven1024
41e9df5ee8 feat: implement async file hash calculation using web workers for improved performance 2025-06-21 22:41:19 +08:00
keven1024
7f5149566c feat: enhance file upload progress view with error handling and user notifications 2025-06-21 16:45:30 +08:00
keven1024
24b4b2dc93 Merge branch 'main' of https://gitea.fudaoyuan.icu/keven/015 2025-06-21 15:51:24 +08:00
keven1024
9b1b89056d chore(backend): update version and build_time in GetStat function to use environment variables for better tracking 2025-06-21 15:51:01 +08:00
keven1024
46e3cf529c chore: update Dockerfile and Drone configuration to use VERSION and BUILD_TIME arguments for better build tracking 2025-06-21 15:47:11 +08:00
25 changed files with 1143 additions and 591 deletions

View File

@@ -17,7 +17,8 @@ steps:
- ${DRONE_TAG} - ${DRONE_TAG}
- latest - latest
build_args: build_args:
- BUILD_TAG=${DRONE_TAG} - VERSION=${DRONE_TAG}
- BUILD_TIME=${DRONE_BUILD_FINISHED}
- name: build-worker - name: build-worker
image: plugins/docker image: plugins/docker
settings: settings:

16
.env.example Normal file
View File

@@ -0,0 +1,16 @@
# 你的下载secret每一次下载次数减1的时候都会根据这里的secret生成一个下载jwt token 有效期一小时使用该下载token有效期内可以多线程下载该文件而不会被多次扣除次数
DOWNLOAD_SECRET="your-secret-token"
UPLOAD_PATH="/upload" # 上传路径
REDIS_URL="redis://127.0.0.1:6379/0" # redis 地址
NODE_ENV="production" # 指定系统环境 production 或者 dev
MAX_LOCALSTORAGE_SIZE="100GB" # 指定实例最大上传容量支持填写人类可读的值比如1TB500GB等
# (可选): 系统状态页面显示站长信息的 头像会使用email的gravatar头像点击是触发mailto:your-email不填写不显示站长信息
ADMIN_EMAIL="keven@fudaoyuan.icu"
ADMIN_NAME="keven"
# 下面的env是前端渲染用到的SITE_URL必填对应你的公网域名
SITE_TITLE="015"
SITE_DESC="015 是一个开源的临时内容分享平台项目, 支持文件和文本上传, 下载, 分享"
SITE_URL="http://localhost:5000"

View File

@@ -26,7 +26,8 @@ RUN CGO_ENABLED=0 GOOS=linux go build -o backend
FROM front-base AS runner FROM front-base AS runner
ARG BUILD_TAG ARG VERSION
ARG BUILD_TIME
WORKDIR /app WORKDIR /app
RUN apk add --no-cache curl openssl RUN apk add --no-cache curl openssl
ENV NODE_ENV production ENV NODE_ENV production
@@ -43,6 +44,8 @@ COPY 015.sh /app/015.sh
ENV PORT=80 HOST=0.0.0.0 ENV PORT=80 HOST=0.0.0.0
ENV SITE_URL="http://localhost" ENV SITE_URL="http://localhost"
ENV UPLOAD_PATH="/uploads" ENV UPLOAD_PATH="/uploads"
ENV VERSION=${VERSION}
ENV BUILD_TIME=${BUILD_TIME}
EXPOSE 80 EXPOSE 80

219
README.md
View File

@@ -1,3 +1,220 @@
# 015 # 015
这里是send企划 015 (/ˈzɪərəʊ wʌn faɪv/, "zero-one-five") is a self-hosted temporary file sharing platform. Focused on providing one-time, temporary file and text upload, processing, and sharing services. The project name originates from [Ichigo](https://darling-in-the-franxx.fandom.com/wiki/Ichigo) from DARLING in the FRANXX.
A modern file sharing website built with Vue 3 + Nuxt 3 + Go, supporting file upload, text sharing, image compression, concurrent processing, instant transfer functionality, and more, featuring a complete sharing management and access control system.
![015 Platform Overview](/docs/image/0.png)
## 🌟 Features
### Core Functionality
🖼️ **High-Performance File Upload** - Supports large file chunked uploads with frontend file hash calculation for instant transfer
📱 **Responsive Design** - Modern UI based on Tailwind V4 + Reka UI, adapts to various devices
**Concurrent Processing** - Uses Web Worker for frontend hash calculation, backend queue system for task processing
🌐 **Multi-language Support** - Complete Chinese and English internationalization support
🔗 **Share Management** - Flexible sharing link generation and management system
### File Processing
🔄 **Smart Instant Transfer** - Frontend instant transfer detection based on file hash + file size, avoiding duplicate uploads
📷 **Image Compression** - Automatic image compression functionality supporting multiple formats
🖼️ **File Preview** - Supports preview of images, videos, audio, documents, and various file types
📊 **Upload Statistics** - Real-time display of upload progress and file information
🌈 **Resume Upload** - Supports resuming uploads after interruption
### Advanced Features
🎛️ **Share Control** - Supports password protection, download count limits, and expiration time settings
🔍 **Pickup Code System** - Supports pickup code sharing, simplifying sharing difficulty
**Queue Processing** - Asynchronous task processing system based on Redis + Asynq
🗂️ **File Management** - Complete file lifecycle management
📷 **Image Processing** - Image compression, format conversion, and other processing features
🏷️ **Download Control** - Download token management system based on JWT
## 📸 Screenshots
![](/docs/image/1.webp)
![](/docs/image/2.webp)
![](/docs/image/3.png)
![](/docs/image/4.png)
## 🏗️ Technical Architecture
### Frontend Tech Stack
- **Vue 3** - Progressive JavaScript framework
- **Nuxt 3** - Vue.js full-stack framework
- **TypeScript** - Complete type safety
- **Tailwind CSS** - Atomic CSS framework
- **Reka UI** - Modern component library
- **Pinia** - State management
- **TanStack Query** - Data fetching and caching
- **Vue Router** - Routing management
- **i18next** - Internationalization support
### Backend Tech Stack
- **Go 1.23** - High-performance server-side language
- **Echo** - High-performance HTTP framework
- **Redis** - Caching and session storage
- **Asynq** - Asynchronous task queue
- **JWT** - Authentication
- **Zap** - Structured logging
### Build System
- **Node.js** - Server-side runtime
- **pnpm** - Fast package manager
- **Husky** - Git hooks management
- **Prettier** - Code formatting
- **Lint-staged** - Staged file checking
### Storage Architecture
- **File Storage** - Local file system storage
- **Redis Cache** - Share information and file metadata caching
- **Queue System** - Asynchronous task processing queue
## 🚀 Quick Start
### Requirements
- Node.js 18+
- Go 1.23+
- Redis 6+
- pnpm 9+
### Install Dependencies
```bash
# Install root dependencies
pnpm install
# Install frontend dependencies
cd front && pnpm install
# Install backend dependencies
cd backend && go mod download
# Install Worker dependencies
cd worker && go mod download
```
### Environment Configuration
```bash
# Copy environment variables file
cp .env.example .env
# Configure necessary environment variables
REDIS_URL=redis://localhost:6379
UPLOAD_PATH=./uploads
download_secret=your_download_secret
```
### Start Services
```bash
# Start all services in development mode
pnpm run dev
# Or start separately
pnpm run dev:front # Frontend service (port 5000)
pnpm run dev:backend # Backend service (port 1323)
pnpm run dev:worker # Worker service
```
## 📁 Project Structure
```
015/
├── front/ # Frontend application (Vue 3 + Nuxt 3)
│ ├── components/ # Vue components
│ │ ├── pages/ # Page routes
│ │ ├── composables/ # Composable functions
│ │ ├── i18n/ # Internationalization files
│ │ └── assets/ # Static assets
│ ├── backend/ # Backend service (Go + Echo)
│ │ ├── internal/ # Internal packages
│ │ │ ├── controllers/ # Controllers
│ │ │ ├── models/ # Data models
│ │ │ ├── services/ # Business logic
│ │ │ └── utils/ # Utility functions
│ │ └── middleware/ # Middleware
│ ├── worker/ # Asynchronous task processing (Go + Asynq)
│ │ ├── internal/ # Internal packages
│ │ │ ├── tasks/ # Task processors
│ │ │ └── utils/ # Utility functions
│ │ └── middleware/ # Middleware
│ └── tmp/ # Temporary files
```
## 🔧 Development Guide
### Code Standards
- Use Prettier for code formatting
- Use Husky + lint-staged for pre-commit checking
- Follow TypeScript type safety standards
### Commit Standards
```bash
# Code formatting will run automatically before commit
git add .
git commit -m "feat: add new feature"
```
### Build and Deploy
```bash
# Build frontend
cd front && pnpm run build
# Build backend (requires Go environment)
cd backend && go build -o main .
# Build Worker
cd worker && go build -o worker .
```
## 📝 Development Roadmap
### Completed Features ✅
- Frontend hash calculation and instant transfer
- Concurrent chunked upload (using Web Worker)
- File upload/text upload and sharing
- Upload statistics page
- Multi-language support
- Maximum upload limits
- Backend queue system and Worker file processing
### Planned Features 🚧
- Resume upload (backend calculates uploaded parts and returns)
- Image format conversion and compression
- Image OCR copy
- Document to Markdown conversion
- Text translation/summarization
- Support for multiple file uploads
## 🤝 Contributing
Welcome to submit Issues and Pull Requests to improve this project.
## 📄 License
This project is licensed under AGPLV3.
## 🔗 Related Links
- [Vue 3 Documentation](https://vuejs.org/)
- [Nuxt 3 Documentation](https://nuxt.com/)
- [Echo Framework Documentation](https://echo.labstack.com/)
- [Asynq Documentation](https://github.com/hibiken/asynq)

View File

@@ -14,7 +14,6 @@ import (
"github.com/hibiken/asynq" "github.com/hibiken/asynq"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/spf13/cast"
) )
func CreateUploadTask(c echo.Context) error { func CreateUploadTask(c echo.Context) error {
@@ -41,8 +40,10 @@ func CreateUploadTask(c echo.Context) error {
"chunk_size": fileInfo.ChunkSize, "chunk_size": fileInfo.ChunkSize,
}) })
} }
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("MAX_LOCALSTORAGE_SIZE"))
maxStorageSize := cast.ToInt64(utils.GetEnv("MAX_LOCALSTORAGE_SIZE")) if err != nil {
return utils.HTTPErrorHandler(c, err)
}
fileInfoMap, err := models.GetRedisFileInfoAll() fileInfoMap, err := models.GetRedisFileInfoAll()
if err != nil { if err != nil {
return utils.HTTPErrorHandler(c, err) return utils.HTTPErrorHandler(c, err)
@@ -56,7 +57,7 @@ func CreateUploadTask(c echo.Context) error {
} }
totalSize += fileInfo.FileSize totalSize += fileInfo.FileSize
} }
if totalSize+r.FileSize > maxStorageSize { if totalSize+r.FileSize > int64(maxStorageSize) {
return utils.HTTPErrorHandler(c, errors.New("存储空间不足")) return utils.HTTPErrorHandler(c, errors.New("存储空间不足"))
} }

View File

@@ -9,6 +9,7 @@ import (
"github.com/hibiken/asynq" "github.com/hibiken/asynq"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/samber/lo" "github.com/samber/lo"
"github.com/spf13/cast"
) )
type FileChartData struct { type FileChartData struct {
@@ -83,7 +84,8 @@ func GetStat(c echo.Context) error {
}) })
return utils.HTTPSuccessHandler(c, map[string]any{ return utils.HTTPSuccessHandler(c, map[string]any{
"version": "0.1.0", "version": utils.GetEnvWithDefault("VERSION", "dev"),
"build_time": cast.ToInt(utils.GetEnvWithDefault("BUILD_TIME", cast.ToString(time.Now().Unix()))),
"max_limit": map[string]any{ "max_limit": map[string]any{
"file_size": maxStorageSize, "file_size": maxStorageSize,
}, },

221
docs/README-zh.md Normal file
View File

@@ -0,0 +1,221 @@
# 015
015 (/ˈzɪərəʊ wʌn faɪv/, "zero-one-five") 是一个支持selfhosted的临时文件分享平台。专注于提供一次性临时的文件和文本上传处理分享服务。项目名称来源于DARLING in the FRANXX的 [](https://darling-in-the-franxx.fandom.com/wiki/Ichigo)
一个基于 Vue 3 + Nuxt 3 + Go 构建的现代文件分享网站,支持文件上传、文本分享、图片压缩、并发处理、秒传功能等,具备完整的分享管理和访问控制体系。
![015 Platform Overview](./image/0.png)
## 🌟 功能特性
### 核心功能
🖼️ **高性能文件上传** - 支持大文件切片上传,前端计算文件哈希实现秒传
📱 **响应式设计** - 基于 Tailwind V4 + Reka UI 的现代化 UI适配各种设备
**并发处理** - 使用 Web Worker 进行前端Hash计算后端队列系统处理任务
🌐 **多语言支持** - 完整的中英文国际化支持
🔗 **分享管理** - 灵活的分享链接生成和管理系统
### 文件处理
🔄 **智能秒传** - 基于文件哈希+文件大小的前端秒传检测,避免重复上传
📷 **图片压缩** - 自动图片压缩功能,支持多种格式
🖼️ **文件预览** - 支持图片、视频、音频、文档等多种文件类型预览
📊 **上传统计** - 实时显示上传进度和文件信息
🌈 **断点续传** - 支持上传中断后的续传功能
### 高级功能
🎛️ **分享控制** - 支持密码保护、下载次数限制、过期时间设置
🔍 **取件码系统** - 支持取件码分享,简化分享难度
**队列处理** - 基于 Redis + Asynq 的异步任务处理系统
🗂️ **文件管理** - 完整的文件生命周期管理
📷 **图片处理** - 图片压缩、格式转换等处理功能
🏷️ **下载控制** - 基于 JWT 的下载令牌管理系统
## 截图
![](./image/1.webp)
![](./image/2.webp)
![](./image/3.png)
![](./image/4.png)
## 🏗️ 技术架构
### 前端技术栈
- **Vue 3** - 渐进式 JavaScript 框架
- **Nuxt 3** - Vue.js 全栈框架
- **TypeScript** - 完整的类型安全
- **Tailwind CSS** - 原子化 CSS 框架
- **Reka UI** - 现代化组件库
- **Pinia** - 状态管理
- **TanStack Query** - 数据获取和缓存
- **Vue Router** - 路由管理
- **i18next** - 国际化支持
### 后端技术栈
- **Go 1.23** - 高性能服务器端语言
- **Echo** - 高性能 HTTP 框架
- **Redis** - 缓存和会话存储
- **Asynq** - 异步任务队列
- **JWT** - 身份验证
- **Zap** - 结构化日志
### 构建系统
- **Node.js** - 服务器端运行时
- **pnpm** - 快速包管理器
- **Husky** - Git hooks 管理
- **Prettier** - 代码格式化
- **Lint-staged** - 暂存文件检查
### 存储架构
- **文件存储** - 本地文件系统存储
- **Redis 缓存** - 分享信息、文件元数据缓存
- **队列系统** - 异步任务处理队列
## 🚀 快速开始
### 环境要求
- Node.js 18+
- Go 1.23+
- Redis 6+
- pnpm 9+
### 安装依赖
```bash
# 安装根目录依赖
pnpm install
# 安装前端依赖
cd front && pnpm install
# 安装后端依赖
cd backend && go mod download
# 安装 Worker 依赖
cd worker && go mod download
```
### 环境配置
```bash
# 复制环境变量文件
cp .env.example .env
# 配置必要的环境变量
REDIS_URL=redis://localhost:6379
UPLOAD_PATH=./uploads
download_secret=your_download_secret
```
### 启动服务
```bash
# 开发模式启动所有服务
pnpm run dev
# 或分别启动
pnpm run dev:front # 前端服务 (端口 5000)
pnpm run dev:backend # 后端服务 (端口 1323)
pnpm run dev:worker # Worker 服务
```
## 📁 项目结构
```
015/
├── front/ # 前端应用 (Vue 3 + Nuxt 3)
│ ├── components/ # Vue 组件
│ │ ├── pages/ # 页面路由
│ │ ├── composables/ # 组合式函数
│ │ ├── i18n/ # 国际化文件
│ │ └── assets/ # 静态资源
│ └── middleware/ # 中间件
├── backend/ # 后端服务 (Go + Echo)
│ ├── internal/ # 内部包
│ │ ├── controllers/ # 控制器
│ │ ├── models/ # 数据模型
│ │ ├── services/ # 业务逻辑
│ │ └── utils/ # 工具函数
│ └── middleware/ # 中间件
├── worker/ # 异步任务处理 (Go + Asynq)
│ ├── internal/ # 内部包
│ │ ├── tasks/ # 任务处理器
│ │ └── utils/ # 工具函数
│ └── middleware/ # 中间件
└── tmp/ # 临时文件
```
## 🔧 开发指南
### 代码规范
- 使用 Prettier 进行代码格式化
- 使用 Husky + lint-staged 进行提交前检查
- 遵循 TypeScript 类型安全规范
### 提交规范
```bash
# 提交前会自动运行代码格式化
git add .
git commit -m "feat: add new feature"
```
### 构建部署
```bash
# 构建前端
cd front && pnpm run build
# 构建后端 (需要 Go 环境)
cd backend && go build -o main .
# 构建 Worker
cd worker && go build -o worker .
```
## 📝 开发计划
### 已完成功能 ✅
- 前端计算哈希和秒传
- 并发切片上传 (使用 Web Worker)
- 文件上传/文本上传和分享
- 上传统计页面
- 多语言支持
- 最大上传限制
- 后端队列系统和 Worker 处理文件
### 计划功能 🚧
- 断点续传 (后端计算已上传部分并返回)
- 图片格式转换和压缩
- 图片 OCR 复制
- 文档转 Markdown
- 文本翻译/总结
- 支持上传多文件
## 🤝 贡献指南
欢迎提交 Issue 和 Pull Request 来改进这个项目。
## 📄 许可证
本项目采用 AGPLV3 许可证。
## 🔗 相关链接
- [Vue 3 文档](https://vuejs.org/)
- [Nuxt 3 文档](https://nuxt.com/)
- [Echo 框架文档](https://echo.labstack.com/)
- [Asynq 文档](https://github.com/hibiken/asynq)

BIN
docs/image/0.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

BIN
docs/image/1.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

BIN
docs/image/2.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 654 KiB

BIN
docs/image/3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

BIN
docs/image/4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

View File

@@ -50,7 +50,7 @@
--card-foreground: oklch(0.129 0.042 264.695); --card-foreground: oklch(0.129 0.042 264.695);
--popover: oklch(1 0 0); --popover: oklch(1 0 0);
--popover-foreground: oklch(0.129 0.042 264.695); --popover-foreground: oklch(0.129 0.042 264.695);
--primary: oklch(0.208 0.042 265.755); --primary: oklch(0.4349 0.0673 257.47);
--primary-foreground: oklch(0.984 0.003 247.858); --primary-foreground: oklch(0.984 0.003 247.858);
--secondary: oklch(0.968 0.007 247.896); --secondary: oklch(0.968 0.007 247.896);
--secondary-foreground: oklch(0.208 0.042 265.755); --secondary-foreground: oklch(0.208 0.042 265.755);

View File

@@ -1,9 +1,11 @@
<script lang="ts" setup> <script lang="ts" setup>
import CircularProgress from '@/components/CircularProgress.vue' import CircularProgress from '@/components/CircularProgress.vue'
import { chunk, shuffle, times } from 'lodash-es' import { chunk, get, shuffle, times } from 'lodash-es'
import { cx } from 'class-variance-authority' import { cx } from 'class-variance-authority'
import calcFileHash from '@/lib/calcFileHash'
import { filesize } from 'filesize' import { filesize } from 'filesize'
import { toast } from 'vue-sonner'
import asyncWorker from '~/lib/asyncWorker'
import calcFileHashWorker from '~/lib/calcFileHashWorker?worker'
const props = defineProps<{ const props = defineProps<{
data: { file: File; config: any; handle_type: string } data: { file: File; config: any; handle_type: string }
}>() }>()
@@ -25,15 +27,16 @@ const fileSliceUploadStatusList = ref<
>([]) >([])
const successCount = computed(() => fileSliceUploadStatusList.value.filter((item) => item.status === 'success').length) const successCount = computed(() => fileSliceUploadStatusList.value.filter((item) => item.status === 'success').length)
const alreadyUploadSize = computed(() => successCount.value * chunkSize.value) const alreadyUploadSize = computed(() => Math.min(successCount.value * chunkSize.value, props?.data?.file?.size))
const uploadProgress = computed(() => Math.round((alreadyUploadSize.value / (props?.data?.file?.size || 0)) * 100)) const uploadProgress = computed(() => Math.round((alreadyUploadSize.value / (props?.data?.file?.size || 0)) * 100))
useAsyncState(async () => { const { error } = useAsyncState(async () => {
const { file } = props.data || {} const { file } = props.data || {}
if (!file) return if (!file) return
const { size, type = 'application/octet-stream' } = file || {} const { size, type = 'application/octet-stream' } = file || {}
const now = Date.now() const now = Date.now()
const hash = await calcFileHash({ file }) const res = await asyncWorker(calcFileHashWorker, { data: { file } })
const { hash } = res?.data || {}
if (hash) { if (hash) {
step.value = 'upload' step.value = 'upload'
calcHashTime.value = Date.now() - now calcHashTime.value = Date.now() - now
@@ -49,7 +52,7 @@ useAsyncState(async () => {
method: 'POST', method: 'POST',
body: { body: {
size, size,
mime_type: type, mime_type: get(type, '', 'application/octet-stream'),
hash, hash,
}, },
}) })
@@ -122,6 +125,13 @@ useAsyncState(async () => {
form.setFieldValue('file_id', id) form.setFieldValue('file_id', id)
emit('change', 'result') emit('change', 'result')
}, null) }, null)
watch(error, (newVal) => {
if (newVal) {
toast.error('上传失败')
}
emit('change', 'input')
})
</script> </script>
<template> <template>
<div class="flex flex-col gap-3"> <div class="flex flex-col gap-3">

View File

@@ -1,99 +1,143 @@
<script setup lang="ts"> <script setup lang="ts">
import { Button } from "@/components/ui/button"; import { Button } from '@/components/ui/button'
import { Input } from "@/components/ui/input"; import { Input } from '@/components/ui/input'
import { useClipboard } from "@vueuse/core"; import { useClipboard } from '@vueuse/core'
import { toast } from "vue-sonner"; import { toast } from 'vue-sonner'
import { useQuery } from "@tanstack/vue-query"; import { useQuery } from '@tanstack/vue-query'
import useMyAppShare from "@/composables/useMyAppShare"; import useMyAppShare from '@/composables/useMyAppShare'
import useMyAppConfig from "@/composables/useMyAppConfig"; import useMyAppConfig from '@/composables/useMyAppConfig'
import showDrawer from "@/lib/showDrawer"; import showDrawer from '@/lib/showDrawer'
import QrCoreDrawer from "@/components/Drawer/QrCoreDrawer.vue"; import QrCoreDrawer from '@/components/Drawer/QrCoreDrawer.vue'
import dayjs from 'dayjs'
const props = defineProps<{ const props = defineProps<{
data: { text: string; config: any; handle_type: string }; data: { text: string; config: any; handle_type: string }
}>(); }>()
const emit = defineEmits<{ const emit = defineEmits<{
(e: "change", key: string): void; (e: 'change', key: string): void
}>(); }>()
const { createTextShare } = useMyAppShare(); const { createTextShare } = useMyAppShare()
const { data } = useQuery({ const { data } = useQuery({
queryKey: ["create-share", props?.data?.text], queryKey: ['create-share', props?.data?.text],
queryFn: async () => { staleTime: Infinity,
const { config, text } = props?.data || {}; queryFn: async () => {
const data = await createTextShare({ const { config, text } = props?.data || {}
text, const data = await createTextShare({
config, text,
}); config,
return data?.data; })
}, return data?.data
}); },
const appConfig = useMyAppConfig(); })
const appConfig = useMyAppConfig()
const url = computed(() => { const url = computed(() => {
const { id } = data?.value || {}; const { id } = data?.value || {}
return `${appConfig?.value?.site_url}/s/${id}`; return `${appConfig?.value?.site_url}/s/${id}`
}); })
const { copy } = useClipboard(); const { copy } = useClipboard()
</script> </script>
<template> <template>
<div class="flex flex-col gap-3"> <div class="flex flex-col gap-3">
<div class="flex flex-col md:flex-row gap-2"> <div class="flex flex-row gap-2">
<div class="flex flex-row justify-between md:basis-1/2"> <div class="flex flex-row justify-between w-full">
<h2 class="text-lg">分享成功</h2> <h2 class="text-lg">分享成功</h2>
<Button <Button
variant="outline" variant="outline"
class="bg-white/70" class="bg-white/70"
size="icon" size="icon"
@click=" @click="
() => { () => {
emit('change', 'input'); emit('change', 'input')
} }
" "
> >
<LucideHome /> <LucideHome />
</Button> </Button>
</div> </div>
<div class="flex flex-row gap-2 flex-1"> </div>
<Input v-model="url" class="bg-white/70" readonly /> <div class="flex flex-col md:flex-row gap-5 rounded-md p-5 bg-white/20 backdrop-blur-xl w-full">
<Button <div class="flex flex-col gap-2 flex-1">
variant="outline" <div class="text-sm font-semibold">信息</div>
class="bg-white/70" <div class="grid grid-cols-2 gap-2">
size="icon" <div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1">
@click=" <div class="text-xs font-semibold">下载次数</div>
() => { <div class="text-3xl font-light">{{ data?.download_nums }}</div>
copy(url); </div>
toast.success('复制成功'); <div class="rounded-xl flex flex-col bg-black/5 px-3 py-2 gap-1">
} <div class="text-xs font-semibold">过期时间</div>
" <div class="text-md font-light">
> {{ dayjs((data?.expire_at ?? 0) * 1000).format('YYYY-MM-DD HH:mm:ss') }}
<LucideCopy /> </div>
</Button> </div>
<Button <div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1" v-if="data?.pickup_code">
variant="outline" <div class="flex flex-row justify-between w-full items-center">
class="bg-white/70" <div class="text-xs font-semibold">提取码</div>
size="icon" <Button
@click=" variant="outline"
() => { class="bg-white/70 p-0 size-6"
showDrawer({ size="icon"
render: ({ ...rest }) => @click="
h(QrCoreDrawer, { () => {
...rest, copy(data?.pickup_code as string)
data: url, toast.success('复制成功')
}), }
}); "
} >
" <LucideCopy class="size-3" />
> </Button>
<LucideQrCode /> </div>
</Button> <div class="flex flex-row gap-2">
</div> <div v-for="s in data?.pickup_code" class="text-2xl font-light">
{{ s }}
</div>
</div>
</div>
</div>
</div>
<div class="flex flex-col gap-5 flex-1">
<div class="text-sm font-semibold">链接</div>
<div class="flex flex-row gap-2">
<Input v-model="url" class="bg-white/70" readonly />
<Button
variant="outline"
class="bg-white/70"
size="icon"
@click="
() => {
copy(url)
toast.success('复制成功')
}
"
>
<LucideCopy />
</Button>
<Button
variant="outline"
class="bg-white/70"
size="icon"
@click="
() => {
showDrawer({
render: ({ ...rest }) =>
h(QrCoreDrawer, {
...rest,
data: url,
}),
})
}
"
>
<LucideQrCode />
</Button>
</div>
</div>
</div>
<h2 class="text-md">内容</h2>
<MarkdownRender class="prose rounded-md bg-white/70 p-3 w-full max-w-full min-h-[30vh]" :markdown="props?.data?.text" />
</div> </div>
<div
class="prose rounded-md bg-white/70 p-3 w-full max-w-full min-h-[30vh]"
v-html="props?.data?.text"
/>
</div>
</template> </template>

View File

@@ -1,93 +1,97 @@
<script setup lang="ts"> <script setup lang="ts">
import dayjs from "dayjs"; import dayjs from 'dayjs'
import AsyncButton from "@/components/ui/button/AsyncButton.vue"; import AsyncButton from '@/components/ui/button/AsyncButton.vue'
import duration from "dayjs/plugin/duration"; import duration from 'dayjs/plugin/duration'
import relativeTime from "dayjs/plugin/relativeTime"; import relativeTime from 'dayjs/plugin/relativeTime'
import { isBoolean } from "lodash-es"; import { isBoolean } from 'lodash-es'
import { LucideCheck, LucideX } from "lucide-vue-next"; import { LucideCheck, LucideX } from 'lucide-vue-next'
import { cx } from "class-variance-authority"; import { cx } from 'class-variance-authority'
import { toast } from "vue-sonner"; import { toast } from 'vue-sonner'
import MarkdownRender from "@/components/MarkdownRender.vue"; import MarkdownRender from '@/components/MarkdownRender.vue'
dayjs.extend(duration); import { Button } from '@/components/ui/button'
dayjs.extend(relativeTime); import { LucideCopy } from 'lucide-vue-next'
import { useClipboard } from '@vueuse/core'
dayjs.extend(duration)
dayjs.extend(relativeTime)
const props = defineProps<{ const props = defineProps<{
data: any; data: any
}>(); }>()
const { getShareToken } = useMyAppShare(); const { getShareToken } = useMyAppShare()
const expireSeconds = computed(() => { const expireSeconds = computed(() => {
return dayjs(props?.data?.expire_at * 10e2).unix() - dayjs().unix(); return dayjs(props?.data?.expire_at * 10e2).unix() - dayjs().unix()
}); })
const { remaining, start } = useCountdown(expireSeconds.value); const { remaining, start } = useCountdown(expireSeconds.value)
const { copy } = useClipboard()
onMounted(() => { onMounted(() => {
start(); start()
}); })
const fileShareInfo = computed(() => { const fileShareInfo = computed(() => {
return [ return [
{ label: "需要密码", value: props?.data?.has_password ?? false }, { label: '需要密码', value: props?.data?.has_password ?? false },
{ {
label: "过期时间", label: '过期时间',
value: dayjs.duration(remaining.value, "seconds").format(`D天 HH:mm:ss`), value: dayjs.duration(remaining.value, 'seconds').format(`D天 HH:mm:ss`),
}, },
{ label: "剩余浏览次数", value: props?.data?.download_nums ?? 0 }, { label: '剩余浏览次数', value: props?.data?.download_nums ?? 0 },
]; ]
}); })
const previewText = ref<string | null>(null); const previewText = ref<string | null>(null)
const handlePreview = async () => { const handlePreview = async () => {
try { try {
const token = await getShareToken(props?.data?.id); const token = await getShareToken(props?.data?.id)
const r = await $fetch<{ const r = await $fetch<{
code: number; code: number
data: { data: {
data: string; data: string
}; }
}>(`/api/download?token=${token}`); }>(`/api/download?token=${token}`)
previewText.value = r?.data?.data; previewText.value = r?.data?.data
} catch (error) { } catch (error) {
toast.error((error as any)?.data?.message || error); toast.error((error as any)?.data?.message || error)
} }
}; }
</script> </script>
<template> <template>
<div <div :class="cx('flex flex-col max-h-full', !!previewText ? 'gap-3' : 'gap-16 items-center')">
:class=" <div :class="cx('flex flex-row w-full', !!previewText ? 'justify-between' : 'justify-center')">
cx( <h1 class="text-xl">查看文本</h1>
'flex flex-col max-h-full', <Button
!!previewText ? 'gap-3' : 'gap-16 items-center', v-if="!!previewText"
) variant="outline"
" size="icon"
> @click="
<h1 class="text-xl">查看文本</h1> () => {
<template v-if="!previewText"> copy(previewText as string)
<div class="flex flex-col gap-2 md:flex-row w-full"> toast.success('复制成功')
<div }
class="flex flex-row md:flex-col md:gap-1 justify-between items-center md:flex-1" "
v-for="item in fileShareInfo" >
> <LucideCopy />
<div class="text-xs opacity-75">{{ item?.label }}</div> </Button>
<component
v-if="isBoolean(item?.value)"
:is="item?.value ? LucideCheck : LucideX"
class="size-6"
/>
<div v-else class="md:text-xl">{{ item?.value }}</div>
</div> </div>
</div> <template v-if="!previewText">
<div class="w-full"> <div class="flex flex-col gap-2 md:flex-row w-full">
<AsyncButton @click="handlePreview" class="w-full">浏览</AsyncButton> <div class="flex flex-row md:flex-col md:gap-1 justify-between items-center md:flex-1" v-for="item in fileShareInfo">
</div> <div class="text-xs opacity-75">{{ item?.label }}</div>
</template> <component v-if="isBoolean(item?.value)" :is="item?.value ? LucideCheck : LucideX" class="size-6" />
<template v-else> <div v-else class="md:text-xl">{{ item?.value }}</div>
<MarkdownRender </div>
:markdown="previewText" </div>
class="rounded-md bg-white/70 p-3 w-full max-w-full min-h-80 overflow-y-auto" <div class="w-full">
/> <AsyncButton @click="handlePreview" class="w-full">浏览</AsyncButton>
</template> </div>
</div> </template>
<template v-else>
<MarkdownRender :markdown="previewText" class="rounded-md bg-white/70 p-3 w-full max-w-full min-h-80 overflow-y-auto" />
</template>
</div>
</template> </template>

View File

@@ -1,98 +1,102 @@
import { toast } from "vue-sonner"; import { toast } from 'vue-sonner'
let shareIdTokenMap: WeakMap<{ share_id: string }, string>; let shareIdTokenMap: WeakMap<{ share_id: string }, string>
const getShareToken = async (share_id: string): Promise<string | undefined> => { const getShareToken = async (share_id: string): Promise<string | undefined> => {
if (!shareIdTokenMap) { if (!shareIdTokenMap) {
shareIdTokenMap = new WeakMap(); shareIdTokenMap = new WeakMap()
}
let token = shareIdTokenMap.get({ share_id });
if (!token) {
const data = await $fetch<{
code: number;
message: string;
data: {
token?: string;
};
}>(`/api/download`, {
method: "POST",
body: {
share_id,
},
});
if (!data?.data?.token) {
throw new Error(data?.message || "获取token失败");
} }
token = data.data.token; let token = shareIdTokenMap.get({ share_id })
shareIdTokenMap.set({ share_id }, token); if (!token) {
} const data = await $fetch<{
return token; code: number
}; message: string
data: {
token?: string
}
}>(`/api/download`, {
method: 'POST',
body: {
share_id,
},
})
if (!data?.data?.token) {
throw new Error(data?.message || '获取token失败')
}
token = data.data.token
shareIdTokenMap.set({ share_id }, token)
}
return token
}
const downloadFile = async (share_id: string) => { const downloadFile = async (share_id: string) => {
try { try {
const token = await getShareToken(share_id); const token = await getShareToken(share_id)
if (!token) { if (!token) {
throw new Error("获取token失败"); throw new Error('获取token失败')
return; return
}
;(window as any)?.open(`/api/download?token=${token}`)
} catch (e) {
toast.error((e as any)?.data?.message || e)
} }
(window as any)?.open(`/api/download?token=${token}`); }
} catch (e) {
toast.error((e as any)?.data?.message || e);
}
};
const createShare = async (data: any) => { const createShare = async (data: any) => {
return await $fetch<{ return await $fetch<{
code: number; code: number
data: { data: {
id?: string; id?: string
}; download_nums?: number
}>(`/api/share`, { expire_at?: number
method: "POST", file_name?: string
body: data, pickup_code?: string
}); }
}; }>(`/api/share`, {
method: 'POST',
body: data,
})
}
const createFileShare = async (data: { const createFileShare = async (data: {
file_id: string; file_id: string
config: { config: {
download_nums: number; download_nums: number
expire_time: number; expire_time: number
has_pickup_code?: boolean; has_pickup_code?: boolean
has_password?: boolean; has_password?: boolean
pickup_code?: string; pickup_code?: string
password?: string; password?: string
notify_email?: string; notify_email?: string
}; }
file_name: string; file_name: string
}) => { }) => {
const { file_id, config, file_name } = data || {}; const { file_id, config, file_name } = data || {}
return await createShare({ return await createShare({
type: "file", type: 'file',
data: file_id, data: file_id,
config, config,
file_name, file_name,
}); })
}; }
const createTextShare = async (data: { text: string; config: any }) => { const createTextShare = async (data: { text: string; config: any }) => {
const { text, config } = data || {}; const { text, config } = data || {}
return await createShare({ return await createShare({
type: "text", type: 'text',
data: text, data: text,
config, config,
}); })
}; }
const useMyAppShare = () => { const useMyAppShare = () => {
return { return {
downloadFile, downloadFile,
createShare, createShare,
createFileShare, createFileShare,
createTextShare, createTextShare,
getShareToken, getShareToken,
}; }
}; }
export default useMyAppShare; export default useMyAppShare

View File

@@ -4,23 +4,45 @@ type UseSeoProps = {
} }
const useSeo = async (props: UseSeoProps = {}) => { const useSeo = async (props: UseSeoProps = {}) => {
const { head, seo } = props || {} const { head, seo } = props || {}
const { data } = await useFetch<any>('/config') const seoMeta = ref<any>()
const seoMeta = computed(() => data.value?.data) if (import.meta.server) {
const { title } = head || {} const { SITE_TITLE, SITE_DESC, SITE_URL } = process.env || {}
useHead({ seoMeta.value = {
...head, site_title: SITE_TITLE,
title: title ? `${title} - ${seoMeta?.value?.site_title}` : seoMeta?.value?.site_title, site_desc: SITE_DESC,
}) site_url: SITE_URL,
useSeoMeta({ }
...seo, const { title } = head || {}
title: seoMeta?.value?.site_title, useHead({
description: seoMeta?.value?.site_desc, link: [
ogTitle: seoMeta?.value?.site_title, { rel: 'icon', href: '/logo.png', sizes: 'any' },
ogDescription: seoMeta?.value?.site_desc, // { rel: 'icon', href: '/favicon.svg', sizes: 'any', type: 'image/svg+xml' },
// ogImage: seoMeta?.value?.site_url, { rel: 'apple-touch-icon', sizes: '180x180', href: '/logo.png' },
// twitterCard: 'summary_large_image', ],
}) meta: [
// used on some mobile browsers
{ name: 'theme-color', content: '#395276' },
],
...head,
title: title ? `${title} - ${seoMeta?.value?.site_title}` : seoMeta?.value?.site_title,
})
useSeoMeta({
...seo,
title: seoMeta?.value?.site_title,
description: seoMeta?.value?.site_desc,
ogTitle: seoMeta?.value?.site_title,
ogDescription: seoMeta?.value?.site_desc,
ogImage: {
url: `${seoMeta?.value?.site_url}/logo.png`,
width: 1024,
height: 1024,
alt: 'logo',
type: 'image/png',
},
twitterCard: 'summary',
})
}
return return
} }
export default useSeo export default useSeo

14
front/lib/asyncWorker.ts Normal file
View File

@@ -0,0 +1,14 @@
const asyncWorker = (w: new () => Worker, opts: { data: any }) => {
const { data } = opts || {}
return new Promise<MessageEvent>((resolve, reject) => {
const worker = new w()
worker.postMessage(data || {})
worker.onmessage = (e: MessageEvent) => {
resolve(e)
}
worker.onerror = (e: ErrorEvent) => {
reject(e)
}
})
}
export default asyncWorker

View File

@@ -1,44 +1,47 @@
import SparkMD5 from 'spark-md5'; import { noop } from 'lodash-es'
import { noop } from 'lodash-es'; import { md5 } from 'js-md5'
interface CalcFileHashProps { interface CalcFileHashProps {
file: File; file: File
onProgress?: (current: number) => void; onProgress?: (current: number) => void
chunkSize?: number; chunkSize?: number
} }
const calcFileHash = async (props: CalcFileHashProps) => { const calcFileHash = async (props: CalcFileHashProps) => {
const { file, onProgress = noop, chunkSize = 100 } = props || {}; const { file, onProgress = noop, chunkSize = 100 } = props || {}
const finalChunkSize = chunkSize * 1024 * 1024; const blob = await file.arrayBuffer()
const chunks = Math.ceil(file.size / finalChunkSize); const hash = md5(blob)
const spark = new SparkMD5.ArrayBuffer(); // 使用 SparkMD5 增量计算哈希 return hash
const fileReader = new FileReader(); // const finalChunkSize = chunkSize * 1024 * 1024;
// const chunks = Math.ceil(file.size / finalChunkSize);
// const spark = new SparkMD5.ArrayBuffer(); // 使用 SparkMD5 增量计算哈希
// const fileReader = new FileReader();
const readChunk = (start: number): Promise<ArrayBuffer> => { // const readChunk = (start: number): Promise<ArrayBuffer> => {
return new Promise((resolve, reject) => { // return new Promise((resolve, reject) => {
const chunk = file.slice(start, start + finalChunkSize); // const chunk = file.slice(start, Math.min(start + finalChunkSize, file.size));
fileReader.onload = (e) => resolve(e.target?.result as ArrayBuffer); // fileReader.onload = (e) => resolve(e.target?.result as ArrayBuffer);
fileReader.onerror = reject; // fileReader.onerror = reject;
fileReader.readAsArrayBuffer(chunk); // fileReader.readAsArrayBuffer(chunk);
}); // });
}; // };
try { // try {
const progressCallback = (current: number) => { // const progressCallback = (current: number) => {
const percentage = Math.round((current / chunks) * 100); // const percentage = Math.round((current / chunks) * 100);
onProgress(percentage); // onProgress(percentage);
}; // };
for (let i = 0; i < chunks; i++) { // for (let i = 0; i < chunks; i++) {
const chunk = await readChunk(i * chunkSize); // const chunk = await readChunk(i * chunkSize);
spark.append(chunk); // spark.append(chunk);
progressCallback(i + 1); // progressCallback(i + 1);
} // }
return spark.end(); // return spark.end();
} catch (error) { // } catch (error) {
throw error; // throw error;
} // }
} }
export default calcFileHash; export default calcFileHash

View File

@@ -0,0 +1,8 @@
import calcFileHash from './calcFileHash'
// 监听主线程消息
self.onmessage = async (e: MessageEvent<{ file: File }>) => {
const { file } = e.data || {}
const hash = await calcFileHash({ file })
self.postMessage({ hash })
}

View File

@@ -1,70 +1,71 @@
{ {
"name": "015-front", "name": "015-front",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
"build": "nuxt build", "build": "nuxt build",
"dev": "nuxt dev", "dev": "nuxt dev",
"generate": "nuxt generate", "generate": "nuxt generate",
"preview": "nuxt preview", "preview": "nuxt preview",
"postinstall": "nuxt prepare" "postinstall": "nuxt prepare"
}, },
"dependencies": { "dependencies": {
"@nuxt/image": "1.10.0", "@nuxt/image": "1.10.0",
"@nuxtjs/i18n": "9.5.5", "@nuxtjs/i18n": "9.5.5",
"@pinia/nuxt": "^0.11.0", "@pinia/nuxt": "^0.11.0",
"@tailwindcss/postcss": "^4.1.3", "@tailwindcss/postcss": "^4.1.3",
"@tailwindcss/vite": "^4.1.3", "@tailwindcss/vite": "^4.1.3",
"@tanstack/vue-query": "^5.76.0", "@tanstack/vue-query": "^5.76.0",
"@tiptap/extension-blockquote": "^2.11.7", "@tiptap/extension-blockquote": "^2.11.7",
"@tiptap/extension-bold": "^2.11.7", "@tiptap/extension-bold": "^2.11.7",
"@tiptap/extension-heading": "^2.11.7", "@tiptap/extension-heading": "^2.11.7",
"@tiptap/extension-italic": "^2.11.7", "@tiptap/extension-italic": "^2.11.7",
"@tiptap/extension-paragraph": "^2.11.7", "@tiptap/extension-paragraph": "^2.11.7",
"@tiptap/extension-placeholder": "^2.11.7", "@tiptap/extension-placeholder": "^2.11.7",
"@tiptap/extension-strike": "^2.11.7", "@tiptap/extension-strike": "^2.11.7",
"@tiptap/extension-text": "^2.11.7", "@tiptap/extension-text": "^2.11.7",
"@tiptap/pm": "^2.11.7", "@tiptap/pm": "^2.11.7",
"@tiptap/starter-kit": "^2.11.7", "@tiptap/starter-kit": "^2.11.7",
"@tiptap/vue-3": "^2.11.7", "@tiptap/vue-3": "^2.11.7",
"@unovis/ts": "^1.5.1", "@unovis/ts": "^1.5.1",
"@unovis/vue": "^1.5.1", "@unovis/vue": "^1.5.1",
"@vee-validate/nuxt": "^4.15.0", "@vee-validate/nuxt": "^4.15.0",
"@vee-validate/rules": "^4.15.0", "@vee-validate/rules": "^4.15.0",
"axios": "^1.8.4", "axios": "^1.8.4",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"filesize": "^10.1.6", "filesize": "^10.1.6",
"lodash-es": "^4.17.21", "js-md5": "^0.8.3",
"lucide-vue-next": "^0.487.0", "lodash-es": "^4.17.21",
"markdown-it": "^14.1.0", "lucide-vue-next": "^0.487.0",
"motion-v": "1.0.0-beta.2", "markdown-it": "^14.1.0",
"nuxt": "^3.17.4", "motion-v": "1.0.0-beta.2",
"nuxt-lucide-icons": "1.0.5", "nuxt": "^3.17.4",
"pinia": "^3.0.2", "nuxt-lucide-icons": "1.0.5",
"qrcode": "^1.5.4", "pinia": "^3.0.2",
"reka-ui": "^2.2.0", "qrcode": "^1.5.4",
"vue": "^3.5.16", "reka-ui": "^2.2.0",
"vue-router": "^4.5.1", "shadcn-nuxt": "2.0.1",
"vue-sonner": "^1.3.2", "spark-md5": "^3.0.2",
"shadcn-nuxt": "2.0.1", "tailwind-merge": "^3.2.0",
"spark-md5": "^3.0.2", "tailwindcss": "^4.1.3",
"tailwind-merge": "^3.2.0", "tiptap-markdown": "^0.8.10",
"tailwindcss": "^4.1.3", "tw-animate-css": "^1.2.5",
"tiptap-markdown": "^0.8.10", "vaul-vue": "^0.4.1",
"tw-animate-css": "^1.2.5", "vue": "^3.5.16",
"vaul-vue": "^0.4.1" "vue-router": "^4.5.1",
}, "vue-sonner": "^1.3.2"
"packageManager": "pnpm@9.11.0+sha512.0a203ffaed5a3f63242cd064c8fb5892366c103e328079318f78062f24ea8c9d50bc6a47aa3567cabefd824d170e78fa2745ed1f16b132e16436146b7688f19b", },
"devDependencies": { "packageManager": "pnpm@9.11.0+sha512.0a203ffaed5a3f63242cd064c8fb5892366c103e328079318f78062f24ea8c9d50bc6a47aa3567cabefd824d170e78fa2745ed1f16b132e16436146b7688f19b",
"@nuxtjs/tailwindcss": "^6.13.2", "devDependencies": {
"@tailwindcss/typography": "^0.5.16", "@nuxtjs/tailwindcss": "^6.13.2",
"@types/markdown-it": "^14.1.2", "@tailwindcss/typography": "^0.5.16",
"@types/qrcode": "^1.5.5", "@types/lodash-es": "^4.17.12",
"@types/lodash-es": "^4.17.12", "@types/markdown-it": "^14.1.2",
"@types/spark-md5": "^3.0.5", "@types/qrcode": "^1.5.5",
"@vueuse/core": "^13.0.0", "@types/spark-md5": "^3.0.5",
"@vueuse/nuxt": "^13.0.0" "@vueuse/core": "^13.0.0",
} "@vueuse/nuxt": "^13.0.0"
}
} }

View File

@@ -1,240 +1,213 @@
<script setup lang="ts"> <script setup lang="ts">
import { CurveType } from "@unovis/ts"; import { CurveType } from '@unovis/ts'
import { AreaChart } from "@/components/ui/chart-area"; import { AreaChart } from '@/components/ui/chart-area'
import { cx } from "class-variance-authority"; import { cx } from 'class-variance-authority'
import { useQuery } from "@tanstack/vue-query"; import { useQuery } from '@tanstack/vue-query'
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from '@/components/ui/skeleton'
import AboutChartTooltip from "@/components/AboutChartTooltip.vue"; import AboutChartTooltip from '@/components/AboutChartTooltip.vue'
import { filesize } from "filesize"; import { filesize } from 'filesize'
import SparkMD5 from "spark-md5"; import SparkMD5 from 'spark-md5'
import useMyAppConfig from "@/composables/useMyAppConfig"; import useMyAppConfig from '@/composables/useMyAppConfig'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import Progress from '~/components/ui/progress/Progress.vue'
const appConfig = useMyAppConfig(); dayjs.extend(relativeTime)
const { site_title, site_desc } = appConfig.value || {};
const appConfig = useMyAppConfig()
const { site_title, site_desc } = appConfig.value || {}
const { data, isLoading } = useQuery({ const { data, isLoading } = useQuery({
queryKey: ["stat"], queryKey: ['stat'],
queryFn: async () => { queryFn: async () => {
const data = await $fetch<{ data: any }>("/api/stat"); const data = await $fetch<{ data: any }>('/api/stat')
return data.data; return data.data
}, },
}); })
const { t } = useI18n(); const { t } = useI18n()
const chartTabs = computed(() => { const chartTabs = computed(() => {
return [ return [
{ {
label: t("about.file"), label: t('about.file'),
value: "storage", value: 'storage',
total: total: data.value?.chart?.storage?.reduce((acc: number, curr: { file_size: number; file_num: number }) => acc + curr.file_num, 0) ?? 0,
data.value?.chart?.storage?.reduce( },
(acc: number, curr: { file_size: number; file_num: number }) => {
acc + curr.file_num, label: t('about.task'),
0, value: 'queue',
) ?? 0, total:
}, data.value?.chart?.queue?.reduce(
{ (acc: number, curr: { processed: number; failed: number }) => acc + curr.processed + curr.failed,
label: t("about.task"), 0
value: "queue", ) ?? 0,
total: },
data.value?.chart?.queue?.reduce( ]
(acc: number, curr: { processed: number; failed: number }) => })
acc + curr.processed + curr.failed,
0,
) ?? 0,
},
];
});
const currentFileSize = computed(() => { const currentFileSize = computed(() => {
return ( return data.value?.chart?.storage?.reduce((acc: number, curr: { file_size: number; file_num: number }) => acc + curr.file_size, 0) ?? 0
data.value?.chart?.storage?.reduce( })
(acc: number, curr: { file_size: number; file_num: number }) =>
acc + curr.file_size,
0,
) ?? 0
);
});
const currentChartTab = ref<"storage" | "queue">("storage"); const currentChartTab = ref<'storage' | 'queue'>('storage')
const currentChartData = computed(() => { const currentChartData = computed(() => {
const { storage, queue } = data.value?.chart || {}; const { storage, queue } = data.value?.chart || {}
if (currentChartTab.value === "storage") { if (currentChartTab.value === 'storage') {
return {
data: storage,
index: 'date',
categories: ['file_size', 'file_num'],
colors: ['#22d3ee', '#c084fc'],
}
}
return { return {
data: storage, data: queue,
index: "date", index: 'date',
categories: ["file_size", "file_num"], categories: ['processed', 'failed'],
colors: ["#22d3ee", "#c084fc"], colors: ['#4ade80', '#f87171'],
}; }
} })
return {
data: queue,
index: "date",
categories: ["processed", "failed"],
colors: ["#4ade80", "#f87171"],
};
});
const genUserAvatar = ({ email }: { email: string }) => { const genUserAvatar = ({ email }: { email: string }) => {
if (!email) { if (!email) {
return "/logo.png"; return '/logo.png'
} }
return `https://www.gravatar.com/avatar/${SparkMD5.hash(email)}?d=retro`; return `https://www.gravatar.com/avatar/${SparkMD5.hash(email)}?d=retro`
}; }
const handleUserClick = ({ url, email }: { url: string; email: string }) => { const handleUserClick = ({ url, email }: { url: string; email: string }) => {
if (url) { if (url) {
return navigateTo(url, { external: true }); return navigateTo(url, { external: true })
} }
if (email) { if (email) {
return navigateTo(`mailto:${email}`, { external: true }); return navigateTo(`mailto:${email}`, { external: true })
} }
return null; return null
}; }
const users = computed(() => { const users = computed(() => {
const { email, name, url } = data.value?.admin || {}; const { email, name, url } = data.value?.admin || {}
return [ return [
...(!!name ...(!!name
? [ ? [
{ {
title: t("about.admin"), title: t('about.admin'),
email, email,
name, name,
url: url ?? (email ? `mailto:${email}` : null), url: url ?? (email ? `mailto:${email}` : null),
}, },
] ]
: []), : []),
{ {
title: t("about.author"), title: t('about.author'),
name: "keven1024", name: 'keven1024',
email: "keven@fudaoyuan.icu", email: 'keven@fudaoyuan.icu',
url: "https://github.com/keven1024", url: 'https://github.com/keven1024',
}, },
]; ]
}); })
</script> </script>
<template> <template>
<div <div class="rounded-xl p-5 bg-white/50 backdrop-blur-xl w-full lg:w-200 my-5 flex flex-col gap-5">
class="rounded-xl p-5 bg-white/50 backdrop-blur-xl w-full lg:w-200 my-5 flex flex-col gap-5" <div class="text-xl font-normal">{{ t('about.title') }}</div>
> <div class="flex flex-col gap-2 items-center">
<div class="text-xl font-normal">{{ t("about.title") }}</div> <NuxtImg src="/logo.png" class="size-20 rounded-xl" />
<div class="flex flex-col gap-2 items-center"> <div class="text-xl">{{ site_title ?? '015' }}</div>
<NuxtImg src="/logo.png" class="size-20 rounded-xl" /> <div class="text-sm opacity-75 text-center px-5">
<div class="text-xl">{{ site_title ?? "015" }}</div> {{ site_desc ?? t('seo.desc') }}
<div class="text-sm opacity-75 text-center px-5">
{{ site_desc ?? t("seo.desc") }}
</div>
</div>
<div class="font-semibold">{{ t("about.systemInfo") }}</div>
<template v-if="isLoading">
<div class="flex flex-row gap-2">
<Skeleton class="w-full h-20 rounded-xl" v-for="i in 2" :key="i" />
</div>
</template>
<template v-else>
<div class="grid grid-cols-2 gap-2">
<div class="rounded-xl bg-white/50 flex-1 flex flex-col p-3">
<div class="opacity-75 text-xs">{{ t("about.systemVersion") }}</div>
<div class="text-xl font-semibold">
{{ data?.version ?? "dev" }}
</div>
</div>
<div class="rounded-xl bg-white/50 flex-1 flex flex-col p-3">
<div class="opacity-75 text-xs">{{ t("about.storage") }}</div>
<div class="text-right flex flex-row items-baseline">
<span class="text-lg font-semibold">{{
filesize(currentFileSize ?? 0)
}}</span>
<span class="text-md opacity-75"
>/ {{ filesize(data?.max_limit?.file_size ?? 0) }}</span
>
</div>
<div class="rounded-full w-full h-1 bg-black/10">
<div
class="rounded-full h-full bg-blue-500"
:style="{
width: `${(currentFileSize / (data?.max_limit?.file_size ?? 0)) * 100}%`,
}"
></div>
</div>
</div>
</div>
</template>
<div class="font-semibold">{{ t("about.analysis") }}</div>
<template v-if="isLoading">
<div class="flex flex-row gap-2">
<Skeleton class="w-full h-96 rounded-xl" />
</div>
</template>
<template v-else>
<div class="flex flex-col gap-2 bg-white/50 w-full rounded-xl py-5">
<div class="flex flex-row gap-2 px-5">
<div
:class="
cx(
'rounded-md min-w-30 flex flex-col px-3 py-1.5 cursor-pointer',
currentChartTab === tab.value && 'bg-black/10',
)
"
v-for="tab in chartTabs"
:key="tab.value"
@click="
() => {
currentChartTab = tab.value as 'storage' | 'queue';
}
"
>
<div class="opacity-75 text-xs">{{ tab.label }}</div>
<div class="text-lg font-semibold">{{ tab.total }}</div>
</div>
</div>
<AreaChart
v-if="currentChartData"
class="h-64 w-full"
:key="currentChartTab"
:index="currentChartData.index"
:data="currentChartData.data"
:categories="currentChartData.categories"
:show-grid-line="false"
:show-legend="false"
:show-y-axis="true"
:show-x-axis="true"
:colors="currentChartData.colors"
:custom-tooltip="AboutChartTooltip"
:curve-type="CurveType.CatmullRom"
/>
</div>
</template>
<template v-if="isLoading">
<div class="flex flex-row gap-2">
<Skeleton class="w-full h-20 rounded-xl" v-for="i in 2" :key="i" />
</div>
</template>
<template v-else>
<div class="grid grid-cols-1 md:grid-cols-2 gap-2">
<div class="flex flex-col gap-3" v-for="user in users" :key="user.name">
<div class="font-semibold">{{ user.title }}</div>
<div
class="rounded-xl bg-white/50 hover:bg-white/40 flex-1 flex flex-row items-center gap-2 p-3 cursor-pointer"
@click="
() => {
handleUserClick(user);
}
"
>
<div class="size-10 rounded-full bg-white/50">
<NuxtImg
:src="genUserAvatar(user)"
class="size-full rounded-full"
/>
</div> </div>
<div class="text-md font-semibold">{{ user.name }}</div>
</div>
</div> </div>
</div> <div class="font-semibold">{{ t('about.systemInfo') }}</div>
</template> <template v-if="isLoading">
</div> <div class="flex flex-row gap-2">
<Skeleton class="w-full h-20 rounded-xl" v-for="i in 2" :key="i" />
</div>
</template>
<template v-else>
<div class="grid grid-cols-2 gap-2">
<div class="rounded-xl bg-white/50 flex-1 flex flex-col p-3">
<div class="opacity-75 text-xs">{{ t('about.systemVersion') }}</div>
<div class="text-xl font-semibold flex items-center gap-1">
{{ data?.version ?? 'dev' }}
<span class="text-xs px-2 py-0.5 rounded bg-primary/20 text-primary">{{ dayjs(data?.build_time * 1000).fromNow() }}</span>
</div>
</div>
<div class="rounded-xl bg-white/50 flex-1 flex flex-col p-3">
<div class="opacity-75 text-xs">{{ t('about.storage') }}</div>
<div class="text-right flex flex-row items-baseline">
<span class="text-lg font-semibold">{{ filesize(currentFileSize ?? 0) }}</span>
<span class="text-md opacity-75">/ {{ filesize(data?.max_limit?.file_size ?? 0) }}</span>
</div>
<Progress class="h-1" :model-value="(currentFileSize / (data?.max_limit?.file_size ?? 0)) * 100" />
</div>
</div>
</template>
<div class="font-semibold">{{ t('about.analysis') }}</div>
<template v-if="isLoading">
<div class="flex flex-row gap-2">
<Skeleton class="w-full h-96 rounded-xl" />
</div>
</template>
<template v-else>
<div class="flex flex-col gap-2 bg-white/50 w-full rounded-xl py-5">
<div class="flex flex-row gap-2 px-5">
<div
:class="cx('rounded-md min-w-30 flex flex-col px-3 py-1.5 cursor-pointer', currentChartTab === tab.value && 'bg-black/10')"
v-for="tab in chartTabs"
:key="tab.value"
@click="
() => {
currentChartTab = tab.value as 'storage' | 'queue'
}
"
>
<div class="opacity-75 text-xs">{{ tab.label }}</div>
<div class="text-lg font-semibold">{{ tab.total }}</div>
</div>
</div>
<AreaChart
v-if="currentChartData"
class="h-64 w-full"
:key="currentChartTab"
:index="currentChartData.index"
:data="currentChartData.data"
:categories="currentChartData.categories"
:show-grid-line="false"
:show-legend="false"
:show-y-axis="true"
:show-x-axis="true"
:colors="currentChartData.colors"
:custom-tooltip="AboutChartTooltip"
:curve-type="CurveType.CatmullRom"
/>
</div>
</template>
<template v-if="isLoading">
<div class="flex flex-row gap-2">
<Skeleton class="w-full h-20 rounded-xl" v-for="i in 2" :key="i" />
</div>
</template>
<template v-else>
<div class="grid grid-cols-1 md:grid-cols-2 gap-2">
<div class="flex flex-col gap-3" v-for="user in users" :key="user.name">
<div class="font-semibold">{{ user.title }}</div>
<div
class="rounded-xl bg-white/50 hover:bg-white/40 flex-1 flex flex-row items-center gap-2 p-3 cursor-pointer"
@click="
() => {
handleUserClick(user)
}
"
>
<div class="size-10 rounded-full bg-white/50">
<NuxtImg :src="genUserAvatar(user)" class="size-full rounded-full" />
</div>
<div class="text-md font-semibold">{{ user.name }}</div>
</div>
</div>
</div>
</template>
</div>
</template> </template>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

8
pnpm-lock.yaml generated
View File

@@ -101,6 +101,9 @@ importers:
filesize: filesize:
specifier: ^10.1.6 specifier: ^10.1.6
version: 10.1.6 version: 10.1.6
js-md5:
specifier: ^0.8.3
version: 0.8.3
lodash-es: lodash-es:
specifier: ^4.17.21 specifier: ^4.17.21
version: 4.17.21 version: 4.17.21
@@ -4262,6 +4265,9 @@ packages:
resolution: {integrity: sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==} resolution: {integrity: sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==}
hasBin: true hasBin: true
js-md5@0.8.3:
resolution: {integrity: sha512-qR0HB5uP6wCuRMrWPTrkMaev7MJZwJuuw4fnwAzRgP4J4/F8RwtodOKpGp4XpqsLBFzzgqIO42efFAyz2Et6KQ==}
js-tokens@4.0.0: js-tokens@4.0.0:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
@@ -11284,6 +11290,8 @@ snapshots:
jiti@2.4.2: {} jiti@2.4.2: {}
js-md5@0.8.3: {}
js-tokens@4.0.0: {} js-tokens@4.0.0: {}
js-tokens@9.0.1: {} js-tokens@9.0.1: {}