mirror of
https://github.com/luckjiawei/podux.git
synced 2026-11-30 00:56:47 +00:00
🎉 hello frpchub!!!
This commit is contained in:
commit
119b53c516
122 files changed
+20770
No files matched your search
+62
@@ -0,0 +1,62 @@
|
|||||||
|
# Binaries for programs and plugins
|
||||||
|
*.exe
|
||||||
|
*.exe~
|
||||||
|
*.dll
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
|
|
||||||
|
# Test binary, built with `go test -c`
|
||||||
|
*.test
|
||||||
|
|
||||||
|
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||||
|
*.out
|
||||||
|
|
||||||
|
# Dependency directories (remove the comment below to include it)
|
||||||
|
# vendor/
|
||||||
|
|
||||||
|
# Go workspace file
|
||||||
|
go.work
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Build output
|
||||||
|
/bin/
|
||||||
|
/dist/
|
||||||
|
/pb_public/
|
||||||
|
|
||||||
|
# PocketBase
|
||||||
|
/pb_data/
|
||||||
|
node_modules
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
|
__debug*
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship made available under
|
||||||
|
the License, as indicated by a copyright notice that is included in
|
||||||
|
or attached to the work (an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
||||||
|
in the Work by the copyright owner or by an individual or Legal Entity
|
||||||
|
authorized to submit on behalf of the copyright owner. For the purposes
|
||||||
|
of this definition, "submitted" means any form of electronic, verbal,
|
||||||
|
or written communication sent to the Licensor or its representatives,
|
||||||
|
including but not limited to communication on electronic mailing lists,
|
||||||
|
source code control systems, and issue tracking systems that are managed
|
||||||
|
by, or on behalf of, the Licensor for the purpose of discussing and
|
||||||
|
improving the Work, but excluding communication that is conspicuously
|
||||||
|
marked or otherwise designated in writing by the copyright owner as
|
||||||
|
"Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
||||||
|
whom a Contribution has been received by the Licensor and subsequently
|
||||||
|
incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a cross-claim
|
||||||
|
or counterclaim in a lawsuit) alleging that the Work or any
|
||||||
|
Contribution embodied within the Work constitutes direct or contributory
|
||||||
|
patent infringement, then any patent licenses granted to You under
|
||||||
|
this License for that Work shall terminate as of the date such
|
||||||
|
litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, You must include a readable copy of the
|
||||||
|
attribution notices contained within such NOTICE file, in
|
||||||
|
at least one of the following places: within a NOTICE text
|
||||||
|
file distributed as part of the Derivative Works; within
|
||||||
|
the Source form or documentation, if provided along with the
|
||||||
|
Derivative Works; or, within a display generated by the
|
||||||
|
Derivative Works, if and wherever such third-party notices
|
||||||
|
normally appear. The contents of the NOTICE file are for
|
||||||
|
informational purposes only and do not modify the License.
|
||||||
|
You may add Your own attribution notices within Derivative
|
||||||
|
Works that You distribute, alongside or as an addition to
|
||||||
|
the NOTICE text from the Work, provided that such additional
|
||||||
|
attribution notices cannot be construed as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own license statement for Your modifications and
|
||||||
|
may provide additional grant of rights to use, copy, modify, merge,
|
||||||
|
publish, distribute, sublicense, and/or sell copies of the
|
||||||
|
Contribution, and to permit persons to whom the Software is
|
||||||
|
furnished to do so.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or reproducing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or exemplary damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or all other
|
||||||
|
commercial damages or losses), even if such Contributor has been
|
||||||
|
advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format in use. Also, it is recommended
|
||||||
|
that a file or directory name and description of purpose be included
|
||||||
|
on the same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright 2026 刘嘉伟
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
<a name="readme-top"></a>
|
||||||
|
|
||||||
|
<!-- PROJECT SHIELDS -->
|
||||||
|
[![Forks][forks-shield]][forks-url]
|
||||||
|
[![Stargazers][stars-shield]][stars-url]
|
||||||
|
[![Issues][issues-shield]][issues-url]
|
||||||
|
[![MIT License][license-shield]][license-url]
|
||||||
|
<!-- PROJECT LOGO -->
|
||||||
|
<br />
|
||||||
|
<div align="center">
|
||||||
|
<a href="https://github.com/luckjiawei/frpc-hub">
|
||||||
|
<img src="site/src/assets/logo.png" alt="Logo" width="140">
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<h3 align="center">Frpc-Hub</h3>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
🎉 Cross-platform desktop client for FRP, visual configuration, easily achieve intranet penetration!
|
||||||
|
<br />
|
||||||
|
Support all frp versions / Auto-start / Visual configuration / Free and open source
|
||||||
|
</p>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
## Milestones
|
||||||
|
|
||||||
|
- 2026-02-28: Released v0.0.1
|
||||||
|
|
||||||
|
|
||||||
|
## Star History
|
||||||
|
|
||||||
|
[](https://www.star-history.com/#luckjiawei/frpc-desktop&Date)
|
||||||
|
|
||||||
|
<!-- MARKDOWN LINKS & IMAGES -->
|
||||||
|
|
||||||
|
[forks-shield]: https://img.shields.io/github/forks/luckjiawei/frpc-hub.svg?style=for-the-badge
|
||||||
|
|
||||||
|
[forks-url]: https://github.com/luckjiawei/frpc-hub/network/members
|
||||||
|
|
||||||
|
[stars-shield]: https://img.shields.io/github/stars/luckjiawei/frpc-hub.svg?style=for-the-badge
|
||||||
|
|
||||||
|
[stars-url]: https://github.com/luckjiawei/frpc-hub/stargazers
|
||||||
|
|
||||||
|
[issues-shield]: https://img.shields.io/github/issues/luckjiawei/frpc-hub.svg?style=for-the-badge
|
||||||
|
|
||||||
|
[issues-url]: https://github.com/luckjiawei/frpc-hub/issues
|
||||||
|
|
||||||
|
[license-shield]: https://img.shields.io/github/license/luckjiawei/frpc-hub.svg?style=for-the-badge
|
||||||
|
|
||||||
|
[license-url]: https://github.com/luckjiawei/frpc-hub/blob/master/LICENSE
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# Git files
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.gitattributes
|
||||||
|
|
||||||
|
# IDE files
|
||||||
|
.vscode
|
||||||
|
.idea
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# Build output
|
||||||
|
dist/
|
||||||
|
build/dist/
|
||||||
|
*.tar.gz
|
||||||
|
*.zip
|
||||||
|
frpc-hub
|
||||||
|
frpc-hub.exe
|
||||||
|
|
||||||
|
# Dependencies
|
||||||
|
node_modules/
|
||||||
|
site/node_modules/
|
||||||
|
site/dist/
|
||||||
|
|
||||||
|
# Database and runtime data
|
||||||
|
pb_data/
|
||||||
|
*.db
|
||||||
|
*.db-shm
|
||||||
|
*.db-wal
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
*.log
|
||||||
|
logs/
|
||||||
|
|
||||||
|
# OS files
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Temporary files
|
||||||
|
*.tmp
|
||||||
|
*.temp
|
||||||
|
tmp/
|
||||||
|
temp/
|
||||||
|
|
||||||
|
# Environment files
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
|
|
||||||
|
# Documentation
|
||||||
|
*.md
|
||||||
|
!README.md
|
||||||
|
docs/
|
||||||
|
|
||||||
|
# CI/CD
|
||||||
|
.github/
|
||||||
|
.gitlab-ci.yml
|
||||||
|
.travis.yml
|
||||||
|
|
||||||
|
# Test files
|
||||||
|
*_test.go
|
||||||
|
test/
|
||||||
|
tests/
|
||||||
|
|
||||||
|
# Claude files
|
||||||
|
.claude/
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Minimal .dockerignore for runtime Docker build
|
||||||
|
# Only the dist/ directory (pre-built binaries) is needed
|
||||||
|
*
|
||||||
|
!dist/
|
||||||
|
!dist/frpc-hub-linux-*
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# Multi-stage Dockerfile for frpc-hub
|
||||||
|
# Stage 1: Build frontend
|
||||||
|
FROM node:20-alpine AS frontend-builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy frontend source
|
||||||
|
COPY site/package*.json site/pnpm-lock.yaml* ./
|
||||||
|
# Install dependencies (try pnpm first, fallback to npm)
|
||||||
|
RUN if [ -f pnpm-lock.yaml ]; then \
|
||||||
|
npm install -g pnpm && pnpm install; \
|
||||||
|
else \
|
||||||
|
npm install; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
COPY site/ ./
|
||||||
|
RUN if [ -f pnpm-lock.yaml ]; then \
|
||||||
|
pnpm run build; \
|
||||||
|
else \
|
||||||
|
npm run build; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Stage 2: Build backend
|
||||||
|
FROM golang:1.25-alpine AS backend-builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install build dependencies
|
||||||
|
RUN apk add --no-cache git
|
||||||
|
|
||||||
|
# Copy go mod files
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
|
||||||
|
# Copy source code
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Copy built frontend from previous stage
|
||||||
|
COPY --from=frontend-builder /app/dist ./pb_public
|
||||||
|
|
||||||
|
# Build the application
|
||||||
|
ARG VERSION=dev
|
||||||
|
ARG BUILD_TIME
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux go build \
|
||||||
|
-trimpath \
|
||||||
|
-ldflags "-s -w -X main.Version=${VERSION} -X main.BuildTime=${BUILD_TIME}" \
|
||||||
|
-o frpc-hub \
|
||||||
|
main.go
|
||||||
|
|
||||||
|
# Stage 3: Final runtime image
|
||||||
|
FROM alpine:latest
|
||||||
|
|
||||||
|
# Install runtime dependencies
|
||||||
|
RUN apk add --no-cache \
|
||||||
|
ca-certificates \
|
||||||
|
tzdata \
|
||||||
|
&& rm -rf /var/cache/apk/*
|
||||||
|
|
||||||
|
# Create non-root user
|
||||||
|
RUN addgroup -g 1000 frpchub && \
|
||||||
|
adduser -D -u 1000 -G frpchub frpchub
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy binary from builder
|
||||||
|
COPY --from=backend-builder /app/frpc-hub .
|
||||||
|
|
||||||
|
# Create data directory
|
||||||
|
RUN mkdir -p /app/pb_data && \
|
||||||
|
chown -R frpchub:frpchub /app
|
||||||
|
|
||||||
|
# Switch to non-root user
|
||||||
|
USER frpchub
|
||||||
|
|
||||||
|
# Expose port
|
||||||
|
EXPOSE 8090
|
||||||
|
|
||||||
|
# Health check
|
||||||
|
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||||
|
CMD wget --no-verbose --tries=1 --spider http://localhost:8090/api/health || exit 1
|
||||||
|
|
||||||
|
# Run the application
|
||||||
|
ENTRYPOINT ["/app/frpc-hub"]
|
||||||
|
CMD ["serve", "--http", "0.0.0.0:8090"]
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Runtime-only Dockerfile - uses pre-built binaries from CI
|
||||||
|
# Used in the second stage of the CI pipeline (after build:binary)
|
||||||
|
FROM alpine:latest
|
||||||
|
|
||||||
|
ARG TARGETARCH
|
||||||
|
|
||||||
|
RUN apk add --no-cache \
|
||||||
|
ca-certificates \
|
||||||
|
tzdata \
|
||||||
|
&& rm -rf /var/cache/apk/*
|
||||||
|
|
||||||
|
RUN addgroup -g 1000 frpchub && \
|
||||||
|
adduser -D -u 1000 -G frpchub frpchub
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy pre-built binary for target architecture
|
||||||
|
COPY dist/frpc-hub-linux-${TARGETARCH} ./frpc-hub
|
||||||
|
RUN chmod +x ./frpc-hub
|
||||||
|
|
||||||
|
RUN mkdir -p /app/pb_data && \
|
||||||
|
chown -R frpchub:frpchub /app
|
||||||
|
|
||||||
|
USER frpchub
|
||||||
|
|
||||||
|
EXPOSE 8090
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||||
|
CMD wget --no-verbose --tries=1 --spider http://localhost:8090/api/health || exit 1
|
||||||
|
|
||||||
|
ENTRYPOINT ["/app/frpc-hub"]
|
||||||
|
CMD ["serve", "--http", "0.0.0.0:8090"]
|
||||||
Executable
+235
@@ -0,0 +1,235 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Build script for frpc-hub - Multi-architecture support
|
||||||
|
# Usage: ./build.sh [options]
|
||||||
|
# Options:
|
||||||
|
# --arch <arch> Build for specific architecture (linux-amd64, linux-arm64, darwin-amd64, darwin-arm64, windows-amd64, all)
|
||||||
|
# --output <dir> Output directory (default: ./dist)
|
||||||
|
# --skip-frontend Skip frontend build
|
||||||
|
# --help Show this help message
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
APP_NAME="frpc-hub"
|
||||||
|
VERSION=${VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo "dev")}
|
||||||
|
BUILD_TIME=$(date -u '+%Y-%m-%d_%H:%M:%S')
|
||||||
|
SITE_DIR="../site"
|
||||||
|
PUBLIC_DIR="../pb_public"
|
||||||
|
OUTPUT_DIR="./dist"
|
||||||
|
SKIP_FRONTEND=false
|
||||||
|
|
||||||
|
# Color output
|
||||||
|
RED='\033[0;31m'
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
YELLOW='\033[1;33m'
|
||||||
|
BLUE='\033[0;34m'
|
||||||
|
NC='\033[0m' # No Color
|
||||||
|
|
||||||
|
# Platform configurations
|
||||||
|
# Format: GOOS-GOARCH
|
||||||
|
PLATFORMS=(
|
||||||
|
"linux-amd64"
|
||||||
|
"linux-arm64"
|
||||||
|
"linux-arm"
|
||||||
|
"darwin-amd64"
|
||||||
|
"darwin-arm64"
|
||||||
|
"windows-amd64"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Parse command line arguments
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case $1 in
|
||||||
|
--arch)
|
||||||
|
SELECTED_ARCH="$2"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
--output)
|
||||||
|
OUTPUT_DIR="$2"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
--skip-frontend)
|
||||||
|
SKIP_FRONTEND=true
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
--help)
|
||||||
|
echo "Usage: $0 [options]"
|
||||||
|
echo "Options:"
|
||||||
|
echo " --arch <arch> Build for specific architecture (linux-amd64, linux-arm64, darwin-amd64, darwin-arm64, windows-amd64, all)"
|
||||||
|
echo " --output <dir> Output directory (default: ./dist)"
|
||||||
|
echo " --skip-frontend Skip frontend build"
|
||||||
|
echo " --help Show this help message"
|
||||||
|
echo ""
|
||||||
|
echo "Available architectures:"
|
||||||
|
for platform in "${PLATFORMS[@]}"; do
|
||||||
|
echo " - $platform"
|
||||||
|
done
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo -e "${RED}Unknown option: $1${NC}"
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# Functions
|
||||||
|
print_header() {
|
||||||
|
echo -e "${BLUE}=========================================="
|
||||||
|
echo -e "$1"
|
||||||
|
echo -e "==========================================${NC}"
|
||||||
|
}
|
||||||
|
|
||||||
|
print_info() {
|
||||||
|
echo -e "${GREEN}[INFO]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
print_warn() {
|
||||||
|
echo -e "${YELLOW}[WARN]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
print_error() {
|
||||||
|
echo -e "${RED}[ERROR]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Build frontend
|
||||||
|
build_frontend() {
|
||||||
|
if [ "$SKIP_FRONTEND" = true ]; then
|
||||||
|
print_warn "Skipping frontend build"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
print_header "Building Frontend"
|
||||||
|
|
||||||
|
if [ ! -d "$SITE_DIR" ]; then
|
||||||
|
print_error "Directory '$SITE_DIR' not found."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
cd "$SITE_DIR"
|
||||||
|
|
||||||
|
# Check for package manager and build
|
||||||
|
if command -v pnpm &> /dev/null; then
|
||||||
|
print_info "Using pnpm..."
|
||||||
|
pnpm install
|
||||||
|
pnpm run build
|
||||||
|
elif command -v npm &> /dev/null; then
|
||||||
|
print_info "Using npm..."
|
||||||
|
npm install
|
||||||
|
npm run build
|
||||||
|
else
|
||||||
|
print_error "Neither npm nor pnpm found. Please install Node.js."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
cd - > /dev/null
|
||||||
|
|
||||||
|
# Prepare static files
|
||||||
|
print_info "Preparing static files..."
|
||||||
|
rm -rf "$PUBLIC_DIR"
|
||||||
|
mkdir -p "$PUBLIC_DIR"
|
||||||
|
|
||||||
|
if [ -d "$SITE_DIR/dist" ]; then
|
||||||
|
cp -r "$SITE_DIR/dist/." "$PUBLIC_DIR/"
|
||||||
|
print_info "Frontend assets copied to $PUBLIC_DIR"
|
||||||
|
else
|
||||||
|
print_error "Frontend build directory '$SITE_DIR/dist' not found."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Build binary for specific platform
|
||||||
|
build_binary() {
|
||||||
|
local platform=$1
|
||||||
|
local goos=$(echo $platform | cut -d'-' -f1)
|
||||||
|
local goarch=$(echo $platform | cut -d'-' -f2)
|
||||||
|
|
||||||
|
local output_name="${APP_NAME}"
|
||||||
|
if [ "$goos" = "windows" ]; then
|
||||||
|
output_name="${output_name}.exe"
|
||||||
|
fi
|
||||||
|
|
||||||
|
local output_path="${OUTPUT_DIR}/${platform}/${output_name}"
|
||||||
|
|
||||||
|
print_info "Building for $platform..."
|
||||||
|
|
||||||
|
mkdir -p "${OUTPUT_DIR}/${platform}"
|
||||||
|
|
||||||
|
# Build with version information
|
||||||
|
GOOS=$goos GOARCH=$goarch CGO_ENABLED=0 go build \
|
||||||
|
-trimpath \
|
||||||
|
-ldflags "-s -w -X main.Version=${VERSION} -X main.BuildTime=${BUILD_TIME}" \
|
||||||
|
-o "$output_path" \
|
||||||
|
../main.go
|
||||||
|
|
||||||
|
if [ $? -eq 0 ]; then
|
||||||
|
# Get file size
|
||||||
|
local size=$(du -h "$output_path" | cut -f1)
|
||||||
|
print_info "✓ Built $platform ($size): $output_path"
|
||||||
|
|
||||||
|
# Create archive
|
||||||
|
cd "${OUTPUT_DIR}/${platform}"
|
||||||
|
if [ "$goos" = "windows" ]; then
|
||||||
|
zip -q "${APP_NAME}-${VERSION}-${platform}.zip" "$output_name"
|
||||||
|
print_info "✓ Created ${APP_NAME}-${VERSION}-${platform}.zip"
|
||||||
|
else
|
||||||
|
tar -czf "${APP_NAME}-${VERSION}-${platform}.tar.gz" "$output_name"
|
||||||
|
print_info "✓ Created ${APP_NAME}-${VERSION}-${platform}.tar.gz"
|
||||||
|
fi
|
||||||
|
cd - > /dev/null
|
||||||
|
else
|
||||||
|
print_error "Failed to build for $platform"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Main build process
|
||||||
|
main() {
|
||||||
|
print_header "Starting Build Process for ${APP_NAME} v${VERSION}"
|
||||||
|
|
||||||
|
# Navigate to project root
|
||||||
|
cd "$(dirname "$0")"
|
||||||
|
|
||||||
|
# Clean output directory
|
||||||
|
rm -rf "$OUTPUT_DIR"
|
||||||
|
mkdir -p "$OUTPUT_DIR"
|
||||||
|
|
||||||
|
# Build frontend
|
||||||
|
build_frontend
|
||||||
|
|
||||||
|
# Tidy go modules
|
||||||
|
print_info "Tidying Go modules..."
|
||||||
|
cd ..
|
||||||
|
go mod tidy
|
||||||
|
cd build
|
||||||
|
|
||||||
|
print_header "Building Binaries"
|
||||||
|
|
||||||
|
# Build for selected platforms
|
||||||
|
if [ -n "$SELECTED_ARCH" ]; then
|
||||||
|
if [ "$SELECTED_ARCH" = "all" ]; then
|
||||||
|
for platform in "${PLATFORMS[@]}"; do
|
||||||
|
build_binary "$platform"
|
||||||
|
done
|
||||||
|
else
|
||||||
|
build_binary "$SELECTED_ARCH"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
# Default: build for current platform
|
||||||
|
CURRENT_OS=$(go env GOOS)
|
||||||
|
CURRENT_ARCH=$(go env GOARCH)
|
||||||
|
build_binary "${CURRENT_OS}-${CURRENT_ARCH}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
print_header "Build Complete!"
|
||||||
|
print_info "Output directory: $OUTPUT_DIR"
|
||||||
|
print_info "Version: $VERSION"
|
||||||
|
print_info "Build time: $BUILD_TIME"
|
||||||
|
|
||||||
|
# List all built archives
|
||||||
|
echo ""
|
||||||
|
print_info "Built packages:"
|
||||||
|
find "$OUTPUT_DIR" -type f \( -name "*.tar.gz" -o -name "*.zip" \) -exec ls -lh {} \;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Run main
|
||||||
|
main
|
||||||
Executable
+184
@@ -0,0 +1,184 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Docker build script for frpc-hub with multi-architecture support
|
||||||
|
# Usage: ./docker-build.sh [options]
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
IMAGE_NAME="frpc-hub"
|
||||||
|
VERSION=${VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo "latest")}
|
||||||
|
BUILD_TIME=$(date -u '+%Y-%m-%d_%H:%M:%S')
|
||||||
|
REGISTRY=${REGISTRY:-""} # Set your registry here, e.g., "docker.io/username"
|
||||||
|
PLATFORMS="linux/amd64,linux/arm64"
|
||||||
|
PUSH=false
|
||||||
|
LATEST=false
|
||||||
|
|
||||||
|
# Color output
|
||||||
|
RED='\033[0;31m'
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
YELLOW='\033[1;33m'
|
||||||
|
BLUE='\033[0;34m'
|
||||||
|
NC='\033[0m'
|
||||||
|
|
||||||
|
print_header() {
|
||||||
|
echo -e "${BLUE}=========================================="
|
||||||
|
echo -e "$1"
|
||||||
|
echo -e "==========================================${NC}"
|
||||||
|
}
|
||||||
|
|
||||||
|
print_info() {
|
||||||
|
echo -e "${GREEN}[INFO]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
print_warn() {
|
||||||
|
echo -e "${YELLOW}[WARN]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
print_error() {
|
||||||
|
echo -e "${RED}[ERROR]${NC} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
show_help() {
|
||||||
|
echo "Usage: $0 [options]"
|
||||||
|
echo ""
|
||||||
|
echo "Options:"
|
||||||
|
echo " -r, --registry <registry> Docker registry (e.g., docker.io/username)"
|
||||||
|
echo " -v, --version <version> Image version tag (default: git tag or 'latest')"
|
||||||
|
echo " -p, --platforms <platforms> Target platforms (default: linux/amd64,linux/arm64)"
|
||||||
|
echo " --push Push image to registry after build"
|
||||||
|
echo " --latest Also tag as 'latest'"
|
||||||
|
echo " --no-cache Build without cache"
|
||||||
|
echo " -h, --help Show this help message"
|
||||||
|
echo ""
|
||||||
|
echo "Examples:"
|
||||||
|
echo " $0 # Build for local use"
|
||||||
|
echo " $0 --push --latest # Build and push with latest tag"
|
||||||
|
echo " $0 -r docker.io/myuser -v 1.0.0 --push # Build and push to registry"
|
||||||
|
echo " $0 -p linux/amd64 # Build for specific platform"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Parse command line arguments
|
||||||
|
NO_CACHE=""
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case $1 in
|
||||||
|
-r|--registry)
|
||||||
|
REGISTRY="$2"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
-v|--version)
|
||||||
|
VERSION="$2"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
-p|--platforms)
|
||||||
|
PLATFORMS="$2"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
--push)
|
||||||
|
PUSH=true
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
--latest)
|
||||||
|
LATEST=true
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
--no-cache)
|
||||||
|
NO_CACHE="--no-cache"
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
-h|--help)
|
||||||
|
show_help
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
print_error "Unknown option: $1"
|
||||||
|
show_help
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# Construct full image name
|
||||||
|
if [ -n "$REGISTRY" ]; then
|
||||||
|
FULL_IMAGE_NAME="${REGISTRY}/${IMAGE_NAME}"
|
||||||
|
else
|
||||||
|
FULL_IMAGE_NAME="${IMAGE_NAME}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Navigate to build directory
|
||||||
|
cd "$(dirname "$0")"
|
||||||
|
|
||||||
|
print_header "Docker Build for ${IMAGE_NAME}"
|
||||||
|
print_info "Version: ${VERSION}"
|
||||||
|
print_info "Build time: ${BUILD_TIME}"
|
||||||
|
print_info "Platforms: ${PLATFORMS}"
|
||||||
|
print_info "Image name: ${FULL_IMAGE_NAME}:${VERSION}"
|
||||||
|
|
||||||
|
# Check if buildx is available
|
||||||
|
if ! docker buildx version &> /dev/null; then
|
||||||
|
print_error "Docker buildx is not available. Please install it first."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Create builder if it doesn't exist
|
||||||
|
if ! docker buildx ls | grep -q "frpc-hub-builder"; then
|
||||||
|
print_info "Creating buildx builder..."
|
||||||
|
docker buildx create --name frpc-hub-builder --use
|
||||||
|
else
|
||||||
|
print_info "Using existing buildx builder..."
|
||||||
|
docker buildx use frpc-hub-builder
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Bootstrap builder
|
||||||
|
docker buildx inspect --bootstrap
|
||||||
|
|
||||||
|
# Prepare build arguments
|
||||||
|
BUILD_ARGS=(
|
||||||
|
"--build-arg" "VERSION=${VERSION}"
|
||||||
|
"--build-arg" "BUILD_TIME=${BUILD_TIME}"
|
||||||
|
"--platform" "${PLATFORMS}"
|
||||||
|
"--file" "Dockerfile"
|
||||||
|
"--tag" "${FULL_IMAGE_NAME}:${VERSION}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Add latest tag if requested
|
||||||
|
if [ "$LATEST" = true ]; then
|
||||||
|
BUILD_ARGS+=("--tag" "${FULL_IMAGE_NAME}:latest")
|
||||||
|
print_info "Also tagging as: ${FULL_IMAGE_NAME}:latest"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Add push flag if requested
|
||||||
|
if [ "$PUSH" = true ]; then
|
||||||
|
BUILD_ARGS+=("--push")
|
||||||
|
print_warn "Images will be pushed to registry"
|
||||||
|
else
|
||||||
|
BUILD_ARGS+=("--load")
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Add no-cache flag if requested
|
||||||
|
if [ -n "$NO_CACHE" ]; then
|
||||||
|
BUILD_ARGS+=("$NO_CACHE")
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Build the image
|
||||||
|
print_header "Building Docker Image"
|
||||||
|
docker buildx build "${BUILD_ARGS[@]}" ..
|
||||||
|
|
||||||
|
if [ $? -eq 0 ]; then
|
||||||
|
print_header "Build Successful!"
|
||||||
|
print_info "Image: ${FULL_IMAGE_NAME}:${VERSION}"
|
||||||
|
|
||||||
|
if [ "$PUSH" = true ]; then
|
||||||
|
print_info "Image pushed to registry"
|
||||||
|
else
|
||||||
|
print_info "Image loaded locally"
|
||||||
|
echo ""
|
||||||
|
print_info "To run the container:"
|
||||||
|
echo " docker run -d -p 8090:8090 -v frpc-hub-data:/app/pb_data ${FULL_IMAGE_NAME}:${VERSION}"
|
||||||
|
echo ""
|
||||||
|
print_info "Or use docker-compose:"
|
||||||
|
echo " docker-compose up -d"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
print_error "Build failed!"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
# Local build version: build the Docker image from source code
|
||||||
|
# Usage: docker compose -f docker-compose.build.yml up -d
|
||||||
|
|
||||||
|
services:
|
||||||
|
frpc-hub:
|
||||||
|
build:
|
||||||
|
context: ..
|
||||||
|
dockerfile: build/Dockerfile
|
||||||
|
args:
|
||||||
|
VERSION: ${VERSION:-latest}
|
||||||
|
BUILD_TIME: ${BUILD_TIME:-$(date -u '+%Y-%m-%d_%H:%M:%S')}
|
||||||
|
image: frpc-hub:${VERSION:-latest}
|
||||||
|
container_name: frpc-hub
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
ports:
|
||||||
|
# Web UI and API
|
||||||
|
- "8090:8090"
|
||||||
|
# Add your frpc proxy ports here
|
||||||
|
# Example:
|
||||||
|
# - "7000:7000" # frps server port
|
||||||
|
# - "7500:7500" # frps dashboard port
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
# Persistent data storage
|
||||||
|
- frpc-hub-data:/app/pb_data
|
||||||
|
# Optional: Mount custom frpc configurations
|
||||||
|
# - ./frpc-configs:/app/frpc-configs
|
||||||
|
|
||||||
|
environment:
|
||||||
|
# Timezone
|
||||||
|
- TZ=Asia/Shanghai
|
||||||
|
# Optional: Custom PocketBase settings
|
||||||
|
# - PB_ENCRYPTION_KEY=your-encryption-key
|
||||||
|
|
||||||
|
# Resource limits (optional)
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: '2'
|
||||||
|
memory: 1G
|
||||||
|
reservations:
|
||||||
|
cpus: '0.5'
|
||||||
|
memory: 256M
|
||||||
|
|
||||||
|
# Network mode (optional)
|
||||||
|
# Uncomment if you need host network for better frpc performance
|
||||||
|
# network_mode: host
|
||||||
|
|
||||||
|
# Logging
|
||||||
|
logging:
|
||||||
|
driver: "json-file"
|
||||||
|
options:
|
||||||
|
max-size: "10m"
|
||||||
|
max-file: "3"
|
||||||
|
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8090/api/health"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 3s
|
||||||
|
start_period: 10s
|
||||||
|
retries: 3
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
frpc-hub-data:
|
||||||
|
driver: local
|
||||||
|
|
||||||
|
networks:
|
||||||
|
default:
|
||||||
|
name: frpc-hub-network
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
# Public image version: use the pre-built Docker image from a registry
|
||||||
|
# Usage: docker compose up -d
|
||||||
|
|
||||||
|
services:
|
||||||
|
frpc-hub:
|
||||||
|
image: ${REGISTRY:-ghcr.io/your-username}/frpc-hub:${VERSION:-latest}
|
||||||
|
container_name: frpc-hub
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
ports:
|
||||||
|
# Web UI and API
|
||||||
|
- "8090:8090"
|
||||||
|
# Add your frpc proxy ports here
|
||||||
|
# Example:
|
||||||
|
# - "7000:7000" # frps server port
|
||||||
|
# - "7500:7500" # frps dashboard port
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
# Persistent data storage
|
||||||
|
- frpc-hub-data:/app/pb_data
|
||||||
|
# Optional: Mount custom frpc configurations
|
||||||
|
# - ./frpc-configs:/app/frpc-configs
|
||||||
|
|
||||||
|
environment:
|
||||||
|
# Timezone
|
||||||
|
- TZ=Asia/Shanghai
|
||||||
|
# Optional: Custom PocketBase settings
|
||||||
|
# - PB_ENCRYPTION_KEY=your-encryption-key
|
||||||
|
|
||||||
|
# Resource limits (optional)
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: '2'
|
||||||
|
memory: 1G
|
||||||
|
reservations:
|
||||||
|
cpus: '0.5'
|
||||||
|
memory: 256M
|
||||||
|
|
||||||
|
# Network mode (optional)
|
||||||
|
# Uncomment if you need host network for better frpc performance
|
||||||
|
# network_mode: host
|
||||||
|
|
||||||
|
# Logging
|
||||||
|
logging:
|
||||||
|
driver: "json-file"
|
||||||
|
options:
|
||||||
|
max-size: "10m"
|
||||||
|
max-file: "3"
|
||||||
|
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8090/api/health"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 3s
|
||||||
|
start_period: 10s
|
||||||
|
retries: 3
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
frpc-hub-data:
|
||||||
|
driver: local
|
||||||
|
|
||||||
|
networks:
|
||||||
|
default:
|
||||||
|
name: frpc-hub-network
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
module frpc-hub
|
||||||
|
|
||||||
|
go 1.25.5
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/fatedier/frp v0.67.0
|
||||||
|
github.com/pelletier/go-toml/v2 v2.2.0
|
||||||
|
github.com/pocketbase/dbx v1.11.0
|
||||||
|
github.com/pocketbase/pocketbase v0.35.0
|
||||||
|
github.com/spf13/cobra v1.10.2
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
|
||||||
|
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 // indirect
|
||||||
|
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
|
||||||
|
github.com/coreos/go-oidc/v3 v3.14.1 // indirect
|
||||||
|
github.com/disintegration/imaging v1.6.2 // indirect
|
||||||
|
github.com/domodwyer/mailyak/v3 v3.6.2 // indirect
|
||||||
|
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||||
|
github.com/fatedier/golib v0.5.1 // indirect
|
||||||
|
github.com/fatih/color v1.18.0 // indirect
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||||
|
github.com/ganigeorgiev/fexpr v0.5.0 // indirect
|
||||||
|
github.com/go-jose/go-jose/v4 v4.0.5 // indirect
|
||||||
|
github.com/go-ozzo/ozzo-validation/v4 v4.3.0 // indirect
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.0 // indirect
|
||||||
|
github.com/golang/snappy v0.0.4 // indirect
|
||||||
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
|
github.com/gorilla/mux v1.8.1 // indirect
|
||||||
|
github.com/hashicorp/yamux v0.1.1 // indirect
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||||
|
github.com/klauspost/cpuid/v2 v2.2.6 // indirect
|
||||||
|
github.com/klauspost/reedsolomon v1.12.0 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||||
|
github.com/pion/dtls/v2 v2.2.7 // indirect
|
||||||
|
github.com/pion/logging v0.2.2 // indirect
|
||||||
|
github.com/pion/stun/v2 v2.0.0 // indirect
|
||||||
|
github.com/pion/transport/v2 v2.2.1 // indirect
|
||||||
|
github.com/pion/transport/v3 v3.0.1 // indirect
|
||||||
|
github.com/pires/go-proxyproto v0.7.0 // indirect
|
||||||
|
github.com/pkg/errors v0.9.1 // indirect
|
||||||
|
github.com/quic-go/quic-go v0.55.0 // indirect
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
|
github.com/samber/lo v1.47.0 // indirect
|
||||||
|
github.com/songgao/water v0.0.0-20200317203138-2b4b6d7c09d8 // indirect
|
||||||
|
github.com/spf13/cast v1.10.0 // indirect
|
||||||
|
github.com/spf13/pflag v1.0.10 // indirect
|
||||||
|
github.com/templexxx/cpu v0.1.1 // indirect
|
||||||
|
github.com/templexxx/xorsimd v0.4.3 // indirect
|
||||||
|
github.com/tjfoc/gmsm v1.4.1 // indirect
|
||||||
|
github.com/vishvananda/netlink v1.3.0 // indirect
|
||||||
|
github.com/vishvananda/netns v0.0.4 // indirect
|
||||||
|
github.com/xtaci/kcp-go/v5 v5.6.13 // indirect
|
||||||
|
golang.org/x/crypto v0.46.0 // indirect
|
||||||
|
golang.org/x/exp v0.0.0-20251219203646-944ab1f22d93 // indirect
|
||||||
|
golang.org/x/image v0.34.0 // indirect
|
||||||
|
golang.org/x/mod v0.31.0 // indirect
|
||||||
|
golang.org/x/net v0.48.0 // indirect
|
||||||
|
golang.org/x/oauth2 v0.34.0 // indirect
|
||||||
|
golang.org/x/sync v0.19.0 // indirect
|
||||||
|
golang.org/x/sys v0.39.0 // indirect
|
||||||
|
golang.org/x/text v0.32.0 // indirect
|
||||||
|
golang.org/x/time v0.5.0 // indirect
|
||||||
|
golang.org/x/tools v0.40.0 // indirect
|
||||||
|
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect
|
||||||
|
golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173 // indirect
|
||||||
|
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||||
|
k8s.io/apimachinery v0.28.8 // indirect
|
||||||
|
k8s.io/utils v0.0.0-20230406110748-d93618cff8a2 // indirect
|
||||||
|
modernc.org/libc v1.66.10 // indirect
|
||||||
|
modernc.org/mathutil v1.7.1 // indirect
|
||||||
|
modernc.org/memory v1.11.0 // indirect
|
||||||
|
modernc.org/sqlite v1.41.0 // indirect
|
||||||
|
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect
|
||||||
|
sigs.k8s.io/yaml v1.3.0 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,326 @@
|
|||||||
|
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||||
|
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8=
|
||||||
|
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
|
||||||
|
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||||
|
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
|
||||||
|
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
|
||||||
|
github.com/asaskevich/govalidator v0.0.0-20200108200545-475eaeb16496/go.mod h1:oGkLhpf+kjZl6xBf758TQhh5XrAeiJv/7FRz/2spLIg=
|
||||||
|
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
|
||||||
|
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
||||||
|
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||||
|
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||||
|
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
||||||
|
github.com/coreos/go-oidc/v3 v3.14.1 h1:9ePWwfdwC4QKRlCXsJGou56adA/owXczOzwKdOumLqk=
|
||||||
|
github.com/coreos/go-oidc/v3 v3.14.1/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU=
|
||||||
|
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
|
||||||
|
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||||
|
github.com/domodwyer/mailyak/v3 v3.6.2 h1:x3tGMsyFhTCaxp6ycgR0FE/bu5QiNp+hetUuCOBXMn8=
|
||||||
|
github.com/domodwyer/mailyak/v3 v3.6.2/go.mod h1:lOm/u9CyCVWHeaAmHIdF4RiKVxKUT/H5XX10lIKAL6c=
|
||||||
|
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||||
|
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||||
|
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||||
|
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||||
|
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||||
|
github.com/fatedier/frp v0.67.0 h1:w6xHLkruAJcq+fZP9VOiY6w/FBy/wB1aPqA4frs98K8=
|
||||||
|
github.com/fatedier/frp v0.67.0/go.mod h1:0Q3mAI0c9WtAsgMQpTQhinWTKa2Qp121YWsqaFu41Zg=
|
||||||
|
github.com/fatedier/golib v0.5.1 h1:hcKAnaw5mdI/1KWRGejxR+i1Hn/NvbY5UsMKDr7o13M=
|
||||||
|
github.com/fatedier/golib v0.5.1/go.mod h1:W6kIYkIFxHsTzbgqg5piCxIiDo4LzwgTY6R5W8l9NFQ=
|
||||||
|
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||||
|
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||||
|
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||||
|
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||||
|
github.com/ganigeorgiev/fexpr v0.5.0 h1:XA9JxtTE/Xm+g/JFI6RfZEHSiQlk+1glLvRK1Lpv/Tk=
|
||||||
|
github.com/ganigeorgiev/fexpr v0.5.0/go.mod h1:RyGiGqmeXhEQ6+mlGdnUleLHgtzzu/VGO2WtJkF5drE=
|
||||||
|
github.com/go-jose/go-jose/v4 v4.0.5 h1:M6T8+mKZl/+fNNuFHvGIzDz7BTLQPIounk/b9dw3AaE=
|
||||||
|
github.com/go-jose/go-jose/v4 v4.0.5/go.mod h1:s3P1lRrkT8igV8D9OjyL4WRyHvjB6a4JSllnOrmmBOA=
|
||||||
|
github.com/go-ozzo/ozzo-validation/v4 v4.3.0 h1:byhDUpfEwjsVQb1vBunvIjh2BHQ9ead57VkAEY4V+Es=
|
||||||
|
github.com/go-ozzo/ozzo-validation/v4 v4.3.0/go.mod h1:2NKgrcHl3z6cJs+3Oo940FPRiTzuqKbvfrL2RxCj6Ew=
|
||||||
|
github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA=
|
||||||
|
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
|
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||||
|
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||||
|
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
|
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
|
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
|
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||||
|
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||||
|
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||||
|
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
|
||||||
|
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||||
|
github.com/google/btree v1.0.1 h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4=
|
||||||
|
github.com/google/btree v1.0.1/go.mod h1:xXMiIv4Fb/0kKde4SpL7qlzvu5cMJDRkFDxJfI9uaxA=
|
||||||
|
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||||
|
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
|
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
|
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
|
github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d h1:KJIErDwbSHjnp/SGzE5ed8Aol7JsKiI5X7yWKAtzhM0=
|
||||||
|
github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U=
|
||||||
|
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/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
||||||
|
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
||||||
|
github.com/hashicorp/yamux v0.1.1 h1:yrQxtgseBDrq9Y652vSRDvsKCJKOUD+GzTS4Y0Y8pvE=
|
||||||
|
github.com/hashicorp/yamux v0.1.1/go.mod h1:CtWFDAQgb7dxtzFs4tWbplKIe2jSi3+5vKbgIO0SLnQ=
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||||
|
github.com/klauspost/reedsolomon v1.12.0 h1:I5FEp3xSwVCcEh3F5A7dofEfhXdF/bWhQWPH+XwBFno=
|
||||||
|
github.com/klauspost/reedsolomon v1.12.0/go.mod h1:EPLZJeh4l27pUGC3aXOjheaoh1I9yut7xTURiW3LQ9Y=
|
||||||
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
|
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
|
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||||
|
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||||
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
|
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||||
|
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||||
|
github.com/pelletier/go-toml/v2 v2.2.0 h1:QLgLl2yMN7N+ruc31VynXs1vhMZa7CeHHejIeBAsoHo=
|
||||||
|
github.com/pelletier/go-toml/v2 v2.2.0/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||||
|
github.com/pion/dtls/v2 v2.2.7 h1:cSUBsETxepsCSFSxC3mc/aDo14qQLMSL+O6IjG28yV8=
|
||||||
|
github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s=
|
||||||
|
github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=
|
||||||
|
github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
|
||||||
|
github.com/pion/stun/v2 v2.0.0 h1:A5+wXKLAypxQri59+tmQKVs7+l6mMM+3d+eER9ifRU0=
|
||||||
|
github.com/pion/stun/v2 v2.0.0/go.mod h1:22qRSh08fSEttYUmJZGlriq9+03jtVmXNODgLccj8GQ=
|
||||||
|
github.com/pion/transport/v2 v2.2.1 h1:7qYnCBlpgSJNYMbLCKuSY9KbQdBFoETvPNETv0y4N7c=
|
||||||
|
github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g=
|
||||||
|
github.com/pion/transport/v3 v3.0.1 h1:gDTlPJwROfSfz6QfSi0ZmeCSkFcnWWiiR9ES0ouANiM=
|
||||||
|
github.com/pion/transport/v3 v3.0.1/go.mod h1:UY7kiITrlMv7/IKgd5eTUcaahZx5oUN3l9SzK5f5xE0=
|
||||||
|
github.com/pires/go-proxyproto v0.7.0 h1:IukmRewDQFWC7kfnb66CSomk2q/seBuilHBYFwyq0Hs=
|
||||||
|
github.com/pires/go-proxyproto v0.7.0/go.mod h1:Vz/1JPY/OACxWGQNIRY2BeyDmpoaWmEP40O9LbuiFR4=
|
||||||
|
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
|
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/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/pocketbase/dbx v1.11.0 h1:LpZezioMfT3K4tLrqA55wWFw1EtH1pM4tzSVa7kgszU=
|
||||||
|
github.com/pocketbase/dbx v1.11.0/go.mod h1:xXRCIAKTHMgUCyCKZm55pUOdvFziJjQfXaWKhu2vhMs=
|
||||||
|
github.com/pocketbase/pocketbase v0.35.0 h1:MW905RYJnpwl8bvFDPCn+/5Y/TGKbf+kpdKiZmqx/1s=
|
||||||
|
github.com/pocketbase/pocketbase v0.35.0/go.mod h1:eA9IKEvGYhdVbngBzgXPDZ2aNAGfDBkB6kcuLnHLTag=
|
||||||
|
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||||
|
github.com/quic-go/quic-go v0.55.0 h1:zccPQIqYCXDt5NmcEabyYvOnomjs8Tlwl7tISjJh9Mk=
|
||||||
|
github.com/quic-go/quic-go v0.55.0/go.mod h1:DR51ilwU1uE164KuWXhinFcKWGlEjzys2l8zUl5Ss1U=
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||||
|
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||||
|
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||||
|
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
|
github.com/samber/lo v1.47.0 h1:z7RynLwP5nbyRscyvcD043DWYoOcYRv3mV8lBeqOCLc=
|
||||||
|
github.com/samber/lo v1.47.0/go.mod h1:RmDH9Ct32Qy3gduHQuKJ3gW1fMHAnE/fAzQuf6He5cU=
|
||||||
|
github.com/songgao/water v0.0.0-20200317203138-2b4b6d7c09d8 h1:TG/diQgUe0pntT/2D9tmUCz4VNwm9MfrtPr0SU2qSX8=
|
||||||
|
github.com/songgao/water v0.0.0-20200317203138-2b4b6d7c09d8/go.mod h1:P5HUIBuIWKbyjl083/loAegFkfbFNx5i2qEP4CNbm7E=
|
||||||
|
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
|
||||||
|
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
|
||||||
|
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||||
|
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||||
|
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
|
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||||
|
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
|
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||||
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
|
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||||
|
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||||
|
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
|
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||||
|
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
|
github.com/templexxx/cpu v0.1.1 h1:isxHaxBXpYFWnk2DReuKkigaZyrjs2+9ypIdGP4h+HI=
|
||||||
|
github.com/templexxx/cpu v0.1.1/go.mod h1:w7Tb+7qgcAlIyX4NhLuDKt78AHA5SzPmq0Wj6HiEnnk=
|
||||||
|
github.com/templexxx/xorsimd v0.4.3 h1:9AQTFHd7Bhk3dIT7Al2XeBX5DWOvsUPZCuhyAtNbHjU=
|
||||||
|
github.com/templexxx/xorsimd v0.4.3/go.mod h1:oZQcD6RFDisW2Am58dSAGwwL6rHjbzrlu25VDqfWkQg=
|
||||||
|
github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho=
|
||||||
|
github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE=
|
||||||
|
github.com/vishvananda/netlink v1.3.0 h1:X7l42GfcV4S6E4vHTsw48qbrV+9PVojNfIhZcwQdrZk=
|
||||||
|
github.com/vishvananda/netlink v1.3.0/go.mod h1:i6NetklAujEcC6fK0JPjT8qSwWyO0HLn4UKG+hGqeJs=
|
||||||
|
github.com/vishvananda/netns v0.0.4 h1:Oeaw1EM2JMxD51g9uhtC0D7erkIjgmj8+JZc26m1YX8=
|
||||||
|
github.com/vishvananda/netns v0.0.4/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
||||||
|
github.com/xtaci/kcp-go/v5 v5.6.13 h1:FEjtz9+D4p8t2x4WjciGt/jsIuhlWjjgPCCWjrVR4Hk=
|
||||||
|
github.com/xtaci/kcp-go/v5 v5.6.13/go.mod h1:75S1AKYYzNUSXIv30h+jPKJYZUwqpfvLshu63nCNSOM=
|
||||||
|
github.com/xtaci/lossyconn v0.0.0-20200209145036-adba10fffc37 h1:EWU6Pktpas0n8lLQwDsRyZfmkPeRbdgPtW609es+/9E=
|
||||||
|
github.com/xtaci/lossyconn v0.0.0-20200209145036-adba10fffc37/go.mod h1:HpMP7DB2CyokmAh4lp0EQnnWhmycP/TvwBGzvuie+H0=
|
||||||
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
|
go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
|
||||||
|
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
|
||||||
|
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||||
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
|
golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
|
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
|
golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE=
|
||||||
|
golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw=
|
||||||
|
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||||
|
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||||
|
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||||
|
golang.org/x/exp v0.0.0-20251219203646-944ab1f22d93 h1:fQsdNF2N+/YewlRZiricy4P1iimyPKZ/xwniHj8Q2a0=
|
||||||
|
golang.org/x/exp v0.0.0-20251219203646-944ab1f22d93/go.mod h1:EPRbTFwzwjXj9NpYyyrvenVh9Y+GFeEvMNh7Xuz7xgU=
|
||||||
|
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||||
|
golang.org/x/image v0.34.0 h1:33gCkyw9hmwbZJeZkct8XyR11yH889EQt/QH4VmXMn8=
|
||||||
|
golang.org/x/image v0.34.0/go.mod h1:2RNFBZRB+vnwwFil8GkMdRvrJOFd1AzdZI6vOY+eJVU=
|
||||||
|
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||||
|
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||||
|
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||||
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
|
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
|
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
|
||||||
|
golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
|
||||||
|
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
|
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
||||||
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||||
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
|
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||||
|
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||||
|
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
|
||||||
|
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||||
|
golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI=
|
||||||
|
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||||
|
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||||
|
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||||
|
golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
|
||||||
|
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
||||||
|
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||||
|
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
|
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/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-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
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.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||||
|
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
|
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.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||||
|
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
|
||||||
|
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||||
|
golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU=
|
||||||
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
|
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
|
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||||
|
golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||||
|
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||||
|
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||||
|
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
|
||||||
|
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||||
|
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||||
|
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||||
|
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.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||||
|
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
|
||||||
|
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
|
||||||
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg=
|
||||||
|
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
|
||||||
|
golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173 h1:/jFs0duh4rdb8uIfPMv78iAJGcPKDeqAFnaLBropIC4=
|
||||||
|
golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173/go.mod h1:tkCQ4FQXmpAgYVh++1cq16/dH4QJtmvpRv19DWGAHSA=
|
||||||
|
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||||
|
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||||
|
google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM=
|
||||||
|
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
|
||||||
|
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||||
|
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
||||||
|
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||||
|
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
|
||||||
|
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
|
||||||
|
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||||
|
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||||
|
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||||
|
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
||||||
|
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||||
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||||
|
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gvisor.dev/gvisor v0.0.0-20230927004350-cbd86285d259 h1:TbRPT0HtzFP3Cno1zZo7yPzEEnfu8EjLfl6IU9VfqkQ=
|
||||||
|
gvisor.dev/gvisor v0.0.0-20230927004350-cbd86285d259/go.mod h1:AVgIgHMwK63XvmAzWG9vLQ41YnVHN0du0tEC46fI7yY=
|
||||||
|
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
|
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
|
k8s.io/apimachinery v0.28.8 h1:hi/nrxHwk4QLV+W/SHve1bypTE59HCDorLY1stBIxKQ=
|
||||||
|
k8s.io/apimachinery v0.28.8/go.mod h1:cBnwIM3fXoRo28SqbV/Ihxf/iviw85KyXOrzxvZQ83U=
|
||||||
|
k8s.io/utils v0.0.0-20230406110748-d93618cff8a2 h1:qY1Ad8PODbnymg2pRbkyMT/ylpTrCM8P2RJ0yroCyIk=
|
||||||
|
k8s.io/utils v0.0.0-20230406110748-d93618cff8a2/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=
|
||||||
|
modernc.org/cc/v4 v4.26.5 h1:xM3bX7Mve6G8K8b+T11ReenJOT+BmVqQj0FY5T4+5Y4=
|
||||||
|
modernc.org/cc/v4 v4.26.5/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
||||||
|
modernc.org/ccgo/v4 v4.28.1 h1:wPKYn5EC/mYTqBO373jKjvX2n+3+aK7+sICCv4Fjy1A=
|
||||||
|
modernc.org/ccgo/v4 v4.28.1/go.mod h1:uD+4RnfrVgE6ec9NGguUNdhqzNIeeomeXf6CL0GTE5Q=
|
||||||
|
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
|
||||||
|
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
|
||||||
|
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||||
|
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||||
|
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||||
|
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||||
|
modernc.org/libc v1.66.10 h1:yZkb3YeLx4oynyR+iUsXsybsX4Ubx7MQlSYEw4yj59A=
|
||||||
|
modernc.org/libc v1.66.10/go.mod h1:8vGSEwvoUoltr4dlywvHqjtAqHBaw0j1jI7iFBTAr2I=
|
||||||
|
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||||
|
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||||
|
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||||
|
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||||
|
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
||||||
|
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||||
|
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||||
|
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||||
|
modernc.org/sqlite v1.41.0 h1:bJXddp4ZpsqMsNN1vS0jWo4IJTZzb8nWpcgvyCFG9Ck=
|
||||||
|
modernc.org/sqlite v1.41.0/go.mod h1:9fjQZ0mB1LLP0GYrp39oOJXx/I2sxEnZtzCmEQIKvGE=
|
||||||
|
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||||
|
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||||
|
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||||
|
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||||
|
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo=
|
||||||
|
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0=
|
||||||
|
sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo=
|
||||||
|
sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8=
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
package dashboard
|
||||||
|
|
||||||
|
import (
|
||||||
|
proxyapp "frpc-hub/internal/application/proxy"
|
||||||
|
serverapp "frpc-hub/internal/application/server"
|
||||||
|
proxydomain "frpc-hub/internal/domain/proxy"
|
||||||
|
serverdomain "frpc-hub/internal/domain/server"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type DashboardStats struct {
|
||||||
|
RunningCount int64
|
||||||
|
StoppedCount int64
|
||||||
|
ProxiesEnabledCount int64
|
||||||
|
ProxiesDisabledCount int64
|
||||||
|
ProxiesOnlineCount int64
|
||||||
|
MaxLatency int64
|
||||||
|
ProxyTypeCounts map[string]int64
|
||||||
|
UptimeSeconds int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type TopologyServerItem struct {
|
||||||
|
ID string `json:"id" db:"id"`
|
||||||
|
ServerName string `json:"serverName" db:"serverName"`
|
||||||
|
ServerAddr string `json:"serverAddr" db:"serverAddr"`
|
||||||
|
BootStatus string `json:"bootStatus" db:"bootStatus"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type TopologyProxyItem struct {
|
||||||
|
ID string `json:"id" db:"id"`
|
||||||
|
Name string `json:"name" db:"name"`
|
||||||
|
ProxyType string `json:"proxyType" db:"proxyType"`
|
||||||
|
LocalIP string `json:"localIP" db:"localIP"`
|
||||||
|
LocalPort string `json:"localPort" db:"localPort"`
|
||||||
|
RemotePort string `json:"remotePort" db:"remotePort"`
|
||||||
|
Status string `json:"status" db:"status"`
|
||||||
|
BootStatus string `json:"bootStatus" db:"bootStatus"`
|
||||||
|
ServerID string `json:"serverId" db:"serverId"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type TopologyData struct {
|
||||||
|
Servers []TopologyServerItem `json:"servers"`
|
||||||
|
Proxies []TopologyProxyItem `json:"proxies"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
app core.App
|
||||||
|
serverService *serverapp.Service
|
||||||
|
proxyService *proxyapp.Service
|
||||||
|
startTime time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(app core.App, serverService *serverapp.Service, proxyService *proxyapp.Service) *Service {
|
||||||
|
return &Service{
|
||||||
|
app: app,
|
||||||
|
serverService: serverService,
|
||||||
|
proxyService: proxyService,
|
||||||
|
startTime: time.Now(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetStats() (*DashboardStats, error) {
|
||||||
|
runningCount, err := s.serverService.GetServerCountByStatus(serverdomain.ServerStatusRunning)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
stoppedCount, err := s.serverService.GetServerCountByStatus(serverdomain.ServerStatusStopped)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
proxiesEnabledCount, err := s.proxyService.GetProxyCountByStatus(proxydomain.ProxyStatusEnabled)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
proxiesDisabledCount, err := s.proxyService.GetProxyCountByStatus(proxydomain.ProxyStatusDisabled)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
proxiesOnlineCount, err := s.proxyService.GetProxyCountByBootStatus(proxydomain.ProxyBootStatusOnline)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
maxLatency, err := s.serverService.GetMaxLatency()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
proxyTypeCounts, err := s.proxyService.GetProxyCountsByType()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &DashboardStats{
|
||||||
|
RunningCount: runningCount,
|
||||||
|
StoppedCount: stoppedCount,
|
||||||
|
ProxiesEnabledCount: proxiesEnabledCount,
|
||||||
|
ProxiesDisabledCount: proxiesDisabledCount,
|
||||||
|
ProxiesOnlineCount: proxiesOnlineCount,
|
||||||
|
MaxLatency: maxLatency,
|
||||||
|
ProxyTypeCounts: proxyTypeCounts,
|
||||||
|
UptimeSeconds: int64(time.Since(s.startTime).Seconds()),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetTopology() (*TopologyData, error) {
|
||||||
|
var servers []TopologyServerItem
|
||||||
|
if err := s.app.DB().Select("id", "serverName", "serverAddr", "bootStatus").From("fh_servers").All(&servers); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if servers == nil {
|
||||||
|
servers = []TopologyServerItem{}
|
||||||
|
}
|
||||||
|
|
||||||
|
var proxies []TopologyProxyItem
|
||||||
|
if err := s.app.DB().Select("id", "name", "proxyType", "localIP", "localPort", "remotePort", "status", "bootStatus", "serverId").From("fh_proxies").All(&proxies); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if proxies == nil {
|
||||||
|
proxies = []TopologyProxyItem{}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &TopologyData{Servers: servers, Proxies: proxies}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,485 @@
|
|||||||
|
package frpc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"path/filepath"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
proxydomain "frpc-hub/internal/domain/proxy"
|
||||||
|
serverdomain "frpc-hub/internal/domain/server"
|
||||||
|
"frpc-hub/pkg/utils"
|
||||||
|
|
||||||
|
"github.com/fatedier/frp/client"
|
||||||
|
v1 "github.com/fatedier/frp/pkg/config/v1"
|
||||||
|
"github.com/fatedier/frp/pkg/util/log"
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
app core.App
|
||||||
|
processes map[string]*client.Service
|
||||||
|
statusMonitors map[string]context.CancelFunc
|
||||||
|
serverRepo serverdomain.Repository
|
||||||
|
proxyRepo proxydomain.Repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(app core.App, serverRepo serverdomain.Repository, proxyRepo proxydomain.Repository) *Service {
|
||||||
|
return &Service{
|
||||||
|
app: app,
|
||||||
|
processes: make(map[string]*client.Service),
|
||||||
|
statusMonitors: make(map[string]context.CancelFunc),
|
||||||
|
serverRepo: serverRepo,
|
||||||
|
proxyRepo: proxyRepo,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fs *Service) genCommonCfgs(id *string) (*v1.ClientCommonConfig, error) {
|
||||||
|
cfg := &v1.ClientCommonConfig{}
|
||||||
|
|
||||||
|
record, err := fs.app.FindRecordById("fh_servers", *id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// basic config
|
||||||
|
cfg.ServerAddr = record.GetString("serverAddr")
|
||||||
|
cfg.ServerPort = record.GetInt("serverPort")
|
||||||
|
|
||||||
|
logDirPath, _ := filepath.Abs("pb_data/frpc/" + *id + "/")
|
||||||
|
if err := os.MkdirAll(logDirPath, 0755); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// log config
|
||||||
|
logStr := record.GetString("log")
|
||||||
|
mainPath := fs.getFrpMainPath(id)
|
||||||
|
var logConfig v1.LogConfig
|
||||||
|
err = json.Unmarshal([]byte(logStr), &logConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
logPath := filepath.Join(mainPath, "logs", "frpc.log")
|
||||||
|
logConfig.To = logPath
|
||||||
|
cfg.Log = logConfig
|
||||||
|
|
||||||
|
// auth config
|
||||||
|
authStr := record.GetString("auth")
|
||||||
|
var authConfig v1.AuthClientConfig
|
||||||
|
err = json.Unmarshal([]byte(authStr), &authConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if authConfig.Method != "none" && authConfig.Method != "" {
|
||||||
|
cfg.Auth = authConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// transport config
|
||||||
|
transportStr := record.GetString("transport")
|
||||||
|
var transportConfig v1.ClientTransportConfig
|
||||||
|
err = json.Unmarshal([]byte(transportStr), &transportConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cfg.Transport = transportConfig
|
||||||
|
if *cfg.Transport.TLS.Enable {
|
||||||
|
tlsCertFile := filepath.Join(mainPath, "certs", "cert.pem")
|
||||||
|
tlsKeyFile := filepath.Join(mainPath, "certs", "key.pem")
|
||||||
|
tlsTrustedCaFile := filepath.Join(mainPath, "certs", "ca.pem")
|
||||||
|
|
||||||
|
if err := os.MkdirAll(filepath.Dir(tlsCertFile), 0755); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(tlsCertFile, []byte(cfg.Transport.TLS.CertFile), 0644); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(tlsKeyFile, []byte(cfg.Transport.TLS.KeyFile), 0600); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(tlsTrustedCaFile, []byte(cfg.Transport.TLS.TrustedCaFile), 0644); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cfg.Transport.TLS.CertFile = tlsCertFile
|
||||||
|
cfg.Transport.TLS.KeyFile = tlsKeyFile
|
||||||
|
cfg.Transport.TLS.TrustedCaFile = tlsTrustedCaFile
|
||||||
|
}
|
||||||
|
|
||||||
|
// metadata config
|
||||||
|
metadataStr := record.GetString("metadatas")
|
||||||
|
var metadataConfig map[string]string
|
||||||
|
err = json.Unmarshal([]byte(metadataStr), &metadataConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cfg.Metadatas = metadataConfig
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fs *Service) genProxyCfgs(serverId *string) ([]v1.ProxyConfigurer, error) {
|
||||||
|
proxies, err := fs.proxyRepo.FindByServerID(*serverId)
|
||||||
|
if err != nil {
|
||||||
|
fs.app.Logger().Error("genProxyCfgs", "err", err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var proxyCfgs []v1.ProxyConfigurer
|
||||||
|
for _, proxyMap := range proxies {
|
||||||
|
jsonData, err := json.Marshal(proxyMap)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert to map to manipulate fields
|
||||||
|
var proxyData map[string]interface{}
|
||||||
|
if err := json.Unmarshal(jsonData, &proxyData); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if proxyMap.ProxyType == "http" || proxyMap.ProxyType == "https" {
|
||||||
|
delete(proxyData, "remotePort")
|
||||||
|
}
|
||||||
|
proxyData["name"] = proxyMap.Name + "-" + proxyMap.Id
|
||||||
|
|
||||||
|
jsonData, err = json.Marshal(proxyData)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch proxyMap.ProxyType {
|
||||||
|
case "tcp":
|
||||||
|
var tcpProxy v1.TCPProxyConfig
|
||||||
|
if err := json.Unmarshal(jsonData, &tcpProxy); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
proxyCfgs = append(proxyCfgs, &tcpProxy)
|
||||||
|
case "udp":
|
||||||
|
var udpProxy v1.UDPProxyConfig
|
||||||
|
if err := json.Unmarshal(jsonData, &udpProxy); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
proxyCfgs = append(proxyCfgs, &udpProxy)
|
||||||
|
case "http":
|
||||||
|
var httpProxy v1.HTTPProxyConfig
|
||||||
|
if err := json.Unmarshal(jsonData, &httpProxy); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
proxyCfgs = append(proxyCfgs, &httpProxy)
|
||||||
|
case "https":
|
||||||
|
var httpsProxy v1.HTTPSProxyConfig
|
||||||
|
if err := json.Unmarshal(jsonData, &httpsProxy); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
proxyCfgs = append(proxyCfgs, &httpsProxy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxyCfgs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleTermSignal(svr *client.Service) {
|
||||||
|
ch := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
<-ch
|
||||||
|
svr.GracefulClose(500 * time.Millisecond)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fs *Service) LaunchFrpc(serverId *string) error {
|
||||||
|
fs.app.Logger().Info("Launch frpc", "id", *serverId)
|
||||||
|
cfg, err := fs.genCommonCfgs(serverId)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
proxyCfgs, err := fs.genProxyCfgs(serverId)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.app.Logger().Debug("Config", "cfg", cfg, "proxyCfgs", proxyCfgs)
|
||||||
|
|
||||||
|
cfg.Complete()
|
||||||
|
log.InitLogger(cfg.Log.To, cfg.Log.Level, int(cfg.Log.MaxDays), cfg.Log.DisablePrintColor)
|
||||||
|
|
||||||
|
svr, err := client.NewService(client.ServiceOptions{
|
||||||
|
Common: cfg,
|
||||||
|
ProxyCfgs: proxyCfgs,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
fs.app.Logger().Error("NewService", "err", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
shouldGracefulClose := cfg.Transport.Protocol == "kcp" || cfg.Transport.Protocol == "quic"
|
||||||
|
if shouldGracefulClose {
|
||||||
|
go handleTermSignal(svr)
|
||||||
|
}
|
||||||
|
fs.processes[*serverId] = svr
|
||||||
|
|
||||||
|
fs.serverRepo.UpdateBootStatus(*serverId, serverdomain.ServerStatusRunning)
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
fs.statusMonitors[*serverId] = cancel
|
||||||
|
|
||||||
|
done := make(chan error, 1)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
fs.app.Logger().Info("Frpc service starting execution", "id", *serverId)
|
||||||
|
err := svr.Run(ctx)
|
||||||
|
if err != nil {
|
||||||
|
fs.app.Logger().Error("Frpc service exited with error", "id", *serverId, "error", err)
|
||||||
|
} else {
|
||||||
|
fs.app.Logger().Info("Frpc service exited normally", "id", *serverId)
|
||||||
|
}
|
||||||
|
done <- err
|
||||||
|
}()
|
||||||
|
|
||||||
|
go fs.monitorServiceStatus(serverId, svr, ctx, done)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// monitorServiceStatus monitors service status and updates the database.
|
||||||
|
func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx context.Context, done <-chan error) {
|
||||||
|
time.Sleep(2 * time.Second)
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-done:
|
||||||
|
fs.app.Logger().Error("Service exited during startup", "id", *id, "error", err)
|
||||||
|
fs.destroying(id)
|
||||||
|
return
|
||||||
|
case <-ctx.Done():
|
||||||
|
fs.app.Logger().Info("Service context cancelled during startup", "id", *id)
|
||||||
|
fs.destroying(id)
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
fs.serverRepo.UpdateBootStatus(*id, serverdomain.ServerStatusRunning)
|
||||||
|
fs.app.Logger().Info("Service is running", "id", *id)
|
||||||
|
}
|
||||||
|
|
||||||
|
go fs.monitorProxyStatus(id, svr, ctx)
|
||||||
|
|
||||||
|
ticker := time.NewTicker(5 * time.Second)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case err := <-done:
|
||||||
|
if err != nil {
|
||||||
|
fs.app.Logger().Error("Service exited with error", "id", *id, "error", err)
|
||||||
|
} else {
|
||||||
|
fs.app.Logger().Info("Service exited normally", "id", *id)
|
||||||
|
}
|
||||||
|
fs.destroying(id)
|
||||||
|
return
|
||||||
|
case <-ctx.Done():
|
||||||
|
fs.app.Logger().Info("Service stopped by user", "id", *id)
|
||||||
|
fs.destroying(id)
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
fs.app.Logger().Debug("Service status check", "id", *id, "status", "running")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fs *Service) destroying(id *string) {
|
||||||
|
fs.serverRepo.UpdateBootStatus(*id, serverdomain.ServerStatusStopped)
|
||||||
|
fs.proxyRepo.UpdateBootStatusByServerID(*id, proxydomain.ProxyBootStatusOffline)
|
||||||
|
delete(fs.processes, *id)
|
||||||
|
delete(fs.statusMonitors, *id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// monitorProxyStatus monitors proxy status from frp and updates the database.
|
||||||
|
func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx context.Context) {
|
||||||
|
fs.app.Logger().Info("Starting proxy status monitoring", "serverId", *serverId)
|
||||||
|
|
||||||
|
statusExporter := svr.StatusExporter()
|
||||||
|
|
||||||
|
ticker := time.NewTicker(5 * time.Second)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
fs.app.Logger().Info("Proxy status monitoring stopped", "serverId", *serverId)
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
proxies, err := fs.proxyRepo.FindByServerID(*serverId)
|
||||||
|
if err != nil {
|
||||||
|
fs.app.Logger().Error("Failed to get proxies", "serverId", *serverId, "error", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
proxyName := proxy.Name + "-" + proxy.Id
|
||||||
|
status, exists := statusExporter.GetProxyStatus(proxyName)
|
||||||
|
|
||||||
|
if exists {
|
||||||
|
var bootStatus proxydomain.ProxyBootStatus
|
||||||
|
switch status.Phase {
|
||||||
|
case "running":
|
||||||
|
bootStatus = proxydomain.ProxyBootStatusOnline
|
||||||
|
case "start error", "check failed", "closed":
|
||||||
|
bootStatus = proxydomain.ProxyBootStatusOffline
|
||||||
|
default:
|
||||||
|
bootStatus = proxydomain.ProxyBootStatusOffline
|
||||||
|
}
|
||||||
|
fs.proxyRepo.UpdateBootStatus(proxy.Id, bootStatus)
|
||||||
|
} else {
|
||||||
|
fs.app.Logger().Debug("Proxy not found in frp status", "serverId", *serverId, "proxyId", proxy.Id, "proxyName", proxyName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TerminateFrpc stops the specified frpc service.
|
||||||
|
func (fs *Service) TerminateFrpc(id *string) error {
|
||||||
|
fs.app.Logger().Info("Stop frpc", "id", *id)
|
||||||
|
|
||||||
|
cancel, exists := fs.statusMonitors[*id]
|
||||||
|
if !exists {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
fs.app.Logger().Info("Frpc stop signal sent", "id", *id)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fs *Service) getFrpMainPath(id *string) string {
|
||||||
|
logDirPath, _ := filepath.Abs("pb_data/frpc/" + *id + "/")
|
||||||
|
return logDirPath
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamLog streams the frpc log file via SSE.
|
||||||
|
// It sends the last 50 lines as initial content, then tails new lines every 500ms.
|
||||||
|
func (fs *Service) StreamLog(serverId string, ctx context.Context, w http.ResponseWriter, flusher http.Flusher) {
|
||||||
|
mainPath := fs.getFrpMainPath(&serverId)
|
||||||
|
logPath := filepath.Join(mainPath, "logs", "frpc.log")
|
||||||
|
|
||||||
|
file, err := os.Open(logPath)
|
||||||
|
if err != nil {
|
||||||
|
fs.app.Logger().Warn("Log file not found", "serverId", serverId, "path", logPath, "error", err)
|
||||||
|
fmt.Fprintf(w, "data: [No log file found]\n\n")
|
||||||
|
flusher.Flush()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
initialLines := utils.ReadLastNLines(file, 50)
|
||||||
|
fs.app.Logger().Info("Streaming log file", "serverId", serverId, "initialLines", len(initialLines))
|
||||||
|
for _, line := range initialLines {
|
||||||
|
fmt.Fprintf(w, "data: %s\n\n", line)
|
||||||
|
}
|
||||||
|
flusher.Flush()
|
||||||
|
|
||||||
|
offset, err := file.Seek(0, io.SeekEnd)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ticker := time.NewTicker(500 * time.Millisecond)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
fi, err := os.Stat(logPath)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if fi.Size() < offset {
|
||||||
|
file.Close()
|
||||||
|
file, err = os.Open(logPath)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
offset = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
file.Seek(offset, io.SeekStart)
|
||||||
|
scanner := bufio.NewScanner(file)
|
||||||
|
hasData := false
|
||||||
|
for scanner.Scan() {
|
||||||
|
line := scanner.Text()
|
||||||
|
if line != "" {
|
||||||
|
fmt.Fprintf(w, "data: %s\n\n", line)
|
||||||
|
hasData = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
newOffset, _ := file.Seek(0, io.SeekCurrent)
|
||||||
|
offset = newOffset
|
||||||
|
|
||||||
|
if hasData {
|
||||||
|
flusher.Flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fs *Service) ReloadFrpc(serverId *string) error {
|
||||||
|
fs.app.Logger().Info("Reload frpc", "id", *serverId)
|
||||||
|
|
||||||
|
proxyCfgs, err := fs.genProxyCfgs(serverId)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
svr := fs.processes[*serverId]
|
||||||
|
// TODO 2026-02-08 reload visitorCfgs
|
||||||
|
svr.UpdateAllConfigurer(proxyCfgs, nil)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsServerRunning checks if a server is currently running.
|
||||||
|
func (fs *Service) IsServerRunning(serverId string) bool {
|
||||||
|
_, exists := fs.processes[serverId]
|
||||||
|
return exists
|
||||||
|
}
|
||||||
|
|
||||||
|
// AutoStartServers automatically starts all servers with autoConnection=true.
|
||||||
|
func (fs *Service) AutoStartServers() {
|
||||||
|
fs.app.Logger().Info("Auto-starting servers with autoConnection enabled")
|
||||||
|
fs.app.Logger().Info("Waiting for 10 seconds before auto-starting servers")
|
||||||
|
time.Sleep(10 * time.Second)
|
||||||
|
|
||||||
|
records, err := fs.serverRepo.FindAllWithAutoConnect()
|
||||||
|
if err != nil {
|
||||||
|
fs.app.Logger().Error("Failed to find auto-connection servers", "error", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
count := 0
|
||||||
|
for _, record := range records {
|
||||||
|
serverId := record.ID
|
||||||
|
serverName := record.ServerName
|
||||||
|
|
||||||
|
fs.app.Logger().Info("Auto-starting server", "id", serverId, "name", serverName)
|
||||||
|
|
||||||
|
go func(id string) {
|
||||||
|
time.Sleep(time.Duration(count) * 500 * time.Millisecond)
|
||||||
|
|
||||||
|
if err := fs.LaunchFrpc(&id); err != nil {
|
||||||
|
fs.app.Logger().Error("Failed to auto-start server", "id", id, "error", err)
|
||||||
|
} else {
|
||||||
|
fs.app.Logger().Info("Successfully auto-started server", "id", id)
|
||||||
|
}
|
||||||
|
}(serverId)
|
||||||
|
|
||||||
|
count++
|
||||||
|
fs.app.Logger().Info("Waiting for 1s before auto-starting next server")
|
||||||
|
time.Sleep(1 * time.Second)
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.app.Logger().Info("Auto-start initiated for servers", "count", count)
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
package github
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
app core.App
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(app core.App) *Service {
|
||||||
|
return &Service{app: app}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GithubRelease is the simplified release info returned to the frontend.
|
||||||
|
type GithubRelease struct {
|
||||||
|
TagName string `json:"tag_name"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
PublishedAt string `json:"published_at"`
|
||||||
|
HTMLURL string `json:"html_url"`
|
||||||
|
DownloadUrl string `json:"download_url"` // Download link automatically matched based on current system architecture
|
||||||
|
}
|
||||||
|
|
||||||
|
// githubInternalRelease used to parse raw GitHub API data
|
||||||
|
type githubInternalRelease struct {
|
||||||
|
TagName string `json:"tag_name"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
PublishedAt string `json:"published_at"`
|
||||||
|
HTMLURL string `json:"html_url"`
|
||||||
|
Assets []struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
BrowserDownloadUrl string `json:"browser_download_url"`
|
||||||
|
} `json:"assets"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFrpReleases fetches fatedier/frp releases and auto-matches a download link for the current OS/arch.
|
||||||
|
func (s *Service) GetFrpReleases() ([]GithubRelease, error) {
|
||||||
|
url := "https://api.github.com/repos/fatedier/frp/releases"
|
||||||
|
|
||||||
|
client := &http.Client{
|
||||||
|
Timeout: 15 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest("GET", url, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req.Header.Set("User-Agent", "frpc-hub-server")
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("github api returned status: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
var internalReleases []githubInternalRelease
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&internalReleases); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
goos := runtime.GOOS
|
||||||
|
goarch := runtime.GOARCH
|
||||||
|
|
||||||
|
var releases []GithubRelease
|
||||||
|
for _, raw := range internalReleases {
|
||||||
|
release := GithubRelease{
|
||||||
|
TagName: raw.TagName,
|
||||||
|
Name: raw.Name,
|
||||||
|
PublishedAt: raw.PublishedAt,
|
||||||
|
HTMLURL: raw.HTMLURL,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, asset := range raw.Assets {
|
||||||
|
assetName := strings.ToLower(asset.Name)
|
||||||
|
|
||||||
|
if strings.Contains(assetName, goos) && strings.Contains(assetName, goarch) {
|
||||||
|
// Special handling for some overlapping cases, e.g., 386 and amd64
|
||||||
|
if goarch == "386" && strings.Contains(assetName, "amd64") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
release.DownloadUrl = asset.BrowserDownloadUrl
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
releases = append(releases, release)
|
||||||
|
}
|
||||||
|
|
||||||
|
return releases, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,499 @@
|
|||||||
|
package importer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/pelletier/go-toml/v2"
|
||||||
|
"github.com/pocketbase/dbx"
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ==================== TOML Parse Types ====================
|
||||||
|
|
||||||
|
type tomlFrpClientConfig struct {
|
||||||
|
ServerAddr string `toml:"serverAddr"`
|
||||||
|
ServerPort int `toml:"serverPort"`
|
||||||
|
Auth tomlAuthConfig `toml:"auth"`
|
||||||
|
Log tomlLogConfig `toml:"log"`
|
||||||
|
Transport tomlTransportConfig `toml:"transport"`
|
||||||
|
Metadatas map[string]string `toml:"metadatas"`
|
||||||
|
Proxies []tomlProxyConfig `toml:"proxies"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type tomlAuthConfig struct {
|
||||||
|
Method string `toml:"method"`
|
||||||
|
Token string `toml:"token"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type tomlLogConfig struct {
|
||||||
|
Level string `toml:"level"`
|
||||||
|
MaxDays int `toml:"maxDays"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type tomlTransportConfig struct {
|
||||||
|
Protocol string `toml:"protocol"`
|
||||||
|
ProxyURL string `toml:"proxyURL"`
|
||||||
|
TLS tomlTLSConfig `toml:"tls"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type tomlTLSConfig struct {
|
||||||
|
Enable bool `toml:"enable"`
|
||||||
|
DisableCustomTLSFirstByte bool `toml:"disableCustomTLSFirstByte"`
|
||||||
|
ServerName string `toml:"serverName"`
|
||||||
|
CertFile string `toml:"certFile"`
|
||||||
|
KeyFile string `toml:"keyFile"`
|
||||||
|
TrustedCaFile string `toml:"trustedCaFile"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type tomlProxyConfig struct {
|
||||||
|
Name string `toml:"name"`
|
||||||
|
Type string `toml:"type"`
|
||||||
|
LocalIP string `toml:"localIP"`
|
||||||
|
LocalPort int `toml:"localPort"`
|
||||||
|
RemotePort int `toml:"remotePort"`
|
||||||
|
Subdomain string `toml:"subdomain"`
|
||||||
|
CustomDomains []string `toml:"customDomains"`
|
||||||
|
Transport map[string]interface{} `toml:"transport"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== API Data Types ====================
|
||||||
|
|
||||||
|
type ParseTomlRequest struct {
|
||||||
|
TomlContent string `json:"tomlContent"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ImportServerInfo struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
ServerAddr string `json:"serverAddr"`
|
||||||
|
ServerPort int `json:"serverPort"`
|
||||||
|
Auth map[string]interface{} `json:"auth"`
|
||||||
|
Log map[string]interface{} `json:"log"`
|
||||||
|
Transport map[string]interface{} `json:"transport"`
|
||||||
|
Metadatas map[string]string `json:"metadatas"`
|
||||||
|
IsDuplicate bool `json:"isDuplicate"`
|
||||||
|
ExistingId string `json:"existingId"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ImportProxyInfo struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
LocalIP string `json:"localIP"`
|
||||||
|
LocalPort int `json:"localPort"`
|
||||||
|
RemotePort int `json:"remotePort"`
|
||||||
|
Subdomain string `json:"subdomain"`
|
||||||
|
CustomDomains []string `json:"customDomains"`
|
||||||
|
Transport map[string]interface{} `json:"transport"`
|
||||||
|
IsDuplicate bool `json:"isDuplicate"`
|
||||||
|
ExistingId string `json:"existingId"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ImportPreviewResponse struct {
|
||||||
|
Server ImportServerInfo `json:"server"`
|
||||||
|
Proxies []ImportProxyInfo `json:"proxies"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProxyImportOption struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Import bool `json:"import"`
|
||||||
|
Overwrite bool `json:"overwrite"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ExecuteImportRequest struct {
|
||||||
|
TomlContent string `json:"tomlContent"`
|
||||||
|
ServerName string `json:"serverName"`
|
||||||
|
ImportServer bool `json:"importServer"`
|
||||||
|
OverwriteServer bool `json:"overwriteServer"`
|
||||||
|
Proxies []ProxyImportOption `json:"proxies"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ImportResult struct {
|
||||||
|
ServerImported bool `json:"serverImported"`
|
||||||
|
ProxiesImported int `json:"proxiesImported"`
|
||||||
|
ProxiesSkipped int `json:"proxiesSkipped"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Service ====================
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
app core.App
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(app core.App) *Service {
|
||||||
|
return &Service{app: app}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ParseToml(req *ParseTomlRequest) (*ImportPreviewResponse, error) {
|
||||||
|
var cfg tomlFrpClientConfig
|
||||||
|
if err := toml.Unmarshal([]byte(req.TomlContent), &cfg); err != nil {
|
||||||
|
return nil, fmt.Errorf("TOML 解析失败: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
serverPort := cfg.ServerPort
|
||||||
|
if serverPort == 0 {
|
||||||
|
serverPort = 7000
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if server already exists (by addr + port)
|
||||||
|
var existingServerId string
|
||||||
|
var serverDuplicate bool
|
||||||
|
var existingServerRow struct {
|
||||||
|
Id string `db:"id"`
|
||||||
|
}
|
||||||
|
err := s.app.DB().
|
||||||
|
Select("id").
|
||||||
|
From("fh_servers").
|
||||||
|
Where(dbx.HashExp{
|
||||||
|
"serverAddr": cfg.ServerAddr,
|
||||||
|
"serverPort": serverPort,
|
||||||
|
}).
|
||||||
|
One(&existingServerRow)
|
||||||
|
if err == nil {
|
||||||
|
serverDuplicate = true
|
||||||
|
existingServerId = existingServerRow.Id
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build auth map
|
||||||
|
authMap := map[string]interface{}{
|
||||||
|
"method": cfg.Auth.Method,
|
||||||
|
"token": cfg.Auth.Token,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build log map with defaults
|
||||||
|
logLevel := cfg.Log.Level
|
||||||
|
if logLevel == "" {
|
||||||
|
logLevel = "info"
|
||||||
|
}
|
||||||
|
logMaxDays := cfg.Log.MaxDays
|
||||||
|
if logMaxDays == 0 {
|
||||||
|
logMaxDays = 3
|
||||||
|
}
|
||||||
|
logMap := map[string]interface{}{
|
||||||
|
"level": logLevel,
|
||||||
|
"maxDays": logMaxDays,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build transport map with defaults
|
||||||
|
protocol := cfg.Transport.Protocol
|
||||||
|
if protocol == "" {
|
||||||
|
protocol = "tcp"
|
||||||
|
}
|
||||||
|
transportMap := map[string]interface{}{
|
||||||
|
"protocol": protocol,
|
||||||
|
"proxyURL": cfg.Transport.ProxyURL,
|
||||||
|
"tls": map[string]interface{}{
|
||||||
|
"enable": cfg.Transport.TLS.Enable,
|
||||||
|
"disableCustomTLSFirstByte": cfg.Transport.TLS.DisableCustomTLSFirstByte,
|
||||||
|
"serverName": cfg.Transport.TLS.ServerName,
|
||||||
|
"certFile": cfg.Transport.TLS.CertFile,
|
||||||
|
"keyFile": cfg.Transport.TLS.KeyFile,
|
||||||
|
"trustedCaFile": cfg.Transport.TLS.TrustedCaFile,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
metadatas := cfg.Metadatas
|
||||||
|
if metadatas == nil {
|
||||||
|
metadatas = map[string]string{}
|
||||||
|
}
|
||||||
|
|
||||||
|
serverInfo := ImportServerInfo{
|
||||||
|
Name: fmt.Sprintf("%s:%d", cfg.ServerAddr, serverPort),
|
||||||
|
ServerAddr: cfg.ServerAddr,
|
||||||
|
ServerPort: serverPort,
|
||||||
|
Auth: authMap,
|
||||||
|
Log: logMap,
|
||||||
|
Transport: transportMap,
|
||||||
|
Metadatas: metadatas,
|
||||||
|
IsDuplicate: serverDuplicate,
|
||||||
|
ExistingId: existingServerId,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build proxy infos with duplicate detection
|
||||||
|
proxies := make([]ImportProxyInfo, 0, len(cfg.Proxies))
|
||||||
|
for _, p := range cfg.Proxies {
|
||||||
|
proxyType := p.Type
|
||||||
|
if proxyType == "" {
|
||||||
|
proxyType = "tcp"
|
||||||
|
}
|
||||||
|
customDomains := p.CustomDomains
|
||||||
|
if customDomains == nil {
|
||||||
|
customDomains = []string{}
|
||||||
|
}
|
||||||
|
proxyTransport := p.Transport
|
||||||
|
if proxyTransport == nil {
|
||||||
|
proxyTransport = map[string]interface{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
proxyInfo := ImportProxyInfo{
|
||||||
|
Name: p.Name,
|
||||||
|
Type: proxyType,
|
||||||
|
LocalIP: p.LocalIP,
|
||||||
|
LocalPort: p.LocalPort,
|
||||||
|
RemotePort: p.RemotePort,
|
||||||
|
Subdomain: p.Subdomain,
|
||||||
|
CustomDomains: customDomains,
|
||||||
|
Transport: proxyTransport,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check proxy duplicate: only meaningful if server already exists
|
||||||
|
if serverDuplicate && existingServerId != "" {
|
||||||
|
var existingProxyRow struct {
|
||||||
|
Id string `db:"id"`
|
||||||
|
}
|
||||||
|
perr := s.app.DB().
|
||||||
|
Select("id").
|
||||||
|
From("fh_proxies").
|
||||||
|
Where(dbx.HashExp{
|
||||||
|
"name": p.Name,
|
||||||
|
"serverId": existingServerId,
|
||||||
|
}).
|
||||||
|
One(&existingProxyRow)
|
||||||
|
if perr == nil {
|
||||||
|
proxyInfo.IsDuplicate = true
|
||||||
|
proxyInfo.ExistingId = existingProxyRow.Id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies = append(proxies, proxyInfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &ImportPreviewResponse{
|
||||||
|
Server: serverInfo,
|
||||||
|
Proxies: proxies,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ExecuteImport(req *ExecuteImportRequest) (*ImportResult, error) {
|
||||||
|
var cfg tomlFrpClientConfig
|
||||||
|
if err := toml.Unmarshal([]byte(req.TomlContent), &cfg); err != nil {
|
||||||
|
return nil, fmt.Errorf("TOML 解析失败: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
serverPort := cfg.ServerPort
|
||||||
|
if serverPort == 0 {
|
||||||
|
serverPort = 7000
|
||||||
|
}
|
||||||
|
|
||||||
|
result := &ImportResult{}
|
||||||
|
|
||||||
|
err := s.app.RunInTransaction(func(txApp core.App) error {
|
||||||
|
serverId, err := s.handleServerImport(txApp, &cfg, serverPort, req, result)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if serverId == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return s.handleProxyImport(txApp, &cfg, serverId, req.Proxies, result)
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleServerImport creates or updates a server record and returns its ID.
|
||||||
|
// Returns empty string if server import was skipped.
|
||||||
|
func (s *Service) handleServerImport(
|
||||||
|
txApp core.App,
|
||||||
|
cfg *tomlFrpClientConfig,
|
||||||
|
serverPort int,
|
||||||
|
req *ExecuteImportRequest,
|
||||||
|
result *ImportResult,
|
||||||
|
) (string, error) {
|
||||||
|
var existingServerRow struct {
|
||||||
|
Id string `db:"id"`
|
||||||
|
}
|
||||||
|
serverExists := false
|
||||||
|
existErr := txApp.DB().
|
||||||
|
Select("id").
|
||||||
|
From("fh_servers").
|
||||||
|
Where(dbx.HashExp{
|
||||||
|
"serverAddr": cfg.ServerAddr,
|
||||||
|
"serverPort": serverPort,
|
||||||
|
}).
|
||||||
|
One(&existingServerRow)
|
||||||
|
if existErr == nil {
|
||||||
|
serverExists = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server exists but we're not importing: use existing ID for proxies
|
||||||
|
if serverExists && !req.ImportServer {
|
||||||
|
return existingServerRow.Id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Not importing server and it doesn't exist: skip
|
||||||
|
if !req.ImportServer {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
serverName := req.ServerName
|
||||||
|
if serverName == "" {
|
||||||
|
serverName = fmt.Sprintf("%s:%d", cfg.ServerAddr, serverPort)
|
||||||
|
}
|
||||||
|
|
||||||
|
logLevel := cfg.Log.Level
|
||||||
|
if logLevel == "" {
|
||||||
|
logLevel = "info"
|
||||||
|
}
|
||||||
|
logMaxDays := cfg.Log.MaxDays
|
||||||
|
if logMaxDays == 0 {
|
||||||
|
logMaxDays = 3
|
||||||
|
}
|
||||||
|
protocol := cfg.Transport.Protocol
|
||||||
|
if protocol == "" {
|
||||||
|
protocol = "tcp"
|
||||||
|
}
|
||||||
|
metadatas := cfg.Metadatas
|
||||||
|
if metadatas == nil {
|
||||||
|
metadatas = map[string]string{}
|
||||||
|
}
|
||||||
|
|
||||||
|
authJSON, _ := json.Marshal(map[string]interface{}{
|
||||||
|
"method": cfg.Auth.Method,
|
||||||
|
"token": cfg.Auth.Token,
|
||||||
|
})
|
||||||
|
logJSON, _ := json.Marshal(map[string]interface{}{
|
||||||
|
"level": logLevel,
|
||||||
|
"maxDays": logMaxDays,
|
||||||
|
})
|
||||||
|
transportJSON, _ := json.Marshal(map[string]interface{}{
|
||||||
|
"protocol": protocol,
|
||||||
|
"proxyURL": cfg.Transport.ProxyURL,
|
||||||
|
"tls": map[string]interface{}{
|
||||||
|
"enable": cfg.Transport.TLS.Enable,
|
||||||
|
"disableCustomTLSFirstByte": cfg.Transport.TLS.DisableCustomTLSFirstByte,
|
||||||
|
"serverName": cfg.Transport.TLS.ServerName,
|
||||||
|
"certFile": cfg.Transport.TLS.CertFile,
|
||||||
|
"keyFile": cfg.Transport.TLS.KeyFile,
|
||||||
|
"trustedCaFile": cfg.Transport.TLS.TrustedCaFile,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
metadatasJSON, _ := json.Marshal(metadatas)
|
||||||
|
|
||||||
|
serversCollection, err := txApp.FindCollectionByNameOrId("fh_servers")
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("找不到服务器集合: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var serverRecord *core.Record
|
||||||
|
if serverExists && req.OverwriteServer {
|
||||||
|
serverRecord, err = txApp.FindRecordById(serversCollection, existingServerRow.Id)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("查找已有服务器失败: %w", err)
|
||||||
|
}
|
||||||
|
} else if serverExists && !req.OverwriteServer {
|
||||||
|
result.ServerImported = false
|
||||||
|
return existingServerRow.Id, nil
|
||||||
|
} else {
|
||||||
|
serverRecord = core.NewRecord(serversCollection)
|
||||||
|
}
|
||||||
|
|
||||||
|
serverRecord.Set("serverName", serverName)
|
||||||
|
serverRecord.Set("serverAddr", cfg.ServerAddr)
|
||||||
|
serverRecord.Set("serverPort", serverPort)
|
||||||
|
serverRecord.Set("serverVersion", "built-in")
|
||||||
|
serverRecord.Set("auth", string(authJSON))
|
||||||
|
serverRecord.Set("log", string(logJSON))
|
||||||
|
serverRecord.Set("transport", string(transportJSON))
|
||||||
|
serverRecord.Set("metadatas", string(metadatasJSON))
|
||||||
|
serverRecord.Set("bootStatus", "stopped")
|
||||||
|
serverRecord.Set("autoConnection", false)
|
||||||
|
serverRecord.Set("description", "")
|
||||||
|
|
||||||
|
if err := txApp.Save(serverRecord); err != nil {
|
||||||
|
return "", fmt.Errorf("保存服务器失败: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
result.ServerImported = true
|
||||||
|
return serverRecord.Id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleProxyImport creates or updates proxy records under the given server.
|
||||||
|
func (s *Service) handleProxyImport(
|
||||||
|
txApp core.App,
|
||||||
|
cfg *tomlFrpClientConfig,
|
||||||
|
serverId string,
|
||||||
|
proxyOpts []ProxyImportOption,
|
||||||
|
result *ImportResult,
|
||||||
|
) error {
|
||||||
|
proxyOptMap := make(map[string]ProxyImportOption, len(proxyOpts))
|
||||||
|
for _, opt := range proxyOpts {
|
||||||
|
proxyOptMap[opt.Name] = opt
|
||||||
|
}
|
||||||
|
|
||||||
|
proxiesCollection, err := txApp.FindCollectionByNameOrId("fh_proxies")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("找不到代理集合: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, p := range cfg.Proxies {
|
||||||
|
opt, ok := proxyOptMap[p.Name]
|
||||||
|
if !ok || !opt.Import {
|
||||||
|
result.ProxiesSkipped++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
var existingProxyRow struct {
|
||||||
|
Id string `db:"id"`
|
||||||
|
}
|
||||||
|
proxyExistsErr := txApp.DB().
|
||||||
|
Select("id").
|
||||||
|
From("fh_proxies").
|
||||||
|
Where(dbx.HashExp{
|
||||||
|
"name": p.Name,
|
||||||
|
"serverId": serverId,
|
||||||
|
}).
|
||||||
|
One(&existingProxyRow)
|
||||||
|
|
||||||
|
var proxyRecord *core.Record
|
||||||
|
if proxyExistsErr == nil && opt.Overwrite {
|
||||||
|
proxyRecord, err = txApp.FindRecordById(proxiesCollection, existingProxyRow.Id)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("查找已有代理 %s 失败: %w", p.Name, err)
|
||||||
|
}
|
||||||
|
} else if proxyExistsErr == nil && !opt.Overwrite {
|
||||||
|
result.ProxiesSkipped++
|
||||||
|
continue
|
||||||
|
} else {
|
||||||
|
proxyRecord = core.NewRecord(proxiesCollection)
|
||||||
|
}
|
||||||
|
|
||||||
|
proxyType := p.Type
|
||||||
|
if proxyType == "" {
|
||||||
|
proxyType = "tcp"
|
||||||
|
}
|
||||||
|
customDomains := p.CustomDomains
|
||||||
|
if customDomains == nil {
|
||||||
|
customDomains = []string{}
|
||||||
|
}
|
||||||
|
customDomainsJSON, _ := json.Marshal(customDomains)
|
||||||
|
|
||||||
|
proxyTransport := p.Transport
|
||||||
|
if proxyTransport == nil {
|
||||||
|
proxyTransport = map[string]interface{}{}
|
||||||
|
}
|
||||||
|
proxyTransportJSON, _ := json.Marshal(proxyTransport)
|
||||||
|
|
||||||
|
proxyRecord.Set("name", p.Name)
|
||||||
|
proxyRecord.Set("proxyType", proxyType)
|
||||||
|
proxyRecord.Set("serverId", serverId)
|
||||||
|
proxyRecord.Set("localIP", p.LocalIP)
|
||||||
|
proxyRecord.Set("localPort", p.LocalPort)
|
||||||
|
proxyRecord.Set("remotePort", p.RemotePort)
|
||||||
|
proxyRecord.Set("subdomain", p.Subdomain)
|
||||||
|
proxyRecord.Set("customDomains", string(customDomainsJSON))
|
||||||
|
proxyRecord.Set("transport", string(proxyTransportJSON))
|
||||||
|
proxyRecord.Set("status", "enabled")
|
||||||
|
proxyRecord.Set("bootStatus", "offline")
|
||||||
|
proxyRecord.Set("description", "")
|
||||||
|
|
||||||
|
if err := txApp.Save(proxyRecord); err != nil {
|
||||||
|
return fmt.Errorf("保存代理 %s 失败: %w", p.Name, err)
|
||||||
|
}
|
||||||
|
result.ProxiesImported++
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
package monitoring
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"frpc-hub/pkg/utils"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pocketbase/dbx"
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MonitorService is the background network monitoring service.
|
||||||
|
type MonitorService struct {
|
||||||
|
app core.App
|
||||||
|
networkService *NetworkService
|
||||||
|
stopChan chan bool
|
||||||
|
latencyTicker *time.Ticker
|
||||||
|
geoTicker *time.Ticker
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewMonitorService creates a new network monitoring service.
|
||||||
|
func NewMonitorService(app core.App, networkService *NetworkService) *MonitorService {
|
||||||
|
return &MonitorService{
|
||||||
|
app: app,
|
||||||
|
networkService: networkService,
|
||||||
|
stopChan: make(chan bool),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start begins background monitoring.
|
||||||
|
// latencyInterval: how often to check latency (e.g., 30s).
|
||||||
|
// geoInterval: how often to check geolocation (e.g., 24h).
|
||||||
|
func (s *MonitorService) Start(latencyInterval, geoInterval time.Duration) {
|
||||||
|
s.app.Logger().Info("Starting network monitor service",
|
||||||
|
"latencyInterval", latencyInterval,
|
||||||
|
"geoInterval", geoInterval)
|
||||||
|
|
||||||
|
// Execute immediately once
|
||||||
|
go s.updateAllServersLatency()
|
||||||
|
go s.updateAllServersGeoLocation()
|
||||||
|
|
||||||
|
s.latencyTicker = time.NewTicker(latencyInterval)
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-s.latencyTicker.C:
|
||||||
|
s.updateAllServersLatency()
|
||||||
|
case <-s.stopChan:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
s.geoTicker = time.NewTicker(geoInterval)
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-s.geoTicker.C:
|
||||||
|
s.updateAllServersGeoLocation()
|
||||||
|
case <-s.stopChan:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
s.app.Logger().Info("Network monitor service started successfully")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stop halts the background monitoring task.
|
||||||
|
func (s *MonitorService) Stop() {
|
||||||
|
if s.latencyTicker != nil {
|
||||||
|
s.latencyTicker.Stop()
|
||||||
|
}
|
||||||
|
if s.geoTicker != nil {
|
||||||
|
s.geoTicker.Stop()
|
||||||
|
}
|
||||||
|
close(s.stopChan)
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateAllServersLatency updates latency for all servers.
|
||||||
|
func (s *MonitorService) updateAllServersLatency() {
|
||||||
|
s.app.Logger().Debug("Updating latency for all servers")
|
||||||
|
|
||||||
|
records, err := s.app.FindRecordsByFilter(
|
||||||
|
"fh_servers",
|
||||||
|
"",
|
||||||
|
"-created",
|
||||||
|
500,
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
s.app.Logger().Error("Failed to fetch servers for latency monitoring", "error", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.app.Logger().Debug("Found servers to check latency", "count", len(records))
|
||||||
|
|
||||||
|
for _, record := range records {
|
||||||
|
go s.updateServerLatency(record.Id, record.GetString("serverAddr"), record.GetInt("serverPort"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateAllServersGeoLocation updates geolocation for servers without geo data.
|
||||||
|
func (s *MonitorService) updateAllServersGeoLocation() {
|
||||||
|
s.app.Logger().Info("Updating geolocation for servers without geo data")
|
||||||
|
|
||||||
|
records, err := s.app.FindRecordsByFilter(
|
||||||
|
"fh_servers",
|
||||||
|
"geoLocation = '' || geoLocation = null",
|
||||||
|
"-created",
|
||||||
|
500,
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
s.app.Logger().Error("Failed to fetch servers for geo monitoring", "error", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(records) == 0 {
|
||||||
|
s.app.Logger().Debug("All servers already have geolocation data")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.app.Logger().Info("Found servers needing geolocation", "count", len(records))
|
||||||
|
|
||||||
|
for _, record := range records {
|
||||||
|
go s.updateServerGeoLocation(record.Id, record.GetString("serverAddr"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateServerLatency updates latency for a single server.
|
||||||
|
func (s *MonitorService) updateServerLatency(serverID string, serverAddr string, serverPort int) {
|
||||||
|
addr := fmt.Sprintf("%s:%d", serverAddr, serverPort)
|
||||||
|
pingResult := utils.PingHost(addr, 5*time.Second)
|
||||||
|
|
||||||
|
networkStatus := map[string]interface{}{
|
||||||
|
"latency": pingResult.Latency,
|
||||||
|
"reachable": pingResult.Reachable,
|
||||||
|
"lastCheckTime": time.Now().Format(time.RFC3339),
|
||||||
|
"error": pingResult.Error,
|
||||||
|
}
|
||||||
|
|
||||||
|
networkStatusJSON, _ := json.Marshal(networkStatus)
|
||||||
|
|
||||||
|
_, err := s.app.DB().
|
||||||
|
Update("fh_servers",
|
||||||
|
dbx.Params{"networkStatus": string(networkStatusJSON)},
|
||||||
|
dbx.HashExp{"id": serverID},
|
||||||
|
).Execute()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
s.app.Logger().Error("Failed to update server latency", "serverId", serverID, "error", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.app.Logger().Debug("Updated latency",
|
||||||
|
"serverId", serverID,
|
||||||
|
"addr", serverAddr,
|
||||||
|
"latency", pingResult.Latency,
|
||||||
|
"reachable", pingResult.Reachable,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateServerGeoLocation updates geolocation for a single server.
|
||||||
|
func (s *MonitorService) updateServerGeoLocation(serverID string, serverAddr string) {
|
||||||
|
location, err := s.networkService.getGeoLocationWithCache(serverAddr)
|
||||||
|
if err != nil {
|
||||||
|
s.app.Logger().Warn("Failed to get geo location", "serverId", serverID, "addr", serverAddr, "error", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
geoLocation := map[string]interface{}{
|
||||||
|
"country": location.Country,
|
||||||
|
"countryCode": location.CountryCode,
|
||||||
|
"region": location.Region,
|
||||||
|
"city": location.City,
|
||||||
|
"isp": location.ISP,
|
||||||
|
"lat": location.Latitude,
|
||||||
|
"lon": location.Longitude,
|
||||||
|
}
|
||||||
|
|
||||||
|
geoLocationJSON, _ := json.Marshal(geoLocation)
|
||||||
|
|
||||||
|
_, err = s.app.DB().
|
||||||
|
Update("fh_servers",
|
||||||
|
dbx.Params{"geoLocation": string(geoLocationJSON)},
|
||||||
|
dbx.HashExp{"id": serverID},
|
||||||
|
).Execute()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
s.app.Logger().Error("Failed to update server geolocation", "serverId", serverID, "error", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.app.Logger().Info("Updated geolocation",
|
||||||
|
"serverId", serverID,
|
||||||
|
"addr", serverAddr,
|
||||||
|
"city", location.City,
|
||||||
|
"isp", location.ISP,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
package monitoring
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"frpc-hub/pkg/utils"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NetworkService is the network diagnostic service.
|
||||||
|
type NetworkService struct {
|
||||||
|
app core.App
|
||||||
|
geoCache map[string]*geoCacheItem // IP geolocation cache
|
||||||
|
geoCacheLock sync.RWMutex // Cache read-write lock
|
||||||
|
}
|
||||||
|
|
||||||
|
// geoCacheItem is a geolocation cache entry.
|
||||||
|
type geoCacheItem struct {
|
||||||
|
Location *utils.GeoLocation
|
||||||
|
ExpiresAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServerNetworkStatus holds network status for a server.
|
||||||
|
type ServerNetworkStatus struct {
|
||||||
|
ServerID string `json:"serverId"`
|
||||||
|
ServerName string `json:"serverName"`
|
||||||
|
ServerAddr string `json:"serverAddr"`
|
||||||
|
ServerPort int `json:"serverPort"`
|
||||||
|
NetworkStatus *NetworkStatus `json:"networkStatus"`
|
||||||
|
GeoLocation *utils.GeoLocation `json:"geoLocation,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NetworkStatus holds latency and reachability information.
|
||||||
|
type NetworkStatus struct {
|
||||||
|
Latency int64 `json:"latency"` // Latency in milliseconds
|
||||||
|
Reachable bool `json:"reachable"` // Whether the host is reachable
|
||||||
|
LastCheckTime time.Time `json:"lastCheckTime"` // Last check timestamp
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewNetworkService creates a new network diagnostic service.
|
||||||
|
func NewNetworkService(app core.App) *NetworkService {
|
||||||
|
return &NetworkService{
|
||||||
|
app: app,
|
||||||
|
geoCache: make(map[string]*geoCacheItem),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetServerNetworkStatus retrieves server network status.
|
||||||
|
func (s *NetworkService) GetServerNetworkStatus(serverID string) (*ServerNetworkStatus, error) {
|
||||||
|
record, err := s.app.FindRecordById("fh_servers", serverID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("server not found: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
serverName := record.GetString("name")
|
||||||
|
serverAddr := record.GetString("serverAddr")
|
||||||
|
serverPort := record.GetInt("serverPort")
|
||||||
|
|
||||||
|
addr := fmt.Sprintf("%s:%d", serverAddr, serverPort)
|
||||||
|
pingResult := utils.PingHost(addr, 5*time.Second)
|
||||||
|
|
||||||
|
networkStatus := &NetworkStatus{
|
||||||
|
Latency: pingResult.Latency,
|
||||||
|
Reachable: pingResult.Reachable,
|
||||||
|
LastCheckTime: time.Now(),
|
||||||
|
Error: pingResult.Error,
|
||||||
|
}
|
||||||
|
|
||||||
|
geoLocation, err := s.getGeoLocationWithCache(serverAddr)
|
||||||
|
if err != nil {
|
||||||
|
s.app.Logger().Warn("Failed to get geo location", "addr", serverAddr, "error", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &ServerNetworkStatus{
|
||||||
|
ServerID: serverID,
|
||||||
|
ServerName: serverName,
|
||||||
|
ServerAddr: serverAddr,
|
||||||
|
ServerPort: serverPort,
|
||||||
|
NetworkStatus: networkStatus,
|
||||||
|
GeoLocation: geoLocation,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// getGeoLocationWithCache retrieves geolocation information with a 24-hour cache.
|
||||||
|
func (s *NetworkService) getGeoLocationWithCache(addr string) (*utils.GeoLocation, error) {
|
||||||
|
s.geoCacheLock.RLock()
|
||||||
|
if item, exists := s.geoCache[addr]; exists {
|
||||||
|
if time.Now().Before(item.ExpiresAt) {
|
||||||
|
s.geoCacheLock.RUnlock()
|
||||||
|
return item.Location, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.geoCacheLock.RUnlock()
|
||||||
|
|
||||||
|
location, err := utils.GetGeoLocation(addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
s.geoCacheLock.Lock()
|
||||||
|
s.geoCache[addr] = &geoCacheItem{
|
||||||
|
Location: location,
|
||||||
|
ExpiresAt: time.Now().Add(24 * time.Hour),
|
||||||
|
}
|
||||||
|
s.geoCacheLock.Unlock()
|
||||||
|
|
||||||
|
return location, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClearGeoCache clears the geolocation cache.
|
||||||
|
func (s *NetworkService) ClearGeoCache() {
|
||||||
|
s.geoCacheLock.Lock()
|
||||||
|
defer s.geoCacheLock.Unlock()
|
||||||
|
s.geoCache = make(map[string]*geoCacheItem)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CleanExpiredCache removes expired entries from the geolocation cache.
|
||||||
|
func (s *NetworkService) CleanExpiredCache() {
|
||||||
|
s.geoCacheLock.Lock()
|
||||||
|
defer s.geoCacheLock.Unlock()
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
for addr, item := range s.geoCache {
|
||||||
|
if now.After(item.ExpiresAt) {
|
||||||
|
delete(s.geoCache, addr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package proxy
|
||||||
|
|
||||||
|
import (
|
||||||
|
proxydomain "frpc-hub/internal/domain/proxy"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
app core.App
|
||||||
|
repo proxydomain.Repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(app core.App, repo proxydomain.Repository) *Service {
|
||||||
|
return &Service{app: app, repo: repo}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetProxyCountByStatus(status proxydomain.ProxyStatus) (int64, error) {
|
||||||
|
return s.repo.CountByStatus(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetProxyCountByBootStatus(status proxydomain.ProxyBootStatus) (int64, error) {
|
||||||
|
return s.repo.CountByBootStatus(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetProxyCountsByType() (map[string]int64, error) {
|
||||||
|
return s.repo.CountByType()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) UpdateProxyBootStatus(proxyID string, status proxydomain.ProxyBootStatus) error {
|
||||||
|
return s.repo.UpdateBootStatus(proxyID, status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) UpdateProxyBootStatusByServerID(serverID string, status proxydomain.ProxyBootStatus) error {
|
||||||
|
return s.repo.UpdateBootStatusByServerID(serverID, status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ResetAllProxyBootStatus() {
|
||||||
|
if err := s.repo.ResetAllBootStatus(); err != nil {
|
||||||
|
s.app.Logger().Error("ResetAllProxyBootStatus failed", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
serverdomain "frpc-hub/internal/domain/server"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
app core.App
|
||||||
|
repo serverdomain.Repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(app core.App, repo serverdomain.Repository) *Service {
|
||||||
|
return &Service{app: app, repo: repo}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetServerCountByStatus(status serverdomain.ServerStatus) (int64, error) {
|
||||||
|
return s.repo.CountByBootStatus(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) UpdateServerBootStatus(serverID string, status serverdomain.ServerStatus) error {
|
||||||
|
return s.repo.UpdateBootStatus(serverID, status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ResetAllServerStatus() {
|
||||||
|
if err := s.repo.ResetAllBootStatus(); err != nil {
|
||||||
|
s.app.Logger().Error("ResetAllServerStatus failed", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetMaxLatency() (int64, error) {
|
||||||
|
return s.repo.GetMaxLatency()
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
package system
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"frpc-hub/pkg/buildinfo"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
const SettingsID = "wcstsqmz8hur331"
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
app core.App
|
||||||
|
}
|
||||||
|
|
||||||
|
type InitializeRequest struct {
|
||||||
|
Email string `json:"email"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
Language string `json:"language"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SettingsResponse struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Initialized bool `json:"initialized"`
|
||||||
|
General map[string]interface{} `json:"general"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateSettingsRequest struct {
|
||||||
|
General map[string]interface{} `json:"general"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(app core.App) *Service {
|
||||||
|
return &Service{app: app}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckInitialized checks if the system has been initialized.
|
||||||
|
func (s *Service) CheckInitialized() (bool, error) {
|
||||||
|
collection, err := s.app.FindCollectionByNameOrId("fh_settings")
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("failed to find settings collection: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
record, err := s.app.FindRecordById(collection, SettingsID)
|
||||||
|
if err != nil {
|
||||||
|
// If record doesn't exist, system is not initialized
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
initialized := record.GetBool("initialized")
|
||||||
|
return initialized, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetSettings retrieves the system settings.
|
||||||
|
func (s *Service) GetSettings() (*SettingsResponse, error) {
|
||||||
|
collection, err := s.app.FindCollectionByNameOrId("fh_settings")
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to find settings collection: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
record, err := s.app.FindRecordById(collection, SettingsID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to find settings record: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
general := make(map[string]interface{})
|
||||||
|
if generalField := record.Get("general"); generalField != nil {
|
||||||
|
if generalMap, ok := generalField.(map[string]interface{}); ok {
|
||||||
|
general = generalMap
|
||||||
|
} else if generalStr, ok := generalField.(string); ok {
|
||||||
|
if err := json.Unmarshal([]byte(generalStr), &general); err != nil {
|
||||||
|
s.app.Logger().Warn("Failed to unmarshal general settings", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &SettingsResponse{
|
||||||
|
ID: record.Id,
|
||||||
|
Initialized: record.GetBool("initialized"),
|
||||||
|
General: general,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateSettings updates the system settings.
|
||||||
|
func (s *Service) UpdateSettings(req *UpdateSettingsRequest) error {
|
||||||
|
if req.General == nil {
|
||||||
|
return errors.New("general settings cannot be nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
generalJSON, err := json.Marshal(req.General)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to marshal general settings: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = s.app.DB().NewQuery(`
|
||||||
|
UPDATE fh_settings
|
||||||
|
SET general = {:general}, updated = STRFTIME('%Y-%m-%d %H:%M:%S', 'now')
|
||||||
|
WHERE id = {:id}
|
||||||
|
`).Bind(map[string]interface{}{
|
||||||
|
"general": string(generalJSON),
|
||||||
|
"id": SettingsID,
|
||||||
|
}).Execute()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to update settings: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
s.app.Logger().Info("Settings updated successfully")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAppVersion returns the application version.
|
||||||
|
func (s *Service) GetAppVersion() string {
|
||||||
|
return buildinfo.AppVersion
|
||||||
|
}
|
||||||
|
|
||||||
|
// LatestVersionResponse holds the latest release info from GitHub.
|
||||||
|
type LatestVersionResponse struct {
|
||||||
|
TagName string `json:"tag_name"`
|
||||||
|
HTMLURL string `json:"html_url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLatestVersion fetches the latest frpc-hub release from GitHub.
|
||||||
|
func (s *Service) GetLatestVersion() (*LatestVersionResponse, error) {
|
||||||
|
client := &http.Client{Timeout: 10 * time.Second}
|
||||||
|
|
||||||
|
req, err := http.NewRequest("GET", "https://api.github.com/repos/luckjiawei/frpc-hub/releases/latest", nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("User-Agent", "frpc-hub-server")
|
||||||
|
req.Header.Set("Accept", "application/vnd.github+json")
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("github api returned status: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
var release LatestVersionResponse
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &release, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// InitializeSystem initializes the system with admin user and settings (with transaction).
|
||||||
|
func (s *Service) InitializeSystem(req *InitializeRequest) error {
|
||||||
|
if req.Email == "" || req.Password == "" {
|
||||||
|
return errors.New("email and password are required")
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.Language != "en" && req.Language != "zh" {
|
||||||
|
req.Language = "en"
|
||||||
|
}
|
||||||
|
|
||||||
|
initialized, err := s.CheckInitialized()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to check initialization status: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if initialized {
|
||||||
|
return errors.New("system is already initialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.app.RunInTransaction(func(txApp core.App) error {
|
||||||
|
usersCollection, err := txApp.FindCollectionByNameOrId("fh_users")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to find users collection: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
userRecord := core.NewRecord(usersCollection)
|
||||||
|
userRecord.Set("email", req.Email)
|
||||||
|
userRecord.Set("password", req.Password)
|
||||||
|
userRecord.Set("passwordConfirm", req.Password)
|
||||||
|
userRecord.Set("emailVisibility", true)
|
||||||
|
|
||||||
|
if err := txApp.Save(userRecord); err != nil {
|
||||||
|
return fmt.Errorf("failed to create admin user: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
settingsCollection, err := txApp.FindCollectionByNameOrId("fh_settings")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to find settings collection: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
settingsRecord, err := txApp.FindRecordById(settingsCollection, SettingsID)
|
||||||
|
if err != nil {
|
||||||
|
settingsRecord = core.NewRecord(settingsCollection)
|
||||||
|
settingsRecord.Set("id", SettingsID)
|
||||||
|
}
|
||||||
|
|
||||||
|
settingsRecord.Set("initialized", true)
|
||||||
|
settingsRecord.Set("general", map[string]interface{}{
|
||||||
|
"defaultLanguage": req.Language,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := txApp.Save(settingsRecord); err != nil {
|
||||||
|
return fmt.Errorf("failed to save settings: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
s.app.Logger().Info("System initialized successfully",
|
||||||
|
"email", req.Email,
|
||||||
|
"language", req.Language,
|
||||||
|
)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package version
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime/debug"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
app core.App
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(app core.App) *Service {
|
||||||
|
return &Service{app: app}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetFrpVersion() string {
|
||||||
|
info, ok := debug.ReadBuildInfo()
|
||||||
|
if !ok {
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, dep := range info.Deps {
|
||||||
|
if dep.Path == "github.com/fatedier/frp" {
|
||||||
|
return dep.Version
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package proxy
|
||||||
|
|
||||||
|
import "frpc-hub/pkg/types"
|
||||||
|
|
||||||
|
// Proxy represents a frpc proxy configuration record.
|
||||||
|
type Proxy struct {
|
||||||
|
Id string `db:"id" json:"id"`
|
||||||
|
ServerId string `db:"serverId" json:"serverId"`
|
||||||
|
ProxyType string `db:"proxyType" json:"proxyType"`
|
||||||
|
Name string `db:"name" json:"name"`
|
||||||
|
LocalIP string `db:"localIP" json:"localIp"`
|
||||||
|
LocalPort types.NullableInt `db:"localPort" json:"localPort"`
|
||||||
|
RemotePort types.NullableInt `db:"remotePort" json:"remotePort,omitempty"`
|
||||||
|
Subdomain string `db:"subdomain" json:"subdomain"`
|
||||||
|
CustomDomains types.JSONStringArray `db:"customDomains" json:"customDomains"`
|
||||||
|
Transport types.JSONMap `db:"transport" json:"transport"`
|
||||||
|
Description string `db:"description" json:"description"`
|
||||||
|
Status string `db:"status" json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProxyStatus string
|
||||||
|
|
||||||
|
const (
|
||||||
|
ProxyStatusEnabled ProxyStatus = "enabled"
|
||||||
|
ProxyStatusDisabled ProxyStatus = "disabled"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ProxyBootStatus string
|
||||||
|
|
||||||
|
const (
|
||||||
|
ProxyBootStatusOnline ProxyBootStatus = "online"
|
||||||
|
ProxyBootStatusOffline ProxyBootStatus = "offline"
|
||||||
|
)
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package proxy
|
||||||
|
|
||||||
|
// Repository defines persistence operations for the proxy domain.
|
||||||
|
type Repository interface {
|
||||||
|
CountByStatus(status ProxyStatus) (int64, error)
|
||||||
|
CountByBootStatus(status ProxyBootStatus) (int64, error)
|
||||||
|
CountByType() (map[string]int64, error)
|
||||||
|
UpdateBootStatus(id string, status ProxyBootStatus) error
|
||||||
|
UpdateBootStatusByServerID(serverID string, status ProxyBootStatus) error
|
||||||
|
ResetAllBootStatus() error
|
||||||
|
FindByServerID(serverID string) ([]Proxy, error)
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
type ServerStatus string
|
||||||
|
|
||||||
|
const (
|
||||||
|
ServerStatusRunning ServerStatus = "running"
|
||||||
|
ServerStatusStopped ServerStatus = "stopped"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ServerRecord is a lightweight struct for DB scanning operations.
|
||||||
|
type ServerRecord struct {
|
||||||
|
ID string `db:"id"`
|
||||||
|
ServerName string `db:"serverName"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
// Repository defines persistence operations for the server domain.
|
||||||
|
type Repository interface {
|
||||||
|
CountByBootStatus(status ServerStatus) (int64, error)
|
||||||
|
UpdateBootStatus(id string, status ServerStatus) error
|
||||||
|
ResetAllBootStatus() error
|
||||||
|
GetMaxLatency() (int64, error)
|
||||||
|
FindAllWithAutoConnect() ([]ServerRecord, error)
|
||||||
|
}
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
package persistence
|
||||||
|
|
||||||
|
import (
|
||||||
|
"frpc-hub/internal/domain/proxy"
|
||||||
|
|
||||||
|
"github.com/pocketbase/dbx"
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ProxyRepository struct {
|
||||||
|
app core.App
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewProxyRepository(app core.App) *ProxyRepository {
|
||||||
|
return &ProxyRepository{app: app}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProxyRepository) CountByStatus(status proxy.ProxyStatus) (int64, error) {
|
||||||
|
var count int64
|
||||||
|
err := r.app.DB().
|
||||||
|
Select("COUNT(*)").
|
||||||
|
From("fh_proxies").
|
||||||
|
Where(dbx.HashExp{"status": string(status)}).
|
||||||
|
Row(&count)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
r.app.Logger().Error("Failed to get proxy count by status", "error", err)
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProxyRepository) CountByBootStatus(status proxy.ProxyBootStatus) (int64, error) {
|
||||||
|
var count int64
|
||||||
|
err := r.app.DB().
|
||||||
|
Select("COUNT(*)").
|
||||||
|
From("fh_proxies").
|
||||||
|
Where(dbx.HashExp{"bootStatus": string(status)}).
|
||||||
|
Row(&count)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
r.app.Logger().Error("Failed to get proxy count by bootStatus", "error", err)
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProxyRepository) CountByType() (map[string]int64, error) {
|
||||||
|
type proxyTypeCount struct {
|
||||||
|
ProxyType string `db:"proxyType"`
|
||||||
|
Count int64 `db:"count"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var results []proxyTypeCount
|
||||||
|
err := r.app.DB().
|
||||||
|
Select("proxyType", "COUNT(*) as count").
|
||||||
|
From("fh_proxies").
|
||||||
|
GroupBy("proxyType").
|
||||||
|
All(&results)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
r.app.Logger().Error("Failed to get proxy counts by type", "error", err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
counts := make(map[string]int64)
|
||||||
|
for _, result := range results {
|
||||||
|
counts[result.ProxyType] = result.Count
|
||||||
|
}
|
||||||
|
|
||||||
|
return counts, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProxyRepository) UpdateBootStatus(id string, status proxy.ProxyBootStatus) error {
|
||||||
|
r.app.Logger().Info("Update proxy boot status", "id", id, "status", status)
|
||||||
|
|
||||||
|
result, err := r.app.DB().
|
||||||
|
Update("fh_proxies", dbx.Params{
|
||||||
|
"bootStatus": string(status),
|
||||||
|
}, dbx.HashExp{
|
||||||
|
"id": id,
|
||||||
|
}).
|
||||||
|
Execute()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
r.app.Logger().Error("Failed to update proxy boot status", "id", id, "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
rowsAffected, _ := result.RowsAffected()
|
||||||
|
r.app.Logger().Info("Proxy boot status updated successfully", "id", id, "status", status, "rowsAffected", rowsAffected)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProxyRepository) UpdateBootStatusByServerID(serverID string, status proxy.ProxyBootStatus) error {
|
||||||
|
r.app.Logger().Info("Update proxy boot status by server id", "id", serverID, "status", status)
|
||||||
|
|
||||||
|
result, err := r.app.DB().
|
||||||
|
Update("fh_proxies", dbx.Params{
|
||||||
|
"bootStatus": string(status),
|
||||||
|
}, dbx.HashExp{
|
||||||
|
"serverId": serverID,
|
||||||
|
}).
|
||||||
|
Execute()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
r.app.Logger().Error("Failed to update proxy boot status by server id", "serverID", serverID, "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
rowsAffected, _ := result.RowsAffected()
|
||||||
|
r.app.Logger().Info("Proxy boot status updated successfully", "serverID", serverID, "status", status, "count", rowsAffected)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProxyRepository) ResetAllBootStatus() error {
|
||||||
|
r.app.Logger().Info("Resetting all proxy boot status to offline")
|
||||||
|
|
||||||
|
result, err := r.app.DB().
|
||||||
|
Update("fh_proxies", dbx.Params{
|
||||||
|
"bootStatus": string(proxy.ProxyBootStatusOffline),
|
||||||
|
}, dbx.Not(dbx.HashExp{
|
||||||
|
"bootStatus": string(proxy.ProxyBootStatusOffline),
|
||||||
|
})).
|
||||||
|
Execute()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
r.app.Logger().Error("Failed to reset proxy boot status", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
rowsAffected, _ := result.RowsAffected()
|
||||||
|
r.app.Logger().Info("Proxy boot status reset completed", "count", rowsAffected)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ProxyRepository) FindByServerID(serverID string) ([]proxy.Proxy, error) {
|
||||||
|
var proxies []proxy.Proxy
|
||||||
|
err := r.app.DB().
|
||||||
|
Select("fh_proxies.*").
|
||||||
|
From("fh_proxies").
|
||||||
|
Where(dbx.HashExp{"serverId": serverID}).
|
||||||
|
All(&proxies)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
r.app.Logger().Error("Failed to find proxies by server id", "serverID", serverID, "error", err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
package persistence
|
||||||
|
|
||||||
|
import (
|
||||||
|
"frpc-hub/internal/domain/server"
|
||||||
|
|
||||||
|
"github.com/pocketbase/dbx"
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ServerRepository struct {
|
||||||
|
app core.App
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewServerRepository(app core.App) *ServerRepository {
|
||||||
|
return &ServerRepository{app: app}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ServerRepository) CountByBootStatus(status server.ServerStatus) (int64, error) {
|
||||||
|
var count int64
|
||||||
|
err := r.app.DB().
|
||||||
|
Select("COUNT(*)").
|
||||||
|
From("fh_servers").
|
||||||
|
Where(dbx.HashExp{"bootStatus": string(status)}).
|
||||||
|
Row(&count)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
r.app.Logger().Error("Failed to get server count by status", "error", err)
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ServerRepository) UpdateBootStatus(id string, status server.ServerStatus) error {
|
||||||
|
r.app.Logger().Info("Update server boot status", "id", id, "status", status)
|
||||||
|
|
||||||
|
result, err := r.app.DB().
|
||||||
|
Update("fh_servers",
|
||||||
|
dbx.Params{"bootStatus": string(status)},
|
||||||
|
dbx.NewExp("id = {:id} AND bootStatus != {:status}", dbx.Params{
|
||||||
|
"id": id,
|
||||||
|
"status": string(status),
|
||||||
|
}),
|
||||||
|
).Execute()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
r.app.Logger().Error("Failed to update server boot status", "id", id, "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
rowsAffected, _ := result.RowsAffected()
|
||||||
|
if rowsAffected > 0 {
|
||||||
|
r.app.Logger().Info("Server boot status updated successfully", "id", id, "status", status)
|
||||||
|
} else {
|
||||||
|
r.app.Logger().Debug("Server boot status unchanged", "id", id, "status", status)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ServerRepository) ResetAllBootStatus() error {
|
||||||
|
r.app.Logger().Info("Resetting all server status to stopped")
|
||||||
|
|
||||||
|
result, err := r.app.DB().
|
||||||
|
Update("fh_servers",
|
||||||
|
dbx.Params{"bootStatus": string(server.ServerStatusStopped)},
|
||||||
|
dbx.NewExp("bootStatus != {:status} AND bootStatus != ''", dbx.Params{"status": string(server.ServerStatusStopped)}),
|
||||||
|
).Execute()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
r.app.Logger().Error("Failed to reset server status", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
rowsAffected, _ := result.RowsAffected()
|
||||||
|
r.app.Logger().Info("Server status reset completed", "count", rowsAffected)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ServerRepository) GetMaxLatency() (int64, error) {
|
||||||
|
var maxLatency int64
|
||||||
|
err := r.app.DB().
|
||||||
|
Select("MAX(CAST(json_extract(networkStatus, '$.latency') AS INTEGER))").
|
||||||
|
From("fh_servers").
|
||||||
|
Where(dbx.NewExp("networkStatus IS NOT NULL AND networkStatus != ''")).
|
||||||
|
Row(&maxLatency)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
r.app.Logger().Error("Failed to get max latency", "error", err)
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return maxLatency, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ServerRepository) FindAllWithAutoConnect() ([]server.ServerRecord, error) {
|
||||||
|
records, err := r.app.FindAllRecords("fh_servers", dbx.HashExp{"autoConnection": true})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result := make([]server.ServerRecord, 0, len(records))
|
||||||
|
for _, rec := range records {
|
||||||
|
result = append(result, server.ServerRecord{
|
||||||
|
ID: rec.Id,
|
||||||
|
ServerName: rec.GetString("serverName"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package httphandler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"frpc-hub/internal/application/dashboard"
|
||||||
|
"frpc-hub/pkg/response"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type DashboardHandler struct {
|
||||||
|
dashboardService *dashboard.Service
|
||||||
|
}
|
||||||
|
|
||||||
|
type DashboardStatsVo struct {
|
||||||
|
RunningCount int64 `json:"runningCount"`
|
||||||
|
StoppedCount int64 `json:"stoppedCount"`
|
||||||
|
ProxiesEnabledCount int64 `json:"proxiesEnabledCount"`
|
||||||
|
ProxiesDisabledCount int64 `json:"proxiesDisabledCount"`
|
||||||
|
ProxiesOnlineCount int64 `json:"proxiesOnlineCount"`
|
||||||
|
MaxLatency int64 `json:"maxLatency"`
|
||||||
|
ProxyTypeCounts map[string]int64 `json:"proxyTypeCounts"`
|
||||||
|
UptimeSeconds int64 `json:"uptimeSeconds"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDashboardHandler(dashboardService *dashboard.Service) *DashboardHandler {
|
||||||
|
return &DashboardHandler{dashboardService: dashboardService}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (dh *DashboardHandler) RegisterHandlers(e *core.ServeEvent) {
|
||||||
|
e.Router.GET("/api/dashboard/topology", func(e *core.RequestEvent) error {
|
||||||
|
data, err := dh.dashboardService.GetTopology()
|
||||||
|
if err != nil {
|
||||||
|
return e.JSON(500, response.Error(err))
|
||||||
|
}
|
||||||
|
return e.JSON(200, data)
|
||||||
|
})
|
||||||
|
|
||||||
|
e.Router.GET("/api/dashboard/stats", func(e *core.RequestEvent) error {
|
||||||
|
stats, err := dh.dashboardService.GetStats()
|
||||||
|
if err != nil {
|
||||||
|
return e.JSON(500, response.Error(err))
|
||||||
|
}
|
||||||
|
return e.JSON(200, DashboardStatsVo{
|
||||||
|
RunningCount: stats.RunningCount,
|
||||||
|
StoppedCount: stats.StoppedCount,
|
||||||
|
ProxiesEnabledCount: stats.ProxiesEnabledCount,
|
||||||
|
ProxiesDisabledCount: stats.ProxiesDisabledCount,
|
||||||
|
ProxiesOnlineCount: stats.ProxiesOnlineCount,
|
||||||
|
MaxLatency: stats.MaxLatency,
|
||||||
|
ProxyTypeCounts: stats.ProxyTypeCounts,
|
||||||
|
UptimeSeconds: stats.UptimeSeconds,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package httphandler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"frpc-hub/internal/application/frpc"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FrpcHandler struct {
|
||||||
|
app core.App
|
||||||
|
service *frpc.Service
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFrpcHandler(app core.App, service *frpc.Service) *FrpcHandler {
|
||||||
|
return &FrpcHandler{
|
||||||
|
app: app,
|
||||||
|
service: service,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *FrpcHandler) RegisterHandlers(e *core.ServeEvent) {
|
||||||
|
e.Router.POST("/api/frpc/launch", func(e *core.RequestEvent) error {
|
||||||
|
data := struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}{}
|
||||||
|
if err := e.BindBody(&data); err != nil {
|
||||||
|
return e.JSON(400, map[string]string{"error": "invalid request body"})
|
||||||
|
}
|
||||||
|
id := data.ID
|
||||||
|
if id == "" {
|
||||||
|
return e.JSON(400, map[string]string{"error": "id is required"})
|
||||||
|
}
|
||||||
|
err := h.service.LaunchFrpc(&id)
|
||||||
|
if err != nil {
|
||||||
|
return e.JSON(500, map[string]string{"error": err.Error()})
|
||||||
|
}
|
||||||
|
return e.JSON(200, map[string]string{"message": "frpc started"})
|
||||||
|
})
|
||||||
|
|
||||||
|
e.Router.GET("/api/frpc/logs/stream", func(e *core.RequestEvent) error {
|
||||||
|
id := e.Request.URL.Query().Get("id")
|
||||||
|
if id == "" {
|
||||||
|
return e.JSON(400, map[string]string{"error": "id is required"})
|
||||||
|
}
|
||||||
|
|
||||||
|
w := e.Response
|
||||||
|
w.Header().Set("Content-Type", "text/event-stream")
|
||||||
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
|
w.Header().Set("Connection", "keep-alive")
|
||||||
|
|
||||||
|
flusher, ok := w.(http.Flusher)
|
||||||
|
if !ok {
|
||||||
|
return e.JSON(500, map[string]string{"error": "streaming not supported"})
|
||||||
|
}
|
||||||
|
|
||||||
|
h.service.StreamLog(id, e.Request.Context(), w, flusher)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
e.Router.POST("/api/frpc/terminate", func(e *core.RequestEvent) error {
|
||||||
|
data := struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}{}
|
||||||
|
if err := e.BindBody(&data); err != nil {
|
||||||
|
return e.JSON(400, map[string]string{"error": "invalid request body"})
|
||||||
|
}
|
||||||
|
id := data.ID
|
||||||
|
if id == "" {
|
||||||
|
return e.JSON(400, map[string]string{"error": "id is required"})
|
||||||
|
}
|
||||||
|
err := h.service.TerminateFrpc(&id)
|
||||||
|
if err != nil {
|
||||||
|
return e.JSON(500, map[string]string{"error": err.Error()})
|
||||||
|
}
|
||||||
|
return e.JSON(200, map[string]string{"message": "frpc terminated"})
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package httphandler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"frpc-hub/internal/application/github"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GithubHandler struct {
|
||||||
|
app core.App
|
||||||
|
service *github.Service
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewGithubHandler(app core.App, service *github.Service) *GithubHandler {
|
||||||
|
return &GithubHandler{
|
||||||
|
app: app,
|
||||||
|
service: service,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *GithubHandler) RegisterHandlers(e *core.ServeEvent) {
|
||||||
|
e.Router.GET("/api/github/frp/releases", func(e *core.RequestEvent) error {
|
||||||
|
releases, err := h.service.GetFrpReleases()
|
||||||
|
if err != nil {
|
||||||
|
return e.JSON(500, map[string]string{"error": err.Error()})
|
||||||
|
}
|
||||||
|
return e.JSON(200, releases)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package httphandler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"frpc-hub/internal/application/importer"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ImportHandler struct {
|
||||||
|
app core.App
|
||||||
|
service *importer.Service
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewImportHandler(app core.App, service *importer.Service) *ImportHandler {
|
||||||
|
return &ImportHandler{app: app, service: service}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *ImportHandler) RegisterHandlers(e *core.ServeEvent) {
|
||||||
|
// Preview: parse TOML content and return server/proxy info with duplicate flags
|
||||||
|
e.Router.POST("/api/import/preview", func(e *core.RequestEvent) error {
|
||||||
|
var req importer.ParseTomlRequest
|
||||||
|
if err := e.BindBody(&req); err != nil {
|
||||||
|
return e.JSON(http.StatusBadRequest, map[string]interface{}{
|
||||||
|
"error": "invalid request body",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if req.TomlContent == "" {
|
||||||
|
return e.JSON(http.StatusBadRequest, map[string]interface{}{
|
||||||
|
"error": "TOML content cannot be empty",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
preview, err := h.service.ParseToml(&req)
|
||||||
|
if err != nil {
|
||||||
|
return e.JSON(http.StatusBadRequest, map[string]interface{}{
|
||||||
|
"error": err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return e.JSON(http.StatusOK, preview)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Execute: import servers and proxies within a transaction
|
||||||
|
e.Router.POST("/api/import/execute", func(e *core.RequestEvent) error {
|
||||||
|
var req importer.ExecuteImportRequest
|
||||||
|
if err := e.BindBody(&req); err != nil {
|
||||||
|
return e.JSON(http.StatusBadRequest, map[string]interface{}{
|
||||||
|
"error": "invalid request body",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if req.TomlContent == "" {
|
||||||
|
return e.JSON(http.StatusBadRequest, map[string]interface{}{
|
||||||
|
"error": "TOML content cannot be empty",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := h.service.ExecuteImport(&req)
|
||||||
|
if err != nil {
|
||||||
|
return e.JSON(http.StatusInternalServerError, map[string]interface{}{
|
||||||
|
"error": err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return e.JSON(http.StatusOK, map[string]interface{}{
|
||||||
|
"message": "import successful",
|
||||||
|
"result": result,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package httphandler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"frpc-hub/internal/application/system"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SystemHandler struct {
|
||||||
|
app core.App
|
||||||
|
service *system.Service
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSystemHandler(app core.App, service *system.Service) *SystemHandler {
|
||||||
|
return &SystemHandler{
|
||||||
|
app: app,
|
||||||
|
service: service,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *SystemHandler) RegisterHandlers(e *core.ServeEvent) {
|
||||||
|
e.Router.GET("/api/system/initialized", func(e *core.RequestEvent) error {
|
||||||
|
initialized, err := h.service.CheckInitialized()
|
||||||
|
if err != nil {
|
||||||
|
return e.JSON(http.StatusInternalServerError, map[string]interface{}{
|
||||||
|
"error": err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return e.JSON(http.StatusOK, map[string]interface{}{
|
||||||
|
"initialized": initialized,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
e.Router.GET("/api/system/settings", func(e *core.RequestEvent) error {
|
||||||
|
settings, err := h.service.GetSettings()
|
||||||
|
if err != nil {
|
||||||
|
return e.JSON(http.StatusInternalServerError, map[string]interface{}{
|
||||||
|
"error": err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return e.JSON(http.StatusOK, settings)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Update system settings
|
||||||
|
e.Router.PUT("/api/system/settings", func(e *core.RequestEvent) error {
|
||||||
|
var req system.UpdateSettingsRequest
|
||||||
|
if err := e.BindBody(&req); err != nil {
|
||||||
|
return e.JSON(http.StatusBadRequest, map[string]interface{}{
|
||||||
|
"error": "Invalid request body",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.service.UpdateSettings(&req); err != nil {
|
||||||
|
return e.JSON(http.StatusInternalServerError, map[string]interface{}{
|
||||||
|
"error": err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return e.JSON(http.StatusOK, map[string]interface{}{
|
||||||
|
"message": "Settings updated successfully",
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
e.Router.GET("/api/system/version", func(e *core.RequestEvent) error {
|
||||||
|
return e.JSON(http.StatusOK, map[string]string{
|
||||||
|
"version": h.service.GetAppVersion(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
e.Router.GET("/api/system/latest-version", func(e *core.RequestEvent) error {
|
||||||
|
latest, err := h.service.GetLatestVersion()
|
||||||
|
if err != nil {
|
||||||
|
return e.JSON(http.StatusInternalServerError, map[string]interface{}{
|
||||||
|
"error": err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return e.JSON(http.StatusOK, latest)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Initialize system (create admin user and settings)
|
||||||
|
e.Router.POST("/api/system/initialize", func(e *core.RequestEvent) error {
|
||||||
|
var req system.InitializeRequest
|
||||||
|
if err := e.BindBody(&req); err != nil {
|
||||||
|
return e.JSON(http.StatusBadRequest, map[string]interface{}{
|
||||||
|
"error": "Invalid request body",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.service.InitializeSystem(&req); err != nil {
|
||||||
|
return e.JSON(http.StatusBadRequest, map[string]interface{}{
|
||||||
|
"error": err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return e.JSON(http.StatusOK, map[string]interface{}{
|
||||||
|
"message": "System initialized successfully",
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package httphandler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"frpc-hub/internal/application/version"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type VersionHandler struct {
|
||||||
|
app core.App
|
||||||
|
service *version.Service
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewVersionHandler(app core.App, service *version.Service) *VersionHandler {
|
||||||
|
return &VersionHandler{
|
||||||
|
app: app,
|
||||||
|
service: service,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *VersionHandler) RegisterHandlers(e *core.ServeEvent) {
|
||||||
|
e.Router.GET("/api/frp/version", func(e *core.RequestEvent) error {
|
||||||
|
return e.JSON(200, map[string]string{
|
||||||
|
"frp": h.service.GetFrpVersion(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"embed"
|
||||||
|
"io/fs"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"frpc-hub/internal/application/dashboard"
|
||||||
|
"frpc-hub/internal/application/frpc"
|
||||||
|
"frpc-hub/internal/application/importer"
|
||||||
|
"frpc-hub/internal/application/monitoring"
|
||||||
|
"frpc-hub/internal/application/proxy"
|
||||||
|
"frpc-hub/internal/application/server"
|
||||||
|
"frpc-hub/internal/application/system"
|
||||||
|
"frpc-hub/internal/application/version"
|
||||||
|
"frpc-hub/internal/infrastructure/persistence"
|
||||||
|
httphandler "frpc-hub/internal/interfaces/http"
|
||||||
|
_ "frpc-hub/migrations"
|
||||||
|
|
||||||
|
"github.com/pocketbase/pocketbase"
|
||||||
|
"github.com/pocketbase/pocketbase/apis"
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
"github.com/pocketbase/pocketbase/plugins/migratecmd"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed all:pb_public
|
||||||
|
var pbPublicDir embed.FS
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
app := pocketbase.New()
|
||||||
|
|
||||||
|
// enable auto creation of migration files when using the "migrate" command
|
||||||
|
migratecmd.MustRegister(app, app.RootCmd, migratecmd.Config{
|
||||||
|
Automigrate: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Infrastructure (Repository implementations)
|
||||||
|
serverRepo := persistence.NewServerRepository(app)
|
||||||
|
proxyRepo := persistence.NewProxyRepository(app)
|
||||||
|
|
||||||
|
// Application Services
|
||||||
|
serverService := server.NewService(app, serverRepo)
|
||||||
|
proxyService := proxy.NewService(app, proxyRepo)
|
||||||
|
frpcService := frpc.NewService(app, serverRepo, proxyRepo)
|
||||||
|
dashboardService := dashboard.NewService(app, serverService, proxyService)
|
||||||
|
settingsService := system.NewService(app)
|
||||||
|
networkService := monitoring.NewNetworkService(app)
|
||||||
|
networkMonitorService := monitoring.NewMonitorService(app, networkService)
|
||||||
|
importService := importer.NewService(app)
|
||||||
|
versionService := version.NewService(app)
|
||||||
|
//githubService := github.NewService(app)
|
||||||
|
|
||||||
|
// HTTP Handlers
|
||||||
|
//githubHandler := httphandler.NewGithubHandler(app, githubService)
|
||||||
|
frpcHandler := httphandler.NewFrpcHandler(app, frpcService)
|
||||||
|
versionHandler := httphandler.NewVersionHandler(app, versionService)
|
||||||
|
dashboardHandler := httphandler.NewDashboardHandler(dashboardService)
|
||||||
|
systemHandler := httphandler.NewSystemHandler(app, settingsService)
|
||||||
|
importHandler := httphandler.NewImportHandler(app, importService)
|
||||||
|
|
||||||
|
// Hook: Reload frpc when proxy is updated
|
||||||
|
app.OnRecordAfterUpdateSuccess("fh_proxies").BindFunc(func(e *core.RecordEvent) error {
|
||||||
|
serverId := e.Record.GetString("serverId")
|
||||||
|
if serverId != "" {
|
||||||
|
// Check if the server is currently running
|
||||||
|
if frpcService.IsServerRunning(serverId) {
|
||||||
|
app.Logger().Info("Proxy updated, reloading frpc configuration", "proxyId", e.Record.Id, "serverId", serverId)
|
||||||
|
if err := frpcService.ReloadFrpc(&serverId); err != nil {
|
||||||
|
app.Logger().Error("Failed to reload frpc after proxy update", "error", err, "serverId", serverId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return e.Next()
|
||||||
|
})
|
||||||
|
|
||||||
|
// register custom routes
|
||||||
|
app.OnServe().BindFunc(func(e *core.ServeEvent) error {
|
||||||
|
// Reset all server statuses to stopped on startup
|
||||||
|
serverService.ResetAllServerStatus()
|
||||||
|
// Reset all proxy statuses to offline on startup
|
||||||
|
proxyService.ResetAllProxyBootStatus()
|
||||||
|
|
||||||
|
// Auto-start servers with autoConnection enabled (non-blocking)
|
||||||
|
go frpcService.AutoStartServers()
|
||||||
|
|
||||||
|
// Start network monitoring service
|
||||||
|
// Latency check: every 30 seconds (frequent for real-time monitoring)
|
||||||
|
// Geolocation check: every 24 hours (only for servers without geo data)
|
||||||
|
networkMonitorService.Start(5*time.Second, 24*time.Hour)
|
||||||
|
|
||||||
|
// Register routes for each module
|
||||||
|
//githubHandler.RegisterHandlers(e)
|
||||||
|
frpcHandler.RegisterHandlers(e)
|
||||||
|
versionHandler.RegisterHandlers(e)
|
||||||
|
dashboardHandler.RegisterHandlers(e)
|
||||||
|
systemHandler.RegisterHandlers(e)
|
||||||
|
importHandler.RegisterHandlers(e)
|
||||||
|
|
||||||
|
// Serve static files from embedded FS
|
||||||
|
content, err := fs.Sub(pbPublicDir, "pb_public")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if index.html exists to ensure frontend is properly embedded
|
||||||
|
if _, err := content.Open("index.html"); err != nil {
|
||||||
|
log.Printf("WARNING: index.html not found in embedded assets! Frontend may not load. Error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.Router.GET("/{path...}", apis.Static(content, true))
|
||||||
|
|
||||||
|
return e.Next()
|
||||||
|
})
|
||||||
|
|
||||||
|
// Overwrite the default serve command to suppress the default startup banner
|
||||||
|
// and use our custom logs
|
||||||
|
for _, cmd := range app.RootCmd.Commands() {
|
||||||
|
if cmd.Use == "serve" {
|
||||||
|
cmd.Run = nil
|
||||||
|
cmd.RunE = func(cmd *cobra.Command, args []string) error {
|
||||||
|
domains := args
|
||||||
|
|
||||||
|
httpAddr, _ := cmd.Flags().GetString("http")
|
||||||
|
httpsAddr, _ := cmd.Flags().GetString("https")
|
||||||
|
origins, _ := cmd.Flags().GetStringSlice("origins")
|
||||||
|
|
||||||
|
// replicate default logic from pocketbase
|
||||||
|
if httpAddr == "" {
|
||||||
|
if len(domains) > 0 {
|
||||||
|
httpAddr = "0.0.0.0:80"
|
||||||
|
} else {
|
||||||
|
httpAddr = "127.0.0.1:8090"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if httpsAddr == "" {
|
||||||
|
if len(domains) > 0 {
|
||||||
|
httpsAddr = "0.0.0.0:443"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("Starting PocketBase server...")
|
||||||
|
log.Println("----------------------------------------------------------------")
|
||||||
|
log.Println("Frontend: http://" + httpAddr + "/")
|
||||||
|
log.Println("Admin UI: http://" + httpAddr + "/_/")
|
||||||
|
log.Println("----------------------------------------------------------------")
|
||||||
|
|
||||||
|
return apis.Serve(app, apis.ServeConfig{
|
||||||
|
HttpAddr: httpAddr,
|
||||||
|
HttpsAddr: httpsAddr,
|
||||||
|
ShowStartBanner: false,
|
||||||
|
AllowedOrigins: origins,
|
||||||
|
CertificateDomains: domains,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := app.Start(); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,5 @@
|
|||||||
|
package buildinfo
|
||||||
|
|
||||||
|
// AppVersion is the single source of truth for the application version.
|
||||||
|
// Update this value to release a new version.
|
||||||
|
const AppVersion = "1.0.0"
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package response
|
||||||
|
|
||||||
|
type ErrorResponse struct {
|
||||||
|
Error string `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func InternalServerError() ErrorResponse {
|
||||||
|
return ErrorResponse{Error: "Internal Server Error"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Error(err error) ErrorResponse {
|
||||||
|
return ErrorResponse{Error: err.Error()}
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
package types
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql/driver"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NullableInt is a custom type for nullable int that can handle empty strings
|
||||||
|
type NullableInt struct {
|
||||||
|
Int int
|
||||||
|
Valid bool // Valid is true if Int is not NULL
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scan implements sql.Scanner interface
|
||||||
|
func (n *NullableInt) Scan(value interface{}) error {
|
||||||
|
if value == nil {
|
||||||
|
n.Valid = false
|
||||||
|
n.Int = 0
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch v := value.(type) {
|
||||||
|
case int64:
|
||||||
|
n.Int = int(v)
|
||||||
|
n.Valid = true
|
||||||
|
return nil
|
||||||
|
case int:
|
||||||
|
n.Int = v
|
||||||
|
n.Valid = true
|
||||||
|
return nil
|
||||||
|
case string:
|
||||||
|
if v == "" {
|
||||||
|
n.Valid = false
|
||||||
|
n.Int = 0
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// Try to parse string to int
|
||||||
|
var i int
|
||||||
|
_, err := fmt.Sscanf(v, "%d", &i)
|
||||||
|
if err != nil {
|
||||||
|
n.Valid = false
|
||||||
|
n.Int = 0
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
n.Int = i
|
||||||
|
n.Valid = true
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
n.Valid = false
|
||||||
|
n.Int = 0
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Value implements driver.Valuer interface
|
||||||
|
func (n NullableInt) Value() (driver.Value, error) {
|
||||||
|
if !n.Valid {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return int64(n.Int), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalJSON implements json.Marshaler interface
|
||||||
|
func (n NullableInt) MarshalJSON() ([]byte, error) {
|
||||||
|
if !n.Valid {
|
||||||
|
return []byte("null"), nil
|
||||||
|
}
|
||||||
|
return json.Marshal(n.Int)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnmarshalJSON implements json.Unmarshaler interface
|
||||||
|
func (n *NullableInt) UnmarshalJSON(data []byte) error {
|
||||||
|
if string(data) == "null" || string(data) == "\"\"" {
|
||||||
|
n.Valid = false
|
||||||
|
n.Int = 0
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var i int
|
||||||
|
if err := json.Unmarshal(data, &i); err != nil {
|
||||||
|
n.Valid = false
|
||||||
|
n.Int = 0
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
n.Int = i
|
||||||
|
n.Valid = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// JSONStringArray is a custom type for []string that can be scanned from JSON
|
||||||
|
type JSONStringArray []string
|
||||||
|
|
||||||
|
// Scan implements sql.Scanner interface
|
||||||
|
func (j *JSONStringArray) Scan(value interface{}) error {
|
||||||
|
if value == nil {
|
||||||
|
*j = []string{}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var bytes []byte
|
||||||
|
switch v := value.(type) {
|
||||||
|
case []byte:
|
||||||
|
bytes = v
|
||||||
|
case string:
|
||||||
|
bytes = []byte(v)
|
||||||
|
default:
|
||||||
|
return errors.New("type assertion to []byte or string failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
var arr []string
|
||||||
|
if err := json.Unmarshal(bytes, &arr); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
*j = arr
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Value implements driver.Valuer interface
|
||||||
|
func (j JSONStringArray) Value() (driver.Value, error) {
|
||||||
|
if j == nil {
|
||||||
|
return "[]", nil
|
||||||
|
}
|
||||||
|
bytes, err := json.Marshal(j)
|
||||||
|
return string(bytes), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// JSONMap is a custom type for map[string]interface{} that can be scanned from JSON
|
||||||
|
type JSONMap map[string]interface{}
|
||||||
|
|
||||||
|
// Scan implements sql.Scanner interface
|
||||||
|
func (j *JSONMap) Scan(value interface{}) error {
|
||||||
|
if value == nil {
|
||||||
|
*j = map[string]interface{}{}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var bytes []byte
|
||||||
|
switch v := value.(type) {
|
||||||
|
case []byte:
|
||||||
|
bytes = v
|
||||||
|
case string:
|
||||||
|
bytes = []byte(v)
|
||||||
|
default:
|
||||||
|
return errors.New("type assertion to []byte or string failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
var m map[string]interface{}
|
||||||
|
if err := json.Unmarshal(bytes, &m); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
*j = m
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Value implements driver.Valuer interface
|
||||||
|
func (j JSONMap) Value() (driver.Value, error) {
|
||||||
|
if j == nil {
|
||||||
|
return "{}", nil
|
||||||
|
}
|
||||||
|
bytes, err := json.Marshal(j)
|
||||||
|
return string(bytes), err
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import "os"
|
||||||
|
|
||||||
|
// ReadLastNLines reads the last n lines from a file.
|
||||||
|
func ReadLastNLines(file *os.File, n int) []string {
|
||||||
|
fi, err := file.Stat()
|
||||||
|
if err != nil || fi.Size() == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := make([]byte, 0, 4096)
|
||||||
|
pos := fi.Size()
|
||||||
|
|
||||||
|
for pos > 0 {
|
||||||
|
chunkSize := int64(4096)
|
||||||
|
if chunkSize > pos {
|
||||||
|
chunkSize = pos
|
||||||
|
}
|
||||||
|
pos -= chunkSize
|
||||||
|
|
||||||
|
chunk := make([]byte, chunkSize)
|
||||||
|
file.ReadAt(chunk, pos)
|
||||||
|
buf = append(chunk, buf...)
|
||||||
|
|
||||||
|
// Count newlines; stop reading more chunks once we have enough
|
||||||
|
count := 0
|
||||||
|
for _, b := range buf {
|
||||||
|
if b == '\n' {
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if count > n+1 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse lines from buf
|
||||||
|
var lines []string
|
||||||
|
start := 0
|
||||||
|
for i, b := range buf {
|
||||||
|
if b == '\n' {
|
||||||
|
line := string(buf[start:i])
|
||||||
|
if line != "" {
|
||||||
|
lines = append(lines, line)
|
||||||
|
}
|
||||||
|
start = i + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if start < len(buf) {
|
||||||
|
line := string(buf[start:])
|
||||||
|
if line != "" {
|
||||||
|
lines = append(lines, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(lines) > n {
|
||||||
|
lines = lines[len(lines)-n:]
|
||||||
|
}
|
||||||
|
return lines
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
// FormatBytes formats bytes to human readable format
|
||||||
|
func FormatBytes(bytes uint64) string {
|
||||||
|
const unit = 1024
|
||||||
|
if bytes < unit {
|
||||||
|
return fmt.Sprintf("%d B", bytes)
|
||||||
|
}
|
||||||
|
div, exp := uint64(unit), 0
|
||||||
|
for n := bytes / unit; n >= unit; n /= unit {
|
||||||
|
div *= unit
|
||||||
|
exp++
|
||||||
|
}
|
||||||
|
units := []string{"KB", "MB", "GB", "TB", "PB", "EB"}
|
||||||
|
return fmt.Sprintf("%.2f %s", float64(bytes)/float64(div), units[exp])
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PingResult latency probe result
|
||||||
|
type PingResult struct {
|
||||||
|
Latency int64 // Latency in milliseconds, -1 means unreachable
|
||||||
|
Reachable bool // Whether the host is reachable
|
||||||
|
Error string // Error message if any
|
||||||
|
}
|
||||||
|
|
||||||
|
// GeoLocation IP geolocation information
|
||||||
|
type GeoLocation struct {
|
||||||
|
Country string `json:"country"` // Country name
|
||||||
|
CountryCode string `json:"countryCode"` // Country code (e.g., CN, US)
|
||||||
|
Region string `json:"region"` // Province/State/Region
|
||||||
|
City string `json:"city"` // City name
|
||||||
|
ISP string `json:"isp"` // Internet Service Provider
|
||||||
|
Latitude float64 `json:"lat"` // Latitude coordinate
|
||||||
|
Longitude float64 `json:"lon"` // Longitude coordinate
|
||||||
|
}
|
||||||
|
|
||||||
|
// PingHost tests host latency via TCP connection
|
||||||
|
func PingHost(addr string, timeout time.Duration) PingResult {
|
||||||
|
if addr == "" {
|
||||||
|
return PingResult{
|
||||||
|
Latency: -1,
|
||||||
|
Reachable: false,
|
||||||
|
Error: "empty address",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If address doesn't contain port, default to 7000
|
||||||
|
if !strings.Contains(addr, ":") {
|
||||||
|
addr = addr + ":7000"
|
||||||
|
}
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
conn, err := net.DialTimeout("tcp", addr, timeout)
|
||||||
|
elapsed := time.Since(start).Milliseconds()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return PingResult{
|
||||||
|
Latency: -1,
|
||||||
|
Reachable: false,
|
||||||
|
Error: err.Error(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
conn.Close()
|
||||||
|
return PingResult{
|
||||||
|
Latency: elapsed,
|
||||||
|
Reachable: true,
|
||||||
|
Error: "",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetGeoLocation retrieves IP geolocation information (using free public API)
|
||||||
|
func GetGeoLocation(addr string) (*GeoLocation, error) {
|
||||||
|
// Resolve IP address (resolve domain name if needed)
|
||||||
|
ip, err := resolveAddr(addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("resolve address failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return directly for private IP addresses
|
||||||
|
if isPrivateIP(ip) {
|
||||||
|
return &GeoLocation{
|
||||||
|
Country: "Private Network",
|
||||||
|
CountryCode: "LAN",
|
||||||
|
Region: "Local",
|
||||||
|
City: "Local",
|
||||||
|
ISP: "Private",
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Query using ip-api.com (free, no key required, 45 requests/min)
|
||||||
|
return getGeoLocationFromAPI(ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveAddr resolves address and extracts IP
|
||||||
|
func resolveAddr(addr string) (string, error) {
|
||||||
|
// Remove port number
|
||||||
|
host := addr
|
||||||
|
if idx := strings.LastIndex(addr, ":"); idx != -1 {
|
||||||
|
host = addr[:idx]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return directly if already an IP address
|
||||||
|
if net.ParseIP(host) != nil {
|
||||||
|
return host, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DNS resolution
|
||||||
|
ips, err := net.LookupIP(host)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(ips) == 0 {
|
||||||
|
return "", fmt.Errorf("no IP found for %s", host)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prefer IPv4 address
|
||||||
|
for _, ip := range ips {
|
||||||
|
if ipv4 := ip.To4(); ipv4 != nil {
|
||||||
|
return ipv4.String(), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return first IP if no IPv4 found
|
||||||
|
return ips[0].String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// isPrivateIP checks if an IP is private
|
||||||
|
func isPrivateIP(ip string) bool {
|
||||||
|
parsedIP := net.ParseIP(ip)
|
||||||
|
if parsedIP == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Private IP ranges
|
||||||
|
privateRanges := []string{
|
||||||
|
"10.0.0.0/8",
|
||||||
|
"172.16.0.0/12",
|
||||||
|
"192.168.0.0/16",
|
||||||
|
"127.0.0.0/8",
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, cidr := range privateRanges {
|
||||||
|
_, subnet, _ := net.ParseCIDR(cidr)
|
||||||
|
if subnet.Contains(parsedIP) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// getGeoLocationFromAPI retrieves geolocation information from ip-api.com
|
||||||
|
func getGeoLocationFromAPI(ip string) (*GeoLocation, error) {
|
||||||
|
// ip-api.com API endpoint
|
||||||
|
url := fmt.Sprintf("http://ip-api.com/json/%s?fields=status,country,countryCode,region,regionName,city,isp,lat,lon", ip)
|
||||||
|
|
||||||
|
client := &http.Client{
|
||||||
|
Timeout: 5 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := client.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("API request failed: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("API returned status: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
var apiResp struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
Country string `json:"country"`
|
||||||
|
CountryCode string `json:"countryCode"`
|
||||||
|
Region string `json:"region"`
|
||||||
|
RegionName string `json:"regionName"`
|
||||||
|
City string `json:"city"`
|
||||||
|
ISP string `json:"isp"`
|
||||||
|
Lat float64 `json:"lat"`
|
||||||
|
Lon float64 `json:"lon"`
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil {
|
||||||
|
return nil, fmt.Errorf("parse API response failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if apiResp.Status != "success" {
|
||||||
|
return nil, fmt.Errorf("API query failed for IP: %s", ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &GeoLocation{
|
||||||
|
Country: apiResp.Country,
|
||||||
|
CountryCode: apiResp.CountryCode,
|
||||||
|
Region: apiResp.RegionName, // Use RegionName (e.g., "Guangdong") instead of Region (e.g., "GD")
|
||||||
|
City: apiResp.City,
|
||||||
|
ISP: apiResp.ISP,
|
||||||
|
Latitude: apiResp.Lat,
|
||||||
|
Longitude: apiResp.Lon,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// RoundDownTo10Minutes rounds down a time to the nearest 10-minute mark
|
||||||
|
// Example: 10:07:30 -> 10:00:00, 10:15:45 -> 10:10:00, 10:20:00 -> 10:20:00
|
||||||
|
func RoundDownTo10Minutes(t time.Time) time.Time {
|
||||||
|
minutes := t.Minute()
|
||||||
|
roundedMinutes := (minutes / 10) * 10
|
||||||
|
return time.Date(
|
||||||
|
t.Year(), t.Month(), t.Day(),
|
||||||
|
t.Hour(), roundedMinutes, 0, 0,
|
||||||
|
t.Location(),
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
VITE_POCKETBASE_URL=/
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
VITE_POCKETBASE_URL=/
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
dist
|
||||||
|
node_modules
|
||||||
|
pnpm-lock.yaml
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"semi": true,
|
||||||
|
"singleQuote": false,
|
||||||
|
"tabWidth": 2,
|
||||||
|
"trailingComma": "es5",
|
||||||
|
"printWidth": 100,
|
||||||
|
"plugins": ["prettier-plugin-tailwindcss"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# React + TypeScript + Vite
|
||||||
|
|
||||||
|
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||||
|
|
||||||
|
Currently, two official plugins are available:
|
||||||
|
|
||||||
|
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||||
|
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||||
|
|
||||||
|
## React Compiler
|
||||||
|
|
||||||
|
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||||
|
|
||||||
|
## Expanding the ESLint configuration
|
||||||
|
|
||||||
|
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||||
|
|
||||||
|
```js
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
// Other configs...
|
||||||
|
|
||||||
|
// Remove tseslint.configs.recommended and replace with this
|
||||||
|
tseslint.configs.recommendedTypeChecked,
|
||||||
|
// Alternatively, use this for stricter rules
|
||||||
|
tseslint.configs.strictTypeChecked,
|
||||||
|
// Optionally, add this for stylistic rules
|
||||||
|
tseslint.configs.stylisticTypeChecked,
|
||||||
|
|
||||||
|
// Other configs...
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
// other options...
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// eslint.config.js
|
||||||
|
import reactX from 'eslint-plugin-react-x'
|
||||||
|
import reactDom from 'eslint-plugin-react-dom'
|
||||||
|
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
// Other configs...
|
||||||
|
// Enable lint rules for React
|
||||||
|
reactX.configs['recommended-typescript'],
|
||||||
|
// Enable lint rules for React DOM
|
||||||
|
reactDom.configs.recommended,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
// other options...
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
```
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import js from '@eslint/js'
|
||||||
|
import globals from 'globals'
|
||||||
|
import reactHooks from 'eslint-plugin-react-hooks'
|
||||||
|
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||||
|
import tseslint from 'typescript-eslint'
|
||||||
|
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||||
|
import prettier from 'eslint-config-prettier'
|
||||||
|
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
js.configs.recommended,
|
||||||
|
tseslint.configs.recommended,
|
||||||
|
reactHooks.configs.flat.recommended,
|
||||||
|
reactRefresh.configs.vite,
|
||||||
|
prettier,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Frpc Hub</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
{
|
||||||
|
"name": "site",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"format": "prettier --write \"src/**/*.{ts,tsx,css,json}\"",
|
||||||
|
"format:check": "prettier --check \"src/**/*.{ts,tsx,css,json}\""
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@iconify/react": "^6.0.2",
|
||||||
|
"@radix-ui/themes": "^3.2.1",
|
||||||
|
"@xyflow/react": "^12.10.1",
|
||||||
|
"framer-motion": "^12.30.0",
|
||||||
|
"i18next": "^25.8.4",
|
||||||
|
"md5": "^2.3.0",
|
||||||
|
"pocketbase": "^0.26.5",
|
||||||
|
"react": "^19.2.0",
|
||||||
|
"react-dom": "^19.2.0",
|
||||||
|
"react-i18next": "^16.5.4",
|
||||||
|
"react-loading-indicators": "^1.0.1",
|
||||||
|
"react-router-dom": "^7.11.0",
|
||||||
|
"recharts": "^3.7.0",
|
||||||
|
"sonner": "^2.0.7",
|
||||||
|
"zustand": "^5.0.11"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.39.1",
|
||||||
|
"@tailwindcss/vite": "^4.1.18",
|
||||||
|
"@types/md5": "^2.3.6",
|
||||||
|
"@types/node": "^24.10.1",
|
||||||
|
"@types/react": "^19.2.5",
|
||||||
|
"@types/react-dom": "^19.2.3",
|
||||||
|
"@vitejs/plugin-react": "^5.1.1",
|
||||||
|
"eslint": "^9.39.1",
|
||||||
|
"eslint-config-prettier": "^10.1.8",
|
||||||
|
"eslint-plugin-react-hooks": "^7.0.1",
|
||||||
|
"eslint-plugin-react-refresh": "^0.4.24",
|
||||||
|
"globals": "^16.5.0",
|
||||||
|
"prettier": "^3.8.1",
|
||||||
|
"prettier-plugin-tailwindcss": "^0.7.2",
|
||||||
|
"tailwindcss": "^4.1.18",
|
||||||
|
"terser": "^5.46.0",
|
||||||
|
"typescript": "~5.9.3",
|
||||||
|
"typescript-eslint": "^8.46.4",
|
||||||
|
"vite": "^7.2.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+4956
File diff suppressed because it is too large.
Load diff
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,42 @@
|
|||||||
|
#root {
|
||||||
|
max-width: 1280px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 2rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
height: 6em;
|
||||||
|
padding: 1.5em;
|
||||||
|
will-change: filter;
|
||||||
|
transition: filter 300ms;
|
||||||
|
}
|
||||||
|
.logo:hover {
|
||||||
|
filter: drop-shadow(0 0 2em #646cffaa);
|
||||||
|
}
|
||||||
|
.logo.react:hover {
|
||||||
|
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes logo-spin {
|
||||||
|
from {
|
||||||
|
transform: rotate(0deg);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: no-preference) {
|
||||||
|
a:nth-of-type(2) .logo {
|
||||||
|
animation: logo-spin infinite 20s linear;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
padding: 2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.read-the-docs {
|
||||||
|
color: #888;
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { BrowserRouter, Routes, Route, Navigate, Outlet } from "react-router-dom";
|
||||||
|
import { lazy, Suspense } from "react";
|
||||||
|
import { RequireAuth } from "./components/RequireAuth";
|
||||||
|
import { RequireSetup } from "./components/RequireSetup";
|
||||||
|
import { MainLayout } from "./layouts/MainLayout";
|
||||||
|
import { Loading } from "./components/Loading";
|
||||||
|
|
||||||
|
// 路由懒加载 - 按需加载页面组件
|
||||||
|
const SetupPage = lazy(() => import("./pages/Setup").then((m) => ({ default: m.SetupPage })));
|
||||||
|
const LoginPage = lazy(() => import("./pages/Login").then((m) => ({ default: m.LoginPage })));
|
||||||
|
const ProxiesPage = lazy(() => import("./pages/Proxies").then((m) => ({ default: m.ProxiesPage })));
|
||||||
|
const ServersPage = lazy(() => import("./pages/Servers").then((m) => ({ default: m.ServersPage })));
|
||||||
|
const DashboardPage = lazy(() =>
|
||||||
|
import("./pages/Dashboard").then((m) => ({ default: m.DashboardPage }))
|
||||||
|
);
|
||||||
|
const SettingsPage = lazy(() =>
|
||||||
|
import("./pages/Settings").then((m) => ({ default: m.SettingsPage }))
|
||||||
|
);
|
||||||
|
const NotFoundPage = lazy(() =>
|
||||||
|
import("./pages/NotFound").then((m) => ({ default: m.NotFoundPage }))
|
||||||
|
);
|
||||||
|
const ServerDetailPage = lazy(() =>
|
||||||
|
import("./pages/ServerDetail").then((m) => ({ default: m.ServerDetailPage }))
|
||||||
|
);
|
||||||
|
const ImportPage = lazy(() => import("./pages/Import").then((m) => ({ default: m.ImportPage })));
|
||||||
|
|
||||||
|
function AuthenticatedLayout() {
|
||||||
|
console.log("AuthenticatedLayout rendered");
|
||||||
|
return (
|
||||||
|
<RequireSetup>
|
||||||
|
<RequireAuth>
|
||||||
|
<MainLayout>
|
||||||
|
<Outlet />
|
||||||
|
</MainLayout>
|
||||||
|
</RequireAuth>
|
||||||
|
</RequireSetup>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
return (
|
||||||
|
<BrowserRouter>
|
||||||
|
<Suspense fallback={<Loading fullscreen />}>
|
||||||
|
<Routes>
|
||||||
|
{/* Setup Route - No authentication or initialization check required */}
|
||||||
|
<Route path="/setup" element={<SetupPage />} />
|
||||||
|
|
||||||
|
{/* Login Route - Requires system to be initialized */}
|
||||||
|
<Route
|
||||||
|
path="/login"
|
||||||
|
element={
|
||||||
|
<RequireSetup>
|
||||||
|
<LoginPage />
|
||||||
|
</RequireSetup>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Authenticated Routes with shared layout */}
|
||||||
|
<Route element={<AuthenticatedLayout />}>
|
||||||
|
<Route path="/dashboard" element={<DashboardPage />} />
|
||||||
|
<Route path="/proxies" element={<ProxiesPage />} />
|
||||||
|
<Route path="/servers" element={<ServersPage />} />
|
||||||
|
<Route path="/servers/:id" element={<ServerDetailPage />} />
|
||||||
|
<Route path="/settings" element={<SettingsPage />} />
|
||||||
|
<Route path="/import" element={<ImportPage />} />
|
||||||
|
{/* <Route path="/versions" element={<VersionPage />} /> */}
|
||||||
|
</Route>
|
||||||
|
|
||||||
|
<Route path="/" element={<Navigate to="/dashboard" replace />} />
|
||||||
|
<Route path="/404" element={<NotFoundPage />} />
|
||||||
|
<Route path="*" element={<Navigate to="/404" replace />} />
|
||||||
|
</Routes>
|
||||||
|
</Suspense>
|
||||||
|
</BrowserRouter>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App;
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,26 @@
|
|||||||
|
import { motion, useSpring, useTransform } from "framer-motion";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
|
||||||
|
export function AnimateNumber({
|
||||||
|
value,
|
||||||
|
unit,
|
||||||
|
decimalPlaces = 2,
|
||||||
|
}: {
|
||||||
|
value: number;
|
||||||
|
unit?: string;
|
||||||
|
rate?: number;
|
||||||
|
decimalPlaces?: number;
|
||||||
|
}) {
|
||||||
|
const spring = useSpring(0, { mass: 0.8, stiffness: 75, damping: 15 });
|
||||||
|
const display = useTransform(spring, (current) => {
|
||||||
|
const factor = Math.pow(10, decimalPlaces);
|
||||||
|
const rounded = (Math.round(current * factor) / factor).toFixed(decimalPlaces);
|
||||||
|
return unit ? `${rounded} ${unit}` : rounded;
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
spring.set(value);
|
||||||
|
}, [spring, value]);
|
||||||
|
|
||||||
|
return <motion.span>{display}</motion.span>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { Box, Flex, Text, Button } from "@radix-ui/themes";
|
||||||
|
import React from "react";
|
||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
|
||||||
|
interface EmptyStateProps {
|
||||||
|
icon?: React.ReactNode;
|
||||||
|
title: string;
|
||||||
|
description: string | React.ReactNode;
|
||||||
|
actionText?: string;
|
||||||
|
onAction?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EmptyState({ icon, title, description, actionText, onAction }: EmptyStateProps) {
|
||||||
|
return (
|
||||||
|
<Box py="9" px="4">
|
||||||
|
<Flex direction="column" align="center" justify="center" gap="4">
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
width: "80px",
|
||||||
|
height: "80px",
|
||||||
|
borderRadius: "24px",
|
||||||
|
background: "linear-gradient(135deg, var(--gray-3) 0%, var(--gray-5) 100%)",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
color: "var(--gray-11)",
|
||||||
|
boxShadow: "0 4px 12px rgba(0,0,0,0.05)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{icon || <Icon icon="lucide:inbox" width="32" height="32" />}
|
||||||
|
</Box>
|
||||||
|
<Flex direction="column" align="center" gap="1">
|
||||||
|
<Text size="4" weight="bold" highContrast>
|
||||||
|
{title}
|
||||||
|
</Text>
|
||||||
|
<Text size="2" color="gray" align="center" style={{ maxWidth: "400px" }}>
|
||||||
|
{description}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
{actionText && onAction && (
|
||||||
|
<Button
|
||||||
|
variant="soft"
|
||||||
|
size="3"
|
||||||
|
onClick={onAction}
|
||||||
|
style={{ cursor: "pointer", marginTop: "8px" }}
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:plus" />
|
||||||
|
{actionText}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { type ReactNode } from "react";
|
||||||
|
import { Text, Box } from "@radix-ui/themes";
|
||||||
|
import { motion, AnimatePresence } from "framer-motion";
|
||||||
|
|
||||||
|
interface FormItemProps {
|
||||||
|
label: string;
|
||||||
|
error?: string;
|
||||||
|
required?: boolean;
|
||||||
|
animate?: boolean;
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
function FormItem({ label, error, required, animate, children }: FormItemProps) {
|
||||||
|
const content = (
|
||||||
|
<Box>
|
||||||
|
<Text as="label" size="2" weight="medium" mb="1" style={{ display: "block" }}>
|
||||||
|
{label} {required && <Text color="red">*</Text>}
|
||||||
|
</Text>
|
||||||
|
{children}
|
||||||
|
<AnimatePresence mode="wait">
|
||||||
|
{error && (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: -10 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
exit={{ opacity: 0, y: -10 }}
|
||||||
|
transition={{ duration: 0.2 }}
|
||||||
|
>
|
||||||
|
<Text color="red" size="1" mt="1" style={{ display: "block" }}>
|
||||||
|
{error}
|
||||||
|
</Text>
|
||||||
|
</motion.div>
|
||||||
|
)}
|
||||||
|
</AnimatePresence>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (animate) {
|
||||||
|
return (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, height: 0 }}
|
||||||
|
animate={{ opacity: 1, height: "auto" }}
|
||||||
|
exit={{ opacity: 0, height: 0 }}
|
||||||
|
transition={{ duration: 0.2, ease: "easeInOut" }}
|
||||||
|
style={{ overflow: "hidden" }}
|
||||||
|
>
|
||||||
|
{content}
|
||||||
|
</motion.div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { FormItem, type FormItemProps };
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { Select } from "@radix-ui/themes";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useLanguage } from "../contexts/LanguageContext";
|
||||||
|
|
||||||
|
export default function LanguageSelector() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { language, setLanguage } = useLanguage();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Select.Root value={language} onValueChange={(value) => setLanguage(value as "en" | "zh")}>
|
||||||
|
<Select.Trigger />
|
||||||
|
<Select.Content>
|
||||||
|
<Select.Item value="en">{t("language.en")}</Select.Item>
|
||||||
|
<Select.Item value="zh">{t("language.zh")}</Select.Item>
|
||||||
|
</Select.Content>
|
||||||
|
</Select.Root>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { motion, AnimatePresence } from "framer-motion";
|
||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
import { useLanguage } from "../contexts/LanguageContext";
|
||||||
|
|
||||||
|
interface LanguageToggleProps {
|
||||||
|
language?: "en" | "zh";
|
||||||
|
onChange?: (lang: "en" | "zh") => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LanguageToggle({ language: customLanguage, onChange }: LanguageToggleProps = {}) {
|
||||||
|
const context = useLanguage();
|
||||||
|
|
||||||
|
// Use custom language/onChange if provided, otherwise use context
|
||||||
|
const language = customLanguage ?? context.language;
|
||||||
|
const setLanguage = onChange ?? context.setLanguage;
|
||||||
|
|
||||||
|
const toggleLanguage = () => {
|
||||||
|
const newLang = language === "en" ? "zh" : "en";
|
||||||
|
setLanguage(newLang);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<motion.div
|
||||||
|
className="cursor-pointer rounded-lg p-2 transition-colors hover:bg-[var(--gray-a3)]"
|
||||||
|
onClick={toggleLanguage}
|
||||||
|
whileTap={{ scale: 0.95 }}
|
||||||
|
whileHover="hover"
|
||||||
|
>
|
||||||
|
<motion.div
|
||||||
|
variants={{
|
||||||
|
hover: { scale: 1.1, rotate: 15 },
|
||||||
|
}}
|
||||||
|
className="flex items-center justify-center"
|
||||||
|
>
|
||||||
|
<AnimatePresence mode="wait" initial={false}>
|
||||||
|
<motion.div
|
||||||
|
key={language}
|
||||||
|
initial={{ rotate: -90, scale: 0 }}
|
||||||
|
animate={{ rotate: 0, scale: 1 }}
|
||||||
|
exit={{ rotate: 90, scale: 0 }}
|
||||||
|
transition={{ duration: 0.2 }}
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon={language === "en" ? "circle-flags:us" : "circle-flags:cn"}
|
||||||
|
width="20"
|
||||||
|
height="20"
|
||||||
|
/>
|
||||||
|
</motion.div>
|
||||||
|
</AnimatePresence>
|
||||||
|
</motion.div>
|
||||||
|
</motion.div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import { Flex, Text } from "@radix-ui/themes";
|
||||||
|
import { motion } from "framer-motion";
|
||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
|
||||||
|
interface LoadingProps {
|
||||||
|
text?: string;
|
||||||
|
size?: "small" | "medium" | "large";
|
||||||
|
minHeight?: string | number;
|
||||||
|
fullscreen?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sizeMap = {
|
||||||
|
small: 24,
|
||||||
|
medium: 32,
|
||||||
|
large: 48,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function Loading({
|
||||||
|
text = "Loading...",
|
||||||
|
size = "medium",
|
||||||
|
minHeight,
|
||||||
|
fullscreen = false,
|
||||||
|
}: LoadingProps) {
|
||||||
|
const iconSize = sizeMap[size];
|
||||||
|
|
||||||
|
const containerStyle = fullscreen
|
||||||
|
? {
|
||||||
|
position: "fixed" as const,
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: 0,
|
||||||
|
width: "100vw",
|
||||||
|
height: "100vh",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
backgroundColor: "var(--gray-2)",
|
||||||
|
zIndex: 9999,
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
minHeight: minHeight || "100%",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
};
|
||||||
|
|
||||||
|
if (fullscreen) {
|
||||||
|
return (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0 }}
|
||||||
|
animate={{ opacity: 1 }}
|
||||||
|
exit={{ opacity: 0 }}
|
||||||
|
transition={{ duration: 0.2 }}
|
||||||
|
style={containerStyle}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
gap: "12px",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon="lucide:loader-circle"
|
||||||
|
width={iconSize}
|
||||||
|
height={iconSize}
|
||||||
|
className="animate-spin"
|
||||||
|
style={{ color: "var(--accent-9)" }}
|
||||||
|
/>
|
||||||
|
{text && (
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{text}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0 }}
|
||||||
|
animate={{ opacity: 1 }}
|
||||||
|
exit={{ opacity: 0 }}
|
||||||
|
transition={{ duration: 0.2 }}
|
||||||
|
style={containerStyle}
|
||||||
|
>
|
||||||
|
<Flex direction="column" align="center" justify="center" gap="3">
|
||||||
|
<Icon
|
||||||
|
icon="lucide:loader-circle"
|
||||||
|
width={iconSize}
|
||||||
|
height={iconSize}
|
||||||
|
className="animate-spin"
|
||||||
|
style={{ color: "var(--accent-9)" }}
|
||||||
|
/>
|
||||||
|
{text && (
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{text}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
</motion.div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { Box, Flex, Heading, Text } from "@radix-ui/themes";
|
||||||
|
import { motion } from "framer-motion";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
interface PageHeaderProps {
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
extra?: ReactNode;
|
||||||
|
visible?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PageHeader({ title, description, extra, visible = true }: PageHeaderProps) {
|
||||||
|
return (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: -20 }}
|
||||||
|
animate={visible ? { opacity: 1, y: 0 } : { opacity: 0, y: -20 }}
|
||||||
|
transition={{ duration: 0.5, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<Flex justify="between" align="center">
|
||||||
|
<Box>
|
||||||
|
<Heading size="6">{title}</Heading>
|
||||||
|
{description && (
|
||||||
|
<Text color="gray" size="2">
|
||||||
|
{description}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
{extra && <Box>{extra}</Box>}
|
||||||
|
</Flex>
|
||||||
|
</motion.div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { motion, type HTMLMotionProps } from "framer-motion";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
interface PageTransitionProps extends HTMLMotionProps<"div"> {
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PageTransition({ children, ...props }: PageTransitionProps) {
|
||||||
|
return (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 10 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
exit={{ opacity: 0, y: -10 }}
|
||||||
|
transition={{
|
||||||
|
duration: 0.3,
|
||||||
|
ease: [0.22, 1, 0.36, 1], // Custom cubic-bezier for a more premium feel
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</motion.div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { Navigate, useLocation } from "react-router-dom";
|
||||||
|
import pb from "../lib/pocketbase";
|
||||||
|
|
||||||
|
interface RequireAuthProps {
|
||||||
|
children: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Route guard component
|
||||||
|
* Check if user is logged in and token is not expired
|
||||||
|
* If not logged in or token expired, redirect to login page
|
||||||
|
*/
|
||||||
|
export function RequireAuth({ children }: RequireAuthProps) {
|
||||||
|
const location = useLocation();
|
||||||
|
|
||||||
|
// Check for valid authentication info
|
||||||
|
const isAuthenticated = pb.authStore.isValid;
|
||||||
|
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
// Not logged in or token expired, redirect to login page
|
||||||
|
// Save current path to redirect back after login
|
||||||
|
return <Navigate to="/login" state={{ from: location }} replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { Navigate, useLocation } from "react-router-dom";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Loading } from "./Loading";
|
||||||
|
import { useSystemStore } from "../stores/systemStore";
|
||||||
|
|
||||||
|
interface RequireSetupProps {
|
||||||
|
children: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Route guard component
|
||||||
|
* Check if system has been initialized by checking the settings table
|
||||||
|
* If not initialized, redirect to setup page
|
||||||
|
*/
|
||||||
|
export function RequireSetup({ children }: RequireSetupProps) {
|
||||||
|
const location = useLocation();
|
||||||
|
const { checkInitialized } = useSystemStore();
|
||||||
|
const [isInitialized, setIsInitialized] = useState<boolean | null>(null);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
|
||||||
|
console.log("RequireSetup component rendered");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
console.log("RequireSetup useEffect triggered");
|
||||||
|
checkInitialization();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const checkInitialization = async () => {
|
||||||
|
console.log("checkInitialization called");
|
||||||
|
try {
|
||||||
|
const initialized = await checkInitialized();
|
||||||
|
console.log("Initialization status:", initialized);
|
||||||
|
setIsInitialized(initialized);
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error("Failed to check initialization status:", error);
|
||||||
|
setIsInitialized(false);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return <Loading fullscreen />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isInitialized) {
|
||||||
|
// Not initialized, redirect to setup page
|
||||||
|
return <Navigate to="/setup" state={{ from: location }} replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { Flex, Text, Badge } from "@radix-ui/themes";
|
||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
|
||||||
|
interface NetworkStatus {
|
||||||
|
reachable: boolean;
|
||||||
|
latency: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ServerLatencyProps {
|
||||||
|
networkStatus?: NetworkStatus;
|
||||||
|
size?: "1" | "2" | "3";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ServerLatency({ networkStatus, size = "2" }: ServerLatencyProps) {
|
||||||
|
if (!networkStatus) {
|
||||||
|
return (
|
||||||
|
<Text size={size} color="gray">
|
||||||
|
-
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!networkStatus.reachable) {
|
||||||
|
return (
|
||||||
|
<Badge color="gray" variant="soft">
|
||||||
|
<Icon icon="lucide:x" width="12" height="12" />
|
||||||
|
Unreachable
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const getLatencyColor = (latency: number) => {
|
||||||
|
if (latency < 50) return "var(--green-11)";
|
||||||
|
if (latency < 150) return "var(--amber-11)";
|
||||||
|
return "var(--red-11)";
|
||||||
|
};
|
||||||
|
|
||||||
|
const color = getLatencyColor(networkStatus.latency);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Flex align="center" gap="1">
|
||||||
|
<Icon icon="lucide:zap" width="14" height="14" color={color} />
|
||||||
|
<Text size={size} weight="medium" style={{ color }}>
|
||||||
|
{networkStatus.latency}ms
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { Flex, Text } from "@radix-ui/themes";
|
||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
|
||||||
|
interface GeoLocation {
|
||||||
|
city?: string;
|
||||||
|
region?: string;
|
||||||
|
country?: string;
|
||||||
|
isp?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ServerLocationProps {
|
||||||
|
geoLocation?: GeoLocation;
|
||||||
|
size?: "1" | "2" | "3";
|
||||||
|
showISP?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ServerLocation({ geoLocation, size = "2", showISP = true }: ServerLocationProps) {
|
||||||
|
if (!geoLocation) {
|
||||||
|
return (
|
||||||
|
<Text size={size} color="gray">
|
||||||
|
-
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const locationText = geoLocation.city || geoLocation.region || geoLocation.country;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Flex direction="column" gap="0">
|
||||||
|
<Flex align="center" gap="1">
|
||||||
|
<Icon icon="lucide:map-pin" width="12" height="12" color="var(--gray-11)" />
|
||||||
|
<Text size={size} weight="medium">
|
||||||
|
{locationText || "Unknown"}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
{showISP && geoLocation.isp && (
|
||||||
|
<Text size="1" color="gray">
|
||||||
|
{geoLocation.isp}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { Box, Card, Flex, Text } from "@radix-ui/themes";
|
||||||
|
import React from "react";
|
||||||
|
|
||||||
|
export function StatCard({
|
||||||
|
title,
|
||||||
|
value,
|
||||||
|
subtitle,
|
||||||
|
icon,
|
||||||
|
color = "gray",
|
||||||
|
}: {
|
||||||
|
title: string;
|
||||||
|
value: React.ReactNode;
|
||||||
|
subtitle?: string;
|
||||||
|
icon: React.ReactNode;
|
||||||
|
color?: "green" | "red" | "blue" | "orange" | "gray";
|
||||||
|
}) {
|
||||||
|
const colorMap = {
|
||||||
|
green: "var(--green-9)",
|
||||||
|
red: "var(--red-9)",
|
||||||
|
blue: "var(--blue-9)",
|
||||||
|
orange: "var(--orange-9)",
|
||||||
|
gray: "var(--gray-9)",
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="flex-1">
|
||||||
|
<Flex gap="4" align="center">
|
||||||
|
<Flex
|
||||||
|
className="h-12 w-12 rounded-xl select-none"
|
||||||
|
align="center"
|
||||||
|
justify="center"
|
||||||
|
style={{
|
||||||
|
backgroundColor: `${colorMap[color]}20`,
|
||||||
|
color: colorMap[color],
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{icon}
|
||||||
|
</Flex>
|
||||||
|
<Flex direction="column" gap="1">
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{title}
|
||||||
|
</Text>
|
||||||
|
<Box>
|
||||||
|
<Text size="6" weight="bold">
|
||||||
|
{value}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
{subtitle && (
|
||||||
|
<Text size="1" color="gray">
|
||||||
|
{subtitle}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { motion, AnimatePresence } from "framer-motion";
|
||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
import { useTheme } from "../contexts/ThemeContext";
|
||||||
|
|
||||||
|
export function ThemeToggle() {
|
||||||
|
const { theme, toggleTheme } = useTheme();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<motion.div
|
||||||
|
className="cursor-pointer rounded-lg p-2 transition-colors hover:bg-[var(--gray-a3)]"
|
||||||
|
onClick={toggleTheme}
|
||||||
|
whileTap={{ scale: 0.95 }}
|
||||||
|
whileHover="hover"
|
||||||
|
>
|
||||||
|
<motion.div
|
||||||
|
variants={{
|
||||||
|
hover: { scale: 1.1, rotate: 15 },
|
||||||
|
}}
|
||||||
|
className="flex items-center justify-center"
|
||||||
|
>
|
||||||
|
<AnimatePresence mode="wait" initial={false}>
|
||||||
|
<motion.div
|
||||||
|
key={theme}
|
||||||
|
initial={{ rotate: -90, scale: 0 }}
|
||||||
|
animate={{ rotate: 0, scale: 1 }}
|
||||||
|
exit={{ rotate: 90, scale: 0 }}
|
||||||
|
transition={{ duration: 0.2 }}
|
||||||
|
>
|
||||||
|
{theme === "light" ? (
|
||||||
|
<Icon icon="lucide:sun" width="20" height="20" color="#f59e0b" />
|
||||||
|
) : (
|
||||||
|
<Icon icon="lucide:moon" width="20" height="20" />
|
||||||
|
)}
|
||||||
|
</motion.div>
|
||||||
|
</AnimatePresence>
|
||||||
|
</motion.div>
|
||||||
|
</motion.div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import React, { createContext, useContext, useEffect, useState, useCallback } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
type Language = "en" | "zh";
|
||||||
|
|
||||||
|
const USER_LANG_KEY = "user-language";
|
||||||
|
|
||||||
|
function getBrowserLanguage(): Language {
|
||||||
|
const lang = navigator.language || "en";
|
||||||
|
return lang.startsWith("zh") ? "zh" : "en";
|
||||||
|
}
|
||||||
|
|
||||||
|
function readUserLanguage(): Language | null {
|
||||||
|
try {
|
||||||
|
const val = localStorage.getItem(USER_LANG_KEY);
|
||||||
|
if (val === "en" || val === "zh") return val;
|
||||||
|
} catch {}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LanguageContextType {
|
||||||
|
language: Language;
|
||||||
|
isManuallySet: boolean;
|
||||||
|
setLanguage: (lang: Language) => void;
|
||||||
|
resetToDefault: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const LanguageContext = createContext<LanguageContextType | undefined>(undefined);
|
||||||
|
|
||||||
|
export const LanguageProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
|
||||||
|
const { i18n } = useTranslation();
|
||||||
|
const [userLanguage, setUserLanguageState] = useState<Language | null>(readUserLanguage);
|
||||||
|
|
||||||
|
const setUserLanguage = useCallback((lang: Language | null) => {
|
||||||
|
setUserLanguageState(lang);
|
||||||
|
try {
|
||||||
|
if (lang === null) {
|
||||||
|
localStorage.removeItem(USER_LANG_KEY);
|
||||||
|
} else {
|
||||||
|
localStorage.setItem(USER_LANG_KEY, lang);
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const language: Language = userLanguage ?? getBrowserLanguage();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
i18n.changeLanguage(language);
|
||||||
|
}, [language, i18n]);
|
||||||
|
|
||||||
|
const setLanguage = useCallback(
|
||||||
|
(lang: Language) => {
|
||||||
|
setUserLanguage(lang);
|
||||||
|
i18n.changeLanguage(lang);
|
||||||
|
},
|
||||||
|
[i18n, setUserLanguage]
|
||||||
|
);
|
||||||
|
|
||||||
|
// 重置为浏览器默认语言(清除用户的手动设置)
|
||||||
|
const resetToDefault = useCallback(() => {
|
||||||
|
setUserLanguage(null);
|
||||||
|
i18n.changeLanguage(getBrowserLanguage());
|
||||||
|
}, [i18n, setUserLanguage]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<LanguageContext.Provider
|
||||||
|
value={{
|
||||||
|
language,
|
||||||
|
isManuallySet: userLanguage !== null,
|
||||||
|
setLanguage,
|
||||||
|
resetToDefault,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</LanguageContext.Provider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useLanguage = () => {
|
||||||
|
const context = useContext(LanguageContext);
|
||||||
|
if (context === undefined) {
|
||||||
|
throw new Error("useLanguage must be used within a LanguageProvider");
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
};
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { createContext, useContext, useState, useEffect, type ReactNode } from "react";
|
||||||
|
|
||||||
|
type Theme = "light" | "dark";
|
||||||
|
|
||||||
|
interface ThemeContextType {
|
||||||
|
theme: Theme;
|
||||||
|
toggleTheme: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
||||||
|
|
||||||
|
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [theme, setTheme] = useState<Theme>(() => {
|
||||||
|
// Read saved theme from localStorage, default to light
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
const saved = localStorage.getItem("theme") as Theme;
|
||||||
|
if (saved) return saved;
|
||||||
|
// Check system preference
|
||||||
|
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
|
||||||
|
return "dark";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "light";
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Save theme to localStorage
|
||||||
|
localStorage.setItem("theme", theme);
|
||||||
|
}, [theme]);
|
||||||
|
|
||||||
|
const toggleTheme = () => {
|
||||||
|
setTheme((prev) => (prev === "light" ? "dark" : "light"));
|
||||||
|
};
|
||||||
|
|
||||||
|
return <ThemeContext.Provider value={{ theme, toggleTheme }}>{children}</ThemeContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTheme() {
|
||||||
|
const context = useContext(ThemeContext);
|
||||||
|
if (context === undefined) {
|
||||||
|
throw new Error("useTheme must be used within a ThemeProvider");
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import i18n from "i18next";
|
||||||
|
import { initReactI18next } from "react-i18next";
|
||||||
|
import en from "./locales/en.json";
|
||||||
|
import zh from "./locales/zh.json";
|
||||||
|
|
||||||
|
let initialLanguage = "en";
|
||||||
|
try {
|
||||||
|
const userLang = localStorage.getItem("user-language");
|
||||||
|
if (userLang === "en" || userLang === "zh") {
|
||||||
|
initialLanguage = userLang;
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
i18n.use(initReactI18next).init({
|
||||||
|
resources: {
|
||||||
|
en: {
|
||||||
|
translation: en,
|
||||||
|
},
|
||||||
|
zh: {
|
||||||
|
translation: zh,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
lng: initialLanguage,
|
||||||
|
fallbackLng: "en",
|
||||||
|
interpolation: {
|
||||||
|
escapeValue: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default i18n;
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
/* Status Indicator Dot Animation */
|
||||||
|
@keyframes status-blink {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
opacity: 1;
|
||||||
|
transform: scale(1);
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
opacity: 0.3;
|
||||||
|
transform: scale(0.85);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-dot {
|
||||||
|
display: inline-block;
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 50%;
|
||||||
|
margin-right: 6px;
|
||||||
|
animation: status-blink 2s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-dot-green {
|
||||||
|
background-color: var(--green-9);
|
||||||
|
box-shadow: 0 0 8px var(--green-a7);
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-dot-red {
|
||||||
|
background-color: var(--red-9);
|
||||||
|
box-shadow: 0 0 8px var(--red-a7);
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-dot-gray {
|
||||||
|
background-color: var(--gray-9);
|
||||||
|
box-shadow: 0 0 8px var(--gray-a7);
|
||||||
|
}
|
||||||
@@ -0,0 +1,453 @@
|
|||||||
|
import { Avatar, Box, DropdownMenu, Flex, Popover, Text } from "@radix-ui/themes";
|
||||||
|
import { type ReactNode, useEffect, useState } from "react";
|
||||||
|
import { Link, useLocation } from "react-router-dom";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import pb from "../lib/pocketbase";
|
||||||
|
import { getGravatarUrl } from "../lib/gravatar";
|
||||||
|
import { motion, AnimatePresence } from "framer-motion";
|
||||||
|
import { PageTransition } from "../components/PageTransition";
|
||||||
|
import { ThemeToggle } from "../components/ThemeToggle";
|
||||||
|
import { LanguageToggle } from "../components/LanguageToggle";
|
||||||
|
import logo from "../assets/logo.png";
|
||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
|
||||||
|
interface MainLayoutProps {
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detect mobile by user agent OR viewport width < 640px (sm breakpoint).
|
||||||
|
// Uses matchMedia so the layout re-evaluates only when the threshold is crossed,
|
||||||
|
// not on every pixel change.
|
||||||
|
function useIsMobile() {
|
||||||
|
const isUA = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
|
||||||
|
navigator.userAgent,
|
||||||
|
);
|
||||||
|
|
||||||
|
const [isSmall, setIsSmall] = useState(() => window.matchMedia("(max-width: 639px)").matches);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const mq = window.matchMedia("(max-width: 639px)");
|
||||||
|
const handler = (e: MediaQueryListEvent) => setIsSmall(e.matches);
|
||||||
|
mq.addEventListener("change", handler);
|
||||||
|
return () => mq.removeEventListener("change", handler);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return isUA || isSmall;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNewerVersion(latest: string, current: string): boolean {
|
||||||
|
const clean = (v: string) => v.replace(/^v/, "");
|
||||||
|
const parts = (v: string) => clean(v).split(".").map(Number);
|
||||||
|
const [la, lb, lc] = parts(latest);
|
||||||
|
const [ca, cb, cc] = parts(current);
|
||||||
|
if (la !== ca) return la > ca;
|
||||||
|
if (lb !== cb) return lb > cb;
|
||||||
|
return lc > cc;
|
||||||
|
}
|
||||||
|
|
||||||
|
const navItems = [
|
||||||
|
{
|
||||||
|
labelKey: "nav.dashboard",
|
||||||
|
path: "/dashboard",
|
||||||
|
icon: <Icon icon="lucide:layout-dashboard" width="18" height="18" />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
labelKey: "nav.servers",
|
||||||
|
path: "/servers",
|
||||||
|
icon: <Icon icon="lucide:server" width="18" height="18" />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
labelKey: "nav.proxies",
|
||||||
|
path: "/proxies",
|
||||||
|
icon: <Icon icon="lucide:network" width="18" height="18" />,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const mobileBottomNavItems = navItems;
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
pb.authStore.clear();
|
||||||
|
window.location.href = "/login";
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleGotoProfile = () => {
|
||||||
|
window.location.href = "/settings?tab=profile";
|
||||||
|
};
|
||||||
|
|
||||||
|
export function MainLayout({ children }: MainLayoutProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const location = useLocation();
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
|
||||||
|
const [appVersion, setAppVersion] = useState<string>("");
|
||||||
|
const [latestVersion, setLatestVersion] = useState<string>("");
|
||||||
|
const [releaseUrl, setReleaseUrl] = useState<string>("");
|
||||||
|
const updateAvailable = appVersion && latestVersion ? isNewerVersion(latestVersion, appVersion) : false;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetch("/api/system/version")
|
||||||
|
.then((res) => res.json())
|
||||||
|
.then((data) => data.version && setAppVersion(data.version))
|
||||||
|
.catch(() => {});
|
||||||
|
|
||||||
|
fetch("/api/system/latest-version")
|
||||||
|
.then((res) => res.json())
|
||||||
|
.then((data) => {
|
||||||
|
if (data.tag_name) setLatestVersion(data.tag_name);
|
||||||
|
if (data.html_url) setReleaseUrl(data.html_url);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Get current user info from PocketBase authStore
|
||||||
|
const currentUser = pb.authStore.record;
|
||||||
|
const userEmail = currentUser?.email || "";
|
||||||
|
const userNickName = currentUser?.nickname || "";
|
||||||
|
const gravatarUrl = currentUser?.avatar
|
||||||
|
? pb.files.getURL(currentUser, currentUser.avatar)
|
||||||
|
: getGravatarUrl(userEmail, 80);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Flex direction="column" className="min-h-screen" style={{ backgroundColor: "var(--gray-2)", minWidth: "320px" }}>
|
||||||
|
{/* Top Navigation */}
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
backgroundColor: "var(--color-background)",
|
||||||
|
borderBottom: "1px solid var(--gray-6)",
|
||||||
|
}}
|
||||||
|
className="sticky top-0 z-50"
|
||||||
|
>
|
||||||
|
<Box className="mx-auto box-border max-w-7xl px-4 py-3 sm:px-6 lg:px-8">
|
||||||
|
<Flex justify="between" align="center">
|
||||||
|
{/* Left: Logo + Desktop Nav */}
|
||||||
|
<Flex align="center" gap="8" style={{ minWidth: 0 }}>
|
||||||
|
{/* Logo */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: -20 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ duration: 0.5, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<Link to="/" className="no-underline">
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<motion.img
|
||||||
|
initial={{ scale: 0, rotate: -180 }}
|
||||||
|
animate={{ scale: 1, rotate: 0 }}
|
||||||
|
transition={{
|
||||||
|
type: "spring",
|
||||||
|
stiffness: 260,
|
||||||
|
damping: 20,
|
||||||
|
delay: 0.1,
|
||||||
|
}}
|
||||||
|
whileHover={{ scale: 1.1, rotate: 10 }}
|
||||||
|
whileTap={{ scale: 0.95 }}
|
||||||
|
src={logo}
|
||||||
|
alt="Frpc Hub Logo"
|
||||||
|
className="h-8 w-8 cursor-pointer rounded-2xl object-contain"
|
||||||
|
/>
|
||||||
|
<Text size="4" weight="bold">
|
||||||
|
Frpc Hub
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
</Link>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
{/* Desktop Navigation Menu */}
|
||||||
|
{!isMobile && (
|
||||||
|
<Flex gap="1">
|
||||||
|
{navItems.map((item) => {
|
||||||
|
const isActive = location.pathname === item.path;
|
||||||
|
return (
|
||||||
|
<Link key={item.path} to={item.path} className="relative no-underline">
|
||||||
|
<motion.div
|
||||||
|
whileHover={{ y: -2 }}
|
||||||
|
whileTap={{ scale: 0.95 }}
|
||||||
|
className="relative"
|
||||||
|
>
|
||||||
|
<Flex
|
||||||
|
align="center"
|
||||||
|
gap="2"
|
||||||
|
className="relative z-10 rounded-lg px-4 py-2 transition-colors"
|
||||||
|
style={{
|
||||||
|
color: isActive ? "var(--accent-11)" : "var(--gray-11)",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{item.icon}
|
||||||
|
<Text size="2" weight="medium">
|
||||||
|
{t(item.labelKey)}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
{isActive && (
|
||||||
|
<motion.div
|
||||||
|
layoutId="active-nav"
|
||||||
|
className="absolute inset-0 rounded-lg bg-[var(--accent-a3)]"
|
||||||
|
transition={{
|
||||||
|
type: "spring",
|
||||||
|
bounce: 0.2,
|
||||||
|
duration: 0.6,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</motion.div>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
{/* Right: Controls */}
|
||||||
|
<Flex align="center" gap={isMobile ? "2" : "4"} style={{ flexShrink: 0 }}>
|
||||||
|
{/* Theme Toggle */}
|
||||||
|
<ThemeToggle />
|
||||||
|
|
||||||
|
{/* Language Toggle */}
|
||||||
|
<LanguageToggle />
|
||||||
|
|
||||||
|
{/* Update Available Badge */}
|
||||||
|
{updateAvailable && (
|
||||||
|
<Popover.Root>
|
||||||
|
<Popover.Trigger>
|
||||||
|
<motion.div
|
||||||
|
whileTap={{ scale: 0.95 }}
|
||||||
|
whileHover={{ scale: 1.05 }}
|
||||||
|
className="relative cursor-pointer rounded-lg p-2 transition-colors hover:bg-[var(--amber-a3)]"
|
||||||
|
style={{ color: "var(--amber-11)" }}
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:arrow-up-circle" width="20" height="20" />
|
||||||
|
<span
|
||||||
|
className="absolute right-1 top-1 h-2 w-2 rounded-full bg-[var(--amber-9)]"
|
||||||
|
style={{ display: "block" }}
|
||||||
|
/>
|
||||||
|
</motion.div>
|
||||||
|
</Popover.Trigger>
|
||||||
|
<Popover.Content style={{ maxWidth: 280 }}>
|
||||||
|
<Flex direction="column" gap="3">
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Icon icon="lucide:package" width="16" height="16" style={{ color: "var(--amber-11)" }} />
|
||||||
|
<Text size="2" weight="bold">
|
||||||
|
{t("version.updateAvailable")}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
<Flex direction="column" gap="1">
|
||||||
|
<Flex justify="between">
|
||||||
|
<Text size="1" color="gray">{t("version.current")}</Text>
|
||||||
|
<Text size="1" weight="medium">v{appVersion}</Text>
|
||||||
|
</Flex>
|
||||||
|
<Flex justify="between">
|
||||||
|
<Text size="1" color="gray">{t("version.latest")}</Text>
|
||||||
|
<Text size="1" weight="medium" style={{ color: "var(--amber-11)" }}>{latestVersion}</Text>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
{releaseUrl && (
|
||||||
|
<a href={releaseUrl} target="_blank" rel="noopener noreferrer" className="no-underline">
|
||||||
|
<Flex
|
||||||
|
align="center"
|
||||||
|
gap="1"
|
||||||
|
className="rounded-md px-3 py-2 transition-colors hover:bg-[var(--amber-a3)]"
|
||||||
|
style={{ color: "var(--amber-11)" }}
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:external-link" width="14" height="14" />
|
||||||
|
<Text size="1" weight="medium">{t("version.updateNow")}</Text>
|
||||||
|
</Flex>
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
</Popover.Content>
|
||||||
|
</Popover.Root>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Settings */}
|
||||||
|
<Link to="/settings" className="no-underline">
|
||||||
|
<motion.div
|
||||||
|
whileTap={{ scale: 0.95 }}
|
||||||
|
whileHover="hover"
|
||||||
|
className="cursor-pointer rounded-lg p-2 transition-colors hover:bg-[var(--gray-a3)]"
|
||||||
|
>
|
||||||
|
<motion.div
|
||||||
|
variants={{ hover: { scale: 1.1, rotate: 30 } }}
|
||||||
|
className="flex items-center justify-center"
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:settings" width="20" height="20" />
|
||||||
|
</motion.div>
|
||||||
|
</motion.div>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
{/* User Dropdown */}
|
||||||
|
<DropdownMenu.Root>
|
||||||
|
<DropdownMenu.Trigger>
|
||||||
|
<motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.98 }}>
|
||||||
|
<Flex align="center" gap="2" className="cursor-pointer">
|
||||||
|
<Avatar
|
||||||
|
size="2"
|
||||||
|
src={gravatarUrl}
|
||||||
|
fallback={userNickName.charAt(0).toUpperCase()}
|
||||||
|
radius="full"
|
||||||
|
/>
|
||||||
|
{/* Show name/email only on desktop */}
|
||||||
|
{!isMobile && (
|
||||||
|
<Flex direction="column" gap="0">
|
||||||
|
<Text size="2" weight="medium">
|
||||||
|
{userNickName}
|
||||||
|
</Text>
|
||||||
|
<Text size="1" color="gray">
|
||||||
|
{userEmail}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
</motion.div>
|
||||||
|
</DropdownMenu.Trigger>
|
||||||
|
<DropdownMenu.Content>
|
||||||
|
<DropdownMenu.Item onClick={handleGotoProfile}>
|
||||||
|
<Icon icon="lucide:user" width="16" height="16" /> {t("settings.profile")}
|
||||||
|
</DropdownMenu.Item>
|
||||||
|
<DropdownMenu.Separator />
|
||||||
|
<DropdownMenu.Item color="red" onClick={handleLogout}>
|
||||||
|
<Icon icon="lucide:log-out" width="16" height="16" /> {t("nav.logout")}
|
||||||
|
</DropdownMenu.Item>
|
||||||
|
</DropdownMenu.Content>
|
||||||
|
</DropdownMenu.Root>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* Main Content */}
|
||||||
|
<Box className="flex w-full flex-1 flex-col overflow-y-auto">
|
||||||
|
<Box
|
||||||
|
className="mx-auto box-border min-h-full w-full max-w-7xl flex-1 px-4 py-6 sm:px-6 lg:px-8"
|
||||||
|
style={{ paddingBottom: isMobile ? "72px" : undefined }}
|
||||||
|
>
|
||||||
|
<AnimatePresence mode="wait" initial={false}>
|
||||||
|
<PageTransition key={location.pathname}>{children}</PageTransition>
|
||||||
|
</AnimatePresence>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* Footer — desktop only */}
|
||||||
|
{!isMobile && (
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
backgroundColor: "var(--color-background)",
|
||||||
|
borderTop: "1px solid var(--gray-6)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box className="mx-auto box-border max-w-7xl px-4 py-4 sm:px-6 lg:px-8">
|
||||||
|
<Flex justify="between" align="center" wrap="wrap" gap="4">
|
||||||
|
{/* Left: Copyright */}
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Text size="1" color="gray">
|
||||||
|
© 2026 Frpc Hub. All rights reserved.
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
{/* Center: Version & Author */}
|
||||||
|
<Flex align="center" gap="4">
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Text size="1" color="gray">
|
||||||
|
Version: <Text weight="medium">{appVersion ? `v${appVersion}` : "—"}</Text>
|
||||||
|
</Text>
|
||||||
|
{updateAvailable && releaseUrl && (
|
||||||
|
<a href={releaseUrl} target="_blank" rel="noopener noreferrer" className="no-underline">
|
||||||
|
<Flex
|
||||||
|
align="center"
|
||||||
|
gap="1"
|
||||||
|
className="rounded-md px-2 py-0.5 transition-colors hover:bg-[var(--amber-a3)]"
|
||||||
|
style={{ color: "var(--amber-11)" }}
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:arrow-up-circle" width="12" height="12" />
|
||||||
|
<Text size="1" weight="medium">{latestVersion}</Text>
|
||||||
|
</Flex>
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Text size="1" color="gray">
|
||||||
|
Author:
|
||||||
|
</Text>
|
||||||
|
<Link
|
||||||
|
to="https://github.com/luckjiawei/"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="hover:text-gray-12 cursor-pointer no-underline transition-colors"
|
||||||
|
style={{
|
||||||
|
color: "var(--gray-11)",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: "4px",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Avatar
|
||||||
|
size="1"
|
||||||
|
src="https://github.com/luckjiawei.png"
|
||||||
|
fallback="L"
|
||||||
|
radius="full"
|
||||||
|
/>
|
||||||
|
<Text weight="medium" size="1">
|
||||||
|
liujiawei
|
||||||
|
</Text>
|
||||||
|
</Link>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
{/* Right: Links */}
|
||||||
|
<Flex align="center" gap="4">
|
||||||
|
<a
|
||||||
|
href="https://github.com/luckjiawei/frpc-hub"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="no-underline"
|
||||||
|
>
|
||||||
|
<Flex
|
||||||
|
align="center"
|
||||||
|
gap="1"
|
||||||
|
className="text-gray-500 transition-colors hover:text-gray-700"
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:github" width="16" height="16" />
|
||||||
|
<Text size="1">Frpc Hub</Text>
|
||||||
|
</Flex>
|
||||||
|
</a>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Mobile Bottom Navigation */}
|
||||||
|
{isMobile && (
|
||||||
|
<Box
|
||||||
|
className="fixed bottom-0 left-0 right-0 z-50"
|
||||||
|
style={{
|
||||||
|
backgroundColor: "var(--color-background)",
|
||||||
|
borderTop: "1px solid var(--gray-6)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Flex justify="between" align="center" style={{ paddingBottom: "env(safe-area-inset-bottom)" }}>
|
||||||
|
{mobileBottomNavItems.map((item) => {
|
||||||
|
const isActive = location.pathname.startsWith(item.path);
|
||||||
|
return (
|
||||||
|
<Link key={item.path} to={item.path} className="no-underline flex-1">
|
||||||
|
<Flex
|
||||||
|
direction="column"
|
||||||
|
align="center"
|
||||||
|
gap="1"
|
||||||
|
className="py-3"
|
||||||
|
style={{ color: isActive ? "var(--accent-11)" : "var(--gray-10)" }}
|
||||||
|
>
|
||||||
|
{item.icon}
|
||||||
|
<Text size="1" weight={isActive ? "bold" : "regular"}>
|
||||||
|
{t(item.labelKey)}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default MainLayout;
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
export const formatBytes = (bytes: number): { value: number; unit: string } => {
|
||||||
|
if (bytes === 0) return { value: 0, unit: "B" };
|
||||||
|
const k = 1024;
|
||||||
|
const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
|
||||||
|
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
return { value: bytes / Math.pow(k, i), unit: sizes[i] };
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format a timestamp into a human-readable "time ago" string
|
||||||
|
* @param timestamp - ISO date string or Date object
|
||||||
|
* @returns Formatted string like "5 minutes ago", "2 days ago", etc.
|
||||||
|
*/
|
||||||
|
export const getTimeAgo = (timestamp: string | Date | null | undefined): string => {
|
||||||
|
if (!timestamp) return "Never";
|
||||||
|
|
||||||
|
const date = new Date(timestamp);
|
||||||
|
const now = new Date();
|
||||||
|
const diffMs = now.getTime() - date.getTime();
|
||||||
|
|
||||||
|
// Handle future dates
|
||||||
|
if (diffMs < 0) return "Just now";
|
||||||
|
|
||||||
|
const diffMinutes = Math.floor(diffMs / (1000 * 60));
|
||||||
|
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
|
||||||
|
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
||||||
|
|
||||||
|
if (diffMinutes < 1) return "Just now";
|
||||||
|
if (diffMinutes < 60) return `${diffMinutes} minute${diffMinutes > 1 ? "s" : ""} ago`;
|
||||||
|
if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? "s" : ""} ago`;
|
||||||
|
if (diffDays < 30) return `${diffDays} day${diffDays > 1 ? "s" : ""} ago`;
|
||||||
|
if (diffDays < 365) {
|
||||||
|
const months = Math.floor(diffDays / 30);
|
||||||
|
return `${months} month${months > 1 ? "s" : ""} ago`;
|
||||||
|
}
|
||||||
|
const years = Math.floor(diffDays / 365);
|
||||||
|
return `${years} year${years > 1 ? "s" : ""} ago`;
|
||||||
|
};
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import md5 from "md5";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate Gravatar URL from email address
|
||||||
|
* @param email - User's email address
|
||||||
|
* @param size - Image size in pixels (default: 80)
|
||||||
|
* @param defaultImage - Default image type if email has no gravatar
|
||||||
|
* Options: 'mp' (mystery person), 'identicon', 'monsterid', 'wavatar', 'retro', 'robohash', 'blank'
|
||||||
|
* @returns Gravatar URL
|
||||||
|
*/
|
||||||
|
export function getGravatarUrl(
|
||||||
|
email: string,
|
||||||
|
size: number = 80,
|
||||||
|
defaultImage: string = "mp"
|
||||||
|
): string {
|
||||||
|
const trimmedEmail = email?.trim().toLowerCase() || "";
|
||||||
|
const hash = md5(trimmedEmail);
|
||||||
|
return `https://www.gravatar.com/avatar/${hash}?s=${size}&d=${defaultImage}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default getGravatarUrl;
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import PocketBase from "pocketbase";
|
||||||
|
|
||||||
|
const pb = new PocketBase(import.meta.env.VITE_POCKETBASE_URL || "/api");
|
||||||
|
|
||||||
|
export default pb;
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
export const REGEX = {
|
||||||
|
// IPv4 or IPv6 address
|
||||||
|
IP: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,
|
||||||
|
// IP or Hostname
|
||||||
|
IP_OR_HOSTNAME:
|
||||||
|
/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$|^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,
|
||||||
|
// Port number (1-65535)
|
||||||
|
PORT: /^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/,
|
||||||
|
// Proxy name (alphanumeric, hyphens, underscores)
|
||||||
|
PROXY_NAME: /^[a-zA-Z0-9_-]+$/,
|
||||||
|
// Server name (alphanumeric, Chinese, spaces, dots, underscores, hyphens)
|
||||||
|
SERVER_NAME: /^[a-zA-Z0-9\u4e00-\u9fa5\s._-]+$/,
|
||||||
|
};
|
||||||
@@ -0,0 +1,443 @@
|
|||||||
|
{
|
||||||
|
"common": {
|
||||||
|
"confirm": "Confirm",
|
||||||
|
"cancel": "Cancel",
|
||||||
|
"save": "Save",
|
||||||
|
"delete": "Delete",
|
||||||
|
"edit": "Edit",
|
||||||
|
"add": "Add",
|
||||||
|
"search": "Search",
|
||||||
|
"loading": "Loading...",
|
||||||
|
"success": "Success",
|
||||||
|
"error": "Error",
|
||||||
|
"warning": "Warning",
|
||||||
|
"info": "Info",
|
||||||
|
"actions": "Actions",
|
||||||
|
"name": "Name",
|
||||||
|
"type": "Type",
|
||||||
|
"status": "Status",
|
||||||
|
"created": "Created",
|
||||||
|
"updated": "Updated",
|
||||||
|
"description": "Description",
|
||||||
|
"close": "Close",
|
||||||
|
"submit": "Submit",
|
||||||
|
"reset": "Reset",
|
||||||
|
"discardChanges": "Discard Changes?",
|
||||||
|
"discardChangesDesc": "You have unsaved changes. Are you sure you want to discard them?",
|
||||||
|
"discard": "Discard",
|
||||||
|
"keepEditing": "Keep Editing",
|
||||||
|
"back": "Back"
|
||||||
|
},
|
||||||
|
"nav": {
|
||||||
|
"dashboard": "Dashboard",
|
||||||
|
"servers": "Servers",
|
||||||
|
"proxies": "Proxies",
|
||||||
|
"settings": "Settings",
|
||||||
|
"logout": "Logout",
|
||||||
|
"version": "Version",
|
||||||
|
"import": "Import"
|
||||||
|
},
|
||||||
|
"auth": {
|
||||||
|
"login": "Login",
|
||||||
|
"signIn": "Sign In",
|
||||||
|
"signingIn": "Signing in...",
|
||||||
|
"username": "Username",
|
||||||
|
"email": "Email",
|
||||||
|
"password": "Password",
|
||||||
|
"rememberMe": "Remember me",
|
||||||
|
"forgotPassword": "Forgot password?",
|
||||||
|
"loginSuccess": "Login successful",
|
||||||
|
"loginFailed": "Login failed",
|
||||||
|
"signInToAccount": "Sign in to your Frpc Hub account",
|
||||||
|
"enterEmail": "Enter your email",
|
||||||
|
"enterPassword": "Enter your password"
|
||||||
|
},
|
||||||
|
"dashboard": {
|
||||||
|
"title": "Dashboard",
|
||||||
|
"welcome": "Welcome to Frpc Hub",
|
||||||
|
"overview": "Overview of your Frpc Hub",
|
||||||
|
"systemOverview": "System Overview",
|
||||||
|
"totalServers": "Total Servers",
|
||||||
|
"runningServers": "Running Servers",
|
||||||
|
"runningProxies": "Running Proxies",
|
||||||
|
"onlineServers": "Online Servers",
|
||||||
|
"totalProxies": "Total Proxies",
|
||||||
|
"onlineProxies": "Online Proxies",
|
||||||
|
"activeProxies": "Active Proxies",
|
||||||
|
"trafficIn": "Traffic In",
|
||||||
|
"trafficOut": "Traffic Out",
|
||||||
|
"recentActivity": "Recent Activity",
|
||||||
|
"quickActions": "Quick Actions",
|
||||||
|
"systemStatus": "System Status",
|
||||||
|
"maxLatency": "Max Latency",
|
||||||
|
"systemUptime": "System Uptime",
|
||||||
|
"runningSinceStartup": "Running since startup",
|
||||||
|
"proxyTypeDistribution": "Proxy Type Distribution",
|
||||||
|
"topology": "Network Topology",
|
||||||
|
"topologyDesc": "Server and proxy relationship overview",
|
||||||
|
"topologyEmpty": "No servers configured",
|
||||||
|
"topologyEmptyDesc": "Add a server to visualize the network topology",
|
||||||
|
"topologyVisitors": "Visitors",
|
||||||
|
"topologyInternet": "Internet",
|
||||||
|
"topologyLocalService": "Local Service",
|
||||||
|
"noProxies": "No proxies configured",
|
||||||
|
"noProxiesDesc": "Add a proxy to see the type distribution",
|
||||||
|
"quickActions": "Quick Actions",
|
||||||
|
"qaServersDesc": "Manage server connections",
|
||||||
|
"qaProxiesDesc": "Configure proxy tunnels",
|
||||||
|
"qaImportDesc": "Import from TOML config",
|
||||||
|
"qaSettingsDesc": "App preferences & profile"
|
||||||
|
},
|
||||||
|
"server": {
|
||||||
|
"title": "Servers",
|
||||||
|
"addServer": "Add Server",
|
||||||
|
"addServerDesc": "Add a new FRP server connection",
|
||||||
|
"editServer": "Edit Server",
|
||||||
|
"updateServerDesc": "Update server connection details",
|
||||||
|
"serverName": "Server Name",
|
||||||
|
"serverAddr": "Server Address",
|
||||||
|
"serverPort": "Server Port",
|
||||||
|
"status": "Status",
|
||||||
|
"running": "Running",
|
||||||
|
"stopped": "Stopped",
|
||||||
|
"start": "Start",
|
||||||
|
"stop": "Stop",
|
||||||
|
"reload": "Reload",
|
||||||
|
"delete": "Delete",
|
||||||
|
"edit": "Edit",
|
||||||
|
"view": "View",
|
||||||
|
"launch": "Launch",
|
||||||
|
"autoConnection": "Auto Connection",
|
||||||
|
"autoConnectionDesc": "Automatically start this server when the application launches",
|
||||||
|
"basic": "Basic",
|
||||||
|
"auth": "Authentication",
|
||||||
|
"log": "Log",
|
||||||
|
"transport": "Transport",
|
||||||
|
"metadatas": "Metadatas",
|
||||||
|
"details": "Server Details",
|
||||||
|
"detailsAndLogs": "Server Details & Logs",
|
||||||
|
"configuration": "Configuration",
|
||||||
|
"noServers": "No Servers Configured",
|
||||||
|
"addFirstServer": "Add your first FRP server to get started. You'll need this to Manage your proxy configurations.",
|
||||||
|
"addYourFirstServer": "Add Your First Server",
|
||||||
|
"latency": "Latency",
|
||||||
|
"location": "Location",
|
||||||
|
"tls": "TLS",
|
||||||
|
"enabled": "Enabled",
|
||||||
|
"disabled": "Disabled",
|
||||||
|
"manageServers": "Manage your FRP server connections",
|
||||||
|
"allServers": "All Servers",
|
||||||
|
"searchServers": "Search servers...",
|
||||||
|
"refresh": "Refresh",
|
||||||
|
"totalServers": "Total Servers",
|
||||||
|
"noResultsFound": "No results found",
|
||||||
|
"noServersMatch": "No servers match your search query",
|
||||||
|
"clearSearch": "Clear Search",
|
||||||
|
"confirmDeletion": "Confirm Deletion",
|
||||||
|
"deleteConfirmMessage": "Are you sure you want to delete this server? This action cannot be undone.",
|
||||||
|
"host": "Host",
|
||||||
|
"port": "Port",
|
||||||
|
"bootStatus": "BootStatus",
|
||||||
|
"basicInformation": "Basic Information",
|
||||||
|
"hostAddress": "Host Address",
|
||||||
|
"createdAt": "Created At",
|
||||||
|
"lastUpdated": "Last Updated",
|
||||||
|
"protocol": "Protocol",
|
||||||
|
"noDescription": "No description provided.",
|
||||||
|
"proxyURL": "Proxy URL",
|
||||||
|
"connectionLogs": "Connection Logs",
|
||||||
|
"clear": "Clear",
|
||||||
|
"noLogsAvailable": "No logs available.",
|
||||||
|
"failedToLoad": "Failed to load server",
|
||||||
|
"backToServers": "Back to Servers",
|
||||||
|
"serverNamePlaceholder": "e.g. Production Server",
|
||||||
|
"hostAddressLabel": "Host Address",
|
||||||
|
"hostAddressPlaceholder": "e.g. frps.example.com",
|
||||||
|
"portLabel": "Port",
|
||||||
|
"portPlaceholder": "7000",
|
||||||
|
"version": "Version",
|
||||||
|
"selectVersion": "Select version",
|
||||||
|
"builtIn": "Built-in",
|
||||||
|
"authentication": "Authentication",
|
||||||
|
"selectAuthMethod": "Select authentication method",
|
||||||
|
"authMethodNone": "None",
|
||||||
|
"authMethodToken": "Token",
|
||||||
|
"authMethodOidc": "OIDC (Coming Soon)",
|
||||||
|
"token": "Token",
|
||||||
|
"tokenPlaceholder": "Authentication token",
|
||||||
|
"clientId": "Client ID",
|
||||||
|
"clientIdPlaceholder": "OIDC Client ID",
|
||||||
|
"clientSecret": "Client Secret",
|
||||||
|
"clientSecretPlaceholder": "OIDC Client Secret",
|
||||||
|
"audience": "Audience",
|
||||||
|
"audiencePlaceholder": "OIDC Audience",
|
||||||
|
"tokenEndpoint": "Token Endpoint",
|
||||||
|
"tokenEndpointPlaceholder": "https://idp.example.com/oauth/token",
|
||||||
|
"descriptionLabel": "Description",
|
||||||
|
"descriptionPlaceholder": "Add some notes about this server...",
|
||||||
|
"logLevel": "Log Level",
|
||||||
|
"logLevelTrace": "Trace",
|
||||||
|
"logLevelDebug": "Debug",
|
||||||
|
"logLevelInfo": "Info",
|
||||||
|
"logLevelWarn": "Warn",
|
||||||
|
"logLevelError": "Error",
|
||||||
|
"logFile": "Log File Path",
|
||||||
|
"logFilePlaceholder": "./frpc.log",
|
||||||
|
"maxDays": "Max Days",
|
||||||
|
"maxDaysPlaceholder": "3",
|
||||||
|
"protocolTcp": "TCP",
|
||||||
|
"protocolKcp": "KCP",
|
||||||
|
"protocolQuic": "QUIC",
|
||||||
|
"protocolWebsocket": "WebSocket",
|
||||||
|
"protocolWss": "WebSocket Secure",
|
||||||
|
"tlsEnable": "Enable TLS",
|
||||||
|
"disableCustomTLSFirstByte": "Disable Custom TLS First Byte",
|
||||||
|
"serverNameSNI": "Server Name (SNI)",
|
||||||
|
"serverNameSNIPlaceholder": "e.g. example.com",
|
||||||
|
"certFileContent": "Cert File Content",
|
||||||
|
"certFilePlaceholder": "Paste certificate content or upload file...",
|
||||||
|
"keyFileContent": "Key File Content",
|
||||||
|
"keyFilePlaceholder": "Paste key content or upload file...",
|
||||||
|
"trustedCAContent": "Trusted CA Content",
|
||||||
|
"trustedCAPlaceholder": "Paste CA certificate content or upload file...",
|
||||||
|
"loadFromFile": "Load from File",
|
||||||
|
"tlsServerName": "TLS Server Name",
|
||||||
|
"tlsServerNamePlaceholder": "frps.example.com",
|
||||||
|
"proxyUrl": "Proxy URL",
|
||||||
|
"proxyUrlPlaceholder": "http://user:pass@192.168.1.1:8080",
|
||||||
|
"dialTimeout": "Dial Timeout",
|
||||||
|
"dialTimeoutPlaceholder": "10s",
|
||||||
|
"poolCount": "Pool Count",
|
||||||
|
"poolCountPlaceholder": "5",
|
||||||
|
"tcpMux": "TCP Mux",
|
||||||
|
"tcpMuxKeepaliveInterval": "Keepalive Interval",
|
||||||
|
"tcpMuxKeepaliveIntervalPlaceholder": "60",
|
||||||
|
"heartbeatInterval": "Heartbeat Interval",
|
||||||
|
"heartbeatIntervalPlaceholder": "30",
|
||||||
|
"heartbeatTimeout": "Heartbeat Timeout",
|
||||||
|
"heartbeatTimeoutPlaceholder": "90",
|
||||||
|
"general": "General",
|
||||||
|
"addMetadata": "Add Metadata",
|
||||||
|
"metadataKey": "Key",
|
||||||
|
"metadataValue": "Value",
|
||||||
|
"metadataKeyPlaceholder": "e.g. environment",
|
||||||
|
"metadataValuePlaceholder": "e.g. production",
|
||||||
|
"noMetadata": "No metadata",
|
||||||
|
"saving": "Saving...",
|
||||||
|
"adding": "Adding...",
|
||||||
|
"saveChanges": "Save Changes",
|
||||||
|
"errorInvalidIP": "Invalid IP address or domain name",
|
||||||
|
"errorInvalidPort": "Port must be between 1 and 65535",
|
||||||
|
"errorInvalidServerName": "Only letters, numbers, Chinese characters, spaces, dots, underscores, and hyphens are allowed"
|
||||||
|
},
|
||||||
|
"proxy": {
|
||||||
|
"title": "Proxies",
|
||||||
|
"addProxy": "Add Proxy",
|
||||||
|
"addProxyDesc": "Configure a new proxy service",
|
||||||
|
"editProxy": "Edit Proxy",
|
||||||
|
"updateProxyDesc": "Update proxy configuration",
|
||||||
|
"proxyName": "Proxy Name",
|
||||||
|
"proxyType": "Proxy Type",
|
||||||
|
"localIP": "Local IP",
|
||||||
|
"localPort": "Local Port",
|
||||||
|
"remotePort": "Remote Port",
|
||||||
|
"customDomains": "Custom Domains",
|
||||||
|
"status": "Status",
|
||||||
|
"online": "Online",
|
||||||
|
"offline": "Offline",
|
||||||
|
"edit": "Edit",
|
||||||
|
"delete": "Delete",
|
||||||
|
"noProxies": "No Proxies Found",
|
||||||
|
"addFirstProxy": "Connect your local services to the world. Add your first proxy configuration to get started.",
|
||||||
|
"createYourFirstProxy": "Create Your First Proxy",
|
||||||
|
"server": "Server",
|
||||||
|
"bootStatus": "Boot Status",
|
||||||
|
"manageProxies": "Manage your proxy configurations",
|
||||||
|
"allProxies": "All Proxies",
|
||||||
|
"searchProxies": "Search proxies...",
|
||||||
|
"refresh": "Refresh",
|
||||||
|
"totalProxies": "Total Proxies",
|
||||||
|
"confirmDeletion": "Confirm Deletion",
|
||||||
|
"deleteConfirmMessage": "Are you sure you want to delete this proxy? This action cannot be undone.",
|
||||||
|
"remotePortOrDomain": "Remote Port / Domain",
|
||||||
|
"selectServer": "Select Server",
|
||||||
|
"selectServerPlaceholder": "Select a server",
|
||||||
|
"noServersAvailable": "No servers available",
|
||||||
|
"goAddServer": "Add a server",
|
||||||
|
"proxyNamePlaceholder": "e.g. my-web-service",
|
||||||
|
"localAddress": "Local Address",
|
||||||
|
"localAddressPlaceholder": "127.0.0.1",
|
||||||
|
"localPortPlaceholder": "8080",
|
||||||
|
"customDomainsLabel": "Custom Domains",
|
||||||
|
"customDomainsPlaceholder": "example.com, www.example.com",
|
||||||
|
"customDomainsDesc": "Multiple domains separated by commas",
|
||||||
|
"subdomain": "Subdomain",
|
||||||
|
"subdomainPlaceholder": "myapp",
|
||||||
|
"subdomainDesc": "Subdomain for the proxy",
|
||||||
|
"remotePortLabel": "Remote Port",
|
||||||
|
"remotePortPlaceholder": "6000",
|
||||||
|
"remotePortDesc": "Port exposed on server side",
|
||||||
|
"descriptionLabel": "Description",
|
||||||
|
"descriptionPlaceholder": "Add some description...",
|
||||||
|
"encryption": "Encryption",
|
||||||
|
"compression": "Compression",
|
||||||
|
"bandwidthLimit": "Bandwidth Limit",
|
||||||
|
"bandwidthLimitPlaceholder": "1MB",
|
||||||
|
"basicConfig": "Basic Config",
|
||||||
|
"advancedOptions": "Advanced Options",
|
||||||
|
"transportEncryption": "Transport Encryption",
|
||||||
|
"transportEncryptionDesc": "Enable to encrypt data during transport",
|
||||||
|
"dataCompression": "Data Compression",
|
||||||
|
"dataCompressionDesc": "Enable to compress data during transport",
|
||||||
|
"saving": "Saving...",
|
||||||
|
"adding": "Adding...",
|
||||||
|
"saveChanges": "Save Changes",
|
||||||
|
"enabled": "Enabled",
|
||||||
|
"disabled": "Disabled",
|
||||||
|
"errorInvalidName": "Invalid name (use alphanumeric, - or _)",
|
||||||
|
"errorInvalidIP": "Invalid IP or hostname",
|
||||||
|
"errorInvalidPort": "Invalid port (1-65535)"
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Settings",
|
||||||
|
"language": "Language",
|
||||||
|
"interfaceLanguage": "Interface Language",
|
||||||
|
"chooseLanguage": "Choose the language for the dashboard",
|
||||||
|
"theme": "Theme",
|
||||||
|
"profile": "Profile",
|
||||||
|
"general": "General",
|
||||||
|
"generalSettings": "General Settings",
|
||||||
|
"configureApp": "Configure how Frpc Hub looks and behaves",
|
||||||
|
"saveSuccess": "Settings saved successfully",
|
||||||
|
"saveFailed": "Failed to save settings",
|
||||||
|
"preferences": "Preferences",
|
||||||
|
"manageWorkspace": "Manage your workspace preferences and system configuration",
|
||||||
|
"personalLanguageOverride": "You have a personal language preference set",
|
||||||
|
"resetToDefault": "Reset to default",
|
||||||
|
"monitorSettings": "Monitor Settings",
|
||||||
|
"latencyCheckInterval": "Latency Check Interval",
|
||||||
|
"latencyCheckIntervalDesc": "How often to check server latency (10-300 seconds)",
|
||||||
|
"locationCheckInterval": "Location Check Interval",
|
||||||
|
"locationCheckIntervalDesc": "How often to check server location and IP (30-600 seconds)",
|
||||||
|
"seconds": "seconds",
|
||||||
|
"userProfile": "User Profile",
|
||||||
|
"managePersonalInfo": "Manage your personal information and account settings",
|
||||||
|
"active": "Active",
|
||||||
|
"personalInformation": "Personal Information",
|
||||||
|
"displayName": "Display Name",
|
||||||
|
"enterDisplayName": "Enter your display name",
|
||||||
|
"emailAddress": "Email Address",
|
||||||
|
"emailPlaceholder": "your.email@example.com",
|
||||||
|
"emailDescription": "Your email is used for notifications and account recovery",
|
||||||
|
"security": "Security",
|
||||||
|
"password": "Password",
|
||||||
|
"lastChanged": "Last changed",
|
||||||
|
"changePassword": "Change Password",
|
||||||
|
"saving": "Saving...",
|
||||||
|
"saveChanges": "Save Changes",
|
||||||
|
"changePasswordTitle": "Change Password",
|
||||||
|
"changePasswordDesc": "Enter your current password and a new password to update your account security.",
|
||||||
|
"currentPassword": "Current Password",
|
||||||
|
"enterCurrentPassword": "Enter current password",
|
||||||
|
"newPassword": "New Password",
|
||||||
|
"enterNewPassword": "Enter new password",
|
||||||
|
"confirmNewPassword": "Confirm New Password",
|
||||||
|
"confirmNewPasswordPlaceholder": "Confirm new password",
|
||||||
|
"updating": "Updating...",
|
||||||
|
"updatePassword": "Update Password",
|
||||||
|
"fillAllFields": "Please fill in all fields",
|
||||||
|
"passwordsDoNotMatch": "New passwords do not match",
|
||||||
|
"passwordTooShort": "Password must be at least 8 characters long",
|
||||||
|
"incorrectPassword": "Current password is incorrect",
|
||||||
|
"passwordUpdateSuccess": "Password updated successfully! Please sign in again."
|
||||||
|
},
|
||||||
|
"language": {
|
||||||
|
"en": "English",
|
||||||
|
"zh": "中文"
|
||||||
|
},
|
||||||
|
"version": {
|
||||||
|
"title": "Version",
|
||||||
|
"current": "Current Version",
|
||||||
|
"latest": "Latest Version",
|
||||||
|
"checkUpdate": "Check for Updates",
|
||||||
|
"upToDate": "You are up to date",
|
||||||
|
"updateAvailable": "Update Available",
|
||||||
|
"updateNow": "View Release"
|
||||||
|
},
|
||||||
|
"import": {
|
||||||
|
"title": "Import",
|
||||||
|
"description": "Import servers and proxies from a FRP TOML config file",
|
||||||
|
"step1Label": "Input",
|
||||||
|
"step2Label": "Preview",
|
||||||
|
"step3Label": "Done",
|
||||||
|
"inputTomlTitle": "Paste or Upload TOML Config",
|
||||||
|
"inputTomlDesc": "Paste the content of your frpc.toml file, or upload it directly. Supports standard FRP v1 client configuration format.",
|
||||||
|
"uploadFile": "Upload File",
|
||||||
|
"tomlPlaceholder": "# frpc.toml\nserverAddr = \"x.x.x.x\"\nserverPort = 7000\n\n[auth]\nmethod = \"token\"\ntoken = \"your-token\"\n\n[[proxies]]\nname = \"ssh\"\ntype = \"tcp\"\nlocalIP = \"127.0.0.1\"\nlocalPort = 22\nremotePort = 6000",
|
||||||
|
"parseAndPreview": "Parse & Preview",
|
||||||
|
"parsing": "Parsing...",
|
||||||
|
"errorEmptyContent": "TOML content cannot be empty",
|
||||||
|
"errorParseFailed": "Failed to parse TOML content. Please check the format.",
|
||||||
|
"serverSection": "Server",
|
||||||
|
"proxySection": "Proxies",
|
||||||
|
"serverName": "Server Name",
|
||||||
|
"serverNamePlaceholder": "e.g. My Server",
|
||||||
|
"serverAddr": "Address",
|
||||||
|
"authMethod": "Auth Method",
|
||||||
|
"duplicate": "Duplicate",
|
||||||
|
"exists": "Exists",
|
||||||
|
"new": "New",
|
||||||
|
"serverDuplicateWarning": "A server with this address and port already exists. You can overwrite it or keep the existing one and only import proxies.",
|
||||||
|
"importServer": "Import Server",
|
||||||
|
"overwriteServer": "Overwrite existing server",
|
||||||
|
"noProxies": "No proxies found in this config file.",
|
||||||
|
"local": "Local",
|
||||||
|
"remote": "Remote",
|
||||||
|
"overwrite": "Overwrite",
|
||||||
|
"selectAll": "Select All",
|
||||||
|
"deselectAll": "Deselect All",
|
||||||
|
"selectedCount": "{{count}} proxy(s) selected",
|
||||||
|
"back": "Back",
|
||||||
|
"confirmImport": "Confirm Import",
|
||||||
|
"importing": "Importing...",
|
||||||
|
"errorImportFailed": "Import failed. Please try again.",
|
||||||
|
"successTitle": "Import Successful!",
|
||||||
|
"successDesc": "Your servers and proxies have been imported.",
|
||||||
|
"serverResult": "Server",
|
||||||
|
"proxiesImported": "Proxies Imported",
|
||||||
|
"proxiesSkipped": "Proxies Skipped",
|
||||||
|
"imported": "Imported",
|
||||||
|
"skipped": "Skipped",
|
||||||
|
"importAnother": "Import Another",
|
||||||
|
"viewServers": "View Servers",
|
||||||
|
"importSuccess": "Import completed successfully"
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"notFound": "Page Not Found",
|
||||||
|
"goHome": "Go to Home",
|
||||||
|
"somethingWrong": "Something went wrong",
|
||||||
|
"tryAgain": "Try Again"
|
||||||
|
},
|
||||||
|
"setup": {
|
||||||
|
"title": "System Initialization",
|
||||||
|
"description": "Set up the administrator account and default language",
|
||||||
|
"language": "Default Language",
|
||||||
|
"adminEmail": "Administrator Email",
|
||||||
|
"enterAdminEmail": "Enter admin email",
|
||||||
|
"password": "Password",
|
||||||
|
"enterPassword": "At least 8 characters",
|
||||||
|
"confirmPassword": "Confirm Password",
|
||||||
|
"enterPasswordAgain": "Enter password again",
|
||||||
|
"complete": "Complete Setup",
|
||||||
|
"initializing": "Initializing...",
|
||||||
|
"success": "System initialized successfully! Please login.",
|
||||||
|
"error": {
|
||||||
|
"allFieldsRequired": "All fields are required",
|
||||||
|
"passwordTooShort": "Password must be at least 8 characters",
|
||||||
|
"passwordMismatch": "Passwords do not match",
|
||||||
|
"invalidEmail": "Invalid email address",
|
||||||
|
"setupFailed": "Failed to initialize system. Please try again.",
|
||||||
|
"settingsCreateFailed": "Failed to initialize system settings"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,443 @@
|
|||||||
|
{
|
||||||
|
"common": {
|
||||||
|
"confirm": "确认",
|
||||||
|
"cancel": "取消",
|
||||||
|
"save": "保存",
|
||||||
|
"delete": "删除",
|
||||||
|
"edit": "编辑",
|
||||||
|
"add": "添加",
|
||||||
|
"search": "搜索",
|
||||||
|
"loading": "加载中...",
|
||||||
|
"success": "成功",
|
||||||
|
"error": "错误",
|
||||||
|
"warning": "警告",
|
||||||
|
"info": "信息",
|
||||||
|
"actions": "操作",
|
||||||
|
"name": "名称",
|
||||||
|
"type": "类型",
|
||||||
|
"status": "状态",
|
||||||
|
"created": "创建时间",
|
||||||
|
"updated": "更新时间",
|
||||||
|
"description": "描述",
|
||||||
|
"close": "关闭",
|
||||||
|
"submit": "提交",
|
||||||
|
"reset": "重置",
|
||||||
|
"discardChanges": "放弃更改?",
|
||||||
|
"discardChangesDesc": "您有未保存的更改。确定要放弃它们吗?",
|
||||||
|
"discard": "放弃",
|
||||||
|
"keepEditing": "继续编辑",
|
||||||
|
"back": "返回"
|
||||||
|
},
|
||||||
|
"nav": {
|
||||||
|
"dashboard": "仪表板",
|
||||||
|
"servers": "服务器",
|
||||||
|
"proxies": "代理",
|
||||||
|
"settings": "设置",
|
||||||
|
"logout": "退出登录",
|
||||||
|
"version": "版本",
|
||||||
|
"import": "导入"
|
||||||
|
},
|
||||||
|
"auth": {
|
||||||
|
"login": "登录",
|
||||||
|
"signIn": "登录",
|
||||||
|
"signingIn": "登录中...",
|
||||||
|
"username": "用户名",
|
||||||
|
"email": "邮箱",
|
||||||
|
"password": "密码",
|
||||||
|
"rememberMe": "记住我",
|
||||||
|
"forgotPassword": "忘记密码?",
|
||||||
|
"loginSuccess": "登录成功",
|
||||||
|
"loginFailed": "登录失败",
|
||||||
|
"signInToAccount": "登录到您的 Frpc Hub 账户",
|
||||||
|
"enterEmail": "输入您的邮箱",
|
||||||
|
"enterPassword": "输入您的密码"
|
||||||
|
},
|
||||||
|
"dashboard": {
|
||||||
|
"title": "仪表板",
|
||||||
|
"welcome": "欢迎使用 Frpc Hub",
|
||||||
|
"overview": "您的 Frpc Hub 概览",
|
||||||
|
"systemOverview": "系统概览",
|
||||||
|
"totalServers": "服务器总数",
|
||||||
|
"runningServers": "运行中的服务器",
|
||||||
|
"runningProxies": "运行中的代理",
|
||||||
|
"onlineServers": "在线服务器",
|
||||||
|
"totalProxies": "代理总数",
|
||||||
|
"onlineProxies": "在线代理",
|
||||||
|
"activeProxies": "活跃代理",
|
||||||
|
"trafficIn": "入站流量",
|
||||||
|
"trafficOut": "出站流量",
|
||||||
|
"recentActivity": "最近活动",
|
||||||
|
"quickActions": "快捷操作",
|
||||||
|
"systemStatus": "系统状态",
|
||||||
|
"maxLatency": "最大延迟",
|
||||||
|
"systemUptime": "系统运行时间",
|
||||||
|
"runningSinceStartup": "自启动以来运行",
|
||||||
|
"proxyTypeDistribution": "代理类型分布",
|
||||||
|
"topology": "网络拓扑",
|
||||||
|
"topologyDesc": "服务器与代理的关系总览",
|
||||||
|
"topologyEmpty": "暂无服务器配置",
|
||||||
|
"topologyEmptyDesc": "添加服务器后即可查看网络拓扑图",
|
||||||
|
"topologyVisitors": "访问者",
|
||||||
|
"topologyInternet": "互联网",
|
||||||
|
"topologyLocalService": "本地服务",
|
||||||
|
"noProxies": "暂无代理配置",
|
||||||
|
"noProxiesDesc": "添加代理后即可查看类型分布",
|
||||||
|
"quickActions": "快速操作",
|
||||||
|
"qaServersDesc": "管理服务器连接",
|
||||||
|
"qaProxiesDesc": "配置代理隧道",
|
||||||
|
"qaImportDesc": "从 TOML 配置文件导入",
|
||||||
|
"qaSettingsDesc": "应用设置与个人资料"
|
||||||
|
},
|
||||||
|
"server": {
|
||||||
|
"title": "服务器",
|
||||||
|
"addServer": "添加服务器",
|
||||||
|
"addServerDesc": "添加一个新的 FRP 服务器连接",
|
||||||
|
"editServer": "编辑服务器",
|
||||||
|
"updateServerDesc": "更新服务器连接详情",
|
||||||
|
"serverName": "服务器名称",
|
||||||
|
"serverAddr": "服务器地址",
|
||||||
|
"serverPort": "服务器端口",
|
||||||
|
"status": "状态",
|
||||||
|
"running": "运行中",
|
||||||
|
"stopped": "已停止",
|
||||||
|
"start": "启动",
|
||||||
|
"stop": "停止",
|
||||||
|
"reload": "重载",
|
||||||
|
"delete": "删除",
|
||||||
|
"edit": "编辑",
|
||||||
|
"view": "查看",
|
||||||
|
"launch": "启动",
|
||||||
|
"autoConnection": "自动连接",
|
||||||
|
"autoConnectionDesc": "应用程序启动时自动启动此服务器",
|
||||||
|
"basic": "基础",
|
||||||
|
"auth": "认证",
|
||||||
|
"log": "日志",
|
||||||
|
"transport": "传输",
|
||||||
|
"metadatas": "元数据",
|
||||||
|
"details": "服务器详情",
|
||||||
|
"detailsAndLogs": "服务器详情和日志",
|
||||||
|
"configuration": "配置",
|
||||||
|
"noServers": "未配置服务器",
|
||||||
|
"addFirstServer": "添加您的第一个 FRP 服务器以开始使用。您需要它来管理您的代理配置。",
|
||||||
|
"addYourFirstServer": "添加您的第一个服务器",
|
||||||
|
"latency": "延迟",
|
||||||
|
"location": "位置",
|
||||||
|
"tls": "TLS",
|
||||||
|
"enabled": "已启用",
|
||||||
|
"disabled": "已禁用",
|
||||||
|
"manageServers": "管理您的 FRP 服务器连接",
|
||||||
|
"allServers": "所有服务器",
|
||||||
|
"searchServers": "搜索服务器...",
|
||||||
|
"refresh": "刷新",
|
||||||
|
"totalServers": "服务器总数",
|
||||||
|
"noResultsFound": "未找到结果",
|
||||||
|
"noServersMatch": "没有服务器匹配您的搜索查询",
|
||||||
|
"clearSearch": "清除搜索",
|
||||||
|
"confirmDeletion": "确认删除",
|
||||||
|
"deleteConfirmMessage": "您确定要删除此服务器吗?此操作无法撤消。",
|
||||||
|
"host": "主机",
|
||||||
|
"port": "端口",
|
||||||
|
"bootStatus": "启动状态",
|
||||||
|
"basicInformation": "基本信息",
|
||||||
|
"hostAddress": "主机地址",
|
||||||
|
"createdAt": "创建时间",
|
||||||
|
"lastUpdated": "最后更新",
|
||||||
|
"protocol": "协议",
|
||||||
|
"noDescription": "未提供描述。",
|
||||||
|
"proxyURL": "代理 URL",
|
||||||
|
"connectionLogs": "连接日志",
|
||||||
|
"clear": "清除",
|
||||||
|
"noLogsAvailable": "没有可用的日志。",
|
||||||
|
"failedToLoad": "加载服务器失败",
|
||||||
|
"backToServers": "返回服务器列表",
|
||||||
|
"serverNamePlaceholder": "例如:生产服务器",
|
||||||
|
"hostAddressLabel": "主机地址",
|
||||||
|
"hostAddressPlaceholder": "例如:frps.example.com",
|
||||||
|
"portLabel": "端口",
|
||||||
|
"portPlaceholder": "7000",
|
||||||
|
"version": "版本",
|
||||||
|
"selectVersion": "选择版本",
|
||||||
|
"builtIn": "内置",
|
||||||
|
"authentication": "认证",
|
||||||
|
"selectAuthMethod": "选择认证方式",
|
||||||
|
"authMethodNone": "无",
|
||||||
|
"authMethodToken": "令牌",
|
||||||
|
"authMethodOidc": "OIDC(即将推出)",
|
||||||
|
"token": "令牌",
|
||||||
|
"tokenPlaceholder": "认证令牌",
|
||||||
|
"clientId": "客户端 ID",
|
||||||
|
"clientIdPlaceholder": "OIDC 客户端 ID",
|
||||||
|
"clientSecret": "客户端密钥",
|
||||||
|
"clientSecretPlaceholder": "OIDC 客户端密钥",
|
||||||
|
"audience": "受众",
|
||||||
|
"audiencePlaceholder": "OIDC 受众",
|
||||||
|
"tokenEndpoint": "令牌端点",
|
||||||
|
"tokenEndpointPlaceholder": "https://idp.example.com/oauth/token",
|
||||||
|
"descriptionLabel": "描述",
|
||||||
|
"descriptionPlaceholder": "添加一些关于此服务器的备注...",
|
||||||
|
"logLevel": "日志级别",
|
||||||
|
"logLevelTrace": "跟踪",
|
||||||
|
"logLevelDebug": "调试",
|
||||||
|
"logLevelInfo": "信息",
|
||||||
|
"logLevelWarn": "警告",
|
||||||
|
"logLevelError": "错误",
|
||||||
|
"logFile": "日志文件路径",
|
||||||
|
"logFilePlaceholder": "./frpc.log",
|
||||||
|
"maxDays": "最大天数",
|
||||||
|
"maxDaysPlaceholder": "3",
|
||||||
|
"protocolTcp": "TCP",
|
||||||
|
"protocolKcp": "KCP",
|
||||||
|
"protocolQuic": "QUIC",
|
||||||
|
"protocolWebsocket": "WebSocket",
|
||||||
|
"protocolWss": "WebSocket 安全",
|
||||||
|
"tlsEnable": "启用 TLS",
|
||||||
|
"disableCustomTLSFirstByte": "禁用自定义 TLS 首字节",
|
||||||
|
"serverNameSNI": "服务器名称(SNI)",
|
||||||
|
"serverNameSNIPlaceholder": "例如:example.com",
|
||||||
|
"certFileContent": "证书文件内容",
|
||||||
|
"certFilePlaceholder": "粘贴证书内容或上传文件...",
|
||||||
|
"keyFileContent": "密钥文件内容",
|
||||||
|
"keyFilePlaceholder": "粘贴密钥内容或上传文件...",
|
||||||
|
"trustedCAContent": "受信任的 CA 内容",
|
||||||
|
"trustedCAPlaceholder": "粘贴 CA 证书内容或上传文件...",
|
||||||
|
"loadFromFile": "从文件加载",
|
||||||
|
"tlsServerName": "TLS 服务器名称",
|
||||||
|
"tlsServerNamePlaceholder": "frps.example.com",
|
||||||
|
"proxyUrl": "代理 URL",
|
||||||
|
"proxyUrlPlaceholder": "http://user:pass@192.168.1.1:8080",
|
||||||
|
"dialTimeout": "拨号超时",
|
||||||
|
"dialTimeoutPlaceholder": "10s",
|
||||||
|
"poolCount": "连接池数量",
|
||||||
|
"poolCountPlaceholder": "5",
|
||||||
|
"tcpMux": "TCP 复用",
|
||||||
|
"tcpMuxKeepaliveInterval": "保活间隔",
|
||||||
|
"tcpMuxKeepaliveIntervalPlaceholder": "60",
|
||||||
|
"heartbeatInterval": "心跳间隔",
|
||||||
|
"heartbeatIntervalPlaceholder": "30",
|
||||||
|
"heartbeatTimeout": "心跳超时",
|
||||||
|
"heartbeatTimeoutPlaceholder": "90",
|
||||||
|
"general": "常规",
|
||||||
|
"addMetadata": "添加元数据",
|
||||||
|
"metadataKey": "键",
|
||||||
|
"metadataValue": "值",
|
||||||
|
"metadataKeyPlaceholder": "例如:environment",
|
||||||
|
"metadataValuePlaceholder": "例如:production",
|
||||||
|
"noMetadata": "无元数据",
|
||||||
|
"saving": "保存中...",
|
||||||
|
"adding": "添加中...",
|
||||||
|
"saveChanges": "保存更改",
|
||||||
|
"errorInvalidIP": "无效的 IP 地址或域名",
|
||||||
|
"errorInvalidPort": "端口必须在 1 到 65535 之间",
|
||||||
|
"errorInvalidServerName": "仅允许字母、数字、中文字符、空格、点、下划线和连字符"
|
||||||
|
},
|
||||||
|
"proxy": {
|
||||||
|
"title": "代理",
|
||||||
|
"addProxy": "添加代理",
|
||||||
|
"addProxyDesc": "配置一个新的代理服务",
|
||||||
|
"editProxy": "编辑代理",
|
||||||
|
"updateProxyDesc": "更新代理配置",
|
||||||
|
"proxyName": "代理名称",
|
||||||
|
"proxyType": "代理类型",
|
||||||
|
"localIP": "本地 IP",
|
||||||
|
"localPort": "本地端口",
|
||||||
|
"remotePort": "远程端口",
|
||||||
|
"customDomains": "自定义域名",
|
||||||
|
"status": "状态",
|
||||||
|
"online": "在线",
|
||||||
|
"offline": "离线",
|
||||||
|
"edit": "编辑",
|
||||||
|
"delete": "删除",
|
||||||
|
"noProxies": "未找到代理",
|
||||||
|
"addFirstProxy": "将您的本地服务连接到世界。添加您的第一个代理配置以开始使用。",
|
||||||
|
"createYourFirstProxy": "创建您的第一个代理",
|
||||||
|
"server": "服务器",
|
||||||
|
"bootStatus": "启动状态",
|
||||||
|
"manageProxies": "管理您的代理配置",
|
||||||
|
"allProxies": "所有代理",
|
||||||
|
"searchProxies": "搜索代理...",
|
||||||
|
"refresh": "刷新",
|
||||||
|
"totalProxies": "代理总数",
|
||||||
|
"confirmDeletion": "确认删除",
|
||||||
|
"deleteConfirmMessage": "您确定要删除此代理吗?此操作无法撤消。",
|
||||||
|
"remotePortOrDomain": "远程端口 / 域名",
|
||||||
|
"selectServer": "选择服务器",
|
||||||
|
"selectServerPlaceholder": "选择一个服务器",
|
||||||
|
"noServersAvailable": "没有可用的服务器",
|
||||||
|
"goAddServer": "去添加服务器",
|
||||||
|
"proxyNamePlaceholder": "例如:my-web-service",
|
||||||
|
"localAddress": "本地地址",
|
||||||
|
"localAddressPlaceholder": "127.0.0.1",
|
||||||
|
"localPortPlaceholder": "8080",
|
||||||
|
"customDomainsLabel": "自定义域名",
|
||||||
|
"customDomainsPlaceholder": "example.com, www.example.com",
|
||||||
|
"customDomainsDesc": "多个域名用逗号分隔",
|
||||||
|
"subdomain": "子域名",
|
||||||
|
"subdomainPlaceholder": "myapp",
|
||||||
|
"subdomainDesc": "代理的子域名",
|
||||||
|
"remotePortLabel": "远程端口",
|
||||||
|
"remotePortPlaceholder": "6000",
|
||||||
|
"remotePortDesc": "在服务器端暴露的端口",
|
||||||
|
"descriptionLabel": "描述",
|
||||||
|
"descriptionPlaceholder": "添加一些描述...",
|
||||||
|
"encryption": "加密",
|
||||||
|
"compression": "压缩",
|
||||||
|
"bandwidthLimit": "带宽限制",
|
||||||
|
"bandwidthLimitPlaceholder": "1MB",
|
||||||
|
"basicConfig": "基础配置",
|
||||||
|
"advancedOptions": "高级选项",
|
||||||
|
"transportEncryption": "传输加密",
|
||||||
|
"transportEncryptionDesc": "启用以在传输过程中加密数据",
|
||||||
|
"dataCompression": "数据压缩",
|
||||||
|
"dataCompressionDesc": "启用以在传输过程中压缩数据",
|
||||||
|
"saving": "保存中...",
|
||||||
|
"adding": "添加中...",
|
||||||
|
"saveChanges": "保存更改",
|
||||||
|
"enabled": "已启用",
|
||||||
|
"disabled": "已禁用",
|
||||||
|
"errorInvalidName": "无效的名称(使用字母数字、- 或 _)",
|
||||||
|
"errorInvalidIP": "无效的 IP 或主机名",
|
||||||
|
"errorInvalidPort": "无效的端口(1-65535)"
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "设置",
|
||||||
|
"language": "语言",
|
||||||
|
"interfaceLanguage": "界面语言",
|
||||||
|
"chooseLanguage": "选择仪表板的语言",
|
||||||
|
"theme": "主题",
|
||||||
|
"profile": "个人资料",
|
||||||
|
"general": "常规",
|
||||||
|
"generalSettings": "常规设置",
|
||||||
|
"configureApp": "配置 Frpc Hub 的外观和行为",
|
||||||
|
"saveSuccess": "设置保存成功",
|
||||||
|
"saveFailed": "设置保存失败",
|
||||||
|
"preferences": "偏好设置",
|
||||||
|
"manageWorkspace": "管理您的工作区偏好和系统配置",
|
||||||
|
"personalLanguageOverride": "您已设置个人语言偏好",
|
||||||
|
"resetToDefault": "恢复默认",
|
||||||
|
"monitorSettings": "监控设置",
|
||||||
|
"latencyCheckInterval": "延迟检测间隔",
|
||||||
|
"latencyCheckIntervalDesc": "检查服务器延迟的频率(10-300 秒)",
|
||||||
|
"locationCheckInterval": "位置检查间隔",
|
||||||
|
"locationCheckIntervalDesc": "检查服务器位置和 IP 的频率(30-600 秒)",
|
||||||
|
"seconds": "秒",
|
||||||
|
"userProfile": "用户资料",
|
||||||
|
"managePersonalInfo": "管理您的个人信息和账户设置",
|
||||||
|
"active": "活跃",
|
||||||
|
"personalInformation": "个人信息",
|
||||||
|
"displayName": "显示名称",
|
||||||
|
"enterDisplayName": "输入您的显示名称",
|
||||||
|
"emailAddress": "电子邮箱",
|
||||||
|
"emailPlaceholder": "your.email@example.com",
|
||||||
|
"emailDescription": "您的邮箱用于通知和账户恢复",
|
||||||
|
"security": "安全",
|
||||||
|
"password": "密码",
|
||||||
|
"lastChanged": "上次修改",
|
||||||
|
"changePassword": "修改密码",
|
||||||
|
"saving": "保存中...",
|
||||||
|
"saveChanges": "保存更改",
|
||||||
|
"changePasswordTitle": "修改密码",
|
||||||
|
"changePasswordDesc": "输入您的当前密码和新密码以更新账户安全。",
|
||||||
|
"currentPassword": "当前密码",
|
||||||
|
"enterCurrentPassword": "输入当前密码",
|
||||||
|
"newPassword": "新密码",
|
||||||
|
"enterNewPassword": "输入新密码",
|
||||||
|
"confirmNewPassword": "确认新密码",
|
||||||
|
"confirmNewPasswordPlaceholder": "确认新密码",
|
||||||
|
"updating": "更新中...",
|
||||||
|
"updatePassword": "更新密码",
|
||||||
|
"fillAllFields": "请填写所有字段",
|
||||||
|
"passwordsDoNotMatch": "新密码不匹配",
|
||||||
|
"passwordTooShort": "密码长度至少为 8 个字符",
|
||||||
|
"incorrectPassword": "当前密码不正确",
|
||||||
|
"passwordUpdateSuccess": "密码更新成功!请重新登录。"
|
||||||
|
},
|
||||||
|
"language": {
|
||||||
|
"en": "English",
|
||||||
|
"zh": "中文"
|
||||||
|
},
|
||||||
|
"version": {
|
||||||
|
"title": "版本",
|
||||||
|
"current": "当前版本",
|
||||||
|
"latest": "最新版本",
|
||||||
|
"checkUpdate": "检查更新",
|
||||||
|
"upToDate": "已是最新版本",
|
||||||
|
"updateAvailable": "有可用更新",
|
||||||
|
"updateNow": "查看发布"
|
||||||
|
},
|
||||||
|
"import": {
|
||||||
|
"title": "导入",
|
||||||
|
"description": "从 FRP TOML 配置文件导入服务器和代理",
|
||||||
|
"step1Label": "输入",
|
||||||
|
"step2Label": "预览",
|
||||||
|
"step3Label": "完成",
|
||||||
|
"inputTomlTitle": "粘贴或上传 TOML 配置",
|
||||||
|
"inputTomlDesc": "粘贴您的 frpc.toml 文件内容,或直接上传文件。支持标准 FRP v1 客户端配置格式。",
|
||||||
|
"uploadFile": "上传文件",
|
||||||
|
"tomlPlaceholder": "# frpc.toml\nserverAddr = \"x.x.x.x\"\nserverPort = 7000\n\n[auth]\nmethod = \"token\"\ntoken = \"your-token\"\n\n[[proxies]]\nname = \"ssh\"\ntype = \"tcp\"\nlocalIP = \"127.0.0.1\"\nlocalPort = 22\nremotePort = 6000",
|
||||||
|
"parseAndPreview": "解析并预览",
|
||||||
|
"parsing": "解析中...",
|
||||||
|
"errorEmptyContent": "TOML 内容不能为空",
|
||||||
|
"errorParseFailed": "TOML 内容解析失败,请检查格式是否正确。",
|
||||||
|
"serverSection": "服务器",
|
||||||
|
"proxySection": "代理",
|
||||||
|
"serverName": "服务器名称",
|
||||||
|
"serverNamePlaceholder": "例如:我的服务器",
|
||||||
|
"serverAddr": "地址",
|
||||||
|
"authMethod": "认证方式",
|
||||||
|
"duplicate": "重复",
|
||||||
|
"exists": "已存在",
|
||||||
|
"new": "新建",
|
||||||
|
"serverDuplicateWarning": "已存在相同地址和端口的服务器。您可以覆盖它,或保留现有服务器并仅导入代理。",
|
||||||
|
"importServer": "导入服务器",
|
||||||
|
"overwriteServer": "覆盖已有服务器",
|
||||||
|
"noProxies": "配置文件中未找到代理。",
|
||||||
|
"local": "本地",
|
||||||
|
"remote": "远端",
|
||||||
|
"overwrite": "覆盖",
|
||||||
|
"selectAll": "全选",
|
||||||
|
"deselectAll": "取消全选",
|
||||||
|
"selectedCount": "已选 {{count}} 个代理",
|
||||||
|
"back": "返回",
|
||||||
|
"confirmImport": "确认导入",
|
||||||
|
"importing": "导入中...",
|
||||||
|
"errorImportFailed": "导入失败,请重试。",
|
||||||
|
"successTitle": "导入成功!",
|
||||||
|
"successDesc": "您的服务器和代理已导入完成。",
|
||||||
|
"serverResult": "服务器",
|
||||||
|
"proxiesImported": "代理导入数",
|
||||||
|
"proxiesSkipped": "代理跳过数",
|
||||||
|
"imported": "已导入",
|
||||||
|
"skipped": "已跳过",
|
||||||
|
"importAnother": "继续导入",
|
||||||
|
"viewServers": "查看服务器",
|
||||||
|
"importSuccess": "导入完成"
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"notFound": "页面未找到",
|
||||||
|
"goHome": "返回首页",
|
||||||
|
"somethingWrong": "出了点问题",
|
||||||
|
"tryAgain": "重试"
|
||||||
|
},
|
||||||
|
"setup": {
|
||||||
|
"title": "系统初始化",
|
||||||
|
"description": "设置管理员账户和默认语言",
|
||||||
|
"language": "默认语言",
|
||||||
|
"adminEmail": "管理员邮箱",
|
||||||
|
"enterAdminEmail": "输入管理员邮箱",
|
||||||
|
"password": "密码",
|
||||||
|
"enterPassword": "至少 8 个字符",
|
||||||
|
"confirmPassword": "确认密码",
|
||||||
|
"enterPasswordAgain": "再次输入密码",
|
||||||
|
"complete": "完成设置",
|
||||||
|
"initializing": "初始化中...",
|
||||||
|
"success": "系统初始化成功!请登录。",
|
||||||
|
"error": {
|
||||||
|
"allFieldsRequired": "所有字段都是必填的",
|
||||||
|
"passwordTooShort": "密码长度至少为 8 个字符",
|
||||||
|
"passwordMismatch": "密码不匹配",
|
||||||
|
"invalidEmail": "无效的邮箱地址",
|
||||||
|
"setupFailed": "系统初始化失败。请重试。",
|
||||||
|
"settingsCreateFailed": "初始化系统设置失败"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { StrictMode } from "react";
|
||||||
|
import { createRoot } from "react-dom/client";
|
||||||
|
import { Theme } from "@radix-ui/themes";
|
||||||
|
import { Toaster } from "sonner";
|
||||||
|
import "@radix-ui/themes/styles.css";
|
||||||
|
import "./index.css";
|
||||||
|
import "./i18n";
|
||||||
|
import App from "./App.tsx";
|
||||||
|
import { ThemeProvider, useTheme } from "./contexts/ThemeContext";
|
||||||
|
import { LanguageProvider } from "./contexts/LanguageContext";
|
||||||
|
|
||||||
|
function ThemedApp() {
|
||||||
|
const { theme } = useTheme();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Theme appearance={theme} accentColor="indigo" grayColor="slate" radius="large">
|
||||||
|
<App />
|
||||||
|
<Toaster richColors position="top-center" />
|
||||||
|
</Theme>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
createRoot(document.getElementById("root")!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<ThemeProvider>
|
||||||
|
<LanguageProvider>
|
||||||
|
<ThemedApp />
|
||||||
|
</LanguageProvider>
|
||||||
|
</ThemeProvider>
|
||||||
|
</StrictMode>
|
||||||
|
);
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
.recharts-legend-wrapper {
|
||||||
|
outline: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recharts-legend-wrapper * {
|
||||||
|
outline: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recharts-surface {
|
||||||
|
outline: none !important;
|
||||||
|
}
|
||||||
@@ -0,0 +1,339 @@
|
|||||||
|
import { Box, Card, Flex, Text } from "@radix-ui/themes";
|
||||||
|
import type {
|
||||||
|
DashboardStats,
|
||||||
|
RecentActivity,
|
||||||
|
TopologyData,
|
||||||
|
TrafficHistoryPoint,
|
||||||
|
} from "./useDashboard";
|
||||||
|
import { TopologyChart } from "./TopologyChart";
|
||||||
|
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer, Legend } from "recharts";
|
||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
import { PageHeader } from "../../components/PageHeader";
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { Link } from "react-router-dom";
|
||||||
|
import { motion } from "framer-motion";
|
||||||
|
import { AnimateNumber } from "../../components/AnimateNumber";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import "./DashboardPage.css";
|
||||||
|
|
||||||
|
interface DashboardViewProps {
|
||||||
|
stats: DashboardStats;
|
||||||
|
activities: RecentActivity[];
|
||||||
|
trafficHistory: TrafficHistoryPoint[];
|
||||||
|
topology: TopologyData;
|
||||||
|
loading: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
import { StatCard } from "../../components/StatCard";
|
||||||
|
|
||||||
|
// Helper function to format uptime
|
||||||
|
function formatUptime(seconds: number): string {
|
||||||
|
const days = Math.floor(seconds / 86400);
|
||||||
|
const hours = Math.floor((seconds % 86400) / 3600);
|
||||||
|
const minutes = Math.floor((seconds % 3600) / 60);
|
||||||
|
|
||||||
|
if (days > 0) {
|
||||||
|
return `${days}d ${hours}h ${minutes}m`;
|
||||||
|
} else if (hours > 0) {
|
||||||
|
return `${hours}h ${minutes}m`;
|
||||||
|
} else {
|
||||||
|
return `${minutes}m`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DashboardView({ stats, topology }: DashboardViewProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(() => setMounted(true), 100);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Flex direction="column" gap="6">
|
||||||
|
{/* Header */}
|
||||||
|
<PageHeader
|
||||||
|
title={t("dashboard.title")}
|
||||||
|
description={t("dashboard.overview")}
|
||||||
|
visible={mounted}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Stats Cards Row 1 */}
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 md:grid-cols-3">
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.1, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<StatCard
|
||||||
|
title={t("dashboard.runningProxies")}
|
||||||
|
value={
|
||||||
|
<>
|
||||||
|
<AnimateNumber value={stats.runningProxies} decimalPlaces={0} />
|
||||||
|
<Text size="2" color="gray" weight="regular" ml="2">
|
||||||
|
/ {stats.totalProxies}
|
||||||
|
</Text>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
color="green"
|
||||||
|
icon={<Icon icon="lucide:network" color="var(--green-11)" width="32" height="32" />}
|
||||||
|
/>
|
||||||
|
</motion.div>
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.2, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<StatCard
|
||||||
|
title={t("dashboard.onlineServers")}
|
||||||
|
value={
|
||||||
|
<>
|
||||||
|
<AnimateNumber value={stats.onlineServers} decimalPlaces={0} />
|
||||||
|
<Text size="2" color="gray" weight="regular" ml="2">
|
||||||
|
/ {stats.totalServers}
|
||||||
|
</Text>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
color="blue"
|
||||||
|
icon={<Icon icon="lucide:server" color="var(--blue-11)" width="32" height="32" />}
|
||||||
|
/>
|
||||||
|
</motion.div>
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.3, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<StatCard
|
||||||
|
title={t("dashboard.maxLatency")}
|
||||||
|
value={
|
||||||
|
<>
|
||||||
|
<AnimateNumber value={stats.maxLatency} decimalPlaces={0} />
|
||||||
|
<Text size="2" color="gray" weight="regular" ml="2">
|
||||||
|
ms
|
||||||
|
</Text>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
color="orange"
|
||||||
|
icon={<Icon icon="lucide:activity" color="var(--orange-11)" width="32" height="32" />}
|
||||||
|
/>
|
||||||
|
</motion.div>
|
||||||
|
{/* <motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.4, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<StatCard
|
||||||
|
title="Traffic Out"
|
||||||
|
value={
|
||||||
|
<AnimateNumber
|
||||||
|
value={stats.totalTrafficOut}
|
||||||
|
unit={stats.totalTrafficOutUnit}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
color="orange"
|
||||||
|
icon={
|
||||||
|
<Icon
|
||||||
|
icon="lucide:upload"
|
||||||
|
color="var(--orange-11)"
|
||||||
|
width="32"
|
||||||
|
height="32"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</motion.div> */}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Quick Actions */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.4, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<Flex direction="column" gap="3">
|
||||||
|
<Text size="2" weight="bold" color="gray">
|
||||||
|
{t("dashboard.quickActions")}
|
||||||
|
</Text>
|
||||||
|
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||||
|
{(
|
||||||
|
[
|
||||||
|
{ to: "/servers", icon: "lucide:server", color: "var(--blue-9)", bg: "var(--blue-3)", titleKey: "nav.servers", descKey: "dashboard.qaServersDesc" },
|
||||||
|
{ to: "/proxies", icon: "lucide:network", color: "var(--green-9)", bg: "var(--green-3)", titleKey: "nav.proxies", descKey: "dashboard.qaProxiesDesc" },
|
||||||
|
{ to: "/import", icon: "lucide:file-input", color: "var(--orange-9)", bg: "var(--orange-3)", titleKey: "nav.import", descKey: "dashboard.qaImportDesc" },
|
||||||
|
{ to: "/settings", icon: "lucide:settings-2", color: "var(--purple-9)", bg: "var(--purple-3)", titleKey: "nav.settings", descKey: "dashboard.qaSettingsDesc" },
|
||||||
|
] as const
|
||||||
|
).map(({ to, icon, color, bg, titleKey, descKey }) => (
|
||||||
|
<Link key={to} to={to} style={{ textDecoration: "none" }}>
|
||||||
|
<Card size="2" style={{ cursor: "pointer", height: "100%" }}>
|
||||||
|
<Flex direction="column" gap="2">
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
width: 36,
|
||||||
|
height: 36,
|
||||||
|
borderRadius: "var(--radius-3)",
|
||||||
|
background: bg,
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icon icon={icon} color={color} width="18" height="18" />
|
||||||
|
</Box>
|
||||||
|
<Flex direction="column" gap="1" style={{ flex: 1 }}>
|
||||||
|
<Text size="2" weight="bold">
|
||||||
|
{t(titleKey)}
|
||||||
|
</Text>
|
||||||
|
<Text size="1" color="gray">
|
||||||
|
{t(descKey)}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
<Flex justify="end">
|
||||||
|
<Icon icon="lucide:arrow-right" color="var(--gray-8)" width="14" height="14" />
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Flex>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
{/* Proxy Type Distribution & System Uptime */}
|
||||||
|
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
|
||||||
|
{/* Proxy Type Pie Chart */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.5, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<Card size="3" style={{ outline: "none" }}>
|
||||||
|
<Flex direction="column" gap="4" style={{ outline: "none" }}>
|
||||||
|
{/* <Text size="3" weight="bold">
|
||||||
|
Proxy Type Distribution
|
||||||
|
</Text> */}
|
||||||
|
|
||||||
|
<Box className="h-[350px] w-full" style={{ outline: "none" }}>
|
||||||
|
{Object.keys(stats.proxyTypeCounts).length === 0 ? (
|
||||||
|
<Flex
|
||||||
|
direction="column"
|
||||||
|
align="center"
|
||||||
|
justify="center"
|
||||||
|
gap="3"
|
||||||
|
style={{ height: "100%" }}
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:pie-chart" color="var(--gray-7)" width="56" height="56" />
|
||||||
|
<Flex direction="column" align="center" gap="1">
|
||||||
|
<Text size="3" weight="medium" color="gray">
|
||||||
|
{t("dashboard.noProxies")}
|
||||||
|
</Text>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("dashboard.noProxiesDesc")}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
) : (
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<PieChart style={{ outline: "none" }}>
|
||||||
|
<Pie
|
||||||
|
style={{ outline: "none" }}
|
||||||
|
data={Object.entries(stats.proxyTypeCounts).map(([type, count]) => ({
|
||||||
|
name: type.toUpperCase(),
|
||||||
|
value: count,
|
||||||
|
}))}
|
||||||
|
cx="50%"
|
||||||
|
cy="50%"
|
||||||
|
labelLine={false}
|
||||||
|
label={({ name, percent }) => `${name} ${((percent || 0) * 100).toFixed(0)}%`}
|
||||||
|
outerRadius={100}
|
||||||
|
fill="#8884d8"
|
||||||
|
dataKey="value"
|
||||||
|
>
|
||||||
|
{Object.keys(stats.proxyTypeCounts).map((type, index) => {
|
||||||
|
const colors = {
|
||||||
|
tcp: "var(--blue-9)",
|
||||||
|
udp: "var(--green-9)",
|
||||||
|
http: "var(--orange-9)",
|
||||||
|
https: "var(--purple-9)",
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<Cell
|
||||||
|
key={`cell-${index}`}
|
||||||
|
fill={colors[type as keyof typeof colors] || "var(--gray-9)"}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Pie>
|
||||||
|
<Tooltip
|
||||||
|
contentStyle={{
|
||||||
|
backgroundColor: "var(--color-panel-solid)",
|
||||||
|
borderColor: "var(--gray-5)",
|
||||||
|
borderRadius: "var(--radius-3)",
|
||||||
|
fontSize: "12px",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Legend />
|
||||||
|
</PieChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
{/* System Uptime */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.6, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<Card size="3">
|
||||||
|
<Flex
|
||||||
|
direction="column"
|
||||||
|
gap="3"
|
||||||
|
align="center"
|
||||||
|
justify="center"
|
||||||
|
className="h-full min-h-[350px]"
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:clock" color="var(--indigo-9)" width="56" height="56" />
|
||||||
|
<Flex direction="column" gap="1" align="center">
|
||||||
|
<Text size="3" weight="medium" color="gray">
|
||||||
|
{t("dashboard.systemUptime")}
|
||||||
|
</Text>
|
||||||
|
<Text size="6" weight="bold" style={{ color: "var(--indigo-11)" }}>
|
||||||
|
{formatUptime(stats.uptimeSeconds)}
|
||||||
|
</Text>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("dashboard.runningSinceStartup")}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
</motion.div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Network Topology */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.7, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<Card size="3">
|
||||||
|
<Flex direction="column" gap="3">
|
||||||
|
<Flex direction="column" gap="1">
|
||||||
|
<Text size="3" weight="bold">
|
||||||
|
{t("dashboard.topology")}
|
||||||
|
</Text>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("dashboard.topologyDesc")}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
<Box>
|
||||||
|
<TopologyChart topology={topology} />
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
</motion.div>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,520 @@
|
|||||||
|
import { useMemo } from "react";
|
||||||
|
import {
|
||||||
|
ReactFlow,
|
||||||
|
Background,
|
||||||
|
BackgroundVariant,
|
||||||
|
Handle,
|
||||||
|
Position,
|
||||||
|
type Node,
|
||||||
|
type Edge,
|
||||||
|
} from "@xyflow/react";
|
||||||
|
import "@xyflow/react/dist/style.css";
|
||||||
|
import { Flex, Text, useThemeContext } from "@radix-ui/themes";
|
||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import type { TopologyData } from "./useDashboard";
|
||||||
|
|
||||||
|
// ── Layout ────────────────────────────────────────────────────────────────────
|
||||||
|
const VISITOR_W = 112;
|
||||||
|
const VISITOR_H = 90;
|
||||||
|
const SERVER_W = 158;
|
||||||
|
const SERVER_H = 92;
|
||||||
|
const PROXY_W = 150;
|
||||||
|
const PROXY_H = 92;
|
||||||
|
const LOCAL_W = 140;
|
||||||
|
const LOCAL_H = 68;
|
||||||
|
const ROW_H = 112; // row height (node height + gap)
|
||||||
|
|
||||||
|
// Column left-edge X positions
|
||||||
|
const COL = {
|
||||||
|
visitor: 0,
|
||||||
|
server: 160, // VISITOR_W + 48
|
||||||
|
proxy: 400, // server + SERVER_W + 82
|
||||||
|
local: 638, // proxy + PROXY_W + 88
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Colours ───────────────────────────────────────────────────────────────────
|
||||||
|
const C = {
|
||||||
|
// edge colours
|
||||||
|
eVisitor: "#6366f1", // visitor → server : indigo (decorative)
|
||||||
|
eOn: "#22c55e", // any active edge : green
|
||||||
|
eOff: "#71717a", // any inactive edge: gray
|
||||||
|
|
||||||
|
// status
|
||||||
|
online: "#22c55e",
|
||||||
|
offline: "#ef4444",
|
||||||
|
|
||||||
|
// proxy type
|
||||||
|
tcp: "#3b82f6",
|
||||||
|
udp: "#22c55e",
|
||||||
|
http: "#f97316",
|
||||||
|
https: "#a855f7",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
function typeColor(t: string): string {
|
||||||
|
return (C as Record<string, string>)[t.toLowerCase()] ?? "#6b7280";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Theme
|
||||||
|
const LIGHT = {
|
||||||
|
bg: "#ffffff",
|
||||||
|
text: "#111827",
|
||||||
|
sub: "#6b7280",
|
||||||
|
border: "#e5e7eb",
|
||||||
|
pageBg: "#f3f4f6",
|
||||||
|
dot: "#d1d5db",
|
||||||
|
};
|
||||||
|
const DARK = {
|
||||||
|
bg: "#1c1c2e",
|
||||||
|
text: "#f0f0f0",
|
||||||
|
sub: "#9ca3af",
|
||||||
|
border: "#2d2d44",
|
||||||
|
pageBg: "#13131f",
|
||||||
|
dot: "#3d3d55",
|
||||||
|
};
|
||||||
|
type Palette = typeof LIGHT;
|
||||||
|
|
||||||
|
// Shared
|
||||||
|
function StatusPill({
|
||||||
|
online,
|
||||||
|
labels = ["Online", "Offline"],
|
||||||
|
}: {
|
||||||
|
online: boolean;
|
||||||
|
labels?: [string, string];
|
||||||
|
}) {
|
||||||
|
const color = online ? C.online : C.offline;
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
display: "inline-flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: 3,
|
||||||
|
padding: "2px 7px",
|
||||||
|
borderRadius: 999,
|
||||||
|
fontSize: 9,
|
||||||
|
fontWeight: 700,
|
||||||
|
background: color + "20",
|
||||||
|
color,
|
||||||
|
border: `1px solid ${color + "60"}`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span style={{ width: 5, height: 5, borderRadius: "50%", background: color }} />
|
||||||
|
{online ? labels[0] : labels[1]}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function NodeCard({
|
||||||
|
w,
|
||||||
|
h,
|
||||||
|
accentColor,
|
||||||
|
children,
|
||||||
|
targetPos,
|
||||||
|
targetColor,
|
||||||
|
sourcePos,
|
||||||
|
sourceColor,
|
||||||
|
p: palette,
|
||||||
|
}: {
|
||||||
|
w: number;
|
||||||
|
h: number;
|
||||||
|
accentColor: string;
|
||||||
|
children: React.ReactNode;
|
||||||
|
targetPos?: Position;
|
||||||
|
targetColor?: string;
|
||||||
|
sourcePos?: Position;
|
||||||
|
sourceColor?: string;
|
||||||
|
p: Palette;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
width: w,
|
||||||
|
height: h,
|
||||||
|
borderRadius: 10,
|
||||||
|
boxSizing: "border-box",
|
||||||
|
border: `1.5px solid ${palette.border}`,
|
||||||
|
borderLeft: `3px solid ${accentColor}`,
|
||||||
|
background: palette.bg,
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
padding: "8px 10px",
|
||||||
|
gap: 4,
|
||||||
|
boxShadow: "0 1px 4px rgba(0,0,0,0.08)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{targetPos !== undefined && (
|
||||||
|
<Handle
|
||||||
|
type="target"
|
||||||
|
position={targetPos}
|
||||||
|
style={{ background: targetColor, border: "none", width: 8, height: 8 }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{sourcePos !== undefined && (
|
||||||
|
<Handle
|
||||||
|
type="source"
|
||||||
|
position={sourcePos}
|
||||||
|
style={{ background: sourceColor, border: "none", width: 8, height: 8 }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Visitor Node
|
||||||
|
function VisitorNode({ data }: { data: Record<string, string> }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const p = data.isDark === "1" ? DARK : LIGHT;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
width: VISITOR_W,
|
||||||
|
height: VISITOR_H,
|
||||||
|
borderRadius: 12,
|
||||||
|
boxSizing: "border-box",
|
||||||
|
border: `2px solid ${C.eVisitor}40`,
|
||||||
|
background: C.eVisitor + "12",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
gap: 5,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Handle
|
||||||
|
type="source"
|
||||||
|
position={Position.Right}
|
||||||
|
style={{ background: C.eOn, border: "none", width: 8, height: 8 }}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
width: 36,
|
||||||
|
height: 36,
|
||||||
|
borderRadius: "50%",
|
||||||
|
background: C.eVisitor + "20",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:users" width={18} height={18} color={C.eVisitor} />
|
||||||
|
</div>
|
||||||
|
<div style={{ textAlign: "center" }}>
|
||||||
|
<div style={{ fontSize: 11, fontWeight: 700, color: p.text }}>
|
||||||
|
{t("dashboard.topologyVisitors")}
|
||||||
|
</div>
|
||||||
|
<div style={{ fontSize: 9, color: p.sub }}>{t("dashboard.topologyInternet")}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server Node
|
||||||
|
function ServerNode({ data }: { data: Record<string, string> }) {
|
||||||
|
const p = data.isDark === "1" ? DARK : LIGHT;
|
||||||
|
const online = data.bootStatus === "running";
|
||||||
|
const accent = online ? C.online : C.eOff;
|
||||||
|
const handleColor = online ? C.eOn : C.eOff;
|
||||||
|
return (
|
||||||
|
<NodeCard
|
||||||
|
w={SERVER_W}
|
||||||
|
h={SERVER_H}
|
||||||
|
accentColor={accent}
|
||||||
|
p={p}
|
||||||
|
targetPos={Position.Left}
|
||||||
|
targetColor={handleColor}
|
||||||
|
sourcePos={Position.Right}
|
||||||
|
sourceColor={handleColor}
|
||||||
|
>
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 6 }}>
|
||||||
|
<Icon icon="lucide:server" width={13} height={13} color={p.sub} />
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: 700,
|
||||||
|
color: p.text,
|
||||||
|
flex: 1,
|
||||||
|
overflow: "hidden",
|
||||||
|
textOverflow: "ellipsis",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{data.serverName}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
fontSize: 10,
|
||||||
|
color: p.sub,
|
||||||
|
overflow: "hidden",
|
||||||
|
textOverflow: "ellipsis",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{data.serverAddr}
|
||||||
|
</span>
|
||||||
|
<StatusPill online={online} labels={["Running", "Stopped"]} />
|
||||||
|
</NodeCard>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Proxy Node
|
||||||
|
function ProxyNode({ data }: { data: Record<string, string> }) {
|
||||||
|
const p = data.isDark === "1" ? DARK : LIGHT;
|
||||||
|
const online = data.bootStatus === "online";
|
||||||
|
const tc = typeColor(data.proxyType);
|
||||||
|
const handleColor = online ? C.eOn : C.eOff;
|
||||||
|
return (
|
||||||
|
<NodeCard
|
||||||
|
w={PROXY_W}
|
||||||
|
h={PROXY_H}
|
||||||
|
accentColor={online ? C.online : C.eOff}
|
||||||
|
p={p}
|
||||||
|
targetPos={Position.Left}
|
||||||
|
targetColor={handleColor}
|
||||||
|
sourcePos={Position.Right}
|
||||||
|
sourceColor={handleColor}
|
||||||
|
>
|
||||||
|
{/* icon + name */}
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 6 }}>
|
||||||
|
<Icon icon="lucide:network" width={13} height={13} color={p.sub} />
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: 700,
|
||||||
|
color: p.text,
|
||||||
|
overflow: "hidden",
|
||||||
|
textOverflow: "ellipsis",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{data.name}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{/* protocol + port */}
|
||||||
|
<span style={{ fontSize: 10, color: p.sub }}>
|
||||||
|
<span style={{ color: tc, fontWeight: 700 }}>{data.proxyType.toUpperCase()}</span>
|
||||||
|
{data.remotePort && <span style={{ fontFamily: "monospace" }}> :{data.remotePort}</span>}
|
||||||
|
</span>
|
||||||
|
{/* status */}
|
||||||
|
<StatusPill online={online} />
|
||||||
|
</NodeCard>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Local Service Node ────────────────────────────────────────────────────────
|
||||||
|
function LocalServiceNode({ data }: { data: Record<string, string> }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const p = data.isDark === "1" ? DARK : LIGHT;
|
||||||
|
return (
|
||||||
|
<NodeCard
|
||||||
|
w={LOCAL_W}
|
||||||
|
h={LOCAL_H}
|
||||||
|
accentColor={C.eOn}
|
||||||
|
p={p}
|
||||||
|
targetPos={Position.Left}
|
||||||
|
targetColor={C.eOn}
|
||||||
|
>
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 6 }}>
|
||||||
|
<Icon icon="lucide:hard-drive" width={13} height={13} color={p.sub} />
|
||||||
|
<span style={{ fontSize: 10, fontWeight: 700, color: p.text }}>
|
||||||
|
{t("dashboard.topologyLocalService")}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span style={{ fontSize: 11, color: p.sub, fontFamily: "monospace" }}>
|
||||||
|
{data.localIP}:{data.localPort}
|
||||||
|
</span>
|
||||||
|
</NodeCard>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const nodeTypes = {
|
||||||
|
visitor: VisitorNode,
|
||||||
|
server: ServerNode,
|
||||||
|
proxy: ProxyNode,
|
||||||
|
localService: LocalServiceNode,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Edge
|
||||||
|
function mkEdge(id: string, source: string, target: string, color: string, active: boolean): Edge {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
source,
|
||||||
|
target,
|
||||||
|
type: "smoothstep",
|
||||||
|
animated: active,
|
||||||
|
style: {
|
||||||
|
stroke: active ? color : C.eOff,
|
||||||
|
strokeWidth: active ? 2 : 1.5,
|
||||||
|
strokeDasharray: active ? undefined : "5 4",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main
|
||||||
|
interface TopologyChartProps {
|
||||||
|
topology: TopologyData;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TopologyChart({ topology }: TopologyChartProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const themeCtx = useThemeContext();
|
||||||
|
const isDark = themeCtx.appearance === "dark";
|
||||||
|
const p = isDark ? DARK : LIGHT;
|
||||||
|
const { servers, proxies } = topology;
|
||||||
|
|
||||||
|
const { nodes, edges, totalRows } = useMemo(() => {
|
||||||
|
if (servers.length === 0) return { nodes: [], edges: [], totalRows: 0 };
|
||||||
|
|
||||||
|
// group proxies by server
|
||||||
|
const groups = new Map<string, typeof proxies>();
|
||||||
|
for (const px of proxies) {
|
||||||
|
if (!groups.has(px.serverId)) groups.set(px.serverId, []);
|
||||||
|
groups.get(px.serverId)!.push(px);
|
||||||
|
}
|
||||||
|
|
||||||
|
// build row assignments
|
||||||
|
const serverRows: Array<{
|
||||||
|
server: (typeof servers)[0];
|
||||||
|
sProxies: typeof proxies;
|
||||||
|
startRow: number;
|
||||||
|
rowCount: number;
|
||||||
|
}> = [];
|
||||||
|
let row = 0;
|
||||||
|
for (const server of servers) {
|
||||||
|
const sProxies = groups.get(server.id) ?? [];
|
||||||
|
const rowCount = Math.max(sProxies.length, 1);
|
||||||
|
serverRows.push({ server, sProxies, startRow: row, rowCount });
|
||||||
|
row += rowCount;
|
||||||
|
}
|
||||||
|
const totalRows = row;
|
||||||
|
|
||||||
|
const nodes: Node[] = [];
|
||||||
|
const edges: Edge[] = [];
|
||||||
|
const dk = isDark ? "1" : "0";
|
||||||
|
|
||||||
|
// Visitor node — vertically centred over all content
|
||||||
|
const visitorY = (totalRows * ROW_H) / 2 - VISITOR_H / 2;
|
||||||
|
nodes.push({
|
||||||
|
id: "visitor",
|
||||||
|
type: "visitor",
|
||||||
|
position: { x: COL.visitor, y: visitorY },
|
||||||
|
data: { isDark: dk },
|
||||||
|
draggable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const { server, sProxies, startRow, rowCount } of serverRows) {
|
||||||
|
const serverOnline = server.bootStatus === "running";
|
||||||
|
const serverCY = (startRow + rowCount / 2) * ROW_H;
|
||||||
|
const serverY = serverCY - SERVER_H / 2;
|
||||||
|
|
||||||
|
// Server node
|
||||||
|
nodes.push({
|
||||||
|
id: server.id,
|
||||||
|
type: "server",
|
||||||
|
position: { x: COL.server, y: serverY },
|
||||||
|
data: {
|
||||||
|
serverName: server.serverName,
|
||||||
|
serverAddr: server.serverAddr,
|
||||||
|
bootStatus: server.bootStatus,
|
||||||
|
isDark: dk,
|
||||||
|
},
|
||||||
|
draggable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Visitor → Server
|
||||||
|
edges.push(mkEdge(`e-vis-${server.id}`, "visitor", server.id, C.eOn, serverOnline));
|
||||||
|
|
||||||
|
if (sProxies.length === 0) continue;
|
||||||
|
|
||||||
|
sProxies.forEach((px, pi) => {
|
||||||
|
const proxyOnline = px.bootStatus === "online";
|
||||||
|
const rowCY = (startRow + pi) * ROW_H + ROW_H / 2;
|
||||||
|
const proxyY = rowCY - PROXY_H / 2;
|
||||||
|
const localY = rowCY - LOCAL_H / 2;
|
||||||
|
const localId = `local-${px.id}`;
|
||||||
|
|
||||||
|
// Proxy node
|
||||||
|
nodes.push({
|
||||||
|
id: px.id,
|
||||||
|
type: "proxy",
|
||||||
|
position: { x: COL.proxy, y: proxyY },
|
||||||
|
data: {
|
||||||
|
name: px.name,
|
||||||
|
proxyType: px.proxyType,
|
||||||
|
remotePort: px.remotePort,
|
||||||
|
status: px.status,
|
||||||
|
bootStatus: px.bootStatus,
|
||||||
|
isDark: dk,
|
||||||
|
},
|
||||||
|
draggable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Local service node
|
||||||
|
nodes.push({
|
||||||
|
id: localId,
|
||||||
|
type: "localService",
|
||||||
|
position: { x: COL.local, y: localY },
|
||||||
|
data: {
|
||||||
|
localIP: px.localIP,
|
||||||
|
localPort: px.localPort,
|
||||||
|
bootStatus: px.bootStatus,
|
||||||
|
isDark: dk,
|
||||||
|
},
|
||||||
|
draggable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Server → Proxy (tunnel)
|
||||||
|
edges.push(
|
||||||
|
mkEdge(`e-${server.id}-${px.id}`, server.id, px.id, C.eOn, serverOnline && proxyOnline)
|
||||||
|
);
|
||||||
|
// Proxy → Local Service
|
||||||
|
edges.push(mkEdge(`e-${px.id}-${localId}`, px.id, localId, C.eOn, proxyOnline));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { nodes, edges, totalRows };
|
||||||
|
}, [servers, proxies, isDark]);
|
||||||
|
|
||||||
|
if (servers.length === 0) {
|
||||||
|
return (
|
||||||
|
<Flex direction="column" align="center" justify="center" gap="3" style={{ height: 240 }}>
|
||||||
|
<Icon icon="lucide:network" color="var(--gray-7)" width="56" height="56" />
|
||||||
|
<Flex direction="column" align="center" gap="1">
|
||||||
|
<Text size="3" weight="medium" color="gray">
|
||||||
|
{t("dashboard.topologyEmpty")}
|
||||||
|
</Text>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("dashboard.topologyEmptyDesc")}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const containerH = Math.max(480, Math.min(900, totalRows * ROW_H + 80));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ height: containerH, borderRadius: 8, overflow: "hidden" }}>
|
||||||
|
<ReactFlow
|
||||||
|
nodes={nodes}
|
||||||
|
edges={edges}
|
||||||
|
nodeTypes={nodeTypes}
|
||||||
|
colorMode={isDark ? "dark" : "light"}
|
||||||
|
fitView
|
||||||
|
fitViewOptions={{ padding: 0.2 }}
|
||||||
|
nodesDraggable={false}
|
||||||
|
nodesConnectable={false}
|
||||||
|
elementsSelectable={false}
|
||||||
|
panOnDrag
|
||||||
|
zoomOnScroll
|
||||||
|
minZoom={0.25}
|
||||||
|
maxZoom={2}
|
||||||
|
proOptions={{ hideAttribution: true }}
|
||||||
|
style={{ background: p.pageBg }}
|
||||||
|
>
|
||||||
|
<Background variant={BackgroundVariant.Dots} gap={22} size={1} color={p.dot} />
|
||||||
|
</ReactFlow>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { DashboardView } from "./DashboardPage.view";
|
||||||
|
import { useDashboard } from "./useDashboard";
|
||||||
|
|
||||||
|
export function DashboardPage() {
|
||||||
|
// @ts-ignore
|
||||||
|
const { stats, activities, trafficHistory, topology, loading } = useDashboard();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DashboardView
|
||||||
|
stats={stats}
|
||||||
|
activities={activities}
|
||||||
|
trafficHistory={trafficHistory}
|
||||||
|
topology={topology}
|
||||||
|
loading={loading}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import { useState, useEffect } from "react";
|
||||||
|
|
||||||
|
export interface DashboardStats {
|
||||||
|
totalProxies: number;
|
||||||
|
runningProxies: number;
|
||||||
|
stoppedProxies: number;
|
||||||
|
totalServers: number;
|
||||||
|
onlineServers: number;
|
||||||
|
offlineServers: number;
|
||||||
|
maxLatency: number;
|
||||||
|
uptime: string;
|
||||||
|
proxyTypeCounts: Record<string, number>;
|
||||||
|
uptimeSeconds: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TopologyServer {
|
||||||
|
id: string;
|
||||||
|
serverName: string;
|
||||||
|
serverAddr: string;
|
||||||
|
bootStatus: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TopologyProxy {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
proxyType: string;
|
||||||
|
localIP: string;
|
||||||
|
localPort: string;
|
||||||
|
remotePort: string;
|
||||||
|
status: string;
|
||||||
|
bootStatus: string;
|
||||||
|
serverId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TopologyData {
|
||||||
|
servers: TopologyServer[];
|
||||||
|
proxies: TopologyProxy[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RecentActivity {
|
||||||
|
id: string;
|
||||||
|
type:
|
||||||
|
| "proxy_started"
|
||||||
|
| "proxy_stopped"
|
||||||
|
| "server_connected"
|
||||||
|
| "server_disconnected"
|
||||||
|
| "config_updated";
|
||||||
|
message: string;
|
||||||
|
timestamp: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TrafficHistoryPoint {
|
||||||
|
time: string;
|
||||||
|
trafficIn: number;
|
||||||
|
trafficOut: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDashboard() {
|
||||||
|
const [stats, setStats] = useState<DashboardStats>({
|
||||||
|
totalProxies: 0,
|
||||||
|
runningProxies: 0,
|
||||||
|
stoppedProxies: 0,
|
||||||
|
totalServers: 0,
|
||||||
|
onlineServers: 0,
|
||||||
|
offlineServers: 0,
|
||||||
|
maxLatency: 0,
|
||||||
|
uptime: "0h 0m",
|
||||||
|
proxyTypeCounts: {},
|
||||||
|
uptimeSeconds: 0,
|
||||||
|
});
|
||||||
|
const [activities] = useState<RecentActivity[]>([]);
|
||||||
|
const [trafficHistory, setTrafficHistory] = useState<TrafficHistoryPoint[]>([]);
|
||||||
|
const [topology, setTopology] = useState<TopologyData>({ servers: [], proxies: [] });
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Format traffic data
|
||||||
|
|
||||||
|
const loadDashboard = async () => {
|
||||||
|
try {
|
||||||
|
// Fetch dashboard stats from API
|
||||||
|
const response = await fetch(`/api/dashboard/stats`, {});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to fetch dashboard stats");
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
setStats({
|
||||||
|
totalProxies: data.proxiesEnabledCount + data.proxiesDisabledCount,
|
||||||
|
runningProxies: data.proxiesOnlineCount ?? 0,
|
||||||
|
stoppedProxies: data.proxiesDisabledCount,
|
||||||
|
totalServers: data.runningCount + data.stoppedCount,
|
||||||
|
onlineServers: data.runningCount,
|
||||||
|
offlineServers: data.stoppedCount,
|
||||||
|
maxLatency: data.maxLatency || 0,
|
||||||
|
// totalTrafficOut: formatBytes(data.totalSent).value,
|
||||||
|
// totalTrafficOutUnit: formatBytes(data.totalSent).unit,
|
||||||
|
uptime: "N/A",
|
||||||
|
proxyTypeCounts: data.proxyTypeCounts || {},
|
||||||
|
uptimeSeconds: data.uptimeSeconds || 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Fetch topology from API
|
||||||
|
try {
|
||||||
|
const topoResponse = await fetch(`/api/dashboard/topology`);
|
||||||
|
if (topoResponse.ok) {
|
||||||
|
const topoData = await topoResponse.json();
|
||||||
|
setTopology(topoData);
|
||||||
|
}
|
||||||
|
} catch (topoErr) {
|
||||||
|
console.error("Failed to load topology:", topoErr);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch traffic history from API
|
||||||
|
try {
|
||||||
|
const historyResponse = await fetch(`/api/dashboard/traffic-history?hours=24`);
|
||||||
|
if (historyResponse.ok) {
|
||||||
|
const historyData = await historyResponse.json();
|
||||||
|
setTrafficHistory(historyData);
|
||||||
|
} else {
|
||||||
|
// If API fails, set empty array
|
||||||
|
setTrafficHistory([]);
|
||||||
|
}
|
||||||
|
} catch (historyErr) {
|
||||||
|
console.error("Failed to load traffic history:", historyErr);
|
||||||
|
// Set empty array on error
|
||||||
|
setTrafficHistory([]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to load dashboard data:", err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loadDashboard();
|
||||||
|
|
||||||
|
// Poll for updates every 30 seconds
|
||||||
|
const interval = setInterval(loadDashboard, 30000);
|
||||||
|
return () => clearInterval(interval);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { stats, activities, trafficHistory, topology };
|
||||||
|
}
|
||||||
@@ -0,0 +1,711 @@
|
|||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Flex,
|
||||||
|
Text,
|
||||||
|
Badge,
|
||||||
|
TextArea,
|
||||||
|
TextField,
|
||||||
|
Separator,
|
||||||
|
Switch,
|
||||||
|
Checkbox,
|
||||||
|
Table,
|
||||||
|
Callout,
|
||||||
|
Tabs,
|
||||||
|
} from "@radix-ui/themes";
|
||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
import { motion } from "framer-motion";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { PageHeader } from "../../components/PageHeader";
|
||||||
|
import type { useImport } from "./useImport";
|
||||||
|
|
||||||
|
type ImportViewProps = ReturnType<typeof useImport> & { visible: boolean };
|
||||||
|
|
||||||
|
// ────────────────────────────────────────────────────────────
|
||||||
|
// Step indicator
|
||||||
|
// ────────────────────────────────────────────────────────────
|
||||||
|
function StepIndicator({ current }: { current: number }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const steps = [
|
||||||
|
{ label: t("import.step1Label"), icon: "lucide:file-text" },
|
||||||
|
{ label: t("import.step2Label"), icon: "lucide:eye" },
|
||||||
|
{ label: t("import.step3Label"), icon: "lucide:check-circle" },
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<Flex align="center" gap="0" mb="6">
|
||||||
|
{steps.map((s, i) => {
|
||||||
|
const idx = i + 1;
|
||||||
|
const done = current > idx;
|
||||||
|
const active = current === idx;
|
||||||
|
return (
|
||||||
|
<Flex key={idx} align="center" style={{ flex: 1 }}>
|
||||||
|
<Flex direction="column" align="center" gap="1" style={{ flex: 1 }}>
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
width: 36,
|
||||||
|
height: 36,
|
||||||
|
borderRadius: "50%",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
background: done
|
||||||
|
? "var(--green-9)"
|
||||||
|
: active
|
||||||
|
? "var(--accent-9)"
|
||||||
|
: "var(--gray-4)",
|
||||||
|
color: done || active ? "white" : "var(--gray-9)",
|
||||||
|
transition: "background 0.3s",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{done ? (
|
||||||
|
<Icon icon="lucide:check" width="16" height="16" />
|
||||||
|
) : (
|
||||||
|
<Icon icon={s.icon} width="16" height="16" />
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
<Text size="1" color={active ? "blue" : "gray"} weight={active ? "bold" : "regular"}>
|
||||||
|
{s.label}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
{i < steps.length - 1 && (
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
height: 2,
|
||||||
|
flex: 1,
|
||||||
|
background: done ? "var(--green-9)" : "var(--gray-4)",
|
||||||
|
marginBottom: 20,
|
||||||
|
transition: "background 0.3s",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ────────────────────────────────────────────────────────────
|
||||||
|
// Step 1: Input TOML
|
||||||
|
// ────────────────────────────────────────────────────────────
|
||||||
|
function Step1({
|
||||||
|
tomlContent,
|
||||||
|
setTomlContent,
|
||||||
|
parseError,
|
||||||
|
parsing,
|
||||||
|
handleFileUpload,
|
||||||
|
handleParse,
|
||||||
|
}: Pick<
|
||||||
|
ImportViewProps,
|
||||||
|
"tomlContent" | "setTomlContent" | "parseError" | "parsing" | "handleFileUpload" | "handleParse"
|
||||||
|
>) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<Flex direction="column" gap="4">
|
||||||
|
<Flex justify="between" align="center">
|
||||||
|
<Text size="3" weight="bold">
|
||||||
|
{t("import.inputTomlTitle")}
|
||||||
|
</Text>
|
||||||
|
<Flex gap="2">
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
id="toml-file-input"
|
||||||
|
accept=".toml"
|
||||||
|
style={{ display: "none" }}
|
||||||
|
onChange={handleFileUpload}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="soft"
|
||||||
|
size="2"
|
||||||
|
onClick={() => document.getElementById("toml-file-input")?.click()}
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:upload" width="14" height="14" />
|
||||||
|
{t("import.uploadFile")}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("import.inputTomlDesc")}
|
||||||
|
</Text>
|
||||||
|
|
||||||
|
<TextArea
|
||||||
|
size="2"
|
||||||
|
placeholder={t("import.tomlPlaceholder")}
|
||||||
|
value={tomlContent}
|
||||||
|
onChange={(e) => setTomlContent(e.target.value)}
|
||||||
|
style={{
|
||||||
|
minHeight: 320,
|
||||||
|
fontFamily: "monospace",
|
||||||
|
fontSize: 13,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{parseError && (
|
||||||
|
<Callout.Root color="red" size="1">
|
||||||
|
<Callout.Icon>
|
||||||
|
<Icon icon="lucide:alert-circle" width="16" height="16" />
|
||||||
|
</Callout.Icon>
|
||||||
|
<Callout.Text>{parseError}</Callout.Text>
|
||||||
|
</Callout.Root>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Flex justify="end">
|
||||||
|
<Button size="2" onClick={handleParse} disabled={parsing || !tomlContent.trim()}>
|
||||||
|
{parsing ? (
|
||||||
|
<Icon icon="lucide:loader-2" width="14" height="14" className="animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Icon icon="lucide:scan-text" width="14" height="14" />
|
||||||
|
)}
|
||||||
|
{parsing ? t("import.parsing") : t("import.parseAndPreview")}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ────────────────────────────────────────────────────────────
|
||||||
|
// Step 2: Preview
|
||||||
|
// ────────────────────────────────────────────────────────────
|
||||||
|
function Step2({
|
||||||
|
preview,
|
||||||
|
serverName,
|
||||||
|
setServerName,
|
||||||
|
importServer,
|
||||||
|
setImportServer,
|
||||||
|
overwriteServer,
|
||||||
|
setOverwriteServer,
|
||||||
|
proxySelections,
|
||||||
|
updateProxySelection,
|
||||||
|
selectAllProxies,
|
||||||
|
selectedProxiesCount,
|
||||||
|
importing,
|
||||||
|
handleExecute,
|
||||||
|
goBack,
|
||||||
|
}: Pick<
|
||||||
|
ImportViewProps,
|
||||||
|
| "preview"
|
||||||
|
| "serverName"
|
||||||
|
| "setServerName"
|
||||||
|
| "importServer"
|
||||||
|
| "setImportServer"
|
||||||
|
| "overwriteServer"
|
||||||
|
| "setOverwriteServer"
|
||||||
|
| "proxySelections"
|
||||||
|
| "updateProxySelection"
|
||||||
|
| "selectAllProxies"
|
||||||
|
| "selectedProxiesCount"
|
||||||
|
| "importing"
|
||||||
|
| "handleExecute"
|
||||||
|
| "goBack"
|
||||||
|
>) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
if (!preview) return null;
|
||||||
|
|
||||||
|
const allSelected = proxySelections.length > 0 && proxySelections.every((s) => s.import);
|
||||||
|
const someSelected = proxySelections.some((s) => s.import);
|
||||||
|
|
||||||
|
const tls = preview.server.transport.tls as Record<string, unknown> | undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Flex direction="column" gap="5">
|
||||||
|
{/* ── Server Section ── */}
|
||||||
|
<Card>
|
||||||
|
<Flex direction="column" gap="3">
|
||||||
|
{/* Header */}
|
||||||
|
<Flex align="center" gap="2" mb="1">
|
||||||
|
<Icon icon="lucide:server" width="18" height="18" color="var(--accent-9)" />
|
||||||
|
<Text size="3" weight="bold">
|
||||||
|
{t("import.serverSection")}
|
||||||
|
</Text>
|
||||||
|
{preview.server.isDuplicate && (
|
||||||
|
<Badge color="orange" variant="soft" size="1">
|
||||||
|
<Icon icon="lucide:alert-triangle" width="12" height="12" />
|
||||||
|
{t("import.duplicate")}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
<Separator size="4" />
|
||||||
|
|
||||||
|
{/* Duplicate warning */}
|
||||||
|
{preview.server.isDuplicate && (
|
||||||
|
<Callout.Root color="orange" size="1">
|
||||||
|
<Callout.Icon>
|
||||||
|
<Icon icon="lucide:alert-triangle" width="14" height="14" />
|
||||||
|
</Callout.Icon>
|
||||||
|
<Callout.Text>{t("import.serverDuplicateWarning")}</Callout.Text>
|
||||||
|
</Callout.Root>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<Tabs.Root defaultValue="general">
|
||||||
|
<Tabs.List>
|
||||||
|
<Tabs.Trigger value="general">{t("server.general")}</Tabs.Trigger>
|
||||||
|
<Tabs.Trigger value="log">{t("server.log")}</Tabs.Trigger>
|
||||||
|
<Tabs.Trigger value="transport">{t("server.transport")}</Tabs.Trigger>
|
||||||
|
<Tabs.Trigger value="metadatas">{t("server.metadatas")}</Tabs.Trigger>
|
||||||
|
</Tabs.List>
|
||||||
|
|
||||||
|
<Box pt="3">
|
||||||
|
{/* General */}
|
||||||
|
<Tabs.Content value="general">
|
||||||
|
<Flex direction="column" gap="3">
|
||||||
|
<Flex gap="3">
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<Text size="1" color="gray" mb="1" as="div">
|
||||||
|
{t("import.serverName")}
|
||||||
|
</Text>
|
||||||
|
<TextField.Root
|
||||||
|
size="2"
|
||||||
|
value={serverName}
|
||||||
|
onChange={(e) => setServerName(e.target.value)}
|
||||||
|
placeholder={t("import.serverNamePlaceholder")}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<Text size="1" color="gray" mb="1" as="div">
|
||||||
|
{t("import.serverAddr")}
|
||||||
|
</Text>
|
||||||
|
<Text size="2" style={{ fontFamily: "monospace", lineHeight: "32px" }}>
|
||||||
|
{preview.server.serverAddr}:{preview.server.serverPort}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
<Flex gap="3">
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<Text size="1" color="gray" mb="1" as="div">
|
||||||
|
{t("import.authMethod")}
|
||||||
|
</Text>
|
||||||
|
<Badge variant="surface" size="1">
|
||||||
|
{(preview.server.auth.method as string) || "none"}
|
||||||
|
</Badge>
|
||||||
|
</Box>
|
||||||
|
{(preview.server.auth.method as string) === "token" && (
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<Text size="1" color="gray" mb="1" as="div">
|
||||||
|
{t("server.token")}
|
||||||
|
</Text>
|
||||||
|
<Text size="2" style={{ fontFamily: "monospace" }}>
|
||||||
|
••••••••
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Tabs.Content>
|
||||||
|
|
||||||
|
{/* Log */}
|
||||||
|
<Tabs.Content value="log">
|
||||||
|
<Flex gap="3">
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<Text size="1" color="gray" mb="1" as="div">
|
||||||
|
{t("server.logLevel")}
|
||||||
|
</Text>
|
||||||
|
<Badge variant="surface" size="1">
|
||||||
|
{(preview.server.log.level as string) || "info"}
|
||||||
|
</Badge>
|
||||||
|
</Box>
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<Text size="1" color="gray" mb="1" as="div">
|
||||||
|
{t("server.maxDays")}
|
||||||
|
</Text>
|
||||||
|
<Text size="2">{String(preview.server.log.maxDays ?? 3)}</Text>
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
</Tabs.Content>
|
||||||
|
|
||||||
|
{/* Transport */}
|
||||||
|
<Tabs.Content value="transport">
|
||||||
|
<Flex direction="column" gap="3">
|
||||||
|
<Flex gap="3">
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<Text size="1" color="gray" mb="1" as="div">
|
||||||
|
{t("server.protocol")}
|
||||||
|
</Text>
|
||||||
|
<Badge variant="surface" size="1">
|
||||||
|
{(preview.server.transport.protocol as string) || "tcp"}
|
||||||
|
</Badge>
|
||||||
|
</Box>
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<Text size="1" color="gray" mb="1" as="div">
|
||||||
|
{t("server.proxyUrl")}
|
||||||
|
</Text>
|
||||||
|
<Text size="2">{(preview.server.transport.proxyURL as string) || "—"}</Text>
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
<Flex gap="3">
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<Text size="1" color="gray" mb="1" as="div">
|
||||||
|
{t("server.tlsEnable")}
|
||||||
|
</Text>
|
||||||
|
<Badge color={tls?.enable ? "green" : "gray"} variant="soft" size="1">
|
||||||
|
{tls?.enable ? t("server.enabled") : t("server.disabled")}
|
||||||
|
</Badge>
|
||||||
|
</Box>
|
||||||
|
{(tls?.enable && tls?.serverName) ? (
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<Text size="1" color="gray" mb="1" as="div">
|
||||||
|
{t("server.serverNameSNI")}
|
||||||
|
</Text>
|
||||||
|
<Text size="2" style={{ fontFamily: "monospace" }}>
|
||||||
|
{tls.serverName as string}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
) : (<div></div>)}
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Tabs.Content>
|
||||||
|
|
||||||
|
{/* Metadatas */}
|
||||||
|
<Tabs.Content value="metadatas">
|
||||||
|
{Object.keys(preview.server.metadatas).length === 0 ? (
|
||||||
|
<Text size="2" color="gray" as="div" style={{ padding: "0.5rem 0" }}>
|
||||||
|
{t("server.noMetadata")}
|
||||||
|
</Text>
|
||||||
|
) : (
|
||||||
|
<Table.Root variant="surface">
|
||||||
|
<Table.Header>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.ColumnHeaderCell>{t("server.metadataKey")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("server.metadataValue")}</Table.ColumnHeaderCell>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Header>
|
||||||
|
<Table.Body>
|
||||||
|
{Object.entries(preview.server.metadatas).map(([k, v]) => (
|
||||||
|
<Table.Row key={k}>
|
||||||
|
<Table.Cell>{k}</Table.Cell>
|
||||||
|
<Table.Cell>{v}</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
))}
|
||||||
|
</Table.Body>
|
||||||
|
</Table.Root>
|
||||||
|
)}
|
||||||
|
</Tabs.Content>
|
||||||
|
</Box>
|
||||||
|
</Tabs.Root>
|
||||||
|
|
||||||
|
{/* Import controls */}
|
||||||
|
<Separator size="4" />
|
||||||
|
<Flex gap="6" align="center" wrap="wrap">
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Switch checked={importServer} onCheckedChange={setImportServer} size="1" />
|
||||||
|
<Text size="2">{t("import.importServer")}</Text>
|
||||||
|
</Flex>
|
||||||
|
{importServer && preview.server.isDuplicate && (
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Switch checked={overwriteServer} onCheckedChange={setOverwriteServer} size="1" />
|
||||||
|
<Text size="2" color="orange">
|
||||||
|
{t("import.overwriteServer")}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* ── Proxy Section ── */}
|
||||||
|
<Card>
|
||||||
|
<Flex direction="column" gap="3">
|
||||||
|
<Flex align="center" justify="between" mb="1">
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Icon icon="lucide:network" width="18" height="18" color="var(--accent-9)" />
|
||||||
|
<Text size="3" weight="bold">
|
||||||
|
{t("import.proxySection")}
|
||||||
|
</Text>
|
||||||
|
<Badge variant="surface" size="1">
|
||||||
|
{preview.proxies.length}
|
||||||
|
</Badge>
|
||||||
|
</Flex>
|
||||||
|
<Flex gap="2">
|
||||||
|
<Button size="1" variant="soft" onClick={() => selectAllProxies(true)}>
|
||||||
|
{t("import.selectAll")}
|
||||||
|
</Button>
|
||||||
|
<Button size="1" variant="soft" color="gray" onClick={() => selectAllProxies(false)}>
|
||||||
|
{t("import.deselectAll")}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
<Separator size="4" />
|
||||||
|
|
||||||
|
{preview.proxies.length === 0 ? (
|
||||||
|
<Text size="2" color="gray" align="center" as="div" style={{ padding: "1rem 0" }}>
|
||||||
|
{t("import.noProxies")}
|
||||||
|
</Text>
|
||||||
|
) : (
|
||||||
|
<Table.Root variant="surface">
|
||||||
|
<Table.Header>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.ColumnHeaderCell width="40px">
|
||||||
|
<Checkbox
|
||||||
|
checked={allSelected ? true : someSelected ? "indeterminate" : false}
|
||||||
|
onCheckedChange={(v) => selectAllProxies(v === true)}
|
||||||
|
/>
|
||||||
|
</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("common.name")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("common.type")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("import.local")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("import.remote")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("common.status")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("import.overwrite")}</Table.ColumnHeaderCell>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Header>
|
||||||
|
<Table.Body>
|
||||||
|
{preview.proxies.map((proxy) => {
|
||||||
|
const sel = proxySelections.find((s) => s.name === proxy.name);
|
||||||
|
const isImport = sel?.import ?? true;
|
||||||
|
const isOverwrite = sel?.overwrite ?? false;
|
||||||
|
return (
|
||||||
|
<Table.Row key={proxy.name} style={{ opacity: isImport ? 1 : 0.45 }}>
|
||||||
|
<Table.Cell>
|
||||||
|
<Checkbox
|
||||||
|
checked={isImport}
|
||||||
|
onCheckedChange={(v) =>
|
||||||
|
updateProxySelection(proxy.name, "import", v === true)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Text size="2" weight="medium">
|
||||||
|
{proxy.name}
|
||||||
|
</Text>
|
||||||
|
{proxy.isDuplicate && (
|
||||||
|
<Badge color="orange" variant="soft" size="1">
|
||||||
|
<Icon icon="lucide:alert-triangle" width="11" height="11" />
|
||||||
|
{t("import.duplicate")}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Badge variant="surface" size="1">
|
||||||
|
{proxy.type}
|
||||||
|
</Badge>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Text size="2" className="font-mono">
|
||||||
|
{proxy.localIP || "127.0.0.1"}:{proxy.localPort || "-"}
|
||||||
|
</Text>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Text size="2" className="font-mono">
|
||||||
|
{proxy.remotePort || proxy.subdomain || proxy.customDomains?.[0] || "-"}
|
||||||
|
</Text>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
{proxy.isDuplicate ? (
|
||||||
|
<Badge color="orange" variant="soft" size="1">
|
||||||
|
{t("import.exists")}
|
||||||
|
</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge color="green" variant="soft" size="1">
|
||||||
|
{t("import.new")}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
{proxy.isDuplicate && isImport ? (
|
||||||
|
<Switch
|
||||||
|
size="1"
|
||||||
|
checked={isOverwrite}
|
||||||
|
onCheckedChange={(v) =>
|
||||||
|
updateProxySelection(proxy.name, "overwrite", v)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Text size="1" color="gray">
|
||||||
|
—
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Table.Body>
|
||||||
|
</Table.Root>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Flex justify="end" gap="2" mt="2">
|
||||||
|
<Text size="1" color="gray" style={{ alignSelf: "center" }}>
|
||||||
|
{t("import.selectedCount", { count: selectedProxiesCount })}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* ── Actions ── */}
|
||||||
|
<Flex justify="between">
|
||||||
|
<Button variant="soft" color="gray" size="2" onClick={goBack}>
|
||||||
|
<Icon icon="lucide:arrow-left" width="14" height="14" />
|
||||||
|
{t("common.back")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="2"
|
||||||
|
onClick={handleExecute}
|
||||||
|
disabled={importing || (!importServer && selectedProxiesCount === 0)}
|
||||||
|
style={{
|
||||||
|
background: "linear-gradient(135deg, var(--accent-9) 0%, var(--accent-10) 100%)",
|
||||||
|
color: "white",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{importing ? (
|
||||||
|
<Icon icon="lucide:loader-2" width="14" height="14" className="animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Icon icon="lucide:download" width="14" height="14" />
|
||||||
|
)}
|
||||||
|
{importing ? t("import.importing") : t("import.confirmImport")}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ────────────────────────────────────────────────────────────
|
||||||
|
// Step 3: Result
|
||||||
|
// ────────────────────────────────────────────────────────────
|
||||||
|
function Step3({ result, handleReset }: Pick<ImportViewProps, "result" | "handleReset">) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
if (!result) return null;
|
||||||
|
return (
|
||||||
|
<Flex direction="column" align="center" gap="5" py="6">
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
width: 72,
|
||||||
|
height: 72,
|
||||||
|
borderRadius: "50%",
|
||||||
|
background: "var(--green-3)",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:check-circle-2" width="40" height="40" color="var(--green-9)" />
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Flex direction="column" align="center" gap="1">
|
||||||
|
<Text size="5" weight="bold">
|
||||||
|
{t("import.successTitle")}
|
||||||
|
</Text>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("import.successDesc")}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
<Card style={{ width: "100%", maxWidth: 400 }}>
|
||||||
|
<Flex direction="column" gap="3">
|
||||||
|
<Flex justify="between" align="center">
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Icon icon="lucide:server" width="16" height="16" color="var(--gray-9)" />
|
||||||
|
<Text size="2">{t("import.serverResult")}</Text>
|
||||||
|
</Flex>
|
||||||
|
<Badge color={result.serverImported ? "green" : "gray"} variant="soft">
|
||||||
|
{result.serverImported ? t("import.imported") : t("import.skipped")}
|
||||||
|
</Badge>
|
||||||
|
</Flex>
|
||||||
|
<Separator size="4" />
|
||||||
|
<Flex justify="between" align="center">
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Icon icon="lucide:network" width="16" height="16" color="var(--gray-9)" />
|
||||||
|
<Text size="2">{t("import.proxiesImported")}</Text>
|
||||||
|
</Flex>
|
||||||
|
<Badge color="green" variant="soft">
|
||||||
|
{result.proxiesImported}
|
||||||
|
</Badge>
|
||||||
|
</Flex>
|
||||||
|
<Flex justify="between" align="center">
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Icon icon="lucide:skip-forward" width="16" height="16" color="var(--gray-9)" />
|
||||||
|
<Text size="2">{t("import.proxiesSkipped")}</Text>
|
||||||
|
</Flex>
|
||||||
|
<Badge color="gray" variant="soft">
|
||||||
|
{result.proxiesSkipped}
|
||||||
|
</Badge>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Flex gap="3">
|
||||||
|
<Button variant="soft" size="2" onClick={handleReset}>
|
||||||
|
<Icon icon="lucide:plus" width="14" height="14" />
|
||||||
|
{t("import.importAnother")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="2"
|
||||||
|
onClick={() => (window.location.href = "/servers")}
|
||||||
|
style={{
|
||||||
|
background: "linear-gradient(135deg, var(--accent-9) 0%, var(--accent-10) 100%)",
|
||||||
|
color: "white",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:server" width="14" height="14" />
|
||||||
|
{t("import.viewServers")}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ────────────────────────────────────────────────────────────
|
||||||
|
// Main View
|
||||||
|
// ────────────────────────────────────────────────────────────
|
||||||
|
export function ImportPageView(props: ImportViewProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { step, visible } = props;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Flex direction="column" gap="5" className="flex flex-1 flex-col">
|
||||||
|
<PageHeader
|
||||||
|
title={t("import.title")}
|
||||||
|
description={t("import.description")}
|
||||||
|
visible={visible}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={visible ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.1, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<Card>
|
||||||
|
<Box p="2">
|
||||||
|
<StepIndicator current={step} />
|
||||||
|
|
||||||
|
{step === 1 && (
|
||||||
|
<Step1
|
||||||
|
tomlContent={props.tomlContent}
|
||||||
|
setTomlContent={props.setTomlContent}
|
||||||
|
parseError={props.parseError}
|
||||||
|
parsing={props.parsing}
|
||||||
|
handleFileUpload={props.handleFileUpload}
|
||||||
|
handleParse={props.handleParse}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{step === 2 && (
|
||||||
|
<Step2
|
||||||
|
preview={props.preview}
|
||||||
|
serverName={props.serverName}
|
||||||
|
setServerName={props.setServerName}
|
||||||
|
importServer={props.importServer}
|
||||||
|
setImportServer={props.setImportServer}
|
||||||
|
overwriteServer={props.overwriteServer}
|
||||||
|
setOverwriteServer={props.setOverwriteServer}
|
||||||
|
proxySelections={props.proxySelections}
|
||||||
|
updateProxySelection={props.updateProxySelection}
|
||||||
|
selectAllProxies={props.selectAllProxies}
|
||||||
|
selectedProxiesCount={props.selectedProxiesCount}
|
||||||
|
importing={props.importing}
|
||||||
|
handleExecute={props.handleExecute}
|
||||||
|
goBack={props.goBack}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{step === 3 && <Step3 result={props.result} handleReset={props.handleReset} />}
|
||||||
|
</Box>
|
||||||
|
</Card>
|
||||||
|
</motion.div>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { useImport } from "./useImport";
|
||||||
|
import { ImportPageView } from "./ImportPage.view";
|
||||||
|
|
||||||
|
export function ImportPage() {
|
||||||
|
const importState = useImport();
|
||||||
|
const [visible, setVisible] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(() => setVisible(true), 100);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return <ImportPageView {...importState} visible={visible} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
import { useState, useCallback } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
export interface ImportServerInfo {
|
||||||
|
name: string;
|
||||||
|
serverAddr: string;
|
||||||
|
serverPort: number;
|
||||||
|
auth: Record<string, unknown>;
|
||||||
|
log: Record<string, unknown>;
|
||||||
|
transport: Record<string, unknown>;
|
||||||
|
metadatas: Record<string, string>;
|
||||||
|
isDuplicate: boolean;
|
||||||
|
existingId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImportProxyInfo {
|
||||||
|
name: string;
|
||||||
|
type: string;
|
||||||
|
localIP: string;
|
||||||
|
localPort: number;
|
||||||
|
remotePort: number;
|
||||||
|
subdomain: string;
|
||||||
|
customDomains: string[];
|
||||||
|
transport: Record<string, unknown>;
|
||||||
|
isDuplicate: boolean;
|
||||||
|
existingId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImportPreview {
|
||||||
|
server: ImportServerInfo;
|
||||||
|
proxies: ImportProxyInfo[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProxySelection {
|
||||||
|
name: string;
|
||||||
|
import: boolean;
|
||||||
|
overwrite: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImportResult {
|
||||||
|
serverImported: boolean;
|
||||||
|
proxiesImported: number;
|
||||||
|
proxiesSkipped: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ImportStep = 1 | 2 | 3;
|
||||||
|
|
||||||
|
export function useImport() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
const [step, setStep] = useState<ImportStep>(1);
|
||||||
|
const [tomlContent, setTomlContent] = useState("");
|
||||||
|
const [preview, setPreview] = useState<ImportPreview | null>(null);
|
||||||
|
const [serverName, setServerName] = useState("");
|
||||||
|
const [importServer, setImportServer] = useState(true);
|
||||||
|
const [overwriteServer, setOverwriteServer] = useState(false);
|
||||||
|
const [proxySelections, setProxySelections] = useState<ProxySelection[]>([]);
|
||||||
|
const [parsing, setParsing] = useState(false);
|
||||||
|
const [importing, setImporting] = useState(false);
|
||||||
|
const [parseError, setParseError] = useState<string | null>(null);
|
||||||
|
const [result, setResult] = useState<ImportResult | null>(null);
|
||||||
|
|
||||||
|
const handleFileUpload = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = (event) => {
|
||||||
|
const content = event.target?.result as string;
|
||||||
|
if (typeof content === "string") {
|
||||||
|
setTomlContent(content);
|
||||||
|
setParseError(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.readAsText(file);
|
||||||
|
e.target.value = "";
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleParse = useCallback(async () => {
|
||||||
|
if (!tomlContent.trim()) {
|
||||||
|
setParseError(t("import.errorEmptyContent"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setParsing(true);
|
||||||
|
setParseError(null);
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/import/preview", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ tomlContent }),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) {
|
||||||
|
setParseError(data.error || t("import.errorParseFailed"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setPreview(data as ImportPreview);
|
||||||
|
// Initialize server name from preview
|
||||||
|
setServerName(data.server.name);
|
||||||
|
// Initialize proxy selections – import all by default
|
||||||
|
const selections: ProxySelection[] = (data.proxies as ImportProxyInfo[]).map((p) => ({
|
||||||
|
name: p.name,
|
||||||
|
import: true,
|
||||||
|
overwrite: false,
|
||||||
|
}));
|
||||||
|
setProxySelections(selections);
|
||||||
|
setStep(2);
|
||||||
|
} catch {
|
||||||
|
setParseError(t("import.errorParseFailed"));
|
||||||
|
} finally {
|
||||||
|
setParsing(false);
|
||||||
|
}
|
||||||
|
}, [tomlContent, t]);
|
||||||
|
|
||||||
|
const updateProxySelection = useCallback(
|
||||||
|
(name: string, field: "import" | "overwrite", value: boolean) => {
|
||||||
|
setProxySelections((prev) =>
|
||||||
|
prev.map((s) => (s.name === name ? { ...s, [field]: value } : s))
|
||||||
|
);
|
||||||
|
},
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
const selectAllProxies = useCallback((selected: boolean) => {
|
||||||
|
setProxySelections((prev) => prev.map((s) => ({ ...s, import: selected })));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleExecute = useCallback(async () => {
|
||||||
|
if (!preview) return;
|
||||||
|
setImporting(true);
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/import/execute", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
tomlContent,
|
||||||
|
serverName,
|
||||||
|
importServer,
|
||||||
|
overwriteServer,
|
||||||
|
proxies: proxySelections,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) {
|
||||||
|
toast.error(data.error || t("import.errorImportFailed"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setResult(data.result as ImportResult);
|
||||||
|
setStep(3);
|
||||||
|
toast.success(t("import.importSuccess"));
|
||||||
|
} catch {
|
||||||
|
toast.error(t("import.errorImportFailed"));
|
||||||
|
} finally {
|
||||||
|
setImporting(false);
|
||||||
|
}
|
||||||
|
}, [preview, tomlContent, serverName, importServer, overwriteServer, proxySelections, t]);
|
||||||
|
|
||||||
|
const handleReset = useCallback(() => {
|
||||||
|
setStep(1);
|
||||||
|
setTomlContent("");
|
||||||
|
setPreview(null);
|
||||||
|
setServerName("");
|
||||||
|
setImportServer(true);
|
||||||
|
setOverwriteServer(false);
|
||||||
|
setProxySelections([]);
|
||||||
|
setParseError(null);
|
||||||
|
setResult(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const goBack = useCallback(() => {
|
||||||
|
setStep((prev) => (prev > 1 ? ((prev - 1) as ImportStep) : prev));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Derived: count selected proxies
|
||||||
|
const selectedProxiesCount = proxySelections.filter((s) => s.import).length;
|
||||||
|
|
||||||
|
return {
|
||||||
|
step,
|
||||||
|
tomlContent,
|
||||||
|
setTomlContent,
|
||||||
|
preview,
|
||||||
|
serverName,
|
||||||
|
setServerName,
|
||||||
|
importServer,
|
||||||
|
setImportServer,
|
||||||
|
overwriteServer,
|
||||||
|
setOverwriteServer,
|
||||||
|
proxySelections,
|
||||||
|
parsing,
|
||||||
|
importing,
|
||||||
|
parseError,
|
||||||
|
result,
|
||||||
|
selectedProxiesCount,
|
||||||
|
handleFileUpload,
|
||||||
|
handleParse,
|
||||||
|
updateProxySelection,
|
||||||
|
selectAllProxies,
|
||||||
|
handleExecute,
|
||||||
|
handleReset,
|
||||||
|
goBack,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { Button, Callout, Flex, Heading, Text, TextField } from "@radix-ui/themes";
|
||||||
|
import { AnimatePresence, motion } from "framer-motion";
|
||||||
|
import { PageTransition } from "../../components/PageTransition";
|
||||||
|
import { ThemeToggle } from "../../components/ThemeToggle";
|
||||||
|
import { LanguageToggle } from "../../components/LanguageToggle";
|
||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
import logo from "../../assets/logo.png";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
interface LoginViewProps {
|
||||||
|
email: string;
|
||||||
|
setEmail: (value: string) => void;
|
||||||
|
password: string;
|
||||||
|
setPassword: (value: string) => void;
|
||||||
|
loading: boolean;
|
||||||
|
error: string;
|
||||||
|
handleSubmit: (e: React.FormEvent) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LoginView({
|
||||||
|
email,
|
||||||
|
setEmail,
|
||||||
|
password,
|
||||||
|
setPassword,
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
handleSubmit,
|
||||||
|
}: LoginViewProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [showPassword, setShowPassword] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PageTransition>
|
||||||
|
<Flex
|
||||||
|
align="center"
|
||||||
|
justify="center"
|
||||||
|
className="relative min-h-screen"
|
||||||
|
style={{ backgroundColor: "var(--gray-2)" }}
|
||||||
|
>
|
||||||
|
<Flex gap="2" className="absolute top-4 right-4">
|
||||||
|
<ThemeToggle />
|
||||||
|
<LanguageToggle />
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
{/* <Card size="4" className="w-full max-w-md shadow-lg"> */}
|
||||||
|
<form onSubmit={handleSubmit} style={{ width: "320px" }}>
|
||||||
|
<Flex direction="column" gap="3">
|
||||||
|
{/* Logo & Title */}
|
||||||
|
<Flex direction="column" align="center" gap="2">
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: -20 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ duration: 0.5, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<Flex align="center" gap="3">
|
||||||
|
<motion.img
|
||||||
|
initial={{ scale: 0, rotate: -180 }}
|
||||||
|
animate={{ scale: 1, rotate: 0 }}
|
||||||
|
transition={{
|
||||||
|
type: "spring",
|
||||||
|
stiffness: 260,
|
||||||
|
damping: 20,
|
||||||
|
delay: 0.1,
|
||||||
|
}}
|
||||||
|
whileHover={{ scale: 1.1, rotate: 10 }}
|
||||||
|
whileTap={{ scale: 0.95 }}
|
||||||
|
src={logo}
|
||||||
|
alt="Frpc Hub Logo"
|
||||||
|
className="h-16 w-16 cursor-pointer rounded-2xl object-contain"
|
||||||
|
/>
|
||||||
|
<Heading size="6">Frpc Hub</Heading>
|
||||||
|
</Flex>
|
||||||
|
</motion.div>
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0 }}
|
||||||
|
animate={{ opacity: 1 }}
|
||||||
|
transition={{ delay: 0.4, duration: 0.5 }}
|
||||||
|
>
|
||||||
|
<Text color="gray" size="2" align="center">
|
||||||
|
{t("auth.signInToAccount")}
|
||||||
|
</Text>
|
||||||
|
</motion.div>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
{/* Error Message */}
|
||||||
|
<AnimatePresence mode="wait">
|
||||||
|
{error && (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, x: 0 }}
|
||||||
|
animate={{ opacity: 1, x: [0, -5, 5, -5, 5, 0] }}
|
||||||
|
exit={{ opacity: 0, scale: 0.9 }}
|
||||||
|
transition={{ duration: 0.4, ease: "easeInOut" }}
|
||||||
|
>
|
||||||
|
<Callout.Root color="red">
|
||||||
|
<Callout.Icon>
|
||||||
|
<Icon icon="lucide:alert-circle"></Icon>
|
||||||
|
</Callout.Icon>
|
||||||
|
<Callout.Text>{error}</Callout.Text>
|
||||||
|
</Callout.Root>
|
||||||
|
</motion.div>
|
||||||
|
)}
|
||||||
|
</AnimatePresence>
|
||||||
|
|
||||||
|
{/* Email Field */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ delay: 0.5, duration: 0.4 }}
|
||||||
|
>
|
||||||
|
<Flex direction="column" gap="1">
|
||||||
|
<Text as="label" size="3" weight="medium" className="">
|
||||||
|
{t("auth.email")}
|
||||||
|
</Text>
|
||||||
|
<TextField.Root
|
||||||
|
size="3"
|
||||||
|
placeholder={t("auth.enterEmail")}
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
>
|
||||||
|
<TextField.Slot>
|
||||||
|
<Icon icon="lucide:mail"></Icon>
|
||||||
|
</TextField.Slot>
|
||||||
|
</TextField.Root>
|
||||||
|
</Flex>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
{/* Password Field */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ delay: 0.6, duration: 0.4 }}
|
||||||
|
>
|
||||||
|
<Flex direction="column" gap="1">
|
||||||
|
<Flex justify="between" align="center">
|
||||||
|
<Text as="label" size="3" weight="medium" className="">
|
||||||
|
{t("auth.password")}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
<TextField.Root
|
||||||
|
size="3"
|
||||||
|
placeholder={t("auth.enterPassword")}
|
||||||
|
type={showPassword ? "text" : "password"}
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
>
|
||||||
|
<TextField.Slot>
|
||||||
|
<Icon icon="lucide:key-round" />
|
||||||
|
</TextField.Slot>
|
||||||
|
<TextField.Slot>
|
||||||
|
<Icon
|
||||||
|
icon={showPassword ? "lucide:eye-off" : "lucide:eye"}
|
||||||
|
style={{ cursor: "pointer" }}
|
||||||
|
onClick={() => setShowPassword(!showPassword)}
|
||||||
|
/>
|
||||||
|
</TextField.Slot>
|
||||||
|
</TextField.Root>
|
||||||
|
|
||||||
|
<Flex justify={"end"} className="mt-1">
|
||||||
|
<Text size="1" color="indigo" className="cursor-pointer hover:underline">
|
||||||
|
{t("auth.forgotPassword")}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
{/* Submit Button */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ delay: 0.7, duration: 0.4 }}
|
||||||
|
whileHover={{ scale: 1.02 }}
|
||||||
|
whileTap={{ scale: 0.98 }}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
<Button size="3" type="submit" disabled={loading} className="!w-full cursor-pointer">
|
||||||
|
{loading ? (
|
||||||
|
<Icon icon="lucide:loader" className="animate-spin"></Icon>
|
||||||
|
) : (
|
||||||
|
<Icon icon="lucide:arrow-right"></Icon>
|
||||||
|
)}
|
||||||
|
{loading ? t("auth.signingIn") : t("auth.signIn")}
|
||||||
|
</Button>
|
||||||
|
</motion.div>
|
||||||
|
</Flex>
|
||||||
|
</form>
|
||||||
|
{/* </Card> */}
|
||||||
|
</Flex>
|
||||||
|
</PageTransition>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { useLogin } from "./useLogin";
|
||||||
|
import { LoginView } from "./LoginPage.view";
|
||||||
|
|
||||||
|
export function LoginPage() {
|
||||||
|
const loginState = useLogin();
|
||||||
|
|
||||||
|
return <LoginView {...loginState} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default LoginPage;
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useNavigate, useLocation } from "react-router-dom";
|
||||||
|
import pb from "../../lib/pocketbase";
|
||||||
|
|
||||||
|
export function useLogin() {
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const location = useLocation();
|
||||||
|
|
||||||
|
// Get the page to visit before login, default to dashboard
|
||||||
|
const from = (location.state as { from?: { pathname: string } })?.from?.pathname || "/dashboard";
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setLoading(true);
|
||||||
|
setError("");
|
||||||
|
|
||||||
|
try {
|
||||||
|
await pb.collection("fh_users").authWithPassword(email, password);
|
||||||
|
// Redirect back to previous page after successful login
|
||||||
|
navigate(from, { replace: true });
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error("Login error:", err);
|
||||||
|
setError(err?.message || "Invalid email or password");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
email,
|
||||||
|
setEmail,
|
||||||
|
password,
|
||||||
|
setPassword,
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
handleSubmit,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import { Box, Button, Flex, Heading, Text } from "@radix-ui/themes";
|
||||||
|
import { Link } from "react-router-dom";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
export function NotFoundPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<Flex
|
||||||
|
direction="column"
|
||||||
|
align="center"
|
||||||
|
justify="center"
|
||||||
|
className="min-h-screen"
|
||||||
|
style={{ backgroundColor: "var(--gray-2)" }}
|
||||||
|
>
|
||||||
|
<Flex direction="column" align="center" gap="6" className="px-4 text-center">
|
||||||
|
{/* 404 Illustration */}
|
||||||
|
<Box className="relative">
|
||||||
|
<Text
|
||||||
|
size="9"
|
||||||
|
weight="bold"
|
||||||
|
className="select-none"
|
||||||
|
style={{
|
||||||
|
fontSize: "12rem",
|
||||||
|
lineHeight: 1,
|
||||||
|
color: "var(--gray-4)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
404
|
||||||
|
</Text>
|
||||||
|
<Box className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
|
||||||
|
<Box
|
||||||
|
className="flex h-24 w-24 animate-bounce items-center justify-center rounded-full"
|
||||||
|
style={{ backgroundColor: "var(--accent-a3)" }}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="48"
|
||||||
|
height="48"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.5"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
style={{ color: "var(--accent-11)" }}
|
||||||
|
>
|
||||||
|
<circle cx="12" cy="12" r="10" />
|
||||||
|
<path d="M16 16s-1.5-2-4-2-4 2-4 2" />
|
||||||
|
<line x1="9" y1="9" x2="9.01" y2="9" />
|
||||||
|
<line x1="15" y1="9" x2="15.01" y2="9" />
|
||||||
|
</svg>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* Text Content */}
|
||||||
|
<Flex direction="column" gap="2" align="center">
|
||||||
|
<Heading size="6">{t("error.notFound")}</Heading>
|
||||||
|
<Text color="gray" size="3" style={{ maxWidth: "400px" }}>
|
||||||
|
{t("error.somethingWrong")}
|
||||||
|
</Text>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
{/* Actions */}
|
||||||
|
<Flex gap="3" mt="2">
|
||||||
|
<Link to="/dashboard">
|
||||||
|
<Button size="3">
|
||||||
|
<svg
|
||||||
|
width="16"
|
||||||
|
height="16"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
|
||||||
|
<polyline points="9 22 9 12 15 12 15 22" />
|
||||||
|
</svg>
|
||||||
|
{t("error.goHome")}
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<Button size="3" variant="soft" color="gray" onClick={() => window.history.back()}>
|
||||||
|
<svg
|
||||||
|
width="16"
|
||||||
|
height="16"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<line x1="19" y1="12" x2="5" y2="12" />
|
||||||
|
<polyline points="12 19 5 12 12 5" />
|
||||||
|
</svg>
|
||||||
|
{t("common.cancel")}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,635 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
Button,
|
||||||
|
Flex,
|
||||||
|
Text,
|
||||||
|
TextField,
|
||||||
|
Box,
|
||||||
|
Separator,
|
||||||
|
IconButton,
|
||||||
|
Switch,
|
||||||
|
TextArea,
|
||||||
|
Tabs,
|
||||||
|
Select,
|
||||||
|
AlertDialog,
|
||||||
|
Callout,
|
||||||
|
} from "@radix-ui/themes";
|
||||||
|
import { REGEX } from "../../lib/regex";
|
||||||
|
import pb from "../../lib/pocketbase";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { FormItem } from "../../components/FormItem";
|
||||||
|
import { motion, AnimatePresence } from "framer-motion";
|
||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
interface AddProxyDialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
onSubmit?: (data: ProxyFormData) => Promise<void>;
|
||||||
|
initialData?: ProxyFormData | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProxyFormData {
|
||||||
|
serverId: string;
|
||||||
|
name: string;
|
||||||
|
type: "tcp" | "udp" | "http" | "https" | "stcp" | "xtcp";
|
||||||
|
localIp: string;
|
||||||
|
localPort: string;
|
||||||
|
remotePort: string;
|
||||||
|
customDomains?: string;
|
||||||
|
subdomain?: string;
|
||||||
|
encryption: boolean;
|
||||||
|
compression: boolean;
|
||||||
|
description?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const proxyTypes = [
|
||||||
|
{
|
||||||
|
value: "tcp",
|
||||||
|
label: "TCP",
|
||||||
|
description: "TCP Port Forwarding",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "udp",
|
||||||
|
label: "UDP",
|
||||||
|
description: "UDP Port Forwarding",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "http",
|
||||||
|
label: "HTTP",
|
||||||
|
description: "HTTP Reverse Proxy",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "https",
|
||||||
|
label: "HTTPS",
|
||||||
|
description: "HTTPS Reverse Proxy",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "stcp",
|
||||||
|
label: "STCP",
|
||||||
|
description: "Secure TCP Tunnel",
|
||||||
|
disabled: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "xtcp",
|
||||||
|
label: "XTCP",
|
||||||
|
description: "P2P TCP Tunnel",
|
||||||
|
disabled: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export function AddProxyDialog({ open, onOpenChange, onSubmit, initialData }: AddProxyDialogProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
// @ts-ignore
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [showDiscardAlert, setShowDiscardAlert] = useState(false);
|
||||||
|
|
||||||
|
const [formData, setFormData] = useState<ProxyFormData>({
|
||||||
|
serverId: "",
|
||||||
|
name: "",
|
||||||
|
type: "tcp",
|
||||||
|
localIp: "127.0.0.1",
|
||||||
|
localPort: "",
|
||||||
|
remotePort: "",
|
||||||
|
customDomains: "",
|
||||||
|
subdomain: "",
|
||||||
|
encryption: false,
|
||||||
|
compression: false,
|
||||||
|
description: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open && initialData) {
|
||||||
|
setFormData(initialData);
|
||||||
|
} else if (open && !initialData) {
|
||||||
|
setFormData({
|
||||||
|
serverId: servers.length > 0 ? servers[0].id : "",
|
||||||
|
name: "",
|
||||||
|
type: "tcp",
|
||||||
|
localIp: "127.0.0.1",
|
||||||
|
localPort: "",
|
||||||
|
remotePort: "",
|
||||||
|
customDomains: "",
|
||||||
|
subdomain: "",
|
||||||
|
encryption: false,
|
||||||
|
compression: false,
|
||||||
|
description: "",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [open, initialData]);
|
||||||
|
|
||||||
|
const [servers, setServers] = useState<{ id: string; serverName: string }[]>([]);
|
||||||
|
const [loadingServers, setLoadingServers] = useState(false);
|
||||||
|
// @ts-ignore
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) {
|
||||||
|
const fetchServers = async () => {
|
||||||
|
try {
|
||||||
|
setLoadingServers(true);
|
||||||
|
const records = await pb.collection("fh_servers").getFullList({
|
||||||
|
sort: "-created",
|
||||||
|
fields: "id,serverName",
|
||||||
|
});
|
||||||
|
setServers(records.map((r) => ({ id: r.id, serverName: r.serverName })));
|
||||||
|
if (records.length > 0 && !formData.serverId) {
|
||||||
|
setFormData((prev) => ({ ...prev, serverId: records[0].id }));
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to fetch servers:", err);
|
||||||
|
toast.error("Failed to fetch servers");
|
||||||
|
} finally {
|
||||||
|
setLoadingServers(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchServers();
|
||||||
|
}
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
const [errors, setErrors] = useState<Partial<Record<keyof ProxyFormData, string>>>({});
|
||||||
|
|
||||||
|
const [activeTab, setActiveTab] = useState("basic");
|
||||||
|
|
||||||
|
const handleChange = (field: keyof ProxyFormData, value: string | boolean) => {
|
||||||
|
setFormData((prev) => ({ ...prev, [field]: value }));
|
||||||
|
|
||||||
|
// Validate on change
|
||||||
|
if (typeof value === "string") {
|
||||||
|
validateField(field, value);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const validateField = (field: keyof ProxyFormData, value: string) => {
|
||||||
|
let error = "";
|
||||||
|
if (value) {
|
||||||
|
switch (field) {
|
||||||
|
case "name":
|
||||||
|
if (!REGEX.PROXY_NAME.test(value)) {
|
||||||
|
error = t("proxy.errorInvalidName");
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "localIp":
|
||||||
|
if (!REGEX.IP_OR_HOSTNAME.test(value)) {
|
||||||
|
error = t("proxy.errorInvalidIP");
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "localPort":
|
||||||
|
case "remotePort":
|
||||||
|
if (!REGEX.PORT.test(value)) {
|
||||||
|
error = t("proxy.errorInvalidPort");
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setErrors((prev) => ({ ...prev, [field]: error }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
try {
|
||||||
|
setSubmitting(true);
|
||||||
|
await onSubmit?.(formData);
|
||||||
|
onOpenChange(false);
|
||||||
|
// Reset form
|
||||||
|
setFormData({
|
||||||
|
serverId: servers.length > 0 ? servers[0].id : "",
|
||||||
|
name: "",
|
||||||
|
type: "tcp",
|
||||||
|
localIp: "127.0.0.1",
|
||||||
|
localPort: "",
|
||||||
|
remotePort: "",
|
||||||
|
customDomains: "",
|
||||||
|
subdomain: "",
|
||||||
|
encryption: false,
|
||||||
|
compression: false,
|
||||||
|
description: "",
|
||||||
|
});
|
||||||
|
setErrors({});
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Submit error:", err);
|
||||||
|
toast.error(err instanceof Error ? err.message : "Failed to add proxy");
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleOpenChange = (newOpen: boolean) => {
|
||||||
|
if (!newOpen) {
|
||||||
|
// Check if form has unsaved changes
|
||||||
|
const initialFormData = initialData || {
|
||||||
|
serverId: servers.length > 0 ? servers[0].id : "",
|
||||||
|
name: "",
|
||||||
|
type: "tcp",
|
||||||
|
localIp: "127.0.0.1",
|
||||||
|
localPort: "",
|
||||||
|
remotePort: "",
|
||||||
|
customDomains: "",
|
||||||
|
subdomain: "",
|
||||||
|
encryption: false,
|
||||||
|
compression: false,
|
||||||
|
description: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
const isDirty = JSON.stringify(formData) !== JSON.stringify(initialFormData);
|
||||||
|
if (isDirty) {
|
||||||
|
setShowDiscardAlert(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onOpenChange(newOpen);
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmDiscard = () => {
|
||||||
|
setShowDiscardAlert(false);
|
||||||
|
onOpenChange(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const isHttpType = formData.type === "http" || formData.type === "https";
|
||||||
|
|
||||||
|
const isEditing = !!initialData;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Dialog.Root open={open} onOpenChange={handleOpenChange}>
|
||||||
|
<Dialog.Content
|
||||||
|
style={{
|
||||||
|
maxWidth: 520,
|
||||||
|
background: "linear-gradient(145deg, var(--gray-1) 0%, var(--gray-2) 100%)",
|
||||||
|
border: "1px solid var(--gray-4)",
|
||||||
|
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.25)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Header */}
|
||||||
|
<Flex justify="between" align="center" mb="4">
|
||||||
|
<Flex align="center" gap="3">
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
background: "linear-gradient(135deg, var(--accent-9) 0%, var(--accent-10) 100%)",
|
||||||
|
padding: "10px",
|
||||||
|
borderRadius: "12px",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:network" width="20" height="20" color="white" />
|
||||||
|
</Box>
|
||||||
|
<Box>
|
||||||
|
<Dialog.Title size="5" weight="bold" mb="0">
|
||||||
|
{initialData ? t("proxy.editProxy") : t("proxy.addProxy")}
|
||||||
|
</Dialog.Title>
|
||||||
|
<Text size="1" color="gray">
|
||||||
|
{initialData ? t("proxy.updateProxyDesc") : t("proxy.addProxyDesc")}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
<Dialog.Close>
|
||||||
|
<IconButton variant="ghost" color="gray" radius="full">
|
||||||
|
<Icon icon="lucide:x" width="16" height="16" />
|
||||||
|
</IconButton>
|
||||||
|
</Dialog.Close>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
<Separator size="4" mb="4" />
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<Tabs.Root value={activeTab} onValueChange={setActiveTab}>
|
||||||
|
<Tabs.List size="2" mb="4">
|
||||||
|
<Tabs.Trigger value="basic">{t("proxy.basicConfig")}</Tabs.Trigger>
|
||||||
|
<Tabs.Trigger value="advanced">{t("proxy.advancedOptions")}</Tabs.Trigger>
|
||||||
|
</Tabs.List>
|
||||||
|
<AnimatePresence mode="wait">
|
||||||
|
{/* Basic Tab */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: -10 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
exit={{ opacity: 0, y: -10 }}
|
||||||
|
transition={{ duration: 0.2 }}
|
||||||
|
>
|
||||||
|
<Tabs.Content value="basic">
|
||||||
|
<Flex direction="column" gap="4">
|
||||||
|
{/* Server Selection */}
|
||||||
|
<FormItem label={t("proxy.selectServer")} required>
|
||||||
|
<Select.Root
|
||||||
|
value={formData.serverId}
|
||||||
|
onValueChange={(value) => handleChange("serverId", value)}
|
||||||
|
disabled={loadingServers || servers.length === 0}
|
||||||
|
>
|
||||||
|
<Select.Trigger
|
||||||
|
placeholder={
|
||||||
|
loadingServers
|
||||||
|
? t("common.loading")
|
||||||
|
: servers.length === 0
|
||||||
|
? t("proxy.noServersAvailable")
|
||||||
|
: t("proxy.selectServerPlaceholder")
|
||||||
|
}
|
||||||
|
style={{ width: "100%" }}
|
||||||
|
/>
|
||||||
|
<Select.Content>
|
||||||
|
{servers.map((server) => (
|
||||||
|
<Select.Item key={server.id} value={server.id}>
|
||||||
|
{server.serverName}
|
||||||
|
</Select.Item>
|
||||||
|
))}
|
||||||
|
</Select.Content>
|
||||||
|
</Select.Root>
|
||||||
|
{servers.length === 0 && !loadingServers && (
|
||||||
|
<Callout.Root size="1" color="orange" mt="2">
|
||||||
|
<Callout.Icon>
|
||||||
|
<Icon icon="lucide:triangle-alert" width="14" height="14" />
|
||||||
|
</Callout.Icon>
|
||||||
|
<Callout.Text>
|
||||||
|
<Flex align="center" justify="between" gap="2">
|
||||||
|
<Text size="1">{t("proxy.noServersAvailable")}</Text>
|
||||||
|
<Button
|
||||||
|
size="1"
|
||||||
|
variant="ghost"
|
||||||
|
color="orange"
|
||||||
|
style={{ cursor: "pointer", flexShrink: 0 }}
|
||||||
|
onClick={() => {
|
||||||
|
onOpenChange(false);
|
||||||
|
navigate("/servers");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("proxy.goAddServer")}
|
||||||
|
<Icon icon="lucide:arrow-right" width="12" height="12" />
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Callout.Text>
|
||||||
|
</Callout.Root>
|
||||||
|
)}
|
||||||
|
</FormItem>
|
||||||
|
|
||||||
|
{/* Proxy Name */}
|
||||||
|
<FormItem label={t("proxy.proxyName")} required error={errors.name}>
|
||||||
|
<TextField.Root
|
||||||
|
size="2"
|
||||||
|
placeholder={t("proxy.proxyNamePlaceholder")}
|
||||||
|
value={formData.name}
|
||||||
|
onChange={(e) => handleChange("name", e.target.value)}
|
||||||
|
color={errors.name ? "red" : undefined}
|
||||||
|
/>
|
||||||
|
</FormItem>
|
||||||
|
|
||||||
|
{/* Proxy Type Selection */}
|
||||||
|
<FormItem label={t("proxy.proxyType")} required>
|
||||||
|
<Flex gap="2" wrap="wrap">
|
||||||
|
{proxyTypes.map((type) => (
|
||||||
|
<Box
|
||||||
|
key={type.value}
|
||||||
|
onClick={() =>
|
||||||
|
!type.disabled &&
|
||||||
|
handleChange("type", type.value as ProxyFormData["type"])
|
||||||
|
}
|
||||||
|
className={`box-border min-w-[64px] rounded-lg border-2 px-3 py-2 text-center transition-all duration-200 ${
|
||||||
|
type.disabled
|
||||||
|
? "cursor-not-allowed opacity-50"
|
||||||
|
: "cursor-pointer opacity-100"
|
||||||
|
} ${
|
||||||
|
formData.type === type.value
|
||||||
|
? "border-[var(--accent-9)] bg-[var(--accent-3)]"
|
||||||
|
: "border-[var(--gray-5)] bg-[var(--gray-2)]"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Text
|
||||||
|
size="1"
|
||||||
|
weight={formData.type === type.value ? "bold" : "regular"}
|
||||||
|
color={
|
||||||
|
type.disabled
|
||||||
|
? "gray"
|
||||||
|
: formData.type === type.value
|
||||||
|
? "blue"
|
||||||
|
: "gray"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{type.label}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
|
</Flex>
|
||||||
|
</FormItem>
|
||||||
|
|
||||||
|
{/* Local Settings */}
|
||||||
|
<Flex gap="3">
|
||||||
|
<Box style={{ flex: 2 }}>
|
||||||
|
<FormItem label={t("proxy.localAddress")} required error={errors.localIp}>
|
||||||
|
<TextField.Root
|
||||||
|
size="2"
|
||||||
|
placeholder={t("proxy.localAddressPlaceholder")}
|
||||||
|
value={formData.localIp}
|
||||||
|
onChange={(e) => handleChange("localIp", e.target.value)}
|
||||||
|
color={errors.localIp ? "red" : undefined}
|
||||||
|
/>
|
||||||
|
</FormItem>
|
||||||
|
</Box>
|
||||||
|
<Box style={{ flex: 1 }}>
|
||||||
|
<FormItem label={t("proxy.localPort")} required error={errors.localPort}>
|
||||||
|
<TextField.Root
|
||||||
|
size="2"
|
||||||
|
placeholder={t("proxy.localPortPlaceholder")}
|
||||||
|
type="number"
|
||||||
|
value={formData.localPort}
|
||||||
|
onChange={(e) => handleChange("localPort", e.target.value)}
|
||||||
|
color={errors.localPort ? "red" : undefined}
|
||||||
|
/>
|
||||||
|
</FormItem>
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
{/* Remote Port or Custom Domains */}
|
||||||
|
{isHttpType ? (
|
||||||
|
<>
|
||||||
|
<FormItem label={t("proxy.customDomainsLabel")}>
|
||||||
|
<TextField.Root
|
||||||
|
size="2"
|
||||||
|
placeholder={t("proxy.customDomainsPlaceholder")}
|
||||||
|
value={formData.customDomains}
|
||||||
|
onChange={(e) => handleChange("customDomains", e.target.value)}
|
||||||
|
/>
|
||||||
|
<Text size="1" color="gray" mt="1">
|
||||||
|
{t("proxy.customDomainsDesc")}
|
||||||
|
</Text>
|
||||||
|
</FormItem>
|
||||||
|
<FormItem label={t("proxy.subdomain")}>
|
||||||
|
<TextField.Root
|
||||||
|
size="2"
|
||||||
|
placeholder={t("proxy.subdomainPlaceholder")}
|
||||||
|
value={formData.subdomain}
|
||||||
|
onChange={(e) => handleChange("subdomain", e.target.value)}
|
||||||
|
/>
|
||||||
|
<Text size="1" color="gray" mt="1">
|
||||||
|
{t("proxy.subdomainDesc")}
|
||||||
|
</Text>
|
||||||
|
</FormItem>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<FormItem
|
||||||
|
label={t("proxy.remotePortLabel")}
|
||||||
|
required
|
||||||
|
error={errors.remotePort}
|
||||||
|
>
|
||||||
|
<TextField.Root
|
||||||
|
size="2"
|
||||||
|
placeholder={t("proxy.remotePortPlaceholder")}
|
||||||
|
type="number"
|
||||||
|
value={formData.remotePort}
|
||||||
|
onChange={(e) => handleChange("remotePort", e.target.value)}
|
||||||
|
color={errors.remotePort ? "red" : undefined}
|
||||||
|
/>
|
||||||
|
<Text size="1" color="gray" mt="1">
|
||||||
|
{t("proxy.remotePortDesc")}
|
||||||
|
</Text>
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
{/* Description */}
|
||||||
|
<FormItem label={t("proxy.descriptionLabel")}>
|
||||||
|
<TextArea
|
||||||
|
size="2"
|
||||||
|
placeholder={t("proxy.descriptionPlaceholder")}
|
||||||
|
value={formData.description}
|
||||||
|
onChange={(e) => handleChange("description", e.target.value)}
|
||||||
|
style={{ minHeight: "80px" }}
|
||||||
|
/>
|
||||||
|
</FormItem>
|
||||||
|
</Flex>
|
||||||
|
</Tabs.Content>
|
||||||
|
</motion.div>
|
||||||
|
{/* Advanced Tab */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: -10 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
exit={{ opacity: 0, y: -10 }}
|
||||||
|
transition={{ duration: 0.2 }}
|
||||||
|
>
|
||||||
|
<Tabs.Content value="advanced">
|
||||||
|
<Flex direction="column" gap="4">
|
||||||
|
{/* Encryption & Compression */}
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
background: "var(--gray-2)",
|
||||||
|
padding: "16px",
|
||||||
|
borderRadius: "12px",
|
||||||
|
border: "1px solid var(--gray-4)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Flex justify="between" align="center" mb="3">
|
||||||
|
<Box>
|
||||||
|
<Text size="2" weight="medium">
|
||||||
|
{t("proxy.transportEncryption")}
|
||||||
|
</Text>
|
||||||
|
<Text size="1" color="gray">
|
||||||
|
{t("proxy.transportEncryptionDesc")}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
<Switch
|
||||||
|
size="2"
|
||||||
|
checked={formData.encryption}
|
||||||
|
onCheckedChange={(checked) => handleChange("encryption", checked)}
|
||||||
|
/>
|
||||||
|
</Flex>
|
||||||
|
<Separator size="4" />
|
||||||
|
<Flex justify="between" align="center" mt="3">
|
||||||
|
<Box>
|
||||||
|
<Text size="2" weight="medium">
|
||||||
|
{t("proxy.dataCompression")}
|
||||||
|
</Text>
|
||||||
|
<Text size="1" color="gray">
|
||||||
|
{t("proxy.dataCompressionDesc")}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
<Switch
|
||||||
|
size="2"
|
||||||
|
checked={formData.compression}
|
||||||
|
onCheckedChange={(checked) => handleChange("compression", checked)}
|
||||||
|
/>
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
</Flex>
|
||||||
|
</Tabs.Content>
|
||||||
|
</motion.div>
|
||||||
|
</AnimatePresence>
|
||||||
|
</Tabs.Root>
|
||||||
|
|
||||||
|
<Separator size="4" my="4" />
|
||||||
|
|
||||||
|
{/* Footer Actions */}
|
||||||
|
<Flex justify="end" gap="3">
|
||||||
|
<Dialog.Close>
|
||||||
|
<Button variant="soft" color="gray" size="2">
|
||||||
|
<Icon icon="lucide:x" width="16" height="16" />
|
||||||
|
{t("common.cancel")}
|
||||||
|
</Button>
|
||||||
|
</Dialog.Close>
|
||||||
|
<Button
|
||||||
|
size="2"
|
||||||
|
disabled={
|
||||||
|
!formData.serverId ||
|
||||||
|
!formData.name ||
|
||||||
|
!formData.type ||
|
||||||
|
!formData.localIp ||
|
||||||
|
!formData.localPort ||
|
||||||
|
!formData.remotePort ||
|
||||||
|
!!errors.serverId ||
|
||||||
|
!!errors.name ||
|
||||||
|
!!errors.type ||
|
||||||
|
!!errors.localIp ||
|
||||||
|
!!errors.localPort ||
|
||||||
|
!!errors.remotePort ||
|
||||||
|
loading
|
||||||
|
}
|
||||||
|
onClick={handleSubmit}
|
||||||
|
style={{
|
||||||
|
background: "linear-gradient(135deg, var(--accent-9) 0%, var(--accent-10) 100%)",
|
||||||
|
color: "white",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{loading ? (
|
||||||
|
isEditing ? (
|
||||||
|
<Icon icon="lucide:pencil" width="16" height="16" color="white" />
|
||||||
|
) : (
|
||||||
|
<Icon icon="lucide:plus" width="16" height="16" color="white" />
|
||||||
|
)
|
||||||
|
) : isEditing ? (
|
||||||
|
<Icon icon="lucide:pencil" width="16" height="16" color="white" />
|
||||||
|
) : (
|
||||||
|
<Icon icon="lucide:plus" width="16" height="16" color="white" />
|
||||||
|
)}
|
||||||
|
{loading
|
||||||
|
? isEditing
|
||||||
|
? t("proxy.saving")
|
||||||
|
: t("proxy.adding")
|
||||||
|
: isEditing
|
||||||
|
? t("proxy.saveChanges")
|
||||||
|
: t("proxy.addProxy")}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Dialog.Content>
|
||||||
|
</Dialog.Root>
|
||||||
|
|
||||||
|
<AlertDialog.Root open={showDiscardAlert} onOpenChange={setShowDiscardAlert}>
|
||||||
|
<AlertDialog.Content maxWidth="450px">
|
||||||
|
<AlertDialog.Title>{t("common.discardChanges")}</AlertDialog.Title>
|
||||||
|
<AlertDialog.Description size="2">
|
||||||
|
{t("common.discardChangesDesc")}
|
||||||
|
</AlertDialog.Description>
|
||||||
|
<Flex gap="3" mt="4" justify="end">
|
||||||
|
<AlertDialog.Cancel>
|
||||||
|
<Button variant="soft" color="gray">
|
||||||
|
{t("common.keepEditing")}
|
||||||
|
</Button>
|
||||||
|
</AlertDialog.Cancel>
|
||||||
|
<AlertDialog.Action>
|
||||||
|
<Button variant="solid" color="red" onClick={confirmDiscard}>
|
||||||
|
{t("common.discard")}
|
||||||
|
</Button>
|
||||||
|
</AlertDialog.Action>
|
||||||
|
</Flex>
|
||||||
|
</AlertDialog.Content>
|
||||||
|
</AlertDialog.Root>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
import { Badge, Button, Card, Flex, Table, Text, TextField, AlertDialog } from "@radix-ui/themes";
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { Link, useNavigate } from "react-router-dom";
|
||||||
|
import { motion } from "framer-motion";
|
||||||
|
import { EmptyState } from "../../components/EmptyState";
|
||||||
|
import { AddProxyDialog, type ProxyFormData } from "./AddProxyDialog";
|
||||||
|
import { type Proxy } from "./useProxies";
|
||||||
|
import { PageHeader } from "../../components/PageHeader";
|
||||||
|
import { StatCard } from "../../components/StatCard";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
interface ProxiesViewProps {
|
||||||
|
proxies: Proxy[];
|
||||||
|
loading: boolean;
|
||||||
|
refreshing: boolean;
|
||||||
|
stats: {
|
||||||
|
total: number;
|
||||||
|
online: number;
|
||||||
|
offline: number;
|
||||||
|
};
|
||||||
|
isDialogOpen: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
editingProxy: Proxy | null;
|
||||||
|
onCreateProxy: (data: any) => Promise<void>;
|
||||||
|
onUpdateProxy: (id: string, data: any) => Promise<void>;
|
||||||
|
onDeleteProxy: (id: string) => Promise<void>;
|
||||||
|
onEditClick: (proxy: Proxy | null) => void;
|
||||||
|
refreshProxies: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ProxiesView({
|
||||||
|
proxies,
|
||||||
|
loading: _loading,
|
||||||
|
refreshing,
|
||||||
|
stats,
|
||||||
|
isDialogOpen,
|
||||||
|
onOpenChange,
|
||||||
|
editingProxy,
|
||||||
|
onCreateProxy,
|
||||||
|
onUpdateProxy,
|
||||||
|
onDeleteProxy,
|
||||||
|
onEditClick,
|
||||||
|
refreshProxies,
|
||||||
|
}: ProxiesViewProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(() => setMounted(true), 100);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleAction = async (data: ProxyFormData) => {
|
||||||
|
const payload = {
|
||||||
|
serverId: data.serverId,
|
||||||
|
proxyType: data.type,
|
||||||
|
name: data.name,
|
||||||
|
localIP: data.localIp,
|
||||||
|
localPort: data.localPort,
|
||||||
|
remotePort: data.remotePort,
|
||||||
|
customDomains: data.customDomains ? data.customDomains.split(",").map((d) => d.trim()) : [],
|
||||||
|
transport: {
|
||||||
|
use_encryption: data.encryption,
|
||||||
|
use_compression: data.compression,
|
||||||
|
},
|
||||||
|
description: data.description,
|
||||||
|
status: "enabled",
|
||||||
|
};
|
||||||
|
|
||||||
|
if (editingProxy) {
|
||||||
|
await onUpdateProxy(editingProxy.id, payload);
|
||||||
|
} else {
|
||||||
|
await onCreateProxy(payload);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const initialFormData: ProxyFormData | null = editingProxy
|
||||||
|
? {
|
||||||
|
serverId: (editingProxy as any).serverId,
|
||||||
|
name: editingProxy.name || "",
|
||||||
|
type: (editingProxy as any).proxyType as any,
|
||||||
|
localIp: (editingProxy as any).localIP || "127.0.0.1",
|
||||||
|
localPort: String(editingProxy.localPort || ""),
|
||||||
|
remotePort: String(editingProxy.remotePort || ""),
|
||||||
|
customDomains: (editingProxy as any).customDomains?.join(", ") || "",
|
||||||
|
encryption: (editingProxy as any).transport?.use_encryption || false,
|
||||||
|
compression: (editingProxy as any).transport?.use_compression || false,
|
||||||
|
description: (editingProxy as any).description || "",
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<AddProxyDialog
|
||||||
|
open={isDialogOpen}
|
||||||
|
onOpenChange={onOpenChange}
|
||||||
|
onSubmit={handleAction}
|
||||||
|
initialData={initialFormData}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Flex direction="column" gap="5" className="flex flex-1 flex-col">
|
||||||
|
{/* Header */}
|
||||||
|
<PageHeader
|
||||||
|
title={t("proxy.title")}
|
||||||
|
description={t("proxy.manageProxies")}
|
||||||
|
visible={mounted}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Stats Cards */}
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.1, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<StatCard
|
||||||
|
title={t("proxy.totalProxies")}
|
||||||
|
value={stats.total}
|
||||||
|
color="gray"
|
||||||
|
icon={<Icon icon="lucide:network" width="32" height="32" color="var(--gray-11)" />}
|
||||||
|
/>
|
||||||
|
</motion.div>
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.2, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<StatCard
|
||||||
|
title={t("proxy.online")}
|
||||||
|
value={<span className="text-[#30A46C]">{stats.online}</span>}
|
||||||
|
color="green"
|
||||||
|
icon={
|
||||||
|
<Icon icon="lucide:check-circle" width="32" height="32" color="var(--green-11)" />
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</motion.div>
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.3, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<StatCard
|
||||||
|
title={t("proxy.offline")}
|
||||||
|
value={<span className="text-[#E5484D]">{stats.offline}</span>}
|
||||||
|
color="red"
|
||||||
|
icon={<Icon icon="lucide:x-circle" width="32" height="32" color="var(--red-11)" />}
|
||||||
|
/>
|
||||||
|
</motion.div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Proxies Table */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.4, ease: "easeOut" }}
|
||||||
|
className="flex flex-1 flex-col overflow-hidden"
|
||||||
|
>
|
||||||
|
<Card className="flex flex-1 flex-col">
|
||||||
|
<Flex direction="column" gap="3" mb="4" p="2">
|
||||||
|
<Flex justify="between" align="center" wrap="wrap" gap="2">
|
||||||
|
<Text size="3" weight="bold">
|
||||||
|
{t("proxy.allProxies")}
|
||||||
|
</Text>
|
||||||
|
<Flex gap="2" wrap="wrap" align="center">
|
||||||
|
<TextField.Root
|
||||||
|
size="2"
|
||||||
|
placeholder={t("proxy.searchProxies")}
|
||||||
|
className="min-w-32 flex-1"
|
||||||
|
>
|
||||||
|
<TextField.Slot>
|
||||||
|
<Icon icon="lucide:search" width="16" height="16" />
|
||||||
|
</TextField.Slot>
|
||||||
|
</TextField.Root>
|
||||||
|
<Button variant="soft" onClick={refreshProxies} disabled={refreshing}>
|
||||||
|
<Icon
|
||||||
|
icon="lucide:refresh-cw"
|
||||||
|
width="14"
|
||||||
|
height="14"
|
||||||
|
className={refreshing ? "animate-spin" : ""}
|
||||||
|
/>
|
||||||
|
{t("proxy.refresh")}
|
||||||
|
</Button>
|
||||||
|
<Button variant="soft" color="gray" onClick={() => navigate("/import")}>
|
||||||
|
<Icon icon="lucide:file-input" width="16" height="16" />
|
||||||
|
{t("nav.import")}
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => onEditClick(null)}>
|
||||||
|
<Icon icon="lucide:plus" width="16" height="16" />
|
||||||
|
{t("proxy.addProxy")}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
{proxies.length === 0 ? (
|
||||||
|
<EmptyState
|
||||||
|
title={t("proxy.noProxies")}
|
||||||
|
description={t("proxy.addFirstProxy")}
|
||||||
|
actionText={t("proxy.createYourFirstProxy")}
|
||||||
|
onAction={() => onEditClick(null)}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<Table.Root>
|
||||||
|
<Table.Header>
|
||||||
|
<Table.Row>
|
||||||
|
<Table.ColumnHeaderCell>{t("common.name")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("common.type")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("proxy.server")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("proxy.localIP")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("proxy.localPort")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("proxy.remotePortOrDomain")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("proxy.bootStatus")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("common.status")}</Table.ColumnHeaderCell>
|
||||||
|
<Table.ColumnHeaderCell>{t("common.actions")}</Table.ColumnHeaderCell>
|
||||||
|
</Table.Row>
|
||||||
|
</Table.Header>
|
||||||
|
<Table.Body>
|
||||||
|
{proxies.map((proxy) => (
|
||||||
|
<Table.Row key={proxy.id}>
|
||||||
|
<Table.Cell>
|
||||||
|
<Text weight="medium">{proxy.name}</Text>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Badge variant="surface">{proxy.proxyType.toUpperCase()}</Badge>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
{(proxy as any).expand?.serverId ? (
|
||||||
|
<Link
|
||||||
|
to={`/servers/${(proxy as any).serverId}`}
|
||||||
|
style={{ textDecoration: "none" }}
|
||||||
|
>
|
||||||
|
<Text size="2" color="blue" style={{ cursor: "pointer" }}>
|
||||||
|
{(proxy as any).expand.serverId.serverName}
|
||||||
|
</Text>
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
-
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{(proxy as any).localIP || "127.0.0.1"}
|
||||||
|
</Text>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>{proxy.localPort}</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
{proxy.proxyType === "http" || proxy.proxyType === "https"
|
||||||
|
? (proxy as any).customDomains?.length > 0
|
||||||
|
? (proxy as any).customDomains.join(", ")
|
||||||
|
: (proxy as any).subdomain || "-"
|
||||||
|
: proxy.remotePort || "-"}
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Badge
|
||||||
|
radius="full"
|
||||||
|
color={proxy.bootStatus === "online" ? "green" : "red"}
|
||||||
|
className={`animate-status-appear ${
|
||||||
|
proxy.bootStatus === "online"
|
||||||
|
? "animate-status-pulse"
|
||||||
|
: "animate-status-fade"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={`status-dot ${
|
||||||
|
proxy.bootStatus === "online" ? "status-dot-green" : "status-dot-red"
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
{proxy.bootStatus === "online" ? t("proxy.online") : t("proxy.offline")}
|
||||||
|
</Badge>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Badge color={proxy.status === "enabled" ? "green" : "red"}>
|
||||||
|
{proxy.status === "enabled" ? t("proxy.enabled") : t("proxy.disabled")}
|
||||||
|
</Badge>
|
||||||
|
</Table.Cell>
|
||||||
|
<Table.Cell>
|
||||||
|
<Flex gap="2">
|
||||||
|
<Button size="1" variant="soft" onClick={() => onEditClick(proxy)}>
|
||||||
|
<Icon icon="lucide:pencil" width="14" height="14" />
|
||||||
|
{t("common.edit")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="1"
|
||||||
|
variant="soft"
|
||||||
|
color="red"
|
||||||
|
onClick={() => setDeleteId(proxy.id)}
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:trash-2" width="14" height="14" />
|
||||||
|
{t("common.delete")}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Table.Cell>
|
||||||
|
</Table.Row>
|
||||||
|
))}
|
||||||
|
</Table.Body>
|
||||||
|
</Table.Root>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
</motion.div>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
<AlertDialog.Root open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
|
||||||
|
<AlertDialog.Content maxWidth="450px">
|
||||||
|
<AlertDialog.Title>{t("proxy.confirmDeletion")}</AlertDialog.Title>
|
||||||
|
<AlertDialog.Description size="2">
|
||||||
|
{t("proxy.deleteConfirmMessage")}
|
||||||
|
</AlertDialog.Description>
|
||||||
|
<Flex gap="3" mt="4" justify="end">
|
||||||
|
<AlertDialog.Cancel>
|
||||||
|
<Button variant="soft" color="gray">
|
||||||
|
<Icon icon="lucide:x" width="16" height="16" />
|
||||||
|
{t("common.cancel")}
|
||||||
|
</Button>
|
||||||
|
</AlertDialog.Cancel>
|
||||||
|
<AlertDialog.Action>
|
||||||
|
<Button
|
||||||
|
variant="solid"
|
||||||
|
color="red"
|
||||||
|
onClick={() => {
|
||||||
|
if (deleteId) {
|
||||||
|
onDeleteProxy(deleteId);
|
||||||
|
setDeleteId(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icon icon="lucide:trash-2" width="16" height="16" />
|
||||||
|
{t("common.delete")}
|
||||||
|
</Button>
|
||||||
|
</AlertDialog.Action>
|
||||||
|
</Flex>
|
||||||
|
</AlertDialog.Content>
|
||||||
|
</AlertDialog.Root>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { useProxies } from "./useProxies";
|
||||||
|
import { ProxiesView } from "./ProxiesPage.view";
|
||||||
|
|
||||||
|
export function ProxiesPage() {
|
||||||
|
const {
|
||||||
|
proxies,
|
||||||
|
loading,
|
||||||
|
refreshing,
|
||||||
|
stats,
|
||||||
|
createProxy,
|
||||||
|
updateProxy,
|
||||||
|
deleteProxy,
|
||||||
|
isDialogOpen,
|
||||||
|
openDialog,
|
||||||
|
closeDialog,
|
||||||
|
editingProxy,
|
||||||
|
refreshProxies,
|
||||||
|
} = useProxies();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ProxiesView
|
||||||
|
proxies={proxies as any}
|
||||||
|
loading={loading}
|
||||||
|
refreshing={refreshing}
|
||||||
|
stats={stats}
|
||||||
|
isDialogOpen={isDialogOpen}
|
||||||
|
onOpenChange={(open) => (open ? openDialog() : closeDialog())}
|
||||||
|
editingProxy={editingProxy as any}
|
||||||
|
onCreateProxy={createProxy}
|
||||||
|
onUpdateProxy={updateProxy}
|
||||||
|
onDeleteProxy={deleteProxy}
|
||||||
|
onEditClick={(proxy) => openDialog(proxy || undefined)}
|
||||||
|
refreshProxies={refreshProxies}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ProxiesPage;
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
import { useState, useEffect, useCallback } from "react";
|
||||||
|
import pb from "../../lib/pocketbase";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
export interface Proxy {
|
||||||
|
id: string;
|
||||||
|
serverId: string;
|
||||||
|
proxyType: "tcp" | "udp" | "http" | "https";
|
||||||
|
name?: string;
|
||||||
|
localIP?: string;
|
||||||
|
localPort?: string;
|
||||||
|
remotePort?: string;
|
||||||
|
subdomain?: string;
|
||||||
|
customDomains?: string[];
|
||||||
|
transport?: Record<string, any>;
|
||||||
|
description?: string;
|
||||||
|
status: "enabled" | "disabled";
|
||||||
|
bootStatus: "online" | "offline";
|
||||||
|
created: string;
|
||||||
|
updated: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateProxyForm {
|
||||||
|
serverId: string;
|
||||||
|
proxyType: "tcp" | "udp" | "http" | "https";
|
||||||
|
name?: string;
|
||||||
|
localIP?: string;
|
||||||
|
localPort?: string;
|
||||||
|
remotePort?: string;
|
||||||
|
subdomain?: string;
|
||||||
|
customDomains?: string[];
|
||||||
|
transport?: Record<string, any>;
|
||||||
|
description?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useProxies() {
|
||||||
|
const [proxies, setProxies] = useState<Proxy[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [refreshing, setRefreshing] = useState(false);
|
||||||
|
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||||
|
const [formData, setFormData] = useState<CreateProxyForm>({
|
||||||
|
serverId: "",
|
||||||
|
proxyType: "tcp",
|
||||||
|
localIP: "127.0.0.1",
|
||||||
|
localPort: "",
|
||||||
|
remotePort: "",
|
||||||
|
subdomain: "",
|
||||||
|
customDomains: [],
|
||||||
|
transport: {},
|
||||||
|
});
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [totalPages, setTotalPages] = useState(1);
|
||||||
|
const PER_PAGE = 10;
|
||||||
|
|
||||||
|
const [editingProxy, setEditingProxy] = useState<Proxy | null>(null);
|
||||||
|
|
||||||
|
const fetchProxies = useCallback(
|
||||||
|
async (isRefresh = false) => {
|
||||||
|
try {
|
||||||
|
// Only show loading spinner on initial load, not on refresh
|
||||||
|
if (!isRefresh && proxies.length === 0) {
|
||||||
|
setLoading(true);
|
||||||
|
} else if (isRefresh) {
|
||||||
|
setRefreshing(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await pb.collection("fh_proxies").getList<Proxy>(page, PER_PAGE, {
|
||||||
|
sort: "-created",
|
||||||
|
expand: "serverId",
|
||||||
|
});
|
||||||
|
setProxies(result.items);
|
||||||
|
setTotalPages(result.totalPages);
|
||||||
|
} catch (err) {
|
||||||
|
if ((err as any)?.isAbort) return;
|
||||||
|
toast.error(err instanceof Error ? err.message : "Failed to fetch proxies");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
setRefreshing(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[page, proxies.length]
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchProxies();
|
||||||
|
}, [fetchProxies]);
|
||||||
|
|
||||||
|
// Auto-refresh proxy status every 5 seconds
|
||||||
|
useEffect(() => {
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
fetchProxies(true); // Pass true to indicate this is a refresh
|
||||||
|
}, 5000);
|
||||||
|
return () => clearInterval(interval);
|
||||||
|
}, [fetchProxies]);
|
||||||
|
|
||||||
|
const openDialog = (proxy?: Proxy) => {
|
||||||
|
if (proxy) {
|
||||||
|
setEditingProxy(proxy);
|
||||||
|
} else {
|
||||||
|
setEditingProxy(null);
|
||||||
|
setFormData({
|
||||||
|
serverId: "",
|
||||||
|
proxyType: "tcp",
|
||||||
|
localIP: "127.0.0.1",
|
||||||
|
localPort: "",
|
||||||
|
remotePort: "",
|
||||||
|
subdomain: "",
|
||||||
|
customDomains: [],
|
||||||
|
transport: {},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setIsDialogOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeDialog = () => {
|
||||||
|
setIsDialogOpen(false);
|
||||||
|
setEditingProxy(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateFormField = (field: keyof CreateProxyForm, value: any) => {
|
||||||
|
setFormData((prev) => ({ ...prev, [field]: value }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const createProxy = async (data?: CreateProxyForm) => {
|
||||||
|
try {
|
||||||
|
setSubmitting(true);
|
||||||
|
const body = data || formData;
|
||||||
|
|
||||||
|
await pb.collection("fh_proxies").create(body);
|
||||||
|
|
||||||
|
await fetchProxies();
|
||||||
|
closeDialog();
|
||||||
|
toast.success("Proxy created successfully");
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : "Failed to create proxy");
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateProxy = async (id: string, data: CreateProxyForm) => {
|
||||||
|
try {
|
||||||
|
setSubmitting(true);
|
||||||
|
|
||||||
|
await pb.collection("fh_proxies").update(id, data);
|
||||||
|
|
||||||
|
await fetchProxies();
|
||||||
|
closeDialog();
|
||||||
|
toast.success("Proxy updated successfully");
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : "Failed to update proxy");
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteProxy = async (id: string) => {
|
||||||
|
try {
|
||||||
|
await pb.collection("fh_proxies").delete(id);
|
||||||
|
await fetchProxies();
|
||||||
|
toast.success("Proxy deleted successfully");
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(err instanceof Error ? err.message : "Failed to delete proxy");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const stats = {
|
||||||
|
total: proxies.length,
|
||||||
|
online: proxies.filter((p) => p.bootStatus === "online").length,
|
||||||
|
offline: proxies.filter((p) => p.bootStatus === "offline").length,
|
||||||
|
// tcp: proxies.filter((p) => p.proxyType === "tcp").length,
|
||||||
|
// udp: proxies.filter((p) => p.proxyType === "udp").length,
|
||||||
|
// http: proxies.filter((p) => p.proxyType === "http").length,
|
||||||
|
// https: proxies.filter((p) => p.proxyType === "https").length,
|
||||||
|
};
|
||||||
|
|
||||||
|
const isEmpty = !loading && proxies.length === 0;
|
||||||
|
|
||||||
|
return {
|
||||||
|
proxies,
|
||||||
|
loading,
|
||||||
|
refreshing,
|
||||||
|
isEmpty,
|
||||||
|
isDialogOpen,
|
||||||
|
formData,
|
||||||
|
submitting,
|
||||||
|
editingProxy,
|
||||||
|
openDialog,
|
||||||
|
closeDialog,
|
||||||
|
updateFormField,
|
||||||
|
createProxy,
|
||||||
|
updateProxy,
|
||||||
|
deleteProxy,
|
||||||
|
page,
|
||||||
|
setPage,
|
||||||
|
totalPages,
|
||||||
|
stats,
|
||||||
|
refreshProxies: () => fetchProxies(true),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,337 @@
|
|||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { useParams, useNavigate } from "react-router-dom";
|
||||||
|
import { Card, Flex, Text, Badge, Grid, Button, Heading, Box } from "@radix-ui/themes";
|
||||||
|
import { Icon } from "@iconify/react";
|
||||||
|
import { PageHeader } from "../../components/PageHeader";
|
||||||
|
import { Loading } from "../../components/Loading";
|
||||||
|
import pb from "../../lib/pocketbase";
|
||||||
|
import type { Server } from "../Servers/useServers";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { motion } from "framer-motion";
|
||||||
|
import { ServerLatency } from "../../components/ServerLatency";
|
||||||
|
import { ServerLocation } from "../../components/ServerLocation";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
export function ServerDetailPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { id } = useParams<{ id: string }>();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const [server, setServer] = useState<Server | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [logs, setLogs] = useState<string[]>([]);
|
||||||
|
const logContainerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Wait for PageTransition to complete before triggering animations
|
||||||
|
const timer = setTimeout(() => setMounted(true), 100);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!id) return;
|
||||||
|
|
||||||
|
const fetchServer = async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const record = await pb.collection("fh_servers").getOne<Server>(id);
|
||||||
|
setServer(record);
|
||||||
|
} catch (err: any) {
|
||||||
|
if (err.isAbort) return;
|
||||||
|
console.error("Failed to load server details:", err);
|
||||||
|
setError(err.message || t("server.failedToLoad"));
|
||||||
|
toast.error(t("server.failedToLoad"));
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchServer();
|
||||||
|
}, [id, navigate]);
|
||||||
|
|
||||||
|
// SSE log streaming
|
||||||
|
useEffect(() => {
|
||||||
|
if (!id) return;
|
||||||
|
|
||||||
|
const es = new EventSource(`/api/frpc/logs/stream?id=${id}`);
|
||||||
|
|
||||||
|
es.onmessage = (event) => {
|
||||||
|
setLogs((prev) => [...prev, event.data]);
|
||||||
|
};
|
||||||
|
|
||||||
|
es.onerror = () => {
|
||||||
|
es.close();
|
||||||
|
};
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
es.close();
|
||||||
|
};
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
|
// Auto-scroll to bottom when new logs arrive
|
||||||
|
useEffect(() => {
|
||||||
|
if (logContainerRef.current) {
|
||||||
|
logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
|
||||||
|
}
|
||||||
|
}, [logs]);
|
||||||
|
|
||||||
|
const getStatusColor = (status: string) => {
|
||||||
|
switch (status) {
|
||||||
|
case "running":
|
||||||
|
return "green";
|
||||||
|
case "stopped":
|
||||||
|
return "red";
|
||||||
|
default:
|
||||||
|
return "gray";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<Flex justify="center" align="center" style={{ height: "100%" }}>
|
||||||
|
<Loading />
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<Flex direction="column" justify="center" align="center" style={{ height: "100%" }} gap="4">
|
||||||
|
<Icon icon="lucide:alert-circle" width="48" height="48" color="var(--red-9)" />
|
||||||
|
<Heading size="4" color="red">
|
||||||
|
{t("server.failedToLoad")}
|
||||||
|
</Heading>
|
||||||
|
<Text color="gray">{error}</Text>
|
||||||
|
<Button variant="soft" onClick={() => navigate("/servers")}>
|
||||||
|
{t("server.backToServers")}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!server) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Flex direction="column" gap="5" className="flex-1">
|
||||||
|
{/* Header */}
|
||||||
|
<PageHeader
|
||||||
|
title={server.serverName}
|
||||||
|
description={t("server.detailsAndLogs")}
|
||||||
|
visible={mounted}
|
||||||
|
/>
|
||||||
|
{/*<motion.div*/}
|
||||||
|
{/* initial={{ opacity: 0, y: -20 }}*/}
|
||||||
|
{/* animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: -20 }}*/}
|
||||||
|
{/* transition={{ duration: 0.5, ease: "easeOut" }}*/}
|
||||||
|
{/*>*/}
|
||||||
|
{/* <Flex justify="end" align="center">*/}
|
||||||
|
{/* <motion.div*/}
|
||||||
|
{/* whileHover={{ scale: 1.05 }}*/}
|
||||||
|
{/* whileTap={{ scale: 0.95 }}*/}
|
||||||
|
{/* >*/}
|
||||||
|
{/* <Button variant="soft" onClick={() => navigate("/servers")}>*/}
|
||||||
|
{/* <Icon icon="lucide:arrow-left" width="16" height="16" />*/}
|
||||||
|
{/* Back to Servers*/}
|
||||||
|
{/* </Button>*/}
|
||||||
|
{/* </motion.div>*/}
|
||||||
|
{/* </Flex>*/}
|
||||||
|
{/*</motion.div>*/}
|
||||||
|
|
||||||
|
<Grid columns={{ initial: "1", md: "2" }} gap="4">
|
||||||
|
{/* Basic Info Card */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.1, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<Card size="3">
|
||||||
|
<Flex direction="column" gap="4">
|
||||||
|
<Heading size="4">{t("server.basicInformation")}</Heading>
|
||||||
|
|
||||||
|
<Grid columns={{ initial: "1", md: "2" }} gap="4">
|
||||||
|
<Box>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("server.hostAddress")}
|
||||||
|
</Text>
|
||||||
|
<Text as="div" size="3" weight="medium">
|
||||||
|
{server.serverAddr}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
<Box>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("server.port")}
|
||||||
|
</Text>
|
||||||
|
<Text as="div" size="3" weight="medium">
|
||||||
|
{server.serverPort}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
<Box>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("server.latency")}
|
||||||
|
</Text>
|
||||||
|
<Box mt="1">
|
||||||
|
<ServerLatency networkStatus={server.networkStatus} size="3" />
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
<Box>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("server.location")}
|
||||||
|
</Text>
|
||||||
|
<Box mt="1">
|
||||||
|
<ServerLocation geoLocation={server.geoLocation} size="3" />
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
<Box>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("common.status")}
|
||||||
|
</Text>
|
||||||
|
<Flex align="center" gap="2" mt="1">
|
||||||
|
<Badge
|
||||||
|
radius="full"
|
||||||
|
color={getStatusColor(server.bootStatus)}
|
||||||
|
variant="soft"
|
||||||
|
className={`animate-status-appear ${
|
||||||
|
server.bootStatus === "running"
|
||||||
|
? "animate-status-pulse"
|
||||||
|
: server.bootStatus === "stopped"
|
||||||
|
? "animate-status-fade"
|
||||||
|
: ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={`status-dot ${
|
||||||
|
server.bootStatus === "running"
|
||||||
|
? "status-dot-green"
|
||||||
|
: server.bootStatus === "stopped"
|
||||||
|
? "status-dot-red"
|
||||||
|
: "status-dot-gray"
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
{server.bootStatus === "running"
|
||||||
|
? t("server.running")
|
||||||
|
: server.bootStatus === "stopped"
|
||||||
|
? t("server.stopped")
|
||||||
|
: t("common.status")}
|
||||||
|
</Badge>
|
||||||
|
</Flex>
|
||||||
|
</Box>
|
||||||
|
<Box>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("server.protocol")}
|
||||||
|
</Text>
|
||||||
|
<Text as="div" size="3" weight="medium" style={{ textTransform: "uppercase" }}>
|
||||||
|
{server.transport?.protocol || "TCP"}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
<Box>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("server.createdAt")}
|
||||||
|
</Text>
|
||||||
|
<Text as="div" size="3">
|
||||||
|
{new Date(server.created).toLocaleString()}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
<Box>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("server.lastUpdated")}
|
||||||
|
</Text>
|
||||||
|
<Text as="div" size="3">
|
||||||
|
{new Date(server.updated).toLocaleString()}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
</Grid>
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
{/* Configuration Summary or Other Info */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.2, ease: "easeOut" }}
|
||||||
|
>
|
||||||
|
<Card size="3" style={{ height: "100%" }}>
|
||||||
|
<Flex direction="column" gap="4">
|
||||||
|
<Heading size="4">{t("server.configuration")}</Heading>
|
||||||
|
<Box>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("common.description")}
|
||||||
|
</Text>
|
||||||
|
<Text as="div" size="3">
|
||||||
|
{server.description || t("server.noDescription")}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{server.transport?.tls?.enable && (
|
||||||
|
<Flex align="center" gap="2">
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("server.tls")}
|
||||||
|
</Text>
|
||||||
|
<Badge color="blue" variant="soft">
|
||||||
|
{t("server.enabled")}
|
||||||
|
</Badge>
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{server.transport?.proxyURL && (
|
||||||
|
<Box>
|
||||||
|
<Text size="2" color="gray">
|
||||||
|
{t("server.proxyURL")}
|
||||||
|
</Text>
|
||||||
|
<Text as="div" size="3" style={{ wordBreak: "break-all" }}>
|
||||||
|
{server.transport.proxyURL}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Flex>
|
||||||
|
</Card>
|
||||||
|
</motion.div>
|
||||||
|
</Grid>
|
||||||
|
|
||||||
|
{/* Logs Section */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
|
||||||
|
transition={{ duration: 0.5, delay: 0.3, ease: "easeOut" }}
|
||||||
|
className="flex flex-1 flex-col" // To make it expand
|
||||||
|
>
|
||||||
|
<Card size="3" className="flex flex-1 flex-col">
|
||||||
|
<Flex justify="between" align="center" mb="4">
|
||||||
|
<Heading size="4">{t("server.connectionLogs")}</Heading>
|
||||||
|
<Flex gap="2">
|
||||||
|
<Button size="1" variant="soft" onClick={() => setLogs([])}>
|
||||||
|
<Icon icon="lucide:trash-2" /> {t("server.clear")}
|
||||||
|
</Button>
|
||||||
|
</Flex>
|
||||||
|
</Flex>
|
||||||
|
|
||||||
|
<Box
|
||||||
|
ref={logContainerRef}
|
||||||
|
style={{
|
||||||
|
backgroundColor: "var(--gray-2)",
|
||||||
|
borderRadius: "var(--radius-3)",
|
||||||
|
padding: "1rem",
|
||||||
|
fontFamily: "monospace",
|
||||||
|
fontSize: "0.9rem",
|
||||||
|
height: "300px",
|
||||||
|
overflowY: "auto",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{logs.length > 0 ? (
|
||||||
|
logs.map((log, index) => (
|
||||||
|
<div key={index} style={{ marginBottom: "4px" }}>
|
||||||
|
<Text color="gray">{log}</Text>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<Text color="gray" style={{ fontStyle: "italic" }}>
|
||||||
|
{t("server.noLogsAvailable")}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Card>
|
||||||
|
</motion.div>
|
||||||
|
</Flex>
|
||||||
|
);
|
||||||
|
}
|
||||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user