Compare commits
11 Commits
b8fda4322f
...
v0.1.2-bet
Author | SHA1 | Date | |
---|---|---|---|
1a8827a67a | |||
761b1d3b27 | |||
fb66b2c359 | |||
ad1b096a3b | |||
2d992e36ec | |||
91f3da635d | |||
93c4339039 | |||
e5cf2c1367 | |||
0e984c46b4 | |||
440aa96ad6 | |||
cfd4e8cb6d |
2
.dockerignore
Normal file
2
.dockerignore
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
46
.gitea/workflows/build.yaml
Normal file
46
.gitea/workflows/build.yaml
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
run-name: build ushare
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build and run u-api:
|
||||||
|
runs-on: tencent-sg
|
||||||
|
steps:
|
||||||
|
- name: prepare enviroment
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: prints date
|
||||||
|
run: date '+%Y-%m-%dT%H:%M:%S'
|
||||||
|
|
||||||
|
- name: print operator
|
||||||
|
run: whoami
|
||||||
|
|
||||||
|
- name: print work dir and files
|
||||||
|
run: pwd & ls -alsh .
|
||||||
|
|
||||||
|
- name: print tag name
|
||||||
|
run: echo "Tag name = ${{ gitea.ref_name }}"
|
||||||
|
|
||||||
|
- name: build prepare config
|
||||||
|
run: |
|
||||||
|
cat << EOF > .docker.config.json
|
||||||
|
${{ secrets.DOCKER_CONFIG }}
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- name: build by kaniko in docker
|
||||||
|
run: |
|
||||||
|
docker run --rm -v $(pwd):/workspace \
|
||||||
|
-v $(pwd)/.docker.config.json:/kaniko/.docker/config.json:ro \
|
||||||
|
gcr.io/kaniko-project/executor:latest \
|
||||||
|
'-d "gitea.loveuer.com/loveuer/build/ushare:${{ gitea.ref_name }}"' \
|
||||||
|
'--single-snapshot'
|
||||||
|
|
||||||
|
clean:
|
||||||
|
if: always()
|
||||||
|
runs-on: tencent-sg
|
||||||
|
steps:
|
||||||
|
- name: clean docker config
|
||||||
|
run: |
|
||||||
|
rm -rf .docker.config.json
|
35
Dockerfile
Normal file
35
Dockerfile
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
# 第一阶段:构建前端
|
||||||
|
FROM node:20-alpine AS frontend-builder
|
||||||
|
RUN npm install -g pnpm --registry=https://registry.npmmirror.com
|
||||||
|
COPY frontend /app/frontend
|
||||||
|
WORKDIR /app/frontend
|
||||||
|
RUN pnpm install --registry=https://registry.npmmirror.com
|
||||||
|
RUN pnpm run build
|
||||||
|
|
||||||
|
# 第二阶段:构建 Golang 后端
|
||||||
|
FROM golang:alpine AS backend-builder
|
||||||
|
WORKDIR /app
|
||||||
|
ENV CGO_ENABLED=0
|
||||||
|
ENV GOOS=linux
|
||||||
|
ENV GOPROXY=https://goproxy.cn
|
||||||
|
COPY go.mod /app/go.mod
|
||||||
|
COPY go.sum /app/go.sum
|
||||||
|
RUN go mod download
|
||||||
|
COPY main.go /app/main.go
|
||||||
|
COPY internal /app/internal
|
||||||
|
RUN go build -ldflags '-s -w' -o ushare .
|
||||||
|
|
||||||
|
# 第三阶段:生成最终镜像
|
||||||
|
FROM nginx:alpine
|
||||||
|
COPY --from=frontend-builder /app/frontend/dist /usr/share/nginx/html
|
||||||
|
COPY --from=backend-builder /app/ushare /usr/local/bin/ushare
|
||||||
|
|
||||||
|
# 配置 Nginx
|
||||||
|
RUN rm /etc/nginx/conf.d/default.conf
|
||||||
|
COPY deployment/nginx.conf /etc/nginx/conf.d
|
||||||
|
|
||||||
|
# 开放端口
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
# 启动服务
|
||||||
|
CMD sh -c "ushare & nginx -g 'daemon off;'"
|
22
deployment/nginx.conf
Normal file
22
deployment/nginx.conf
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /api {
|
||||||
|
proxy_pass http://localhost:9119;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /ushare {
|
||||||
|
proxy_pass http://localhost:9119;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
}
|
||||||
|
}
|
@ -2,9 +2,19 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
<!-- Emoji 图标方案 -->
|
||||||
|
<link rel="icon"
|
||||||
|
href="data:image/svg+xml,
|
||||||
|
<svg xmlns='http://www.w3.org/2000/svg'
|
||||||
|
viewBox='0 0 100 100'>
|
||||||
|
<text y='.9em'
|
||||||
|
font-size='90'
|
||||||
|
style='font-family: Arial, sans-serif'>
|
||||||
|
🗃️
|
||||||
|
</text>
|
||||||
|
</svg>">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Vite + React + TS</title>
|
<title>UShare</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
@ -13,6 +13,7 @@
|
|||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
"react-jss": "^10.10.0",
|
"react-jss": "^10.10.0",
|
||||||
|
"react-router-dom": "^7.5.3",
|
||||||
"zustand": "^5.0.3"
|
"zustand": "^5.0.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
51
frontend/pnpm-lock.yaml
generated
51
frontend/pnpm-lock.yaml
generated
@ -17,6 +17,9 @@ importers:
|
|||||||
react-jss:
|
react-jss:
|
||||||
specifier: ^10.10.0
|
specifier: ^10.10.0
|
||||||
version: 10.10.0(react@19.1.0)
|
version: 10.10.0(react@19.1.0)
|
||||||
|
react-router-dom:
|
||||||
|
specifier: ^7.5.3
|
||||||
|
version: 7.5.3(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||||
zustand:
|
zustand:
|
||||||
specifier: ^5.0.3
|
specifier: ^5.0.3
|
||||||
version: 5.0.3(@types/react@19.1.2)(react@19.1.0)
|
version: 5.0.3(@types/react@19.1.2)(react@19.1.0)
|
||||||
@ -640,6 +643,10 @@ packages:
|
|||||||
convert-source-map@2.0.0:
|
convert-source-map@2.0.0:
|
||||||
resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
|
resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
|
||||||
|
|
||||||
|
cookie@1.0.2:
|
||||||
|
resolution: {integrity: sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==}
|
||||||
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
cross-spawn@7.0.6:
|
cross-spawn@7.0.6:
|
||||||
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
|
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
|
||||||
engines: {node: '>= 8'}
|
engines: {node: '>= 8'}
|
||||||
@ -1120,6 +1127,23 @@ packages:
|
|||||||
resolution: {integrity: sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==}
|
resolution: {integrity: sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==}
|
||||||
engines: {node: '>=0.10.0'}
|
engines: {node: '>=0.10.0'}
|
||||||
|
|
||||||
|
react-router-dom@7.5.3:
|
||||||
|
resolution: {integrity: sha512-cK0jSaTyW4jV9SRKAItMIQfWZ/D6WEZafgHuuCb9g+SjhLolY78qc+De4w/Cz9ybjvLzShAmaIMEXt8iF1Cm+A==}
|
||||||
|
engines: {node: '>=20.0.0'}
|
||||||
|
peerDependencies:
|
||||||
|
react: '>=18'
|
||||||
|
react-dom: '>=18'
|
||||||
|
|
||||||
|
react-router@7.5.3:
|
||||||
|
resolution: {integrity: sha512-3iUDM4/fZCQ89SXlDa+Ph3MevBrozBAI655OAfWQlTm9nBR0IKlrmNwFow5lPHttbwvITZfkeeeZFP6zt3F7pw==}
|
||||||
|
engines: {node: '>=20.0.0'}
|
||||||
|
peerDependencies:
|
||||||
|
react: '>=18'
|
||||||
|
react-dom: '>=18'
|
||||||
|
peerDependenciesMeta:
|
||||||
|
react-dom:
|
||||||
|
optional: true
|
||||||
|
|
||||||
react@19.1.0:
|
react@19.1.0:
|
||||||
resolution: {integrity: sha512-FS+XFBNvn3GTAWq26joslQgWNoFu08F4kl0J4CgdNKADkdSGXQyTCnKteIAJy96Br6YbpEU1LSzV5dYtjMkMDg==}
|
resolution: {integrity: sha512-FS+XFBNvn3GTAWq26joslQgWNoFu08F4kl0J4CgdNKADkdSGXQyTCnKteIAJy96Br6YbpEU1LSzV5dYtjMkMDg==}
|
||||||
engines: {node: '>=0.10.0'}
|
engines: {node: '>=0.10.0'}
|
||||||
@ -1155,6 +1179,9 @@ packages:
|
|||||||
engines: {node: '>=10'}
|
engines: {node: '>=10'}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
|
set-cookie-parser@2.7.1:
|
||||||
|
resolution: {integrity: sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==}
|
||||||
|
|
||||||
shallow-equal@1.2.1:
|
shallow-equal@1.2.1:
|
||||||
resolution: {integrity: sha512-S4vJDjHHMBaiZuT9NPb616CSmLf618jawtv3sufLl6ivK8WocjAo58cXwbRV1cgqxH0Qbv+iUt6m05eqEa2IRA==}
|
resolution: {integrity: sha512-S4vJDjHHMBaiZuT9NPb616CSmLf618jawtv3sufLl6ivK8WocjAo58cXwbRV1cgqxH0Qbv+iUt6m05eqEa2IRA==}
|
||||||
|
|
||||||
@ -1205,6 +1232,9 @@ packages:
|
|||||||
peerDependencies:
|
peerDependencies:
|
||||||
typescript: '>=4.8.4'
|
typescript: '>=4.8.4'
|
||||||
|
|
||||||
|
turbo-stream@2.4.0:
|
||||||
|
resolution: {integrity: sha512-FHncC10WpBd2eOmGwpmQsWLDoK4cqsA/UT/GqNoaKOQnT8uzhtCbg3EoUDMvqpOSAI0S26mr0rkjzbOO6S3v1g==}
|
||||||
|
|
||||||
type-check@0.4.0:
|
type-check@0.4.0:
|
||||||
resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==}
|
resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==}
|
||||||
engines: {node: '>= 0.8.0'}
|
engines: {node: '>= 0.8.0'}
|
||||||
@ -1833,6 +1863,8 @@ snapshots:
|
|||||||
|
|
||||||
convert-source-map@2.0.0: {}
|
convert-source-map@2.0.0: {}
|
||||||
|
|
||||||
|
cookie@1.0.2: {}
|
||||||
|
|
||||||
cross-spawn@7.0.6:
|
cross-spawn@7.0.6:
|
||||||
dependencies:
|
dependencies:
|
||||||
path-key: 3.1.1
|
path-key: 3.1.1
|
||||||
@ -2344,6 +2376,21 @@ snapshots:
|
|||||||
|
|
||||||
react-refresh@0.17.0: {}
|
react-refresh@0.17.0: {}
|
||||||
|
|
||||||
|
react-router-dom@7.5.3(react-dom@19.1.0(react@19.1.0))(react@19.1.0):
|
||||||
|
dependencies:
|
||||||
|
react: 19.1.0
|
||||||
|
react-dom: 19.1.0(react@19.1.0)
|
||||||
|
react-router: 7.5.3(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||||
|
|
||||||
|
react-router@7.5.3(react-dom@19.1.0(react@19.1.0))(react@19.1.0):
|
||||||
|
dependencies:
|
||||||
|
cookie: 1.0.2
|
||||||
|
react: 19.1.0
|
||||||
|
set-cookie-parser: 2.7.1
|
||||||
|
turbo-stream: 2.4.0
|
||||||
|
optionalDependencies:
|
||||||
|
react-dom: 19.1.0(react@19.1.0)
|
||||||
|
|
||||||
react@19.1.0: {}
|
react@19.1.0: {}
|
||||||
|
|
||||||
regenerator-runtime@0.14.1: {}
|
regenerator-runtime@0.14.1: {}
|
||||||
@ -2388,6 +2435,8 @@ snapshots:
|
|||||||
|
|
||||||
semver@7.7.1: {}
|
semver@7.7.1: {}
|
||||||
|
|
||||||
|
set-cookie-parser@2.7.1: {}
|
||||||
|
|
||||||
shallow-equal@1.2.1: {}
|
shallow-equal@1.2.1: {}
|
||||||
|
|
||||||
shebang-command@2.0.0:
|
shebang-command@2.0.0:
|
||||||
@ -2429,6 +2478,8 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
typescript: 5.7.3
|
typescript: 5.7.3
|
||||||
|
|
||||||
|
turbo-stream@2.4.0: {}
|
||||||
|
|
||||||
type-check@0.4.0:
|
type-check@0.4.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
prelude-ls: 1.2.1
|
prelude-ls: 1.2.1
|
||||||
|
@ -1,5 +0,0 @@
|
|||||||
import {FileSharing} from "./page/share.tsx";
|
|
||||||
|
|
||||||
export function App() {
|
|
||||||
return <FileSharing />;
|
|
||||||
}
|
|
32
frontend/src/api/auth.ts
Normal file
32
frontend/src/api/auth.ts
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
import {useState} from "react";
|
||||||
|
import {message} from "../component/message/u-message.tsx";
|
||||||
|
|
||||||
|
export interface User {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
login_at: number;
|
||||||
|
token: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useAuth = () => {
|
||||||
|
const [user, setUser] = useState<User | null>(null)
|
||||||
|
|
||||||
|
const login = async (username: string, password: string) => {
|
||||||
|
let res = await fetch("/api/uauth/login", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {"Content-Type": "application/json"},
|
||||||
|
body: JSON.stringify({username: username, password: password}),
|
||||||
|
})
|
||||||
|
|
||||||
|
if(res.status !== 200) {
|
||||||
|
message.error("账号或密码错误")
|
||||||
|
throw new Error(await res.text())
|
||||||
|
}
|
||||||
|
|
||||||
|
let jes = await res.json() as User;
|
||||||
|
|
||||||
|
setUser(jes)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {user, login}
|
||||||
|
}
|
83
frontend/src/api/upload.ts
Normal file
83
frontend/src/api/upload.ts
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
|
||||||
|
|
||||||
|
interface UploadRes {
|
||||||
|
code: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useFileUpload = () => {
|
||||||
|
const [progress, setProgress] = useState(0);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const uploadFile = async (file: File): Promise<string> => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
setProgress(0);
|
||||||
|
|
||||||
|
try {
|
||||||
|
console.log(`[D] api.Upload: upload file = ${file.name}, size = ${file.size}`, file);
|
||||||
|
const url = `/api/ushare/${file.name}`;
|
||||||
|
|
||||||
|
// 1. 初始化上传
|
||||||
|
const res1 = await fetch(url, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: {"X-File-Size": file.size.toString()}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res1.ok) {
|
||||||
|
console.log(`[D] upload: put file not ok, status = ${res1.status}, res = ${await res1.text()}`)
|
||||||
|
if (res1.status === 401) {
|
||||||
|
window.location.href = "/login?next=/share"
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error("上传失败<1>");
|
||||||
|
}
|
||||||
|
|
||||||
|
const j1 = await res1.json() as UploadRes;
|
||||||
|
if (!j1.code) {
|
||||||
|
throw new Error("上传失败<2>");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 准备分片上传
|
||||||
|
const CHUNK_SIZE = 1024 * 1024;
|
||||||
|
const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
|
||||||
|
const code = j1.code;
|
||||||
|
|
||||||
|
// 3. 上传分片
|
||||||
|
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
|
||||||
|
const start = chunkIndex * CHUNK_SIZE;
|
||||||
|
const end = Math.min(start + CHUNK_SIZE, file.size);
|
||||||
|
const chunk = file.slice(start, end);
|
||||||
|
|
||||||
|
const res = await fetch(`/api/ushare/${code}`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Range": `bytes=${start}-${end - 1}`,
|
||||||
|
"Content-Type": "application/octet-stream"
|
||||||
|
},
|
||||||
|
body: chunk
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.text();
|
||||||
|
throw new Error(`上传失败<3>: ${err}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新进度
|
||||||
|
// const currentProgress = Number(((chunkIndex + 1) / totalChunks * 100).toFixed(2)); // 小数
|
||||||
|
const currentProgress = Math.round(((chunkIndex + 1) / totalChunks) * 100); // 整数 0-100
|
||||||
|
setProgress(currentProgress);
|
||||||
|
}
|
||||||
|
|
||||||
|
return code;
|
||||||
|
} catch (err) {
|
||||||
|
throw err; // 将错误继续抛出以便组件处理
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return { uploadFile, progress, loading, error };
|
||||||
|
};
|
@ -1,5 +1,5 @@
|
|||||||
import React, {ReactNode} from 'react';
|
import React, {ReactNode} from 'react';
|
||||||
import {createUseStyles} from "react-jss";
|
import {createUseStyles} from 'react-jss';
|
||||||
|
|
||||||
const useStyle = createUseStyles({
|
const useStyle = createUseStyles({
|
||||||
ubutton: {
|
ubutton: {
|
||||||
@ -10,6 +10,8 @@ const useStyle = createUseStyles({
|
|||||||
borderRadius: "5px",
|
borderRadius: "5px",
|
||||||
cursor: "pointer",
|
cursor: "pointer",
|
||||||
transition: "background-color 0.3s",
|
transition: "background-color 0.3s",
|
||||||
|
position: 'relative',
|
||||||
|
overflow: 'hidden',
|
||||||
"&:hover": {
|
"&:hover": {
|
||||||
backgroundColor: "#45a049",
|
backgroundColor: "#45a049",
|
||||||
},
|
},
|
||||||
@ -17,17 +19,84 @@ const useStyle = createUseStyles({
|
|||||||
backgroundColor: "#a5d6a7",
|
backgroundColor: "#a5d6a7",
|
||||||
cursor: "not-allowed",
|
cursor: "not-allowed",
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
})
|
loadingContent: {
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: '8px',
|
||||||
|
},
|
||||||
|
spinner: {
|
||||||
|
animation: '$spin 1s linear infinite',
|
||||||
|
border: '2px solid white',
|
||||||
|
borderTopColor: 'transparent',
|
||||||
|
borderRadius: '50%',
|
||||||
|
width: '16px',
|
||||||
|
height: '16px',
|
||||||
|
},
|
||||||
|
'@keyframes spin': {
|
||||||
|
'0%': {transform: 'rotate(0deg)'},
|
||||||
|
'100%': {transform: 'rotate(360deg)'},
|
||||||
|
},
|
||||||
|
progressBar: {
|
||||||
|
position: 'absolute',
|
||||||
|
bottom: 0,
|
||||||
|
left: 0,
|
||||||
|
height: '3px',
|
||||||
|
backgroundColor: 'rgba(255,255,255,0.5)',
|
||||||
|
width: '100%',
|
||||||
|
},
|
||||||
|
progressFill: {
|
||||||
|
height: '100%',
|
||||||
|
backgroundColor: 'white',
|
||||||
|
transition: 'width 0.3s ease',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
onClick: () => void;
|
onClick?: () => void;
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
style?: React.CSSProperties | undefined;
|
style?: React.CSSProperties;
|
||||||
|
loading?: boolean;
|
||||||
|
process?: number;
|
||||||
};
|
};
|
||||||
export const UButton: React.FC<Props> = ({onClick, children, style,disabled = false}) => {
|
|
||||||
const classes= useStyle()
|
export const UButton: React.FC<Props> = ({
|
||||||
return <button style={style} className={classes.ubutton} disabled={disabled} onClick={onClick}>
|
onClick,
|
||||||
|
children,
|
||||||
|
disabled = false,
|
||||||
|
style,
|
||||||
|
loading,
|
||||||
|
process
|
||||||
|
}) => {
|
||||||
|
const classes = useStyle();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
style={style}
|
||||||
|
className={classes.ubutton}
|
||||||
|
disabled={disabled || loading}
|
||||||
|
onClick={onClick}
|
||||||
|
>
|
||||||
|
{/* 显示加载状态或默认内容 */}
|
||||||
|
{loading ? (
|
||||||
|
<div className={classes.loadingContent}>
|
||||||
|
<span className={classes.spinner}/>
|
||||||
{children}
|
{children}
|
||||||
|
{process && `(${process}%)`}
|
||||||
|
</div>
|
||||||
|
) : children}
|
||||||
|
|
||||||
|
{/* 显示进度条 */}
|
||||||
|
{process !== undefined && (
|
||||||
|
<div className={classes.progressBar}>
|
||||||
|
<div
|
||||||
|
className={classes.progressFill}
|
||||||
|
style={{width: `${Math.min(Math.max(process, 0), 100)}%`}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
}
|
);
|
||||||
|
};
|
159
frontend/src/component/fluid/cloud.tsx
Normal file
159
frontend/src/component/fluid/cloud.tsx
Normal file
@ -0,0 +1,159 @@
|
|||||||
|
import { useRef, useEffect } from 'react';
|
||||||
|
|
||||||
|
export const CloudBackground = () => {
|
||||||
|
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||||
|
|
||||||
|
// 完整可配置参数
|
||||||
|
const config = {
|
||||||
|
cloudNum: 8, // 云朵数量
|
||||||
|
maxSpeed: 3.0, // 最大水平速度
|
||||||
|
cloudSize: 100, // 基础云朵尺寸 (新增)
|
||||||
|
sizeVariation: 0.5, // 尺寸随机变化率 (0-1)
|
||||||
|
colorVariation: 20, // 色相变化范围
|
||||||
|
verticalOscillation: 0.5, // 垂直浮动幅度
|
||||||
|
shapeComplexity: 5, // 形状复杂度(组成圆形数量)
|
||||||
|
boundaryOffset: 3 // 边界偏移倍数
|
||||||
|
};
|
||||||
|
|
||||||
|
type Cloud = {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
speed: number;
|
||||||
|
circles: CloudCircle[];
|
||||||
|
color: string;
|
||||||
|
maxRadius: number; // 记录云朵最大半径
|
||||||
|
};
|
||||||
|
|
||||||
|
type CloudCircle = {
|
||||||
|
offsetX: number;
|
||||||
|
offsetY: number;
|
||||||
|
radius: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const canvas = canvasRef.current!;
|
||||||
|
const ctx = canvas.getContext('2d')!;
|
||||||
|
|
||||||
|
const resize = () => {
|
||||||
|
canvas.width = window.innerWidth;
|
||||||
|
canvas.height = window.innerHeight;
|
||||||
|
};
|
||||||
|
resize();
|
||||||
|
|
||||||
|
// 生成云朵形状(基于配置参数)
|
||||||
|
const createCloudShape = () => {
|
||||||
|
const circles: CloudCircle[] = [];
|
||||||
|
const circleCount = 4 + Math.floor(Math.random() * config.shapeComplexity);
|
||||||
|
|
||||||
|
for(let i = 0; i < circleCount; i++) {
|
||||||
|
circles.push({
|
||||||
|
offsetX: (Math.random() - 0.5) * config.cloudSize * 1.5,
|
||||||
|
offsetY: (Math.random() - 0.5) * config.cloudSize * 0.8,
|
||||||
|
radius: config.cloudSize * (1 - config.sizeVariation + Math.random() * config.sizeVariation)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return circles;
|
||||||
|
};
|
||||||
|
|
||||||
|
let clouds: Cloud[] = [];
|
||||||
|
const createClouds = () => {
|
||||||
|
clouds = Array.from({ length: config.cloudNum }).map(() => {
|
||||||
|
const shape = createCloudShape();
|
||||||
|
return {
|
||||||
|
x: Math.random() * canvas.width,
|
||||||
|
y: canvas.height * (0.2 + Math.random() * 0.6),
|
||||||
|
speed: (Math.random() * 0.5 + 0.5) * config.maxSpeed,
|
||||||
|
circles: shape,
|
||||||
|
color: `hsla(210, 30%, 95%, ${0.8 + Math.random() * 0.2})`,
|
||||||
|
maxRadius: Math.max(...shape.map(c => c.radius)) // 计算最大半径
|
||||||
|
};
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const drawCloud = (cloud: Cloud) => {
|
||||||
|
ctx.save();
|
||||||
|
ctx.beginPath();
|
||||||
|
|
||||||
|
cloud.circles.forEach(circle => {
|
||||||
|
ctx.moveTo(cloud.x + circle.offsetX, cloud.y + circle.offsetY);
|
||||||
|
ctx.arc(
|
||||||
|
cloud.x + circle.offsetX,
|
||||||
|
cloud.y + circle.offsetY,
|
||||||
|
circle.radius,
|
||||||
|
0,
|
||||||
|
Math.PI * 2
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const gradient = ctx.createRadialGradient(
|
||||||
|
cloud.x, cloud.y, 0,
|
||||||
|
cloud.x, cloud.y, config.cloudSize * 2
|
||||||
|
);
|
||||||
|
gradient.addColorStop(0, cloud.color);
|
||||||
|
gradient.addColorStop(1, `hsla(210, 50%, 98%, 0.3)`);
|
||||||
|
|
||||||
|
ctx.fillStyle = gradient;
|
||||||
|
ctx.filter = `blur(${config.cloudSize * 0.2}px)`; // 模糊与尺寸关联
|
||||||
|
ctx.fill();
|
||||||
|
ctx.restore();
|
||||||
|
};
|
||||||
|
|
||||||
|
let animationFrameId: number;
|
||||||
|
const animate = () => {
|
||||||
|
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||||
|
|
||||||
|
// 天空渐变背景
|
||||||
|
const skyGradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
|
||||||
|
skyGradient.addColorStop(0, '#e6f3ff');
|
||||||
|
skyGradient.addColorStop(1, '#d1e8ff');
|
||||||
|
ctx.fillStyle = skyGradient;
|
||||||
|
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||||
|
|
||||||
|
clouds.forEach(cloud => {
|
||||||
|
cloud.x += cloud.speed;
|
||||||
|
cloud.y += Math.sin(Date.now() / 1000 + cloud.x) * config.verticalOscillation;
|
||||||
|
|
||||||
|
// 基于实际最大半径的边界检测
|
||||||
|
const resetPosition = cloud.x > canvas.width + (cloud.maxRadius * config.boundaryOffset);
|
||||||
|
if (resetPosition) {
|
||||||
|
cloud.x = -cloud.maxRadius * config.boundaryOffset;
|
||||||
|
// 重置时重新生成形状
|
||||||
|
const newShape = createCloudShape();
|
||||||
|
cloud.circles = newShape;
|
||||||
|
cloud.maxRadius = Math.max(...newShape.map(c => c.radius));
|
||||||
|
}
|
||||||
|
|
||||||
|
drawCloud(cloud);
|
||||||
|
});
|
||||||
|
|
||||||
|
animationFrameId = requestAnimationFrame(animate);
|
||||||
|
};
|
||||||
|
|
||||||
|
createClouds();
|
||||||
|
animate();
|
||||||
|
|
||||||
|
window.addEventListener('resize', () => {
|
||||||
|
resize();
|
||||||
|
createClouds();
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('resize', resize);
|
||||||
|
cancelAnimationFrame(animationFrameId);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<canvas
|
||||||
|
ref={canvasRef}
|
||||||
|
style={{
|
||||||
|
position: 'fixed',
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
zIndex: -1,
|
||||||
|
width: '100%',
|
||||||
|
height: '100%'
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
124
frontend/src/component/fluid/fluid.tsx
Normal file
124
frontend/src/component/fluid/fluid.tsx
Normal file
@ -0,0 +1,124 @@
|
|||||||
|
import { useRef, useEffect } from 'react';
|
||||||
|
|
||||||
|
export const AnimatedBackground = () => {
|
||||||
|
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||||
|
|
||||||
|
// 粒子配置
|
||||||
|
const config = {
|
||||||
|
particleNum: 100,
|
||||||
|
maxSpeed: 1.5,
|
||||||
|
particleRadius: 2,
|
||||||
|
lineWidth: 1.5,
|
||||||
|
lineDistance: 100
|
||||||
|
};
|
||||||
|
|
||||||
|
type Particle = {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
speedX: number;
|
||||||
|
speedY: number;
|
||||||
|
color: string;
|
||||||
|
radius: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const canvas = canvasRef.current!;
|
||||||
|
const ctx = canvas.getContext('2d')!;
|
||||||
|
|
||||||
|
// 设置canvas尺寸
|
||||||
|
const resize = () => {
|
||||||
|
canvas.width = window.innerWidth;
|
||||||
|
canvas.height = window.innerHeight;
|
||||||
|
};
|
||||||
|
resize();
|
||||||
|
|
||||||
|
// 创建粒子数组
|
||||||
|
let particles: Particle[] = [];
|
||||||
|
const createParticles = () => {
|
||||||
|
particles = Array.from({ length: config.particleNum }).map(() => ({
|
||||||
|
x: Math.random() * canvas.width,
|
||||||
|
y: Math.random() * canvas.height,
|
||||||
|
speedX: (Math.random() - 0.5) * config.maxSpeed,
|
||||||
|
speedY: (Math.random() - 0.5) * config.maxSpeed,
|
||||||
|
color: `hsl(${Math.random() * 360}, 70%, 60%)`,
|
||||||
|
radius: Math.random() * config.particleRadius + 1
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
// 绘制连线
|
||||||
|
const drawLine = (p1: Particle, p2: Particle) => {
|
||||||
|
const dx = p1.x - p2.x;
|
||||||
|
const dy = p1.y - p2.y;
|
||||||
|
const dist = Math.sqrt(dx * dx + dy * dy);
|
||||||
|
|
||||||
|
if (dist < config.lineDistance) {
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.strokeStyle = p1.color;
|
||||||
|
ctx.lineWidth = config.lineWidth * (1 - dist / config.lineDistance);
|
||||||
|
ctx.moveTo(p1.x, p1.y);
|
||||||
|
ctx.lineTo(p2.x, p2.y);
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 动画循环
|
||||||
|
let animationFrameId: number;
|
||||||
|
const animate = () => {
|
||||||
|
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||||
|
|
||||||
|
// 更新粒子位置
|
||||||
|
particles.forEach(particle => {
|
||||||
|
particle.x += particle.speedX;
|
||||||
|
particle.y += particle.speedY;
|
||||||
|
|
||||||
|
// 边界反弹
|
||||||
|
if (particle.x < 0 || particle.x > canvas.width) particle.speedX *= -1;
|
||||||
|
if (particle.y < 0 || particle.y > canvas.height) particle.speedY *= -1;
|
||||||
|
|
||||||
|
// 绘制粒子
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.fillStyle = particle.color;
|
||||||
|
ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
|
||||||
|
ctx.fill();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 绘制粒子间的连线
|
||||||
|
for (let i = 0; i < particles.length; i++) {
|
||||||
|
for (let j = i + 1; j < particles.length; j++) {
|
||||||
|
drawLine(particles[i], particles[j]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
animationFrameId = requestAnimationFrame(animate);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 初始化
|
||||||
|
createParticles();
|
||||||
|
animate();
|
||||||
|
|
||||||
|
// 窗口resize处理
|
||||||
|
window.addEventListener('resize', () => {
|
||||||
|
resize();
|
||||||
|
createParticles();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 清理
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('resize', resize);
|
||||||
|
cancelAnimationFrame(animationFrameId);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<canvas
|
||||||
|
ref={canvasRef}
|
||||||
|
style={{
|
||||||
|
position: 'fixed',
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
zIndex: -1,
|
||||||
|
backgroundColor: '#1a1a1a'
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
@ -1,84 +1,126 @@
|
|||||||
// MessageContext.tsx
|
import {createRoot} from "react-dom/client";
|
||||||
import React, { createContext, useContext, useState, useCallback, useRef } from 'react';
|
import {useState} from "react";
|
||||||
import ReactDOM from 'react-dom';
|
import {createUseStyles} from "react-jss";
|
||||||
import './Message.css';
|
|
||||||
|
const useStyle = createUseStyles({
|
||||||
|
container: {
|
||||||
|
position: 'fixed',
|
||||||
|
width: '100%',
|
||||||
|
display: 'flex',
|
||||||
|
zIndex: 10000,
|
||||||
|
top: '20px',
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
flexDirection: "column",
|
||||||
|
},
|
||||||
|
message: {
|
||||||
|
width: '100%',
|
||||||
|
maxWidth: '300px',
|
||||||
|
background: '#fafafa', // 浅灰背景与其他状态统一
|
||||||
|
borderRadius: '8px',
|
||||||
|
padding: '10px 10px 10px 20px', // 统一左侧20px留白
|
||||||
|
|
||||||
|
borderLeft: '4px solid #e0e0e0', // 加粗为4px与其他状态一致
|
||||||
|
color: '#757575', // 中性灰文字
|
||||||
|
|
||||||
|
boxShadow: '0 2px 6px rgba(224, 224, 224, 0.15)', // 灰色投影
|
||||||
|
transition: 'all 0.3s ease-in-out', // 补全时间单位
|
||||||
|
|
||||||
|
marginBottom: '20px',
|
||||||
|
|
||||||
|
'&.success': {
|
||||||
|
color: '#2e7d32',
|
||||||
|
backgroundColor: '#f0f9eb',
|
||||||
|
borderLeft: '4px solid #4CAF50',
|
||||||
|
paddingLeft: '20px',
|
||||||
|
boxShadow: '0 2px 6px rgba(76, 175, 80, 0.15)'
|
||||||
|
},
|
||||||
|
'&.warning': {
|
||||||
|
color: '#faad14', // 警告文字色
|
||||||
|
backgroundColor: '#fffbe6', // 浅黄色背景
|
||||||
|
borderLeft: '4px solid #ffc53d', // 琥珀色左侧标识
|
||||||
|
paddingLeft: '20px',
|
||||||
|
boxShadow: '0 2px 6px rgba(255, 197, 61, 0.15)' // 金色投影
|
||||||
|
},
|
||||||
|
'&.error': {
|
||||||
|
color: '#f5222d', // 错误文字色
|
||||||
|
backgroundColor: '#fff1f0', // 浅红色背景
|
||||||
|
borderLeft: '4px solid #ff4d4f', // 品红色左侧标识
|
||||||
|
paddingLeft: '20px',
|
||||||
|
boxShadow: '0 2px 6px rgba(255, 77, 79, 0.15)' // 红色投影
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
let el = document.querySelector("#u-message")
|
||||||
|
if (!el) {
|
||||||
|
el = document.createElement('div')
|
||||||
|
el.className = 'u-message'
|
||||||
|
el.id = 'u-message'
|
||||||
|
document.body.append(el)
|
||||||
|
}
|
||||||
|
|
||||||
export interface Message {
|
export interface Message {
|
||||||
id: number;
|
id: number
|
||||||
content: string;
|
content: string
|
||||||
type: 'info' | 'success' | 'warning' | 'error';
|
duration: number
|
||||||
|
type: 'info' | 'success' | 'warning' | 'error'
|
||||||
}
|
}
|
||||||
|
|
||||||
export type MessageType = Message['type'];
|
export interface MessageApi {
|
||||||
|
info: (content: string, duration?: number) => void;
|
||||||
|
warning: (content: string, duration?: number) => void;
|
||||||
|
success: (content: string, duration?: number) => void;
|
||||||
|
error: (content: string, duration?: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
const MessageContext = createContext<{
|
const default_duration = 3000
|
||||||
addMessage: (content: string, type?: MessageType, duration?: number) => void;
|
|
||||||
removeMessage: (id: number) => void;
|
|
||||||
}>({
|
let add: (msg: Message) => void;
|
||||||
addMessage: () => {},
|
|
||||||
removeMessage: () => {},
|
const MessageContainer: React.FC = () => {
|
||||||
|
const classes = useStyle()
|
||||||
|
const [msgs, setMsgs] = useState<Message[]>([]);
|
||||||
|
|
||||||
|
const remove = (id: number) => {
|
||||||
|
setMsgs(prevMsgs => prevMsgs.filter(v => v.id !== id));
|
||||||
|
}
|
||||||
|
|
||||||
|
add = (msg: Message) => {
|
||||||
|
const id = Date.now();
|
||||||
|
setMsgs(prevMsgs => {
|
||||||
|
const newMsgs = [{...msg, id}, ...prevMsgs];
|
||||||
|
// 直接限制数组长度为5,移除最旧的消息(最后一项)
|
||||||
|
if (newMsgs.length > 5) {
|
||||||
|
newMsgs.pop();
|
||||||
|
}
|
||||||
|
return newMsgs;
|
||||||
});
|
});
|
||||||
|
|
||||||
export const MessageProvider: React.FC = ({ children }) => {
|
setTimeout(() => {
|
||||||
const [messages, setMessages] = useState<Message[]>([]);
|
remove(id);
|
||||||
const timerRef = useRef<Record<string, NodeJS.Timeout>>({});
|
}, msg.duration ?? default_duration);
|
||||||
|
|
||||||
const addMessage = useCallback((content: string, type: MessageType = 'info', duration: number = 3000) => {
|
|
||||||
const id = Date.now();
|
|
||||||
setMessages(prev => [...prev, { id, content, type }]);
|
|
||||||
|
|
||||||
timerRef.current[id] = setTimeout(() => {
|
|
||||||
removeMessage(id);
|
|
||||||
}, duration);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const removeMessage = useCallback((id: number) => {
|
|
||||||
setMessages(prev => prev.filter(msg => msg.id !== id));
|
|
||||||
clearTimeout(timerRef.current[id]);
|
|
||||||
delete timerRef.current[id];
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<MessageContext.Provider value={{ addMessage, removeMessage }}>
|
|
||||||
{children}
|
|
||||||
{ReactDOM.createPortal(
|
|
||||||
<div className="message-container">
|
|
||||||
{messages.map(({ id, content, type }) => (
|
|
||||||
<MessageItem
|
|
||||||
key={id}
|
|
||||||
id={id}
|
|
||||||
content={content}
|
|
||||||
type={type}
|
|
||||||
onClose={() => removeMessage(id)}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>,
|
|
||||||
document.body
|
|
||||||
)}
|
|
||||||
</MessageContext.Provider>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
interface MessageItemProps {
|
|
||||||
id: number;
|
|
||||||
content: string;
|
|
||||||
type: MessageType;
|
|
||||||
onClose: () => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const MessageItem: React.FC<MessageItemProps> = ({ id, content, type, onClose }) => {
|
return <div className={classes.container}>
|
||||||
return (
|
{msgs.map(m => <div key={m.id} className={`${classes.message} ${m.type}`}>{m.content}</div>)}
|
||||||
<div className={`message-item ${type}`}>
|
|
||||||
{content}
|
|
||||||
<button onClick={onClose}>×</button>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const useMessage = (): ReturnType<typeof MessageContext> => {
|
|
||||||
const context = useContext(MessageContext);
|
|
||||||
if (!context) {
|
|
||||||
throw new Error('useMessage must be used within a MessageProvider');
|
|
||||||
}
|
}
|
||||||
return context;
|
|
||||||
};
|
createRoot(el).render(<MessageContainer/>)
|
||||||
|
|
||||||
|
export const message: MessageApi = {
|
||||||
|
info: function (content: string, duration?: number): void {
|
||||||
|
add({content: content, duration: duration, type: "info"} as Message)
|
||||||
|
},
|
||||||
|
warning: function (content: string, duration?: number): void {
|
||||||
|
add({content: content, duration: duration, type: "warning"} as Message)
|
||||||
|
},
|
||||||
|
success: function (content: string, duration?: number): void {
|
||||||
|
add({content: content, duration: duration, type: "success"} as Message)
|
||||||
|
},
|
||||||
|
error: function (content: string, duration?: number): void {
|
||||||
|
add({content: content, duration: duration, type: "error"} as Message)
|
||||||
|
}
|
||||||
|
}
|
@ -1,10 +1,19 @@
|
|||||||
import { StrictMode } from 'react'
|
import { StrictMode } from 'react'
|
||||||
import { createRoot } from 'react-dom/client'
|
import { createRoot } from 'react-dom/client'
|
||||||
import './index.css'
|
import './index.css'
|
||||||
import {App} from './App.tsx'
|
import {createBrowserRouter, RouterProvider} from "react-router-dom";
|
||||||
|
import {Login} from "./page/login.tsx";
|
||||||
|
import {FileSharing} from "./page/share.tsx";
|
||||||
|
|
||||||
createRoot(document.getElementById('root')!).render(
|
const container = document.getElementById('root')
|
||||||
|
const root = createRoot(container!)
|
||||||
|
const router = createBrowserRouter([
|
||||||
|
{path: "/login", element: <Login />},
|
||||||
|
{path: "*", element: <FileSharing />},
|
||||||
|
])
|
||||||
|
|
||||||
|
root.render(
|
||||||
<StrictMode>
|
<StrictMode>
|
||||||
<App />
|
<RouterProvider router={router} />
|
||||||
</StrictMode>,
|
</StrictMode>,
|
||||||
)
|
)
|
||||||
|
@ -1,9 +1,11 @@
|
|||||||
import {createUseStyles} from "react-jss";
|
import {createUseStyles} from "react-jss";
|
||||||
import {UButton} from "../../component/button/u-button.tsx";
|
import {UButton} from "../../component/button/u-button.tsx";
|
||||||
import React from "react";
|
import React, {useState} from "react";
|
||||||
import {useStore} from "../../store/share.ts";
|
import {useStore} from "../../store/share.ts";
|
||||||
|
import {message} from "../../component/message/u-message.tsx";
|
||||||
|
import {useFileUpload} from "../../api/upload.ts";
|
||||||
|
|
||||||
const useStyle = createUseStyles({
|
const useUploadStyle = createUseStyles({
|
||||||
container: {
|
container: {
|
||||||
backgroundColor: "#e3f2fd",
|
backgroundColor: "#e3f2fd",
|
||||||
display: "flex",
|
display: "flex",
|
||||||
@ -39,9 +41,94 @@ const useStyle = createUseStyles({
|
|||||||
'&:hover': {}
|
'&:hover': {}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const useShowStyle = createUseStyles({
|
||||||
|
container: {
|
||||||
|
backgroundColor: "#e3f2fd",
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
position: "relative", // 为关闭按钮提供定位基准
|
||||||
|
},
|
||||||
|
title: {
|
||||||
|
color: "#2c9678",
|
||||||
|
marginTop: 0,
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
alignItems: "center",
|
||||||
|
},
|
||||||
|
form: {
|
||||||
|
backgroundColor: "#C8E6C9",
|
||||||
|
boxShadow: "inset 0 0 15px rgba(56, 142, 60, 0.15)",
|
||||||
|
padding: "30px",
|
||||||
|
borderRadius: "15px",
|
||||||
|
width: "70%",
|
||||||
|
margin: "20px 60px 20px 0",
|
||||||
|
position: "relative",
|
||||||
|
},
|
||||||
|
closeButton: {
|
||||||
|
position: "absolute",
|
||||||
|
top: "10px",
|
||||||
|
right: "10px",
|
||||||
|
background: "transparent",
|
||||||
|
color: "white",
|
||||||
|
border: "none",
|
||||||
|
borderRadius: "50%",
|
||||||
|
width: "24px",
|
||||||
|
height: "24px",
|
||||||
|
cursor: "pointer",
|
||||||
|
"&:hover": {
|
||||||
|
// background: "#cc0000",
|
||||||
|
boxShadow: "20px 20px 60px #fff, -20px -20px 60px #fff",
|
||||||
|
// boxShadow: "20px 20px 60px #eee",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
codeWrapper: {
|
||||||
|
backgroundColor: "rgba(255,255,255,0.8)",
|
||||||
|
padding: "0 15px",
|
||||||
|
borderRadius: "8px",
|
||||||
|
margin: "15px 0",
|
||||||
|
overflowX: "auto",
|
||||||
|
},
|
||||||
|
pre: {
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'row',
|
||||||
|
color: 'black',
|
||||||
|
alignItems: 'center',
|
||||||
|
height: '24px',
|
||||||
|
"& > code": {
|
||||||
|
marginLeft: "0",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
copyButton: {
|
||||||
|
marginLeft: 'auto',
|
||||||
|
background: "#2c9678",
|
||||||
|
color: "white",
|
||||||
|
border: "none",
|
||||||
|
padding: "8px 16px",
|
||||||
|
borderRadius: "4px",
|
||||||
|
cursor: "pointer",
|
||||||
|
transition: "background 0.3s",
|
||||||
|
"&:hover": {
|
||||||
|
background: "#1f6d5a",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
export const PanelLeft = () => {
|
export const PanelLeft = () => {
|
||||||
const style = useStyle()
|
const [code, set_code] = useState("")
|
||||||
|
|
||||||
|
if (code) {
|
||||||
|
return <PanelLeftShow code={code} set_code={set_code} />
|
||||||
|
}
|
||||||
|
|
||||||
|
return <PanelLeftUpload set_code={set_code}/>
|
||||||
|
};
|
||||||
|
|
||||||
|
const PanelLeftUpload: React.FC<{ set_code: (code:string) => void }> = ({set_code}) => {
|
||||||
|
const style = useUploadStyle()
|
||||||
const {file, setFile} = useStore()
|
const {file, setFile} = useStore()
|
||||||
|
const {uploadFile, progress, loading} = useFileUpload();
|
||||||
|
|
||||||
function onFileSelect() {
|
function onFileSelect() {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
@ -53,8 +140,13 @@ export const PanelLeft = () => {
|
|||||||
setFile(e.currentTarget.files ? e.currentTarget.files[0] : null)
|
setFile(e.currentTarget.files ? e.currentTarget.files[0] : null)
|
||||||
}
|
}
|
||||||
|
|
||||||
function onFileUpload() {
|
async function onFileUpload() {
|
||||||
console.log(`[D] onFileUpload: upload file = ${file?.name}, size = ${file?.size}`, file)
|
if (!file) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const code = await uploadFile(file)
|
||||||
|
set_code(code)
|
||||||
}
|
}
|
||||||
|
|
||||||
function onFileClean() {
|
function onFileClean() {
|
||||||
@ -65,13 +157,17 @@ export const PanelLeft = () => {
|
|||||||
<div className={style.form}>
|
<div className={style.form}>
|
||||||
<h2 className={style.title}>上传文件</h2>
|
<h2 className={style.title}>上传文件</h2>
|
||||||
{
|
{
|
||||||
!file &&
|
!file && !loading &&
|
||||||
<UButton onClick={onFileSelect}>选择文件</UButton>
|
<UButton onClick={onFileSelect}>选择文件</UButton>
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
file &&
|
file && !loading &&
|
||||||
<UButton onClick={onFileUpload}>上传文件</UButton>
|
<UButton onClick={onFileUpload}>上传文件</UButton>
|
||||||
}
|
}
|
||||||
|
{
|
||||||
|
loading &&
|
||||||
|
<UButton process={progress} loading={loading}>上传中</UButton>
|
||||||
|
}
|
||||||
<input type="file" className={style.file} id="real-file-input" onChange={onFileChange}/>
|
<input type="file" className={style.file} id="real-file-input" onChange={onFileChange}/>
|
||||||
{
|
{
|
||||||
file &&
|
file &&
|
||||||
@ -82,4 +178,44 @@ export const PanelLeft = () => {
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
const PanelLeftShow: React.FC<{ code: string; set_code: (code: string) => void }> = ({ code, set_code }) => {
|
||||||
|
const classes = useShowStyle();
|
||||||
|
|
||||||
|
const handleCopy = async () => {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(code);
|
||||||
|
message.success("复制成功!");
|
||||||
|
} catch (err) {
|
||||||
|
message.warning("复制失败,请手动选择文本复制");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={classes.container}>
|
||||||
|
|
||||||
|
<div className={classes.form}>
|
||||||
|
<button
|
||||||
|
className={classes.closeButton}
|
||||||
|
onClick={() => set_code('')}
|
||||||
|
aria-label="关闭"
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
<h2 className={classes.title}>
|
||||||
|
上传成功!
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<div className={classes.codeWrapper}>
|
||||||
|
<pre className={classes.pre}>
|
||||||
|
<code>{code}</code>
|
||||||
|
<button className={classes.copyButton} onClick={handleCopy}>
|
||||||
|
一键复制
|
||||||
|
</button>
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
};
|
};
|
@ -2,6 +2,7 @@ import {createUseStyles} from "react-jss";
|
|||||||
|
|
||||||
const useStyle = createUseStyles({
|
const useStyle = createUseStyles({
|
||||||
container: {
|
container: {
|
||||||
|
backgroundColor: 'lightgray',
|
||||||
position: "relative",
|
position: "relative",
|
||||||
overflow: "hidden",
|
overflow: "hidden",
|
||||||
},
|
},
|
||||||
|
@ -41,7 +41,7 @@ export const PanelRight = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function onFetchFile() {
|
async function onFetchFile() {
|
||||||
const url = `/api/share/fetch?code=${code}`
|
const url = `/ushare/${code}`
|
||||||
console.log('[D] onFetchFile: url =', url)
|
console.log('[D] onFetchFile: url =', url)
|
||||||
const link = document.createElement('a');
|
const link = document.createElement('a');
|
||||||
link.href = url;
|
link.href = url;
|
||||||
|
183
frontend/src/page/login.tsx
Normal file
183
frontend/src/page/login.tsx
Normal file
@ -0,0 +1,183 @@
|
|||||||
|
import React, { useState } from "react";
|
||||||
|
import { createUseStyles } from "react-jss";
|
||||||
|
import { CloudBackground } from "../component/fluid/cloud.tsx";
|
||||||
|
import {useAuth} from "../api/auth.ts";
|
||||||
|
|
||||||
|
const useClass = createUseStyles({
|
||||||
|
container: {
|
||||||
|
overflow: 'hidden',
|
||||||
|
height: '100vh',
|
||||||
|
margin: 0,
|
||||||
|
padding: 0,
|
||||||
|
boxSizing: "border-box",
|
||||||
|
fontFamily: "'Segoe UI', Arial, sans-serif",
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
position: 'relative',
|
||||||
|
},
|
||||||
|
login_container: {
|
||||||
|
background: "rgba(255,255,255,.5)",
|
||||||
|
boxShadow: "0 2px 10px rgba(0, 0, 0, 0.1)",
|
||||||
|
width: "350px",
|
||||||
|
height: '100%',
|
||||||
|
position: 'absolute',
|
||||||
|
left: '70%',
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
},
|
||||||
|
form: {
|
||||||
|
height: '100%',
|
||||||
|
width: '100%',
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
flexDirection: 'column',
|
||||||
|
color: "#1a73e8",
|
||||||
|
padding: '40px',
|
||||||
|
},
|
||||||
|
input: {
|
||||||
|
width: '100%',
|
||||||
|
marginTop: '20px',
|
||||||
|
"& > input": {
|
||||||
|
width: "calc(100% - 30px)",
|
||||||
|
padding: "12px 15px",
|
||||||
|
border: "1px solid #ddd",
|
||||||
|
borderRadius: "6px",
|
||||||
|
fontSize: "16px",
|
||||||
|
transition: "border-color 0.3s",
|
||||||
|
|
||||||
|
"&:focus": {
|
||||||
|
outline: "none",
|
||||||
|
borderColor: "#1a73e8",
|
||||||
|
boxShadow: "0 0 0 2px rgba(26, 115, 232, 0.2)",
|
||||||
|
},
|
||||||
|
"&:hover": {
|
||||||
|
borderColor: "#1a73e8",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
button: {
|
||||||
|
marginTop: '20px',
|
||||||
|
width: '100%',
|
||||||
|
"& > button": {
|
||||||
|
width: "100%",
|
||||||
|
padding: "12px",
|
||||||
|
background: "#1a73e8",
|
||||||
|
color: "white",
|
||||||
|
border: "none",
|
||||||
|
borderRadius: "6px",
|
||||||
|
fontSize: "16px",
|
||||||
|
cursor: "pointer",
|
||||||
|
transition: "background 0.3s",
|
||||||
|
"&:hover": {
|
||||||
|
background: "#1557b0",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
inputContainer: {
|
||||||
|
position: 'relative',
|
||||||
|
width: '100%',
|
||||||
|
marginTop: '20px',
|
||||||
|
},
|
||||||
|
inputField: {
|
||||||
|
width: "calc(100% - 52px)",
|
||||||
|
padding: "12px 35px 12px 15px",
|
||||||
|
border: "1px solid #ddd",
|
||||||
|
borderRadius: "6px",
|
||||||
|
fontSize: "16px",
|
||||||
|
transition: "border-color 0.3s",
|
||||||
|
"&:focus": {
|
||||||
|
outline: "none",
|
||||||
|
borderColor: "#1a73e8",
|
||||||
|
boxShadow: "0 0 0 2px rgba(26, 115, 232, 0.2)",
|
||||||
|
},
|
||||||
|
"&:hover": {
|
||||||
|
borderColor: "#1a73e8",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
iconButton: {
|
||||||
|
position: 'absolute',
|
||||||
|
right: '10px',
|
||||||
|
top: '50%',
|
||||||
|
transform: 'translateY(-50%)',
|
||||||
|
background: 'transparent',
|
||||||
|
border: 'none',
|
||||||
|
cursor: 'pointer',
|
||||||
|
color: '#666',
|
||||||
|
"&:hover": {
|
||||||
|
color: '#333',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
export const Login: React.FC = () => {
|
||||||
|
const classes = useClass()
|
||||||
|
const {login} = useAuth()
|
||||||
|
const [username, setUsername] = useState("")
|
||||||
|
const [password, setPassword] = useState("")
|
||||||
|
const [showPassword, setShowPassword] = useState(false)
|
||||||
|
|
||||||
|
const onLogin = async () => {
|
||||||
|
try {
|
||||||
|
await login(username, password)
|
||||||
|
window.location.href = "/"
|
||||||
|
} catch (_e) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return <div className={classes.container}>
|
||||||
|
<CloudBackground/>
|
||||||
|
<div className={classes.login_container}>
|
||||||
|
<div className={classes.form}>
|
||||||
|
<h2>UShare</h2>
|
||||||
|
|
||||||
|
{/* 用户名输入框 */}
|
||||||
|
<div className={classes.inputContainer}>
|
||||||
|
<input
|
||||||
|
className={classes.inputField}
|
||||||
|
placeholder="请输入账号"
|
||||||
|
value={username}
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
/>
|
||||||
|
{username && (
|
||||||
|
<button
|
||||||
|
className={classes.iconButton}
|
||||||
|
onClick={() => setUsername("")}
|
||||||
|
style={{ right: '10px', fontSize: '16px' }}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 密码输入框 */}
|
||||||
|
<div className={classes.inputContainer}>
|
||||||
|
<input
|
||||||
|
className={classes.inputField}
|
||||||
|
placeholder="请输入密码"
|
||||||
|
type={showPassword ? "text" : "password"}
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
className={classes.iconButton}
|
||||||
|
onMouseDown={() => setShowPassword(true)}
|
||||||
|
onMouseUp={() => setShowPassword(false)}
|
||||||
|
onMouseLeave={() => setShowPassword(false)}
|
||||||
|
style={{ right: '10px', fontSize: '12px' }}
|
||||||
|
>
|
||||||
|
{showPassword ? "👁" : "👁"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className={classes.button}>
|
||||||
|
<button onClick={onLogin}>登录</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
@ -3,5 +3,8 @@
|
|||||||
"references": [
|
"references": [
|
||||||
{ "path": "./tsconfig.app.json" },
|
{ "path": "./tsconfig.app.json" },
|
||||||
{ "path": "./tsconfig.node.json" }
|
{ "path": "./tsconfig.node.json" }
|
||||||
]
|
],
|
||||||
|
"compilerOptions": {
|
||||||
|
"allowJs": true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,11 @@ export default defineConfig({
|
|||||||
'/api': {
|
'/api': {
|
||||||
target: 'http://127.0.0.1:9119',
|
target: 'http://127.0.0.1:9119',
|
||||||
changeOrigin: true
|
changeOrigin: true
|
||||||
}
|
},
|
||||||
|
'/ushare': {
|
||||||
|
target: 'http://127.0.0.1:9119',
|
||||||
|
changeOrigin: true
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
10
go.mod
10
go.mod
@ -24,11 +24,15 @@ require (
|
|||||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
|
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
|
||||||
|
github.com/jedib0t/go-pretty/v6 v6.6.7 // indirect
|
||||||
github.com/kevinburke/ssh_config v1.2.0 // indirect
|
github.com/kevinburke/ssh_config v1.2.0 // indirect
|
||||||
|
github.com/matoous/go-nanoid/v2 v2.1.0 // indirect
|
||||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||||
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
||||||
github.com/pjbgf/sha1cd v0.3.0 // indirect
|
github.com/pjbgf/sha1cd v0.3.0 // indirect
|
||||||
|
github.com/rivo/uniseg v0.4.7 // indirect
|
||||||
github.com/sagikazarmark/locafero v0.7.0 // indirect
|
github.com/sagikazarmark/locafero v0.7.0 // indirect
|
||||||
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect
|
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect
|
||||||
github.com/skeema/knownhosts v1.2.2 // indirect
|
github.com/skeema/knownhosts v1.2.2 // indirect
|
||||||
@ -43,9 +47,9 @@ require (
|
|||||||
golang.org/x/crypto v0.32.0 // indirect
|
golang.org/x/crypto v0.32.0 // indirect
|
||||||
golang.org/x/mod v0.17.0 // indirect
|
golang.org/x/mod v0.17.0 // indirect
|
||||||
golang.org/x/net v0.33.0 // indirect
|
golang.org/x/net v0.33.0 // indirect
|
||||||
golang.org/x/sync v0.10.0 // indirect
|
golang.org/x/sync v0.11.0 // indirect
|
||||||
golang.org/x/sys v0.29.0 // indirect
|
golang.org/x/sys v0.30.0 // indirect
|
||||||
golang.org/x/text v0.21.0 // indirect
|
golang.org/x/text v0.22.0 // indirect
|
||||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
|
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
|
||||||
gopkg.in/warnings.v0 v0.1.2 // indirect
|
gopkg.in/warnings.v0 v0.1.2 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
14
go.sum
14
go.sum
@ -48,6 +48,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
|||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
|
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
|
||||||
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
|
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
|
||||||
|
github.com/jedib0t/go-pretty/v6 v6.6.7 h1:m+LbHpm0aIAPLzLbMfn8dc3Ht8MW7lsSO4MPItz/Uuo=
|
||||||
|
github.com/jedib0t/go-pretty/v6 v6.6.7/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU=
|
||||||
github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4=
|
github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4=
|
||||||
github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
|
github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
|
||||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
@ -59,11 +61,15 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
|||||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
github.com/loveuer/nf v0.3.5 h1:DlgTa6Rx8D3/VtH9e0fLGAxmPwSYd7b3nfBltSMuypE=
|
github.com/loveuer/nf v0.3.5 h1:DlgTa6Rx8D3/VtH9e0fLGAxmPwSYd7b3nfBltSMuypE=
|
||||||
github.com/loveuer/nf v0.3.5/go.mod h1:IAq0K1c/mlNQzLBvUzAD1LCWiVlt2GqTMPdDjej3Ryo=
|
github.com/loveuer/nf v0.3.5/go.mod h1:IAq0K1c/mlNQzLBvUzAD1LCWiVlt2GqTMPdDjej3Ryo=
|
||||||
|
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.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
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/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
|
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||||
|
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||||
github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI=
|
github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI=
|
||||||
github.com/onsi/gomega v1.27.10/go.mod h1:RsS8tutOdbdgzbPtzzATp12yT7kM5I5aElG3evPbQ0M=
|
github.com/onsi/gomega v1.27.10/go.mod h1:RsS8tutOdbdgzbPtzzATp12yT7kM5I5aElG3evPbQ0M=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
|
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
|
||||||
@ -74,6 +80,9 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
|||||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
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/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
|
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||||
|
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||||
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
|
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
|
||||||
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
|
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
|
||||||
github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo=
|
github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo=
|
||||||
@ -133,6 +142,7 @@ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJ
|
|||||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
||||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
|
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
@ -149,6 +159,8 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
||||||
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||||
|
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
|
golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
|
||||||
@ -165,6 +177,8 @@ golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
|||||||
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||||
|
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
||||||
|
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||||
|
@ -18,7 +18,10 @@ func Start(ctx context.Context) <-chan struct{} {
|
|||||||
return c.SendStatus(http.StatusOK)
|
return c.SendStatus(http.StatusOK)
|
||||||
})
|
})
|
||||||
|
|
||||||
app.Get("/api/share/fetch", handler.Fetch())
|
app.Get("/ushare/:code", handler.Fetch())
|
||||||
|
app.Put("/api/ushare/:filename", handler.AuthVerify(), handler.ShareNew()) // 获取上传 code, 分片大小
|
||||||
|
app.Post("/api/ushare/:code", handler.ShareUpload()) // 分片上传接口
|
||||||
|
app.Post("/api/uauth/login", handler.AuthLogin())
|
||||||
|
|
||||||
ready := make(chan struct{})
|
ready := make(chan struct{})
|
||||||
ln, err := net.Listen("tcp", opt.Cfg.Address)
|
ln, err := net.Listen("tcp", opt.Cfg.Address)
|
||||||
|
184
internal/controller/meta.go
Normal file
184
internal/controller/meta.go
Normal file
@ -0,0 +1,184 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"github.com/loveuer/nf/nft/log"
|
||||||
|
"github.com/loveuer/ushare/internal/model"
|
||||||
|
"github.com/loveuer/ushare/internal/opt"
|
||||||
|
gonanoid "github.com/matoous/go-nanoid/v2"
|
||||||
|
"github.com/spf13/viper"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type metaInfo struct {
|
||||||
|
f *os.File
|
||||||
|
name string
|
||||||
|
create time.Time
|
||||||
|
last time.Time
|
||||||
|
size int64
|
||||||
|
cursor int64
|
||||||
|
user string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *metaInfo) generateMeta(code string) error {
|
||||||
|
content := fmt.Sprintf("filename=%s\ncreated_at=%d\nsize=%d\nuploader=%s",
|
||||||
|
m.name, m.create.UnixMilli(), m.size, m.user,
|
||||||
|
)
|
||||||
|
|
||||||
|
return os.WriteFile(opt.MetaPath(code), []byte(content), 0644)
|
||||||
|
}
|
||||||
|
|
||||||
|
type meta struct {
|
||||||
|
sync.Mutex
|
||||||
|
ctx context.Context
|
||||||
|
m map[string]*metaInfo
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
MetaManager = &meta{m: make(map[string]*metaInfo)}
|
||||||
|
)
|
||||||
|
|
||||||
|
const letters = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||||
|
|
||||||
|
func (m *meta) New(size int64, filename, ip string) (string, error) {
|
||||||
|
now := time.Now()
|
||||||
|
code, err := gonanoid.Generate(letters, opt.CodeLength)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
f, err := os.Create(opt.FilePath(code))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = f.Truncate(size); err != nil {
|
||||||
|
f.Close()
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
m.Lock()
|
||||||
|
defer m.Unlock()
|
||||||
|
|
||||||
|
m.m[code] = &metaInfo{f: f, name: filename, last: now, size: size, cursor: 0, create: now, user: ip}
|
||||||
|
|
||||||
|
return code, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *meta) Write(code string, start, end int64, reader io.Reader) (total, cursor int64, err error) {
|
||||||
|
m.Lock()
|
||||||
|
defer m.Unlock()
|
||||||
|
|
||||||
|
if _, ok := m.m[code]; !ok {
|
||||||
|
return 0, 0, fmt.Errorf("code not exist")
|
||||||
|
}
|
||||||
|
|
||||||
|
w, err := io.CopyN(m.m[code].f, reader, end-start+1)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
m.m[code].cursor += w
|
||||||
|
m.m[code].last = time.Now()
|
||||||
|
|
||||||
|
total = m.m[code].size
|
||||||
|
cursor = m.m[code].cursor
|
||||||
|
|
||||||
|
if m.m[code].cursor == m.m[code].size {
|
||||||
|
defer delete(m.m, code)
|
||||||
|
if err = m.m[code].generateMeta(code); err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return total, cursor, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *meta) Start(ctx context.Context) {
|
||||||
|
ticker := time.NewTicker(time.Minute)
|
||||||
|
m.ctx = ctx
|
||||||
|
|
||||||
|
// 清理 2 分钟内没有继续上传的 part
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case now := <-ticker.C:
|
||||||
|
for code, info := range m.m {
|
||||||
|
if now.Sub(info.last) > 2*time.Minute {
|
||||||
|
m.Lock()
|
||||||
|
if err := info.f.Close(); err != nil {
|
||||||
|
log.Warn("handler.Meta: [timer] close file failed, file = %s, err = %s", opt.FilePath(code), err.Error())
|
||||||
|
}
|
||||||
|
if err := os.RemoveAll(opt.FilePath(code)); err != nil {
|
||||||
|
log.Warn("handler.Meta: [timer] remove file failed, file = %s, err = %s", opt.FilePath(code), err.Error())
|
||||||
|
}
|
||||||
|
delete(m.m, code)
|
||||||
|
m.Unlock()
|
||||||
|
log.Warn("MetaController: code timeout removed, code = %s", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// 清理一天前的文件
|
||||||
|
go func() {
|
||||||
|
ticker := time.NewTicker(5 * time.Minute)
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case now := <-ticker.C:
|
||||||
|
_ = filepath.Walk(opt.Cfg.DataPath, func(path string, info os.FileInfo, err error) error {
|
||||||
|
if info.IsDir() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
name := filepath.Base(info.Name())
|
||||||
|
if !strings.HasPrefix(name, ".meta.") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
viper.SetConfigFile(path)
|
||||||
|
viper.SetConfigType("env")
|
||||||
|
if err = viper.ReadInConfig(); err != nil {
|
||||||
|
// todo log
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
mi := new(model.Meta)
|
||||||
|
|
||||||
|
if err = viper.Unmarshal(mi); err != nil {
|
||||||
|
// todo log
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
code := strings.TrimPrefix(name, ".meta.")
|
||||||
|
|
||||||
|
if now.Sub(time.UnixMilli(mi.CreatedAt)) > 24*time.Hour {
|
||||||
|
|
||||||
|
log.Debug("controller.meta: file out of date, code = %s, user_key = %s", code, mi.Uploader)
|
||||||
|
|
||||||
|
os.RemoveAll(opt.FilePath(code))
|
||||||
|
os.RemoveAll(path)
|
||||||
|
|
||||||
|
m.Lock()
|
||||||
|
delete(m.m, code)
|
||||||
|
m.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
86
internal/controller/user.go
Normal file
86
internal/controller/user.go
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
package controller
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/loveuer/ushare/internal/model"
|
||||||
|
"github.com/loveuer/ushare/internal/opt"
|
||||||
|
"github.com/loveuer/ushare/internal/pkg/tool"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type userManager struct {
|
||||||
|
sync.Mutex
|
||||||
|
ctx context.Context
|
||||||
|
um map[string]*model.User
|
||||||
|
}
|
||||||
|
|
||||||
|
func (um *userManager) Login(username string, password string) (*model.User, error) {
|
||||||
|
var (
|
||||||
|
now = time.Now()
|
||||||
|
)
|
||||||
|
|
||||||
|
if username != "admin" {
|
||||||
|
return nil, errors.New("账号或密码错误")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !tool.ComparePassword(password, opt.Cfg.Auth) {
|
||||||
|
return nil, errors.New("账号或密码错误")
|
||||||
|
}
|
||||||
|
|
||||||
|
op := &model.User{
|
||||||
|
Id: 1,
|
||||||
|
Username: username,
|
||||||
|
LoginAt: now.Unix(),
|
||||||
|
Token: tool.RandomString(32),
|
||||||
|
}
|
||||||
|
|
||||||
|
um.Lock()
|
||||||
|
defer um.Unlock()
|
||||||
|
um.um[op.Token] = op
|
||||||
|
|
||||||
|
return op, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (um *userManager) Verify(token string) (*model.User, error) {
|
||||||
|
um.Lock()
|
||||||
|
defer um.Unlock()
|
||||||
|
|
||||||
|
op, ok := um.um[token]
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("未登录或凭证已失效, 请重新登录")
|
||||||
|
}
|
||||||
|
|
||||||
|
return op, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (um *userManager) Start(ctx context.Context) {
|
||||||
|
um.ctx = ctx
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
|
||||||
|
ticker := time.NewTicker(time.Minute)
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-um.ctx.Done():
|
||||||
|
return
|
||||||
|
case now := <-ticker.C:
|
||||||
|
um.Lock()
|
||||||
|
for _, op := range um.um {
|
||||||
|
if now.Sub(time.UnixMilli(op.LoginAt)) > 8*time.Hour {
|
||||||
|
delete(um.um, op.Token)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
um.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
UserManager = &userManager{
|
||||||
|
um: make(map[string]*model.User),
|
||||||
|
}
|
||||||
|
)
|
70
internal/handler/auth.go
Normal file
70
internal/handler/auth.go
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/loveuer/nf"
|
||||||
|
"github.com/loveuer/ushare/internal/controller"
|
||||||
|
"github.com/loveuer/ushare/internal/model"
|
||||||
|
"github.com/loveuer/ushare/internal/opt"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AuthVerify() nf.HandlerFunc {
|
||||||
|
tokenFn := func(c *nf.Ctx) (token string) {
|
||||||
|
if token = c.Get("Authorization"); token != "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
token = c.Cookies("ushare")
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
return func(c *nf.Ctx) error {
|
||||||
|
if opt.Cfg.Auth == "" {
|
||||||
|
return c.Next()
|
||||||
|
}
|
||||||
|
|
||||||
|
token := tokenFn(c)
|
||||||
|
if token == "" {
|
||||||
|
return c.Status(http.StatusUnauthorized).JSON(map[string]string{"error": "unauthorized"})
|
||||||
|
}
|
||||||
|
|
||||||
|
op, err := controller.UserManager.Verify(token)
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(http.StatusUnauthorized).JSON(map[string]string{"error": "unauthorized", "msg": err.Error()})
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Locals("user", op)
|
||||||
|
|
||||||
|
return c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func AuthLogin() nf.HandlerFunc {
|
||||||
|
return func(c *nf.Ctx) error {
|
||||||
|
type Req struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
err error
|
||||||
|
req Req
|
||||||
|
op *model.User
|
||||||
|
)
|
||||||
|
|
||||||
|
if err = c.BodyParser(&req); err != nil {
|
||||||
|
return c.Status(http.StatusBadRequest).JSON(map[string]string{"msg": "错误的用户名或密码<1>"})
|
||||||
|
}
|
||||||
|
|
||||||
|
if op, err = controller.UserManager.Login(req.Username, req.Password); err != nil {
|
||||||
|
return c.Status(http.StatusBadRequest).JSON(map[string]string{"msg": err.Error()})
|
||||||
|
}
|
||||||
|
|
||||||
|
header := fmt.Sprintf("ushare=%s; Path=/; Max-Age=%d", op.Token, 8*3600)
|
||||||
|
c.SetHeader("Set-Cookie", header)
|
||||||
|
|
||||||
|
return c.Status(http.StatusOK).JSON(map[string]any{"data": op})
|
||||||
|
}
|
||||||
|
}
|
@ -3,17 +3,23 @@ package handler
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/loveuer/nf"
|
"github.com/loveuer/nf"
|
||||||
|
"github.com/loveuer/nf/nft/log"
|
||||||
|
"github.com/loveuer/ushare/internal/controller"
|
||||||
"github.com/loveuer/ushare/internal/model"
|
"github.com/loveuer/ushare/internal/model"
|
||||||
"github.com/loveuer/ushare/internal/opt"
|
"github.com/loveuer/ushare/internal/opt"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
|
"github.com/spf13/cast"
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Fetch() nf.HandlerFunc {
|
func Fetch() nf.HandlerFunc {
|
||||||
return func(c *nf.Ctx) error {
|
return func(c *nf.Ctx) error {
|
||||||
code := c.Query("code")
|
code := c.Param("code")
|
||||||
|
log.Debug("handler.Fetch: code = %s", code)
|
||||||
info := new(model.Meta)
|
info := new(model.Meta)
|
||||||
_, err := os.Stat(opt.MetaPath(code))
|
_, err := os.Stat(opt.MetaPath(code))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -40,3 +46,73 @@ func Fetch() nf.HandlerFunc {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ShareNew() nf.HandlerFunc {
|
||||||
|
return func(c *nf.Ctx) error {
|
||||||
|
filename := strings.TrimSpace(c.Param("filename"))
|
||||||
|
if filename == "" {
|
||||||
|
return c.Status(http.StatusBadRequest).JSON(map[string]string{"msg": "filename required"})
|
||||||
|
}
|
||||||
|
|
||||||
|
size, err := cast.ToInt64E(c.Get(opt.HeaderSize))
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(http.StatusBadRequest).JSON(map[string]string{"msg": "miss header: " + opt.HeaderSize})
|
||||||
|
}
|
||||||
|
|
||||||
|
code, err := controller.MetaManager.New(size, filename, c.IP())
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(http.StatusInternalServerError).JSON(map[string]string{"msg": ""})
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.Status(http.StatusOK).JSON(map[string]string{"code": code})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ShareUpload() nf.HandlerFunc {
|
||||||
|
rangeValidator := regexp.MustCompile(`^bytes=\d+-\d+$`)
|
||||||
|
return func(c *nf.Ctx) error {
|
||||||
|
code := strings.TrimSpace(c.Param("code"))
|
||||||
|
if len(code) != opt.CodeLength {
|
||||||
|
return c.Status(http.StatusBadRequest).JSON(map[string]string{"msg": "invalid file code"})
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug("handler.ShareUpload: code = %s", code)
|
||||||
|
|
||||||
|
ranger := strings.TrimSpace(c.Get("Range"))
|
||||||
|
if ranger == "" {
|
||||||
|
return c.Status(http.StatusBadRequest).JSON(map[string]string{"msg": "miss header: Range"})
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug("handler.ShareUpload: code = %s, ranger = %s", code, ranger)
|
||||||
|
|
||||||
|
if !rangeValidator.MatchString(ranger) {
|
||||||
|
log.Warn("handler.ShareUpload: invalid range, ranger = %s", ranger)
|
||||||
|
return c.Status(http.StatusBadRequest).JSON(map[string]string{"msg": "Range invalid(1)"})
|
||||||
|
}
|
||||||
|
|
||||||
|
strs := strings.Split(strings.TrimPrefix(ranger, "bytes="), "-")
|
||||||
|
if len(strs) != 2 {
|
||||||
|
return c.Status(http.StatusBadRequest).JSON(map[string]string{"msg": "Range invalid(2)"})
|
||||||
|
}
|
||||||
|
|
||||||
|
start, err := cast.ToInt64E(strs[0])
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(http.StatusBadRequest).JSON(map[string]string{"msg": "Range invalid(3)"})
|
||||||
|
}
|
||||||
|
|
||||||
|
end, err := cast.ToInt64E(strs[1])
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(http.StatusBadRequest).JSON(map[string]string{"msg": "Range invalid(4)"})
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug("handler.ShareUpload: code = %s, start = %d, end = %d", code, start, end)
|
||||||
|
|
||||||
|
total, cursor, err := controller.MetaManager.Write(code, start, end, c.Request.Body)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("handler.ShareUpload: write error: %s", err)
|
||||||
|
return c.Status(http.StatusInternalServerError).JSON(map[string]string{"msg": ""})
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.Status(http.StatusOK).JSON(map[string]any{"size": total, "cursor": cursor})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -4,5 +4,5 @@ type Meta struct {
|
|||||||
Filename string `json:"filename" mapstructure:"filename"`
|
Filename string `json:"filename" mapstructure:"filename"`
|
||||||
CreatedAt int64 `json:"created_at" mapstructure:"created_at"`
|
CreatedAt int64 `json:"created_at" mapstructure:"created_at"`
|
||||||
Size int64 `json:"size" mapstructure:"size"`
|
Size int64 `json:"size" mapstructure:"size"`
|
||||||
UploaderIp string `json:"uploader_ip" mapstructure:"uploader_ip"`
|
Uploader string `json:"uploader" mapstructure:"uploader"`
|
||||||
}
|
}
|
||||||
|
10
internal/model/user.go
Normal file
10
internal/model/user.go
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
package model
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
Id int `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Key string `json:"key"`
|
||||||
|
Password string `json:"-"`
|
||||||
|
LoginAt int64 `json:"login_at"`
|
||||||
|
Token string `json:"token"`
|
||||||
|
}
|
@ -1,11 +1,25 @@
|
|||||||
package opt
|
package opt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/loveuer/nf/nft/log"
|
||||||
|
"github.com/loveuer/ushare/internal/pkg/tool"
|
||||||
|
)
|
||||||
|
|
||||||
type config struct {
|
type config struct {
|
||||||
Debug bool
|
Debug bool
|
||||||
Address string
|
Address string
|
||||||
DataPath string
|
DataPath string
|
||||||
|
Auth string
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
Cfg = &config{}
|
Cfg = &config{}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func Init(_ context.Context) {
|
||||||
|
if Cfg.Auth != "" {
|
||||||
|
Cfg.Auth = tool.NewPassword(Cfg.Auth)
|
||||||
|
log.Debug("opt.Init: encrypted password = %s", Cfg.Auth)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -4,6 +4,8 @@ import "path/filepath"
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
Meta = ".meta."
|
Meta = ".meta."
|
||||||
|
HeaderSize = "X-File-Size"
|
||||||
|
CodeLength = 8
|
||||||
)
|
)
|
||||||
|
|
||||||
func FilePath(code string) string {
|
func FilePath(code string) string {
|
||||||
|
51
internal/pkg/db/client.go
Normal file
51
internal/pkg/db/client.go
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"au99999/internal/opt"
|
||||||
|
"au99999/pkg/tool"
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var Default *Client
|
||||||
|
|
||||||
|
type DBType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
DBTypeSqlite = "sqlite"
|
||||||
|
DBTypeMysql = "mysql"
|
||||||
|
DBTypePostgres = "postgres"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Client struct {
|
||||||
|
ctx context.Context
|
||||||
|
cli *gorm.DB
|
||||||
|
dbType DBType
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Type() DBType {
|
||||||
|
return c.dbType
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Session(ctxs ...context.Context) *gorm.DB {
|
||||||
|
var ctx context.Context
|
||||||
|
if len(ctxs) > 0 && ctxs[0] != nil {
|
||||||
|
ctx = ctxs[0]
|
||||||
|
} else {
|
||||||
|
ctx = tool.Timeout(30)
|
||||||
|
}
|
||||||
|
|
||||||
|
session := c.cli.Session(&gorm.Session{Context: ctx})
|
||||||
|
|
||||||
|
if opt.Cfg.Debug {
|
||||||
|
session = session.Debug()
|
||||||
|
}
|
||||||
|
|
||||||
|
return session
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Close() {
|
||||||
|
d, _ := c.cli.DB()
|
||||||
|
d.Close()
|
||||||
|
}
|
65
internal/pkg/db/new.go
Normal file
65
internal/pkg/db/new.go
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/glebarez/sqlite"
|
||||||
|
"gorm.io/driver/mysql"
|
||||||
|
"gorm.io/driver/postgres"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
const tip = `example:
|
||||||
|
for sqlite -> sqlite::<filepath>
|
||||||
|
sqlite::data.sqlite
|
||||||
|
sqlite::/data/data.db
|
||||||
|
for mysql -> mysql::<gorm_dsn>
|
||||||
|
mysql::user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local
|
||||||
|
for postgres -> postgres::<gorm_dsn>
|
||||||
|
postgres::host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai
|
||||||
|
`
|
||||||
|
|
||||||
|
func New(ctx context.Context, uri string) (*Client, error) {
|
||||||
|
parts := strings.SplitN(uri, "::", 2)
|
||||||
|
|
||||||
|
if len(parts) != 2 {
|
||||||
|
return nil, fmt.Errorf("db.Init: db uri invalid\n%s", tip)
|
||||||
|
}
|
||||||
|
|
||||||
|
c := &Client{}
|
||||||
|
|
||||||
|
var (
|
||||||
|
err error
|
||||||
|
dsn = parts[1]
|
||||||
|
)
|
||||||
|
|
||||||
|
switch parts[0] {
|
||||||
|
case "sqlite":
|
||||||
|
c.dbType = DBTypeSqlite
|
||||||
|
c.cli, err = gorm.Open(sqlite.Open(dsn))
|
||||||
|
case "mysql":
|
||||||
|
c.dbType = DBTypeMysql
|
||||||
|
c.cli, err = gorm.Open(mysql.Open(dsn))
|
||||||
|
case "postgres":
|
||||||
|
c.dbType = DBTypePostgres
|
||||||
|
c.cli, err = gorm.Open(postgres.Open(dsn))
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("db type only support: [sqlite, mysql, postgres], unsupported db type: %s", parts[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("db.Init: open %s with dsn:%s, err: %w", parts[0], dsn, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Init(ctx context.Context, uri string) (err error) {
|
||||||
|
if Default, err = New(ctx, uri); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
38
internal/pkg/tool/ctx.go
Normal file
38
internal/pkg/tool/ctx.go
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
package tool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Timeout(seconds ...int) (ctx context.Context) {
|
||||||
|
var (
|
||||||
|
duration time.Duration
|
||||||
|
)
|
||||||
|
|
||||||
|
if len(seconds) > 0 && seconds[0] > 0 {
|
||||||
|
duration = time.Duration(seconds[0]) * time.Second
|
||||||
|
} else {
|
||||||
|
duration = time.Duration(30) * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, _ = context.WithTimeout(context.Background(), duration)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func TimeoutCtx(ctx context.Context, seconds ...int) context.Context {
|
||||||
|
var (
|
||||||
|
duration time.Duration
|
||||||
|
)
|
||||||
|
|
||||||
|
if len(seconds) > 0 && seconds[0] > 0 {
|
||||||
|
duration = time.Duration(seconds[0]) * time.Second
|
||||||
|
} else {
|
||||||
|
duration = time.Duration(30) * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
nctx, _ := context.WithTimeout(ctx, duration)
|
||||||
|
|
||||||
|
return nctx
|
||||||
|
}
|
50
internal/pkg/tool/human.go
Normal file
50
internal/pkg/tool/human.go
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
package tool
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
func HumanDuration(nano int64) string {
|
||||||
|
duration := float64(nano)
|
||||||
|
unit := "ns"
|
||||||
|
if duration >= 1000 {
|
||||||
|
duration /= 1000
|
||||||
|
unit = "us"
|
||||||
|
}
|
||||||
|
|
||||||
|
if duration >= 1000 {
|
||||||
|
duration /= 1000
|
||||||
|
unit = "ms"
|
||||||
|
}
|
||||||
|
|
||||||
|
if duration >= 1000 {
|
||||||
|
duration /= 1000
|
||||||
|
unit = " s"
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf("%6.2f%s", duration, unit)
|
||||||
|
}
|
||||||
|
|
||||||
|
func HumanSize(size int64) string {
|
||||||
|
const (
|
||||||
|
_ = iota
|
||||||
|
KB = 1 << (10 * iota) // 1 KB = 1024 bytes
|
||||||
|
MB // 1 MB = 1024 KB
|
||||||
|
GB // 1 GB = 1024 MB
|
||||||
|
TB // 1 TB = 1024 GB
|
||||||
|
PB // 1 PB = 1024 TB
|
||||||
|
)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case size >= PB:
|
||||||
|
return fmt.Sprintf("%.2f PB", float64(size)/PB)
|
||||||
|
case size >= TB:
|
||||||
|
return fmt.Sprintf("%.2f TB", float64(size)/TB)
|
||||||
|
case size >= GB:
|
||||||
|
return fmt.Sprintf("%.2f GB", float64(size)/GB)
|
||||||
|
case size >= MB:
|
||||||
|
return fmt.Sprintf("%.2f MB", float64(size)/MB)
|
||||||
|
case size >= KB:
|
||||||
|
return fmt.Sprintf("%.2f KB", float64(size)/KB)
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("%d bytes", size)
|
||||||
|
}
|
||||||
|
}
|
68
internal/pkg/tool/loadash.go
Normal file
68
internal/pkg/tool/loadash.go
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
package tool
|
||||||
|
|
||||||
|
import "math"
|
||||||
|
|
||||||
|
func Map[T, R any](vals []T, fn func(item T, index int) R) []R {
|
||||||
|
var result = make([]R, len(vals))
|
||||||
|
for idx, v := range vals {
|
||||||
|
result[idx] = fn(v, idx)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func Chunk[T any](vals []T, size int) [][]T {
|
||||||
|
if size <= 0 {
|
||||||
|
panic("Second parameter must be greater than 0")
|
||||||
|
}
|
||||||
|
|
||||||
|
chunksNum := len(vals) / size
|
||||||
|
if len(vals)%size != 0 {
|
||||||
|
chunksNum += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
result := make([][]T, 0, chunksNum)
|
||||||
|
|
||||||
|
for i := 0; i < chunksNum; i++ {
|
||||||
|
last := (i + 1) * size
|
||||||
|
if last > len(vals) {
|
||||||
|
last = len(vals)
|
||||||
|
}
|
||||||
|
result = append(result, vals[i*size:last:last])
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// 对 vals 取样 x 个
|
||||||
|
func Sample[T any](vals []T, x int) []T {
|
||||||
|
if x < 0 {
|
||||||
|
panic("Second parameter can't be negative")
|
||||||
|
}
|
||||||
|
|
||||||
|
n := len(vals)
|
||||||
|
if n == 0 {
|
||||||
|
return []T{}
|
||||||
|
}
|
||||||
|
|
||||||
|
if x >= n {
|
||||||
|
return vals
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理x=1的特殊情况
|
||||||
|
if x == 1 {
|
||||||
|
return []T{vals[(n-1)/2]}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算采样步长并生成结果数组
|
||||||
|
step := float64(n-1) / float64(x-1)
|
||||||
|
result := make([]T, x)
|
||||||
|
|
||||||
|
for i := 0; i < x; i++ {
|
||||||
|
// 计算采样位置并四舍五入
|
||||||
|
pos := float64(i) * step
|
||||||
|
index := int(math.Round(pos))
|
||||||
|
result[i] = vals[index]
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
11
internal/pkg/tool/must.go
Normal file
11
internal/pkg/tool/must.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package tool
|
||||||
|
|
||||||
|
import "github.com/loveuer/nf/nft/log"
|
||||||
|
|
||||||
|
func Must(errs ...error) {
|
||||||
|
for _, err := range errs {
|
||||||
|
if err != nil {
|
||||||
|
log.Panic(err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
84
internal/pkg/tool/password.go
Normal file
84
internal/pkg/tool/password.go
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
package tool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"github.com/loveuer/nf/nft/log"
|
||||||
|
"golang.org/x/crypto/pbkdf2"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
EncryptHeader string = "pbkdf2:sha256" // 用户密码加密
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPassword(password string) string {
|
||||||
|
return EncryptPassword(password, RandomString(8), int(RandomInt(50000)+100000))
|
||||||
|
}
|
||||||
|
|
||||||
|
func ComparePassword(in, db string) bool {
|
||||||
|
strs := strings.Split(db, "$")
|
||||||
|
if len(strs) != 3 {
|
||||||
|
log.Error("password in db invalid: %s", db)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
encs := strings.Split(strs[0], ":")
|
||||||
|
if len(encs) != 3 {
|
||||||
|
log.Error("password in db invalid: %s", db)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
encIteration, err := strconv.Atoi(encs[2])
|
||||||
|
if err != nil {
|
||||||
|
log.Error("password in db invalid: %s, convert iter err: %s", db, err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return EncryptPassword(in, strs[1], encIteration) == db
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncryptPassword(password, salt string, iter int) string {
|
||||||
|
hash := pbkdf2.Key([]byte(password), []byte(salt), iter, 32, sha256.New)
|
||||||
|
encrypted := hex.EncodeToString(hash)
|
||||||
|
return fmt.Sprintf("%s:%d$%s$%s", EncryptHeader, iter, salt, encrypted)
|
||||||
|
}
|
||||||
|
|
||||||
|
func CheckPassword(password string) error {
|
||||||
|
if len(password) < 8 || len(password) > 32 {
|
||||||
|
return errors.New("密码长度不符合")
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
err error
|
||||||
|
match bool
|
||||||
|
patternList = []string{`[0-9]+`, `[a-z]+`, `[A-Z]+`, `[!@#%]+`} //, `[~!@#$%^&*?_-]+`}
|
||||||
|
matchAccount = 0
|
||||||
|
tips = []string{"缺少数字", "缺少小写字母", "缺少大写字母", "缺少'!@#%'"}
|
||||||
|
locktips = make([]string, 0)
|
||||||
|
)
|
||||||
|
|
||||||
|
for idx, pattern := range patternList {
|
||||||
|
match, err = regexp.MatchString(pattern, password)
|
||||||
|
if err != nil {
|
||||||
|
log.Warn("regex match string err, reg_str: %s, err: %v", pattern, err)
|
||||||
|
return errors.New("密码强度不够")
|
||||||
|
}
|
||||||
|
|
||||||
|
if match {
|
||||||
|
matchAccount++
|
||||||
|
} else {
|
||||||
|
locktips = append(locktips, tips[idx])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if matchAccount < 3 {
|
||||||
|
return fmt.Errorf("密码强度不够, 可能 %s", strings.Join(locktips, ", "))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
20
internal/pkg/tool/password_test.go
Normal file
20
internal/pkg/tool/password_test.go
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
package tool
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestEncPassword(t *testing.T) {
|
||||||
|
password := "123456"
|
||||||
|
|
||||||
|
result := EncryptPassword(password, RandomString(8), 50000)
|
||||||
|
|
||||||
|
t.Logf("sum => %s", result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPassword(t *testing.T) {
|
||||||
|
p := "wahaha@123"
|
||||||
|
p = NewPassword(p)
|
||||||
|
t.Logf("password => %s", p)
|
||||||
|
|
||||||
|
result := ComparePassword("wahaha@123", p)
|
||||||
|
t.Logf("compare result => %v", result)
|
||||||
|
}
|
54
internal/pkg/tool/random.go
Normal file
54
internal/pkg/tool/random.go
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
package tool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"math/big"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
letters = []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
||||||
|
letterNum = []byte("0123456789")
|
||||||
|
letterLow = []byte("abcdefghijklmnopqrstuvwxyz")
|
||||||
|
letterCap = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
||||||
|
letterSyb = []byte("!@#$%^&*()_+-=")
|
||||||
|
)
|
||||||
|
|
||||||
|
func RandomInt(max int64) int64 {
|
||||||
|
num, _ := rand.Int(rand.Reader, big.NewInt(max))
|
||||||
|
return num.Int64()
|
||||||
|
}
|
||||||
|
|
||||||
|
func RandomString(length int) string {
|
||||||
|
result := make([]byte, length)
|
||||||
|
for i := 0; i < length; i++ {
|
||||||
|
num, _ := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
|
||||||
|
result[i] = letters[num.Int64()]
|
||||||
|
}
|
||||||
|
return string(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func RandomPassword(length int, withSymbol bool) string {
|
||||||
|
result := make([]byte, length)
|
||||||
|
kind := 3
|
||||||
|
if withSymbol {
|
||||||
|
kind++
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < length; i++ {
|
||||||
|
switch i % kind {
|
||||||
|
case 0:
|
||||||
|
num, _ := rand.Int(rand.Reader, big.NewInt(int64(len(letterNum))))
|
||||||
|
result[i] = letterNum[num.Int64()]
|
||||||
|
case 1:
|
||||||
|
num, _ := rand.Int(rand.Reader, big.NewInt(int64(len(letterLow))))
|
||||||
|
result[i] = letterLow[num.Int64()]
|
||||||
|
case 2:
|
||||||
|
num, _ := rand.Int(rand.Reader, big.NewInt(int64(len(letterCap))))
|
||||||
|
result[i] = letterCap[num.Int64()]
|
||||||
|
case 3:
|
||||||
|
num, _ := rand.Int(rand.Reader, big.NewInt(int64(len(letterSyb))))
|
||||||
|
result[i] = letterSyb[num.Int64()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return string(result)
|
||||||
|
}
|
124
internal/pkg/tool/table.go
Normal file
124
internal/pkg/tool/table.go
Normal file
@ -0,0 +1,124 @@
|
|||||||
|
package tool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"github.com/jedib0t/go-pretty/v6/table"
|
||||||
|
"github.com/loveuer/nf/nft/log"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TablePrinter(data any, writers ...io.Writer) {
|
||||||
|
var w io.Writer = os.Stdout
|
||||||
|
if len(writers) > 0 && writers[0] != nil {
|
||||||
|
w = writers[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
t := table.NewWriter()
|
||||||
|
structPrinter(t, "", data)
|
||||||
|
_, _ = fmt.Fprintln(w, t.Render())
|
||||||
|
}
|
||||||
|
|
||||||
|
func structPrinter(w table.Writer, prefix string, item any) {
|
||||||
|
Start:
|
||||||
|
rv := reflect.ValueOf(item)
|
||||||
|
if rv.IsZero() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for rv.Type().Kind() == reflect.Pointer {
|
||||||
|
rv = rv.Elem()
|
||||||
|
}
|
||||||
|
|
||||||
|
switch rv.Type().Kind() {
|
||||||
|
case reflect.Invalid,
|
||||||
|
reflect.Uintptr,
|
||||||
|
reflect.Chan,
|
||||||
|
reflect.Func,
|
||||||
|
reflect.UnsafePointer:
|
||||||
|
case reflect.Bool,
|
||||||
|
reflect.Int,
|
||||||
|
reflect.Int8,
|
||||||
|
reflect.Int16,
|
||||||
|
reflect.Int32,
|
||||||
|
reflect.Int64,
|
||||||
|
reflect.Uint,
|
||||||
|
reflect.Uint8,
|
||||||
|
reflect.Uint16,
|
||||||
|
reflect.Uint32,
|
||||||
|
reflect.Uint64,
|
||||||
|
reflect.Float32,
|
||||||
|
reflect.Float64,
|
||||||
|
reflect.Complex64,
|
||||||
|
reflect.Complex128,
|
||||||
|
reflect.Interface:
|
||||||
|
w.AppendRow(table.Row{strings.TrimPrefix(prefix, "."), rv.Interface()})
|
||||||
|
case reflect.String:
|
||||||
|
val := rv.String()
|
||||||
|
if len(val) <= 160 {
|
||||||
|
w.AppendRow(table.Row{strings.TrimPrefix(prefix, "."), val})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.AppendRow(table.Row{strings.TrimPrefix(prefix, "."), val[0:64] + "..." + val[len(val)-64:]})
|
||||||
|
case reflect.Array, reflect.Slice:
|
||||||
|
for i := 0; i < rv.Len(); i++ {
|
||||||
|
p := strings.Join([]string{prefix, fmt.Sprintf("[%d]", i)}, ".")
|
||||||
|
structPrinter(w, p, rv.Index(i).Interface())
|
||||||
|
}
|
||||||
|
case reflect.Map:
|
||||||
|
for _, k := range rv.MapKeys() {
|
||||||
|
structPrinter(w, fmt.Sprintf("%s.{%v}", prefix, k), rv.MapIndex(k).Interface())
|
||||||
|
}
|
||||||
|
case reflect.Pointer:
|
||||||
|
goto Start
|
||||||
|
case reflect.Struct:
|
||||||
|
for i := 0; i < rv.NumField(); i++ {
|
||||||
|
p := fmt.Sprintf("%s.%s", prefix, rv.Type().Field(i).Name)
|
||||||
|
field := rv.Field(i)
|
||||||
|
|
||||||
|
//log.Debug("TablePrinter: prefix: %s, field: %v", p, rv.Field(i))
|
||||||
|
|
||||||
|
if !field.CanInterface() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
structPrinter(w, p, field.Interface())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TableMapPrinter(data []byte) {
|
||||||
|
m := make(map[string]any)
|
||||||
|
if err := json.Unmarshal(data, &m); err != nil {
|
||||||
|
log.Warn(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
t := table.NewWriter()
|
||||||
|
addRow(t, "", m)
|
||||||
|
fmt.Println(t.Render())
|
||||||
|
}
|
||||||
|
|
||||||
|
func addRow(w table.Writer, prefix string, m any) {
|
||||||
|
rv := reflect.ValueOf(m)
|
||||||
|
switch rv.Type().Kind() {
|
||||||
|
case reflect.Map:
|
||||||
|
for _, k := range rv.MapKeys() {
|
||||||
|
key := k.String()
|
||||||
|
if prefix != "" {
|
||||||
|
key = strings.Join([]string{prefix, k.String()}, ".")
|
||||||
|
}
|
||||||
|
addRow(w, key, rv.MapIndex(k).Interface())
|
||||||
|
}
|
||||||
|
case reflect.Slice, reflect.Array:
|
||||||
|
for i := 0; i < rv.Len(); i++ {
|
||||||
|
addRow(w, fmt.Sprintf("%s[%d]", prefix, i), rv.Index(i).Interface())
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
w.AppendRow(table.Row{prefix, m})
|
||||||
|
}
|
||||||
|
}
|
73
internal/pkg/tool/tools.go
Normal file
73
internal/pkg/tool/tools.go
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
package tool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Min[T ~int | ~uint | ~int8 | ~uint8 | ~int16 | ~uint16 | ~int32 | ~uint32 | ~int64 | ~uint64 | ~float32 | ~float64](a, b T) T {
|
||||||
|
if a <= b {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func Mins[T ~int | ~uint | ~int8 | ~uint8 | ~int16 | ~uint16 | ~int32 | ~uint32 | ~int64 | ~uint64 | ~float32 | ~float64](vals ...T) T {
|
||||||
|
var val T
|
||||||
|
|
||||||
|
if len(vals) == 0 {
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
|
||||||
|
val = vals[0]
|
||||||
|
|
||||||
|
for _, item := range vals[1:] {
|
||||||
|
if item < val {
|
||||||
|
val = item
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
|
||||||
|
func Max[T ~int | ~uint | ~int8 | ~uint8 | ~int16 | ~uint16 | ~int32 | ~uint32 | ~int64 | ~uint64 | ~float32 | ~float64](a, b T) T {
|
||||||
|
if a >= b {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func Maxs[T ~int | ~uint | ~int8 | ~uint8 | ~int16 | ~uint16 | ~int32 | ~uint32 | ~int64 | ~uint64 | ~float32 | ~float64](vals ...T) T {
|
||||||
|
var val T
|
||||||
|
|
||||||
|
if len(vals) == 0 {
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range vals {
|
||||||
|
if item > val {
|
||||||
|
val = item
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
|
||||||
|
func Sum[T ~int | ~uint | ~int8 | ~uint8 | ~int16 | ~uint16 | ~int32 | ~uint32 | ~int64 | ~uint64 | ~float32 | ~float64](vals ...T) T {
|
||||||
|
var sum T = 0
|
||||||
|
for i := range vals {
|
||||||
|
sum += vals[i]
|
||||||
|
}
|
||||||
|
return sum
|
||||||
|
}
|
||||||
|
|
||||||
|
func Percent(val, minVal, maxVal, minPercent, maxPercent float64) string {
|
||||||
|
return fmt.Sprintf(
|
||||||
|
"%d%%",
|
||||||
|
int(math.Round(
|
||||||
|
((val-minVal)/(maxVal-minVal)*(maxPercent-minPercent)+minPercent)*100,
|
||||||
|
)),
|
||||||
|
)
|
||||||
|
}
|
70
internal/pkg/tool/tools_test.go
Normal file
70
internal/pkg/tool/tools_test.go
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
package tool
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestPercent(t *testing.T) {
|
||||||
|
type args struct {
|
||||||
|
val float64
|
||||||
|
minVal float64
|
||||||
|
maxVal float64
|
||||||
|
minPercent float64
|
||||||
|
maxPercent float64
|
||||||
|
}
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
args args
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "case 1",
|
||||||
|
args: args{
|
||||||
|
val: 0.5,
|
||||||
|
minVal: 0,
|
||||||
|
maxVal: 1,
|
||||||
|
minPercent: 0,
|
||||||
|
maxPercent: 1,
|
||||||
|
},
|
||||||
|
want: "50%",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "case 2",
|
||||||
|
args: args{
|
||||||
|
val: 0.3,
|
||||||
|
minVal: 0.1,
|
||||||
|
maxVal: 0.6,
|
||||||
|
minPercent: 0,
|
||||||
|
maxPercent: 1,
|
||||||
|
},
|
||||||
|
want: "40%",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "case 3",
|
||||||
|
args: args{
|
||||||
|
val: 700,
|
||||||
|
minVal: 700,
|
||||||
|
maxVal: 766,
|
||||||
|
minPercent: 0.1,
|
||||||
|
maxPercent: 0.7,
|
||||||
|
},
|
||||||
|
want: "10%",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "case 4",
|
||||||
|
args: args{
|
||||||
|
val: 766,
|
||||||
|
minVal: 700,
|
||||||
|
maxVal: 766,
|
||||||
|
minPercent: 0.1,
|
||||||
|
maxPercent: 0.7,
|
||||||
|
},
|
||||||
|
want: "70%",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := Percent(tt.args.val, tt.args.minVal, tt.args.maxVal, tt.args.minPercent, tt.args.maxPercent); got != tt.want {
|
||||||
|
t.Errorf("Percent() = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
13
main.go
13
main.go
@ -3,7 +3,9 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"flag"
|
"flag"
|
||||||
|
"github.com/loveuer/nf/nft/log"
|
||||||
"github.com/loveuer/ushare/internal/api"
|
"github.com/loveuer/ushare/internal/api"
|
||||||
|
"github.com/loveuer/ushare/internal/controller"
|
||||||
"github.com/loveuer/ushare/internal/opt"
|
"github.com/loveuer/ushare/internal/opt"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"syscall"
|
"syscall"
|
||||||
@ -11,15 +13,24 @@ import (
|
|||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
flag.BoolVar(&opt.Cfg.Debug, "debug", false, "debug mode")
|
flag.BoolVar(&opt.Cfg.Debug, "debug", false, "debug mode")
|
||||||
flag.StringVar(&opt.Cfg.Address, "address", "0.0.0.0:80", "")
|
flag.StringVar(&opt.Cfg.Address, "address", "0.0.0.0:9119", "")
|
||||||
flag.StringVar(&opt.Cfg.DataPath, "data", "/data", "")
|
flag.StringVar(&opt.Cfg.DataPath, "data", "/data", "")
|
||||||
|
flag.StringVar(&opt.Cfg.Auth, "auth", "", "auth required(admin, password)")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
|
if opt.Cfg.Debug {
|
||||||
|
log.SetLogLevel(log.LogLevelDebug)
|
||||||
|
log.Debug("start server with debug mode")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
|
opt.Init(ctx)
|
||||||
|
controller.UserManager.Start(ctx)
|
||||||
|
controller.MetaManager.Start(ctx)
|
||||||
api.Start(ctx)
|
api.Start(ctx)
|
||||||
|
|
||||||
<-ctx.Done()
|
<-ctx.Done()
|
||||||
|
166
page/login.html
Normal file
166
page/login.html
Normal file
@ -0,0 +1,166 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Login Page</title>
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
background-color: #f5f5f5;
|
||||||
|
height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-container {
|
||||||
|
width: 100%;
|
||||||
|
padding: 20px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-box {
|
||||||
|
background: white;
|
||||||
|
padding: 40px;
|
||||||
|
border-radius: 10px;
|
||||||
|
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
|
||||||
|
width: 100%;
|
||||||
|
max-width: 400px;
|
||||||
|
}
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
text-align: center;
|
||||||
|
color: #333;
|
||||||
|
margin-bottom: 30px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
color: #555;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="text"],
|
||||||
|
input[type="password"] {
|
||||||
|
width: 100%;
|
||||||
|
padding: 12px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 5px;
|
||||||
|
font-size: 16px;
|
||||||
|
transition: border-color 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="text"]:focus,
|
||||||
|
input[type="password"]:focus {
|
||||||
|
border-color: #4CAF50;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-options {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remember-me {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.forgot-password {
|
||||||
|
color: #4CAF50;
|
||||||
|
text-decoration: none;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.forgot-password:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-button {
|
||||||
|
width: 100%;
|
||||||
|
padding: 12px;
|
||||||
|
background-color: #4CAF50;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 5px;
|
||||||
|
font-size: 16px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-button:hover {
|
||||||
|
background-color: #45a049;
|
||||||
|
}
|
||||||
|
|
||||||
|
.signup-link {
|
||||||
|
text-align: center;
|
||||||
|
margin-top: 20px;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.signup-link a {
|
||||||
|
color: #4CAF50;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.signup-link a:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Responsive Design */
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.login-box {
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-options {
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="login-container">
|
||||||
|
<div class="login-box">
|
||||||
|
<h2>Welcome Back</h2>
|
||||||
|
<form class="login-form">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="username">Username</label>
|
||||||
|
<input type="text" id="username" name="username" required>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="password">Password</label>
|
||||||
|
<input type="password" id="password" name="password" required>
|
||||||
|
</div>
|
||||||
|
<div class="form-options">
|
||||||
|
<label class="remember-me">
|
||||||
|
<input type="checkbox"> Remember me
|
||||||
|
</label>
|
||||||
|
<a href="#" class="forgot-password">Forgot Password?</a>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="login-button">Log In</button>
|
||||||
|
</form>
|
||||||
|
<p class="signup-link">Don't have an account? <a href="#">Sign up</a></p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
Reference in New Issue
Block a user