Compare commits
168 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47781ff374 | ||
|
|
7760697233 | ||
|
|
8f1ced62ac | ||
|
|
72560cf233 | ||
|
|
62443f38a4 | ||
|
|
5c264a4297 | ||
|
|
332fa7195f | ||
|
|
4ce68d91a8 | ||
|
|
78cfc3943c | ||
|
|
7772a935d7 | ||
|
|
7d204345cc | ||
|
|
f9251663a2 | ||
|
|
75c269b60e | ||
|
|
64126e7c4c | ||
|
|
f8a43c9b1f | ||
|
|
9aa52915b0 | ||
|
|
fe66240671 | ||
|
|
1635a31f33 | ||
|
|
67b1d07fbe | ||
|
|
ceb2d026d2 | ||
|
|
123178084a | ||
|
|
183297bd2c | ||
|
|
55900224ae | ||
|
|
a64fa95608 | ||
|
|
70fc2be02f | ||
|
|
e14eed73c4 | ||
|
|
4a8932f921 | ||
|
|
60831c779e | ||
|
|
7663e8eb0a | ||
|
|
fe6c832275 | ||
|
|
f1dec39851 | ||
|
|
59cd23daf7 | ||
|
|
7ca301e54d | ||
|
|
6d7dc6bc40 | ||
|
|
bde4e36e47 | ||
|
|
e5b5def6f0 | ||
|
|
ed7ac4e657 | ||
|
|
22637bcf6e | ||
|
|
3d8d1ccd3f | ||
|
|
ae7db9de02 | ||
|
|
6304dffa39 | ||
|
|
2ea2d89f44 | ||
|
|
b98853ebe1 | ||
|
|
e9d0848f87 | ||
|
|
155c697e53 | ||
|
|
301dcaf8b6 | ||
|
|
8f3bafcbfb | ||
|
|
b471972dd4 | ||
|
|
8c4c7b0471 | ||
|
|
9679a42be2 | ||
|
|
e43d27958d | ||
|
|
31c0736562 | ||
|
|
185f7a3503 | ||
|
|
90607aad7c | ||
|
|
e250202deb | ||
|
|
e8653a8e8b | ||
|
|
b4a4be09fa | ||
|
|
bfe9a8f3d6 | ||
|
|
a71cc5e919 | ||
|
|
18a626fd04 | ||
|
|
ca33fcc332 | ||
|
|
85c6b4582f | ||
|
|
9eaf06e7a8 | ||
|
|
0c980e8b6c | ||
|
|
831d9b2660 | ||
|
|
dd3ced5b03 | ||
|
|
d7d2a5c00b | ||
|
|
a82c894119 | ||
|
|
d4b0368ae2 | ||
|
|
f317e0f538 | ||
|
|
e17b1a04c5 | ||
|
|
04ebb22d35 | ||
|
|
552434e389 | ||
|
|
d5fc54de31 | ||
|
|
675a6e860a | ||
|
|
18a74b6545 | ||
|
|
313ce4455f | ||
|
|
208875841e | ||
|
|
35c5e1ccec | ||
|
|
6da3d9a15d | ||
|
|
23c33fc52e | ||
|
|
4f4139159e | ||
|
|
62463494b4 | ||
|
|
c8fd8c874b | ||
|
|
a8f0fb2bf3 | ||
|
|
70d35a1a15 | ||
|
|
4355a29a52 | ||
|
|
9e2a6411ec | ||
|
|
d8bc68b008 | ||
|
|
d2478dd23b | ||
|
|
647417fb4e | ||
|
|
ea0065b415 | ||
|
|
2194c9687f | ||
|
|
99538c6fdb | ||
|
|
0f0814ce40 | ||
|
|
15922ea2df | ||
|
|
52af187fe9 | ||
|
|
9fff65d0d7 | ||
|
|
da58c53909 | ||
|
|
07fc182ccb | ||
|
|
028d0c10fe | ||
|
|
b4f577e758 | ||
|
|
84c104be90 | ||
|
|
a4b3dad85e | ||
|
|
6238897c18 | ||
|
|
c931d10485 | ||
|
|
dd05510d27 | ||
|
|
5de6ed9eea | ||
|
|
7166ec5cb3 | ||
|
|
8676b12a66 | ||
|
|
d8c9491a99 | ||
|
|
e6cc1b0229 | ||
|
|
50c0a14cc6 | ||
|
|
1ed154913d | ||
|
|
12efc10e0e | ||
|
|
b80cb0c2d8 | ||
|
|
d294027463 | ||
|
|
a66c5a26b0 | ||
|
|
27fcfd73d9 | ||
|
|
f525f48a8a | ||
|
|
9961609e64 | ||
|
|
ff58262725 | ||
|
|
80a01a2849 | ||
|
|
8924de58c0 | ||
|
|
41b0076464 | ||
|
|
fa17009695 | ||
|
|
8fad0a4163 | ||
|
|
836a3c866a | ||
|
|
045031dd3c | ||
|
|
3e8c782315 | ||
|
|
77667024fd | ||
|
|
9902f46c7a | ||
|
|
164d07b8e0 | ||
|
|
b59aec2d97 | ||
|
|
0df8ee0a8d | ||
|
|
083005dac3 | ||
|
|
e959a0bc3e | ||
|
|
6bd008f119 | ||
|
|
d306581e34 | ||
|
|
f34ea51725 | ||
|
|
218387151f | ||
|
|
427d958a41 | ||
|
|
8b0d90cdc3 | ||
|
|
0a9d414751 | ||
|
|
f1c2e1a3d7 | ||
|
|
cfe166e8c9 | ||
|
|
29300a9448 | ||
|
|
2a24f713cb | ||
|
|
427f1f6456 | ||
|
|
c8f36e6f8e | ||
|
|
03ccd13f8f | ||
|
|
b2c0e85844 | ||
|
|
c1ec2aee5b | ||
|
|
3d173d0321 | ||
|
|
4d0a6f0a49 | ||
|
|
e41d7a6305 | ||
|
|
60af6d2023 | ||
|
|
dc16661fff | ||
|
|
f36221de05 | ||
|
|
e556b0f39d | ||
|
|
13cbf5e5ed | ||
|
|
8392b26455 | ||
|
|
c64c152124 | ||
|
|
ecc4aefd33 | ||
|
|
590a071dfb | ||
|
|
cf2d81bf9a | ||
|
|
e62f329d53 | ||
|
|
421955a844 |
16
.env.example
@@ -1,16 +0,0 @@
|
||||
# 你的下载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" # 指定实例最大上传容量,支持填写人类可读的值,比如1TB,500GB等
|
||||
|
||||
# (可选): 系统状态页面显示站长信息的 头像会使用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"
|
||||
31
.gitea/workflows/build.yaml
Normal file
@@ -0,0 +1,31 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
build-test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
- name: Set build time
|
||||
id: build-time
|
||||
run: echo "time=$(date +%s)" >> $GITHUB_OUTPUT
|
||||
- name: build-app
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
push: false
|
||||
tags: 015-app:test
|
||||
build-args: |
|
||||
VERSION=${{ gitea.ref_name || github.ref_name }}
|
||||
BUILD_TIME=${{ steps.build-time.outputs.time }}
|
||||
- name: build-worker
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./worker/Dockerfile
|
||||
push: false
|
||||
tags: 015-worker:test
|
||||
47
.gitea/workflows/lint.yaml
Normal file
@@ -0,0 +1,47 @@
|
||||
name: Lint
|
||||
|
||||
on:
|
||||
push:
|
||||
|
||||
jobs:
|
||||
lint-front:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '24'
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
cache: true
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
- name: Run frontend lint
|
||||
run: pnpm lint:front
|
||||
|
||||
lint-backend:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.work'
|
||||
- name: Run golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
skip-cache: true
|
||||
working-directory: backend
|
||||
|
||||
lint-worker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.work'
|
||||
- name: Run golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
skip-cache: true
|
||||
working-directory: worker
|
||||
84
.gitea/workflows/publish.yaml
Normal file
@@ -0,0 +1,84 @@
|
||||
name: Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
build-app:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: docker/setup-qemu-action@v3
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
- uses: docker/login-action@v3
|
||||
with:
|
||||
username: fudaoyuanicu
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
- uses: docker/metadata-action@v5
|
||||
id: meta
|
||||
with:
|
||||
images: fudaoyuanicu/015-app
|
||||
tags: |
|
||||
type=pep440,pattern={{version}}
|
||||
type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', 'main') }}
|
||||
- name: Set build time
|
||||
id: build-time
|
||||
run: |
|
||||
echo "time=$(date +%s)" >> $GITHUB_OUTPUT
|
||||
shell: bash
|
||||
- name: build-app
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
build-args: |
|
||||
VERSION=${{ gitea.ref_name || github.ref_name }}
|
||||
BUILD_TIME=${{ steps.build-time.outputs.time }}
|
||||
|
||||
build-worker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: docker/setup-qemu-action@v3
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
- uses: docker/login-action@v3
|
||||
with:
|
||||
username: fudaoyuanicu
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
- uses: docker/metadata-action@v5
|
||||
id: meta
|
||||
with:
|
||||
images: fudaoyuanicu/015-worker
|
||||
tags: |
|
||||
type=pep440,pattern={{version}}
|
||||
type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', 'main') }}
|
||||
- name: Set build time
|
||||
id: build-time
|
||||
run: |
|
||||
echo "time=$(date +%s)" >> $GITHUB_OUTPUT
|
||||
shell: bash
|
||||
- name: build-worker
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./worker/Dockerfile
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build-app, build-worker]
|
||||
steps:
|
||||
- name: Send deployment webhook
|
||||
run: |
|
||||
curl -X POST http://192.168.100.5:8364/v1/update \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer helloworld"
|
||||
BIN
.github/image/0.png
vendored
Normal file
|
After Width: | Height: | Size: 716 KiB |
0
docs/image/3.png → .github/image/1.png
vendored
|
Before Width: | Height: | Size: 1.0 MiB After Width: | Height: | Size: 1.0 MiB |
0
docs/image/4.png → .github/image/2.png
vendored
|
Before Width: | Height: | Size: 1.0 MiB After Width: | Height: | Size: 1.0 MiB |
BIN
.github/image/3.png
vendored
Normal file
|
After Width: | Height: | Size: 1.4 MiB |
BIN
.github/image/4.png
vendored
Normal file
|
After Width: | Height: | Size: 750 KiB |
BIN
.github/image/5.png
vendored
Normal file
|
After Width: | Height: | Size: 807 KiB |
BIN
.github/image/6.png
vendored
Normal file
|
After Width: | Height: | Size: 1.1 MiB |
1
.gitignore
vendored
@@ -22,6 +22,7 @@ logs
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
config.yaml
|
||||
|
||||
# Serwist
|
||||
/front/public/sw*
|
||||
|
||||
5
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"i18n-ally.localesPaths": ["front/i18n/locales"],
|
||||
"i18n-ally.enabledFrameworks": ["vue"],
|
||||
"i18n-ally.keystyle": "nested"
|
||||
}
|
||||
25
Dockerfile
@@ -5,7 +5,7 @@ FROM front-base AS front-deps
|
||||
RUN apk add --no-cache gcompat
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN corepack enable pnpm && pnpm i && pnpm --filter=015-front deploy dist
|
||||
RUN corepack enable pnpm && pnpm i && pnpm --filter=015-front deploy dist --legacy
|
||||
|
||||
|
||||
FROM front-base AS front-builder
|
||||
@@ -13,16 +13,17 @@ WORKDIR /app
|
||||
COPY --from=front-deps /app/dist/ .
|
||||
RUN corepack enable pnpm && pnpm build
|
||||
|
||||
FROM golang:1.23.1 AS backend-builder
|
||||
FROM golang:1.25.5 AS backend-builder
|
||||
WORKDIR /app
|
||||
# Download Go modules
|
||||
COPY backend/go.mod backend/go.sum ./
|
||||
RUN go env -w GO111MODULE=on && go env -w GOPROXY=https://goproxy.cn,direct && go mod download
|
||||
# Copy the source code. Note the slash at the end, as explained in
|
||||
# https://docs.docker.com/engine/reference/builder/#copy
|
||||
COPY backend/ .
|
||||
# Build
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -o backend
|
||||
# Workspace and module manifests for cache
|
||||
COPY go.work go.work.sum ./
|
||||
COPY backend/ ./backend/
|
||||
COPY worker/ ./worker/
|
||||
COPY pkg/ ./pkg/
|
||||
RUN go env -w GO111MODULE=on && go env -w GOPROXY=https://goproxy.cn,direct && \
|
||||
go mod download
|
||||
# Build from workspace root so pkg/utils, pkg/models, pkg/services resolve
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -o backend-bin ./backend
|
||||
|
||||
|
||||
FROM front-base AS runner
|
||||
@@ -37,13 +38,11 @@ RUN adduser --system --uid 1001 nuxtjs
|
||||
|
||||
# Only `.output` folder is needed from the build stage
|
||||
COPY --from=front-builder --chown=nuxtjs:nodejs /app/.output/ ./
|
||||
COPY --from=backend-builder /app/backend /bin/backend
|
||||
COPY --from=backend-builder /app/backend-bin /bin/backend
|
||||
COPY 015.sh /app/015.sh
|
||||
|
||||
# Change the port and host
|
||||
ENV PORT=80 HOST=0.0.0.0
|
||||
ENV SITE_URL="http://localhost"
|
||||
ENV UPLOAD_PATH="/uploads"
|
||||
ENV VERSION=${VERSION}
|
||||
ENV BUILD_TIME=${BUILD_TIME}
|
||||
|
||||
|
||||
235
LICENSE
Normal file
@@ -0,0 +1,235 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
interview
|
||||
Copyright (C) 2025 keven
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
|
||||
@@ -1,10 +1,16 @@
|
||||
<div align="center"><a name="readme-top"></a>
|
||||
|
||||
# 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 构建的现代文件分享网站,支持文件上传、文本分享、图片压缩、并发处理、秒传功能等,具备完整的分享管理和访问控制体系。
|
||||
|
||||

|
||||

|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
</div>
|
||||
|
||||
## 🌟 功能特性
|
||||
|
||||
@@ -33,101 +39,90 @@
|
||||
📷 **图片处理** - 图片压缩、格式转换等处理功能
|
||||
🏷️ **下载控制** - 基于 JWT 的下载令牌管理系统
|
||||
|
||||
## 截图
|
||||
## 📸 截图预览
|
||||
|
||||

|
||||
| 选择文件上传页面 | 输入文本上传页面 |
|
||||
|---------------------------------------|-----------------------------------------------|
|
||||
|  |  |
|
||||
|
||||

|
||||
| 多选文件上传 | 文件上传进度热力图 |
|
||||
|------------------------------------------------|---------------------------------------------------|
|
||||
|  |  |
|
||||
|
||||

|
||||
| 文件上传进度条 | 文件上传成功页面 |
|
||||
|------------------------------------------------|-------------------------------------------------|
|
||||
|  |  |
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### Docker
|
||||
|
||||
1. 下载文件
|
||||
- config.example.yaml
|
||||
- docker-compose.yml
|
||||
|
||||
2. 把config.example.yaml配置完成后改为config.yaml
|
||||
|
||||
|
||||
3. 启动
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### Docker
|
||||
|
||||
1. 下载文件
|
||||
- config.example.yaml
|
||||
- docker-compose.yml
|
||||
|
||||
2. 把config.example.yaml配置完成后改为config.yaml
|
||||
|
||||
|
||||
3. 启动
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||

|
||||
|
||||
## 🏗️ 技术架构
|
||||
|
||||
### 前端技术栈
|
||||
|
||||
- **Vue 3** - 渐进式 JavaScript 框架
|
||||
- **Nuxt 3** - Vue.js 全栈框架
|
||||
- **TypeScript** - 完整的类型安全
|
||||
- **Tailwind CSS** - 原子化 CSS 框架
|
||||
- **Reka UI** - 现代化组件库
|
||||
- **Pinia** - 状态管理
|
||||
- **TanStack Query** - 数据获取和缓存
|
||||
- **Vue Router** - 路由管理
|
||||
- **i18next** - 国际化支持
|
||||
- **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** - 结构化日志
|
||||
- **Go 1.23** - 高性能服务器端语言
|
||||
- **Echo** - 高性能 HTTP 框架
|
||||
- **Redis** - 缓存和会话存储
|
||||
- **Asynq** - 异步任务队列
|
||||
- **JWT** - 身份验证
|
||||
- **Zap** - 结构化日志
|
||||
|
||||
### 构建系统
|
||||
|
||||
- **Node.js** - 服务器端运行时
|
||||
- **pnpm** - 快速包管理器
|
||||
- **Husky** - Git hooks 管理
|
||||
- **Prettier** - 代码格式化
|
||||
- **Lint-staged** - 暂存文件检查
|
||||
- **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 服务
|
||||
```
|
||||
- **文件存储** - 本地文件系统存储
|
||||
- **Redis 缓存** - 分享信息、文件元数据缓存
|
||||
- **队列系统** - 异步任务处理队列
|
||||
|
||||
## 📁 项目结构
|
||||
|
||||
@@ -159,9 +154,9 @@ pnpm run dev:worker # Worker 服务
|
||||
|
||||
### 代码规范
|
||||
|
||||
- 使用 Prettier 进行代码格式化
|
||||
- 使用 Husky + lint-staged 进行提交前检查
|
||||
- 遵循 TypeScript 类型安全规范
|
||||
- 使用 Prettier 进行代码格式化
|
||||
- 使用 Husky + lint-staged 进行提交前检查
|
||||
- 遵循 TypeScript 类型安全规范
|
||||
|
||||
### 提交规范
|
||||
|
||||
@@ -188,22 +183,22 @@ cd worker && go build -o worker .
|
||||
|
||||
### 已完成功能 ✅
|
||||
|
||||
- 前端计算哈希和秒传
|
||||
- 并发切片上传 (使用 Web Worker)
|
||||
- 文件上传/文本上传和分享
|
||||
- 上传统计页面
|
||||
- 多语言支持
|
||||
- 最大上传限制
|
||||
- 后端队列系统和 Worker 处理文件
|
||||
- 前端计算哈希和秒传
|
||||
- 并发切片上传 (使用 Web Worker)
|
||||
- 文件上传/文本上传和分享
|
||||
- 上传统计页面
|
||||
- 多语言支持
|
||||
- 最大上传限制
|
||||
- 后端队列系统和 Worker 处理文件
|
||||
|
||||
### 计划功能 🚧
|
||||
|
||||
- 断点续传 (后端计算已上传部分并返回)
|
||||
- 图片格式转换和压缩
|
||||
- 图片 OCR 复制
|
||||
- 文档转 Markdown
|
||||
- 文本翻译/总结
|
||||
- 支持上传多文件
|
||||
- 断点续传 (后端计算已上传部分并返回)
|
||||
- 图片格式转换和压缩
|
||||
- 图片 OCR 复制
|
||||
- 文档转 Markdown
|
||||
- 文本翻译/总结
|
||||
- 支持上传多文件
|
||||
|
||||
## 🤝 贡献指南
|
||||
|
||||
@@ -215,7 +210,7 @@ cd worker && go build -o worker .
|
||||
|
||||
## 🔗 相关链接
|
||||
|
||||
- [Vue 3 文档](https://vuejs.org/)
|
||||
- [Nuxt 3 文档](https://nuxt.com/)
|
||||
- [Echo 框架文档](https://echo.labstack.com/)
|
||||
- [Asynq 文档](https://github.com/hibiken/asynq)
|
||||
- [Vue 3 文档](https://vuejs.org/)
|
||||
- [Nuxt 3 文档](https://nuxt.com/)
|
||||
- [Echo 框架文档](https://echo.labstack.com/)
|
||||
- [Asynq 文档](https://github.com/hibiken/asynq)
|
||||
183
README.md
@@ -1,10 +1,16 @@
|
||||
<div align="center"><a name="readme-top"></a>
|
||||
|
||||
# 015
|
||||
|
||||
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.
|
||||
|
||||

|
||||

|
||||
|
||||
English | [中文](README-zh.md)
|
||||
|
||||
</div>
|
||||
|
||||
## 🌟 Features
|
||||
|
||||
@@ -35,98 +41,68 @@ A modern file sharing website built with Vue 3 + Nuxt 3 + Go, supporting file up
|
||||
|
||||
## 📸 Screenshots
|
||||
|
||||

|
||||
| File Selection Upload Page | Text Input Upload Page |
|
||||
|---------------------------------------|-----------------------------------------------|
|
||||
|  |  |
|
||||
|
||||

|
||||
| Multiple File Upload | Upload Progress Heatmap |
|
||||
|------------------------------------------------|---------------------------------------------------|
|
||||
|  |  |
|
||||
|
||||

|
||||
|
||||

|
||||
| Upload Progress Bar | Upload Success Page |
|
||||
|------------------------------------------------|-------------------------------------------------|
|
||||
|  |  |
|
||||
|
||||
## 🏗️ 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
|
||||
- **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
|
||||
- **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
|
||||
- **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
|
||||
- **File Storage** - Local file system storage
|
||||
- **Redis Cache** - Share information and file metadata caching
|
||||
- **Queue System** - Asynchronous task processing queue
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Requirements
|
||||
### Docker
|
||||
|
||||
- Node.js 18+
|
||||
- Go 1.23+
|
||||
- Redis 6+
|
||||
- pnpm 9+
|
||||
1. Download files
|
||||
- config.example.yaml
|
||||
- docker-compose.yml
|
||||
|
||||
### Install Dependencies
|
||||
2. Rename config.example.yaml to config.yaml after configuration
|
||||
|
||||
3. Start
|
||||
```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
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
## 📁 Project Structure
|
||||
@@ -139,28 +115,29 @@ pnpm run dev:worker # Worker service
|
||||
│ │ ├── 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
|
||||
│ └── middleware/ # Middleware
|
||||
├── 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
|
||||
- Use Prettier for code formatting
|
||||
- Use Husky + lint-staged for pre-commit checking
|
||||
- Follow TypeScript type safety standards
|
||||
|
||||
### Commit Standards
|
||||
|
||||
@@ -187,22 +164,22 @@ cd worker && go build -o worker .
|
||||
|
||||
### 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
|
||||
- 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
|
||||
- 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
|
||||
|
||||
@@ -214,7 +191,7 @@ 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)
|
||||
- [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)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
FROM golang:1.23.1 AS builder
|
||||
FROM golang:1.25.5 AS builder
|
||||
|
||||
# Set destination for COPY
|
||||
WORKDIR /app
|
||||
|
||||
@@ -1,50 +1,36 @@
|
||||
module backend
|
||||
|
||||
go 1.23.1
|
||||
go 1.25.5
|
||||
|
||||
require (
|
||||
dario.cat/mergo v1.0.1
|
||||
github.com/dustin/go-humanize v1.0.1
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/gorilla/sessions v1.4.0
|
||||
github.com/hibiken/asynq v0.25.1
|
||||
github.com/labstack/echo-contrib v0.17.3
|
||||
github.com/labstack/echo/v4 v4.13.3
|
||||
github.com/labstack/echo-contrib v0.50.0
|
||||
github.com/labstack/echo/v5 v5.0.1
|
||||
github.com/matoous/go-nanoid/v2 v2.1.0
|
||||
github.com/redis/go-redis/v9 v9.7.3
|
||||
github.com/samber/lo v1.50.0
|
||||
github.com/spf13/cast v1.7.1
|
||||
github.com/spf13/viper v1.20.1
|
||||
go.uber.org/zap v1.27.0
|
||||
golang.org/x/crypto v0.39.0
|
||||
golang.org/x/time v0.11.0
|
||||
github.com/samber/lo v1.52.0
|
||||
github.com/spf13/cast v1.10.0
|
||||
github.com/stretchr/testify v1.11.1
|
||||
go.uber.org/zap v1.27.1
|
||||
golang.org/x/crypto v0.47.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/fsnotify/fsnotify v1.8.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/context v1.1.2 // indirect
|
||||
github.com/gorilla/securecookie v1.1.2 // indirect
|
||||
github.com/labstack/gommon v0.4.2 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/redis/go-redis/v9 v9.17.3 // indirect
|
||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||
github.com/sagikazarmark/locafero v0.7.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||
github.com/spf13/afero v1.12.0 // indirect
|
||||
github.com/spf13/pflag v1.0.6 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
golang.org/x/net v0.37.0 // indirect
|
||||
golang.org/x/sys v0.33.0 // indirect
|
||||
golang.org/x/text v0.26.0 // indirect
|
||||
google.golang.org/protobuf v1.36.5 // indirect
|
||||
golang.org/x/sys v0.40.0 // indirect
|
||||
golang.org/x/text v0.33.0 // indirect
|
||||
golang.org/x/time v0.14.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
dario.cat/mergo v1.0.1 h1:Ra4+bf83h2ztPIQYNP99R6m+Y7KfnARDfID+a+vLl4s=
|
||||
dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
@@ -10,16 +8,10 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
|
||||
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
|
||||
github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
|
||||
@@ -38,73 +30,46 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/labstack/echo-contrib v0.17.3 h1:hj+qXksKZG1scSe9ksUXMtv7fZYN+PtQT+bPcYA3/TY=
|
||||
github.com/labstack/echo-contrib v0.17.3/go.mod h1:TcRBrzW8jcC4JD+5Dc/pvOyAps0rtgzj7oBqoR3nYsc=
|
||||
github.com/labstack/echo/v4 v4.13.3 h1:pwhpCPrTl5qry5HRdM5FwdXnhXSLSY+WE+YQSeCaafY=
|
||||
github.com/labstack/echo/v4 v4.13.3/go.mod h1:o90YNEeQWjDozo584l7AwhJMHN0bOC4tAfg+Xox9q5g=
|
||||
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
|
||||
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
|
||||
github.com/labstack/echo-contrib v0.50.0 h1:MLTQdqME3BEBczV2thYz9yPT5sBhzkoUEpwAOY9llds=
|
||||
github.com/labstack/echo-contrib v0.50.0/go.mod h1:oftqJL4enNg9ao1VLpVZmisVE5/8uwHtIYE4zTpqyWU=
|
||||
github.com/labstack/echo/v5 v5.0.1 h1:60L7x1KMWRIJuaFqvnEHH322g+YnsMWq5Rzaeo6lcP4=
|
||||
github.com/labstack/echo/v5 v5.0.1/go.mod h1:SyvlSdObGjRXeQfCCXW/sybkZdOOQZBmpKF0bvALaeo=
|
||||
github.com/matoous/go-nanoid/v2 v2.1.0 h1:P64+dmq21hhWdtvZfEAofnvJULaRR1Yib0+PnU669bE=
|
||||
github.com/matoous/go-nanoid/v2 v2.1.0/go.mod h1:KlbGNQ+FhrUNIHUxZdL63t7tl4LaPkZNpUULS8H4uVM=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
|
||||
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM=
|
||||
github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA=
|
||||
github.com/redis/go-redis/v9 v9.17.3 h1:fN29NdNrE17KttK5Ndf20buqfDZwGNgoUr9qjl1DQx4=
|
||||
github.com/redis/go-redis/v9 v9.17.3/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo=
|
||||
github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k=
|
||||
github.com/samber/lo v1.50.0 h1:XrG0xOeHs+4FQ8gJR97zDz5uOFMW7OwFWiFVzqopKgY=
|
||||
github.com/samber/lo v1.50.0/go.mod h1:RjZyNk6WSnUFRKK6EyOhsRJMqft3G+pg7dCWHQCWvsc=
|
||||
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
|
||||
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
|
||||
github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs=
|
||||
github.com/spf13/afero v1.12.0/go.mod h1:ZTlWwG4/ahT8W7T0WQ5uYmjI9duaLQGy3Q2OAl4sk/4=
|
||||
github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
|
||||
github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
|
||||
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4=
|
||||
github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
||||
github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw=
|
||||
github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
|
||||
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
|
||||
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
||||
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
|
||||
golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
|
||||
golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c=
|
||||
golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
|
||||
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
|
||||
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
|
||||
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
|
||||
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
|
||||
google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=
|
||||
google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
|
||||
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
|
||||
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
|
||||
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
|
||||
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
|
||||
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
|
||||
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
|
||||
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
|
||||
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
45
backend/internal/controllers/about.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
"encoding/json"
|
||||
"pkg/models"
|
||||
u "pkg/utils"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
func GetAbout(c *echo.Context) error {
|
||||
maxStorageSize, err := u.GetFileSize(u.GetEnv("upload.maximum"))
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
fileInfoMap, err := models.GetRedisFileInfoAll()
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
currentFileSize := lo.Reduce(lo.Values(fileInfoMap), func(agg int64, item string, _ int) int64 {
|
||||
var fileInfo models.RedisFileInfo
|
||||
err := json.Unmarshal([]byte(item), &fileInfo)
|
||||
if err != nil {
|
||||
return agg
|
||||
}
|
||||
return agg + fileInfo.FileSize
|
||||
}, 0)
|
||||
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"bg_url": u.GetEnv("about.bg_url"),
|
||||
"content": u.GetEnvMapString("about.content"),
|
||||
"email": u.GetEnv("about.email"),
|
||||
"name": u.GetEnv("about.name"),
|
||||
"url": u.GetEnv("about.url"),
|
||||
"avatar": u.GetEnv("about.avatar"),
|
||||
"file": map[string]any{
|
||||
"maximun": maxStorageSize,
|
||||
"current": currentFileSize,
|
||||
},
|
||||
})
|
||||
}
|
||||
22
backend/internal/controllers/config.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
u "pkg/utils"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
func GetConfig(c *echo.Context) error {
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"site_title": u.GetEnvMapString("site.title"),
|
||||
"site_desc": u.GetEnvMapString("site.desc"),
|
||||
"site_url": u.GetEnv("site.url"),
|
||||
"site_icon": u.GetEnvWithDefault("site.icon", "/logo.png"),
|
||||
"site_bg_url": u.GetEnvWithDefault("site.bg_url", "https://img.fudaoyuan.icu/api/1/random/?scale_min=1.5&webp=true&md=false&format=302"),
|
||||
"version": u.GetEnvWithDefault("VERSION", "dev"),
|
||||
"build_time": cast.ToInt(u.GetEnvWithDefault("BUILD_TIME", cast.ToString(time.Now().Unix()))),
|
||||
})
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/models"
|
||||
"backend/internal/utils"
|
||||
"backend/middleware"
|
||||
"errors"
|
||||
"fmt"
|
||||
"pkg/models"
|
||||
u "pkg/utils"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
type DownloadShareClaims struct {
|
||||
@@ -17,31 +17,30 @@ type DownloadShareClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func DownloadShare(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
token := cc.FormValue("token")
|
||||
func DownloadShare(c *echo.Context) error {
|
||||
token := c.FormValue("token")
|
||||
if token == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("缺少token"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
claims := DownloadShareClaims{}
|
||||
t, err := jwt.ParseWithClaims(token, &claims, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(utils.GetEnv("download_secret")), nil
|
||||
return []byte(u.GetEnv("share.download_secret")), nil
|
||||
})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if !t.Valid {
|
||||
return utils.HTTPErrorHandler(c, errors.New("token格式错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
shareInfo, _ := models.GetRedisShareInfo(claims.ShareId)
|
||||
|
||||
if shareInfo.Type == models.ShareTypeFile {
|
||||
fileInfo, _ := models.GetRedisFileInfo(shareInfo.Data)
|
||||
uploadPath, err := utils.GetUploadDirPath()
|
||||
uploadPath, err := u.GetUploadDirPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return cc.Attachment(fmt.Sprintf("%s/%s", uploadPath, utils.GetFileId(fileInfo.FileHash, fileInfo.FileSize)), shareInfo.FileName)
|
||||
return c.Attachment(fmt.Sprintf("%s/%s", uploadPath, u.GetFileId(fileInfo.FileHash, fileInfo.FileSize)), shareInfo.FileName)
|
||||
}
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"data": shareInfo.Data,
|
||||
@@ -53,16 +52,14 @@ type VaildateShareProps struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func VaildateShare(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
|
||||
func VaildateShare(c *echo.Context) error {
|
||||
r := new(VaildateShareProps)
|
||||
if err := cc.Bind(r); err != nil {
|
||||
if err := c.Bind(r); err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
if r.ShareId == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("缺少分享ID"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
|
||||
shareInfo, err := models.GetRedisShareInfo(r.ShareId)
|
||||
@@ -70,33 +67,34 @@ func VaildateShare(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if shareInfo == nil {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享不存在"))
|
||||
return utils.HTTPErrorHandler(c, ErrShareNotFound)
|
||||
}
|
||||
if shareInfo.Password != "" {
|
||||
if r.Password == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("缺少分享密码"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
hash, err := utils.GeneratePasswordHash(r.Password)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if hash != shareInfo.Password {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享密码错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidSharePassword)
|
||||
}
|
||||
}
|
||||
// 如果下载次数为0,则设置为-1 防止空值问题
|
||||
if shareInfo.ViewNum < 1 {
|
||||
return utils.HTTPErrorHandler(c, errors.New("下载次数不足"))
|
||||
return utils.HTTPErrorHandler(c, ErrInsufficientDownloadQuota)
|
||||
}
|
||||
downloadWindow := u.GetEnvWithDefault("share.download_window", "12")
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, DownloadShareClaims{
|
||||
ShareId: r.ShareId,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(60 * time.Minute)),
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(cast.ToDuration(downloadWindow + "h"))),
|
||||
},
|
||||
})
|
||||
|
||||
// Sign and get the complete encoded token as a string using the secret
|
||||
downloadToken, err := token.SignedString([]byte(utils.GetEnv("download_secret")))
|
||||
downloadToken, err := token.SignedString([]byte(u.GetEnv("share.download_secret")))
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
@@ -106,10 +104,10 @@ func VaildateShare(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if fileInfo == nil {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享文件不存在"))
|
||||
return utils.HTTPErrorHandler(c, ErrShareFileNotFound)
|
||||
}
|
||||
if fileInfo.FileType != models.FileTypeUpload {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享文件状态错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidShareFileState)
|
||||
}
|
||||
}
|
||||
// download_nums 必须放在创建token的时候减掉,不然多线程下载会导致多次减掉
|
||||
@@ -118,9 +116,30 @@ func VaildateShare(c echo.Context) error {
|
||||
if latestViewNum < 1 {
|
||||
latestViewNum = -1
|
||||
}
|
||||
models.SetRedisShareInfo(r.ShareId, models.RedisShareInfo{
|
||||
err = models.SetRedisShareInfo(r.ShareId, models.RedisShareInfo{
|
||||
ViewNum: latestViewNum,
|
||||
})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
// 统计分享数
|
||||
currentDate := time.Now().Format("2006-01-02")
|
||||
statData, _ := models.GetRedisStat(currentDate)
|
||||
if statData == nil {
|
||||
statData = &models.StatData{
|
||||
FileSize: 0,
|
||||
FileNum: 0,
|
||||
ShareNum: 0,
|
||||
DownloadNum: 0,
|
||||
}
|
||||
}
|
||||
statData.DownloadNum += 1
|
||||
err = models.SetRedisStat(currentDate, *statData)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
if shareInfo.Type == models.ShareTypeFile {
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"token": downloadToken,
|
||||
|
||||
30
backend/internal/controllers/errors.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package controllers
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
// 通用错误(参数校验失败)
|
||||
ErrInvalidRequest = errors.New("InvalidRequest") // 调用接口参数错误
|
||||
|
||||
// 任务相关
|
||||
ErrTaskNotFound = errors.New("TaskNotFound") // 任务不存在
|
||||
ErrTaskExpired = errors.New("TaskExpired") // 任务已过期
|
||||
|
||||
// 文件上传相关
|
||||
ErrInsufficientStorage = errors.New("InsufficientStorage") // 存储空间不足
|
||||
ErrUploadTaskExpired = errors.New("UploadTaskExpired") // 上传任务已过期
|
||||
ErrInvalidUploadTaskState = errors.New("InvalidUploadTaskState") // 上传任务状态错误
|
||||
ErrInvalidFileSliceIndex = errors.New("InvalidFileSliceIndex") // 文件切片索引错误
|
||||
ErrInvalidFileSliceSize = errors.New("InvalidFileSliceSize") // 文件切片大小错误
|
||||
ErrIncompleteFileSlices = errors.New("IncompleteFileSlices") // 文件切片不完整
|
||||
ErrFileMD5Mismatch = errors.New("FileMD5Mismatch") // 文件MD5不一致
|
||||
|
||||
// 分享相关
|
||||
ErrShareFileNotFound = errors.New("ShareFileNotFound") // 分享文件不存在
|
||||
ErrInvalidShareFileState = errors.New("InvalidShareFileState") // 分享文件状态错误
|
||||
ErrShareNotFound = errors.New("ShareNotFound") // 分享不存在
|
||||
|
||||
// 下载相关
|
||||
ErrInvalidSharePassword = errors.New("InvalidSharePassword") // 分享密码错误
|
||||
ErrInsufficientDownloadQuota = errors.New("InsufficientDownloadQuota") // 下载次数不足
|
||||
)
|
||||
@@ -1,22 +1,22 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/models"
|
||||
"backend/internal/services"
|
||||
"backend/internal/utils"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"mime/multipart"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"pkg/models"
|
||||
s "pkg/services"
|
||||
u "pkg/utils"
|
||||
"time"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
func CreateUploadTask(c echo.Context) error {
|
||||
func CreateUploadTask(c *echo.Context) error {
|
||||
// cc := c.(*middleware.CustomContext)
|
||||
r := new(models.FileInfo)
|
||||
if err := c.Bind(r); err != nil {
|
||||
@@ -24,12 +24,23 @@ func CreateUploadTask(c echo.Context) error {
|
||||
}
|
||||
|
||||
if r.FileSize == 0 || r.MimeType == "" || r.FileHash == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
fileId := u.GetFileId(r.FileHash, r.FileSize)
|
||||
fileInfo, err := models.GetRedisFileInfo(fileId)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
fileId := utils.GetFileId(r.FileHash, r.FileSize)
|
||||
fileInfo, _ := models.GetRedisFileInfo(fileId)
|
||||
|
||||
if fileInfo != nil {
|
||||
uploadPath, err := u.GetUploadDirPath()
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
sliceList, err := services.GetFileSliceList(fileId, uploadPath)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"size": fileInfo.FileSize,
|
||||
"mime_type": fileInfo.MimeType,
|
||||
@@ -38,9 +49,10 @@ func CreateUploadTask(c echo.Context) error {
|
||||
"expire": fileInfo.Expire,
|
||||
"id": fileId,
|
||||
"chunk_size": fileInfo.ChunkSize,
|
||||
"chunks": sliceList,
|
||||
})
|
||||
}
|
||||
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("MAX_LOCALSTORAGE_SIZE"))
|
||||
maxStorageSize, err := u.GetFileSize(u.GetEnv("upload.maximum"))
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
@@ -58,14 +70,15 @@ func CreateUploadTask(c echo.Context) error {
|
||||
totalSize += fileInfo.FileSize
|
||||
}
|
||||
if totalSize+r.FileSize > int64(maxStorageSize) {
|
||||
return utils.HTTPErrorHandler(c, errors.New("存储空间不足"))
|
||||
return utils.HTTPErrorHandler(c, ErrInsufficientStorage)
|
||||
}
|
||||
|
||||
ChunkSize := int64(1 * 1024 * 1024)
|
||||
if r.FileSize > 500*1024*1024 {
|
||||
ChunkSize = r.FileSize / 500
|
||||
ChunkSize := int64(0.25 * 1024 * 1024)
|
||||
// 根据文件大小动态调整块大小
|
||||
for r.FileSize/ChunkSize > 1000 {
|
||||
ChunkSize *= 2
|
||||
}
|
||||
uploadTaskExpire := int64(3600)
|
||||
uploadTaskExpire := cast.ToInt64(u.GetEnvWithDefault("upload.remove_expire", "2")) * 3600
|
||||
newFileInfo := models.RedisFileInfo{
|
||||
FileType: models.FileTypeInit,
|
||||
FileInfo: models.FileInfo{
|
||||
@@ -82,14 +95,7 @@ func CreateUploadTask(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
client := utils.GetQueueClient()
|
||||
json, err := json.Marshal(map[string]any{
|
||||
"file_id": fileId,
|
||||
})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
_, err = client.Enqueue(asynq.NewTask("file:remove", json), asynq.ProcessIn(time.Duration(uploadTaskExpire)*time.Second))
|
||||
err = s.SetFileRemoveTask(fileId, time.Duration(uploadTaskExpire)*time.Second)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
@@ -111,14 +117,14 @@ type UploadFileSliceProps struct {
|
||||
FileSlice *multipart.FileHeader `form:"file"`
|
||||
}
|
||||
|
||||
func UploadFileSlice(c echo.Context) error {
|
||||
func UploadFileSlice(c *echo.Context) error {
|
||||
r := new(UploadFileSliceProps)
|
||||
if err := c.Bind(r); err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
if r.FileId == "" || r.FileIndex == 0 || r.FileSlice == nil {
|
||||
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
fileInfo, err := models.GetRedisFileInfo(r.FileId)
|
||||
if err != nil {
|
||||
@@ -127,18 +133,18 @@ func UploadFileSlice(c echo.Context) error {
|
||||
|
||||
now := time.Now().Unix()
|
||||
if fileInfo.CreatedAt+fileInfo.Expire < now {
|
||||
return utils.HTTPErrorHandler(c, errors.New("上传任务已过期"))
|
||||
return utils.HTTPErrorHandler(c, ErrUploadTaskExpired)
|
||||
}
|
||||
|
||||
if fileInfo.FileType != models.FileTypeInit {
|
||||
return utils.HTTPErrorHandler(c, errors.New("上传任务状态错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidUploadTaskState)
|
||||
}
|
||||
if r.FileIndex > ((fileInfo.FileSize / fileInfo.ChunkSize) + 1) {
|
||||
return utils.HTTPErrorHandler(c, errors.New("文件切片索引错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidFileSliceIndex)
|
||||
}
|
||||
|
||||
if r.FileSlice.Size > fileInfo.ChunkSize {
|
||||
return utils.HTTPErrorHandler(c, errors.New("文件切片大小错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidFileSliceSize)
|
||||
}
|
||||
|
||||
// 打开文件
|
||||
@@ -146,9 +152,14 @@ func UploadFileSlice(c echo.Context) error {
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
defer file.Close()
|
||||
defer file.Close() //nolint:errcheck
|
||||
|
||||
if err := services.CreateFileSlice(file, r.FileId, r.FileIndex); err != nil {
|
||||
uploadPath, err := u.GetUploadDirPath()
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
if _, err := services.CreateFileSlice(r.FileId, uploadPath, file, r.FileIndex); err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
@@ -161,14 +172,14 @@ type FinishUploadTaskProps struct {
|
||||
FileId string `json:"id"`
|
||||
}
|
||||
|
||||
func FinishUploadTask(c echo.Context) error {
|
||||
func FinishUploadTask(c *echo.Context) error {
|
||||
r := new(FinishUploadTaskProps)
|
||||
if err := c.Bind(r); err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
if r.FileId == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("文件ID不能为空"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
|
||||
fileInfo, err := models.GetRedisFileInfo(r.FileId)
|
||||
@@ -177,50 +188,74 @@ func FinishUploadTask(c echo.Context) error {
|
||||
}
|
||||
|
||||
if fileInfo.FileType != models.FileTypeInit {
|
||||
return utils.HTTPErrorHandler(c, errors.New("上传任务状态错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidUploadTaskState)
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
if fileInfo.CreatedAt+fileInfo.Expire < now {
|
||||
return utils.HTTPErrorHandler(c, errors.New("上传任务已过期"))
|
||||
return utils.HTTPErrorHandler(c, ErrUploadTaskExpired)
|
||||
}
|
||||
|
||||
// 合并文件切片
|
||||
uploadPath, _ := utils.GetUploadDirPath()
|
||||
slicesPath := filepath.Join(uploadPath, fmt.Sprintf("%s_%s", r.FileId, "tmp"))
|
||||
uploadPath, err := u.GetUploadDirPath()
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
fileSliceList, err := services.GetFileSliceList(r.FileId, uploadPath)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
if len(fileSliceList) != int(math.Ceil(float64(fileInfo.FileSize)/float64(fileInfo.ChunkSize))) {
|
||||
return utils.HTTPErrorHandler(c, ErrIncompleteFileSlices)
|
||||
}
|
||||
|
||||
// 最终合并后的文件路径
|
||||
mergeFilePath := filepath.Join(uploadPath, r.FileId)
|
||||
if err := services.MergeFileSlices(slicesPath, mergeFilePath); err != nil {
|
||||
mergeFilePath, err := services.MergeFileSlices(r.FileId, uploadPath)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
// 计算文件MD5
|
||||
file, err := os.Open(mergeFilePath)
|
||||
if err != nil {
|
||||
file.Close()
|
||||
os.Remove(mergeFilePath)
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
defer file.Close() //nolint:errcheck
|
||||
|
||||
file_hash, err := u.GetFileMd5(file)
|
||||
if err != nil || file_hash != fileInfo.FileHash {
|
||||
defer os.Remove(mergeFilePath) //nolint:errcheck
|
||||
if err == nil {
|
||||
return utils.HTTPErrorHandler(c, ErrFileMD5Mismatch)
|
||||
}
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
file_hash, err := utils.GetFileMd5(file)
|
||||
|
||||
if err != nil {
|
||||
file.Close()
|
||||
os.Remove(mergeFilePath)
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
if file_hash != fileInfo.FileHash {
|
||||
file.Close()
|
||||
os.Remove(mergeFilePath)
|
||||
return utils.HTTPErrorHandler(c, errors.New("文件MD5不一致"))
|
||||
}
|
||||
defer file.Close()
|
||||
// 更新文件信息
|
||||
models.SetRedisFileInfo(r.FileId, models.RedisFileInfo{
|
||||
err = models.SetRedisFileInfo(r.FileId, models.RedisFileInfo{
|
||||
FileType: models.FileTypeUpload,
|
||||
})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
// 统计
|
||||
currentDate := time.Now().Format("2006-01-02")
|
||||
statData, _ := models.GetRedisStat(currentDate)
|
||||
if statData == nil {
|
||||
statData = &models.StatData{
|
||||
FileSize: 0,
|
||||
FileNum: 0,
|
||||
ShareNum: 0,
|
||||
DownloadNum: 0,
|
||||
}
|
||||
}
|
||||
statData.FileSize += fileInfo.FileSize
|
||||
statData.FileNum += 1
|
||||
err = models.SetRedisStat(currentDate, *statData)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"size": fileInfo.FileSize,
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/models"
|
||||
"backend/internal/utils"
|
||||
"backend/middleware"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"pkg/models"
|
||||
u "pkg/utils"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
gonanoid "github.com/matoous/go-nanoid/v2"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
type CreateShareProps struct {
|
||||
@@ -32,19 +32,19 @@ type ShareConfig struct {
|
||||
HasPickupCode bool `json:"has_pickup_code"`
|
||||
}
|
||||
|
||||
func CreateShareInfo(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
func CreateShareInfo(c *echo.Context) error {
|
||||
owner, _ := echo.ContextGet[string](c, "auth")
|
||||
|
||||
r := new(CreateShareProps)
|
||||
if err := cc.Bind(r); err != nil {
|
||||
if err := c.Bind(r); err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if r.Config.ExpireAt < 1 {
|
||||
return utils.HTTPErrorHandler(c, errors.New("非法的分享过期时间"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
ExpireTime := time.Now().Add(time.Duration(r.Config.ExpireAt) * time.Minute)
|
||||
if r.Data == "" || (r.Type != models.ShareTypeFile && r.Type != models.ShareTypeText) || ExpireTime.Before(time.Now()) || r.Config.ViewNum < 1 {
|
||||
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
|
||||
id, err := gonanoid.New()
|
||||
@@ -58,10 +58,10 @@ func CreateShareInfo(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if fileInfo == nil {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享文件不存在"))
|
||||
return utils.HTTPErrorHandler(c, ErrShareFileNotFound)
|
||||
}
|
||||
if fileInfo.FileType != models.FileTypeUpload {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享文件状态错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidShareFileState)
|
||||
}
|
||||
}
|
||||
password := ""
|
||||
@@ -73,17 +73,20 @@ func CreateShareInfo(c echo.Context) error {
|
||||
password = hash
|
||||
}
|
||||
|
||||
models.SetRedisShareInfo(id, models.RedisShareInfo{
|
||||
err = models.SetRedisShareInfo(id, models.RedisShareInfo{
|
||||
Data: r.Data,
|
||||
Type: r.Type,
|
||||
CreatedAt: time.Now().Unix(),
|
||||
Owner: cc.Auth.(string),
|
||||
Owner: owner,
|
||||
ViewNum: r.Config.ViewNum,
|
||||
Password: password,
|
||||
// NotifyEmail: r.Config.NotifyEmail,
|
||||
FileName: r.FileName,
|
||||
ExpireAt: ExpireTime.Unix(),
|
||||
})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
var pickupCode string
|
||||
if r.Config.HasPickupCode {
|
||||
for {
|
||||
@@ -105,18 +108,41 @@ func CreateShareInfo(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
shareIDs = append(shareIDs, id)
|
||||
models.SetRedisFileShareRelational(r.Data, shareIDs)
|
||||
client := utils.GetQueueClient()
|
||||
err = models.SetRedisFileShareRelational(r.Data, shareIDs)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
client := u.GetQueueClient()
|
||||
json, err := json.Marshal(map[string]any{"share_id": id, "file_id": r.Data})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
_, err = client.Enqueue(asynq.NewTask("share:remove", json), asynq.ProcessIn(time.Duration(r.Config.ExpireAt)*time.Minute))
|
||||
// 这里延时分享过期时间基础上加下载窗口期后1小时删除,防止用户过期前几分钟才开始下载,下载一半文件不见了
|
||||
downloadWindow := u.GetEnvWithDefault("share.download_window", "12")
|
||||
deleteTime := time.Duration(r.Config.ExpireAt)*time.Minute + cast.ToDuration(downloadWindow+"h") + 1*time.Hour
|
||||
_, err = client.Enqueue(asynq.NewTask("share:remove", json), asynq.ProcessIn(deleteTime))
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
}
|
||||
|
||||
// 统计分享数
|
||||
currentDate := time.Now().Format("2006-01-02")
|
||||
statData, _ := models.GetRedisStat(currentDate)
|
||||
if statData == nil {
|
||||
statData = &models.StatData{
|
||||
FileSize: 0,
|
||||
FileNum: 0,
|
||||
ShareNum: 0,
|
||||
DownloadNum: 0,
|
||||
}
|
||||
}
|
||||
statData.ShareNum += 1
|
||||
err = models.SetRedisStat(currentDate, *statData)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"id": id,
|
||||
"file_name": r.FileName,
|
||||
@@ -130,11 +156,10 @@ type GetShareProps struct {
|
||||
ShareId string `param:"id"`
|
||||
}
|
||||
|
||||
func GetShareInfo(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
shareId := cc.Param("id")
|
||||
func GetShareInfo(c *echo.Context) error {
|
||||
shareId := c.Param("id")
|
||||
if shareId == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("缺少分享ID"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
|
||||
shareInfo, err := models.GetRedisShareInfo(shareId)
|
||||
@@ -142,7 +167,7 @@ func GetShareInfo(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if shareInfo == nil || shareInfo.ViewNum < 1 {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享不存在"))
|
||||
return utils.HTTPErrorHandler(c, ErrShareNotFound)
|
||||
}
|
||||
|
||||
if shareInfo.Type == models.ShareTypeFile {
|
||||
@@ -151,10 +176,10 @@ func GetShareInfo(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if fileInfo == nil {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享文件不存在"))
|
||||
return utils.HTTPErrorHandler(c, ErrShareFileNotFound)
|
||||
}
|
||||
if fileInfo.FileType != models.FileTypeUpload {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享文件状态错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidShareFileState)
|
||||
}
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"id": shareId,
|
||||
@@ -180,18 +205,17 @@ func GetShareInfo(c echo.Context) error {
|
||||
})
|
||||
}
|
||||
|
||||
func GetShareByPickupCode(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
pickupCode := cc.Param("code")
|
||||
func GetShareByPickupCode(c *echo.Context) error {
|
||||
pickupCode := c.Param("code")
|
||||
if pickupCode == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("缺少提取码"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
shareId, err := models.GetRedisPickupData(strings.ToUpper(pickupCode))
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if shareId == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享不存在"))
|
||||
return utils.HTTPErrorHandler(c, ErrShareNotFound)
|
||||
}
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"share_id": shareId,
|
||||
|
||||
@@ -1,102 +1,75 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/models"
|
||||
"backend/internal/utils"
|
||||
"encoding/json"
|
||||
"time"
|
||||
"pkg/models"
|
||||
u "pkg/utils"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/samber/lo"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
type FileChartData struct {
|
||||
FileSize int64 `json:"file_size"`
|
||||
FileNum int64 `json:"file_num"`
|
||||
Date string `json:"date"`
|
||||
const (
|
||||
DateLayout = "2006-01-02"
|
||||
DaysToAnalyze = 30
|
||||
QueueHistoryDays = 30
|
||||
)
|
||||
|
||||
type StatChartData struct {
|
||||
FileSize int64 `json:"file_size"`
|
||||
FileNum int64 `json:"file_num"`
|
||||
ShareNum int64 `json:"share_num"`
|
||||
DownloadNum int64 `json:"download_num"`
|
||||
}
|
||||
|
||||
func GetStat(c echo.Context) error {
|
||||
fileInfoMap, err := models.GetRedisFileInfoAll()
|
||||
type QueueChartData struct {
|
||||
Processed int `json:"processed"`
|
||||
Failed int `json:"failed"`
|
||||
}
|
||||
|
||||
func GetStat(c *echo.Context) error {
|
||||
statInfoMap, err := models.GetRedisStatAll()
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
fileChartData := make(map[string]FileChartData)
|
||||
for _, value := range fileInfoMap {
|
||||
var fileInfo models.RedisFileInfo
|
||||
err := json.Unmarshal([]byte(value), &fileInfo)
|
||||
|
||||
statChartData := make(map[string]StatChartData)
|
||||
for key, value := range statInfoMap {
|
||||
var statData models.StatData
|
||||
err := json.Unmarshal([]byte(value), &statData)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if fileInfo.FileType != models.FileTypeUpload {
|
||||
statChartData[key] = StatChartData{
|
||||
FileSize: statData.FileSize,
|
||||
FileNum: statData.FileNum,
|
||||
ShareNum: statData.ShareNum,
|
||||
DownloadNum: statData.DownloadNum,
|
||||
}
|
||||
}
|
||||
|
||||
queueInspector := u.GetQueueInspector()
|
||||
queues, err := queueInspector.History("default", QueueHistoryDays)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
queuesChartData := make(map[string]QueueChartData)
|
||||
for _, item := range queues {
|
||||
dateKey := item.Date.Format(DateLayout)
|
||||
if item.Processed == 0 && item.Failed == 0 {
|
||||
continue
|
||||
}
|
||||
if time.Unix(fileInfo.CreatedAt, 0).After(time.Now().Add(-30 * 24 * time.Hour)) {
|
||||
dateKey := time.Unix(fileInfo.CreatedAt, 0).Format("2006-01-02")
|
||||
if data, ok := fileChartData[dateKey]; ok {
|
||||
fileChartData[dateKey] = FileChartData{
|
||||
FileSize: data.FileSize + fileInfo.FileSize,
|
||||
FileNum: data.FileNum + 1,
|
||||
}
|
||||
} else {
|
||||
fileChartData[dateKey] = FileChartData{
|
||||
FileSize: fileInfo.FileSize,
|
||||
FileNum: 1,
|
||||
}
|
||||
}
|
||||
queuesChartData[dateKey] = QueueChartData{
|
||||
Processed: item.Processed,
|
||||
Failed: item.Failed,
|
||||
}
|
||||
}
|
||||
storageChartData := lo.Times(30, func(i int) FileChartData {
|
||||
dateKey := time.Now().AddDate(0, 0, -i).Format("2006-01-02")
|
||||
if data, ok := fileChartData[dateKey]; ok {
|
||||
return FileChartData{
|
||||
FileSize: data.FileSize,
|
||||
FileNum: data.FileNum,
|
||||
Date: dateKey,
|
||||
}
|
||||
}
|
||||
return FileChartData{
|
||||
FileSize: 0,
|
||||
FileNum: 0,
|
||||
Date: dateKey,
|
||||
}
|
||||
})
|
||||
|
||||
queueInspector := utils.GetQueueInspector()
|
||||
queues, err := queueInspector.History("default", 30)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("MAX_LOCALSTORAGE_SIZE"))
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
queueData := lo.Map(queues, func(item *asynq.DailyStats, _ int) map[string]any {
|
||||
return map[string]any{
|
||||
"date": item.Date.Format("2006-01-02"),
|
||||
"processed": item.Processed,
|
||||
"failed": item.Failed,
|
||||
}
|
||||
})
|
||||
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"version": utils.GetEnvWithDefault("VERSION", "dev"),
|
||||
"build_time": cast.ToInt(utils.GetEnvWithDefault("BUILD_TIME", cast.ToString(time.Now().Unix()))),
|
||||
"max_limit": map[string]any{
|
||||
"file_size": maxStorageSize,
|
||||
},
|
||||
"admin": map[string]any{
|
||||
"name": utils.GetEnv("ADMIN_NAME"),
|
||||
"email": utils.GetEnv("ADMIN_EMAIL"),
|
||||
"url": utils.GetEnv("ADMIN_URL"),
|
||||
},
|
||||
"chart": map[string]any{
|
||||
"storage": storageChartData,
|
||||
"queue": queueData,
|
||||
"storage": statChartData,
|
||||
"queue": queuesChartData,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,38 +1,36 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/models"
|
||||
"backend/internal/controllers/task"
|
||||
"backend/internal/utils"
|
||||
"backend/middleware"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"pkg/models"
|
||||
u "pkg/utils"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
type GenCompressImageRequest struct {
|
||||
FileId string `json:"file_id"`
|
||||
var handleTaskMap = map[string]func(c *echo.Context) ([]byte, error){
|
||||
"image:compress": task.HandleImageCompress,
|
||||
"image:convert": task.HandleImageConvert,
|
||||
}
|
||||
|
||||
func GenCompressImage(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
r := new(GenCompressImageRequest)
|
||||
if err := cc.Bind(r); err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
func CreateTask(c *echo.Context) error {
|
||||
taskType := c.Param("type")
|
||||
if taskType == "" {
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
|
||||
if r.FileId == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误"))
|
||||
handleTask, ok := handleTaskMap[taskType]
|
||||
if !ok {
|
||||
return utils.HTTPErrorHandler(c, ErrTaskNotFound)
|
||||
}
|
||||
client := utils.GetQueueClient()
|
||||
json, err := json.Marshal(map[string]any{
|
||||
"file_id": r.FileId,
|
||||
})
|
||||
json, err := handleTask(c)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
info, err := client.Enqueue(asynq.NewTask("image:compress", json), asynq.MaxRetry(3))
|
||||
|
||||
client := u.GetQueueClient()
|
||||
info, err := client.Enqueue(asynq.NewTask(taskType, json), asynq.MaxRetry(3))
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
@@ -42,11 +40,10 @@ func GenCompressImage(c echo.Context) error {
|
||||
})
|
||||
}
|
||||
|
||||
func GetCompressImage(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
taskId := cc.Param("id")
|
||||
func GetTask(c *echo.Context) error {
|
||||
taskId := c.Param("id")
|
||||
if taskId == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
|
||||
taskInfo, err := models.GetRedisTaskInfo(taskId)
|
||||
@@ -54,11 +51,11 @@ func GetCompressImage(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if taskInfo == nil {
|
||||
client := utils.GetQueueInspector()
|
||||
client := u.GetQueueInspector()
|
||||
|
||||
queneTaskInfo, err := client.GetTaskInfo("default", taskId)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, errors.New("任务已过期"))
|
||||
return utils.HTTPErrorHandler(c, ErrTaskExpired)
|
||||
}
|
||||
stateMap := map[asynq.TaskState]string{
|
||||
asynq.TaskStateActive: "processing",
|
||||
7
backend/internal/controllers/task/errors.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package task
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidRequest = errors.New("InvalidRequest")
|
||||
)
|
||||
53
backend/internal/controllers/task/image.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
type BaseImageRequest struct {
|
||||
FileId string `json:"file_id"`
|
||||
}
|
||||
|
||||
func HandleImageCompress(c *echo.Context) ([]byte, error) {
|
||||
r := new(BaseImageRequest)
|
||||
if err := c.Bind(r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.FileId == "" {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
json, err := json.Marshal(map[string]any{
|
||||
"file_id": r.FileId,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return json, nil
|
||||
}
|
||||
|
||||
type ImageConvertRequest struct {
|
||||
BaseImageRequest
|
||||
TargetExt string `json:"target_ext"`
|
||||
}
|
||||
|
||||
func HandleImageConvert(c *echo.Context) ([]byte, error) {
|
||||
r := new(ImageConvertRequest)
|
||||
if err := c.Bind(r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.FileId == "" || r.TargetExt == "" {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
json, err := json.Marshal(map[string]any{
|
||||
"file_id": r.FileId,
|
||||
"target_ext": r.TargetExt,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return json, nil
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func GetRedisFileShareRelational(fileId string) ([]string, error) {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
fileShareRelationalUnmarshalData, err := rdb.HGet(ctx, "015:fileShareRelational", fileId).Result()
|
||||
if err == redis.Nil {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var shareIDs []string
|
||||
if err := json.Unmarshal([]byte(fileShareRelationalUnmarshalData), &shareIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shareIDs, nil
|
||||
}
|
||||
|
||||
func SetRedisFileShareRelational(fileId string, shareIDs []string) error {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
jsonData, _ := json.Marshal(shareIDs)
|
||||
_, err := rdb.HSet(ctx, "015:fileShareRelational", fileId, string(jsonData)).Result()
|
||||
return err
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func GetRedisTaskInfo(taskId string) (*map[string]any, error) {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
taskInfo := rdb.Get(ctx, fmt.Sprintf("015:taskInfoMap:%s", taskId))
|
||||
taskInfoUnmarshalData, err := taskInfo.Result()
|
||||
if err == redis.Nil {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var taskInfoData map[string]any
|
||||
|
||||
if err := json.Unmarshal([]byte(taskInfoUnmarshalData), &taskInfoData); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &taskInfoData, nil
|
||||
}
|
||||
|
||||
func SetRedisTaskInfo(taskId string, taskInfo map[string]any) error {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
jsonData, _ := json.Marshal(taskInfo)
|
||||
_, err := rdb.Set(ctx, fmt.Sprintf("015:taskInfoMap:%s", taskId), jsonData, time.Hour).Result()
|
||||
return err
|
||||
}
|
||||
@@ -1,89 +1,89 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func CreateFileSlice(fileSlice io.Reader, fileId string, fileIndex int64) error {
|
||||
uploadPath, err := utils.GetUploadDirPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
func CreateFileSlice(fileId string, uploadPath string, fileSlice io.Reader, fileIndex int64) (string, error) {
|
||||
filePath := filepath.Join(uploadPath, fmt.Sprintf("%s_%s", fileId, "tmp"))
|
||||
if err := os.MkdirAll(filePath, 0755); err != nil {
|
||||
return err
|
||||
return "", err
|
||||
}
|
||||
|
||||
dst, err := os.Create(filepath.Join(filePath, fmt.Sprintf("%d", fileIndex)))
|
||||
if err != nil {
|
||||
return err
|
||||
return "", err
|
||||
}
|
||||
defer dst.Close()
|
||||
defer dst.Close() //nolint:errcheck
|
||||
|
||||
if _, err = io.Copy(dst, fileSlice); err != nil {
|
||||
return err
|
||||
return "", err
|
||||
}
|
||||
|
||||
return nil
|
||||
return filePath, nil
|
||||
}
|
||||
|
||||
// MergeFileSlices 合并文件切片
|
||||
func MergeFileSlices(slicesPath string, mergeFilePath string) error {
|
||||
// 创建最终文件
|
||||
destFile, err := os.Create(mergeFilePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建合并文件失败: %v", err)
|
||||
}
|
||||
defer destFile.Close()
|
||||
|
||||
// 读取目录下的所有文件
|
||||
func GetFileSliceList(fileId string, uploadPath string) ([]int, error) {
|
||||
slicesPath := filepath.Join(uploadPath, fmt.Sprintf("%s_%s", fileId, "tmp"))
|
||||
files, err := os.ReadDir(slicesPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取切片目录失败: %v", err)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("读取切片目录失败: %v", err)
|
||||
}
|
||||
|
||||
// 按照索引排序文件切片
|
||||
sliceFiles := make([]string, len(files))
|
||||
fileSliceList := []int{}
|
||||
for _, file := range files {
|
||||
index, err := strconv.Atoi(file.Name())
|
||||
if err != nil {
|
||||
return fmt.Errorf("无效的切片文件名: %v", err)
|
||||
return nil, fmt.Errorf("无效的切片文件名: %v", err)
|
||||
}
|
||||
sliceFiles[index-1] = filepath.Join(slicesPath, file.Name())
|
||||
fileSliceList = append(fileSliceList, index)
|
||||
}
|
||||
sort.Ints(fileSliceList)
|
||||
return fileSliceList, nil
|
||||
}
|
||||
|
||||
// MergeFileSlices 合并文件切片
|
||||
func MergeFileSlices(fileId string, uploadPath string) (string, error) {
|
||||
mergeFilePath := filepath.Join(uploadPath, fileId)
|
||||
slicesPath := filepath.Join(uploadPath, fmt.Sprintf("%s_%s", fileId, "tmp"))
|
||||
defer os.RemoveAll(slicesPath) //nolint:errcheck
|
||||
// 创建最终文件
|
||||
destFile, err := os.Create(mergeFilePath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("创建合并文件失败: %v", err)
|
||||
}
|
||||
defer destFile.Close() //nolint:errcheck
|
||||
|
||||
fileSliceList, err := GetFileSliceList(fileId, uploadPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 合并文件
|
||||
buffer := make([]byte, 4*1024*1024) // 4MB buffer
|
||||
for _, sliceFile := range sliceFiles {
|
||||
sf, err := os.Open(sliceFile)
|
||||
for _, index := range fileSliceList {
|
||||
sliceFilePath := filepath.Join(slicesPath, fmt.Sprintf("%d", index))
|
||||
sf, err := os.Open(sliceFilePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("打开切片文件失败: %v", err)
|
||||
return "", fmt.Errorf("打开切片文件失败: %v", err)
|
||||
}
|
||||
|
||||
defer sf.Close() //nolint:errcheck
|
||||
for {
|
||||
n, err := sf.Read(buffer)
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
sf.Close()
|
||||
return fmt.Errorf("读取切片文件失败: %v", err)
|
||||
return "", fmt.Errorf("读取切片文件失败: %v", err)
|
||||
}
|
||||
|
||||
if _, err := destFile.Write(buffer[:n]); err != nil {
|
||||
sf.Close()
|
||||
return fmt.Errorf("写入合并文件失败: %v", err)
|
||||
return "", fmt.Errorf("写入合并文件失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
sf.Close()
|
||||
}
|
||||
defer os.RemoveAll(slicesPath)
|
||||
return nil
|
||||
return mergeFilePath, nil
|
||||
}
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var v *viper.Viper
|
||||
|
||||
func init() {
|
||||
InitEnv()
|
||||
}
|
||||
|
||||
func InitEnv() {
|
||||
if v != nil {
|
||||
return
|
||||
}
|
||||
v = viper.New()
|
||||
v.SetConfigName(".env")
|
||||
v.SetConfigType("env")
|
||||
v.AddConfigPath(".")
|
||||
v.AddConfigPath("../")
|
||||
v.AutomaticEnv()
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
|
||||
// 只有当错误不是"配置文件未找到"时才 panic
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func GetEnv(key string) string {
|
||||
InitEnv()
|
||||
return v.GetString(key)
|
||||
}
|
||||
|
||||
func GetEnvWithDefault(key string, defaultValue string) string {
|
||||
value := v.GetString(key)
|
||||
if value == "" {
|
||||
return defaultValue
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
)
|
||||
|
||||
func GetFileId(fileHash string, fileSize int64) string {
|
||||
return fmt.Sprintf("%s_%d", fileHash, fileSize)
|
||||
}
|
||||
|
||||
func GetFileMd5(file io.Reader) (string, error) {
|
||||
|
||||
const bufferSize = 1024 * 1000 // 1MB
|
||||
|
||||
hash := md5.New()
|
||||
for buf, reader := make([]byte, bufferSize), bufio.NewReader(file); ; {
|
||||
n, err := reader.Read(buf)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
|
||||
hash.Write(buf[:n])
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%x", hash.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func GetUploadDirPath() (string, error) {
|
||||
basepath, err := os.Getwd()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
finalPath := filepath.Join(basepath, "uploads")
|
||||
uploadPath := GetEnvWithDefault("UPLOAD_PATH", finalPath)
|
||||
if err := os.MkdirAll(uploadPath, 0755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return uploadPath, nil
|
||||
}
|
||||
|
||||
func GetFileSize(size string) (uint64, error) {
|
||||
return humanize.ParseBytes(size)
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package utils
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
type Option interface {
|
||||
@@ -36,7 +36,7 @@ func (o WithData) applyTo(props *HTTPBaseResponse) {
|
||||
props.data = o
|
||||
}
|
||||
|
||||
func HTTPBaseHandler(c echo.Context, options ...Option) error {
|
||||
func HTTPBaseHandler(c *echo.Context, options ...Option) error {
|
||||
props := HTTPBaseResponse{code: http.StatusOK, message: "success", data: map[string]any{}}
|
||||
for _, option := range options {
|
||||
option.applyTo(&props)
|
||||
@@ -49,10 +49,10 @@ func HTTPBaseHandler(c echo.Context, options ...Option) error {
|
||||
})
|
||||
}
|
||||
|
||||
func HTTPSuccessHandler(c echo.Context, data map[string]any, options ...HTTPBaseResponseProps) error {
|
||||
func HTTPSuccessHandler(c *echo.Context, data map[string]any, options ...HTTPBaseResponseProps) error {
|
||||
return HTTPBaseHandler(c, WithData(data))
|
||||
}
|
||||
|
||||
func HTTPErrorHandler(c echo.Context, err error, options ...HTTPBaseResponseProps) error {
|
||||
func HTTPErrorHandler(c *echo.Context, err error, options ...HTTPBaseResponseProps) error {
|
||||
return HTTPBaseHandler(c, WithMessage(err.Error()), WithCode(http.StatusBadRequest))
|
||||
}
|
||||
|
||||
@@ -3,14 +3,19 @@ package utils
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"pkg/utils"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrPasswordSaltNotSet = errors.New("PasswordSaltNotSet")
|
||||
)
|
||||
|
||||
func GeneratePasswordHash(password string) (string, error) {
|
||||
salt := GetEnv("PASSWORD_SALT")
|
||||
salt := utils.GetEnv("share.password_salt")
|
||||
if salt == "" {
|
||||
return "", errors.New("请配置PASSWORD_SALT")
|
||||
return "", ErrPasswordSaltNotSet
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), []byte(salt), 1, 64*1024, 4, 32)
|
||||
return fmt.Sprintf("%x", hash), nil
|
||||
|
||||
@@ -1,44 +1,33 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"backend/internal/controllers"
|
||||
"backend/internal/utils"
|
||||
"backend/middleware"
|
||||
"fmt"
|
||||
"pkg/utils"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 日志
|
||||
var logger *zap.Logger
|
||||
if utils.GetEnvWithDefault("NODE_ENV", "production") == "production" {
|
||||
if utils.GetEnvWithDefault("node.env", "production") == "production" {
|
||||
logger, _ = zap.NewProduction()
|
||||
} else {
|
||||
logger, _ = zap.NewDevelopment()
|
||||
}
|
||||
defer logger.Sync()
|
||||
defer logger.Sync() //nolint:errcheck
|
||||
zap.ReplaceGlobals(logger)
|
||||
|
||||
e := echo.New()
|
||||
e.Use(middleware.ContextMiddleware())
|
||||
e.Use(middleware.SessionMiddleware())
|
||||
e.Use(middleware.AuthMiddleware())
|
||||
e.Use(middleware.RateLimiterMiddleware())
|
||||
e.Use(middleware.LoggerMiddleware())
|
||||
for _, middleware := range middlewares {
|
||||
e.Use(middleware())
|
||||
}
|
||||
|
||||
e.POST("/file/create", controllers.CreateUploadTask)
|
||||
e.POST("/file/slice", controllers.UploadFileSlice)
|
||||
e.POST("/file/finish", controllers.FinishUploadTask)
|
||||
e.GET("/share/:id", controllers.GetShareInfo)
|
||||
e.POST("/share", controllers.CreateShareInfo)
|
||||
e.GET("/download", controllers.DownloadShare)
|
||||
e.POST("/download", controllers.VaildateShare)
|
||||
e.GET("/share/pickup/:code", controllers.GetShareByPickupCode)
|
||||
|
||||
e.POST("/image/compress", controllers.GenCompressImage)
|
||||
e.GET("/image/compress/:id", controllers.GetCompressImage)
|
||||
|
||||
e.GET("/stat", controllers.GetStat)
|
||||
e.Logger.Fatal(e.Start(":1323"))
|
||||
for _, route := range routes {
|
||||
e.Match(route.Method, route.Path, route.Handler)
|
||||
}
|
||||
if err := e.Start(fmt.Sprintf(":%s", utils.GetEnvWithDefault("api.port", "5001"))); err != nil {
|
||||
logger.Fatal("server failed", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
14
backend/middleware.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"backend/middleware"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
var middlewares = []func() echo.MiddlewareFunc{
|
||||
middleware.SessionMiddleware,
|
||||
middleware.AuthMiddleware,
|
||||
middleware.RateLimiterMiddleware,
|
||||
middleware.LoggerMiddleware,
|
||||
}
|
||||
@@ -3,14 +3,14 @@ package middleware
|
||||
import (
|
||||
"github.com/gorilla/sessions"
|
||||
"github.com/labstack/echo-contrib/session"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
gonanoid "github.com/matoous/go-nanoid/v2"
|
||||
)
|
||||
|
||||
// CustomMiddleware 创建自定义中间件
|
||||
func AuthMiddleware() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
return func(c *echo.Context) error {
|
||||
sess, err := session.Get("session", c)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -30,11 +30,8 @@ func AuthMiddleware() echo.MiddlewareFunc {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
cc := c.(*CustomContext)
|
||||
cc.Auth = sess.Values["auth"]
|
||||
// 将自定义上下文传递给下一个处理器
|
||||
return next(cc)
|
||||
c.Set("auth", sess.Values["auth"])
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
// CustomContext 扩展 echo.Context 以添加自定义功能
|
||||
type CustomContext struct {
|
||||
echo.Context
|
||||
Auth interface{}
|
||||
}
|
||||
|
||||
// NewCustomContext 创建自定义上下文的构造函数
|
||||
func NewCustomContext(c echo.Context) *CustomContext {
|
||||
return &CustomContext{
|
||||
Context: c,
|
||||
}
|
||||
}
|
||||
|
||||
// ContextMiddleware 中间件用于将标准 echo.Context 转换为 CustomContext
|
||||
func ContextMiddleware() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
cc := NewCustomContext(c)
|
||||
return next(cc)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v4/middleware"
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/labstack/echo/v5/middleware"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
@@ -10,7 +10,7 @@ func LoggerMiddleware() echo.MiddlewareFunc {
|
||||
return middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
|
||||
LogURI: true,
|
||||
LogStatus: true,
|
||||
LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error {
|
||||
LogValuesFunc: func(c *echo.Context, v middleware.RequestLoggerValues) error {
|
||||
zap.L().Info("request",
|
||||
zap.String("url", v.URI),
|
||||
zap.Int("status", v.Status),
|
||||
|
||||
@@ -5,9 +5,8 @@ import (
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
echo_middleware "github.com/labstack/echo/v4/middleware"
|
||||
"golang.org/x/time/rate"
|
||||
"github.com/labstack/echo/v5"
|
||||
echo_middleware "github.com/labstack/echo/v5/middleware"
|
||||
)
|
||||
|
||||
type RateSkiper struct {
|
||||
@@ -23,22 +22,22 @@ var RateSkipList = []RateSkiper{
|
||||
|
||||
func RateLimiterMiddleware() echo.MiddlewareFunc {
|
||||
config := echo_middleware.RateLimiterConfig{
|
||||
Skipper: func(e echo.Context) bool {
|
||||
Skipper: func(e *echo.Context) bool {
|
||||
path := e.Path()
|
||||
r := e.Request()
|
||||
return slices.Contains(RateSkipList, RateSkiper{Path: path, Method: r.Method})
|
||||
},
|
||||
Store: echo_middleware.NewRateLimiterMemoryStoreWithConfig(
|
||||
echo_middleware.RateLimiterMemoryStoreConfig{Rate: rate.Limit(10), Burst: 30, ExpiresIn: 3 * time.Minute},
|
||||
echo_middleware.RateLimiterMemoryStoreConfig{Rate: 10, Burst: 30, ExpiresIn: 3 * time.Minute},
|
||||
),
|
||||
IdentifierExtractor: func(ctx echo.Context) (string, error) {
|
||||
IdentifierExtractor: func(ctx *echo.Context) (string, error) {
|
||||
id := ctx.RealIP()
|
||||
return id, nil
|
||||
},
|
||||
ErrorHandler: func(context echo.Context, err error) error {
|
||||
ErrorHandler: func(context *echo.Context, err error) error {
|
||||
return context.JSON(http.StatusForbidden, nil)
|
||||
},
|
||||
DenyHandler: func(context echo.Context, identifier string, err error) error {
|
||||
DenyHandler: func(context *echo.Context, identifier string, err error) error {
|
||||
return context.JSON(http.StatusTooManyRequests, nil)
|
||||
},
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ package middleware
|
||||
import (
|
||||
"github.com/gorilla/sessions"
|
||||
"github.com/labstack/echo-contrib/session"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
func SessionMiddleware() echo.MiddlewareFunc {
|
||||
|
||||
33
backend/route.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"backend/internal/controllers"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
type Route struct {
|
||||
Method []string
|
||||
Path string
|
||||
Handler func(c *echo.Context) error
|
||||
}
|
||||
|
||||
var routes = []Route{
|
||||
{Method: []string{"POST"}, Path: "/file/create", Handler: controllers.CreateUploadTask},
|
||||
{Method: []string{"POST"}, Path: "/file/slice", Handler: controllers.UploadFileSlice},
|
||||
{Method: []string{"POST"}, Path: "/file/finish", Handler: controllers.FinishUploadTask},
|
||||
|
||||
{Method: []string{"GET"}, Path: "/share/:id", Handler: controllers.GetShareInfo},
|
||||
{Method: []string{"POST"}, Path: "/share", Handler: controllers.CreateShareInfo},
|
||||
|
||||
{Method: []string{"GET"}, Path: "/download", Handler: controllers.DownloadShare},
|
||||
{Method: []string{"POST"}, Path: "/download", Handler: controllers.VaildateShare},
|
||||
{Method: []string{"GET"}, Path: "/share/pickup/:code", Handler: controllers.GetShareByPickupCode},
|
||||
|
||||
{Method: []string{"GET"}, Path: "/stat", Handler: controllers.GetStat},
|
||||
{Method: []string{"GET"}, Path: "/config", Handler: controllers.GetConfig},
|
||||
{Method: []string{"GET"}, Path: "/about", Handler: controllers.GetAbout},
|
||||
|
||||
{Method: []string{"POST"}, Path: "/task/:type", Handler: controllers.CreateTask},
|
||||
{Method: []string{"GET"}, Path: "/task/:id", Handler: controllers.GetTask},
|
||||
}
|
||||
60
backend/test/utils/http_result_test.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"backend/internal/utils"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestHTTPSuccessHandler(t *testing.T) {
|
||||
e := echo.New()
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
c := e.NewContext(req, rec)
|
||||
|
||||
data := map[string]interface{}{"result": "success"}
|
||||
err := utils.HTTPSuccessHandler(c, data)
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rec.Code)
|
||||
|
||||
var response map[string]interface{}
|
||||
err = json.Unmarshal(rec.Body.Bytes(), &response)
|
||||
assert.NoError(t, err)
|
||||
|
||||
expected := map[string]interface{}{
|
||||
"code": float64(http.StatusOK),
|
||||
"message": "success",
|
||||
"data": data,
|
||||
}
|
||||
assert.Equal(t, expected, response)
|
||||
}
|
||||
|
||||
func TestHTTPErrorHandler(t *testing.T) {
|
||||
e := echo.New()
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
c := e.NewContext(req, rec)
|
||||
|
||||
err := utils.HTTPErrorHandler(c, assert.AnError)
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Equal(t, http.StatusBadRequest, rec.Code)
|
||||
|
||||
var response map[string]interface{}
|
||||
err = json.Unmarshal(rec.Body.Bytes(), &response)
|
||||
assert.NoError(t, err)
|
||||
|
||||
expected := map[string]interface{}{
|
||||
"code": float64(http.StatusBadRequest),
|
||||
"message": assert.AnError.Error(),
|
||||
"data": map[string]interface{}{},
|
||||
}
|
||||
assert.Equal(t, expected, response)
|
||||
}
|
||||
74
backend/test/utils/password_test.go
Normal file
@@ -0,0 +1,74 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"backend/internal/utils"
|
||||
u "pkg/utils"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestGeneratePasswordHash(t *testing.T) {
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
password string
|
||||
salt string
|
||||
expectError bool
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "share.password_salt未配置",
|
||||
password: "testpassword",
|
||||
salt: "",
|
||||
expectError: true,
|
||||
err: utils.ErrPasswordSaltNotSet,
|
||||
},
|
||||
{
|
||||
name: "正常生成哈希",
|
||||
password: "testpassword123",
|
||||
salt: "testsalt",
|
||||
expectError: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// 设置环境变量
|
||||
u.InitEnv(u.EnvOption{
|
||||
ConfigData: bytes.NewBuffer([]byte(fmt.Sprintf(`
|
||||
share:
|
||||
password_salt: %s
|
||||
`, tt.salt))),
|
||||
})
|
||||
u.SetEnv("share.password_salt", tt.salt)
|
||||
|
||||
hash, err := utils.GeneratePasswordHash(tt.password)
|
||||
|
||||
if tt.expectError {
|
||||
if err == nil {
|
||||
t.Errorf("期望错误,但得到了 nil")
|
||||
return
|
||||
}
|
||||
if err != tt.err {
|
||||
t.Errorf("期望错误信息 '%s',但得到了 '%s'", tt.err.Error(), err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("不期望错误,但得到了: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 验证哈希格式:argon2 32字节 = 64个十六进制字符
|
||||
if len(hash) != 64 {
|
||||
t.Errorf("期望哈希长度为64,但得到了 %d", len(hash))
|
||||
}
|
||||
assert.Equal(t, hash, "537275f995fdd46eb2e5455b8a29adccb60c5637689d29646676a5f1bffb63f3")
|
||||
})
|
||||
}
|
||||
}
|
||||
55
config.example.yaml
Normal file
@@ -0,0 +1,55 @@
|
||||
share:
|
||||
# (必填)你的下载secret,每一次下载次数减1的时候都会根据这里的secret生成一个下载jwt token, 有效期一小时,使用该下载token有效期内可以多线程下载该文件而不会被多次扣除次数
|
||||
download_secret: your-secret-token
|
||||
# 颁发的下载token的窗口期,默认12小时,文件过期后自动从服务器删除时间为此时间基础上加1小时,默认为12+1=13小时
|
||||
download_window: 12
|
||||
# (必填)设置密码时会把密码加盐
|
||||
password_salt: your-passwall-salt
|
||||
|
||||
upload:
|
||||
# 上传文件保存路径
|
||||
path: /upload
|
||||
# 指定实例最大上传容量,支持填写人类可读的值,比如1TiB,500GiB等,注意填写GiB而不是GB, Gib按1024字节计算,Gb按1000字节计算
|
||||
maximum: 100GiB
|
||||
|
||||
redis:
|
||||
# (必填)redis 地址
|
||||
url: redis://redis:6379/0
|
||||
|
||||
# 站点基本信息
|
||||
site:
|
||||
# 必填,对应你的公网域名
|
||||
url: http://localhost:5000
|
||||
title:
|
||||
'en': '015'
|
||||
desc:
|
||||
'en': '015 is an open-source temporary file sharing platform project that supports uploading, downloading, and sharing files and text.'
|
||||
icon: '/logo.png'
|
||||
bg_url: 'https://img.fudaoyuan.icu/api/1/random/?scale_min=1.5&webp=true&md=false&format=302'
|
||||
|
||||
# 关于页面的
|
||||
about:
|
||||
# hero图片 推荐3:1 比例
|
||||
bg_url: 'https://files.mastodon.social/site_uploads/files/000/000/001/@1x/57c12f441d083cde.png'
|
||||
# 关于信息,markdown格式
|
||||
content:
|
||||
'zh': |
|
||||
### markdown测试文案
|
||||
|
||||
这里有一个图片示例:
|
||||
|
||||

|
||||
|
||||
这里有一个[示例链接](https://fudaoyuan.icu)
|
||||
'en': |
|
||||
### Markdown Test Content
|
||||
|
||||
Here is an image example:
|
||||
|
||||

|
||||
|
||||
Here is a [sample link](https://fudaoyuan.icu)
|
||||
email: keven@fudaoyuan.icu
|
||||
name: keven
|
||||
url: 'https://fudaoyuan.icu'
|
||||
avatar: ''
|
||||
24
docker-compose.yml
Normal file
@@ -0,0 +1,24 @@
|
||||
services:
|
||||
app:
|
||||
image: fudaoyuanicu/015-app:latest
|
||||
container_name: 015-app
|
||||
volumes:
|
||||
- ./uploads:/uploads
|
||||
- ./config.yaml:/app/config.yaml
|
||||
ports:
|
||||
- '8080:80'
|
||||
depends_on:
|
||||
- redis
|
||||
|
||||
worker:
|
||||
image: fudaoyuanicu/015-worker:latest
|
||||
container_name: worker
|
||||
volumes:
|
||||
- ./uploads:/uploads
|
||||
- ./config.yaml:/config.yaml
|
||||
depends_on:
|
||||
- app
|
||||
- redis
|
||||
redis:
|
||||
image: redis:7
|
||||
container_name: redis
|
||||
BIN
docs/image/0.png
|
Before Width: | Height: | Size: 1.8 MiB |
|
Before Width: | Height: | Size: 1.0 MiB |
|
Before Width: | Height: | Size: 654 KiB |
@@ -1,19 +1,19 @@
|
||||
<!-- app.vue -->
|
||||
<script setup lang="ts">
|
||||
import { defineRule } from 'vee-validate';
|
||||
import { all } from '@vee-validate/rules';
|
||||
import { defineRule } from 'vee-validate'
|
||||
import { all } from '@vee-validate/rules'
|
||||
Object.entries(all).forEach(([name, rule]) => {
|
||||
defineRule(name, rule);
|
||||
});
|
||||
defineRule(name, rule)
|
||||
})
|
||||
// @ts-check
|
||||
const { $serwist } = useNuxtApp();
|
||||
$serwist?.addEventListener("installed", () => {
|
||||
console.log("Serwist installed!");
|
||||
});
|
||||
void $serwist?.register({ immediate: true });
|
||||
// const { $serwist } = useNuxtApp();
|
||||
// $serwist?.addEventListener("installed", () => {
|
||||
// console.log("Serwist installed!");
|
||||
// });
|
||||
// void $serwist?.register({ immediate: true });
|
||||
</script>
|
||||
<template>
|
||||
<NuxtLayout>
|
||||
<NuxtPage />
|
||||
</NuxtLayout>
|
||||
</template>
|
||||
<NuxtLayout>
|
||||
<NuxtPage />
|
||||
</NuxtLayout>
|
||||
</template>
|
||||
|
||||
@@ -41,6 +41,24 @@
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--animate-accordion-down: accordion-down 0.2s ease-out;
|
||||
--animate-accordion-up: accordion-up 0.2s ease-out;
|
||||
@keyframes accordion-down {
|
||||
from {
|
||||
height: 0;
|
||||
}
|
||||
to {
|
||||
height: var(--reka-accordion-content-height);
|
||||
}
|
||||
}
|
||||
@keyframes accordion-up {
|
||||
from {
|
||||
height: var(--reka-accordion-content-height);
|
||||
}
|
||||
to {
|
||||
height: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:root {
|
||||
|
||||
127
front/components/About/AboutBaseInfo.vue
Normal file
@@ -0,0 +1,127 @@
|
||||
<script setup lang="ts">
|
||||
import { useQuery } from '@tanstack/vue-query'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import getFileSize from '~/lib/getFileSize'
|
||||
import SparkMD5 from 'spark-md5'
|
||||
import useMyAppConfig from '@/composables/useMyAppConfig'
|
||||
import Progress from '~/components/ui/progress/Progress.vue'
|
||||
import renderI18n from '~/lib/renderI18n'
|
||||
import { I18nT } from 'vue-i18n'
|
||||
|
||||
const { locale } = useI18n()
|
||||
const appConfig = useMyAppConfig()
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['about'],
|
||||
queryFn: async () => {
|
||||
const data = await $fetch<{
|
||||
data: {
|
||||
file: {
|
||||
maximun: number
|
||||
current: number
|
||||
}
|
||||
bg_url?: string
|
||||
avatar?: string
|
||||
name?: string
|
||||
email?: string
|
||||
url?: string
|
||||
content?: Record<string, string>
|
||||
}
|
||||
}>('/api/about')
|
||||
return data?.data
|
||||
},
|
||||
})
|
||||
const { t } = useI18n()
|
||||
|
||||
const genUserAvatar = (email: string) => {
|
||||
return `https://www.gravatar.com/avatar/${SparkMD5.hash(email)}?d=retro`
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template v-if="isLoading">
|
||||
<div class="flex flex-col gap-2">
|
||||
<Skeleton class="aspect-[3/1] w-full rounded-xl" />
|
||||
<div class="flex flex-col gap-2 items-center">
|
||||
<Skeleton class="h-6 w-32 rounded" />
|
||||
<Skeleton class="h-4 w-52 rounded" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<NuxtImg v-if="data?.bg_url" :src="data?.bg_url" class="aspect-[3/1] w-full rounded-xl object-cover" />
|
||||
<div class="flex flex-col gap-2 items-center">
|
||||
<div class="text-xl">{{ renderI18n(appConfig?.site_title ?? {}, 'en', locale) }}</div>
|
||||
<div class="text-sm opacity-75 text-center px-5">
|
||||
<I18nT keypath="page.about.powerBy" tag="span">
|
||||
<NuxtLink href="https://github.com/keven1024/015" target="_blank" class="text-primary hover:underline">015</NuxtLink>
|
||||
</I18nT>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="font-semibold">{{ t('page.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-1 md:grid-cols-2 gap-2">
|
||||
<div class="rounded-xl bg-white/50 flex-1 flex flex-col p-3 gap-2">
|
||||
<div class="opacity-75 text-xs">{{ t('page.about.admin') }}</div>
|
||||
<div
|
||||
class="flex flex-row gap-2 items-center cursor-pointer"
|
||||
@click="
|
||||
() => {
|
||||
if (data?.url) {
|
||||
navigateTo(data?.url, { external: true })
|
||||
return
|
||||
}
|
||||
if (data?.email) {
|
||||
navigateTo(`mailto:${data?.email ?? ''}`, { external: true })
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
"
|
||||
>
|
||||
<Avatar class="size-10">
|
||||
<AvatarImage v-if="!!data?.avatar || !!data?.email" :src="data?.avatar || genUserAvatar(data?.email as string)" />
|
||||
<AvatarFallback class="bg-black/10 font-bold">
|
||||
{{ data?.name?.charAt(0)?.toUpperCase() }}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div class="flex flex-col">
|
||||
<div class="text-md font-semibold">{{ data?.name }}</div>
|
||||
<div class="text-xs opacity-75">{{ data?.email }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/50 flex-1 flex flex-col p-3 gap-2">
|
||||
<div class="opacity-75 text-xs">{{ t('page.about.storage') }}</div>
|
||||
<div class="text-right flex flex-row items-baseline">
|
||||
<span class="text-lg font-semibold">{{ getFileSize(data?.file?.current ?? 0) }}</span>
|
||||
<span class="text-md opacity-75">/ {{ getFileSize(data?.file?.maximun ?? 0) }}</span>
|
||||
</div>
|
||||
<Progress class="h-1" :model-value="((data?.file?.current ?? 0) / (data?.file?.maximun ?? 0)) * 100" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-if="isLoading">
|
||||
<Skeleton class="w-full h-16 rounded-xl" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<div v-if="data?.content" class="rounded-xl bg-white/50 flex flex-col px-3 gap-2">
|
||||
<Accordion type="single" collapsible>
|
||||
<AccordionItem value="about">
|
||||
<AccordionTrigger>
|
||||
<span class="font-semibold">{{ t('page.about.about') }}</span>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<MarkdownRender class="max-w-full" :markdown="renderI18n(data?.content ?? {}, 'en', locale) ?? ''" />
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
187
front/components/About/AboutChartView.vue
Normal file
@@ -0,0 +1,187 @@
|
||||
<script setup lang="ts">
|
||||
import { CurveType } from '@unovis/ts'
|
||||
import { AreaChart } from '@/components/ui/chart-area'
|
||||
import { cx } from 'class-variance-authority'
|
||||
import { useQuery } from '@tanstack/vue-query'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import AboutChartTooltip from '@/components/AboutChartTooltip.vue'
|
||||
import dayjs from 'dayjs'
|
||||
import { times } from 'lodash-es'
|
||||
|
||||
interface StatChartData {
|
||||
file_size: number
|
||||
file_num: number
|
||||
share_num: number
|
||||
download_num: number
|
||||
date: string
|
||||
}
|
||||
|
||||
interface QueueChartData {
|
||||
processed: number
|
||||
failed: number
|
||||
date: string
|
||||
}
|
||||
|
||||
type ChartDataItem = StatChartData | QueueChartData
|
||||
|
||||
type ChartConfig = {
|
||||
data: ChartDataItem[]
|
||||
index: string
|
||||
categories: string[]
|
||||
colors: string[]
|
||||
}
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['stat'],
|
||||
queryFn: async () => {
|
||||
const response = await $fetch<{
|
||||
data: {
|
||||
chart: {
|
||||
storage: Record<string, StatChartData>
|
||||
queue: Record<string, QueueChartData>
|
||||
}
|
||||
}
|
||||
}>('/api/stat')
|
||||
return response.data
|
||||
},
|
||||
})
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const chartTabs = computed(() => {
|
||||
return [
|
||||
{
|
||||
label: t('page.about.file'),
|
||||
value: 'storage',
|
||||
total: data.value?.chart?.storage
|
||||
? Object.values(data.value.chart.storage).reduce((acc: number, curr: StatChartData) => acc + curr.file_num, 0)
|
||||
: 0,
|
||||
},
|
||||
{
|
||||
label: t('page.about.share'),
|
||||
value: 'share',
|
||||
total: data.value?.chart?.storage
|
||||
? Object.values(data.value.chart.storage).reduce((acc: number, curr: StatChartData) => acc + curr.share_num, 0)
|
||||
: 0,
|
||||
},
|
||||
{
|
||||
label: t('page.about.download'),
|
||||
value: 'download',
|
||||
total: data.value?.chart?.storage
|
||||
? Object.values(data.value.chart.storage).reduce((acc: number, curr: StatChartData) => acc + curr.download_num, 0)
|
||||
: 0,
|
||||
},
|
||||
{
|
||||
label: t('page.about.task'),
|
||||
value: 'queue',
|
||||
total: data.value?.chart?.queue
|
||||
? Object.values(data.value.chart.queue).reduce((acc: number, curr: QueueChartData) => acc + curr.processed + curr.failed, 0)
|
||||
: 0,
|
||||
},
|
||||
]
|
||||
})
|
||||
|
||||
const currentChartTab = ref<'storage' | 'queue' | 'share' | 'download'>('storage')
|
||||
const currentChartData = computed((): ChartConfig => {
|
||||
const { storage, queue } = data.value?.chart || {}
|
||||
if (currentChartTab.value === 'queue') {
|
||||
const queueData = times(30, (i) => {
|
||||
return {
|
||||
date: dayjs().subtract(i, 'day').format('YYYY-MM-DD'),
|
||||
processed: queue?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.processed || 0,
|
||||
failed: queue?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.failed || 0,
|
||||
}
|
||||
})
|
||||
return {
|
||||
data: queueData,
|
||||
index: 'date' as const,
|
||||
categories: ['processed', 'failed'] as const,
|
||||
colors: ['#4ade80', '#f87171'],
|
||||
}
|
||||
}
|
||||
const storageData = times(30, (i) => {
|
||||
const base = { date: dayjs().subtract(i, 'day').format('YYYY-MM-DD') }
|
||||
if (currentChartTab.value === 'share') {
|
||||
return {
|
||||
...base,
|
||||
share_num: storage?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.share_num || 0,
|
||||
}
|
||||
}
|
||||
if (currentChartTab.value === 'download') {
|
||||
return {
|
||||
...base,
|
||||
download_num: storage?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.download_num || 0,
|
||||
}
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
file_size: storage?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.file_size || 0,
|
||||
file_num: storage?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.file_num || 0,
|
||||
}
|
||||
})
|
||||
|
||||
let categories = ['file_size', 'file_num']
|
||||
if (currentChartTab.value === 'share') {
|
||||
categories = ['share_num']
|
||||
}
|
||||
if (currentChartTab.value === 'download') {
|
||||
categories = ['download_num']
|
||||
}
|
||||
let colors = ['#38bdf8', '#a78bfa']
|
||||
if (currentChartTab.value === 'share') {
|
||||
colors = ['#ea580c']
|
||||
}
|
||||
if (currentChartTab.value === 'download') {
|
||||
colors = ['#a3e635']
|
||||
}
|
||||
return {
|
||||
data: storageData as ChartDataItem[],
|
||||
index: 'date' as const,
|
||||
categories,
|
||||
colors,
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="font-semibold">{{ t('page.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="grid grid-cols-2 md:grid-cols-4 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>
|
||||
20
front/components/About/AboutVersionView.vue
Normal file
@@ -0,0 +1,20 @@
|
||||
<script setup lang="ts">
|
||||
import useMyAppConfig from '@/composables/useMyAppConfig'
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
const appConfig = useMyAppConfig()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-row flex-wrap gap-4 items-center text-sm opacity-60">
|
||||
<div class="flex flex-row gap-1 opacity-100">
|
||||
<NuxtLink href="https://github.com/keven1024/015" target="_blank" class="text-primary hover:underline">015</NuxtLink>
|
||||
{{ appConfig?.version ?? 'dev' }}
|
||||
</div>
|
||||
|
||||
<div v-if="appConfig?.build_time">
|
||||
{{ `Build at ${dayjs(appConfig?.build_time * 1000).format('YYYY-MM-DD')}` }}
|
||||
</div>
|
||||
<div>Designed by <NuxtLink href="https://fudaoyuan.icu" target="_blank" class="text-primary hover:underline">keven1024</NuxtLink></div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,53 +1,43 @@
|
||||
<script setup lang="ts">
|
||||
import { filesize } from "filesize";
|
||||
import getFileSize from '~/lib/getFileSize'
|
||||
|
||||
const props = defineProps<{
|
||||
data: { name: string; value: string; color: string }[];
|
||||
title: string;
|
||||
}>();
|
||||
data: { name: string; value: string; color: string }[]
|
||||
title: string
|
||||
}>()
|
||||
const dataKeyMap = {
|
||||
file_size: {
|
||||
"zh-CN": "文件大小",
|
||||
en: "File Size",
|
||||
},
|
||||
file_num: {
|
||||
"zh-CN": "文件数量",
|
||||
en: "File Num",
|
||||
},
|
||||
processed: {
|
||||
"zh-CN": "处理数量",
|
||||
en: "Processed",
|
||||
},
|
||||
failed: {
|
||||
"zh-CN": "失败数量",
|
||||
en: "Failed",
|
||||
},
|
||||
};
|
||||
file_size: {
|
||||
'zh-CN': '文件大小',
|
||||
en: 'File Size',
|
||||
},
|
||||
file_num: {
|
||||
'zh-CN': '文件数量',
|
||||
en: 'File Num',
|
||||
},
|
||||
processed: {
|
||||
'zh-CN': '处理数量',
|
||||
en: 'Processed',
|
||||
},
|
||||
failed: {
|
||||
'zh-CN': '失败数量',
|
||||
en: 'Failed',
|
||||
},
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="rounded-md bg-white p-2 flex flex-col gap-2">
|
||||
<div class="text-sm font-medium">{{ title }}</div>
|
||||
<div v-for="(item, index) in data" :key="index">
|
||||
<div class="flex flex-row items-center gap-2">
|
||||
<div
|
||||
class="h-5 w-2 rounded-full"
|
||||
:style="{ backgroundColor: item.color ?? '#222' }"
|
||||
></div>
|
||||
<div class="text-xs font-medium">
|
||||
{{
|
||||
dataKeyMap?.[item.name as keyof typeof dataKeyMap]?.["en"] ??
|
||||
item.name
|
||||
}}
|
||||
<div class="rounded-md bg-white p-2 flex flex-col gap-2">
|
||||
<div class="text-sm font-medium">{{ title }}</div>
|
||||
<div v-for="(item, index) in data" :key="index">
|
||||
<div class="flex flex-row items-center gap-2">
|
||||
<div class="h-5 w-2 rounded-full" :style="{ backgroundColor: item.color ?? '#222' }"></div>
|
||||
<div class="text-xs font-medium">
|
||||
{{ dataKeyMap?.[item.name as keyof typeof dataKeyMap]?.['en'] ?? item.name }}
|
||||
</div>
|
||||
<div class="text-sm">
|
||||
{{ ['file_size']?.includes(item?.name) ? getFileSize(item.value) : item.value }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-sm">
|
||||
{{
|
||||
["file_size"]?.includes(item?.name)
|
||||
? filesize(item.value)
|
||||
: item.value
|
||||
}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
29
front/components/BaseCard.vue
Normal file
@@ -0,0 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
title?: string
|
||||
showBackButton?: boolean
|
||||
}>()
|
||||
const router = useRouter()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="rounded-xl p-5 bg-white/50 backdrop-blur-xl w-full lg:w-200">
|
||||
<div v-if="title" class="flex flex-row justify-between">
|
||||
<h1 class="text-xl font-normal">{{ title }}</h1>
|
||||
<Button
|
||||
v-if="!!showBackButton"
|
||||
variant="outline"
|
||||
class="bg-white/70"
|
||||
size="icon"
|
||||
@click="
|
||||
() => {
|
||||
router.push('/')
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideHome />
|
||||
</Button>
|
||||
</div>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,19 +1,21 @@
|
||||
<script lang="ts" setup>
|
||||
import { VisSingleContainer, VisDonut } from '@unovis/vue'
|
||||
import { withDefaults, defineProps } from 'vue'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
value?: number
|
||||
size?: number
|
||||
color?: string
|
||||
}>(), {
|
||||
value: 0,
|
||||
size: 40,
|
||||
color: '#06b6d4'
|
||||
})
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
value?: number
|
||||
size?: number
|
||||
color?: string
|
||||
}>(),
|
||||
{
|
||||
value: 0,
|
||||
size: 40,
|
||||
color: '#06b6d4',
|
||||
}
|
||||
)
|
||||
const data = computed(() => {
|
||||
const progress = Math.min(Math.max(props.value, 0), 100)
|
||||
return [progress, 100 - progress ]
|
||||
return [progress, 100 - progress]
|
||||
})
|
||||
const getValue = (d: number) => d
|
||||
const getColor = (d: number, i: number) => [props?.color, 'transparent'][i]
|
||||
|
||||
@@ -1,120 +1,119 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
LucideShare,
|
||||
LucideImage,
|
||||
LucideBot,
|
||||
LucideLanguages,
|
||||
LucideFileText,
|
||||
LucideImageMinus,
|
||||
LucideArrowRightLeft,
|
||||
LucideImagePlus,
|
||||
LucideAudioLines,
|
||||
LucideListMusic,
|
||||
} from "lucide-vue-next";
|
||||
import { cx } from "class-variance-authority";
|
||||
import { isObject } from "lodash-es";
|
||||
import showDrawer from "@/lib/showDrawer";
|
||||
import FileShareHandle from "@/components/Preprocessing/FileShareHandle.vue";
|
||||
const { t } = useI18n();
|
||||
LucideShare,
|
||||
LucideImage,
|
||||
LucideBot,
|
||||
LucideLanguages,
|
||||
LucideFileText,
|
||||
LucideImageMinus,
|
||||
LucideArrowRightLeft,
|
||||
LucideImagePlus,
|
||||
LucideAudioLines,
|
||||
LucideListMusic,
|
||||
} from 'lucide-vue-next'
|
||||
import { cx } from 'class-variance-authority'
|
||||
import { isObject } from 'lodash-es'
|
||||
import showDrawer from '@/lib/showDrawer'
|
||||
import FileShareHandle from '@/components/Preprocessing/FileShareHandle.vue'
|
||||
import ImageConvertHandle from '@/components/Preprocessing/ImageConvertHandle.vue'
|
||||
import type { FileShareHandleProps } from '../Preprocessing/types'
|
||||
const { t } = useI18n()
|
||||
const props = defineProps<{
|
||||
hide: () => void;
|
||||
file: File;
|
||||
onFileHandle: ({ type, config }: { type: string; config: any }) => void;
|
||||
}>();
|
||||
hide: () => void
|
||||
file: File[]
|
||||
onFileHandle: (props: FileShareHandleProps) => void
|
||||
}>()
|
||||
|
||||
const isImage = computed(() => props.file.type.startsWith("image/"));
|
||||
const isVideo = computed(() => props.file.type.startsWith("video/"));
|
||||
const isAudio = computed(() => props.file.type.startsWith("audio/"));
|
||||
const isMedia = computed(() => isImage.value || isVideo.value || isAudio.value);
|
||||
const isImage = computed(() => props.file.every((r) => r?.type?.startsWith('image/')))
|
||||
const isVideo = computed(() => props.file.every((r) => r?.type?.startsWith('video/')))
|
||||
const isAudio = computed(() => props.file.every((r) => r?.type?.startsWith('audio/')))
|
||||
const isMedia = computed(() => isImage.value || isVideo.value || isAudio.value)
|
||||
|
||||
const isPDF = computed(() => props.file.type.startsWith("application/pdf"));
|
||||
const isDOC = computed(() => props.file.type.startsWith("application/msword"));
|
||||
const isXLS = computed(() =>
|
||||
props.file.type.startsWith("application/vnd.ms-excel"),
|
||||
);
|
||||
const isPPT = computed(() =>
|
||||
props.file.type.startsWith("application/vnd.ms-powerpoint"),
|
||||
);
|
||||
const isDocument = computed(
|
||||
() => isPDF.value || isDOC.value || isXLS.value || isPPT.value,
|
||||
);
|
||||
const isPDF = computed(() => props.file.every((r) => r?.type?.startsWith('application/pdf')))
|
||||
const isDOC = computed(() => props.file.every((r) => r?.type?.startsWith('application/msword')))
|
||||
const isXLS = computed(() => props.file.every((r) => r?.type?.startsWith('application/vnd.ms-excel')))
|
||||
const isPPT = computed(() => props.file.every((r) => r?.type?.startsWith('application/vnd.ms-powerpoint')))
|
||||
const isDocument = computed(() => isPDF.value || isDOC.value || isXLS.value || isPPT.value)
|
||||
const actions = [
|
||||
{
|
||||
label: t("file.handleType.file-share"),
|
||||
icon: LucideShare,
|
||||
className: "bg-green-300",
|
||||
onClick: () => {
|
||||
showDrawer({
|
||||
render: ({ hide }) => h(FileShareHandle, { ...props, hide }),
|
||||
});
|
||||
{
|
||||
label: t('page.upload.file.handleType.file-share'),
|
||||
icon: LucideShare,
|
||||
className: 'bg-green-300',
|
||||
onClick: () => {
|
||||
showDrawer({
|
||||
render: ({ hide }) => h(FileShareHandle, { ...props, hide }),
|
||||
})
|
||||
},
|
||||
},
|
||||
},
|
||||
isImage.value && {
|
||||
label: t("file.handleType.file-image-compress"),
|
||||
icon: LucideImageMinus,
|
||||
className: "bg-red-300",
|
||||
onClick: () => {
|
||||
props.onFileHandle({ type: "file-image-compress", config: {} });
|
||||
isImage.value && {
|
||||
label: t('page.upload.file.handleType.file-image-compress'),
|
||||
icon: LucideImageMinus,
|
||||
className: 'bg-red-300',
|
||||
onClick: () => {
|
||||
props.onFileHandle({ type: 'file-image-compress', config: {} })
|
||||
},
|
||||
},
|
||||
},
|
||||
// isImage.value && {
|
||||
// label: '图片翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// isImage.value && {
|
||||
// label: '图片超分', icon: LucideImagePlus, className: 'bg-cyan-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// (isAudio.value || isVideo.value) && {
|
||||
// label: '转文本', icon: LucideListMusic, className: 'bg-cyan-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// isAudio.value && {
|
||||
// label: '语音克隆', icon: LucideAudioLines, className: 'bg-cyan-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// (isDocument.value || isMedia.value) && {
|
||||
// label: '格式转换', icon: LucideArrowRightLeft, className: 'bg-purple-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
isImage.value && {
|
||||
label: t('page.upload.file.handleType.file-image-convert'),
|
||||
icon: LucideArrowRightLeft,
|
||||
className: 'bg-purple-300',
|
||||
onClick: () => {
|
||||
showDrawer({
|
||||
render: ({ hide }) => h(ImageConvertHandle, { ...props, hide }),
|
||||
})
|
||||
},
|
||||
},
|
||||
// isImage.value && {
|
||||
// label: '图片翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// isImage.value && {
|
||||
// label: '图片超分', icon: LucideImagePlus, className: 'bg-cyan-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// (isAudio.value || isVideo.value) && {
|
||||
// label: '转文本', icon: LucideListMusic, className: 'bg-cyan-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// isAudio.value && {
|
||||
// label: '语音克隆', icon: LucideAudioLines, className: 'bg-cyan-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// (isDocument.value || isMedia.value) && {
|
||||
// label: '格式转换', icon: LucideArrowRightLeft, className: 'bg-purple-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
]?.filter(isObject) as {
|
||||
label: string;
|
||||
icon: any;
|
||||
className: string;
|
||||
onClick: () => void;
|
||||
}[];
|
||||
label: string
|
||||
icon: any
|
||||
className: string
|
||||
onClick: () => void
|
||||
}[]
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-5 p-5">
|
||||
<div class="flex flex-row gap-2">
|
||||
<div
|
||||
v-for="item in actions"
|
||||
:key="item.label"
|
||||
class="flex flex-col items-center gap-2 max-w-20"
|
||||
@click="
|
||||
() => {
|
||||
props?.hide();
|
||||
item?.onClick();
|
||||
}
|
||||
"
|
||||
>
|
||||
<div
|
||||
:class="
|
||||
cx(
|
||||
'size-14 flex justify-center items-center rounded-full mx-3',
|
||||
item?.className,
|
||||
)
|
||||
"
|
||||
>
|
||||
<component :is="item?.icon" />
|
||||
<div class="flex flex-col gap-5 p-5">
|
||||
<div class="flex flex-row gap-2">
|
||||
<div
|
||||
v-for="item in actions"
|
||||
:key="item.label"
|
||||
class="flex flex-col items-center gap-2 max-w-20"
|
||||
@click="
|
||||
() => {
|
||||
props?.hide()
|
||||
item?.onClick()
|
||||
}
|
||||
"
|
||||
>
|
||||
<div :class="cx('size-14 flex justify-center items-center rounded-full mx-3', item?.className)">
|
||||
<component :is="item?.icon" />
|
||||
</div>
|
||||
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,57 +1,56 @@
|
||||
<script setup lang="ts">
|
||||
import VeeForm from "@/components/VeeForm.vue";
|
||||
import FormButton from "@/components/Field/FormButton.vue";
|
||||
import PinInputField from "@/components/Field/PinInputField.vue";
|
||||
import type { FormContext, GenericObject } from "vee-validate";
|
||||
import { toast } from "vue-sonner";
|
||||
const router = useRouter();
|
||||
import VeeForm from '@/components/VeeForm.vue'
|
||||
import FormButton from '@/components/Field/FormButton.vue'
|
||||
import PinInputField from '@/components/Field/PinInputField.vue'
|
||||
import type { FormContext, GenericObject } from 'vee-validate'
|
||||
import { toast } from 'vue-sonner'
|
||||
const router = useRouter()
|
||||
const { t } = useI18n()
|
||||
const props = defineProps<{
|
||||
hide: () => void;
|
||||
}>();
|
||||
const handleSubmit = async (
|
||||
form: FormContext<GenericObject, GenericObject>,
|
||||
) => {
|
||||
try {
|
||||
const code = form.values.code;
|
||||
const data = await $fetch<{
|
||||
data: {
|
||||
share_id: string;
|
||||
};
|
||||
}>(`/api/share/pickup/${code}`);
|
||||
if (!data.data.share_id) {
|
||||
toast.error("取件码错误");
|
||||
form.resetForm();
|
||||
return;
|
||||
hide: () => void
|
||||
}>()
|
||||
const handleSubmit = async (form: FormContext<GenericObject, GenericObject>) => {
|
||||
try {
|
||||
const code = form.values.code
|
||||
const data = await $fetch<{
|
||||
data: {
|
||||
share_id: string
|
||||
}
|
||||
}>(`/api/share/pickup/${code}`)
|
||||
if (!data.data.share_id) {
|
||||
toast.error(t('page.upload.pickup.codeError'))
|
||||
form.resetForm()
|
||||
return
|
||||
}
|
||||
const { share_id } = data.data
|
||||
props.hide()
|
||||
router.push({
|
||||
path: `/s/${share_id}`,
|
||||
})
|
||||
return
|
||||
} catch (error) {
|
||||
toast.error(t('page.upload.pickup.codeError'))
|
||||
form.resetForm()
|
||||
}
|
||||
const { share_id } = data.data;
|
||||
props.hide();
|
||||
router.push({
|
||||
path: `/s/${share_id}`,
|
||||
});
|
||||
return;
|
||||
} catch (error) {
|
||||
toast.error("取件码错误");
|
||||
form.resetForm();
|
||||
}
|
||||
};
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<VeeForm>
|
||||
<div class="flex flex-col gap-5">
|
||||
<div class="text-xl font-bold">输入取件码</div>
|
||||
<PinInputField
|
||||
name="code"
|
||||
:rules="
|
||||
(value) => {
|
||||
if (value?.length !== 4) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
"
|
||||
/>
|
||||
<FormButton @click="handleSubmit">提交</FormButton>
|
||||
</div>
|
||||
</VeeForm>
|
||||
<VeeForm>
|
||||
<div class="flex flex-col gap-5">
|
||||
<div class="text-xl font-bold">{{ t('page.upload.pickup.title') }}</div>
|
||||
<PinInputField
|
||||
name="code"
|
||||
:rules="
|
||||
(value) => {
|
||||
if (value?.length !== 4) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
"
|
||||
/>
|
||||
<FormButton @click="handleSubmit">{{ t('btn.submit') }}</FormButton>
|
||||
</div>
|
||||
</VeeForm>
|
||||
</template>
|
||||
|
||||
@@ -1,74 +1,62 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
LucideShare,
|
||||
LucideImage,
|
||||
LucideBot,
|
||||
LucideLanguages,
|
||||
} from "lucide-vue-next";
|
||||
import { cx } from "class-variance-authority";
|
||||
import showDrawer from "@/lib/showDrawer";
|
||||
import TextShareHandle from "@/components/Preprocessing/TextShareHandle.vue";
|
||||
import { LucideShare, LucideImage, LucideBot, LucideLanguages } from 'lucide-vue-next'
|
||||
import { cx } from 'class-variance-authority'
|
||||
import showDrawer from '@/lib/showDrawer'
|
||||
import TextShareHandle from '@/components/Preprocessing/TextShareHandle.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
hide: () => void;
|
||||
text: string;
|
||||
onTextHandle: ({ type, config }: { type: string; config: any }) => void;
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
hide: () => void
|
||||
text: string
|
||||
onTextHandle: ({ type, config }: { type: string; config: any }) => void
|
||||
}>()
|
||||
const { t } = useI18n()
|
||||
const actions = [
|
||||
{
|
||||
label: t("text.handleType.text-share"),
|
||||
icon: LucideShare,
|
||||
className: "bg-green-300",
|
||||
onClick: () => {
|
||||
showDrawer({
|
||||
render: ({ hide }) => h(TextShareHandle, { ...props, hide }),
|
||||
});
|
||||
{
|
||||
label: t('page.upload.text.handleType.text-share'),
|
||||
icon: LucideShare,
|
||||
className: 'bg-green-300',
|
||||
onClick: () => {
|
||||
showDrawer({
|
||||
render: ({ hide }) => h(TextShareHandle, { ...props, hide }),
|
||||
})
|
||||
},
|
||||
},
|
||||
},
|
||||
// {
|
||||
// label: '生成配图', icon: LucideImage, className: 'bg-red-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// label: '问大模型', icon: LucideBot, className: 'bg-blue-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// label: '文本翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
];
|
||||
// {
|
||||
// label: '生成配图', icon: LucideImage, className: 'bg-red-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// label: '问大模型', icon: LucideBot, className: 'bg-blue-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// label: '文本翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
]
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-5 p-5">
|
||||
<div class="flex flex-row gap-2">
|
||||
<div
|
||||
v-for="item in actions"
|
||||
:key="item.label"
|
||||
class="flex flex-col items-center gap-2 max-w-20"
|
||||
@click="
|
||||
() => {
|
||||
props?.hide();
|
||||
item?.onClick();
|
||||
}
|
||||
"
|
||||
>
|
||||
<div
|
||||
:class="
|
||||
cx(
|
||||
'size-14 flex justify-center items-center rounded-full mx-3',
|
||||
item?.className,
|
||||
)
|
||||
"
|
||||
>
|
||||
<component :is="item?.icon" />
|
||||
<div class="flex flex-col gap-5 p-5">
|
||||
<div class="flex flex-row gap-2">
|
||||
<div
|
||||
v-for="item in actions"
|
||||
:key="item.label"
|
||||
class="flex flex-col items-center gap-2 max-w-20"
|
||||
@click="
|
||||
() => {
|
||||
props?.hide()
|
||||
item?.onClick()
|
||||
}
|
||||
"
|
||||
>
|
||||
<div :class="cx('size-14 flex justify-center items-center rounded-full mx-3', item?.className)">
|
||||
<component :is="item?.icon" />
|
||||
</div>
|
||||
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,42 +1,71 @@
|
||||
<script setup lang="ts">
|
||||
import FileUpload from "@/components/FileUpload.vue";
|
||||
import { cx } from "class-variance-authority";
|
||||
import type { RuleExpression } from "vee-validate";
|
||||
import FileUpload from '@/components/FileUpload.vue'
|
||||
import { cx } from 'class-variance-authority'
|
||||
import type { RuleExpression } from 'vee-validate'
|
||||
import Button from '../ui/button/Button.vue'
|
||||
import { PlusIcon } from 'lucide-vue-next'
|
||||
import { isEmpty } from 'lodash-es'
|
||||
|
||||
const props = defineProps<{
|
||||
name: string;
|
||||
rules?: RuleExpression<File>;
|
||||
}>();
|
||||
const { value, setValue } = useField<File>(props?.name, props?.rules);
|
||||
const { t } = useI18n();
|
||||
name: string
|
||||
rules?: RuleExpression<File[]>
|
||||
}>()
|
||||
const { value, setValue } = useField<File[]>(props?.name, props?.rules)
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<FileUpload
|
||||
@onChange="
|
||||
(file) => {
|
||||
setValue(file);
|
||||
}
|
||||
"
|
||||
v-slot="{ isOverDropZone }"
|
||||
>
|
||||
<div
|
||||
:class="
|
||||
cx(
|
||||
'bg-white/50 rounded-md p-2 w-full h-40 flex flex-col items-center justify-center border border-dashed border-black/20 cursor-pointer text-gray-500 gap-3',
|
||||
isOverDropZone && '!bg-green-100/50 ',
|
||||
)
|
||||
"
|
||||
<FileUpload
|
||||
@onChange="
|
||||
(file) => {
|
||||
// 这里没hash,我们姑且认为name和size,type都一样的为同一个文件
|
||||
setValue([...(value?.filter((r) => r?.name !== file?.name || r?.type !== file?.type || r?.size !== file?.size) || []), file])
|
||||
}
|
||||
"
|
||||
v-slot="{ isOverDropZone }"
|
||||
>
|
||||
<template v-if="!!value">
|
||||
<FilePreviewView :value="value" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<LucideUpload class="size-10" />
|
||||
<div class="text-sm">
|
||||
{{ t("file.uploadFilePlaceholder") }}
|
||||
<div
|
||||
:class="
|
||||
cx(
|
||||
'bg-white/50 rounded-md p-2 w-full min-h-40 flex flex-col items-center justify-center border border-dashed border-black/20 cursor-pointer text-gray-500 gap-3 transition-all duration-300',
|
||||
isOverDropZone && '!bg-green-100/50 '
|
||||
)
|
||||
"
|
||||
>
|
||||
<template v-if="!isEmpty(value)">
|
||||
<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-5 w-full">
|
||||
<div v-for="item in value" :key="item?.name" class="flex flex-col items-center justify-center relative">
|
||||
<div class="absolute top-0 right-0">
|
||||
<Button
|
||||
class="size-5 p-0 bg-red-500/20 hover:bg-red-500/60 text-red-500 hover:text-white"
|
||||
@click="
|
||||
(e: any) => {
|
||||
e.stopPropagation()
|
||||
setValue(
|
||||
value?.filter((r) => r?.name !== item?.name || r?.type !== item?.type || r?.size !== item?.size) || []
|
||||
)
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideX class="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<FilePreviewView :value="item" />
|
||||
</div>
|
||||
<div class="flex flex-col items-center justify-center opacity-50 gap-1">
|
||||
<div class="size-16 flex justify-center items-center rounded-xl bg-white/80">
|
||||
<PlusIcon class="size-7" />
|
||||
</div>
|
||||
<div class="mb-3">{{ t('page.upload.file.addMore') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<LucideUpload class="size-10" />
|
||||
<div class="text-sm select-none">
|
||||
{{ t('page.upload.file.uploadFilePlaceholder') }}
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</FileUpload>
|
||||
</FileUpload>
|
||||
</template>
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
</Field>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Input } from '@/components/ui/input'
|
||||
const props = defineProps<{
|
||||
name: string
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import Tiptap from '@/components/Tiptap.vue'
|
||||
import Tiptap from '@/components/Tiptap/Index.vue'
|
||||
import type { RuleExpression } from 'vee-validate'
|
||||
const props = defineProps<{
|
||||
name: string
|
||||
rules?: RuleExpression<string>
|
||||
}>()
|
||||
const { value, } = useField<string>(props.name, props.rules)
|
||||
const { value } = useField<string>(props.name, props.rules)
|
||||
</script>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { cx } from 'class-variance-authority'
|
||||
export type filePreview = {
|
||||
type: string
|
||||
name: string
|
||||
@@ -8,6 +9,7 @@ export type filePreview = {
|
||||
import { LucideFileAudio, LucideFileVideo, LucideFile, LucideFileCode, LucideFileArchive, LucideFileText } from 'lucide-vue-next'
|
||||
const props = defineProps<{
|
||||
file: File | filePreview
|
||||
class?: string
|
||||
}>()
|
||||
const imageUrl = computed(() => {
|
||||
if (props?.file?.type?.startsWith('image/') && props?.file instanceof File) {
|
||||
@@ -30,18 +32,23 @@ const fileIcon = computed(() => {
|
||||
if (baseType === 'audio') {
|
||||
return LucideFileAudio
|
||||
}
|
||||
if (baseType === 'text' || ["json", "ld+json", "html"]?.includes(type)) {
|
||||
if (baseType === 'text' || ['json', 'ld+json', 'html']?.includes(type ?? '')) {
|
||||
return LucideFileCode
|
||||
}
|
||||
if (['pdf', 'msword',
|
||||
'vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'vnd.ms-excel',
|
||||
'vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'vnd.ms-powerpoint',
|
||||
'vnd.openxmlformats-officedocument.presentationml.presentation'].includes(type)) {
|
||||
if (
|
||||
[
|
||||
'pdf',
|
||||
'msword',
|
||||
'vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'vnd.ms-excel',
|
||||
'vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'vnd.ms-powerpoint',
|
||||
'vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
].includes(type ?? '')
|
||||
) {
|
||||
return LucideFileText
|
||||
}
|
||||
if (['zip', 'vnd.rar', 'x-tar', 'gz', 'bz2', 'x-7z-compressed'].includes(type)) {
|
||||
if (['zip', 'vnd.rar', 'x-tar', 'gz', 'bz2', 'x-7z-compressed'].includes(type ?? '')) {
|
||||
return LucideFileArchive
|
||||
}
|
||||
return LucideFile
|
||||
@@ -51,11 +58,10 @@ const fileIcon = computed(() => {
|
||||
<template>
|
||||
<div v-if="!!imageUrl" class="flex max-w-30 max-h-20">
|
||||
<div class="object-contain m-auto h-full">
|
||||
<img :src="imageUrl" class="w-full h-full border border-black/20 rounded" />
|
||||
<img :src="imageUrl" class="w-full h-full border border-black/20 rounded" />
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!imageUrl" class="size-16 flex justify-center items-center rounded-xl bg-white/80">
|
||||
<component :is="fileIcon" class="size-10" />
|
||||
<div v-if="!imageUrl" :class="cx('flex justify-center items-center rounded-xl bg-white/80 size-16', props?.class)">
|
||||
<component :is="fileIcon" class="size-[62.5%]" />
|
||||
</div>
|
||||
|
||||
</template>
|
||||
</template>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts" setup>
|
||||
import { filesize } from 'filesize'
|
||||
import type { filePreview } from './FileIcon.vue';
|
||||
import getFileSize from '~/lib/getFileSize'
|
||||
import type { filePreview } from './FileIcon.vue'
|
||||
const props = defineProps<{
|
||||
value: File | filePreview
|
||||
}>()
|
||||
@@ -17,6 +17,6 @@ const fileInfo = computed(() => {
|
||||
<div class="truncate">{{ fileInfo?.name }}</div>
|
||||
<div>{{ `.${fileInfo?.ext}` }}</div>
|
||||
</div>
|
||||
<div class="text-xs opacity-50">{{ filesize(value?.size ?? 0) }}</div>
|
||||
<div class="text-xs opacity-50">{{ getFileSize(value?.size ?? 0) }}</div>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
44
front/components/FileUploadBlockProgressView.vue
Normal file
@@ -0,0 +1,44 @@
|
||||
<script setup lang="ts">
|
||||
import type { Graphics } from 'pixi.js'
|
||||
import type { PixiExpose } from '@/components/Pixi.vue'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
size?: number
|
||||
data?: { chunks: Record<number, { status: 'success' | 'error' | 'processing'; createdAt: number }>; chunkLength: number }
|
||||
}>(),
|
||||
{
|
||||
size: 16,
|
||||
data: () => ({ chunks: [], chunkLength: 0 }),
|
||||
}
|
||||
)
|
||||
const pixiRef = ref<PixiExpose>()
|
||||
const width = computed(() => pixiRef.value?.width || 0)
|
||||
const height = computed(() => pixiRef.value?.height || 0)
|
||||
watchEffect(() => {
|
||||
console.log('data', props.data)
|
||||
})
|
||||
const renderGraphics = (graphics: Graphics) => {
|
||||
graphics.clear()
|
||||
Object.entries(props?.data?.chunks || {})?.map(([index, item]) => {
|
||||
const { status, createdAt } = item || {}
|
||||
const size = width.value / props.data?.chunkLength
|
||||
const x = Number(index) * size
|
||||
graphics.rect(x, 0, size, height.value)
|
||||
let color = 0x60a5fa
|
||||
if (status === 'success') {
|
||||
color = 0x4ade80
|
||||
}
|
||||
if (status === 'error') {
|
||||
color = 0xf87171
|
||||
}
|
||||
graphics.fill(color)
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Pixi ref="pixiRef">
|
||||
<graphics @render="renderGraphics" />
|
||||
</Pixi>
|
||||
</template>
|
||||
62
front/components/FileUploadHeatMapView.vue
Normal file
@@ -0,0 +1,62 @@
|
||||
<script setup lang="ts">
|
||||
import type { Graphics } from 'pixi.js'
|
||||
import type { PixiExpose } from '@/components/Pixi.vue'
|
||||
|
||||
let props = withDefaults(
|
||||
defineProps<{
|
||||
size?: number
|
||||
gap?: number
|
||||
data?: { chunks: Record<number, { status: 'success' | 'error' | 'processing'; createdAt: number }>; chunkLength: number }
|
||||
}>(),
|
||||
{
|
||||
size: 16,
|
||||
gap: 4,
|
||||
data: () => ({ chunks: [], chunkLength: 0 }),
|
||||
}
|
||||
)
|
||||
const pixiRef = ref<PixiExpose>()
|
||||
const width = computed(() => pixiRef.value?.width)
|
||||
const height = computed(() => pixiRef.value?.height)
|
||||
|
||||
const size = ref(props.size)
|
||||
const gap = ref(props.gap)
|
||||
const itemsPerRow = ref(0)
|
||||
const itemsPerCol = computed(() => Math.ceil(props?.data?.chunkLength / itemsPerRow.value))
|
||||
watchEffect(() => {
|
||||
if (!width?.value || !height?.value || !pixiRef.value) return
|
||||
itemsPerRow.value = (width.value + gap.value) / (props.size + gap.value)
|
||||
if (itemsPerRow.value - Math.floor(itemsPerRow.value) > 0.5) {
|
||||
itemsPerRow.value = Math.floor(itemsPerRow.value)
|
||||
} else {
|
||||
itemsPerRow.value = Math.ceil(itemsPerRow.value)
|
||||
}
|
||||
size.value = (width.value - (itemsPerRow.value - 1) * gap.value) / itemsPerRow.value
|
||||
pixiRef.value.contentHeight = itemsPerCol.value * (size.value + gap.value) - gap.value
|
||||
})
|
||||
|
||||
const renderGraphics = (graphics: Graphics) => {
|
||||
graphics.clear()
|
||||
Object.entries(props?.data?.chunks || {})?.map(([index, item]) => {
|
||||
const { status, createdAt } = item || {}
|
||||
const row = Math.floor(Number(index) / itemsPerRow.value)
|
||||
const col = Number(index) % itemsPerRow.value
|
||||
const x = col * (size.value + gap.value)
|
||||
const y = row * (size.value + gap.value)
|
||||
graphics.roundRect(x, y, size.value, size.value, 4)
|
||||
let color = 0x60a5fa
|
||||
if (status === 'success') {
|
||||
color = 0x4ade80
|
||||
}
|
||||
if (status === 'error') {
|
||||
color = 0xf87171
|
||||
}
|
||||
graphics.fill(color)
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Pixi ref="pixiRef">
|
||||
<graphics @render="renderGraphics" />
|
||||
</Pixi>
|
||||
</template>
|
||||
16
front/components/GlobalDayjs.vue
Normal file
@@ -0,0 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import dayjs from 'dayjs'
|
||||
import relativeTime from 'dayjs/plugin/relativeTime'
|
||||
import 'dayjs/locale/en'
|
||||
import 'dayjs/locale/zh-cn'
|
||||
|
||||
dayjs.extend(relativeTime)
|
||||
|
||||
const { locale } = useI18n()
|
||||
|
||||
watchEffect(() => {
|
||||
dayjs.locale(locale.value.toLowerCase())
|
||||
})
|
||||
</script>
|
||||
|
||||
<template></template>
|
||||
@@ -3,31 +3,32 @@ import { Drawer, DrawerContent } from '@/components/ui/drawer'
|
||||
import { createVNode } from 'vue'
|
||||
import useStore from '@/composables/useStore'
|
||||
|
||||
const store = useStore('drawer')
|
||||
const drawer = computed(() => store?._get('drawer'))
|
||||
const currentDrawer = computed(() => drawer?.value?.[drawer?.value?.length - 1])
|
||||
const store = useStore()
|
||||
const currentDrawer = computed(() => store.drawer?.[store.drawer?.length - 1])
|
||||
|
||||
const render = computed<() => Component>(() => currentDrawer?.value?.render)
|
||||
const hide = computed<() => void>(() => currentDrawer?.value?.onClose)
|
||||
const render = computed(() => currentDrawer?.value?.render)
|
||||
const hide = computed(() => currentDrawer?.value?.onClose)
|
||||
const Children = () =>
|
||||
createVNode(render.value, {
|
||||
hide: hide?.value,
|
||||
})
|
||||
render.value
|
||||
? createVNode(render.value, {
|
||||
hide: hide?.value,
|
||||
})
|
||||
: null
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Drawer
|
||||
:open="!!drawer?.[drawer?.length - 1]"
|
||||
:open="!!store.drawer?.[store.drawer?.length - 1]"
|
||||
@update:open="
|
||||
(open) => {
|
||||
if (!open && drawer?.length > 0) {
|
||||
if (!open && store?.drawer?.length && hide) {
|
||||
hide()
|
||||
}
|
||||
}
|
||||
"
|
||||
>
|
||||
<DrawerContent>
|
||||
<div class="mx-auto w-full max-w-sm pb-10">
|
||||
<div class="mx-auto w-full max-w-lg pb-10 px-3">
|
||||
<Children />
|
||||
</div>
|
||||
</DrawerContent>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts" setup>
|
||||
import VeeForm from '@/components/VeeForm.vue'
|
||||
import FileUploadInputFileView from './FileUploadInputFileView.vue'
|
||||
import FileUploadProgressView from './FileUploadProgressView.vue'
|
||||
import FileUploadProgressView from './FileUploadProgressView/index.vue'
|
||||
import ResultIndexView from '@/components/Result/ResultIndexView.vue'
|
||||
|
||||
const fileStepList = [
|
||||
@@ -16,19 +16,26 @@ const renderComponent = computed(() => {
|
||||
return fileStepList.find((item) => item.key === step.value)?.component
|
||||
})
|
||||
const formRef = ref<InstanceType<typeof VeeForm>>()
|
||||
watch(() => step.value, (newVal) => {
|
||||
if (newVal === 'input') {
|
||||
formRef.value?.form?.resetForm()
|
||||
formRef.value?.form?.setValues({ file: null })
|
||||
watch(
|
||||
() => step.value,
|
||||
(newVal) => {
|
||||
if (newVal === 'input') {
|
||||
formRef.value?.form?.resetForm()
|
||||
formRef.value?.form?.setValues({ file: null })
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
</script>
|
||||
<template>
|
||||
<VeeForm ref="formRef" v-slot="{ values }" :keepValues="true">
|
||||
<div class="rounded-xl p-5 bg-white/50 backdrop-blur-xl w-full lg:w-200">
|
||||
<component :is="renderComponent" :data="values" @change="(key: string) => {
|
||||
step = key
|
||||
}" />
|
||||
</div>
|
||||
<component
|
||||
:is="renderComponent"
|
||||
:data="values"
|
||||
@change="
|
||||
(key: string) => {
|
||||
step = key
|
||||
}
|
||||
"
|
||||
/>
|
||||
</VeeForm>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
@@ -1,42 +1,39 @@
|
||||
<script lang="ts" setup>
|
||||
import showDrawer from "@/lib/showDrawer";
|
||||
import FileShareDrawer from "@/components/Drawer/FileShareDrawer.vue";
|
||||
import FileUploadField from "@/components/Field/FileUploadField.vue";
|
||||
import FormButton from "@/components/Field/FormButton.vue";
|
||||
import PickupShareBtn from "@/components/PickupShareBtn.vue";
|
||||
import showDrawer from '@/lib/showDrawer'
|
||||
import FileShareDrawer from '@/components/Drawer/FileShareDrawer.vue'
|
||||
import FileUploadField from '@/components/Field/FileUploadField.vue'
|
||||
import FormButton from '@/components/Field/FormButton.vue'
|
||||
import PickupShareBtn from '@/components/PickupShareBtn.vue'
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "change", key: string): void;
|
||||
}>();
|
||||
(e: 'change', key: string): void
|
||||
}>()
|
||||
|
||||
const { t } = useI18n();
|
||||
const { t } = useI18n()
|
||||
|
||||
const handleFormSubmit = async (form: any) => {
|
||||
const { file } = form?.values || {};
|
||||
showDrawer({
|
||||
render: ({ hide }) =>
|
||||
h(FileShareDrawer, {
|
||||
hide,
|
||||
file,
|
||||
onFileHandle: ({ type, config }) => {
|
||||
form.setFieldValue("handle_type", type);
|
||||
form.setFieldValue("config", config);
|
||||
emit("change", "progress");
|
||||
},
|
||||
}),
|
||||
});
|
||||
};
|
||||
const { file } = form?.values || {}
|
||||
showDrawer({
|
||||
render: ({ hide }) =>
|
||||
h(FileShareDrawer, {
|
||||
hide,
|
||||
file,
|
||||
onFileHandle: ({ type, config }) => {
|
||||
form.setFieldValue('handle_type', type)
|
||||
form.setFieldValue('config', config)
|
||||
emit('change', 'progress')
|
||||
},
|
||||
}),
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="gap-5 flex flex-col">
|
||||
<div class="text-xl font-normal">{{ t("file.uploadFile") }}</div>
|
||||
<FileUploadField name="file" rules="required" />
|
||||
<div class="flex flex-row gap-3">
|
||||
<FormButton @click="handleFormSubmit">
|
||||
<LucideShare class="size-4" />{{ t("btn.submit") }}
|
||||
</FormButton>
|
||||
<PickupShareBtn />
|
||||
</div>
|
||||
</div>
|
||||
<BaseCard class="gap-5 flex flex-col" :title="t('page.upload.file.uploadFile')">
|
||||
<FileUploadField name="file" rules="required" />
|
||||
<div class="flex flex-row gap-3">
|
||||
<FormButton @click="handleFormSubmit"> <LucideShare class="size-4" />{{ t('btn.submit') }} </FormButton>
|
||||
<PickupShareBtn />
|
||||
</div>
|
||||
</BaseCard>
|
||||
</template>
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
import CircularProgress from '@/components/CircularProgress.vue'
|
||||
import { chunk, get, shuffle, times } from 'lodash-es'
|
||||
import { cx } from 'class-variance-authority'
|
||||
import { filesize } from 'filesize'
|
||||
import { toast } from 'vue-sonner'
|
||||
import asyncWorker from '~/lib/asyncWorker'
|
||||
import calcFileHashWorker from '~/lib/calcFileHashWorker?worker'
|
||||
const props = defineProps<{
|
||||
data: { file: File; config: any; handle_type: string }
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'change', key: string): void
|
||||
}>()
|
||||
|
||||
const form = useFormContext()
|
||||
|
||||
const step = ref<'hash' | 'upload'>('hash')
|
||||
const calcHashTime = ref(0)
|
||||
const chunkSize = ref(0)
|
||||
const fileSliceUploadStatusList = ref<
|
||||
{
|
||||
status: string
|
||||
index: number
|
||||
}[]
|
||||
>([])
|
||||
|
||||
const successCount = computed(() => fileSliceUploadStatusList.value.filter((item) => item.status === 'success').length)
|
||||
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 { error } = useAsyncState(async () => {
|
||||
const { file } = props.data || {}
|
||||
if (!file) return
|
||||
const { size, type = 'application/octet-stream' } = file || {}
|
||||
const now = Date.now()
|
||||
const res = await asyncWorker(calcFileHashWorker, { data: { file } })
|
||||
const { hash } = res?.data || {}
|
||||
if (hash) {
|
||||
step.value = 'upload'
|
||||
calcHashTime.value = Date.now() - now
|
||||
}
|
||||
|
||||
const createData = await $fetch<{
|
||||
data: {
|
||||
id: string
|
||||
type: 'init' | 'already'
|
||||
chunk_size: number
|
||||
}
|
||||
}>('/api/file/create', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
size,
|
||||
mime_type: get(type, '', 'application/octet-stream'),
|
||||
hash,
|
||||
},
|
||||
})
|
||||
const { id, chunk_size, type: createType } = createData?.data || {}
|
||||
if (createType !== 'init') {
|
||||
// 文件存在
|
||||
form.setFieldValue('file_id', id)
|
||||
emit('change', 'result')
|
||||
return
|
||||
}
|
||||
chunkSize.value = chunk_size
|
||||
const chunks = Math.ceil(size / chunk_size)
|
||||
fileSliceUploadStatusList.value = times(chunks, (i) => ({
|
||||
status: 'pending',
|
||||
index: i,
|
||||
}))
|
||||
|
||||
const readChunk = (start: number): Promise<ArrayBuffer> => {
|
||||
const fileReader = new FileReader()
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunk = file.slice(start, start + chunk_size)
|
||||
fileReader.onload = (e) => resolve(e.target?.result as ArrayBuffer)
|
||||
fileReader.onerror = reject
|
||||
fileReader.readAsArrayBuffer(chunk)
|
||||
})
|
||||
}
|
||||
|
||||
const chunkedUploadTasks = chunk(shuffle([...fileSliceUploadStatusList.value]), 3)
|
||||
for (let i = 0; i < chunkedUploadTasks?.length; i++) {
|
||||
await Promise.all(
|
||||
chunkedUploadTasks?.[i]?.map(async (item: any) => {
|
||||
const { index } = item || {}
|
||||
try {
|
||||
const chunk = await readChunk(index * chunk_size)
|
||||
// console.log('chunk', chunk)
|
||||
const formData = new FormData()
|
||||
formData.append('file', new Blob([chunk]))
|
||||
formData.append('index', index + 1)
|
||||
formData.append('id', id)
|
||||
fileSliceUploadStatusList.value[index].status = 'uploading'
|
||||
const res = await $fetch<{
|
||||
code: number
|
||||
}>('/api/file/slice', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
const { code } = res || {}
|
||||
if (code !== 200) {
|
||||
throw new Error('上传失败')
|
||||
}
|
||||
fileSliceUploadStatusList.value[index].status = 'success'
|
||||
} catch (error) {
|
||||
console.log('error', error)
|
||||
// fileSliceStatusList.value[index].status = 'error'
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
const r = await $fetch<{
|
||||
code: number
|
||||
}>('/api/file/finish', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id,
|
||||
},
|
||||
})
|
||||
if (r?.code !== 200) {
|
||||
throw new Error('上传失败')
|
||||
}
|
||||
form.setFieldValue('file_id', id)
|
||||
emit('change', 'result')
|
||||
}, null)
|
||||
|
||||
watch(error, (newVal) => {
|
||||
if (newVal) {
|
||||
toast.error('上传失败')
|
||||
}
|
||||
emit('change', 'input')
|
||||
})
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="text-xl font-normal">正在上传</div>
|
||||
<div class="flex flex-col items-center gap-4 md:flex-row md:justify-evenly">
|
||||
<div :class="cx('flex flex-row items-center gap-5', step !== 'hash' && 'opacity-50')">
|
||||
<div class="flex flex-col gap-0.5 items-center">
|
||||
<div class="text-xs opacity-50">1.计算hash</div>
|
||||
<div class="text-3xl font-light">
|
||||
<LucideLoaderCircle v-if="step === 'hash'" class="size-5 my-1 animate-spin" />
|
||||
<div v-else>{{ calcHashTime }}ms</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div :class="cx('flex flex-row items-center gap-5 min-w-32', step !== 'upload' && 'opacity-50')">
|
||||
<CircularProgress :size="80" :value="step !== 'upload' ? 0 : uploadProgress" />
|
||||
<div class="flex flex-col gap-0.5 items-center">
|
||||
<div class="text-xs opacity-50">2.上传文件</div>
|
||||
<div class="text-3xl font-light">{{ step !== 'upload' ? 0 : uploadProgress }}%</div>
|
||||
<div class="text-sm opacity-50" v-if="alreadyUploadSize">
|
||||
{{ filesize(alreadyUploadSize) }} / {{ filesize(data?.file?.size) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-row gap-2 items-baseline">
|
||||
<div class="text-md font-normal">详细信息</div>
|
||||
<div class="text-xs opacity-50" v-if="step === 'upload' && fileSliceUploadStatusList?.length > 0">
|
||||
当前正在上传分块{{ `${successCount}/${Math.ceil(data?.file?.size / chunkSize)}` }} 并发:3
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-row flex-wrap gap-1">
|
||||
<div
|
||||
v-for="i in fileSliceUploadStatusList"
|
||||
:class="
|
||||
cx(
|
||||
'rounded size-4 ',
|
||||
i.status === 'pending' && 'bg-white/90',
|
||||
i.status === 'uploading' && 'bg-yellow-500',
|
||||
i.status === 'success' && 'bg-green-500'
|
||||
)
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,61 @@
|
||||
<script setup lang="ts">
|
||||
import getFileSize from '~/lib/getFileSize'
|
||||
import { clamp } from 'lodash-es'
|
||||
import FileUploadBlockProgressView from '@/components/FileUploadBlockProgressView.vue'
|
||||
import FileUploadHeatMapView from '@/components/FileUploadHeatMapView.vue'
|
||||
import type { SelectedFile, Uploadfile } from './types'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const props = defineProps<{
|
||||
uploadfiles: Uploadfile[]
|
||||
selectedFile: SelectedFile
|
||||
}>()
|
||||
const selectedUploadfile = computed(() => props.uploadfiles.find((item) => item.fileId === props.selectedFile))
|
||||
const selectedUploadfileChunk = computed(() => Object.values(selectedUploadfile.value?.uploadInfo?.chunks || {}))
|
||||
const selectedUploadfileViewMode = ref<'progress' | 'heatmap'>('progress')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="col-span-4 flex flex-col bg-white/80 rounded-xl p-3 gap-5" v-if="selectedFile">
|
||||
<div class="flex flex-row gap-2 items-center">
|
||||
<LucideInfo class="size-4" />
|
||||
{{ t('page.progress.file.uploadDetails') }}
|
||||
</div>
|
||||
<div class="grid grid-cols-3 text-sm gap-3">
|
||||
<div>
|
||||
{{ t('page.progress.file.chunk') }}: {{ selectedUploadfile?.uploadInfo?.chunkLength }} x
|
||||
{{ getFileSize(selectedUploadfile?.uploadInfo?.ChunkSize as number) }}
|
||||
</div>
|
||||
<div class="truncate col-span-2">Hash: {{ selectedUploadfile?.hash }}</div>
|
||||
<div>{{ t('page.progress.file.completed') }}: {{ selectedUploadfileChunk?.filter((r) => r.status === 'success')?.length || 0 }}</div>
|
||||
<div>{{ t('page.progress.file.discarded') }}: {{ selectedUploadfileChunk?.filter((r) => r.status === 'error')?.length || 0 }}</div>
|
||||
<div>
|
||||
{{ t('page.progress.file.pending') }}:
|
||||
{{ (selectedUploadfile?.uploadInfo?.chunkLength || 0) - (selectedUploadfileChunk?.length || 0) }}
|
||||
</div>
|
||||
<div class="col-span-3 flex flex-row justify-between items-center">
|
||||
<div class="text-md font-bold">
|
||||
{{ selectedUploadfileViewMode === 'progress' ? t('page.progress.file.chunkProgress') : t('page.progress.file.chunkHeatmap') }}
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
class="ml-auto text-xs"
|
||||
@click="selectedUploadfileViewMode = selectedUploadfileViewMode === 'progress' ? 'heatmap' : 'progress'"
|
||||
>
|
||||
<LucideArrowDownUp class="size-4" />
|
||||
{{ selectedUploadfileViewMode === 'progress' ? t('page.progress.file.heatmap') : t('page.progress.file.progressBar') }}
|
||||
</Button>
|
||||
</div>
|
||||
<div class="h-7 col-span-3 flex flex-row gap-2 items-center" v-if="selectedUploadfileViewMode === 'progress'">
|
||||
<div class="flex-1 h-full">
|
||||
<FileUploadBlockProgressView :data="selectedUploadfile?.uploadInfo" />
|
||||
</div>
|
||||
{{ clamp(((selectedUploadfileChunk?.length || 0) / (selectedUploadfile?.uploadInfo?.chunkLength || 0)) * 100, 0, 100)?.toFixed(2) }}%
|
||||
</div>
|
||||
<div v-if="selectedUploadfileViewMode === 'heatmap'" class="col-span-3 bg-black/5 rounded p-2">
|
||||
<FileUploadHeatMapView :size="12" :data="selectedUploadfile?.uploadInfo" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,18 @@
|
||||
<script setup lang="ts">
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-2 pt-3">
|
||||
<div class="text-xl font-bold">{{ t('page.progress.file.uploadSpeedInfo.title') }}</div>
|
||||
<div class="opacity-75">
|
||||
<i18n-t keypath="page.progress.file.uploadSpeedInfo.desc.base">
|
||||
<template #chunkNum>
|
||||
<b>{{ t('page.progress.file.uploadSpeedInfo.desc.chunkNum') }}</b>
|
||||
</template>
|
||||
<template #chunkSize>
|
||||
<b>{{ t('page.progress.file.uploadSpeedInfo.desc.chunkSize') }}</b>
|
||||
</template>
|
||||
</i18n-t>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,78 @@
|
||||
<script setup lang="ts">
|
||||
import type { Uploadfile } from './types'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { uploadfiles } = defineProps<{
|
||||
uploadfiles: Uploadfile[]
|
||||
}>()
|
||||
const totalTaskStatus = computed(() => {
|
||||
if (uploadfiles.some((r) => r.status === 'start')) {
|
||||
return 'start'
|
||||
}
|
||||
if (uploadfiles.some((r) => r.status === 'pause')) {
|
||||
return 'pause'
|
||||
}
|
||||
return 'disabled'
|
||||
})
|
||||
const totalUploadProgress = computed(() => {
|
||||
const successCount = uploadfiles.reduce((acc, curr) => {
|
||||
const { status, uploadInfo } = curr || {}
|
||||
if (status === 'finish') return acc
|
||||
const { chunks } = uploadInfo || {}
|
||||
return acc + Object.entries(chunks || {}).filter(([index, chunk]) => chunk.status === 'success').length
|
||||
}, 0)
|
||||
const totalCount = uploadfiles.reduce((acc, curr) => {
|
||||
const { status, uploadInfo } = curr || {}
|
||||
if (status === 'finish') return acc
|
||||
const { chunkLength } = uploadInfo || {}
|
||||
return acc + (chunkLength || 0)
|
||||
}, 0)
|
||||
return ((successCount || 0) / (totalCount || 0)) * 100
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="rounded-xl col-span-4 md:col-span-1 bg-white/80 h-32 md:h-auto md:aspect-square flex flex-col gap-2 relative overflow-hidden">
|
||||
<div class="absolute top-0 left-0 w-full h-full z-[0] flex flex-col justify-end">
|
||||
<div class="w-full bg-green-100 border-t border-green-500" :style="`height: ${totalUploadProgress || 0}%`"></div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 justify-between p-3 h-full relative z-[1]">
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="text-xs opacity-70">{{ t('page.progress.file.totalUploadProgress') }}</div>
|
||||
<div class="text-4xl font-bold">{{ (totalUploadProgress || 0).toFixed(1) }}%</div>
|
||||
</div>
|
||||
<div class="flex flex-row gap-2">
|
||||
<Button
|
||||
class="aspect-square hover:text-white p-0 bg-green-200 hover:bg-green-300 text-green-500"
|
||||
:disabled="['start', 'disabled'].includes(totalTaskStatus)"
|
||||
@click="
|
||||
() => {
|
||||
uploadfiles.forEach((r) => {
|
||||
r.status = 'start'
|
||||
})
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucidePlay class="size-1/2" />
|
||||
</Button>
|
||||
<Button
|
||||
class="aspect-square hover:text-white p-0 bg-orange-200 hover:bg-orange-300 text-orange-500"
|
||||
:disabled="['pause', 'disabled'].includes(totalTaskStatus)"
|
||||
@click="
|
||||
() => {
|
||||
uploadfiles.forEach((r) => {
|
||||
r.status = 'pause'
|
||||
})
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideSquare class="size-1/2" />
|
||||
</Button>
|
||||
<!-- <Button class="aspect-square bg-blue-200 hover:bg-blue-300 text-blue-500 hover:text-white p-0">
|
||||
<LucideSettings class="size-1/2" />
|
||||
</Button> -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,60 @@
|
||||
<script setup lang="ts">
|
||||
import dayjs from 'dayjs'
|
||||
import { motion } from 'motion-v'
|
||||
import getFileSize from '~/lib/getFileSize'
|
||||
import showDrawer from '~/lib/showDrawer'
|
||||
import FileUploadSpeedInfoView from './FileUploadSpeedInfoView.vue'
|
||||
import { clamp } from 'lodash-es'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const props = defineProps<{
|
||||
speedChartData: Record<string, { fileId: string; index: number; value: number }[]>
|
||||
}>()
|
||||
const speedChartList = ref<{ timestamp: number; value: number }[]>([])
|
||||
useIntervalFn(() => {
|
||||
speedChartList.value.push({
|
||||
timestamp: dayjs().unix() - 1,
|
||||
value: props.speedChartData[dayjs().unix() - 1]?.reduce((acc, curr) => acc + curr.value, 0) ?? 0,
|
||||
})
|
||||
if (speedChartList.value.length > 60) {
|
||||
speedChartList.value.shift()
|
||||
}
|
||||
}, 1000)
|
||||
|
||||
const handleShowSpeedInfo = () => {
|
||||
showDrawer({
|
||||
render: ({ hide }) => h(FileUploadSpeedInfoView, { hide }),
|
||||
})
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="rounded-xl p-3 bg-white/80 flex flex-col gap-2 col-span-4 md:col-span-3 h-32 md:h-auto">
|
||||
<div class="flex flex-col gap-1">
|
||||
<div @click="handleShowSpeedInfo" class="flex flex-row gap-1 items-center text-xs opacity-70">
|
||||
{{ t('page.progress.file.totalUploadProgress') }}
|
||||
<LucideInfo class="size-3" />
|
||||
</div>
|
||||
<div class="text-2xl font-bold">
|
||||
{{ `${getFileSize(speedChartData[dayjs().unix() - 1]?.reduce((acc, curr) => acc + curr.value, 0) ?? 0) ?? 0}/s` }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-1 relative overflow-hidden flex flex-row gap-0.5 justify-end items-end">
|
||||
<motion.div
|
||||
class="w-2 shrink-0 bg-primary relative"
|
||||
:style="{
|
||||
height: `${clamp((i.value / Math.max(...(speedChartList?.map((r) => r.value) || [1]))) * 100, 1, 100)}%`,
|
||||
}"
|
||||
:layoutId="i.timestamp"
|
||||
v-for="i in speedChartList"
|
||||
:key="i.timestamp"
|
||||
:initial="{ x: 10, opacity: 0 }"
|
||||
:animate="{ x: 0, opacity: 1 }"
|
||||
:transition="{ duration: 1 }"
|
||||
>
|
||||
</motion.div>
|
||||
<!-- <BarChart class="h-full" :data="data" index="time" :categories="['value']" :showTooltip="false"
|
||||
:showLegend="false" :showXAxis="false" :showYAxis="false" :showGrid="false" :groupMaxWidth="10" /> -->
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
400
front/components/Home/File/FileUploadProgressView/index.vue
Normal file
@@ -0,0 +1,400 @@
|
||||
<script setup lang="ts">
|
||||
import { LucideSquare, LucideInfo, LucideFolders, LucideArrowUpFromLine, LucideCircleX, LucideCheckCircle, LucideLoaderCircle } from 'lucide-vue-next'
|
||||
import Button from '@/components/ui/button/Button.vue'
|
||||
|
||||
import getFileSize from '~/lib/getFileSize'
|
||||
import { cx } from 'class-variance-authority'
|
||||
import asyncWorker from '@/lib/asyncWorker'
|
||||
import calcFileHashWorker from '@/lib/calcFileHashWorker?worker'
|
||||
import { clamp, get, isEmpty, isNumber, sample, shuffle, throttle, times } from 'lodash-es'
|
||||
import { nanoid } from 'nanoid'
|
||||
import { toast } from 'vue-sonner'
|
||||
import dayjs from 'dayjs'
|
||||
import showDrawer from '~/lib/showDrawer'
|
||||
import FileUploadTotalSpeedView from './FileUploadTotalSpeedView.vue'
|
||||
import FileUploadTotalProgressControlView from './FileUploadTotalProgressControlView.vue'
|
||||
import FileUploadSpeedInfoView from './FileUploadSpeedInfoView.vue'
|
||||
import getFileChunk from '~/lib/getFileChunk'
|
||||
import type { FileHandleKey } from '~/components/Preprocessing/types'
|
||||
import asyncWait from '@/lib/asyncWait'
|
||||
import axios from 'axios'
|
||||
import type { SelectedFile, Uploadfile } from './types'
|
||||
import FileUploadDetailView from './FileUploadDetailView.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
data: { file: File[]; config: Record<string, any>; handle_type: FileHandleKey }
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
(e: 'change', key: string): void
|
||||
}>()
|
||||
const form = useFormContext()
|
||||
const { t } = useI18n()
|
||||
|
||||
const selectedFile = ref<SelectedFile>(null)
|
||||
const uploadfiles = ref<Uploadfile[]>([])
|
||||
|
||||
const procressTaskList = ref<Map<string, any>>(new Map())
|
||||
const activeTaskList = computed(() => uploadfiles.value.filter((r) => r.queue.length > 0 && r.status === 'start'))
|
||||
const activeTaskAllQueue = computed(() => activeTaskList.value.flatMap((r) => r.queue))
|
||||
const batchNum = ref(3)
|
||||
|
||||
const speedChartData = ref<Record<number, { fileId: string; index: number; value: number }[]>>({})
|
||||
|
||||
onMounted(() => {
|
||||
props.data.file.forEach((file) => {
|
||||
uploadfiles.value.push({
|
||||
fileId: `${file.name}_${file.size}`,
|
||||
file,
|
||||
status: 'start',
|
||||
procressType: 'hash',
|
||||
queue: [
|
||||
{ taskType: 'hash', queueType: 'sync', taskId: nanoid() },
|
||||
{ taskType: 'create', queueType: 'sync', taskId: nanoid() },
|
||||
{ taskType: 'chunk', queueType: 'sync', taskId: nanoid() },
|
||||
],
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
const { error, execute, isLoading } = useAsyncState(
|
||||
async () => {
|
||||
while (activeTaskAllQueue.value.length > 0) {
|
||||
const taskList = uploadfiles?.value?.filter((r) => r.queue.length > 0 && r.status === 'start')
|
||||
await asyncWait(10) // 让出主线程,防止空转导致ui卡死
|
||||
await Promise.all(
|
||||
times(batchNum.value, async (i: number) => {
|
||||
const file = sample(taskList)
|
||||
const { fileId, queue } = file || {}
|
||||
if (!fileId) return
|
||||
const task = get(queue, '0')
|
||||
if (!task) return
|
||||
const { taskId, index, queueType, taskType, retry } = task || {}
|
||||
if (procressTaskList.value.has(taskId)) return
|
||||
procressTaskList.value.set(taskId, task)
|
||||
|
||||
const uploadFileIndex = uploadfiles.value.findIndex((r) => r.fileId === file?.fileId)
|
||||
|
||||
if (queueType === 'async') {
|
||||
if (!!retry && retry >= 3) {
|
||||
toast.error(t('page.progress.file.uploadError'), {
|
||||
description: t('page.progress.file.chunkUploadFailed', [file?.file?.name, index]),
|
||||
})
|
||||
uploadfiles.value[uploadFileIndex]!.status = 'error'
|
||||
return
|
||||
}
|
||||
uploadfiles.value[uploadFileIndex]?.queue.shift()
|
||||
}
|
||||
// console.log('[start]', taskType, taskId, queueType)
|
||||
try {
|
||||
if (taskType === 'hash') {
|
||||
await handleHash(fileId)
|
||||
}
|
||||
if (taskType === 'create') {
|
||||
await handleCreate(fileId)
|
||||
}
|
||||
if (taskType === 'chunk') {
|
||||
await handleChunk(fileId)
|
||||
}
|
||||
if (taskType === 'upload' && isNumber(index)) {
|
||||
await handleUpload(fileId, index)
|
||||
}
|
||||
if (taskType === 'finish') {
|
||||
await handleFinish(fileId)
|
||||
}
|
||||
// console.log('[finish]', taskType, taskId)
|
||||
if (queueType === 'sync') {
|
||||
uploadfiles.value[uploadFileIndex]?.queue.shift()
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('error', error)
|
||||
// todo 重新加入队列
|
||||
if (queueType === 'async') {
|
||||
uploadfiles.value[uploadFileIndex]?.queue.push({ ...task, retry: (task?.retry || 0) + 1 })
|
||||
toast.warning(t('page.progress.file.uploadError'), {
|
||||
description: t('page.progress.file.chunkUploadRetry', [file?.file?.name, index]),
|
||||
})
|
||||
}
|
||||
if (queueType === 'sync') {
|
||||
uploadfiles.value[uploadFileIndex]!.status = 'error'
|
||||
toast.error(t('page.progress.file.uploadError'), {
|
||||
description: t('page.progress.file.fileUploadFailed', [file?.file?.name]),
|
||||
})
|
||||
}
|
||||
} finally {
|
||||
procressTaskList.value.delete(taskId)
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
},
|
||||
null,
|
||||
{ immediate: false }
|
||||
)
|
||||
|
||||
watchEffect(async () => {
|
||||
if (activeTaskAllQueue.value.length > 0 && !isLoading.value) {
|
||||
execute()
|
||||
}
|
||||
})
|
||||
|
||||
const handleHash = async (fileId: string) => {
|
||||
const uploadfile = uploadfiles.value.find((item) => item.fileId === fileId)
|
||||
if (!uploadfile?.file) return
|
||||
uploadfile.procressType = 'hash'
|
||||
const res = await asyncWorker(calcFileHashWorker, { data: { file: uploadfile.file } })
|
||||
const { hash } = res?.data || {}
|
||||
uploadfile.hash = hash
|
||||
}
|
||||
|
||||
const handleCreate = async (fileId: string) => {
|
||||
const uploadfile = uploadfiles.value.find((item) => item.fileId === fileId)
|
||||
if (!uploadfile?.file) return
|
||||
const { hash, file } = uploadfile || {}
|
||||
if (!hash) return
|
||||
uploadfile.procressType = 'create'
|
||||
const { size, type = 'application/octet-stream' } = file || {}
|
||||
const createData = await $fetch<{
|
||||
data: {
|
||||
id: string
|
||||
type: 'init' | 'already'
|
||||
chunk_size: number
|
||||
chunks: number[]
|
||||
}
|
||||
}>('/api/file/create', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
size,
|
||||
mime_type: type || 'application/octet-stream',
|
||||
hash,
|
||||
},
|
||||
})
|
||||
const { id, chunk_size, type: createType, chunks = [] } = createData?.data || {}
|
||||
uploadfile.id = id
|
||||
uploadfile.uploadInfo = {
|
||||
chunks: Object.fromEntries(chunks.map((index: number) => [index - 1, { status: 'success', createdAt: dayjs().unix() }])),
|
||||
chunkLength: Math.ceil(size / chunk_size),
|
||||
ChunkSize: chunk_size,
|
||||
}
|
||||
if (createType !== 'init') {
|
||||
// 文件存在
|
||||
uploadfile.status = 'finish'
|
||||
uploadfile.procressType = 'finish'
|
||||
uploadfile.queue = []
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const handleChunk = async (fileId: string) => {
|
||||
const uploadfile = uploadfiles.value.find((item) => item.fileId === fileId)
|
||||
if (!uploadfile?.file) return
|
||||
const { chunkLength } = uploadfile.uploadInfo || {}
|
||||
if (!chunkLength) return
|
||||
|
||||
uploadfile.procressType = 'upload'
|
||||
const tasks = shuffle(
|
||||
times(chunkLength, (i: number) => ({ taskType: 'upload' as const, queueType: 'async' as const, taskId: nanoid(), index: i }))
|
||||
)
|
||||
uploadfile.queue.push(...tasks)
|
||||
}
|
||||
|
||||
const handleUpload = async (fileId: string, index: number) => {
|
||||
const uploadfile = uploadfiles.value.find((item) => item.fileId === fileId)
|
||||
if (!uploadfile?.file) return
|
||||
const { id, uploadInfo } = uploadfile || {}
|
||||
const { chunkLength, ChunkSize } = uploadInfo || {}
|
||||
if (!ChunkSize || !id) return
|
||||
|
||||
if (uploadfile.procressType !== 'upload') uploadfile.procressType = 'upload'
|
||||
let chunkInfo = uploadfile.uploadInfo?.chunks?.[index]
|
||||
if (!chunkInfo) {
|
||||
uploadfile.uploadInfo!.chunks[index] = {
|
||||
status: 'processing',
|
||||
createdAt: dayjs().unix(),
|
||||
}
|
||||
}
|
||||
|
||||
const chunk = await getFileChunk(uploadfile.file, index * ChunkSize, ChunkSize)
|
||||
const formData = new FormData()
|
||||
formData.append('file', new Blob([chunk]))
|
||||
formData.append('index', (index + 1).toString())
|
||||
formData.append('id', id)
|
||||
const { data: res } = await axios.post('/api/file/slice', formData, {
|
||||
onUploadProgress: throttle((progressEvent) => {
|
||||
const { rate } = progressEvent || {}
|
||||
const timestamp = dayjs().unix()
|
||||
speedChartData.value[timestamp] = [...(speedChartData.value[timestamp] || []), { fileId, index, value: rate || 0 }]
|
||||
}, 1000),
|
||||
})
|
||||
const { code } = res || {}
|
||||
if (code !== 200) {
|
||||
throw new Error(t('page.progress.file.uploadFailed'))
|
||||
}
|
||||
uploadfile.uploadInfo!.chunks![index]!.status = 'success'
|
||||
if (Object.entries(uploadfile.uploadInfo!.chunks || {}).filter(([index, chunk]) => chunk.status === 'success').length === chunkLength) {
|
||||
uploadfile.queue.push({ taskType: 'finish', queueType: 'sync', taskId: nanoid() })
|
||||
}
|
||||
}
|
||||
|
||||
const handleFinish = async (fileId: string) => {
|
||||
const uploadfile = uploadfiles.value.find((item) => item.fileId === fileId)
|
||||
if (!uploadfile?.file) return
|
||||
uploadfile.procressType = 'finish'
|
||||
const { id } = uploadfile || {}
|
||||
const res = await $fetch<{
|
||||
code: number
|
||||
}>('/api/file/finish', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id,
|
||||
},
|
||||
})
|
||||
if (res?.code !== 200) {
|
||||
throw new Error(t('page.progress.file.uploadFailed'))
|
||||
}
|
||||
uploadfile.status = 'finish'
|
||||
}
|
||||
|
||||
watchEffect(() => {
|
||||
if (!isEmpty(uploadfiles.value) && uploadfiles.value.every((r) => r.status === 'finish')) {
|
||||
// console.log('change', uploadfiles.value)
|
||||
form.setFieldValue(
|
||||
'files',
|
||||
uploadfiles.value.map((item) => {
|
||||
const { id, file } = item || {}
|
||||
return {
|
||||
id,
|
||||
file,
|
||||
}
|
||||
})
|
||||
)
|
||||
emit('change', 'result')
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
uploadfiles.value = []
|
||||
})
|
||||
|
||||
const handleShowSpeedInfo = () => {
|
||||
showDrawer({
|
||||
render: ({ hide }) => h(FileUploadSpeedInfoView, { hide }),
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<BaseCard class="grid grid-cols-4 gap-5">
|
||||
<FileUploadTotalSpeedView :speedChartData="speedChartData" />
|
||||
<FileUploadTotalProgressControlView :uploadfiles="uploadfiles" />
|
||||
<div class="col-span-4 flex flex-col bg-white/80 rounded-xl p-3 text-md gap-5">
|
||||
<div class="flex flex-row gap-2 items-center">
|
||||
<LucideFolders class="size-4" />
|
||||
{{ t('page.progress.file.fileList') }}
|
||||
</div>
|
||||
<div class="flex flex-col -mx-3 text-sm">
|
||||
<div class="grid grid-cols-[2fr_6rem_6rem] md:grid-cols-[2fr_6rem_6rem_4fr] gap-2 border-b border-black/20 pb-2 px-3">
|
||||
<div>{{ t('page.progress.file.fileName') }}</div>
|
||||
<div>{{ t('page.progress.file.fileSize') }}</div>
|
||||
<div @click="handleShowSpeedInfo" class="flex flex-row gap-1 items-center">
|
||||
{{ t('page.progress.file.uploadSpeed') }}
|
||||
<LucideInfo class="size-3" />
|
||||
</div>
|
||||
<div class="hidden md:block">{{ t('page.progress.file.progress') }}</div>
|
||||
</div>
|
||||
<div
|
||||
:class="
|
||||
cx(
|
||||
'grid grid-cols-[2fr_6rem_6rem] md:grid-cols-[2fr_6rem_6rem_4fr] gap-2 py-2 border-b border-black/20 items-center hover:bg-primary/30 px-3 cursor-pointer',
|
||||
selectedFile === item?.fileId && 'bg-primary text-white hover:bg-primary!'
|
||||
)
|
||||
"
|
||||
v-for="(item, index) in uploadfiles"
|
||||
@click="
|
||||
() => {
|
||||
if (selectedFile === item?.fileId) {
|
||||
selectedFile = null
|
||||
} else {
|
||||
selectedFile = item?.fileId
|
||||
}
|
||||
}
|
||||
"
|
||||
>
|
||||
<div class="flex flex-row gap-2 items-center grow md:grow-0 overflow-hidden">
|
||||
<Button
|
||||
class="size-8 p-0 hover:bg-white/50"
|
||||
variant="ghost"
|
||||
:disabled="['finish']?.includes(item?.procressType)"
|
||||
@click="
|
||||
(e: Event) => {
|
||||
e.stopPropagation()
|
||||
if (item?.status === 'start') {
|
||||
uploadfiles[index]!.status = 'pause'
|
||||
} else {
|
||||
uploadfiles[index]!.status = 'start'
|
||||
}
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideArrowUpFromLine class="size-4 text-green-500" v-if="item?.status === 'start'" />
|
||||
<LucideSquare class="size-4 text-gray-500" v-if="item?.status === 'pause'" />
|
||||
<LucideCircleX class="size-4 text-red-500" v-if="item?.status === 'error'" />
|
||||
<LucideCheckCircle class="size-4 text-green-500" v-if="item?.status === 'finish'" />
|
||||
</Button>
|
||||
<div class="truncate">{{ item?.file?.name }}</div>
|
||||
</div>
|
||||
<div>{{ getFileSize(item?.file?.size) }}</div>
|
||||
<div>
|
||||
<template v-if="item?.status === 'start' && item?.procressType === 'upload'">
|
||||
{{
|
||||
`${getFileSize(
|
||||
Object.entries(speedChartData)
|
||||
?.filter(([key, value]) => value.some((r) => r.fileId === item?.fileId) && dayjs().unix() - 1 === Number(key))
|
||||
?.reduce((acc, curr) => acc + curr[1]?.reduce((acc, curr) => acc + curr.value, 0), 0) ?? 0
|
||||
)} /s`
|
||||
}}
|
||||
</template>
|
||||
</div>
|
||||
<div
|
||||
class="flex flex-row gap-2 items-center col-span-3 md:col-span-1"
|
||||
v-if="['hash', 'create', 'chunk']?.includes(item?.procressType)"
|
||||
>
|
||||
<LucideLoaderCircle class="size-4 animate-spin" />
|
||||
<div>{{ t(`page.progress.file.processing.${item?.procressType}`) }}</div>
|
||||
</div>
|
||||
<div class="flex flex-row gap-2 items-center col-span-3 md:col-span-1" v-if="item?.procressType === 'finish'">
|
||||
{{ item?.status === 'finish' ? t('page.progress.file.instantUploadSuccess') : null }}
|
||||
{{ item?.status === 'error' ? t('page.progress.file.uploadFailedRetry') : null }}
|
||||
</div>
|
||||
<div class="flex flex-row gap-2 items-center col-span-3 md:col-span-1" v-if="item?.procressType === 'upload'">
|
||||
<div class="rounded-full bg-white/50 w-full h-2 overflow-hidden border border-white">
|
||||
<div
|
||||
class="h-full bg-primary"
|
||||
:style="`width: ${clamp(
|
||||
((Object.entries(item?.uploadInfo?.chunks || {})?.filter(([index, chunk]) => chunk.status === 'success')
|
||||
?.length || 0) /
|
||||
(item?.uploadInfo?.chunkLength || 0)) *
|
||||
100,
|
||||
0,
|
||||
100
|
||||
)}%`"
|
||||
></div>
|
||||
</div>
|
||||
<div>
|
||||
{{
|
||||
clamp(
|
||||
((Object.entries(item?.uploadInfo?.chunks || {})?.filter(([index, chunk]) => chunk.status === 'success')
|
||||
?.length || 0) /
|
||||
(item?.uploadInfo?.chunkLength || 0)) *
|
||||
100,
|
||||
0,
|
||||
100
|
||||
)?.toFixed(2)
|
||||
}}%
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<FileUploadDetailView :uploadfiles="uploadfiles" :selectedFile="selectedFile" />
|
||||
</BaseCard>
|
||||
</template>
|
||||
24
front/components/Home/File/FileUploadProgressView/types.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
type Uploadfile = {
|
||||
fileId: string
|
||||
id?: string // 后端文件id
|
||||
file: File
|
||||
status: 'start' | 'pause' | 'finish' | 'error'
|
||||
hash?: string
|
||||
procressType: 'hash' | 'create' | 'upload' | 'finish'
|
||||
uploadInfo?: {
|
||||
chunks: Record<number, { status: 'success' | 'error' | 'processing'; createdAt: number }>
|
||||
chunkLength: number
|
||||
ChunkSize: number
|
||||
}
|
||||
queue: {
|
||||
taskId: string
|
||||
taskType: 'hash' | 'create' | 'chunk' | 'upload' | 'finish'
|
||||
queueType: 'sync' | 'async' // sync任务禁止并发
|
||||
index?: number
|
||||
retry?: number
|
||||
}[]
|
||||
}
|
||||
|
||||
type SelectedFile = string | null
|
||||
|
||||
export type { Uploadfile, SelectedFile }
|
||||
@@ -14,19 +14,26 @@ const renderComponent = computed(() => {
|
||||
return textStepList.find((item) => item.key === step.value)?.component
|
||||
})
|
||||
const formRef = ref<InstanceType<typeof VeeForm>>()
|
||||
watch(() => step.value, (newVal) => {
|
||||
if (newVal === 'input') {
|
||||
formRef.value?.form?.resetForm()
|
||||
// formRef.value?.form?.setValues({ file: null })
|
||||
watch(
|
||||
() => step.value,
|
||||
(newVal) => {
|
||||
if (newVal === 'input') {
|
||||
formRef.value?.form?.resetForm()
|
||||
// formRef.value?.form?.setValues({ file: null })
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
</script>
|
||||
<template>
|
||||
<VeeForm ref="formRef" v-slot="{ values }" :keepValues="true">
|
||||
<div class="rounded-xl p-5 bg-white/50 backdrop-blur-xl w-full lg:w-200">
|
||||
<component :is="renderComponent" :data="values" @change="(key: string) => {
|
||||
step = key
|
||||
}" />
|
||||
</div>
|
||||
<component
|
||||
:is="renderComponent"
|
||||
:data="values"
|
||||
@change="
|
||||
(key: string) => {
|
||||
step = key
|
||||
}
|
||||
"
|
||||
/>
|
||||
</VeeForm>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
@@ -1,74 +1,71 @@
|
||||
<script lang="ts" setup>
|
||||
import MarkdownInputField from "@/components/Field/MarkdownInputField.vue";
|
||||
import FormButton from "@/components/Field/FormButton.vue";
|
||||
import Button from "@/components/ui/button/Button.vue";
|
||||
import showDrawer from "@/lib/showDrawer";
|
||||
import { h } from "vue";
|
||||
import TextShareDrawer from "@/components/Drawer/TextShareDrawer.vue";
|
||||
import { cx } from "class-variance-authority";
|
||||
import PickupShareBtn from "@/components/PickupShareBtn.vue";
|
||||
const form = useFormContext();
|
||||
const { t } = useI18n();
|
||||
import MarkdownInputField from '@/components/Field/MarkdownInputField.vue'
|
||||
import FormButton from '@/components/Field/FormButton.vue'
|
||||
import Button from '@/components/ui/button/Button.vue'
|
||||
import showDrawer from '@/lib/showDrawer'
|
||||
import { h } from 'vue'
|
||||
import TextShareDrawer from '@/components/Drawer/TextShareDrawer.vue'
|
||||
import { cx } from 'class-variance-authority'
|
||||
import PickupShareBtn from '@/components/PickupShareBtn.vue'
|
||||
const form = useFormContext()
|
||||
const { t } = useI18n()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "change", key: string): void;
|
||||
}>();
|
||||
(e: 'change', key: string): void
|
||||
}>()
|
||||
|
||||
const handleTextShare = ({ type, config }: { type: string; config: any }) => {
|
||||
form?.setFieldValue("handle_type", type);
|
||||
form?.setFieldValue("config", config);
|
||||
emit("change", "result");
|
||||
};
|
||||
form?.setFieldValue('handle_type', type)
|
||||
form?.setFieldValue('config', config)
|
||||
emit('change', 'result')
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="gap-5 flex flex-col">
|
||||
<div class="text-xl font-normal">{{ t("text.uploadText") }}</div>
|
||||
<div class="relative">
|
||||
<MarkdownInputField
|
||||
name="text"
|
||||
:placeholder="t('text.uploadTextPlaceholder')"
|
||||
class="max-h-[50vh] min-h-40 overflow-y-auto max-w-full [&>*]:pr-10"
|
||||
rules="required"
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
:class="
|
||||
cx(
|
||||
'absolute right-2 top-2 hover:bg-black/10 transition-all duration-300',
|
||||
form?.values.text?.length > 0
|
||||
? 'opacity-100'
|
||||
: 'opacity-0 pointer-events-none',
|
||||
)
|
||||
"
|
||||
@click="
|
||||
() => {
|
||||
form?.setValues({ text: '' });
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideX />
|
||||
</Button>
|
||||
</div>
|
||||
<div class="flex flex-row gap-3">
|
||||
<FormButton
|
||||
@click="
|
||||
async (form) => {
|
||||
const { text } = form?.values || {};
|
||||
showDrawer({
|
||||
render: ({ hide }) =>
|
||||
h(TextShareDrawer, {
|
||||
hide,
|
||||
text,
|
||||
onTextHandle: handleTextShare,
|
||||
}),
|
||||
});
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideShare class="size-4" />{{ t("btn.submit") }}
|
||||
</FormButton>
|
||||
<PickupShareBtn />
|
||||
</div>
|
||||
</div>
|
||||
<BaseCard class="gap-5 flex flex-col" :title="t('page.upload.text.uploadText')">
|
||||
<div class="relative">
|
||||
<MarkdownInputField
|
||||
name="text"
|
||||
:placeholder="t('page.upload.text.uploadTextPlaceholder')"
|
||||
class="max-h-[50vh] min-h-40 overflow-y-auto max-w-full *:pr-10 flex flex-col"
|
||||
rules="required"
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
:class="
|
||||
cx(
|
||||
'absolute right-2 top-2 hover:bg-black/10 transition-all duration-300',
|
||||
form?.values.text?.length > 0 ? 'opacity-100' : 'opacity-0 pointer-events-none'
|
||||
)
|
||||
"
|
||||
@click="
|
||||
() => {
|
||||
form?.setValues({ text: '' })
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideX />
|
||||
</Button>
|
||||
</div>
|
||||
<div class="flex flex-row gap-3">
|
||||
<FormButton
|
||||
@click="
|
||||
async (form) => {
|
||||
const { text } = form?.values || {}
|
||||
showDrawer({
|
||||
render: ({ hide }) =>
|
||||
h(TextShareDrawer, {
|
||||
hide,
|
||||
text,
|
||||
onTextHandle: handleTextShare,
|
||||
}),
|
||||
})
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideShare class="size-4" />{{ t('btn.submit') }}
|
||||
</FormButton>
|
||||
<PickupShareBtn />
|
||||
</div>
|
||||
</BaseCard>
|
||||
</template>
|
||||
|
||||
@@ -11,5 +11,13 @@ const renderHtml = computed(() => {
|
||||
})
|
||||
</script>
|
||||
<template>
|
||||
<div :class="cx('prose', props?.class)" v-html="renderHtml" />
|
||||
</template>
|
||||
<div
|
||||
:class="
|
||||
cx(
|
||||
'prose prose-sm [&>*]:outline-none prose-p:my-1 prose-headings:my-2 prose-pre:mb-0 prose-blockquote:border-black/50 selection:bg-primary/20 break-all',
|
||||
props?.class
|
||||
)
|
||||
"
|
||||
v-html="renderHtml"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
<script setup lang="ts">
|
||||
import AsyncButton from '@/components/ui/button/AsyncButton.vue';
|
||||
import showDrawer from '@/lib/showDrawer';
|
||||
import PickupShareDrawer from './Drawer/PickupShareDrawer.vue';
|
||||
import AsyncButton from '@/components/ui/button/AsyncButton.vue'
|
||||
import showDrawer from '@/lib/showDrawer'
|
||||
import PickupShareDrawer from './Drawer/PickupShareDrawer.vue'
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AsyncButton variant="outline" class="gap-2" @click="async()=>{
|
||||
showDrawer({ render: ({ hide }) => h(PickupShareDrawer, { hide }) })
|
||||
}">
|
||||
<AsyncButton
|
||||
variant="outline"
|
||||
class="gap-2"
|
||||
@click="
|
||||
async () => {
|
||||
showDrawer({ render: ({ hide }) => h(PickupShareDrawer, { hide }) })
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideArchive class="size-4" />
|
||||
取件
|
||||
{{ t('page.upload.pickup.btn') }}
|
||||
</AsyncButton>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
47
front/components/Pixi.vue
Normal file
@@ -0,0 +1,47 @@
|
||||
<script setup lang="ts">
|
||||
import { Application } from 'vue3-pixi'
|
||||
import { useElementSize, useDevicePixelRatio } from '@vueuse/core'
|
||||
|
||||
export interface PixiExpose {
|
||||
app: Application
|
||||
width: number
|
||||
height: number
|
||||
contentHeight: number
|
||||
ref: HTMLElement
|
||||
}
|
||||
|
||||
const containerRef = ref<HTMLElement>()
|
||||
const app = ref<Application>()
|
||||
const { width: windowWidth, height: windowHeight } = useWindowSize()
|
||||
const { width: containerWidth, height: containerHeight } = useElementSize(containerRef)
|
||||
const width = computed(() => Math.min(containerWidth.value, windowWidth.value))
|
||||
const contentHeight = ref(0)
|
||||
const height = computed(() => {
|
||||
if (!contentHeight.value) return Math.min(containerHeight.value, windowHeight.value)
|
||||
if (containerHeight.value > contentHeight.value) return contentHeight.value
|
||||
return contentHeight.value
|
||||
})
|
||||
const { pixelRatio } = useDevicePixelRatio()
|
||||
const resolution = computed(() => pixelRatio.value ?? 1)
|
||||
watchEffect(() => {
|
||||
if (app.value?.app?.renderer) {
|
||||
app.value?.app?.renderer?.resize(width.value, height.value)
|
||||
}
|
||||
})
|
||||
|
||||
defineExpose({
|
||||
app,
|
||||
width,
|
||||
height,
|
||||
contentHeight,
|
||||
ref: containerRef,
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="containerRef" class="w-full h-full">
|
||||
<Application :width="width" :height="height" :resolution="resolution" ref="app" autoDensity antialias :backgroundAlpha="0">
|
||||
<slot :width="width" :height="height" />
|
||||
</Application>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,66 +1,100 @@
|
||||
<script setup lang="ts">
|
||||
import SwitchField from '../Field/SwitchField.vue';
|
||||
import InputField from '../Field/InputField.vue';
|
||||
import SelectField from '../Field/SelectField.vue';
|
||||
import FormButton from '../Field/FormButton.vue';
|
||||
import SwitchField from '../Field/SwitchField.vue'
|
||||
import InputField from '../Field/InputField.vue'
|
||||
import SelectField from '../Field/SelectField.vue'
|
||||
import FormButton from '../Field/FormButton.vue'
|
||||
import type { FileShareHandleProps } from './types'
|
||||
const { t } = useI18n()
|
||||
const props = defineProps<{
|
||||
hide: () => void
|
||||
file: File
|
||||
onFileHandle: ({ type, config }: { type: string, config: any }) => void
|
||||
file: File[]
|
||||
onFileHandle: (props: FileShareHandleProps) => void
|
||||
}>()
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<VeeForm v-slot="{ values, setFieldValue }" :initialValues="{ download_nums: 1, expire_time: 1440 }">
|
||||
<div class="flex flex-col gap-3">
|
||||
<h2 class="text-lg font-bold">分享选项</h2>
|
||||
<h2 class="text-lg font-bold">{{ t('page.shareOptions.file.title') }}</h2>
|
||||
<div class="flex flex-row items-center gap-2 text-sm">
|
||||
|
||||
<SelectField name="download_nums" label="下载次数" :options="[
|
||||
{ label: '1次下载', value: 1 },
|
||||
{ label: '2次下载', value: 2 },
|
||||
{ label: '3次下载', value: 3 },
|
||||
{ label: '5次下载', value: 5 },
|
||||
{ label: '10次下载', value: 10 },
|
||||
]" />
|
||||
或
|
||||
<SelectField name="expire_time" label="过期时间" :options="[
|
||||
{ label: '5分钟', value: 5 },
|
||||
{ label: '1小时', value: 60 },
|
||||
{ label: '1天', value: 1440 },
|
||||
{ label: '3天', value: 4320 },
|
||||
]" />
|
||||
后过期
|
||||
<SelectField
|
||||
name="download_nums"
|
||||
:label="t('page.shareOptions.file.downloadNums')"
|
||||
:options="[
|
||||
{ label: t('page.shareOptions.file.downloadOptions.xdownload', [1]), value: 1 },
|
||||
{ label: t('page.shareOptions.file.downloadOptions.xdownload', [2]), value: 2 },
|
||||
{ label: t('page.shareOptions.file.downloadOptions.xdownload', [3]), value: 3 },
|
||||
{ label: t('page.shareOptions.file.downloadOptions.xdownload', [5]), value: 5 },
|
||||
{ label: t('page.shareOptions.file.downloadOptions.xdownload', [10]), value: 10 },
|
||||
]"
|
||||
/>
|
||||
{{ t('page.shareOptions.file.or') }}
|
||||
<SelectField
|
||||
name="expire_time"
|
||||
:label="t('page.shareOptions.file.expireTime')"
|
||||
:options="[
|
||||
{ label: t('page.shareOptions.file.expireOptions.5min'), value: 5 },
|
||||
{ label: t('page.shareOptions.file.expireOptions.1hour'), value: 60 },
|
||||
{ label: t('page.shareOptions.file.expireOptions.1day'), value: 1440 },
|
||||
{ label: t('page.shareOptions.file.expireOptions.3days'), value: 4320 },
|
||||
]"
|
||||
/>
|
||||
{{ t('page.shareOptions.file.expireAfter') }}
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="flex flex-row gap-3 min-h-9">
|
||||
<SwitchField name="has_pickup_code" label="取件码" :rules="((value: boolean) => {
|
||||
if (!!value) {
|
||||
setFieldValue('has_password', false)
|
||||
}
|
||||
return true
|
||||
})" />
|
||||
<SwitchField
|
||||
name="has_pickup_code"
|
||||
:label="t('page.shareOptions.file.pickupCode')"
|
||||
:rules="
|
||||
(value: boolean) => {
|
||||
if (!!value) {
|
||||
setFieldValue('has_password', false)
|
||||
}
|
||||
return true
|
||||
}
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-row gap-3 min-h-9">
|
||||
<SwitchField name="has_password" label="密码保护" :rules="((value: boolean) => {
|
||||
if (!!value) {
|
||||
setFieldValue('has_pickup_code', false)
|
||||
}
|
||||
return true
|
||||
})" />
|
||||
<InputField v-if="!!values.has_password" name="password" placeholder="请输入密码" rules="required" />
|
||||
<SwitchField
|
||||
name="has_password"
|
||||
:label="t('page.shareOptions.file.passwordProtection')"
|
||||
:rules="
|
||||
(value: boolean) => {
|
||||
if (!!value) {
|
||||
setFieldValue('has_pickup_code', false)
|
||||
}
|
||||
return true
|
||||
}
|
||||
"
|
||||
/>
|
||||
<InputField
|
||||
v-if="!!values.has_password"
|
||||
name="password"
|
||||
:placeholder="t('page.shareOptions.file.passwordPlaceholder')"
|
||||
rules="required"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-row gap-3 min-h-9">
|
||||
<SwitchField name="has_notify" label="下载通知" />
|
||||
<InputField v-if="!!values.has_notify" name="notify_email" placeholder="请输入邮箱"
|
||||
rules="required" />
|
||||
<SwitchField name="has_notify" :label="t('page.shareOptions.file.downloadNotify')" />
|
||||
<InputField
|
||||
v-if="!!values.has_notify"
|
||||
name="notify_email"
|
||||
:placeholder="t('page.shareOptions.file.emailPlaceholder')"
|
||||
rules="required"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<FormButton @click="async (form) => {
|
||||
onFileHandle({ type: 'file-share', config: values })
|
||||
hide()
|
||||
}">提交</FormButton>
|
||||
<FormButton
|
||||
@click="
|
||||
async (form) => {
|
||||
onFileHandle({ type: 'file-share', config: values })
|
||||
hide()
|
||||
}
|
||||
"
|
||||
>{{ t('btn.submit') }}</FormButton
|
||||
>
|
||||
</div>
|
||||
</VeeForm>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
43
front/components/Preprocessing/ImageConvertHandle.vue
Normal file
@@ -0,0 +1,43 @@
|
||||
<script setup lang="ts">
|
||||
import SelectField from '../Field/SelectField.vue'
|
||||
import FormButton from '../Field/FormButton.vue'
|
||||
import type { FileShareHandleProps } from './types'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { t } = useI18n()
|
||||
const props = defineProps<{
|
||||
hide: () => void
|
||||
file: File[]
|
||||
onFileHandle: (props: FileShareHandleProps) => void
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<VeeForm v-slot="{ values }" :initialValues="{ target_ext: 'jpg' }">
|
||||
<div class="flex flex-col gap-3">
|
||||
<h2 class="text-lg font-bold">{{ t('page.shareOptions.imageConvert.title') }}</h2>
|
||||
<div class="flex flex-row gap-2 items-center">
|
||||
<Label>{{ t('page.shareOptions.imageConvert.targetFormat') }}</Label>
|
||||
<SelectField
|
||||
name="target_ext"
|
||||
:label="t('page.shareOptions.imageConvert.targetFormat')"
|
||||
:options="[
|
||||
{ label: 'JPG', value: 'jpg' },
|
||||
{ label: 'PNG', value: 'png' },
|
||||
{ label: 'WEBP', value: 'webp' },
|
||||
]"
|
||||
rules="required"
|
||||
/>
|
||||
</div>
|
||||
<FormButton
|
||||
@click="
|
||||
async (form) => {
|
||||
onFileHandle({ type: 'file-image-convert', config: values })
|
||||
hide()
|
||||
}
|
||||
"
|
||||
>{{ t('btn.submit') }}</FormButton
|
||||
>
|
||||
</div>
|
||||
</VeeForm>
|
||||
</template>
|
||||
@@ -1,65 +1,100 @@
|
||||
<script setup lang="ts">
|
||||
import SwitchField from '../Field/SwitchField.vue';
|
||||
import InputField from '../Field/InputField.vue';
|
||||
import SelectField from '../Field/SelectField.vue';
|
||||
import FormButton from '../Field/FormButton.vue';
|
||||
import SwitchField from '../Field/SwitchField.vue'
|
||||
import InputField from '../Field/InputField.vue'
|
||||
import SelectField from '../Field/SelectField.vue'
|
||||
import FormButton from '../Field/FormButton.vue'
|
||||
import type { TextShareHandleProps } from './types'
|
||||
const { t } = useI18n()
|
||||
const props = defineProps<{
|
||||
hide: () => void
|
||||
text: string
|
||||
onTextHandle: ({ type, config }: { type: string, config: any }) => void
|
||||
onTextHandle: (props: TextShareHandleProps) => void
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<VeeForm v-slot="{ values, setFieldValue }" :initialValues="{ download_nums: 1, expire_time: 1440 }">
|
||||
<div class="flex flex-col gap-3">
|
||||
<h2 class="text-lg font-bold">分享选项</h2>
|
||||
<h2 class="text-lg font-bold">{{ t('page.shareOptions.text.title') }}</h2>
|
||||
<div class="flex flex-row items-center gap-2 text-sm">
|
||||
|
||||
<SelectField name="download_nums" label="浏览次数" :options="[
|
||||
{ label: '1次浏览', value: 1 },
|
||||
{ label: '2次浏览', value: 2 },
|
||||
{ label: '3次浏览', value: 3 },
|
||||
{ label: '5次浏览', value: 5 },
|
||||
{ label: '10次浏览', value: 10 },
|
||||
]" />
|
||||
或
|
||||
<SelectField name="expire_time" label="过期时间" :options="[
|
||||
{ label: '5分钟', value: 5 },
|
||||
{ label: '1小时', value: 60 },
|
||||
{ label: '1天', value: 1440 },
|
||||
{ label: '3天', value: 4320 },
|
||||
]" />
|
||||
后过期
|
||||
<SelectField
|
||||
name="download_nums"
|
||||
:label="t('page.shareOptions.text.viewNums')"
|
||||
:options="[
|
||||
{ label: t('page.shareOptions.text.viewOptions.xview', [1]), value: 1 },
|
||||
{ label: t('page.shareOptions.text.viewOptions.xview', [2]), value: 2 },
|
||||
{ label: t('page.shareOptions.text.viewOptions.xview', [3]), value: 3 },
|
||||
{ label: t('page.shareOptions.text.viewOptions.xview', [5]), value: 5 },
|
||||
{ label: t('page.shareOptions.text.viewOptions.xview', [10]), value: 10 },
|
||||
]"
|
||||
/>
|
||||
{{ t('page.shareOptions.text.or') }}
|
||||
<SelectField
|
||||
name="expire_time"
|
||||
:label="t('page.shareOptions.text.expireTime')"
|
||||
:options="[
|
||||
{ label: t('page.shareOptions.text.expireOptions.5min'), value: 5 },
|
||||
{ label: t('page.shareOptions.text.expireOptions.1hour'), value: 60 },
|
||||
{ label: t('page.shareOptions.text.expireOptions.1day'), value: 1440 },
|
||||
{ label: t('page.shareOptions.text.expireOptions.3days'), value: 4320 },
|
||||
]"
|
||||
/>
|
||||
{{ t('page.shareOptions.text.expireAfter') }}
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="flex flex-row gap-3 min-h-9">
|
||||
<SwitchField name="has_pickup_code" label="取件码" :rules="((value: boolean) => {
|
||||
if (!!value) {
|
||||
setFieldValue('has_password', false)
|
||||
}
|
||||
return true
|
||||
})" />
|
||||
<SwitchField
|
||||
name="has_pickup_code"
|
||||
:label="t('page.shareOptions.text.pickupCode')"
|
||||
:rules="
|
||||
(value: boolean) => {
|
||||
if (!!value) {
|
||||
setFieldValue('has_password', false)
|
||||
}
|
||||
return true
|
||||
}
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-row gap-3 min-h-9">
|
||||
<SwitchField name="has_password" label="密码保护" :rules="((value: boolean) => {
|
||||
if (!!value) {
|
||||
setFieldValue('has_pickup_code', false)
|
||||
}
|
||||
return true
|
||||
})" />
|
||||
<InputField v-if="!!values.has_password" name="password" placeholder="请输入密码" rules="required" />
|
||||
<SwitchField
|
||||
name="has_password"
|
||||
:label="t('page.shareOptions.text.passwordProtection')"
|
||||
:rules="
|
||||
(value: boolean) => {
|
||||
if (!!value) {
|
||||
setFieldValue('has_pickup_code', false)
|
||||
}
|
||||
return true
|
||||
}
|
||||
"
|
||||
/>
|
||||
<InputField
|
||||
v-if="!!values.has_password"
|
||||
name="password"
|
||||
:placeholder="t('page.shareOptions.text.passwordPlaceholder')"
|
||||
rules="required"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-row gap-3 min-h-9">
|
||||
<SwitchField name="has_notify" label="已读通知" />
|
||||
<InputField v-if="!!values.has_notify" name="notify_email" placeholder="请输入邮箱"
|
||||
rules="required" />
|
||||
<SwitchField name="has_notify" :label="t('page.shareOptions.text.readNotify')" />
|
||||
<InputField
|
||||
v-if="!!values.has_notify"
|
||||
name="notify_email"
|
||||
:placeholder="t('page.shareOptions.text.emailPlaceholder')"
|
||||
rules="required"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<FormButton @click="async (form) => {
|
||||
onTextHandle({ type: 'text-share', config: values })
|
||||
hide()
|
||||
}">提交</FormButton>
|
||||
<FormButton
|
||||
@click="
|
||||
async (form) => {
|
||||
onTextHandle({ type: 'text-share', config: values })
|
||||
hide()
|
||||
}
|
||||
"
|
||||
>{{ t('btn.submit') }}</FormButton
|
||||
>
|
||||
</div>
|
||||
</VeeForm>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
5
front/components/Preprocessing/types.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export type FileHandleKey = 'file-share' | 'file-image-compress' | 'file-image-convert'
|
||||
export type FileShareHandleProps = { type: FileHandleKey; config: Record<string, any> }
|
||||
|
||||
export type TextHandleKey = 'text-share'
|
||||
export type TextShareHandleProps = { type: TextHandleKey; config: Record<string, any> }
|
||||
@@ -1,152 +1,199 @@
|
||||
<script setup lang="ts">
|
||||
import { Button } from "@/components/ui/button";
|
||||
import FilePreviewView from "@/components/FilePreviewView.vue";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useClipboard } from "@vueuse/core";
|
||||
import { toast } from "vue-sonner";
|
||||
import { useQuery } from "@tanstack/vue-query";
|
||||
import useMyAppShare from "@/composables/useMyAppShare";
|
||||
import useMyAppConfig from "@/composables/useMyAppConfig";
|
||||
import dayjs from "dayjs";
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
import "dayjs/locale/zh-cn"; // 导入中文语言包
|
||||
import showDrawer from "@/lib/showDrawer";
|
||||
import QrCoreDrawer from "@/components/Drawer/QrCoreDrawer.vue";
|
||||
dayjs.extend(relativeTime); // 扩展 relativeTime 插件
|
||||
dayjs.locale("zh-cn"); // 设置语言为中文
|
||||
import { Button } from '@/components/ui/button'
|
||||
import FilePreviewView from '@/components/FilePreviewView.vue'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { useClipboard } from '@vueuse/core'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { useQuery } from '@tanstack/vue-query'
|
||||
import useMyAppShare from '@/composables/useMyAppShare'
|
||||
import useMyAppConfig from '@/composables/useMyAppConfig'
|
||||
import dayjs from 'dayjs'
|
||||
import showDrawer from '@/lib/showDrawer'
|
||||
import QrCoreDrawer from '@/components/Drawer/QrCoreDrawer.vue'
|
||||
import { h } from 'vue'
|
||||
import { cx } from 'class-variance-authority'
|
||||
import type { handleFileComponentProps } from './types'
|
||||
|
||||
const props = defineProps<{
|
||||
data: { file: File; config: any; handle_type: string; file_id: string };
|
||||
}>();
|
||||
const props = defineProps<handleFileComponentProps>()
|
||||
const emit = defineEmits<{
|
||||
(e: "change", key: string): void;
|
||||
}>();
|
||||
const { createFileShare } = useMyAppShare();
|
||||
(e: 'change', key: string): void
|
||||
}>()
|
||||
const { t } = useI18n()
|
||||
const { createFileShare } = useMyAppShare()
|
||||
const { data } = useQuery({
|
||||
queryKey: ["create-share", props?.data?.file_id],
|
||||
queryFn: async () => {
|
||||
const { file_id, config, file } = props?.data || {};
|
||||
const { name } = file || {};
|
||||
const data = await createFileShare({
|
||||
file_id,
|
||||
config,
|
||||
file_name: name,
|
||||
});
|
||||
return data?.data;
|
||||
},
|
||||
});
|
||||
queryKey: ['create-share', ...props?.data?.files?.map((item) => item.id)],
|
||||
queryFn: async () => {
|
||||
const { files, config } = props?.data || {}
|
||||
const data = await createFileShare({
|
||||
files: files?.map((item) => {
|
||||
const { id, file } = item || {}
|
||||
return { id, name: file.name }
|
||||
}),
|
||||
config: config as any,
|
||||
})
|
||||
return data?.map((item) => item?.data)
|
||||
},
|
||||
})
|
||||
const selectedFile = ref<string | undefined>()
|
||||
const selectedFileShare = computed(() => {
|
||||
return data?.value?.find((item) => item?.id === selectedFile.value)
|
||||
})
|
||||
watchEffect(() => {
|
||||
if (data?.value && data?.value?.length === 1 && !!data?.value?.[0]?.id) {
|
||||
selectedFile.value = data.value[0].id
|
||||
}
|
||||
})
|
||||
|
||||
const appConfig = useMyAppConfig();
|
||||
const url = computed(() => {
|
||||
const { id } = data?.value || {};
|
||||
return `${appConfig?.value?.site_url}/s/${id}`;
|
||||
});
|
||||
watchEffect(() => {
|
||||
console.log('data', data?.value)
|
||||
})
|
||||
|
||||
const { copy } = useClipboard();
|
||||
const appConfig = useMyAppConfig()
|
||||
const getShareUrl = (id: string) => {
|
||||
return `${appConfig?.value?.site_url}/s/${id}`
|
||||
}
|
||||
|
||||
const { copy } = useClipboard()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-3">
|
||||
<h2 class="text-lg">上传成功</h2>
|
||||
<div class="flex flex-col gap-3 items-center">
|
||||
<div class="flex flex-col h-30 items-center">
|
||||
<FilePreviewView :value="props?.data?.file" />
|
||||
</div>
|
||||
<div
|
||||
class="flex flex-col md:flex-row gap-5 rounded-md p-5 bg-white/20 backdrop-blur-xl w-full"
|
||||
>
|
||||
<div class="flex flex-col gap-2 flex-1">
|
||||
<div class="text-sm font-semibold">信息</div>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1">
|
||||
<div class="text-xs font-semibold">下载次数</div>
|
||||
<div class="text-3xl font-light">{{ data?.download_nums }}</div>
|
||||
<BaseCard class="flex flex-col gap-3" :title="t('page.result.file.title')" :showBackButton="true">
|
||||
<div class="flex flex-col gap-3 items-center">
|
||||
<div v-if="data?.length === 1" class="flex flex-col h-30 items-center">
|
||||
<FilePreviewView :value="props?.data?.files?.[0]?.file as File" />
|
||||
</div>
|
||||
<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 * 1000).format("YYYY-MM-DD HH:mm:ss")
|
||||
}}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1"
|
||||
v-if="data?.pickup_code"
|
||||
>
|
||||
<div class="flex flex-row justify-between w-full items-center">
|
||||
<div class="text-xs font-semibold">提取码</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
class="bg-white/70 p-0 size-6"
|
||||
size="icon"
|
||||
@click="
|
||||
() => {
|
||||
copy(data?.pickup_code);
|
||||
toast.success('复制成功');
|
||||
}
|
||||
"
|
||||
<div v-else class="flex flex-col gap-2 w-full p-5 bg-white/20 backdrop-blur-xl rounded-md">
|
||||
<div class="text-sm font-semibold">{{ t('page.result.file.fileList') }}</div>
|
||||
<div
|
||||
v-for="file in data"
|
||||
:class="
|
||||
cx(
|
||||
'flex flex-row justify-between items-center gap-1 rounded-md p-2 border border-black/10 w-full cursor-pointer',
|
||||
selectedFile === file?.id && 'bg-primary text-white'
|
||||
)
|
||||
"
|
||||
@click="selectedFile = file?.id"
|
||||
>
|
||||
<LucideCopy class="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<div class="flex flex-row gap-2">
|
||||
<div v-for="s in data?.pickup_code" class="text-2xl font-light">
|
||||
{{ s }}
|
||||
<div class="flex flex-row items-center gap-2 flex-1 min-w-0">
|
||||
<FileIcon
|
||||
:file="props?.data?.files?.[data?.findIndex((i) => i?.id === file?.id) as number]?.file as File"
|
||||
:class="cx('!size-7 !rounded-md shrink-0', selectedFile === file?.id && '!bg-white/50')"
|
||||
/>
|
||||
<div class="text-sm flex-1 truncate">{{ file?.file_name }}</div>
|
||||
</div>
|
||||
<div class="flex flex-row items-center gap-2 shrink-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
:class="cx('bg-white/70', selectedFile === file?.id && '!bg-white/30 border-none hover:text-white/80')"
|
||||
size="icon"
|
||||
@click="
|
||||
() => {
|
||||
copy(getShareUrl(file?.id as string))
|
||||
toast.success(t('page.result.file.copySuccess'))
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideCopy />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
:class="cx('bg-white/70', selectedFile === file?.id && '!bg-white/30 border-none hover:text-white/80')"
|
||||
size="icon"
|
||||
@click="
|
||||
() => {
|
||||
showDrawer({
|
||||
render: ({ ...rest }) =>
|
||||
h(QrCoreDrawer, {
|
||||
...rest,
|
||||
data: getShareUrl(file?.id as string),
|
||||
}),
|
||||
})
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideQrCode />
|
||||
</Button>
|
||||
</div>
|
||||
</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>
|
||||
<div v-if="!!selectedFileShare" class="flex flex-col md:flex-row gap-5 rounded-md p-5 bg-white/20 backdrop-blur-xl w-full">
|
||||
<div class="flex flex-col gap-2 flex-1">
|
||||
<div class="text-sm font-semibold">{{ t('page.result.file.info') }}</div>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1">
|
||||
<div class="text-xs font-semibold">{{ t('page.result.file.downloadNums') }}</div>
|
||||
<div class="text-3xl font-light">{{ selectedFileShare?.download_nums }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1">
|
||||
<div class="text-xs font-semibold">{{ t('page.result.file.expireTime') }}</div>
|
||||
<div class="text-md font-light">
|
||||
{{ dayjs((selectedFileShare?.expire_at || 0) * 1000).format('YYYY-MM-DD HH:mm:ss') }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1" v-if="selectedFileShare?.pickup_code">
|
||||
<div class="flex flex-row justify-between w-full items-center">
|
||||
<div class="text-xs font-semibold">{{ t('page.result.file.pickupCode') }}</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
class="bg-white/70 p-0 size-6"
|
||||
size="icon"
|
||||
@click="
|
||||
() => {
|
||||
copy(selectedFileShare?.pickup_code as string)
|
||||
toast.success(t('page.result.file.copySuccess'))
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideCopy class="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<div class="flex flex-row gap-2">
|
||||
<div v-for="s in selectedFileShare?.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">{{ t('page.result.file.link') }}</div>
|
||||
<div class="flex flex-row gap-2">
|
||||
<Input :model-value="getShareUrl(selectedFileShare?.id as string)" class="bg-white/70" readonly />
|
||||
<Button
|
||||
variant="outline"
|
||||
class="bg-white/70"
|
||||
size="icon"
|
||||
@click="
|
||||
() => {
|
||||
copy(getShareUrl(selectedFileShare?.id as string))
|
||||
toast.success(t('page.result.file.copySuccess'))
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideCopy />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
class="bg-white/70"
|
||||
size="icon"
|
||||
@click="
|
||||
() => {
|
||||
showDrawer({
|
||||
render: ({ ...rest }) =>
|
||||
h(QrCoreDrawer, {
|
||||
...rest,
|
||||
data: url,
|
||||
}),
|
||||
});
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideQrCode />
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
class="bg-white/70"
|
||||
size="icon"
|
||||
@click="
|
||||
() => {
|
||||
showDrawer({
|
||||
render: ({ ...rest }) =>
|
||||
h(QrCoreDrawer, {
|
||||
...rest,
|
||||
data: getShareUrl(selectedFileShare?.id as string),
|
||||
}),
|
||||
})
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideQrCode />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
class="hover:bg-white/50 w-40"
|
||||
@click="
|
||||
() => {
|
||||
emit('change', 'input');
|
||||
}
|
||||
"
|
||||
>
|
||||
确定
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</BaseCard>
|
||||
</template>
|
||||
|
||||
@@ -1,66 +1,92 @@
|
||||
<script setup lang="ts">
|
||||
import { useQuery } from '@tanstack/vue-query'
|
||||
import { AsyncButton, Button } from '@/components/ui/button'
|
||||
import { useQueries, useQuery } from '@tanstack/vue-query'
|
||||
import { AsyncButton } from '@/components/ui/button'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { filesize } from 'filesize'
|
||||
import useMyAppShare from '@/composables/useMyAppShare'
|
||||
import { toast } from 'vue-sonner'
|
||||
import type { handleFileComponentProps } from './types'
|
||||
import { get } from 'lodash-es'
|
||||
|
||||
const { t } = useI18n()
|
||||
const emit = defineEmits<{
|
||||
(e: 'change', key: string): void
|
||||
}>()
|
||||
const props = defineProps<{
|
||||
data: { file: File; config: any; handle_type: string; file_id: string }
|
||||
}>()
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: ['create-image-compress', props?.data?.file_id],
|
||||
const props = defineProps<handleFileComponentProps>()
|
||||
const fileIds = computed(() => props?.data?.files?.map((item) => item.id))
|
||||
const { data: taskIds } = useQuery({
|
||||
queryKey: ['create-image-compress', fileIds.value],
|
||||
queryFn: async () => {
|
||||
const { file_id } = props?.data || {}
|
||||
const data = await $fetch<{
|
||||
code: number
|
||||
data: {
|
||||
id?: string
|
||||
}
|
||||
}>(`/api/image/compress`, {
|
||||
method: 'POST',
|
||||
body: {
|
||||
file_id,
|
||||
},
|
||||
})
|
||||
return data?.data
|
||||
return await Promise.all(
|
||||
props?.data?.files?.map(async (file) => {
|
||||
const { id } = file || {}
|
||||
if (!id) return
|
||||
const data = await $fetch<{
|
||||
code: number
|
||||
data: {
|
||||
id?: string
|
||||
}
|
||||
}>(`/api/task/image:compress`, {
|
||||
method: 'POST',
|
||||
body: {
|
||||
file_id: id,
|
||||
},
|
||||
})
|
||||
return data?.data?.id
|
||||
})
|
||||
)
|
||||
},
|
||||
staleTime: Infinity,
|
||||
enabled: !!fileIds.value && fileIds.value?.length > 0,
|
||||
})
|
||||
|
||||
const taskId = computed(() => data?.value?.id)
|
||||
|
||||
const { data: taskData, refetch } = useQuery({
|
||||
queryKey: ['image-compress-task', taskId],
|
||||
queryFn: async () => {
|
||||
const data = await $fetch<{
|
||||
code: number
|
||||
data: {
|
||||
result: {
|
||||
old_file: {
|
||||
id: string
|
||||
size: number
|
||||
}
|
||||
new_file: {
|
||||
id: string
|
||||
size: number
|
||||
}
|
||||
}[]
|
||||
status: 'success' | 'retry' | 'archived'
|
||||
err?: {
|
||||
message?: string
|
||||
retry?: number
|
||||
max_retry?: number
|
||||
const taskResults = useQueries({
|
||||
queries: computed(
|
||||
() =>
|
||||
taskIds?.value?.filter(Boolean).map((taskId) => {
|
||||
return {
|
||||
queryKey: ['task-image-compress', taskId],
|
||||
queryFn: async () => {
|
||||
const data = await $fetch<{
|
||||
code: number
|
||||
data: {
|
||||
result: {
|
||||
old_file: {
|
||||
id: string
|
||||
size: number
|
||||
}
|
||||
new_file: {
|
||||
id: string
|
||||
size: number
|
||||
}
|
||||
}[]
|
||||
status: 'success' | 'retry' | 'archived'
|
||||
err?: {
|
||||
message?: string
|
||||
retry?: number
|
||||
max_retry?: number
|
||||
}
|
||||
}
|
||||
}>(`/api/task/${taskId}`)
|
||||
return data?.data
|
||||
},
|
||||
enabled: !!taskId,
|
||||
}
|
||||
}) ?? []
|
||||
),
|
||||
})
|
||||
|
||||
const totalSize = computed(() => {
|
||||
return taskResults.value.reduce(
|
||||
(acc, item) => {
|
||||
const { new_file, old_file } = get(item, 'data.result.0') || {}
|
||||
return {
|
||||
oldSize: acc.oldSize + (old_file?.size ?? 0),
|
||||
newSize: acc.newSize + (new_file?.size ?? 0),
|
||||
}
|
||||
}>(`/api/image/compress/${taskId.value}`)
|
||||
return data?.data
|
||||
},
|
||||
enabled: !!taskId.value,
|
||||
},
|
||||
{ oldSize: 0, newSize: 0 }
|
||||
)
|
||||
})
|
||||
|
||||
const { downloadFileByShareId, createFileShare } = useMyAppShare()
|
||||
@@ -70,66 +96,98 @@ const { counter, pause } = useInterval(2000, { controls: true })
|
||||
watch(
|
||||
() => counter.value,
|
||||
() => {
|
||||
if (['success', 'archived'].includes(taskData.value?.status ?? '')) {
|
||||
pause()
|
||||
return
|
||||
}
|
||||
refetch()
|
||||
}
|
||||
)
|
||||
taskResults.value.forEach((item) => {
|
||||
if (['success', 'archived'].includes(item.data?.status ?? '')) return
|
||||
item.refetch()
|
||||
})
|
||||
|
||||
watch(
|
||||
() => taskData.value?.err?.retry,
|
||||
(newVal, oldVal) => {
|
||||
if (!oldVal || !newVal || !taskData.value?.err?.max_retry) {
|
||||
return
|
||||
}
|
||||
if (newVal <= taskData.value?.err?.max_retry) {
|
||||
toast.error(`处理错误: ${taskData.value?.err?.message}, 将再次重试`)
|
||||
if (taskResults.value.every((item) => ['success', 'archived'].includes(item.data?.status ?? ''))) {
|
||||
pause()
|
||||
}
|
||||
}
|
||||
)
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-3">
|
||||
<h2 class="text-lg">上传成功</h2>
|
||||
<div class="flex flex-col gap-1 items-center">
|
||||
<div class="flex flex-col h-30 items-center justify-center">
|
||||
<FilePreviewView :value="props?.data?.file" />
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="taskData?.status === 'success'" class="flex flex-col gap-2" v-for="item in taskData?.result">
|
||||
<div class="bg-white/80 p-2 rounded-md w-full flex flex-row items-center justify-between gap-2">
|
||||
<div class="flex flex-row gap-2 items-center max-w-2/3">
|
||||
<div class="flex flex-row items-center justify-center rounded-md bg-black/5 p-2">
|
||||
<LucideImage />
|
||||
</div>
|
||||
<div class="truncate w-auto">{{ props?.data?.file?.name }}</div>
|
||||
<div class="flex flex-row gap-2 items-center text-sm shrink-0">
|
||||
<span class="opacity-75">{{ filesize(item.new_file.size ?? 0) }}</span>
|
||||
<span class="bg-green-200 text-green-600 rounded-md px-1 py-0.5 flex flex-row gap-1 items-center text-xs">
|
||||
<LucideChevronDown class="size-4" />
|
||||
{{ ((1 - item.new_file.size / item.old_file.size) * 100).toFixed(2) }}%
|
||||
</span>
|
||||
<BaseCard class="flex flex-col gap-3" :title="t('page.result.imageCompress.title')" :showBackButton="true">
|
||||
<div class="flex flex-row gap-3">
|
||||
<div class="rounded-xl flex flex-col bg-white/70 px-3 py-2 gap-1 basis-2/3">
|
||||
<div class="text-sm font-semibold">{{ t('page.result.imageCompress.totalSize') }}</div>
|
||||
<div class="text-2xl font-light flex flex-row items-center gap-1">
|
||||
<span v-if="totalSize.oldSize > 0" class="opacity-75">{{ filesize(totalSize.oldSize) }}</span>
|
||||
<span v-else><Skeleton class="w-12 h-10" /></span>
|
||||
<LucideChevronsRight class="size-6" />
|
||||
<span v-if="totalSize.newSize > 0">{{ filesize(totalSize.newSize) }}</span>
|
||||
<span v-else><Skeleton class="w-12 h-10" /></span>
|
||||
<div
|
||||
v-if="totalSize.oldSize > 0 && totalSize.newSize > 0"
|
||||
class="rounded flex flex-row items-center bg-green-100 text-green-600 p-1 py-0.5 text-sm"
|
||||
>
|
||||
<LucideArrowDown class="size-4" />
|
||||
{{ ((1 - totalSize.newSize / totalSize.oldSize) * 100).toFixed(2) }}%
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-xl flex flex-col bg-white/70 px-3 py-2 gap-1 basis-1/3">
|
||||
<div class="text-sm font-semibold">{{ t('page.result.imageCompress.task') }}</div>
|
||||
<div class="text-3xl font-light">{{ taskResults.length }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-for="(item, index) in props?.data?.files" class="flex flex-row rounded-xl bg-white/70 p-3 justify-between w-full gap-3">
|
||||
<div class="flex flex-row gap-2 items-center w-full overflow-hidden">
|
||||
<div class="*:h-12 overflow-hidden">
|
||||
<FileIcon :file="item?.file" />
|
||||
</div>
|
||||
<div class="flex flex-col gap-0.5 flex-1 overflow-hidden">
|
||||
<div class="truncate w-auto">{{ item?.file?.name }}</div>
|
||||
<div class="text-xs opacity-50">{{ filesize(item?.file?.size ?? 0) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center justify-center" v-if="!taskResults?.[index]?.data">
|
||||
<Skeleton class="w-16 h-12" />
|
||||
</div>
|
||||
<div class="flex flex-row gap-1 items-center text-sm" v-if="taskResults?.[index]?.data?.status === 'retry'">
|
||||
<LucideLoader2 class="size-4 animate-spin" />
|
||||
{{
|
||||
t('page.result.imageCompress.retry', [
|
||||
taskResults?.[index]?.data?.err?.retry ?? 0,
|
||||
taskResults?.[index]?.data?.err?.max_retry ?? 0,
|
||||
])
|
||||
}}
|
||||
</div>
|
||||
<div class="flex items-center justify-center" v-if="taskResults?.[index]?.data?.status === 'archived'">
|
||||
<div class="text-sm text-red-500 px-2 py-1 rounded-md bg-red-100">{{ t('page.result.imageCompress.failed') }}</div>
|
||||
</div>
|
||||
<div class="flex flex-row gap-2 items-center shrink-0" v-if="taskResults?.[index]?.data?.status === 'success'">
|
||||
<div class="flex flex-col gap-1 items-center">
|
||||
<div class="rounded flex flex-row items-center bg-green-100 text-green-600 px-1 text-xs">
|
||||
<LucideArrowDown class="size-4" />
|
||||
{{
|
||||
(
|
||||
(1 -
|
||||
(taskResults?.[index]?.data?.result?.[0]?.new_file?.size ?? 0) /
|
||||
(taskResults?.[index]?.data?.result?.[0]?.old_file?.size ?? 0)) *
|
||||
100
|
||||
).toFixed(2)
|
||||
}}%
|
||||
</div>
|
||||
<div class="text-xs opacity-50">{{ filesize(taskResults?.[index]?.data?.result?.[0]?.new_file?.size ?? 0) }}</div>
|
||||
</div>
|
||||
<AsyncButton
|
||||
variant="outline"
|
||||
class="bg-black/5"
|
||||
size="icon"
|
||||
@click="
|
||||
async () => {
|
||||
const { new_file } = taskResults?.[index]?.data?.result?.[0] || {}
|
||||
if (!new_file?.id) return
|
||||
const data = await createFileShare({
|
||||
file_id: item.new_file.id,
|
||||
files: [{ id: new_file?.id as string, name: item?.file?.name }],
|
||||
config: {
|
||||
download_nums: 1,
|
||||
expire_time: 60,
|
||||
has_pickup_code: false,
|
||||
has_password: false,
|
||||
},
|
||||
file_name: props?.data?.file?.name,
|
||||
})
|
||||
const { id } = data?.data || {}
|
||||
const { id } = data?.[0]?.data || {}
|
||||
if (!id) {
|
||||
return
|
||||
}
|
||||
@@ -140,27 +198,9 @@ watch(
|
||||
}
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideDownload />
|
||||
</AsyncButton>
|
||||
><LucideArrowDown
|
||||
/></AsyncButton>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="taskData?.status !== 'retry' && !!taskData?.err?.message" class="flex flex-col gap-2">
|
||||
<div class="w-full h-16 flex flex-row items-center gap-3 bg-white/80 rounded-md p-2">
|
||||
<div class="size-10 flex items-center justify-center rounded-md bg-red-200">
|
||||
<LucideAlertTriangle class="size-5 text-red-600" />
|
||||
</div>
|
||||
<div class="text-sm">
|
||||
{{ `经过 ${taskData?.err?.retry} 次重试后任务处理失败: ${taskData?.err?.message}` }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-row justify-center">
|
||||
<Button @click="emit('change', 'input')"> 返回首页 </Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else="taskData?.status !== 'retry' && !!taskData?.err?.message" class="flex flex-col gap-2">
|
||||
<Skeleton class="w-full h-16 flex flex-row items-center justify-between" v-for="i in 3" />
|
||||
</div>
|
||||
</div>
|
||||
</BaseCard>
|
||||
</template>
|
||||
|
||||
190
front/components/Result/ImageConvertResult.vue
Normal file
@@ -0,0 +1,190 @@
|
||||
<script setup lang="ts">
|
||||
import { useQueries, useQuery } from '@tanstack/vue-query'
|
||||
import { AsyncButton } from '@/components/ui/button'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { filesize } from 'filesize'
|
||||
import useMyAppShare from '@/composables/useMyAppShare'
|
||||
import { toast } from 'vue-sonner'
|
||||
import type { handleFileComponentProps } from './types'
|
||||
|
||||
const { t } = useI18n()
|
||||
const emit = defineEmits<{
|
||||
(e: 'change', key: string): void
|
||||
}>()
|
||||
const props = defineProps<handleFileComponentProps>()
|
||||
const fileIds = computed(() => props?.data?.files?.map((item) => item.id))
|
||||
const targetExt = computed(() => props?.data?.config?.target_ext)
|
||||
const { data: taskIds } = useQuery({
|
||||
queryKey: ['create-image-convert', fileIds.value, targetExt.value],
|
||||
queryFn: async () => {
|
||||
return await Promise.all(
|
||||
props?.data?.files?.map(async (file) => {
|
||||
const { id } = file || {}
|
||||
if (!id) return
|
||||
const data = await $fetch<{
|
||||
code: number
|
||||
data: {
|
||||
id?: string
|
||||
}
|
||||
}>(`/api/task/image:convert`, {
|
||||
method: 'POST',
|
||||
body: {
|
||||
file_id: id,
|
||||
target_ext: targetExt.value,
|
||||
},
|
||||
})
|
||||
return data?.data?.id
|
||||
})
|
||||
)
|
||||
},
|
||||
staleTime: Infinity,
|
||||
enabled: !!fileIds.value && fileIds.value?.length > 0,
|
||||
})
|
||||
|
||||
const taskResults = useQueries({
|
||||
queries: computed(
|
||||
() =>
|
||||
taskIds?.value?.filter(Boolean).map((taskId) => {
|
||||
return {
|
||||
queryKey: ['task-image-convert', taskId],
|
||||
queryFn: async () => {
|
||||
const data = await $fetch<{
|
||||
code: number
|
||||
data: {
|
||||
result: {
|
||||
old_file: {
|
||||
id: string
|
||||
size: number
|
||||
}
|
||||
new_file: {
|
||||
id: string
|
||||
size: number
|
||||
}
|
||||
}[]
|
||||
status: 'success' | 'retry' | 'archived'
|
||||
err?: {
|
||||
message?: string
|
||||
retry?: number
|
||||
max_retry?: number
|
||||
}
|
||||
}
|
||||
}>(`/api/task/${taskId}`)
|
||||
return data?.data
|
||||
},
|
||||
enabled: !!taskId,
|
||||
}
|
||||
}) ?? []
|
||||
),
|
||||
})
|
||||
|
||||
const { downloadFileByShareId, createFileShare } = useMyAppShare()
|
||||
|
||||
const { counter, pause } = useInterval(2000, { controls: true })
|
||||
|
||||
watch(
|
||||
() => counter.value,
|
||||
() => {
|
||||
taskResults.value.forEach((item) => {
|
||||
if (['success', 'archived'].includes(item.data?.status ?? '')) return
|
||||
item.refetch()
|
||||
})
|
||||
|
||||
if (taskResults.value.every((item) => ['success', 'archived'].includes(item.data?.status ?? ''))) {
|
||||
pause()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
const totalExt = computed(() => {
|
||||
return props?.data?.files?.reduce<string[]>((acc, item) => {
|
||||
const [, originalName, originalExt] = item?.file?.name?.match(/(.*?)\.([^.]+(?:\.[^.]+)*)$/) ?? []
|
||||
if (originalExt) acc.push(originalExt)
|
||||
return acc
|
||||
}, [])
|
||||
})
|
||||
</script>
|
||||
<template>
|
||||
<BaseCard class="flex flex-col gap-3" :title="t('page.result.imageConvert.title')" :showBackButton="true">
|
||||
<div class="flex flex-row gap-3">
|
||||
<div class="rounded-xl flex flex-col bg-white/70 px-3 py-2 gap-1 basis-2/3">
|
||||
<div class="text-sm font-semibold">{{ t('page.result.imageConvert.convert') }}</div>
|
||||
<div class="text-2xl font-light flex flex-row items-center gap-1">
|
||||
<div v-for="ext in totalExt" class="rounded flex flex-row items-center bg-primary/20 text-primary p-1 py-0.5 text-sm">
|
||||
{{ ext?.toUpperCase() }}
|
||||
</div>
|
||||
<LucideChevronsRight class="size-6" />
|
||||
<div class="rounded flex flex-row items-center bg-primary/20 text-primary p-1 py-0.5 text-sm">
|
||||
{{ targetExt?.toUpperCase() }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-xl flex flex-col bg-white/70 px-3 py-2 gap-1 basis-1/3">
|
||||
<div class="text-sm font-semibold">{{ t('page.result.imageConvert.task') }}</div>
|
||||
<div class="text-3xl font-light">{{ taskResults.length }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-for="(item, index) in props?.data?.files" class="flex flex-row rounded-xl bg-white/70 p-3 justify-between w-full gap-3">
|
||||
<div class="flex flex-row gap-2 items-center w-full overflow-hidden">
|
||||
<div class="*:h-12 overflow-hidden">
|
||||
<FileIcon :file="item?.file" />
|
||||
</div>
|
||||
<div class="flex flex-col gap-0.5 flex-1 overflow-hidden">
|
||||
<div class="truncate w-auto">{{ item?.file?.name }}</div>
|
||||
<div class="text-xs opacity-50">{{ filesize(item?.file?.size ?? 0) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center justify-center" v-if="!taskResults?.[index]?.data">
|
||||
<Skeleton class="w-16 h-12" />
|
||||
</div>
|
||||
<div class="flex flex-row gap-1 items-center text-sm" v-if="taskResults?.[index]?.data?.status === 'retry'">
|
||||
<LucideLoader2 class="size-4 animate-spin" />
|
||||
{{
|
||||
t('page.result.imageConvert.retry', [
|
||||
taskResults?.[index]?.data?.err?.retry ?? 0,
|
||||
taskResults?.[index]?.data?.err?.max_retry ?? 0,
|
||||
])
|
||||
}}
|
||||
</div>
|
||||
<div class="flex items-center justify-center" v-if="taskResults?.[index]?.data?.status === 'archived'">
|
||||
<div class="text-sm text-red-500 px-2 py-1 rounded-md bg-red-100">{{ t('page.result.imageConvert.failed') }}</div>
|
||||
</div>
|
||||
<div class="flex flex-row gap-2 items-center shrink-0" v-if="taskResults?.[index]?.data?.status === 'success'">
|
||||
<div class="flex flex-col gap-1 items-center">
|
||||
<div class="rounded flex flex-row items-center bg-primary/20 text-primary px-1 text-xs">
|
||||
{{ targetExt.toUpperCase() }}
|
||||
</div>
|
||||
<div class="text-xs opacity-50">{{ filesize(taskResults?.[index]?.data?.result?.[0]?.new_file?.size ?? 0) }}</div>
|
||||
</div>
|
||||
<AsyncButton
|
||||
size="icon"
|
||||
@click="
|
||||
async () => {
|
||||
const { new_file } = taskResults?.[index]?.data?.result?.[0] || {}
|
||||
if (!new_file?.id) return
|
||||
const [, originalName, originalExt] = item?.file?.name?.match(/(.*?)\.([^.]+(?:\.[^.]+)*)$/) ?? []
|
||||
const data = await createFileShare({
|
||||
files: [{ id: new_file?.id as string, name: `${originalName}.${targetExt}` }],
|
||||
config: {
|
||||
download_nums: 1,
|
||||
expire_time: 60,
|
||||
has_pickup_code: false,
|
||||
has_password: false,
|
||||
},
|
||||
})
|
||||
const { id } = data?.[0]?.data || {}
|
||||
if (!id) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await downloadFileByShareId(id)
|
||||
} catch (error: any) {
|
||||
toast.error(error?.data?.message || error?.message || error)
|
||||
}
|
||||
}
|
||||
"
|
||||
><LucideArrowDown
|
||||
/></AsyncButton>
|
||||
</div>
|
||||
</div>
|
||||
</BaseCard>
|
||||
</template>
|
||||
@@ -1,45 +1,31 @@
|
||||
<script lang="ts" setup>
|
||||
import FileShareResult from "@/components/Result/FileShareResult.vue";
|
||||
import TextShareResult from "@/components/Result/TextShareResult.vue";
|
||||
import ImageCompressResult from "@/components/Result/ImageCompressResult.vue";
|
||||
|
||||
type basehandleData = { config: any; handle_type: string };
|
||||
|
||||
type filehandleData = { file: File; file_id: string } & basehandleData;
|
||||
type texthandleData = { text: string } & basehandleData;
|
||||
import FileShareResult from '@/components/Result/FileShareResult.vue'
|
||||
import TextShareResult from '@/components/Result/TextShareResult.vue'
|
||||
import ImageCompressResult from '@/components/Result/ImageCompressResult.vue'
|
||||
import ImageConvertResult from '@/components/Result/ImageConvertResult.vue'
|
||||
import type { filehandleData, handleComponent, handleKey, texthandleData } from './types'
|
||||
|
||||
const props = defineProps<{
|
||||
data: filehandleData | texthandleData;
|
||||
}>();
|
||||
data: filehandleData | texthandleData
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "change", key: string): void;
|
||||
}>();
|
||||
(e: 'change', key: string): void
|
||||
}>()
|
||||
|
||||
const handleList = [
|
||||
{ component: FileShareResult, key: "file-share" },
|
||||
{ component: TextShareResult, key: "text-share" },
|
||||
{ component: ImageCompressResult, key: "file-image-compress" },
|
||||
];
|
||||
const handleList: { component: handleComponent; key: handleKey }[] = [
|
||||
{ component: FileShareResult, key: 'file-share' },
|
||||
{ component: TextShareResult, key: 'text-share' },
|
||||
{ component: ImageCompressResult, key: 'file-image-compress' },
|
||||
{ component: ImageConvertResult, key: 'file-image-convert' },
|
||||
]
|
||||
|
||||
const activeHandle = computed(() => {
|
||||
return handleList.find((item) => item.key === props?.data?.handle_type);
|
||||
});
|
||||
return handleList.find((item) => item.key === props?.data?.handle_type)
|
||||
})
|
||||
// vue这个ts蠢的没边了,本来想写component: FileShareResult | TextShareResult,结果不行
|
||||
</script>
|
||||
<template>
|
||||
<div>
|
||||
<component
|
||||
v-if="'file' in data"
|
||||
:is="activeHandle?.component"
|
||||
:data="data"
|
||||
@change="(key: string) => emit('change', key)"
|
||||
/>
|
||||
<component
|
||||
v-if="'text' in data"
|
||||
:is="activeHandle?.component"
|
||||
:data="data"
|
||||
@change="(key: string) => emit('change', key)"
|
||||
/>
|
||||
</div>
|
||||
<component v-if="'files' in data" :is="activeHandle?.component" :data="data" @change="(key: string) => emit('change', key)" />
|
||||
<component v-if="'text' in data" :is="activeHandle?.component" :data="data" @change="(key: string) => emit('change', key)" />
|
||||
</template>
|
||||
|
||||
@@ -9,10 +9,10 @@ import useMyAppConfig from '@/composables/useMyAppConfig'
|
||||
import showDrawer from '@/lib/showDrawer'
|
||||
import QrCoreDrawer from '@/components/Drawer/QrCoreDrawer.vue'
|
||||
import dayjs from 'dayjs'
|
||||
import { h } from 'vue'
|
||||
import type { handleTextComponentProps } from './types'
|
||||
|
||||
const props = defineProps<{
|
||||
data: { text: string; config: any; handle_type: string }
|
||||
}>()
|
||||
const props = defineProps<handleTextComponentProps>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'change', key: string): void
|
||||
@@ -38,44 +38,28 @@ const url = computed(() => {
|
||||
})
|
||||
|
||||
const { copy } = useClipboard()
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="flex flex-row gap-2">
|
||||
<div class="flex flex-row justify-between w-full">
|
||||
<h2 class="text-lg">分享成功</h2>
|
||||
<Button
|
||||
variant="outline"
|
||||
class="bg-white/70"
|
||||
size="icon"
|
||||
@click="
|
||||
() => {
|
||||
emit('change', 'input')
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideHome />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<BaseCard class="flex flex-col gap-3" :title="t('page.result.text.title')" :showBackButton="true">
|
||||
<div class="flex flex-col md:flex-row gap-5 rounded-md p-5 bg-white/20 backdrop-blur-xl w-full">
|
||||
<div class="flex flex-col gap-2 flex-1">
|
||||
<div class="text-sm font-semibold">信息</div>
|
||||
<div class="text-sm font-semibold">{{ t('page.result.text.info') }}</div>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1">
|
||||
<div class="text-xs font-semibold">下载次数</div>
|
||||
<div class="text-xs font-semibold">{{ t('page.result.text.viewNums') }}</div>
|
||||
<div class="text-3xl font-light">{{ data?.download_nums }}</div>
|
||||
</div>
|
||||
<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-xs font-semibold">{{ t('page.result.text.expireTime') }}</div>
|
||||
<div class="text-md font-light">
|
||||
{{ dayjs((data?.expire_at ?? 0) * 1000).format('YYYY-MM-DD HH:mm:ss') }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1" v-if="data?.pickup_code">
|
||||
<div class="flex flex-row justify-between w-full items-center">
|
||||
<div class="text-xs font-semibold">提取码</div>
|
||||
<div class="text-xs font-semibold">{{ t('page.result.text.pickupCode') }}</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
class="bg-white/70 p-0 size-6"
|
||||
@@ -83,7 +67,7 @@ const { copy } = useClipboard()
|
||||
@click="
|
||||
() => {
|
||||
copy(data?.pickup_code as string)
|
||||
toast.success('复制成功')
|
||||
toast.success(t('page.result.text.copySuccess'))
|
||||
}
|
||||
"
|
||||
>
|
||||
@@ -99,7 +83,7 @@ const { copy } = useClipboard()
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-5 flex-1">
|
||||
<div class="text-sm font-semibold">链接</div>
|
||||
<div class="text-sm font-semibold">{{ t('page.result.text.link') }}</div>
|
||||
<div class="flex flex-row gap-2">
|
||||
<Input v-model="url" class="bg-white/70" readonly />
|
||||
<Button
|
||||
@@ -109,7 +93,7 @@ const { copy } = useClipboard()
|
||||
@click="
|
||||
() => {
|
||||
copy(url)
|
||||
toast.success('复制成功')
|
||||
toast.success(t('page.result.text.copySuccess'))
|
||||
}
|
||||
"
|
||||
>
|
||||
@@ -137,7 +121,7 @@ const { copy } = useClipboard()
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<h2 class="text-md">内容</h2>
|
||||
<h2 class="text-md">{{ t('page.result.text.content') }}</h2>
|
||||
<MarkdownRender class="prose rounded-md bg-white/70 p-3 w-full max-w-full min-h-[30vh]" :markdown="props?.data?.text" />
|
||||
</div>
|
||||
</BaseCard>
|
||||
</template>
|
||||
|
||||
11
front/components/Result/types.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import type { FileHandleKey, TextHandleKey } from '../Preprocessing/types'
|
||||
|
||||
type basehandleData = { config: Record<string, any> }
|
||||
|
||||
export type filehandleData = { files: { id: string; file: File }[]; handle_type: FileHandleKey } & basehandleData
|
||||
export type texthandleData = { text: string; handle_type: TextHandleKey } & basehandleData
|
||||
export type handleKey = FileHandleKey | TextHandleKey
|
||||
|
||||
export type handleTextComponentProps = { data: texthandleData }
|
||||
export type handleFileComponentProps = { data: filehandleData }
|
||||
export type handleComponent = Component<handleTextComponentProps | handleFileComponentProps>
|
||||
@@ -1,40 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Editor, EditorContent } from '@tiptap/vue-3'
|
||||
import StarterKit from '@tiptap/starter-kit'
|
||||
import { Markdown } from 'tiptap-markdown';
|
||||
import Placeholder from '@tiptap/extension-placeholder'
|
||||
const props = defineProps<{
|
||||
modelValue: string
|
||||
placeholder?: string
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: string): void
|
||||
}>()
|
||||
|
||||
const editor = ref<Editor | undefined>(undefined)
|
||||
onMounted(() => {
|
||||
editor.value = new Editor({
|
||||
content: props.modelValue,
|
||||
extensions: [StarterKit, Markdown.configure({
|
||||
transformPastedText: true,
|
||||
transformCopiedText: true
|
||||
}), Placeholder.configure({
|
||||
placeholder: props.placeholder ?? ''
|
||||
})],
|
||||
onUpdate: () => {
|
||||
// HTML
|
||||
emit('update:modelValue', editor.value?.storage?.markdown?.getMarkdown() ?? '')
|
||||
}
|
||||
})
|
||||
})
|
||||
watch(() => props.modelValue, (value) => {
|
||||
editor.value?.commands.setContent(value)
|
||||
})
|
||||
onUnmounted(() => {
|
||||
editor.value?.destroy()
|
||||
})
|
||||
|
||||
</script>
|
||||
<template>
|
||||
<editor-content :editor="editor" class="prose prose-sm bg-white/50 rounded-md p-2 [&>*]:outline-none prose-p:my-1" />
|
||||
</template>
|
||||
61
front/components/Tiptap/Index.vue
Normal file
@@ -0,0 +1,61 @@
|
||||
<script setup lang="ts">
|
||||
import { Editor, EditorContent } from '@tiptap/vue-3'
|
||||
import StarterKit from '@tiptap/starter-kit'
|
||||
import { Markdown } from 'tiptap-markdown'
|
||||
import Placeholder from '@tiptap/extension-placeholder'
|
||||
import { cx } from 'class-variance-authority'
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue?: string
|
||||
placeholder?: string
|
||||
class?: string
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: string): void
|
||||
}>()
|
||||
|
||||
const editor = ref<Editor | undefined>(undefined)
|
||||
onMounted(() => {
|
||||
editor.value = new Editor({
|
||||
content: props.modelValue,
|
||||
extensions: [
|
||||
StarterKit,
|
||||
Markdown.configure({
|
||||
transformPastedText: true,
|
||||
transformCopiedText: true,
|
||||
}),
|
||||
Placeholder.configure({
|
||||
placeholder: props.placeholder ?? '',
|
||||
}),
|
||||
// CommandsPlugin,
|
||||
],
|
||||
onUpdate: () => {
|
||||
emit('update:modelValue', (editor.value as any)?.storage?.markdown?.getMarkdown() ?? '')
|
||||
},
|
||||
})
|
||||
})
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(value) => {
|
||||
if (value !== (editor.value as any)?.storage?.markdown?.getMarkdown()) {
|
||||
editor.value?.commands.setContent(value ?? '')
|
||||
}
|
||||
}
|
||||
)
|
||||
onUnmounted(() => {
|
||||
editor.value?.destroy()
|
||||
})
|
||||
</script>
|
||||
<template>
|
||||
<editor-content
|
||||
:editor="editor as any"
|
||||
:class="
|
||||
cx(
|
||||
'prose prose-sm bg-white/50 rounded-md p-2 [&>*]:outline-none prose-p:my-1 prose-headings:my-2 prose-pre:mb-0 prose-blockquote:border-black/50 selection:bg-primary/20 max-w-full',
|
||||
props.class
|
||||
)
|
||||
"
|
||||
>
|
||||
</editor-content>
|
||||
<!-- <BubbleMenuView :editor="editor as any" /> -->
|
||||
</template>
|
||||
15
front/components/ui/accordion/Accordion.vue
Normal file
@@ -0,0 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccordionRootEmits, AccordionRootProps } from 'reka-ui'
|
||||
import { AccordionRoot, useForwardPropsEmits } from 'reka-ui'
|
||||
|
||||
const props = defineProps<AccordionRootProps>()
|
||||
const emits = defineEmits<AccordionRootEmits>()
|
||||
|
||||
const forwarded = useForwardPropsEmits(props, emits)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AccordionRoot data-slot="accordion" v-bind="forwarded">
|
||||
<slot />
|
||||
</AccordionRoot>
|
||||
</template>
|
||||
23
front/components/ui/accordion/AccordionContent.vue
Normal file
@@ -0,0 +1,23 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccordionContentProps } from 'reka-ui'
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import { AccordionContent } from 'reka-ui'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<AccordionContentProps & { class?: HTMLAttributes['class'] }>()
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AccordionContent
|
||||
data-slot="accordion-content"
|
||||
v-bind="delegatedProps"
|
||||
class="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
|
||||
>
|
||||
<div :class="cn('pt-0 pb-4', props.class)">
|
||||
<slot />
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</template>
|
||||