Compare commits

...

109 Commits

Author SHA1 Message Date
耗子 f757862ebe feat: 同步前端更改 2023-10-30 03:25:27 +08:00
耗子 462b2f96d3 feat: 同步前端更改 2023-10-30 02:54:35 +08:00
耗子 ef79f043a3 fix: 优化 Pure-Ftpd systemd 文件 2023-10-30 02:34:11 +08:00
耗子 7b0221a7a6 fix: 移除不存在的 Redis 重载 2023-10-29 22:26:57 +08:00
耗子 fe04657c71 feat: 适配前端修改 2023-10-29 22:26:27 +08:00
耗子 77dbf006fe feat: 适配前端修改 2023-10-29 21:17:35 +08:00
耗子 2202e1a8a2 feat: 日志只读取 1000 行 2023-10-29 16:17:37 +08:00
耗子 83ebe763d2 feat: 适配前端修改 2023-10-29 16:07:18 +08:00
耗子 c82bd280aa feat: 适配前端修改 2023-10-29 15:44:02 +08:00
耗子 fe4a6e2e78 feat: 规范统一使用 422 状态码 2023-10-29 02:59:17 +08:00
耗子 08a443333f fix: lint 2023-10-27 03:25:23 +08:00
耗子 b330f8de82 feat: 接口调整 2023-10-27 02:58:59 +08:00
耗子 66ae4e4537 feat: 入口不准设置成 /api 2023-10-27 00:44:25 +08:00
耗子 e975d0e03f fix: 统计数据库排除自带的 2023-10-27 00:42:38 +08:00
耗子 8b1e8176a1 fix: 修复 PostgreSQL 数据库数量计算 2023-10-26 13:30:25 +08:00
耗子 3af985e501 feat: 发布 v2.1.1 2023-10-26 13:03:37 +08:00
耗子 2c60481525 ci: try to fix public 2023-10-26 13:03:12 +08:00
耗子 93bbefd40e fix: lint 2023-10-26 12:37:35 +08:00
耗子 63865ff1da feat: 优化安全入口 2023-10-26 03:33:05 +08:00
耗子 1b75b3a9a5 feat: 插件列表支持分页 2023-10-25 23:39:21 +08:00
耗子 21ccf17439 fix: lint 2023-10-25 21:52:02 +08:00
耗子 b00ae6f008 fix: 更新版本号 2023-10-25 21:44:05 +08:00
耗子 5b83a2c067 feat: 更新日志接口 2023-10-25 21:42:41 +08:00
耗子 a4f1c8c6fa feat: 首页优化 2023-10-25 20:40:37 +08:00
耗子 abf5962821 chore: 修改赞助信息 2023-10-25 02:53:50 +08:00
耗子 1c7b14d803 feat: Create FUNDING.yml 2023-10-25 02:51:34 +08:00
耗子 f0c8deee7d chore: 修改许可证为 AGPL v3 2023-10-25 02:22:55 +08:00
耗子 e96d95700a feat: 校验后移除 checksums 文件 2023-10-25 02:14:33 +08:00
耗子 0e10823448 feat: 优化更新和重启流程 2023-10-24 03:15:09 +08:00
耗子 e28b00f76d feat: 优化更新和重启流程 2023-10-24 02:51:07 +08:00
耗子 76dde17573 feat: 校验面板安装包 2023-10-23 22:19:35 +08:00
耗子 342b8048f0 fix: 修复极狐的版本号获取 2023-10-23 21:59:50 +08:00
耗子 9e58b613df feat: 优化 shell 执行错误处理 2023-10-23 21:54:22 +08:00
耗子 fe66704aaf feat: 优化 shell 执行错误处理 2023-10-23 21:48:02 +08:00
耗子 b62bcbaa73 feat: init env in test 2023-10-23 21:30:20 +08:00
耗子 39039534ba feat: init env in test 2023-10-23 21:29:41 +08:00
耗子 fd0092a299 feat: 添加 checksums 校验 2023-10-23 21:26:07 +08:00
耗子 5ec25deaf6 feat: 安装脚本优化 2023-10-23 20:15:06 +08:00
耗子 af21a6307e feat: 为面板安装添加 checksum 验证 2023-10-23 20:12:42 +08:00
耗子 a7de247f60 feat: 优化 curl 命令 2023-10-23 19:41:21 +08:00
耗子 12c25bfcab feat: 支持获取指定版本 2023-10-23 19:39:38 +08:00
耗子 24a32c03fd chore: 移除 resources 文件夹 2023-10-23 16:03:16 +08:00
耗子 5c4346d101 fix(workflow): 移除 public 文件夹 2023-10-23 16:01:40 +08:00
耗子 a4c80dd919 fix(workflow): 修复 apt 2023-10-23 15:47:53 +08:00
耗子 ccfd5550b9 fix(CI): 修复测试 2023-10-23 15:45:18 +08:00
耗子 5217e04bbf Merge branch 'v2.1' 2023-10-23 15:37:21 +08:00
耗子 4203f1b1bf fix(CI): 修复产物传递 2023-10-23 15:37:09 +08:00
耗子 02e4536f62 fix(CI): 修复文件名错误 2023-10-23 11:38:52 +08:00
耗子 ab1ba21823 feat(CI): 添加下载前端构建 2023-10-23 10:34:28 +08:00
耗子 441327b80f fix(SSH): 规范端口类型 2023-10-23 03:26:54 +08:00
耗子 eb0df71ef5 feat: 支持 Websocket 2023-10-23 02:52:49 +08:00
耗子 50ec426181 feat: 同步前端接口更新 2023-10-23 02:37:19 +08:00
耗子 949248b994 docs: 更新说明 2023-10-22 14:19:59 +08:00
耗子 d2e904c557 feat: 同步 v2.1 前端修改 2023-10-22 14:15:59 +08:00
耗子 834d707710 feat: 发布 v2.0.58 2023-10-19 22:36:45 +08:00
耗子 03b3d776b1 docs: 更新赞助商信息 2023-10-19 14:04:45 +08:00
耗子 3b5df9765e feat: 优化安装脚本 2023-10-19 03:39:13 +08:00
耗子 14baa7f7c3 feat: 发布 v2.0.57 2023-10-19 03:16:59 +08:00
耗子 0ecd60184b feat: 移除更新代理 2023-10-19 03:13:42 +08:00
耗子 6fcd65d0dd feat: 下载节点全局替换 2023-10-19 02:43:18 +08:00
耗子 1ca0cc0fa3 feat: 发布 v2.0.56 2023-10-16 20:57:27 +08:00
耗子 b844081956 ci: 调整发布配置 2023-10-16 20:56:56 +08:00
耗子 2724ba2751 ci: 调整发布配置 2023-10-16 20:40:44 +08:00
耗子 1dbf2ea9a3 ci: 修复错误 2023-10-16 20:29:35 +08:00
耗子 07c4083005 feat: 发布 v2.0.54 2023-10-16 20:28:12 +08:00
耗子 032133b54a ci: 在极狐发布版本 2023-10-16 20:27:06 +08:00
耗子 e10e0d4b9b feat: 将限速的阿里云镜像更换为腾讯云镜像 2023-10-16 19:44:23 +08:00
耗子 22b9b7f2aa feat: 将限速的阿里云镜像更换为腾讯云镜像 2023-10-16 19:39:12 +08:00
耗子 97562f189e fix: 修复在有 swap 的情况下无法安装的 bug 2023-10-15 22:31:25 +08:00
耗子 50daebeb0e Merge remote-tracking branch 'origin/main' 2023-10-10 20:04:40 +08:00
耗子 4bf23ff7ba feat: 更新依赖机器人配置 2023-10-10 20:04:28 +08:00
耗子 013b70d7ad Merge branch 'renovate/github.com-bytedance-sonic-1.x' into 'main'
chore(deps): Update module github.com/bytedance/sonic to v1.10.2

See merge request haozi-team/panel!21
2023-10-10 02:00:28 +08:00
耗子 aecb0a2ee6 Merge remote-tracking branch 'origin/main' 2023-10-10 00:59:19 +08:00
耗子 74d2bda1fe feat: 发布 v2.0.53 2023-10-10 00:59:12 +08:00
Renovate 918bdd0d95 chore(deps): Update module github.com/bytedance/sonic to v1.10.2 2023-10-08 04:07:18 +00:00
耗子 d5108ae684 Merge branch 'renovate/github.com-goravel-framework-1.x' into 'main'
chore(deps): Update module github.com/goravel/framework to v1.13.2

See merge request haozi-team/panel!20
2023-10-07 20:23:34 +08:00
耗子 1165d149f3 Merge branch 'renovate/golang.org-x-exp-digest' into 'main'
chore(deps): Update golang.org/x/exp digest to 7918f67

See merge request haozi-team/panel!19
2023-10-07 20:23:20 +08:00
耗子 4c8f4fa4ea feat: 卸载面板删除 /usr/bin/panel 2023-10-07 20:05:07 +08:00
耗子 be74716f74 feat: 操作 swap 后检查 /etc/fstab 是否正确 2023-10-07 20:03:29 +08:00
耗子 fdfe5725fd Merge remote-tracking branch 'origin/main' 2023-10-07 19:55:11 +08:00
耗子 8f33693228 feat: 添加面板卸载脚本 2023-10-07 19:55:04 +08:00
Renovate d9b5ed096b chore(deps): Update module github.com/goravel/framework to v1.13.2 2023-10-07 10:12:51 +00:00
Renovate 4cae56a56e chore(deps): Update golang.org/x/exp digest to 7918f67 2023-10-06 14:06:37 +00:00
耗子 2898801b27 Merge branch 'renovate/github.com-imroc-req-v3-3.x' into 'main'
chore(deps): Update module github.com/imroc/req/v3 to v3.42.1

See merge request haozi-team/panel!18
2023-10-06 20:56:54 +08:00
Renovate 5a22fc8fe5 chore(deps): Update module github.com/imroc/req/v3 to v3.42.1 2023-10-06 11:06:40 +00:00
耗子 ac9642d344 Merge remote-tracking branch 'origin/main' 2023-10-06 14:59:41 +08:00
耗子 f542491a38 ci: 调整作业产物为 3 天过期 2023-10-06 14:59:34 +08:00
耗子 64163575e2 Merge branch 'renovate/golang.org-x-exp-digest' into 'main'
chore(deps): Update golang.org/x/exp digest to 3e424a5

See merge request haozi-team/panel!17
2023-10-06 14:26:11 +08:00
耗子 2e07a26646 fix: 创建网站同步创建 PostgreSQL 数据库 2023-10-06 14:07:53 +08:00
Renovate 36b1478e32 chore(deps): Update golang.org/x/exp digest to 3e424a5 2023-10-05 20:06:26 +00:00
耗子 e5b24f25bd docs: 更新 README 2023-10-06 03:25:34 +08:00
耗子 6a100245de Merge branch 'renovate/golang.org-x-crypto-0.x' into 'main'
chore(deps): Update module golang.org/x/crypto to v0.14.0

See merge request haozi-team/panel!16
2023-10-06 02:27:59 +08:00
耗子 046c28a387 feat: 安装脚本优化 2023-10-06 00:22:09 +08:00
Renovate 937e940dd8 chore(deps): Update module golang.org/x/crypto to v0.14.0 2023-10-05 16:18:22 +00:00
耗子 be7063b4fc fix: 回滚,OpenResty 需更新 1.22 后才能支持 OpenSSL 3 编译 2023-10-05 00:05:11 +08:00
耗子 70e9342c5d feat: 发布 v2.0.51 2023-10-04 23:49:34 +08:00
耗子 0756a7b507 feat: OpenResty 使用 OpenSSL 3 编译 2023-10-04 23:49:05 +08:00
耗子 47f104bcae feat: 发布 v2.0.50 2023-10-04 23:08:56 +08:00
耗子 d20e57dca9 feat: 移除 OpenResty 的 GeoIP 模块 2023-10-04 23:08:34 +08:00
耗子 09cc10a563 docs: 文档更新 2023-10-03 20:47:58 +08:00
耗子 b188b3f1b8 feat: 优化 arm 判断 2023-10-02 16:32:05 +08:00
耗子 99dac8721e feat: 更新 PostgreSQL 的描述 2023-09-30 23:42:56 +08:00
耗子 c93eb4b309 feat: 优化网站添加 2023-09-29 17:37:01 +08:00
耗子 266f12d15a feat: 发布 v2.0.49 2023-09-29 17:02:12 +08:00
耗子 3a18b36df2 feat: 优化面板更新校验 2023-09-28 20:23:08 +08:00
耗子 ebcc022418 fix: 发布 v2.0.48 2023-09-28 19:50:23 +08:00
耗子 aa0fb2afcc fix: 修复 MySQL 更新 2023-09-28 19:50:03 +08:00
耗子 bde2c50696 fix: 修复 MySQL 版本号未更新 2023-09-28 19:39:26 +08:00
耗子 0945949b37 fix: 多打了一个引号 2023-09-28 17:01:37 +08:00
165 changed files with 3078 additions and 18138 deletions
+4
View File
@@ -0,0 +1,4 @@
# These are supported funding model platforms
open_collective: haozi-panel
custom: ['https://afdian.net/a/haozi-team']
+7
View File
@@ -17,6 +17,13 @@ jobs:
uses: actions/setup-go@v4
with:
go-version: 'stable'
- name: Fetch Frontend
run: |
sudo apt-get install -y curl jq unzip zip
curl -sSL https://api.github.com/repos/haozi-team/panel-frontend/releases/latest | jq -r ".assets[] | select(.name | contains(\"dist\")) | .browser_download_url" | xargs curl -L -o frontend.zip
rm -rf public
unzip frontend.zip
mv dist public
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v5
with:
+5 -1
View File
@@ -13,6 +13,10 @@ jobs:
with:
go-version: 'stable'
- name: Install dependencies
run: go mod tidy
run: sudo apt-get install -y curl jq
- name: Set up environment
run: |
cp panel-example.conf .env
go run . artisan key:generate
- name: Run tests
run: go test ./...
+1
View File
@@ -71,3 +71,4 @@ __debug_bin
# 前端工具链 #
.sass-cache/*
node_modules/
/public
+43 -1
View File
@@ -23,6 +23,7 @@ variables:
stages:
- prepare
- build
- release
golangci_lint:
stage: prepare
@@ -37,6 +38,13 @@ unit_test:
extends: .go_cache
allow_failure: true
script:
- rm -rf /etc/apt/sources.list
- rm -rf /etc/apt/sources.list.d/*
- wget -O /etc/apt/sources.list https://mirrors.ustc.edu.cn/repogen/conf/debian-http-4-bookworm
- apt-get update
- apt-get install -y curl jq
- cp panel-example.conf .env
- go run . artisan key:generate
- go test -v -coverprofile=coverage.txt -covermode=atomic ./...
build:
@@ -49,4 +57,38 @@ build:
name: "$OUTPUT_NAME"
paths:
- $OUTPUT_NAME
expire_in: 1 week
expire_in: 3 days
fetch:
stage: build
image: alpine:latest
before_script:
- sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories
- apk add --no-cache curl jq unzip zip
script:
- curl -sSL "https://jihulab.com/api/v4/projects/haozi-team%2Fpanel-frontend/releases" | jq -r '.[0].assets.links[] | select(.name | contains("dist")) | .direct_asset_url' | xargs curl -L -o frontend.zip
- rm -rf public
- unzip frontend.zip
- mv dist public
artifacts:
name: "frontend"
paths:
- public
expire_in: 3 days
release:
stage: release
dependencies:
- build
- fetch
image:
name: goreleaser/goreleaser
entrypoint: [ '' ]
only:
- tags
variables:
# Disable shallow cloning so that goreleaser can diff between tags to
# generate a changelog.
GIT_DEPTH: 0
script:
- goreleaser release --clean
+19 -3
View File
@@ -5,6 +5,7 @@ builds:
binary: panel
env:
- CGO_ENABLED=0
- GOPROXY=https://goproxy.cn,direct
goos:
- linux
goarch:
@@ -12,7 +13,6 @@ builds:
- arm64
goamd64:
- v2
- v3
ldflags:
- -s -w --extldflags "-static -fpic"
archives:
@@ -23,12 +23,28 @@ archives:
format: zip
wrap_in_directory: false
strip_parent_binary_folder: true
rlcp: true
files:
- LICENSE
- public/*
- storage/*
- database/*
- scripts/*
- resources/*
- panel-example.conf
gitlab_urls:
api: https://jihulab.com/api/v4/
download: https://jihulab.com
# set to true if you use a self-signed certificate
skip_tls_verify: false
# set to true if you want to upload to the Package Registry rather than attachments
# Only works with GitLab 13.5+
#
# Since: v1.3
use_package_registry: true
# Set this if you set GITLAB_TOKEN to the value of CI_JOB_TOKEN.
#
# Since: v1.11
use_job_token: true
+17
View File
@@ -0,0 +1,17 @@
## 行为准则
耗子Linux面板遵守业界通用的行为准则。任何违反行为准则的行为都可以报告给我们:
- 参与者将容忍反对意见。
- 参与者必须确保他们的语言和行为没有人身攻击和贬低个人言论。
- 在解释他人的言行时,参与者应始终保持良好的意图。
- 不能容忍可合理视为骚扰的行为。
## Code of Conduct
The HaoZi Linux Panel complies with the industry's common code of conduct. Any breach of the Code of Conduct can be reported to us:
- Participants will be tolerant of opposing views.
- Participants must ensure that their language and actions are free of personal attacks and disparaging personal remarks.
- When interpreting the words and actions of others, participants should always assume good intentions.
- Behavior that can be reasonably considered harassment will not be tolerated.
+628 -169
View File
@@ -1,202 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Preamble
1. Definitions.
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
"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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
"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.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
"Work" shall mean the work of authorship, whether in Source or
Object form, 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).
The precise terms and conditions for copying, distribution and
modification follow.
"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.
TERMS AND CONDITIONS
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to 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."
0. Definitions.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
"This License" refers to version 3 of the GNU Affero General Public License.
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.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
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 a Contribution incorporated 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.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
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:
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
A "covered work" means either the unmodified Program or a work based
on the Program.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
(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
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, 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 addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
1. Source Code.
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.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
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.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
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 redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
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 consequential 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 any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
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.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
END OF TERMS AND CONDITIONS
The Corresponding Source for a work in source code form is that
same work.
APPENDIX: How to apply the Apache License to your work.
2. Basic Permissions.
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. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
Copyright 2022 HaoZi Technology Co., Ltd.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
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
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
http://www.apache.org/licenses/LICENSE-2.0
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
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.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+52 -56
View File
@@ -1,46 +1,72 @@
# 耗子Linux面板
<h1 align="center">耗子 Linux 面板</h1>
[![Release](https://img.shields.io/github/release/haozi-team/panel.svg)](https://github.com/haozi-team/panel/releases)
[![Test](https://github.com/haozi-team/panel/actions/workflows/test.yml/badge.svg)](https://github.com/haozi-team/panel/actions)
[![Report Card](https://goreportcard.com/badge/github.com/haozi-team/panel)](https://goreportcard.com/report/github.com/haozi-team/panel)
[![Codecov](https://codecov.io/gh/haozi-team/panel/branch/main/graph/badge.svg?token=XFT5NGNSRG)](https://codecov.io/gh/haozi-team/panel)
![License](https://img.shields.io/github/license/haozi-team/panel)
<p align="center">
<a href="https://github.com/haozi-team/panel/releases"><img src="https://img.shields.io/github/release/haozi-team/panel.svg"></a>
<a href="https://github.com/haozi-team/panel/actions"><img src="https://github.com/haozi-team/panel/actions/workflows/test.yml/badge.svg"></a>
<a href="https://goreportcard.com/report/github.com/haozi-team/panel"><img src="https://goreportcard.com/badge/github.com/haozi-team/panel"></a>
<a href="https://codecov.io/gh/haozi-team/panel"><img src="https://codecov.io/gh/haozi-team/panel/branch/main/graph/badge.svg?token=XFT5NGNSRG"></a>
<a href="https://img.shields.io/github/license/haozi-team/panel"><img src="https://img.shields.io/github/license/haozi-team/panel"></a>
</p>
这是耗子Linux面板,一种使用GO开发的轻量Linux服务器运维管理面板。
<p align="center">
[简体中文] | [<a href="README_EN.md">English</a>]
</p>
通知:严禁使用耗子Linux面板从事任何非法活动,非法站点请勿向我们请求任何形式的技术支持,如果在技术支持过程中发现非法内容,我们将立即停止技术支持并留存相关证据
耗子 Linux 面板是针对我们自身业务需要使用 Golang 开发的轻量 Linux 服务器运维管理面板,以 GNU Affero General Public License v3.0 开源
#### 交流QQ群:[12370907](https://jq.qq.com/?_wv=1027&k=I1oJKSTH) | QQ频道:[pd.qq.com/s/fyol46wfy](https://pd.qq.com/s/fyol46wfy)
免责声明:严禁使用耗子 Linux 面板从事任何非法活动,非法站点请勿向我们请求任何形式的技术支持,如果在技术支持过程中发现非法内容,我们将立即停止技术支持并留存相关证据。
广告: [`WeAvatar` 多端多元化的统一头像服务](https://weavatar.com)
交流QQ群:[12370907](https://jq.qq.com/?_wv=1027&k=I1oJKSTH) | QQ频道:[pd.qq.com/s/fyol46wfy](https://pd.qq.com/s/fyol46wfy)
## 重要说明
目前我们正在重构面板前端部分开发 2.1 版本,v2.0.58 将是 2.0 的最后一个版本。
新前端将使用 Vue + Naive UI 开发,预计 10 月底可以完成。
存量用户请尽快更新至 v2.0.58,以便后续升级到 2.1 版本。
## 运行环境
面板仅支持主流 `amd64` | `arm64` 系统的最新版本,且随着系统版本的更新,面板也会逐步停止对旧版本系统的支持
耗子Linux面板仅支持 `amd64` | `arm64` 架构下的主流系统的最新版本,不支持 `Ubuntu`,因为其发版太过频繁,难以维护
不支持 `Ubuntu`,因为其发版太过频繁,难以维护
低配机器建议使用 `Debian`,资源占用较 `RHEL` 系更低。其他机器建议使用 `AlmaLinux` | `RockyLinux`,维护周期更长也更稳定
低配机器建议使用 `Debian`,资源占用较 `RHEL` 系更低。其他机器建议使用 `RockyLinux` | `AlmaLinux`,维护周期更长
不在下表中的其他系统(OpenCloudOS 8、Anolis 8、CentOS Stream 8/9、Debian 11等),可自行尝试安装,但不保证能够正常运行,且不提供无偿技术支持(理论上不会有大问题)
不在下表中的其他系统(OpenCloudOS 8、Anolis 8、CentOS Stream 8/9、Debian 11等),可自行尝试安装,但不保证能够正常运行,且不提供技术支持(理论上不会有大问题)。
CentOS Stream 可使用迁移脚本迁移至支持的系统: [CentOS 8/9 迁移脚本](https://github.com/haozi-team/byecentos)
| 系统 | 版本 |
|------------|----|
| RHEL | 9 |
| RockyLinux | 9 |
| AlmaLinux | 9 |
| RockyLinux | 9 |
| Debian | 12 |
随着系统版本的不断更新,我们亦可能会终止部分过于老旧的系统的支持,以保证面板的稳定性。
## 安装面板
安装面板前,你需要了解LNMP环境的基本知识,以及如何处理常见的LNMP环境问题,我们不建议0基础的用户安装和使用耗子Linux面板。
安装面板前,你需要了解LNMP环境的基本知识,以及如何处理常见的LNMP环境问题,不建议0基础的用户安装和使用耗子Linux面板[推荐: 宝塔 - 简单好用服务器运维面板](https://www.bt.cn/?invite_code=M190eXRpZWE=)
如果你决定继续,请以`root`用户登录服务器,执行以下命令安装面板:
```shell
bash <(curl -sSL https://dl.cdn.haozi.net/panel/install_panel.sh)
HAOZI_DL_URL="https://jihulab.com/haozi-team/download/-/raw/main/panel"; curl -sSL -O ${HAOZI_DL_URL}/install_panel.sh && curl -sSL -O ${HAOZI_DL_URL}/install_panel.sh.checksum.txt && sha256sum -c install_panel.sh.checksum.txt && bash install_panel.sh || echo "Checksum 验证失败,文件可能被篡改,已终止操作"
```
## 卸载面板
优先建议备份数据重装系统,这样可以保证系统纯净。
如果你无法重装系统,请以`root`用户登录服务器,执行以下命令卸载面板:
```shell
HAOZI_DL_URL="https://jihulab.com/haozi-team/download/-/raw/main/panel"; curl -sSL -O ${HAOZI_DL_URL}/uninstall_panel.sh && curl -sSL -O ${HAOZI_DL_URL}/uninstall_panel.sh.checksum.txt && sha256sum -c uninstall_panel.sh.checksum.txt && bash uninstall_panel.sh || echo "Checksum 验证失败,文件可能被篡改,已终止操作"
```
卸载面板前请务必备份好所有数据,提前卸载面板全部插件。卸载后数据将**无法恢复**!
## 日常维护
使用`panel`命令进行日常维护:
@@ -49,42 +75,33 @@ bash <(curl -sSL https://dl.cdn.haozi.net/panel/install_panel.sh)
panel
```
在 [Wiki](https://github.com/haozi-team/panel/wiki) 中查看更多使用方法和技巧。
## 问题反馈
使用类问题,可在 [WePublish社区论坛](https://wepublish.cn/forums) 提问或QQ群`@汤姆猫`寻求帮助
使用类问题,可在 [WePublish 社区论坛](https://wepublish.cn/forums) 提问或QQ群`@坤坤`寻求 AI 帮助,亦可在群里寻求付费支持
面板自身问题,可在 GitHub 的`Issues`
页面提交问题反馈,注意[提问的智慧](https://github.com/ryanhanwu/How-To-Ask-Questions-The-Smart-Way/blob/main/README-zh_CN.md)。
面板自身问题,可在 GitHub 的`Issues`页面提交问题反馈,注意[提问的智慧](https://github.com/ryanhanwu/How-To-Ask-Questions-The-Smart-Way/blob/main/README-zh_CN.md)。
## 贡献代码
### 寻找/创建 Issue
您可以在 [Issue 列表](https://github.com/haozi-team/panel/issues) 中寻找或创建一个 Issue,留言表达想要处理该 Issue
的意愿,得到维护者的确认后,即可开始处理。
您可以在 [Issue 列表](https://github.com/haozi-team/panel/issues) 中寻找或创建一个 Issue,留言表达想要处理该 Issue 的意愿,得到维护者的确认后,即可开始处理。
### 创建 PR
- 在开发过程中,如果遇到问题可以随时在 Issue 中详尽描述该问题,以进一步沟通,但在此之前请确保自己已通过 Google
等方式尽可能的尝试解决问题
- PR 须提交至我们的极狐GitLab仓库[https://jihulab.com/haozi-team/panel](https://jihulab.com/haozi-team/panel)
- 在开发过程中,如果遇到问题可以随时在 Issue 中详尽描述该问题,以进一步沟通,但在此之前请确保自己已通过 Google 等方式尽可能的尝试解决问题;
- PR 须提交至我们的极狐 GitLab 仓库[https://jihulab.com/haozi-team/panel](https://jihulab.com/haozi-team/panel),勿在 GitHub 上提交
- 当 PR 开发完毕后,请为其添加 `🚀 Review Ready` 标签,维护者将及时进行评审;
- 我们非常欢迎您的贡献,将在下次发版时将您添加到首页贡献者中;❤️
## 赞助商
### 服务器
- [盾云](https://www.ddunyun.com/aff/PNYAXMKI)
### CDN
- [无畏云加速](https://su.sctes.com/register?code=8st689ujpmm2p)
- [又拍云](https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral)
- [AnyCast.Ai](https://www.anycast.ai/)
- [盾云CDN](http://cdn.ddunyun.com/)
### 对象存储
@@ -93,30 +110,9 @@ panel
### DevOps
- [极狐GitLab](https://www.jihulab.com/)
- [极狐 GitLab](https://www.jihulab.com/)
#### 接受云资源和资金赞助,可通过QQ群咨询联系
## 行为准则
耗子Linux面板遵守业界通用的行为准则。任何违反行为准则的行为都可以报告给我们:
- 参与者将容忍反对意见。
- 参与者必须确保他们的语言和行为没有人身攻击和贬低个人言论。
- 在解释他人的言行时,参与者应始终保持良好的意图。
- 不能容忍可合理视为骚扰的行为。
## 安全说明
安全性是我们最关心的问题之一,我们已在生产环境广泛应用耗子Linux面板。
耗子Linux面板采用业界多种方案尽可能保证面板的安全性,但是我们不能保证面板的绝对安全性,**因此我们不对面板的安全性做任何保证
**
如果您在使用面板的过程中发现任何安全问题,请勿提交 Issue,可通过以下方式直接联系我们:
- 邮箱:i@haozi.net
- QQ826896000
**接受云资源和资金赞助,可通过QQ群咨询联系**
## 贡献者
+127
View File
@@ -0,0 +1,127 @@
<h1 align="center">HaoZi Linux Panel</h1>
<p align="center">
<a href="https://github.com/haozi-team/panel/releases"><img src="https://img.shields.io/github/release/haozi-team/panel.svg"></a>
<a href="https://github.com/haozi-team/panel/actions"><img src="https://github.com/haozi-team/panel/actions/workflows/test.yml/badge.svg"></a>
<a href="https://goreportcard.com/report/github.com/haozi-team/panel"><img src="https://goreportcard.com/badge/github.com/haozi-team/panel"></a>
<a href="https://codecov.io/gh/haozi-team/panel"><img src="https://codecov.io/gh/haozi-team/panel/branch/main/graph/badge.svg?token=XFT5NGNSRG"></a>
<a href="https://img.shields.io/github/license/haozi-team/panel"><img src="https://img.shields.io/github/license/haozi-team/panel"></a>
</p>
<p align="center">
[<a href="README.md">简体中文</a>] | [English]
</p>
The HaoZi Linux Panel is a lightweight Linux server operation and maintenance management panel developed using Golang for our own business needs. It is open source under the GNU Affero General Public License v3.0 protocol.
Disclaimer: It is strictly prohibited to use the HaoZi Linux Panel to engage in any illegal activities. Please do not request any form of technical support from us for illegal sites. If illegal content is discovered during the technical support process, we will immediately stop technical support and retain relevant evidence.
Communication QQ group: [12370907](https://jq.qq.com/?_wv=1027&k=I1oJKSTH) | QQ channel: [pd.qq.com/s/fyol46wfy](https://pd.qq.com/s/fyol46wfy)
## UI Screenshots
![UI Screenshots](ui.png)
## Operating Environment
HaoZi Linux Panel only supports the latest version of mainstream systems under the `amd64` | `arm64` architecture. It does not support `Ubuntu` because its releases are too frequent and difficult to maintain.
Recommended to use `Debian` for low-configuration machines, as its resource usage is lower than that of the `RHEL` system. For other machines, recommended to use `RockyLinux` | `AlmaLinux`, which has a longer maintenance cycle and is more stable.
For other systems not in the table below (OpenCloudOS 8, Anolis 8, CentOS Stream 8/9, Debian 11, etc.), you can try to install it yourself, but normal operation is not guaranteed, and free technical support is not provided (theoretically there will be no major question).
CentOS Stream can be migrated to a supported system using the migration script: [CentOS 8/9 Migration Script](https://github.com/haozi-team/byecentos)
| OS | Version |
|------------|---------|
| RHEL | 9 |
| RockyLinux | 9 |
| AlmaLinux | 9 |
| Debian | 12 |
As system versions are constantly updated, we may also terminate support for some older systems to ensure the stability of the panel.
## Install Panel
Before installing the panel, you need to understand the basic knowledge of the LNMP environment and how to deal with common LNMP environment problems. It is not recommended for users with zero basic knowledge to install and use HaoZi Linux Panel ([Recommended: aaPanel - easy-to-use server operation and maintenance panel](https://aapanel.com)).
If you decide to continue, please log in to the server as `root` user and execute the following command to install the panel:
```shell
HAOZI_DL_URL="https://jihulab.com/haozi-team/download/-/raw/main/panel"; curl -sSL -O ${HAOZI_DL_URL}/install_panel.sh && curl -sSL -O ${HAOZI_DL_URL}/install_panel.sh.checksum.txt && sha256sum -c install_panel.sh.checksum.txt && bash install_panel.sh || echo "Checksum Verification Failed, File May Have Been Tampered With, Operation Terminated"
```
## Uninstall Panel
Recommended to back up data and reinstall the system first, so that the system can be kept clean.
If you are unable to reinstall the system, log in to the server as the `root` user and execute the following command to uninstall the panel:
```shell
HAOZI_DL_URL="https://jihulab.com/haozi-team/download/-/raw/main/panel"; curl -sSL -O ${HAOZI_DL_URL}/uninstall_panel.sh && curl -sSL -O ${HAOZI_DL_URL}/uninstall_panel.sh.checksum.txt && sha256sum -c uninstall_panel.sh.checksum.txt && bash uninstall_panel.sh || echo "Checksum Verification Failed, File May Have Been Tampered With, Operation Terminated"
```
Before uninstalling the panel, please be sure to back up all data and uninstall all panel plugins in advance. The data will **not be recoverable** after uninstallation!
## Daily Maintenance
Use `panel` command for daily maintenance:
```shell
panel
```
See more usage methods and tips in [Wiki](https://github.com/haozi-team/panel/wiki).
## Feedback
For usage issues, you can ask questions in the [WePublish Community Forum](https://wepublish.cn/forums) or seek AI help in the QQ group `@坤坤`. You can also seek paid support in the group.
For issues with the panel itself, you can submit feedback on the `Issues` page of GitHub. Please note [the wisdom of asking questions](http://www.catb.org/~esr/faqs/smart-questions.html).
## Contribute code
### Find/Create Issue
You can find or create an Issue in [Issue List](https://github.com/haozi-team/panel/issues), leave a message to express your willingness to deal with the Issue, and get confirmation from the maintainer. Start processing.
### Create PR
- During the development process, if you encounter a problem, you can describe the problem in detail in the Issue at any time for further communication, but before doing so, please make sure that you have tried your best to solve the problem through Google and other methods;
- PRs must be submitted to our JiHu GitLab repository [https://jihulab.com/haozi-team/panel](https://jihulab.com/haozi-team/panel). Do not submit on GitHub;
- When the PR is completed, please add the `🚀 Review Ready` tag to it, and the maintainer will review it in time;
- We very much welcome your contributions and will add you to the homepage contributors in the next release; ❤️
## Sponsor
### CDN
- [无畏云加速](https://su.sctes.com/register?code=8st689ujpmm2p)
- [盾云CDN](http://cdn.ddunyun.com/)
### Object Storage
- [又拍云](https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral)
### DevOps
- [JiHu GitLab](https://www.jihulab.com/)
**Accept cloud resources and financial sponsorship, you can contact us through QQ group**
## Contributor
This project owes its existence to all those who have contributed. To contribute, please check the contributed code section first.
<a href="https://github.com/DevHaoZi" target="_blank"><img src="https://avatars.githubusercontent.com/u/115467771?v=4" width="48" height="48"></a>
## Star History
<a href="https://star-history.com/#haozi-team/panel&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=haozi-team/panel&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=haozi-team/panel&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=haozi-team/panel&type=Date" />
</picture>
</a>
+25
View File
@@ -0,0 +1,25 @@
## 安全说明
安全性是我们最关心的问题之一,我们已在多个不同应用的生产环境广泛应用耗子Linux面板,至今无一例安全事故。
耗子Linux面板采用业界多种方案尽可能保证面板的安全性,但是我们不能保证面板的绝对安全性,**因此我们不对面板的安全性做任何保证**。
如果您在使用面板的过程中发现任何安全问题,请勿提交 Issue,可通过以下方式直接联系我们:
- 邮箱:i@haozi.net
- QQ826896000
致某些 CVE 爱好者:通过面板 `access_token` 执行的任何操作(包括且不限于:获取 root 权限、读取/写入系统敏感文件、执行任意 shell 命令等)均不被认为是安全问题,请不要刷此类报告浪费彼此的时间,这类低水平的报告对你的简历也没有任何帮助。
## Security Policy
Security is one of our biggest concerns. We have widely used HaoZi Linux Panel in production environments for many different applications, and there has been no safety incident so far.
HaoZi Linux Panel adopts various solutions in the industry to ensure the security of the panel as much as possible, but we cannot guarantee the absolute security of the panel, **therefore we do not make any guarantees on the security of the panel**.
If you find any security issues while using the panel, please do not submit an Issue. You can contact us directly through the following methods:
- Email: i@haozi.net
- Telegram: @devhaozi
To some CVE enthusiasts: Any operation performed through the panel `access_token` (including but not limited to: obtaining root permissions, reading/writing system sensitive files, executing arbitrary shell commands, etc.) is not considered a security issue, please Dont waste each others time with these types of reports. These low-level reports wont do anything to help your resume.
+8 -6
View File
@@ -86,18 +86,20 @@ func (receiver *Panel) Handle(ctx console.Context) error {
return nil
}
input := arg1
proxy := false
if input == "y" || input == "Y" || input == "yes" || input == "Yes" {
proxy = true
panel, err := tools.GetLatestPanelVersion()
if err != nil {
color.Redln("获取最新版本失败")
return err
}
err = tools.UpdatePanel(cast.ToBool(proxy))
err = tools.UpdatePanel(panel)
if err != nil {
color.Redln("更新失败: " + err.Error())
return nil
}
color.Greenln("更新成功")
tools.RestartPanel()
case "getInfo":
var user models.User
@@ -496,7 +498,7 @@ func (receiver *Panel) Handle(ctx console.Context) error {
default:
color.Yellowln(facades.Config().GetString("panel.name") + "命令行工具 - " + facades.Config().GetString("panel.version"))
color.Greenln("请使用以下命令:")
color.Greenln("panel update {proxy} 更新 / 修复面板到最新版本")
color.Greenln("panel update 更新 / 修复面板到最新版本")
color.Greenln("panel getInfo 重新初始化面板账号信息")
color.Greenln("panel getPort 获取面板访问端口")
color.Greenln("panel getEntrance 获取面板访问入口")
+21 -19
View File
@@ -27,8 +27,8 @@ func NewCronController() *CronController {
// List 获取计划任务列表
func (c *CronController) List(ctx http.Context) http.Response {
limit := ctx.Request().QueryInt("limit")
page := ctx.Request().QueryInt("page")
limit := ctx.Request().QueryInt("limit", 10)
page := ctx.Request().QueryInt("page", 1)
var crons []models.Cron
var total int64
@@ -54,15 +54,15 @@ func (c *CronController) Add(ctx http.Context) http.Response {
"backup_type": "required_if:type,backup|in:website,mysql,postgresql",
})
if err != nil {
return Error(ctx, http.StatusBadRequest, err.Error())
return Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return Error(ctx, http.StatusBadRequest, validator.Errors().One())
return Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
// 单独验证时间格式
if !regexp.MustCompile(`^((\*|\d+|\d+-\d+|\d+/\d+|\d+-\d+/\d+|\*/\d+)(,(\*|\d+|\d+-\d+|\d+/\d+|\d+-\d+/\d+|\*/\d+))*\s?){5}$`).MatchString(ctx.Request().Input("time")) {
return Error(ctx, http.StatusBadRequest, "时间格式错误")
return Error(ctx, http.StatusUnprocessableEntity, "时间格式错误")
}
shell := ctx.Request().Input("script")
@@ -74,7 +74,7 @@ func (c *CronController) Add(ctx http.Context) http.Response {
backupName = ctx.Request().Input("website")
}
backupPath := ctx.Request().Input("backup_path")
if len(backupName) == 0 {
if len(backupPath) == 0 {
backupPath = c.setting.Get(models.SettingKeyBackupPath) + "/" + backupType
}
backupSave := ctx.Request().InputInt("save", 10)
@@ -151,7 +151,7 @@ func (c *CronController) Script(ctx http.Context) http.Response {
var cron models.Cron
err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron)
if err != nil {
return Error(ctx, http.StatusBadRequest, "计划任务不存在")
return Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在")
}
return Success(ctx, tools.Read(cron.Shell))
@@ -165,25 +165,25 @@ func (c *CronController) Update(ctx http.Context) http.Response {
"script": "required",
})
if err != nil {
return Error(ctx, http.StatusBadRequest, err.Error())
return Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return Error(ctx, http.StatusBadRequest, validator.Errors().One())
return Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
// 单独验证时间格式
if !regexp.MustCompile(`^((\*|\d+|\d+-\d+|\d+/\d+|\d+-\d+/\d+|\*/\d+)(,(\*|\d+|\d+-\d+|\d+/\d+|\d+-\d+/\d+|\*/\d+))*\s?){5}$`).MatchString(ctx.Request().Input("time")) {
return Error(ctx, http.StatusBadRequest, "时间格式错误")
return Error(ctx, http.StatusUnprocessableEntity, "时间格式错误")
}
var cron models.Cron
err = facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron)
if err != nil {
return Error(ctx, http.StatusBadRequest, "计划任务不存在")
return Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在")
}
if !cron.Status {
return Error(ctx, http.StatusBadRequest, "计划任务已禁用")
return Error(ctx, http.StatusUnprocessableEntity, "计划任务已禁用")
}
cron.Time = ctx.Request().Input("time")
@@ -213,7 +213,7 @@ func (c *CronController) Delete(ctx http.Context) http.Response {
var cron models.Cron
err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron)
if err != nil {
return Error(ctx, http.StatusBadRequest, "计划任务不存在")
return Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在")
}
c.cron.DeleteFromSystem(cron)
@@ -234,16 +234,16 @@ func (c *CronController) Status(ctx http.Context) http.Response {
"status": "bool",
})
if err != nil {
return Error(ctx, http.StatusBadRequest, err.Error())
return Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return Error(ctx, http.StatusBadRequest, validator.Errors().One())
return Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
var cron models.Cron
err = facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron)
if err != nil {
return Error(ctx, http.StatusBadRequest, "计划任务不存在")
return Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在")
}
cron.Status = ctx.Request().InputBool("status")
@@ -266,12 +266,14 @@ func (c *CronController) Log(ctx http.Context) http.Response {
var cron models.Cron
err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron)
if err != nil {
return Error(ctx, http.StatusBadRequest, "计划任务不存在")
return Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在")
}
if !tools.Exists(cron.Log) {
return Error(ctx, http.StatusBadRequest, "日志文件不存在")
return Error(ctx, http.StatusUnprocessableEntity, "日志文件不存在")
}
return Success(ctx, tools.Read(cron.Log))
log := tools.Exec("tail -n 1000 " + cron.Log)
return Success(ctx, log)
}
+173 -39
View File
@@ -1,6 +1,7 @@
package controllers
import (
"database/sql"
"fmt"
"regexp"
"strings"
@@ -21,12 +22,14 @@ type MenuItem struct {
}
type InfoController struct {
plugin services.Plugin
plugin services.Plugin
setting services.Setting
}
func NewInfoController() *InfoController {
return &InfoController{
plugin: services.NewPluginImpl(),
plugin: services.NewPluginImpl(),
setting: services.NewSettingImpl(),
}
}
@@ -44,21 +47,6 @@ func (c *InfoController) Name(ctx http.Context) http.Response {
})
}
// Menu 获取面板菜单
func (c *InfoController) Menu(ctx http.Context) http.Response {
return Success(ctx, []MenuItem{
{Name: "home", Title: "主页", Icon: "layui-icon-home", Jump: "/"},
{Name: "website", Title: "网站管理", Icon: "layui-icon-website", Jump: "website/list"},
{Name: "monitor", Title: "资源监控", Icon: "layui-icon-chart-screen", Jump: "monitor"},
{Name: "safe", Title: "系统安全", Icon: "layui-icon-auz", Jump: "safe"},
/*{Name: "file", Title: "文件管理", Icon: "layui-icon-file", Jump: "file"},*/
{Name: "cron", Title: "计划任务", Icon: "layui-icon-date", Jump: "cron"},
{Name: "ssh", Title: "SSH", Icon: "layui-icon-layer", Jump: "ssh"},
{Name: "plugin", Title: "插件中心", Icon: "layui-icon-app", Jump: "plugin"},
{Name: "setting", Title: "面板设置", Icon: "layui-icon-set", Jump: "setting"},
})
}
// HomePlugins 获取首页插件
func (c *InfoController) HomePlugins(ctx http.Context) http.Response {
var plugins []models.Plugin
@@ -100,6 +88,112 @@ func (c *InfoController) SystemInfo(ctx http.Context) http.Response {
})
}
// CountInfo 获取面板统计信息
func (c *InfoController) CountInfo(ctx http.Context) http.Response {
var websiteCount int64
err := facades.Orm().Query().Model(models.Website{}).Count(&websiteCount)
if err != nil {
websiteCount = -1
}
var mysql models.Plugin
mysqlInstalled := true
err = facades.Orm().Query().Where("slug like ?", "mysql%").FirstOrFail(&mysql)
if err != nil {
mysqlInstalled = false
}
var postgresql models.Plugin
postgresqlInstalled := true
err = facades.Orm().Query().Where("slug like ?", "postgresql%").FirstOrFail(&postgresql)
if err != nil {
postgresqlInstalled = false
}
var databaseCount int64
if mysqlInstalled {
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if status == "active" {
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
type database struct {
Name string `json:"name"`
}
db, err := sql.Open("mysql", "root:"+rootPassword+"@unix(/tmp/mysql.sock)/")
if err != nil {
facades.Log().With(map[string]any{
"error": err.Error(),
}).Error("[面板][InfoController] 获取数据库列表失败")
databaseCount = -1
} else {
defer db.Close()
rows, err := db.Query("SHOW DATABASES")
if err != nil {
facades.Log().With(map[string]any{
"error": err.Error(),
}).Error("[面板][InfoController] 获取数据库列表失败")
databaseCount = -1
} else {
defer rows.Close()
var databases []database
for rows.Next() {
var d database
err := rows.Scan(&d.Name)
if err != nil {
continue
}
if d.Name == "information_schema" || d.Name == "performance_schema" || d.Name == "mysql" || d.Name == "sys" {
continue
}
databases = append(databases, d)
}
databaseCount = int64(len(databases))
}
}
}
}
if postgresqlInstalled {
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if status == "active" {
raw := tools.Exec(`echo "\l" | su - postgres -c "psql"`)
databases := strings.Split(raw, "\n")
if len(databases) >= 4 {
databases = databases[3 : len(databases)-1]
for _, db := range databases {
parts := strings.Split(db, "|")
if len(parts) != 9 || len(strings.TrimSpace(parts[0])) == 0 || strings.TrimSpace(parts[0]) == "template0" || strings.TrimSpace(parts[0]) == "template1" || strings.TrimSpace(parts[0]) == "postgres" {
continue
}
databaseCount++
}
}
}
}
var ftpCount int64
var ftpPlugin = c.plugin.GetInstalledBySlug("pureftpd")
if ftpPlugin.ID != 0 {
listRaw := tools.Exec("pure-pw list")
if len(listRaw) != 0 {
listArr := strings.Split(listRaw, "\n")
ftpCount = int64(len(listArr))
}
}
var cronCount int64
err = facades.Orm().Query().Model(models.Cron{}).Count(&cronCount)
if err != nil {
cronCount = -1
}
return Success(ctx, http.Json{
"website": websiteCount,
"database": databaseCount,
"ftp": ftpCount,
"cron": cronCount,
})
}
// InstalledDbAndPhp 获取已安装的数据库和 PHP 版本
func (c *InfoController) InstalledDbAndPhp(ctx http.Context) http.Response {
var php []models.Plugin
@@ -123,24 +217,32 @@ func (c *InfoController) InstalledDbAndPhp(ctx http.Context) http.Response {
}
type data struct {
Slug string `json:"slug"`
Name string `json:"name"`
Label string `json:"label"`
Value string `json:"value"`
}
var phpData []data
phpData = append(phpData, data{Slug: "0", Name: "不使用"})
var dbData []data
phpData = append(phpData, data{Value: "0", Label: "不使用"})
dbData = append(dbData, data{Value: "0", Label: "不使用"})
for _, p := range php {
match := regexp.MustCompile(`php(\d+)`).FindStringSubmatch(p.Slug)
if len(match) == 0 {
continue
}
phpData = append(phpData, data{Slug: strings.ReplaceAll(p.Slug, "php", ""), Name: c.plugin.GetBySlug(p.Slug).Name})
phpData = append(phpData, data{Value: strings.ReplaceAll(p.Slug, "php", ""), Label: c.plugin.GetBySlug(p.Slug).Name})
}
if mysqlInstalled {
dbData = append(dbData, data{Value: "mysql", Label: "MySQL"})
}
if postgresqlInstalled {
dbData = append(dbData, data{Value: "postgresql", Label: "PostgreSQL"})
}
return Success(ctx, http.Json{
"php": phpData,
"mysql": mysqlInstalled,
"postgresql": postgresqlInstalled,
"php": phpData,
"db": dbData,
})
}
@@ -152,25 +254,47 @@ func (c *InfoController) CheckUpdate(ctx http.Context) http.Response {
return Error(ctx, http.StatusInternalServerError, "获取最新版本失败")
}
if version == remote.Version {
if tools.VersionCompare(version, remote.Version, ">=") {
return Success(ctx, http.Json{
"update": false,
"version": remote.Version,
"name": remote.Name,
"body": remote.Body,
"date": remote.Date,
"update": false,
})
}
return Success(ctx, http.Json{
"update": true,
"version": remote.Version,
"name": remote.Name,
"body": remote.Body,
"date": remote.Date,
"update": true,
})
}
// UpdateInfo 获取更新信息
func (c *InfoController) UpdateInfo(ctx http.Context) http.Response {
version := facades.Config().GetString("panel.version")
current, err := tools.GetLatestPanelVersion()
if err != nil {
return Error(ctx, http.StatusInternalServerError, "获取最新版本失败")
}
if tools.VersionCompare(version, current.Version, ">=") {
return Error(ctx, http.StatusInternalServerError, "当前版本已是最新版本")
}
versions, err := tools.GenerateVersions(version, current.Version)
if err != nil {
return Error(ctx, http.StatusInternalServerError, "获取更新信息失败")
}
var versionInfo []tools.PanelInfo
for _, v := range versions {
info, err := tools.GetPanelVersion(v)
if err != nil {
continue
}
versionInfo = append(versionInfo, info)
}
return Success(ctx, versionInfo)
}
// Update 更新面板
func (c *InfoController) Update(ctx http.Context) http.Response {
var task models.Task
@@ -179,13 +303,23 @@ func (c *InfoController) Update(ctx http.Context) http.Response {
return Error(ctx, http.StatusInternalServerError, "当前有任务正在执行,禁止更新")
}
proxy := ctx.Request().InputBool("proxy")
err = tools.UpdatePanel(proxy)
panel, err := tools.GetLatestPanelVersion()
if err != nil {
facades.Log().Error("[面板][InfoController] 更新面板失败 ", err.Error())
facades.Log().With(map[string]any{
"error": err.Error(),
}).Error("[面板][InfoController] 获取最新版本失败")
return Error(ctx, http.StatusInternalServerError, "获取最新版本失败")
}
err = tools.UpdatePanel(panel)
if err != nil {
facades.Log().With(map[string]any{
"error": err.Error(),
}).Error("[面板][InfoController] 更新面板失败")
return Error(ctx, http.StatusInternalServerError, "更新失败: "+err.Error())
}
tools.RestartPanel()
return Success(ctx, nil)
}
@@ -197,6 +331,6 @@ func (c *InfoController) Restart(ctx http.Context) http.Response {
return Error(ctx, http.StatusInternalServerError, "当前有任务正在执行,禁止重启")
}
tools.Exec("systemctl restart panel")
tools.RestartPanel()
return Success(ctx, nil)
}
+1 -1
View File
@@ -23,7 +23,7 @@ func NewMonitorController() *MonitorController {
// Switch 监控开关
func (r *MonitorController) Switch(ctx http.Context) http.Response {
value := ctx.Request().InputBool("switch")
value := ctx.Request().InputBool("monitor")
err := r.setting.Set(models.SettingKeyMonitor, cast.ToString(value))
if err != nil {
facades.Log().Error("[面板][MonitorController] 更新监控开关失败 ", err)
+25 -7
View File
@@ -51,7 +51,7 @@ func (r *PluginController) List(ctx http.Context) http.Response {
Show bool `json:"show"`
}
var p []plugin
var pluginArr []plugin
for _, item := range plugins {
installed, installedVersion, show := false, "", false
if _, ok := installedPluginsMap[item.Slug]; ok {
@@ -59,7 +59,7 @@ func (r *PluginController) List(ctx http.Context) http.Response {
installedVersion = installedPluginsMap[item.Slug].Version
show = installedPluginsMap[item.Slug].Show
}
p = append(p, plugin{
pluginArr = append(pluginArr, plugin{
Name: item.Name,
Description: item.Description,
Slug: item.Slug,
@@ -72,7 +72,25 @@ func (r *PluginController) List(ctx http.Context) http.Response {
})
}
return Success(ctx, p)
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(pluginArr) {
return Success(ctx, http.Json{
"total": 0,
"items": []plugin{},
})
}
if endIndex > len(pluginArr) {
endIndex = len(pluginArr)
}
pagedPlugins := pluginArr[startIndex:endIndex]
return Success(ctx, http.Json{
"total": len(pluginArr),
"items": pagedPlugins,
})
}
// Install 安装插件
@@ -87,7 +105,7 @@ func (r *PluginController) Install(ctx http.Context) http.Response {
}
if installedPlugin.ID != 0 {
return Error(ctx, http.StatusBadRequest, "插件已安装")
return Error(ctx, http.StatusUnprocessableEntity, "插件已安装")
}
var lock sync.RWMutex
@@ -143,7 +161,7 @@ func (r *PluginController) Uninstall(ctx http.Context) http.Response {
}
if installedPlugin.ID == 0 {
return Error(ctx, http.StatusBadRequest, "插件未安装")
return Error(ctx, http.StatusUnprocessableEntity, "插件未安装")
}
var lock sync.RWMutex
@@ -199,7 +217,7 @@ func (r *PluginController) Update(ctx http.Context) http.Response {
}
if installedPlugin.ID == 0 {
return Error(ctx, http.StatusBadRequest, "插件未安装")
return Error(ctx, http.StatusUnprocessableEntity, "插件未安装")
}
var lock sync.RWMutex
@@ -254,7 +272,7 @@ func (r *PluginController) UpdateShow(ctx http.Context) http.Response {
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
if plugin.ID == 0 {
return Error(ctx, http.StatusBadRequest, "插件未安装")
return Error(ctx, http.StatusUnprocessableEntity, "插件未安装")
}
plugin.Show = show
@@ -143,12 +143,12 @@ func (c *Fail2banController) List(ctx http.Context) http.Response {
limit := ctx.Request().QueryInt("limit", 10)
raw := tools.Read("/etc/fail2ban/jail.local")
if len(raw) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "Fail2ban 规则为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "Fail2ban 规则为空")
}
jailList := regexp.MustCompile(`\[(.*?)]`).FindAllStringSubmatch(raw, -1)
if len(jailList) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "Fail2ban 规则为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "Fail2ban 规则为空")
}
var jails []Jail
@@ -152,7 +152,7 @@ func (c *Mysql57Controller) SaveConfig(ctx http.Context) http.Response {
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空")
}
if !tools.Write("/www/server/mysql/conf/my.cnf", config, 0644) {
@@ -171,7 +171,7 @@ func (c *Mysql57Controller) Load(ctx http.Context) http.Response {
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
if len(rootPassword) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码为空")
}
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
@@ -181,13 +181,13 @@ func (c *Mysql57Controller) Load(ctx http.Context) http.Response {
raw := tools.Exec("/www/server/mysql/bin/mysqladmin -uroot -p" + rootPassword + " extended-status 2>&1")
if strings.Contains(raw, "Access denied for user") {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码错误")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码错误")
}
if !strings.Contains(raw, "Uptime") {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL负载失败")
}
data := make(map[int]map[string]string)
var data []map[string]string
expressions := []struct {
regex string
name string
@@ -212,16 +212,16 @@ func (c *Mysql57Controller) Load(ctx http.Context) http.Response {
{`Table_locks_waited\s+\|\s+(\d+)\s+\|`, "锁表次数"},
}
for i, expression := range expressions {
for _, expression := range expressions {
re := regexp.MustCompile(expression.regex)
matches := re.FindStringSubmatch(raw)
if len(matches) > 1 {
data[i] = make(map[string]string)
data[i] = map[string]string{"name": expression.name, "value": matches[1]}
d := map[string]string{"name": expression.name, "value": matches[1]}
if expression.name == "发送" || expression.name == "接收" {
data[i]["value"] = tools.FormatBytes(cast.ToFloat64(matches[1]))
d["value"] = tools.FormatBytes(cast.ToFloat64(matches[1]))
}
data = append(data, d)
}
}
@@ -290,7 +290,7 @@ func (c *Mysql57Controller) GetRootPassword(ctx http.Context) http.Response {
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
if len(rootPassword) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码为空")
}
return controllers.Success(ctx, rootPassword)
@@ -311,9 +311,9 @@ func (c *Mysql57Controller) SetRootPassword(ctx http.Context) http.Response {
return controllers.Error(ctx, http.StatusInternalServerError, "MySQL 未运行")
}
rootPassword := ctx.Request().Input(models.SettingKeyMysqlRootPassword)
rootPassword := ctx.Request().Input("password")
if len(rootPassword) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码不能为空")
}
oldRootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -407,10 +407,10 @@ func (c *Mysql57Controller) AddDatabase(ctx http.Context) http.Response {
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -437,10 +437,10 @@ func (c *Mysql57Controller) DeleteDatabase(ctx http.Context) http.Response {
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -463,7 +463,28 @@ func (c *Mysql57Controller) BackupList(ctx http.Context) http.Response {
return controllers.Error(ctx, http.StatusInternalServerError, "获取备份列表失败")
}
return controllers.Success(ctx, backupList)
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(backupList) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []services.BackupFile{},
})
}
if endIndex > len(backupList) {
endIndex = len(backupList)
}
pagedBackupList := backupList[startIndex:endIndex]
if pagedBackupList == nil {
pagedBackupList = []services.BackupFile{}
}
return controllers.Success(ctx, http.Json{
"total": len(backupList),
"items": pagedBackupList,
})
}
// UploadBackup 上传备份
@@ -475,7 +496,7 @@ func (c *Mysql57Controller) UploadBackup(ctx http.Context) http.Response {
file, err := ctx.Request().File("file")
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败")
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/mysql"
@@ -486,7 +507,7 @@ func (c *Mysql57Controller) UploadBackup(ctx http.Context) http.Response {
name := file.GetClientOriginalName()
_, err = file.StoreAs(backupPath, name)
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败")
}
return controllers.Success(ctx, "上传文件成功")
@@ -503,10 +524,10 @@ func (c *Mysql57Controller) CreateBackup(ctx http.Context) http.Response {
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
database := ctx.Request().Input("database")
@@ -530,10 +551,10 @@ func (c *Mysql57Controller) DeleteBackup(ctx http.Context) http.Response {
"name": "required|min_len:1|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/mysql"
@@ -551,17 +572,17 @@ func (c *Mysql57Controller) RestoreBackup(ctx http.Context) http.Response {
}
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|min_len:1|max_len:255",
"backup": "required|min_len:1|max_len:255",
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
err = c.backup.MysqlRestore(ctx.Request().Input("database"), ctx.Request().Input("name"))
err = c.backup.MysqlRestore(ctx.Request().Input("database"), ctx.Request().Input("backup"))
if err != nil {
facades.Log().Error("[MYSQL57] 还原失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "还原失败: "+err.Error())
@@ -669,10 +690,10 @@ func (c *Mysql57Controller) AddUser(ctx http.Context) http.Response {
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -697,10 +718,10 @@ func (c *Mysql57Controller) DeleteUser(ctx http.Context) http.Response {
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -722,10 +743,10 @@ func (c *Mysql57Controller) SetUserPassword(ctx http.Context) http.Response {
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -749,10 +770,10 @@ func (c *Mysql57Controller) SetUserPrivileges(ctx http.Context) http.Response {
"database": "required|min_len:1|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -152,7 +152,7 @@ func (c *Mysql80Controller) SaveConfig(ctx http.Context) http.Response {
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空")
}
if !tools.Write("/www/server/mysql/conf/my.cnf", config, 0644) {
@@ -171,7 +171,7 @@ func (c *Mysql80Controller) Load(ctx http.Context) http.Response {
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
if len(rootPassword) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码为空")
}
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
@@ -181,13 +181,13 @@ func (c *Mysql80Controller) Load(ctx http.Context) http.Response {
raw := tools.Exec("/www/server/mysql/bin/mysqladmin -uroot -p" + rootPassword + " extended-status 2>&1")
if strings.Contains(raw, "Access denied for user") {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码错误")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码错误")
}
if !strings.Contains(raw, "Uptime") {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL负载失败")
}
data := make(map[int]map[string]string)
var data []map[string]string
expressions := []struct {
regex string
name string
@@ -212,16 +212,16 @@ func (c *Mysql80Controller) Load(ctx http.Context) http.Response {
{`Table_locks_waited\s+\|\s+(\d+)\s+\|`, "锁表次数"},
}
for i, expression := range expressions {
for _, expression := range expressions {
re := regexp.MustCompile(expression.regex)
matches := re.FindStringSubmatch(raw)
if len(matches) > 1 {
data[i] = make(map[string]string)
data[i] = map[string]string{"name": expression.name, "value": matches[1]}
d := map[string]string{"name": expression.name, "value": matches[1]}
if expression.name == "发送" || expression.name == "接收" {
data[i]["value"] = tools.FormatBytes(cast.ToFloat64(matches[1]))
d["value"] = tools.FormatBytes(cast.ToFloat64(matches[1]))
}
data = append(data, d)
}
}
@@ -290,7 +290,7 @@ func (c *Mysql80Controller) GetRootPassword(ctx http.Context) http.Response {
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
if len(rootPassword) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码为空")
}
return controllers.Success(ctx, rootPassword)
@@ -311,9 +311,9 @@ func (c *Mysql80Controller) SetRootPassword(ctx http.Context) http.Response {
return controllers.Error(ctx, http.StatusInternalServerError, "MySQL 未运行")
}
rootPassword := ctx.Request().Input(models.SettingKeyMysqlRootPassword)
rootPassword := ctx.Request().Input("password")
if len(rootPassword) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "MySQL root密码不能为空")
}
oldRootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -407,10 +407,10 @@ func (c *Mysql80Controller) AddDatabase(ctx http.Context) http.Response {
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -437,10 +437,10 @@ func (c *Mysql80Controller) DeleteDatabase(ctx http.Context) http.Response {
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -463,7 +463,28 @@ func (c *Mysql80Controller) BackupList(ctx http.Context) http.Response {
return controllers.Error(ctx, http.StatusInternalServerError, "获取备份列表失败")
}
return controllers.Success(ctx, backupList)
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(backupList) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []services.BackupFile{},
})
}
if endIndex > len(backupList) {
endIndex = len(backupList)
}
pagedBackupList := backupList[startIndex:endIndex]
if pagedBackupList == nil {
pagedBackupList = []services.BackupFile{}
}
return controllers.Success(ctx, http.Json{
"total": len(backupList),
"items": pagedBackupList,
})
}
// UploadBackup 上传备份
@@ -475,7 +496,7 @@ func (c *Mysql80Controller) UploadBackup(ctx http.Context) http.Response {
file, err := ctx.Request().File("file")
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败")
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/mysql"
@@ -486,7 +507,7 @@ func (c *Mysql80Controller) UploadBackup(ctx http.Context) http.Response {
name := file.GetClientOriginalName()
_, err = file.StoreAs(backupPath, name)
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败")
}
return controllers.Success(ctx, "上传文件成功")
@@ -503,10 +524,10 @@ func (c *Mysql80Controller) CreateBackup(ctx http.Context) http.Response {
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
database := ctx.Request().Input("database")
@@ -530,10 +551,10 @@ func (c *Mysql80Controller) DeleteBackup(ctx http.Context) http.Response {
"name": "required|min_len:1|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/mysql"
@@ -551,17 +572,17 @@ func (c *Mysql80Controller) RestoreBackup(ctx http.Context) http.Response {
}
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|min_len:1|max_len:255",
"backup": "required|min_len:1|max_len:255",
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
err = c.backup.MysqlRestore(ctx.Request().Input("database"), ctx.Request().Input("name"))
err = c.backup.MysqlRestore(ctx.Request().Input("database"), ctx.Request().Input("backup"))
if err != nil {
facades.Log().Error("[MYSQL80] 还原失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "还原失败: "+err.Error())
@@ -669,10 +690,10 @@ func (c *Mysql80Controller) AddUser(ctx http.Context) http.Response {
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -697,10 +718,10 @@ func (c *Mysql80Controller) DeleteUser(ctx http.Context) http.Response {
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -722,10 +743,10 @@ func (c *Mysql80Controller) SetUserPassword(ctx http.Context) http.Response {
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -749,10 +770,10 @@ func (c *Mysql80Controller) SetUserPrivileges(ctx http.Context) http.Response {
"database": "required|min_len:1|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
@@ -250,14 +250,14 @@ func (c *Php74Controller) InstallExtension(ctx http.Context) http.Response {
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展已安装")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展已安装")
}
var task models.Task
@@ -276,7 +276,7 @@ func (c *Php74Controller) InstallExtension(ctx http.Context) http.Response {
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展不存在")
}
func (c *Php74Controller) UninstallExtension(ctx http.Context) http.Response {
@@ -287,14 +287,14 @@ func (c *Php74Controller) UninstallExtension(ctx http.Context) http.Response {
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if !item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展未安装")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展未安装")
}
var task models.Task
@@ -313,7 +313,7 @@ func (c *Php74Controller) UninstallExtension(ctx http.Context) http.Response {
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展不存在")
}
func (c *Php74Controller) GetExtensions() []Extension {
@@ -250,14 +250,14 @@ func (c *Php80Controller) InstallExtension(ctx http.Context) http.Response {
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展已安装")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展已安装")
}
var task models.Task
@@ -276,7 +276,7 @@ func (c *Php80Controller) InstallExtension(ctx http.Context) http.Response {
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展不存在")
}
func (c *Php80Controller) UninstallExtension(ctx http.Context) http.Response {
@@ -287,14 +287,14 @@ func (c *Php80Controller) UninstallExtension(ctx http.Context) http.Response {
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if !item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展未安装")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展未安装")
}
var task models.Task
@@ -313,7 +313,7 @@ func (c *Php80Controller) UninstallExtension(ctx http.Context) http.Response {
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展不存在")
}
func (c *Php80Controller) GetExtensions() []Extension {
@@ -250,14 +250,14 @@ func (c *Php81Controller) InstallExtension(ctx http.Context) http.Response {
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展已安装")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展已安装")
}
var task models.Task
@@ -276,7 +276,7 @@ func (c *Php81Controller) InstallExtension(ctx http.Context) http.Response {
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展不存在")
}
func (c *Php81Controller) UninstallExtension(ctx http.Context) http.Response {
@@ -287,14 +287,14 @@ func (c *Php81Controller) UninstallExtension(ctx http.Context) http.Response {
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if !item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展未安装")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展未安装")
}
var task models.Task
@@ -313,7 +313,7 @@ func (c *Php81Controller) UninstallExtension(ctx http.Context) http.Response {
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展不存在")
}
func (c *Php81Controller) GetExtensions() []Extension {
@@ -250,14 +250,14 @@ func (c *Php82Controller) InstallExtension(ctx http.Context) http.Response {
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展已安装")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展已安装")
}
var task models.Task
@@ -276,7 +276,7 @@ func (c *Php82Controller) InstallExtension(ctx http.Context) http.Response {
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展不存在")
}
func (c *Php82Controller) UninstallExtension(ctx http.Context) http.Response {
@@ -287,14 +287,14 @@ func (c *Php82Controller) UninstallExtension(ctx http.Context) http.Response {
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if !item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展未安装")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展未安装")
}
var task models.Task
@@ -313,7 +313,7 @@ func (c *Php82Controller) UninstallExtension(ctx http.Context) http.Response {
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "扩展不存在")
}
func (c *Php82Controller) GetExtensions() []Extension {
@@ -6,6 +6,7 @@ import (
"strings"
"github.com/goravel/framework/contracts/http"
"github.com/spf13/cast"
"panel/app/http/controllers"
"panel/pkg/tools"
@@ -26,7 +27,7 @@ func (c *PhpMyAdminController) Info(ctx http.Context) http.Response {
files, err := os.ReadDir("/www/server/phpmyadmin")
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "找不到 phpMyAdmin 目录")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "找不到 phpMyAdmin 目录")
}
var phpmyadmin string
@@ -36,18 +37,18 @@ func (c *PhpMyAdminController) Info(ctx http.Context) http.Response {
}
}
if len(phpmyadmin) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "找不到 phpMyAdmin 目录")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "找不到 phpMyAdmin 目录")
}
conf := tools.Read("/www/server/vhost/phpmyadmin.conf")
match := regexp.MustCompile(`listen\s+(\d+);`).FindStringSubmatch(conf)
if len(match) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "找不到 phpMyAdmin 端口")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "找不到 phpMyAdmin 端口")
}
return controllers.Success(ctx, http.Json{
"phpmyadmin": phpmyadmin,
"port": match[1],
"path": phpmyadmin,
"port": cast.ToInt(match[1]),
})
}
@@ -59,7 +60,7 @@ func (c *PhpMyAdminController) SetPort(ctx http.Context) http.Response {
port := ctx.Request().Input("port")
if len(port) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "端口不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "端口不能为空")
}
conf := tools.Read("/www/server/vhost/phpmyadmin.conf")
@@ -170,7 +170,7 @@ func (c *Postgresql15Controller) SaveConfig(ctx http.Context) http.Response {
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空")
}
if !tools.Write("/www/server/postgresql/data/postgresql.conf", config, 0644) {
@@ -189,7 +189,7 @@ func (c *Postgresql15Controller) SaveUserConfig(ctx http.Context) http.Response
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空")
}
if !tools.Write("/www/server/postgresql/data/pg_hba.conf", config, 0644) {
@@ -256,16 +256,23 @@ func (c *Postgresql15Controller) DatabaseList(ctx http.Context) http.Response {
return controllers.Error(ctx, http.StatusInternalServerError, "PostgreSQL 已停止运行")
}
raw := tools.Exec(`echo "\l" | su - postgres -c "psql"`)
databases := strings.Split(raw, "\n")
databases = databases[3 : len(databases)-1]
type database struct {
Name string `json:"name"`
Owner string `json:"owner"`
Encoding string `json:"encoding"`
}
raw := tools.Exec(`echo "\l" | su - postgres -c "psql"`)
databases := strings.Split(raw, "\n")
if len(databases) >= 4 {
databases = databases[3 : len(databases)-1]
} else {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []database{},
})
}
var databaseList []database
for _, db := range databases {
parts := strings.Split(db, "|")
@@ -314,10 +321,10 @@ func (c *Postgresql15Controller) AddDatabase(ctx http.Context) http.Response {
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
database := ctx.Request().Input("database")
@@ -346,10 +353,10 @@ func (c *Postgresql15Controller) DeleteDatabase(ctx http.Context) http.Response
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:postgres,template0,template1",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
database := ctx.Request().Input("database")
@@ -371,7 +378,28 @@ func (c *Postgresql15Controller) BackupList(ctx http.Context) http.Response {
return controllers.Error(ctx, http.StatusInternalServerError, "获取备份列表失败")
}
return controllers.Success(ctx, backupList)
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(backupList) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []services.BackupFile{},
})
}
if endIndex > len(backupList) {
endIndex = len(backupList)
}
pagedBackupList := backupList[startIndex:endIndex]
if pagedBackupList == nil {
pagedBackupList = []services.BackupFile{}
}
return controllers.Success(ctx, http.Json{
"total": len(backupList),
"items": pagedBackupList,
})
}
// UploadBackup 上传备份
@@ -383,7 +411,7 @@ func (c *Postgresql15Controller) UploadBackup(ctx http.Context) http.Response {
file, err := ctx.Request().File("file")
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败")
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/postgresql"
@@ -394,7 +422,7 @@ func (c *Postgresql15Controller) UploadBackup(ctx http.Context) http.Response {
name := file.GetClientOriginalName()
_, err = file.StoreAs(backupPath, name)
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败")
}
return controllers.Success(ctx, nil)
@@ -411,10 +439,10 @@ func (c *Postgresql15Controller) CreateBackup(ctx http.Context) http.Response {
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
database := ctx.Request().Input("database")
@@ -438,10 +466,10 @@ func (c *Postgresql15Controller) DeleteBackup(ctx http.Context) http.Response {
"name": "required|min_len:1|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/postgresql"
@@ -459,17 +487,17 @@ func (c *Postgresql15Controller) RestoreBackup(ctx http.Context) http.Response {
}
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|min_len:1|max_len:255",
"backup": "required|min_len:1|max_len:255",
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
err = c.backup.PostgresqlRestore(ctx.Request().Input("database"), ctx.Request().Input("name"))
err = c.backup.PostgresqlRestore(ctx.Request().Input("database"), ctx.Request().Input("backup"))
if err != nil {
facades.Log().Error("[PostgreSQL] 还原失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "还原失败: "+err.Error())
@@ -544,10 +572,10 @@ func (c *Postgresql15Controller) AddUser(ctx http.Context) http.Response {
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
user := ctx.Request().Input("user")
@@ -573,10 +601,10 @@ func (c *Postgresql15Controller) DeleteUser(ctx http.Context) http.Response {
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
user := ctx.Request().Input("user")
@@ -598,10 +626,10 @@ func (c *Postgresql15Controller) SetUserPassword(ctx http.Context) http.Response
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
user := ctx.Request().Input("user")
@@ -170,7 +170,7 @@ func (c *Postgresql16Controller) SaveConfig(ctx http.Context) http.Response {
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空")
}
if !tools.Write("/www/server/postgresql/data/postgresql.conf", config, 0644) {
@@ -189,7 +189,7 @@ func (c *Postgresql16Controller) SaveUserConfig(ctx http.Context) http.Response
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空")
}
if !tools.Write("/www/server/postgresql/data/pg_hba.conf", config, 0644) {
@@ -256,16 +256,23 @@ func (c *Postgresql16Controller) DatabaseList(ctx http.Context) http.Response {
return controllers.Error(ctx, http.StatusInternalServerError, "PostgreSQL 已停止运行")
}
raw := tools.Exec(`echo "\l" | su - postgres -c "psql"`)
databases := strings.Split(raw, "\n")
databases = databases[3 : len(databases)-1]
type database struct {
Name string `json:"name"`
Owner string `json:"owner"`
Encoding string `json:"encoding"`
}
raw := tools.Exec(`echo "\l" | su - postgres -c "psql"`)
databases := strings.Split(raw, "\n")
if len(databases) >= 4 {
databases = databases[3 : len(databases)-1]
} else {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []database{},
})
}
var databaseList []database
for _, db := range databases {
parts := strings.Split(db, "|")
@@ -314,10 +321,10 @@ func (c *Postgresql16Controller) AddDatabase(ctx http.Context) http.Response {
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
database := ctx.Request().Input("database")
@@ -346,10 +353,10 @@ func (c *Postgresql16Controller) DeleteDatabase(ctx http.Context) http.Response
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:postgres,template0,template1",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
database := ctx.Request().Input("database")
@@ -371,7 +378,28 @@ func (c *Postgresql16Controller) BackupList(ctx http.Context) http.Response {
return controllers.Error(ctx, http.StatusInternalServerError, "获取备份列表失败")
}
return controllers.Success(ctx, backupList)
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(backupList) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []services.BackupFile{},
})
}
if endIndex > len(backupList) {
endIndex = len(backupList)
}
pagedBackupList := backupList[startIndex:endIndex]
if pagedBackupList == nil {
pagedBackupList = []services.BackupFile{}
}
return controllers.Success(ctx, http.Json{
"total": len(backupList),
"items": pagedBackupList,
})
}
// UploadBackup 上传备份
@@ -383,7 +411,7 @@ func (c *Postgresql16Controller) UploadBackup(ctx http.Context) http.Response {
file, err := ctx.Request().File("file")
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败")
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/postgresql"
@@ -394,7 +422,7 @@ func (c *Postgresql16Controller) UploadBackup(ctx http.Context) http.Response {
name := file.GetClientOriginalName()
_, err = file.StoreAs(backupPath, name)
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "上传文件失败")
}
return controllers.Success(ctx, nil)
@@ -411,10 +439,10 @@ func (c *Postgresql16Controller) CreateBackup(ctx http.Context) http.Response {
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
database := ctx.Request().Input("database")
@@ -438,10 +466,10 @@ func (c *Postgresql16Controller) DeleteBackup(ctx http.Context) http.Response {
"name": "required|min_len:1|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/postgresql"
@@ -459,17 +487,17 @@ func (c *Postgresql16Controller) RestoreBackup(ctx http.Context) http.Response {
}
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|min_len:1|max_len:255",
"backup": "required|min_len:1|max_len:255",
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
err = c.backup.PostgresqlRestore(ctx.Request().Input("database"), ctx.Request().Input("name"))
err = c.backup.PostgresqlRestore(ctx.Request().Input("database"), ctx.Request().Input("backup"))
if err != nil {
facades.Log().Error("[PostgreSQL] 还原失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "还原失败: "+err.Error())
@@ -544,10 +572,10 @@ func (c *Postgresql16Controller) AddUser(ctx http.Context) http.Response {
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
user := ctx.Request().Input("user")
@@ -573,10 +601,10 @@ func (c *Postgresql16Controller) DeleteUser(ctx http.Context) http.Response {
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
user := ctx.Request().Input("user")
@@ -598,10 +626,10 @@ func (c *Postgresql16Controller) SetUserPassword(ctx http.Context) http.Response
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
user := ctx.Request().Input("user")
@@ -5,6 +5,7 @@ import (
"strings"
"github.com/goravel/framework/contracts/http"
"github.com/spf13/cast"
"panel/app/http/controllers"
"panel/pkg/tools"
@@ -41,26 +42,6 @@ func (c *PureFtpdController) Status(ctx http.Context) http.Response {
}
}
// Reload 重载配置
func (c *PureFtpdController) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "pureftpd")
if check != nil {
return check
}
tools.Exec("systemctl reload pure-ftpd")
status := tools.Exec("systemctl status pure-ftpd | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PureFtpd状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Restart 重启服务
func (c *PureFtpdController) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "pureftpd")
@@ -184,10 +165,10 @@ func (c *PureFtpdController) Add(ctx http.Context) http.Response {
"path": "required",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
username := ctx.Request().Input("username")
@@ -198,7 +179,7 @@ func (c *PureFtpdController) Add(ctx http.Context) http.Response {
path = "/" + path
}
if !tools.Exists(path) {
return controllers.Error(ctx, http.StatusBadRequest, "目录不存在")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "目录不存在")
}
tools.Chmod(path, 0755)
@@ -220,10 +201,10 @@ func (c *PureFtpdController) Delete(ctx http.Context) http.Response {
"username": "required",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
username := ctx.Request().Input("username")
@@ -246,10 +227,10 @@ func (c *PureFtpdController) ChangePassword(ctx http.Context) http.Response {
"password": "required|min_len:6",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
username := ctx.Request().Input("username")
@@ -273,7 +254,7 @@ func (c *PureFtpdController) GetPort(ctx http.Context) http.Response {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PureFtpd端口失败")
}
return controllers.Success(ctx, port)
return controllers.Success(ctx, cast.ToInt(port))
}
// SetPort 设置端口
@@ -287,10 +268,10 @@ func (c *PureFtpdController) SetPort(ctx http.Context) http.Response {
"port": "required",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
port := ctx.Request().Input("port")
@@ -40,26 +40,6 @@ func (c *RedisController) Status(ctx http.Context) http.Response {
}
}
// Reload 重载配置
func (c *RedisController) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "redis")
if check != nil {
return check
}
tools.Exec("systemctl reload redis")
status := tools.Exec("systemctl status redis | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取Redis状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Restart 重启服务
func (c *RedisController) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "redis")
@@ -145,7 +125,7 @@ func (c *RedisController) SaveConfig(ctx http.Context) http.Response {
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "配置不能为空")
}
if !tools.Write("/www/server/redis/redis.conf", config, 0644) {
@@ -43,7 +43,7 @@ func (c *S3fsController) List(ctx http.Context) http.Response {
var s3fsList []s3fs
err := sonic.UnmarshalString(c.setting.Get("s3fs", "[]"), &s3fsList)
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "获取 S3fs 挂载失败")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "获取 S3fs 挂载失败")
}
startIndex := (page - 1) * limit
@@ -58,6 +58,9 @@ func (c *S3fsController) List(ctx http.Context) http.Response {
endIndex = len(s3fsList)
}
pagedS3fsList := s3fsList[startIndex:endIndex]
if pagedS3fsList == nil {
pagedS3fsList = []s3fs{}
}
return controllers.Success(ctx, http.Json{
"total": len(s3fsList),
@@ -345,10 +345,10 @@ func (c *SupervisorController) AddProcess(ctx http.Context) http.Response {
"num": "required",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
name := ctx.Request().Input("name")
+27 -14
View File
@@ -2,7 +2,6 @@ package toolbox
import (
"regexp"
"strconv"
"strings"
"github.com/goravel/framework/contracts/http"
@@ -29,7 +28,7 @@ func (c *ToolBoxController) GetDNS(ctx http.Context) http.Response {
raw := tools.Read("/etc/resolv.conf")
match := regexp.MustCompile(`nameserver\s+(\S+)`).FindAllStringSubmatch(raw, -1)
if len(match) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "找不到 DNS 信息")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "找不到 DNS 信息")
}
var dns []string
@@ -51,7 +50,7 @@ func (c *ToolBoxController) SetDNS(ctx http.Context) http.Response {
dns2 := ctx.Request().Input("dns2")
if len(dns1) == 0 || len(dns2) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "DNS 信息不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "DNS 信息不能为空")
}
var dns string
@@ -69,13 +68,14 @@ func (c *ToolBoxController) GetSWAP(ctx http.Context) http.Response {
return check
}
var total, size, used, free string
var total, used, free string
var size int64
if tools.Exists("/www/swap") {
s, _ := tools.FileSize("/www/swap")
size = strconv.Itoa(int(s / 1024 / 1024))
size = s / 1024 / 1024
total = tools.FormatBytes(float64(s))
} else {
size = "0.00 B"
size = 0
total = "0.00 B"
}
@@ -112,7 +112,7 @@ func (c *ToolBoxController) SetSWAP(ctx http.Context) http.Response {
if size > 1 {
free := tools.Exec("df -k /www | awk '{print $4}' | tail -n 1")
if cast.ToInt64(free)*1024 < int64(size)*1024*1024 {
return controllers.Error(ctx, http.StatusBadRequest, "磁盘空间不足,当前剩余 "+tools.FormatBytes(cast.ToFloat64(free)))
return controllers.Error(ctx, http.StatusUnprocessableEntity, "磁盘空间不足,当前剩余 "+tools.FormatBytes(cast.ToFloat64(free)))
}
if strings.Contains(tools.Exec("df -T /www | awk '{print $2}' | tail -n 1"), "btrfs") {
@@ -139,15 +139,28 @@ func (c *ToolBoxController) GetTimezone(ctx http.Context) http.Response {
raw := tools.Exec("LC_ALL=C timedatectl | grep zone")
match := regexp.MustCompile(`zone:\s+(\S+)`).FindStringSubmatch(raw)
if len(match) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "找不到时区信息")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "找不到时区信息")
}
type zone struct {
Label string `json:"label"`
Value string `json:"value"`
}
zonesRaw := tools.Exec("LC_ALL=C timedatectl list-timezones")
zones := strings.Split(zonesRaw, "\n")
var zonesList []zone
for _, z := range zones {
zonesList = append(zonesList, zone{
Label: z,
Value: z,
})
}
return controllers.Success(ctx, http.Json{
"zone": match[1],
"zones": zones,
"timezone": match[1],
"timezones": zonesList,
})
}
@@ -160,7 +173,7 @@ func (c *ToolBoxController) SetTimezone(ctx http.Context) http.Response {
timezone := ctx.Request().Input("timezone")
if len(timezone) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "时区不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "时区不能为空")
}
tools.Exec("timedatectl set-timezone " + timezone)
@@ -187,7 +200,7 @@ func (c *ToolBoxController) SetHosts(ctx http.Context) http.Response {
hosts := ctx.Request().Input("hosts")
if len(hosts) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "hosts 信息不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "hosts 信息不能为空")
}
tools.Write("/etc/hosts", hosts, 0644)
@@ -204,10 +217,10 @@ func (c *ToolBoxController) SetRootPassword(ctx http.Context) http.Response {
password := ctx.Request().Input("password")
if len(password) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "密码不能为空")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "密码不能为空")
}
if !regexp.MustCompile(`^[a-zA-Z0-9·~!@#$%^&*()_+-=\[\]{};:'",./<>?]{6,20}$`).MatchString(password) {
return controllers.Error(ctx, http.StatusBadRequest, "密码必须为 6-20 位字母、数字或特殊字符")
return controllers.Error(ctx, http.StatusUnprocessableEntity, "密码必须为 6-20 位字母、数字或特殊字符")
}
password = strings.ReplaceAll(password, `'`, `\'`)
+26 -8
View File
@@ -129,13 +129,27 @@ func (r *SafeController) GetFirewallRules(ctx http.Context) http.Response {
// AddFirewallRule 添加防火墙规则
func (r *SafeController) AddFirewallRule(ctx http.Context) http.Response {
if !r.firewallStatus() {
return Error(ctx, http.StatusBadRequest, "防火墙未启动")
return Error(ctx, http.StatusUnprocessableEntity, "防火墙未启动")
}
port := ctx.Request().InputInt("port", 0)
protocol := ctx.Request().Input("protocol", "")
if port == 0 || protocol == "" {
return Error(ctx, http.StatusBadRequest, "参数错误")
port := ctx.Request().Input("port")
protocol := ctx.Request().Input("protocol")
if port == "" || protocol == "" || (protocol != "tcp" && protocol != "udp") {
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
// 端口有 2 种写法,一种是 80-443,一种是 80
if strings.Contains(port, "-") {
ports := strings.Split(port, "-")
startPort := cast.ToInt(ports[0])
endPort := cast.ToInt(ports[1])
if startPort < 1 || startPort > 65535 || endPort < 1 || endPort > 65535 || startPort > endPort {
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
} else {
port := cast.ToInt(port)
if port < 1 || port > 65535 {
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
}
if tools.IsRHEL() {
@@ -143,6 +157,10 @@ func (r *SafeController) AddFirewallRule(ctx http.Context) http.Response {
tools.Exec("firewall-cmd --add-port=" + cast.ToString(port) + "/" + protocol + " --permanent 2>&1")
tools.Exec("firewall-cmd --reload")
} else {
// ufw 需要替换 - 为 : 添加
if strings.Contains(port, "-") {
port = strings.ReplaceAll(port, "-", ":")
}
tools.Exec("ufw delete allow " + cast.ToString(port) + "/" + protocol)
tools.Exec("ufw allow " + cast.ToString(port) + "/" + protocol)
tools.Exec("ufw reload")
@@ -154,13 +172,13 @@ func (r *SafeController) AddFirewallRule(ctx http.Context) http.Response {
// DeleteFirewallRule 删除防火墙规则
func (r *SafeController) DeleteFirewallRule(ctx http.Context) http.Response {
if !r.firewallStatus() {
return Error(ctx, http.StatusBadRequest, "防火墙未启动")
return Error(ctx, http.StatusUnprocessableEntity, "防火墙未启动")
}
port := ctx.Request().InputInt("port", 0)
protocol := ctx.Request().Input("protocol", "")
if port == 0 || protocol == "" {
return Error(ctx, http.StatusBadRequest, "参数错误")
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
if tools.IsRHEL() {
@@ -247,7 +265,7 @@ func (r *SafeController) GetSshPort(ctx http.Context) http.Response {
func (r *SafeController) SetSshPort(ctx http.Context) http.Response {
port := ctx.Request().InputInt("port", 0)
if port == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
oldPort := tools.Exec("cat /etc/ssh/sshd_config | grep 'Port ' | awk '{print $2}'")
+24 -10
View File
@@ -1,6 +1,8 @@
package controllers
import (
"regexp"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"panel/pkg/tools"
@@ -28,25 +30,33 @@ func (r *SettingController) List(ctx http.Context) http.Response {
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
var result = make(map[string]string)
for _, setting := range settings {
if setting.Key == models.SettingKeyMysqlRootPassword {
continue
}
result[setting.Key] = setting.Value
type data struct {
Name string `json:"name"`
Username string `json:"username"`
Password string `json:"password"`
Email string `json:"email"`
Port string `json:"port"`
Entrance string `json:"entrance"`
WebsitePath string `json:"website_path"`
BackupPath string `json:"backup_path"`
}
var result data
result.Name = r.setting.Get(models.SettingKeyName)
result.Entrance = r.setting.Get(models.SettingKeyEntrance)
result.WebsitePath = r.setting.Get(models.SettingKeyWebsitePath)
result.BackupPath = r.setting.Get(models.SettingKeyBackupPath)
var user models.User
err = facades.Auth().User(ctx, &user)
if err != nil {
facades.Log().Error("[面板][SettingController] 获取用户失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
result["username"] = user.Username
result["email"] = user.Email
result.Username = user.Username
result.Email = user.Email
result["port"] = tools.Exec(`cat /www/panel/panel.conf | grep APP_PORT | awk -F '=' '{print $2}' | tr -d '\n'`)
result.Port = tools.Exec(`cat /www/panel/panel.conf | grep APP_PORT | awk -F '=' '{print $2}' | tr -d '\n'`)
return Success(ctx, result)
}
@@ -62,6 +72,10 @@ func (r *SettingController) Save(ctx http.Context) http.Response {
email := ctx.Request().Input("email")
password := ctx.Request().Input("password")
if !regexp.MustCompile(`^/[^/]*[^/]$`).MatchString(entrance) || entrance == "/api" {
return Error(ctx, http.StatusUnprocessableEntity, "入口格式错误")
}
err := r.setting.Set(models.SettingKeyName, name)
if err != nil {
facades.Log().Error("[面板][SettingController] 保存设置失败 ", err)
+4 -3
View File
@@ -10,6 +10,7 @@ import (
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/gorilla/websocket"
"github.com/spf13/cast"
"panel/app/models"
"panel/app/services"
@@ -40,7 +41,7 @@ func (r *SshController) GetInfo(ctx http.Context) http.Response {
return Success(ctx, http.Json{
"host": host,
"port": port,
"port": cast.ToInt(port),
"user": user,
"password": password,
})
@@ -55,10 +56,10 @@ func (r *SshController) UpdateInfo(ctx http.Context) http.Response {
"password": "required",
})
if err != nil {
return Error(ctx, http.StatusBadRequest, err.Error())
return Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return Error(ctx, http.StatusBadRequest, validator.Errors().One())
return Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
host := ctx.Request().Input("host")
+13 -10
View File
@@ -34,16 +34,13 @@ func (r *TaskController) Status(ctx http.Context) http.Response {
// List 获取任务列表
func (r *TaskController) List(ctx http.Context) http.Response {
status := ctx.Request().Query("status")
if len(status) == 0 {
status = models.TaskStatusWaiting
}
var tasks []models.Task
var total int64
err := facades.Orm().Query().Where("status", status).Paginate(ctx.Request().QueryInt("page"), ctx.Request().QueryInt("limit"), &tasks, &total)
err := facades.Orm().Query().Paginate(ctx.Request().QueryInt("page", 1), ctx.Request().QueryInt("limit", 10), &tasks, &total)
if err != nil {
facades.Log().Error("[面板][TaskController] 查询任务列表失败 ", err)
facades.Log().With(map[string]any{
"error": err.Error(),
}).Error("[面板][TaskController] 查询任务列表失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
@@ -58,11 +55,14 @@ func (r *TaskController) Log(ctx http.Context) http.Response {
var task models.Task
err := facades.Orm().Query().Where("id", ctx.Request().QueryInt("id")).FirstOrFail(&task)
if err != nil {
facades.Log().Error("[面板][TaskController] 查询任务失败 ", err)
facades.Log().With(map[string]any{
"id": ctx.Request().QueryInt("id"),
"error": err.Error(),
}).Error("[面板][TaskController] 查询任务失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
log := tools.Exec("tail -n 30 " + task.Log)
log := tools.Exec("tail -n 1000 " + task.Log)
return Success(ctx, log)
}
@@ -72,7 +72,10 @@ func (r *TaskController) Delete(ctx http.Context) http.Response {
var task models.Task
_, err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).Delete(&task)
if err != nil {
facades.Log().Error("[面板][TaskController] 删除任务失败 ", err)
facades.Log().With(map[string]any{
"id": ctx.Request().QueryInt("id"),
"error": err.Error(),
}).Error("[面板][TaskController] 删除任务失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
+10 -4
View File
@@ -26,7 +26,7 @@ func (r *UserController) Login(ctx http.Context) http.Response {
return Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if errors != nil {
return Error(ctx, http.StatusUnprocessableEntity, errors.All())
return Error(ctx, http.StatusUnprocessableEntity, errors.One())
}
var user models.User
@@ -61,12 +61,18 @@ func (r *UserController) Login(ctx http.Context) http.Response {
// Info 用户信息
func (r *UserController) Info(ctx http.Context) http.Response {
user, ok := ctx.Value("user").(models.User)
if !ok {
return Error(ctx, http.StatusUnauthorized, "登录已过期")
var user models.User
err := facades.Auth().User(ctx, &user)
if err != nil {
facades.Log().With(map[string]any{
"error": err.Error(),
}).Error("[面板][UserController] 查询用户信息失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, http.Json{
"id": user.ID,
"role": []string{"admin"},
"username": user.Username,
"email": user.Email,
})
+44 -39
View File
@@ -30,8 +30,8 @@ func NewWebsiteController() *WebsiteController {
// List 网站列表
func (c *WebsiteController) List(ctx http.Context) http.Response {
limit := ctx.Request().QueryInt("limit")
page := ctx.Request().QueryInt("page")
limit := ctx.Request().QueryInt("limit", 10)
page := ctx.Request().QueryInt("page", 1)
total, websites, err := c.website.List(page, limit)
if err != nil {
@@ -53,7 +53,8 @@ func (c *WebsiteController) Add(ctx http.Context) http.Response {
}
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|regex:^[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)*$|not_exists:websites,name",
"domain": "required",
"domains": "required|slice",
"ports": "required|slice",
"php": "required",
"db": "bool",
"db_type": "required_if:db,true",
@@ -62,15 +63,16 @@ func (c *WebsiteController) Add(ctx http.Context) http.Response {
"db_password": "required_if:db,true",
})
if err != nil {
return Error(ctx, http.StatusBadRequest, err.Error())
return Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return Error(ctx, http.StatusBadRequest, validator.Errors().One())
return Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
var website services.PanelWebsite
website.Name = ctx.Request().Input("name")
website.Domain = ctx.Request().Input("domain")
website.Domains = ctx.Request().InputArray("domains")
website.Ports = ctx.Request().InputArray("ports")
website.Php = ctx.Request().InputInt("php")
website.Db = ctx.Request().InputBool("db")
website.DbType = ctx.Request().Input("db_type")
@@ -148,7 +150,7 @@ func (c *WebsiteController) GetConfig(ctx http.Context) http.Response {
}
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
config, err := c.website.GetConfig(id)
@@ -167,14 +169,13 @@ func (c *WebsiteController) SaveConfig(ctx http.Context) http.Response {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"id": "required",
"domains": "required",
"ports": "required",
"domains": "required|slice",
"ports": "required|slice",
"hsts": "bool",
"ssl": "bool",
"http_redirect": "bool",
"open_basedir": "bool",
"waf": "required",
"waf": "bool",
"waf_cache": "required",
"waf_mode": "required",
"waf_cc_deny": "required",
@@ -187,19 +188,19 @@ func (c *WebsiteController) SaveConfig(ctx http.Context) http.Response {
"ssl_certificate_key": "required_if:ssl,true",
})
if err != nil {
return Error(ctx, http.StatusBadRequest, err.Error())
return Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return Error(ctx, http.StatusBadRequest, validator.Errors().One())
return Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
var website models.Website
if facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&website) != nil {
return Error(ctx, http.StatusBadRequest, "网站不存在")
return Error(ctx, http.StatusUnprocessableEntity, "网站不存在")
}
if !website.Status {
return Error(ctx, http.StatusBadRequest, "网站已停用,请先启用")
return Error(ctx, http.StatusUnprocessableEntity, "网站已停用,请先启用")
}
// 原文
@@ -213,15 +214,15 @@ func (c *WebsiteController) SaveConfig(ctx http.Context) http.Response {
// 目录
path := ctx.Request().Input("path")
if !tools.Exists(path) {
return Error(ctx, http.StatusBadRequest, "网站目录不存在")
return Error(ctx, http.StatusUnprocessableEntity, "网站目录不存在")
}
website.Path = path
// 域名
domain := "server_name"
domains := strings.Split(ctx.Request().Input("domains"), "\n")
domains := ctx.Request().InputArray("domains")
if len(domains) == 0 {
return Error(ctx, http.StatusBadRequest, "域名不能为空")
return Error(ctx, http.StatusUnprocessableEntity, "域名不能为空")
}
for _, v := range domains {
if v == "" {
@@ -232,19 +233,19 @@ func (c *WebsiteController) SaveConfig(ctx http.Context) http.Response {
domain += ";"
domainConfigOld := tools.Cut(raw, "# server_name标记位开始", "# server_name标记位结束")
if len(strings.TrimSpace(domainConfigOld)) == 0 {
return Error(ctx, http.StatusBadRequest, "配置文件中缺少server_name标记位")
return Error(ctx, http.StatusUnprocessableEntity, "配置文件中缺少server_name标记位")
}
raw = strings.Replace(raw, domainConfigOld, "\n "+domain+"\n ", -1)
// 端口
var port strings.Builder
ports := strings.Split(ctx.Request().Input("ports"), "\n")
ports := ctx.Request().InputArray("ports")
if len(ports) == 0 {
return Error(ctx, http.StatusBadRequest, "端口不能为空")
return Error(ctx, http.StatusUnprocessableEntity, "端口不能为空")
}
for i, v := range ports {
if _, err := strconv.Atoi(v); err != nil && v != "443 ssl http2" {
return Error(ctx, http.StatusBadRequest, "端口格式错误")
return Error(ctx, http.StatusUnprocessableEntity, "端口格式错误")
}
if v == "443" && ctx.Request().InputBool("ssl") {
v = "443 ssl http2"
@@ -257,18 +258,18 @@ func (c *WebsiteController) SaveConfig(ctx http.Context) http.Response {
}
portConfigOld := tools.Cut(raw, "# port标记位开始", "# port标记位结束")
if len(strings.TrimSpace(portConfigOld)) == 0 {
return Error(ctx, http.StatusBadRequest, "配置文件中缺少port标记位")
return Error(ctx, http.StatusUnprocessableEntity, "配置文件中缺少port标记位")
}
raw = strings.Replace(raw, portConfigOld, "\n"+port.String()+"\n ", -1)
// 运行目录
root := tools.Cut(raw, "# root标记位开始", "# root标记位结束")
if len(strings.TrimSpace(root)) == 0 {
return Error(ctx, http.StatusBadRequest, "配置文件中缺少root标记位")
return Error(ctx, http.StatusUnprocessableEntity, "配置文件中缺少root标记位")
}
match := regexp.MustCompile(`root\s+(.+);`).FindStringSubmatch(root)
if len(match) != 2 {
return Error(ctx, http.StatusBadRequest, "配置文件中root标记位格式错误")
return Error(ctx, http.StatusUnprocessableEntity, "配置文件中root标记位格式错误")
}
rootNew := strings.Replace(root, match[1], ctx.Request().Input("root"), -1)
raw = strings.Replace(raw, root, rootNew, -1)
@@ -276,11 +277,11 @@ func (c *WebsiteController) SaveConfig(ctx http.Context) http.Response {
// 默认文件
index := tools.Cut(raw, "# index标记位开始", "# index标记位结束")
if len(strings.TrimSpace(index)) == 0 {
return Error(ctx, http.StatusBadRequest, "配置文件中缺少index标记位")
return Error(ctx, http.StatusUnprocessableEntity, "配置文件中缺少index标记位")
}
match = regexp.MustCompile(`index\s+(.+);`).FindStringSubmatch(index)
if len(match) != 2 {
return Error(ctx, http.StatusBadRequest, "配置文件中index标记位格式错误")
return Error(ctx, http.StatusUnprocessableEntity, "配置文件中index标记位格式错误")
}
indexNew := strings.Replace(index, match[1], ctx.Request().Input("index"), -1)
raw = strings.Replace(raw, index, indexNew, -1)
@@ -299,12 +300,16 @@ func (c *WebsiteController) SaveConfig(ctx http.Context) http.Response {
}
// WAF
waf := ctx.Request().Input("waf")
waf := ctx.Request().InputBool("waf")
wafStr := "off"
if waf {
wafStr = "on"
}
wafMode := ctx.Request().Input("waf_mode", "DYNAMIC")
wafCcDeny := ctx.Request().Input("waf_cc_deny", "rate=1000r/m duration=60m")
wafCache := ctx.Request().Input("waf_cache", "capacity=50")
wafConfig := `# waf标记位开始
waf ` + waf + `;
waf ` + wafStr + `;
waf_rule_path /www/server/openresty/ngx_waf/assets/rules/;
waf_mode ` + wafMode + `;
waf_cc_deny ` + wafCcDeny + `;
@@ -391,7 +396,7 @@ func (c *WebsiteController) ClearLog(ctx http.Context) http.Response {
}
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
website := models.Website{}
@@ -410,7 +415,7 @@ func (c *WebsiteController) ClearLog(ctx http.Context) http.Response {
func (c *WebsiteController) UpdateRemark(ctx http.Context) http.Response {
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
website := models.Website{}
@@ -445,7 +450,7 @@ func (c *WebsiteController) BackupList(ctx http.Context) http.Response {
func (c *WebsiteController) CreateBackup(ctx http.Context) http.Response {
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
website := models.Website{}
@@ -468,7 +473,7 @@ func (c *WebsiteController) CreateBackup(ctx http.Context) http.Response {
func (c *WebsiteController) UploadBackup(ctx http.Context) http.Response {
file, err := ctx.Request().File("file")
if err != nil {
return Error(ctx, http.StatusBadRequest, "上传文件失败")
return Error(ctx, http.StatusUnprocessableEntity, "上传文件失败")
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/website"
@@ -479,7 +484,7 @@ func (c *WebsiteController) UploadBackup(ctx http.Context) http.Response {
name := file.GetClientOriginalName()
_, err = file.StoreAs(backupPath, name)
if err != nil {
return Error(ctx, http.StatusBadRequest, "上传文件失败")
return Error(ctx, http.StatusUnprocessableEntity, "上传文件失败")
}
return Success(ctx, "上传文件成功")
@@ -489,11 +494,11 @@ func (c *WebsiteController) UploadBackup(ctx http.Context) http.Response {
func (c *WebsiteController) RestoreBackup(ctx http.Context) http.Response {
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
fileName := ctx.Request().Input("name")
if len(fileName) == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
website := models.Website{}
@@ -516,7 +521,7 @@ func (c *WebsiteController) RestoreBackup(ctx http.Context) http.Response {
func (c *WebsiteController) DeleteBackup(ctx http.Context) http.Response {
fileName := ctx.Request().Input("name")
if len(fileName) == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/website"
@@ -539,7 +544,7 @@ func (c *WebsiteController) ResetConfig(ctx http.Context) http.Response {
}
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
website := models.Website{}
@@ -629,7 +634,7 @@ func (c *WebsiteController) Status(ctx http.Context) http.Response {
}
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
return Error(ctx, http.StatusUnprocessableEntity, "参数错误")
}
website := models.Website{}
+3 -17
View File
@@ -6,16 +6,14 @@ import (
"github.com/goravel/framework/auth"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"panel/app/models"
)
// Jwt 确保通过 JWT 鉴权
func Jwt() http.Middleware {
return func(ctx http.Context) {
token := ctx.Request().Header("access_token", ctx.Request().Input("access_token", ctx.Request().Header("Sec-WebSocket-Protocol")))
token := ctx.Request().Header("Authorization", ctx.Request().Header("Sec-WebSocket-Protocol"))
if len(token) == 0 {
ctx.Request().AbortWithStatusJson(http.StatusUnauthorized, http.Json{
ctx.Request().AbortWithStatusJson(http.StatusOK, http.Json{
"code": 401,
"message": "未登录",
})
@@ -27,7 +25,7 @@ func Jwt() http.Middleware {
if errors.Is(err, auth.ErrorTokenExpired) {
token, err = facades.Auth().Refresh(ctx)
if err != nil {
// Refresh time exceeded
// 到达刷新时间上限
ctx.Request().AbortWithStatusJson(http.StatusOK, http.Json{
"code": 401,
"message": "登录已过期",
@@ -45,18 +43,6 @@ func Jwt() http.Middleware {
}
}
// 取出用户信息
var user models.User
if err := facades.Auth().User(ctx, &user); err != nil {
ctx.Request().AbortWithStatusJson(http.StatusForbidden, http.Json{
"code": 403,
"message": "用户不存在",
})
return
}
ctx.WithValue("user", user)
ctx.Response().Header("Authorization", token)
ctx.Request().Next()
}
+17 -4
View File
@@ -1,17 +1,30 @@
package middleware
import (
"fmt"
"github.com/gin-contrib/static"
contractshttp "github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/gin"
"panel/app/services"
)
func Static() contractshttp.Middleware {
return func(ctx contractshttp.Context) {
static.Serve(services.NewSettingImpl().Get("entrance", "/"), static.LocalFile("/www/panel/public", false))(ctx.(*gin.Context).Instance())
func Static() http.Middleware {
return func(ctx http.Context) {
// 自动纠正 URL 格式
if ctx.Request().Path() == services.NewSettingImpl().Get("entrance", "/") && ctx.Request().Path() != "/" {
// ctx.Response().Redirect(http.StatusFound, ctx.Request().Path()+"/")
ctx.Response().Writer().WriteHeader(http.StatusFound)
_, err := ctx.Response().Writer().Write([]byte(fmt.Sprintf(`<html><head><meta http-equiv="refresh" content="0;url=%s/"></head></html>`, ctx.Request().Path())))
if err != nil {
return
}
ctx.Response().Flush()
return
}
static.Serve(services.NewSettingImpl().Get("entrance", "/"), static.LocalFile("public", false))(ctx.(*gin.Context).Instance())
ctx.Request().Next()
}
}
+1 -1
View File
@@ -9,5 +9,5 @@ var (
Excludes = []string{"mysql80"}
Install = `bash /www/panel/scripts/mysql/install.sh 57`
Uninstall = `bash /www/panel/scripts/mysql/uninstall.sh 57`
Update = `bash /www/panel/scripts/mysql/update.sh 57"`
Update = `bash /www/panel/scripts/mysql/update.sh 57`
)
+1 -1
View File
@@ -2,7 +2,7 @@ package postgresql15
var (
Name = "PostgreSQL-15"
Description = "PostgreSQL 是开源的对象 - 关系数据库数据库管理系统,在类似 BSD 许可与 MIT 许可的 PostgreSQL 许可下发行。"
Description = "PostgreSQL 是世界上最先进的开源关系数据库,在类似 BSD 与 MIT 许可的 PostgreSQL 许可下发行。"
Slug = "postgresql15"
Version = "15.4"
Requires = []string{}
+1 -1
View File
@@ -2,7 +2,7 @@ package postgresql16
var (
Name = "PostgreSQL-16"
Description = "PostgreSQL 是开源的对象 - 关系数据库数据库管理系统,在类似 BSD 许可与 MIT 许可的 PostgreSQL 许可下发行。"
Description = "PostgreSQL 是世界上最先进的开源关系数据库,在类似 BSD 与 MIT 许可的 PostgreSQL 许可下发行。"
Slug = "postgresql16"
Version = "16.0"
Requires = []string{}
+98 -43
View File
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"github.com/goravel/framework/facades"
@@ -21,32 +22,34 @@ type Website interface {
Add(website PanelWebsite) (models.Website, error)
Delete(id int) error
GetConfig(id int) (WebsiteSetting, error)
GetConfigByName(name string) (WebsiteSetting, error)
}
type PanelWebsite struct {
Name string `json:"name"`
Status bool `json:"status"`
Domain string `json:"domain"`
Path string `json:"path"`
Php int `json:"php"`
Ssl bool `json:"ssl"`
Remark string `json:"remark"`
Db bool `json:"db"`
DbType string `json:"db_type"`
DbName string `json:"db_name"`
DbUser string `json:"db_user"`
DbPassword string `json:"db_password"`
Name string `json:"name"`
Status bool `json:"status"`
Domains []string `json:"domains"`
Ports []string `json:"ports"`
Path string `json:"path"`
Php int `json:"php"`
Ssl bool `json:"ssl"`
Remark string `json:"remark"`
Db bool `json:"db"`
DbType string `json:"db_type"`
DbName string `json:"db_name"`
DbUser string `json:"db_user"`
DbPassword string `json:"db_password"`
}
// WebsiteSetting 网站设置
type WebsiteSetting struct {
Name string `json:"name"`
Ports []string `json:"ports"`
Domains []string `json:"domains"`
Ports []string `json:"ports"`
Root string `json:"root"`
Path string `json:"path"`
Index string `json:"index"`
Php int `json:"php"`
Php string `json:"php"`
OpenBasedir bool `json:"open_basedir"`
Ssl bool `json:"ssl"`
SslCertificate string `json:"ssl_certificate"`
@@ -107,7 +110,6 @@ func (r *WebsiteImpl) Add(website PanelWebsite) (models.Website, error) {
website.Ssl = false
website.Status = true
website.Domain = strings.TrimSpace(website.Domain)
w := models.Website{
Name: website.Name,
@@ -126,44 +128,81 @@ func (r *WebsiteImpl) Add(website PanelWebsite) (models.Website, error) {
index := `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>耗子Linux面板</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>耗子Linux面板</title>
<style>
body {
background-color: #f9f9f9;
margin: 0;
padding: 0;
}
.container {
max-width: 800px;
margin: 2em auto;
background-color: #ffffff;
padding: 20px;
border-radius: 12px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
h1 {
font-size: 2.5em;
margin-top: 0;
margin-bottom: 20px;
text-align: center;
color: #333;
border-bottom: 2px solid #ddd;
padding-bottom: 0.5em;
}
p {
color: #555;
line-height: 1.8;
}
@media screen and (max-width: 768px) {
.container {
padding: 15px;
margin: 2em 15px;
}
h1 {
font-size: 1.8em;
}
}
</style>
</head>
<body>
<h1>耗子Linux面板</h1>
<p>这是耗子Linux面板的网站默认页面!</p>
<p>当您看到此页面,说明您的网站已创建成功。</p>
<div class="container">
<h1>耗子Linux面板</h1>
<p>这是耗子Linux面板的网站默认页面!</p>
<p>当您看到此页面,说明您的网站已创建成功。</p>
</div>
</body>
</html>
`
tools.Write(website.Path+"/index.html", index, 0644)
domainArr := strings.Split(website.Domain, "\n")
portList := ""
portArr := make(map[string]bool)
domainList := ""
for key, value := range domainArr {
temp := strings.Split(value, ":")
domainList += " " + temp[0]
portUsed := make(map[string]bool)
domainUsed := make(map[string]bool)
if len(temp) < 2 {
if _, ok := portArr["80"]; !ok {
if key == len(domainArr)-1 {
portList += " listen 80;"
} else {
portList += " listen 80;\n"
}
portArr["80"] = true
}
} else {
if _, ok := portArr[temp[1]]; !ok {
if key == len(domainArr)-1 {
portList += " listen " + temp[1] + ";"
} else {
portList += " listen " + temp[1] + ";\n"
}
portArr[temp[1]] = true
for i, port := range website.Ports {
if _, ok := portUsed[port]; !ok {
if i == len(website.Ports)-1 {
portList += " listen " + port + ";"
} else {
portList += " listen " + port + ";\n"
}
portUsed[port] = true
}
}
if len(website.Ports) == 0 {
portList += " listen 80;\n"
}
for _, domain := range website.Domains {
if _, ok := domainUsed[domain]; !ok {
domainList += " " + domain
domainUsed[domain] = true
}
}
@@ -243,6 +282,12 @@ server
tools.Exec(`/www/server/mysql/bin/mysql -uroot -p` + rootPassword + ` -e "GRANT ALL PRIVILEGES ON ` + website.DbName + `.* TO '` + website.DbUser + `'@'localhost';"`)
tools.Exec(`/www/server/mysql/bin/mysql -uroot -p` + rootPassword + ` -e "FLUSH PRIVILEGES;"`)
}
if website.Db && website.DbType == "postgresql" {
tools.Exec(`echo "CREATE DATABASE ` + website.DbName + `;" | su - postgres -c "psql"`)
tools.Exec(`echo "CREATE USER ` + website.DbUser + ` WITH PASSWORD '` + website.DbPassword + `';" | su - postgres -c "psql"`)
tools.Exec(`echo "ALTER DATABASE ` + website.DbName + ` OWNER TO ` + website.DbUser + `;" | su - postgres -c "psql"`)
tools.Exec(`echo "GRANT ALL PRIVILEGES ON DATABASE ` + website.DbName + ` TO ` + website.DbUser + `;" | su - postgres -c "psql"`)
}
return w, nil
}
@@ -282,7 +327,7 @@ func (r *WebsiteImpl) GetConfig(id int) (WebsiteSetting, error) {
setting.Name = website.Name
setting.Path = website.Path
setting.Ssl = website.Ssl
setting.Php = website.Php
setting.Php = strconv.Itoa(website.Php)
setting.Raw = config
ports := tools.Cut(config, "# port标记位开始", "# port标记位结束")
@@ -364,3 +409,13 @@ func (r *WebsiteImpl) GetConfig(id int) (WebsiteSetting, error) {
return setting, nil
}
// GetConfigByName 根据网站名称获取网站配置
func (r *WebsiteImpl) GetConfigByName(name string) (WebsiteSetting, error) {
var website models.Website
if err := facades.Orm().Query().Where("name", name).First(&website); err != nil {
return WebsiteSetting{}, err
}
return r.GetConfig(int(website.ID))
}
+1 -1
View File
@@ -8,6 +8,6 @@ func init() {
config := facades.Config()
config.Add("panel", map[string]any{
"name": "耗子Linux面板",
"version": "v2.0.45",
"version": "v2.1.3",
})
}
+12 -12
View File
@@ -3,21 +3,21 @@ module panel
go 1.18
require (
github.com/bytedance/sonic v1.10.1
github.com/bytedance/sonic v1.10.2
github.com/gertd/go-pluralize v0.2.1
github.com/gin-contrib/static v0.0.1
github.com/gookit/color v1.5.4
github.com/goravel/framework v1.13.1
github.com/goravel/framework v1.13.2
github.com/goravel/gin v1.1.5
github.com/gorilla/websocket v1.5.0
github.com/iancoleman/strcase v0.3.0
github.com/imroc/req/v3 v3.42.0
github.com/imroc/req/v3 v3.42.1
github.com/mojocn/base64Captcha v1.3.5
github.com/shirou/gopsutil v3.21.11+incompatible
github.com/spf13/cast v1.5.1
github.com/stretchr/testify v1.8.4
golang.org/x/crypto v0.13.0
golang.org/x/exp v0.0.0-20230905200255-921286631fa9
golang.org/x/crypto v0.14.0
golang.org/x/exp v0.0.0-20231006140011-7918f672742d
)
require (
@@ -73,7 +73,7 @@ require (
github.com/golang-jwt/jwt/v4 v4.5.0 // indirect
github.com/golang-jwt/jwt/v5 v5.0.0 // indirect
github.com/golang-migrate/migrate/v4 v4.16.2 // indirect
github.com/golang-module/carbon/v2 v2.2.6 // indirect
github.com/golang-module/carbon/v2 v2.2.8 // indirect
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
github.com/golang-sql/sqlexp v0.1.0 // indirect
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
@@ -170,19 +170,19 @@ require (
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/arch v0.5.0 // indirect
golang.org/x/image v0.11.0 // indirect
golang.org/x/mod v0.12.0 // indirect
golang.org/x/net v0.15.0 // indirect
golang.org/x/mod v0.13.0 // indirect
golang.org/x/net v0.16.0 // indirect
golang.org/x/oauth2 v0.10.0 // indirect
golang.org/x/sync v0.3.0 // indirect
golang.org/x/sys v0.12.0 // indirect
golang.org/x/sync v0.4.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
golang.org/x/tools v0.13.0 // indirect
golang.org/x/tools v0.14.0 // indirect
google.golang.org/api v0.126.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20230803162519-f966b187b2e5 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20230726155614-23370e0ffb3e // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d // indirect
google.golang.org/grpc v1.58.0 // indirect
google.golang.org/grpc v1.58.2 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
+25 -25
View File
@@ -87,8 +87,8 @@ github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b/go.mod h1:H0wQ
github.com/brianvoe/gofakeit/v6 v6.23.2 h1:lVde18uhad5wII/f5RMVFLtdQNE0HaGFuBUXmYKk8i8=
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM=
github.com/bytedance/sonic v1.10.1 h1:7a1wuFXL1cMy7a3f7/VFcEtriuXQnUBhtoVfOZiaysc=
github.com/bytedance/sonic v1.10.1/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=
github.com/bytedance/sonic v1.10.2 h1:GQebETVBxYB7JGWJtLBi07OVzWwt+8dWA00gEVW2ZFE=
github.com/bytedance/sonic v1.10.2/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=
github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM=
github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
@@ -244,8 +244,8 @@ github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJ
github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang-migrate/migrate/v4 v4.16.2 h1:8coYbMKUyInrFk1lfGfRovTLAW7PhWp8qQDT2iKfuoA=
github.com/golang-migrate/migrate/v4 v4.16.2/go.mod h1:pfcJX4nPHaVdc5nmdCikFBWtm+UBpiZjRNNsyBbp0/o=
github.com/golang-module/carbon/v2 v2.2.6 h1:4nHkIx7A7d+aoRDAGLwxZEJWAAZpmH5Bm/pVUl58FXI=
github.com/golang-module/carbon/v2 v2.2.6/go.mod h1:XDALX7KgqmHk95xyLeaqX9/LJGbfLATyruTziq68SZ8=
github.com/golang-module/carbon/v2 v2.2.8 h1:a1VxHHKAR7fc1ho7sYXhS1s5S4x7+oqAf2EY5p8C46A=
github.com/golang-module/carbon/v2 v2.2.8/go.mod h1:XDALX7KgqmHk95xyLeaqX9/LJGbfLATyruTziq68SZ8=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A=
@@ -354,8 +354,8 @@ github.com/goravel/file-rotatelogs v0.0.0-20211215053220-2ab31dd9575c h1:obhFK91
github.com/goravel/file-rotatelogs v0.0.0-20211215053220-2ab31dd9575c/go.mod h1:YSWsLXlG16u5CWFaXNZHhEQD10+NwF3xfgDV816OwLE=
github.com/goravel/file-rotatelogs/v2 v2.4.1 h1:ogkeIFcTHSBRUBpZYiyJbpul8hkVXxHPuDbOaP78O1M=
github.com/goravel/file-rotatelogs/v2 v2.4.1/go.mod h1:euk9qr52WrzM8ICs1hecFcR4CZ/ZZOPdacHfvHgbOf0=
github.com/goravel/framework v1.13.1 h1:3VM0ZEqbPtHN5llrtB1Mtw9Vr4VK/wPcupzNU7dreSs=
github.com/goravel/framework v1.13.1/go.mod h1:CKsMPL8D72wKEZILHUo8Zzi6I9GDW424GpoLAMlB9b8=
github.com/goravel/framework v1.13.2 h1:7BRNihQ/ZNeA384941yg8zRytXRXkkStksXNyyUEgQI=
github.com/goravel/framework v1.13.2/go.mod h1:BOUTIwzhOMyKNXaxSYbVB74NkmbS2xv1W1fPRv9eDws=
github.com/goravel/gin v1.1.5 h1:HWVBxSDHsfpq2lWvuagQVMJlCwznf6ifc71IYEo3sCE=
github.com/goravel/gin v1.1.5/go.mod h1:FxnhnqcMJk/Sk6jA/xcXn6tHtFzayNXeFuw7GnLORMY=
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
@@ -384,8 +384,8 @@ github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4=
github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY=
github.com/imroc/req/v3 v3.42.0 h1:g7wWva3aIJI02mrnqmXe0N5SVkXHQPsYN3Tmw2ZHn3U=
github.com/imroc/req/v3 v3.42.0/go.mod h1:W7dOrfQORA9nFoj+CafIZ6P5iyk+rWdbp2sffOAvABU=
github.com/imroc/req/v3 v3.42.1 h1:g82SouLvX7pqwqJjpQJYrVvuI+LOycWhyuwxtLlyQJk=
github.com/imroc/req/v3 v3.42.1/go.mod h1:W7dOrfQORA9nFoj+CafIZ6P5iyk+rWdbp2sffOAvABU=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
@@ -680,8 +680,8 @@ golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0=
golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -692,8 +692,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190501045829-6d32002ffd75/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
@@ -723,8 +723,8 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
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.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.13.0 h1:I/DsJXRlw/8l/0c24sM9yb0T4z9liZTduXvdAWYiysY=
golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
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-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -768,8 +768,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.15.0 h1:ugBLEUaxABaB5AJqW9enI0ACdci2RUd4eP51NTBvuJ8=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.16.0 h1:7eBu7KsSvFDtSXUIDbh3aqlK4DPsZ1rByC8PFfBThos=
golang.org/x/net v0.16.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -796,8 +796,8 @@ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/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.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ=
golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -862,14 +862,14 @@ 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.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
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.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.12.0 h1:/ZfYdc3zq+q02Rv9vGqTeSItdzZTSNDmfTi0mBAuidU=
golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -949,8 +949,8 @@ golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
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.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.14.0 h1:jvNa2pY0M4r62jkRQ6RwEZZyPcymeL9XZMLBbV7U2nc=
golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -1049,8 +1049,8 @@ google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA5
google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU=
google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU=
google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ=
google.golang.org/grpc v1.58.0 h1:32JY8YpPMSR45K+c3o6b8VL73V+rR8k+DeMIr4vRH8o=
google.golang.org/grpc v1.58.0/go.mod h1:tgX3ZQDlNJGU96V6yHh1T/JeoBQ2TXdr43YbYSsCJk0=
google.golang.org/grpc v1.58.2 h1:SXUpjxeVF3FKrTYQI4f4KvbGD5u2xccdYdurwowix5I=
google.golang.org/grpc v1.58.2/go.mod h1:tgX3ZQDlNJGU96V6yHh1T/JeoBQ2TXdr43YbYSsCJk0=
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=
+11 -10
View File
@@ -1,17 +1,18 @@
/*
Copyright 2022 HaoZi Technology Co., Ltd.
Copyright (C) 2022 - now HaoZi Technology Co., Ltd.
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
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
http://www.apache.org/licenses/LICENSE-2.0
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
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.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package main
+1 -1
View File
@@ -19,5 +19,5 @@ func IsRHEL() bool {
// IsArm 判断是否是 ARM 架构
func IsArm() bool {
return runtime.GOARCH == "arm"
return runtime.GOARCH == "arm" || runtime.GOARCH == "arm64"
}
+21 -3
View File
@@ -1,12 +1,14 @@
package tools
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/goravel/framework/facades"
"github.com/goravel/framework/support"
)
// Write 写入文件
@@ -52,7 +54,13 @@ func Exec(shell string) string {
output, err := cmd.CombinedOutput()
if err != nil {
facades.Log().Errorf("[面板][Helpers] 执行命令 %s 失败: %s", shell, err.Error())
if support.Env == support.EnvTest {
fmt.Println(string(output))
fmt.Println(err.Error())
panic(err)
} else {
facades.Log().Errorf("[面板][Helpers] 执行命令 %s 失败: %s", shell, err.Error())
}
return ""
}
@@ -65,13 +73,23 @@ func ExecAsync(shell string) {
err := cmd.Start()
if err != nil {
facades.Log().Errorf("[面板][Helpers] 执行命令 %s 失败: %s", shell, err.Error())
if support.Env == support.EnvTest {
fmt.Println(err.Error())
panic(err)
} else {
facades.Log().Errorf("[面板][Helpers] 执行命令 %s 失败: %s", shell, err.Error())
}
}
go func() {
err := cmd.Wait()
if err != nil {
facades.Log().Errorf("[面板][Helpers] 执行命令 %s 失败: %s", shell, err.Error())
if support.Env == support.EnvTest {
fmt.Println(err.Error())
panic(err)
} else {
facades.Log().Errorf("[面板][Helpers] 执行命令 %s 失败: %s", shell, err.Error())
}
}
}()
}
+272 -45
View File
@@ -3,13 +3,14 @@ package tools
import (
"errors"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/gookit/color"
"github.com/imroc/req/v3"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/host"
@@ -57,21 +58,122 @@ func GetMonitoringInfo() MonitoringInfo {
return res
}
// VersionCompare 版本比较
func VersionCompare(ver1, ver2, operator string) bool {
v1 := strings.TrimPrefix(ver1, "v")
v2 := strings.TrimPrefix(ver2, "v")
v1s := strings.Split(v1, ".")
v2s := strings.Split(v2, ".")
for len(v1s) < len(v2s) {
v1s = append(v1s, "0")
}
for len(v2s) < len(v1s) {
v2s = append(v2s, "0")
}
for i := 0; i < len(v1s); i++ {
if v1s[i] > v2s[i] {
return operator == ">" || operator == ">=" || operator == "!="
} else if v1s[i] < v2s[i] {
return operator == "<" || operator == "<=" || operator == "!="
}
}
return operator == "==" || operator == ">=" || operator == "<="
}
// GenerateVersions 获取版本列表
func GenerateVersions(start, end string) ([]string, error) {
var versions []string
start = strings.TrimPrefix(start, "v")
end = strings.TrimPrefix(end, "v")
startParts := strings.Split(start, ".")
endParts := strings.Split(end, ".")
if len(startParts) != 3 || len(endParts) != 3 {
return nil, fmt.Errorf("版本格式错误")
}
startMajor, err := strconv.Atoi(startParts[0])
if err != nil {
return nil, fmt.Errorf("无效的起始主版本号: %v", err)
}
startMinor, err := strconv.Atoi(startParts[1])
if err != nil {
return nil, fmt.Errorf("无效的起始次版本号: %v", err)
}
startPatch, err := strconv.Atoi(startParts[2])
if err != nil {
return nil, fmt.Errorf("无效的起始修订号: %v", err)
}
endMajor, err := strconv.Atoi(endParts[0])
if err != nil {
return nil, fmt.Errorf("无效的结束主版本号: %v", err)
}
endMinor, err := strconv.Atoi(endParts[1])
if err != nil {
return nil, fmt.Errorf("无效的结束次版本号: %v", err)
}
endPatch, err := strconv.Atoi(endParts[2])
if err != nil {
return nil, fmt.Errorf("无效的结束修订号: %v", err)
}
for major := startMajor; major <= endMajor; major++ {
for minor := 0; minor <= 99; minor++ {
for patch := 0; patch <= 99; patch++ {
if major == startMajor && minor < startMinor {
continue
}
if major == startMajor && minor == startMinor && patch <= startPatch {
continue
}
if major == endMajor && minor > endMinor {
return versions, nil
}
if major == endMajor && minor == endMinor && patch > endPatch {
return versions, nil
}
versions = append(versions, fmt.Sprintf("%d.%d.%d", major, minor, patch))
}
}
}
if len(versions) == 0 {
return []string{}, nil
}
return versions, nil
}
type PanelInfo struct {
Name string `json:"name"`
Version string `json:"version"`
DownloadUrl string `json:"download_url"`
Body string `json:"body"`
Date string `json:"date"`
Name string `json:"name"`
Version string `json:"version"`
DownloadName string `json:"download_name"`
DownloadUrl string `json:"download_url"`
Body string `json:"body"`
Date string `json:"date"`
Checksums string `json:"checksums"`
ChecksumsUrl string `json:"checksums_url"`
}
// GetLatestPanelVersion 获取最新版本
func GetLatestPanelVersion() (PanelInfo, error) {
var info PanelInfo
var output string
isChina := IsChina()
cmd := exec.Command("/bin/bash", "-c", "curl \"https://api.github.com/repos/haozi-team/panel/releases/latest\"")
output, err := cmd.Output()
if err != nil {
if isChina {
output = Exec(`curl -sSL "https://jihulab.com/api/v4/projects/haozi-team%2Fpanel/releases/permalink/latest"`)
} else {
output = Exec(`curl -sSL "https://api.github.com/repos/haozi-team/panel/releases/latest"`)
}
if len(output) == 0 {
return info, errors.New("获取最新版本失败")
}
@@ -80,7 +182,7 @@ func GetLatestPanelVersion() (PanelInfo, error) {
return info, errors.New("创建临时文件失败")
}
defer os.Remove(file.Name())
_, err = file.Write(output)
_, err = file.Write([]byte(output))
if err != nil {
return info, errors.New("写入临时文件失败")
}
@@ -90,41 +192,131 @@ func GetLatestPanelVersion() (PanelInfo, error) {
}
fileName := file.Name()
name := exec.Command("/bin/bash", "-c", "jq -r '.name' "+fileName)
version := exec.Command("/bin/bash", "-c", "jq -r '.tag_name' "+fileName)
body := exec.Command("/bin/bash", "-c", "jq -r '.body' "+fileName)
date := exec.Command("/bin/bash", "-c", "jq -r '.published_at' "+fileName)
nameOutput, _ := name.Output()
versionOutput, _ := version.Output()
bodyOutput, _ := body.Output()
dateOutput, _ := date.Output()
info.Name = strings.TrimSpace(string(nameOutput))
info.Version = strings.TrimSpace(string(versionOutput))
info.Body = strings.TrimSpace(string(bodyOutput))
info.Date = strings.TrimSpace(string(dateOutput))
if IsArm() {
downloadUrl := exec.Command("/bin/bash", "-c", "jq -r '.assets[] | select(.name | contains(\"arm64\")) | .browser_download_url' "+fileName)
downloadUrlOutput, _ := downloadUrl.Output()
info.DownloadUrl = strings.TrimSpace(string(downloadUrlOutput))
var name, version, body, date, downloadName, downloadUrl, checksums, checksumsUrl string
if isChina {
name = Exec("jq -r '.name' " + fileName)
version = Exec("jq -r '.tag_name' " + fileName)
body = Exec("jq -r '.description' " + fileName)
date = Exec("jq -r '.created_at' " + fileName)
checksums = Exec("jq -r '.assets.links[] | select(.name | contains(\"checksums\")) | .name' " + fileName)
checksumsUrl = Exec("jq -r '.assets.links[] | select(.name | contains(\"checksums\")) | .direct_asset_url' " + fileName)
if IsArm() {
downloadName = Exec("jq -r '.assets.links[] | select(.name | contains(\"arm64\")) | .name' " + fileName)
downloadUrl = Exec("jq -r '.assets.links[] | select(.name | contains(\"arm64\")) | .direct_asset_url' " + fileName)
} else {
downloadName = Exec("jq -r '.assets.links[] | select(.name | contains(\"amd64v2\")) | .name' " + fileName)
downloadUrl = Exec("jq -r '.assets.links[] | select(.name | contains(\"amd64v2\")) | .direct_asset_url' " + fileName)
}
} else {
downloadUrl := exec.Command("/bin/bash", "-c", "jq -r '.assets[] | select(.name | contains(\"amd64v2\")) | .browser_download_url' "+fileName)
downloadUrlOutput, _ := downloadUrl.Output()
info.DownloadUrl = strings.TrimSpace(string(downloadUrlOutput))
name = Exec("jq -r '.name' " + fileName)
version = Exec("jq -r '.tag_name' " + fileName)
body = Exec("jq -r '.body' " + fileName)
date = Exec("jq -r '.published_at' " + fileName)
checksums = Exec("jq -r '.assets[] | select(.name | contains(\"checksums\")) | .name' " + fileName)
checksumsUrl = Exec("jq -r '.assets[] | select(.name | contains(\"checksums\")) | .browser_download_url' " + fileName)
if IsArm() {
downloadName = Exec("jq -r '.assets[] | select(.name | contains(\"arm64\")) | .name' " + fileName)
downloadUrl = Exec("jq -r '.assets[] | select(.name | contains(\"arm64\")) | .browser_download_url' " + fileName)
} else {
downloadName = Exec("jq -r '.assets[] | select(.name | contains(\"amd64v2\")) | .name' " + fileName)
downloadUrl = Exec("jq -r '.assets[] | select(.name | contains(\"amd64v2\")) | .browser_download_url' " + fileName)
}
}
info.Name = name
info.Version = version
info.Body = body
info.Date = date
info.DownloadName = downloadName
info.DownloadUrl = downloadUrl
info.Checksums = checksums
info.ChecksumsUrl = checksumsUrl
return info, nil
}
// GetPanelVersion 获取指定面板版本
func GetPanelVersion(version string) (PanelInfo, error) {
var info PanelInfo
var output string
isChina := IsChina()
if !strings.HasPrefix(version, "v") {
version = "v" + version
}
if isChina {
output = Exec(`curl -sSL "https://jihulab.com/api/v4/projects/haozi-team%2Fpanel/releases/` + version + `"`)
} else {
output = Exec(`curl -sSL "https://api.github.com/repos/haozi-team/panel/releases/tags/` + version + `"`)
}
if len(output) == 0 {
return info, errors.New("获取面板版本失败")
}
file, err := os.CreateTemp("", "panel")
if err != nil {
return info, errors.New("创建临时文件失败")
}
defer os.Remove(file.Name())
_, err = file.Write([]byte(output))
if err != nil {
return info, errors.New("写入临时文件失败")
}
err = file.Close()
if err != nil {
return info, errors.New("关闭临时文件失败")
}
fileName := file.Name()
var name, version2, body, date, downloadName, downloadUrl, checksums, checksumsUrl string
if isChina {
name = Exec("jq -r '.name' " + fileName)
version2 = Exec("jq -r '.tag_name' " + fileName)
body = Exec("jq -r '.description' " + fileName)
date = Exec("jq -r '.created_at' " + fileName)
checksums = Exec("jq -r '.assets.links[] | select(.name | contains(\"checksums\")) | .name' " + fileName)
checksumsUrl = Exec("jq -r '.assets.links[] | select(.name | contains(\"checksums\")) | .direct_asset_url' " + fileName)
if IsArm() {
downloadName = Exec("jq -r '.assets.links[] | select(.name | contains(\"arm64\")) | .name' " + fileName)
downloadUrl = Exec("jq -r '.assets.links[] | select(.name | contains(\"arm64\")) | .direct_asset_url' " + fileName)
} else {
downloadName = Exec("jq -r '.assets.links[] | select(.name | contains(\"amd64v2\")) | .name' " + fileName)
downloadUrl = Exec("jq -r '.assets.links[] | select(.name | contains(\"amd64v2\")) | .direct_asset_url' " + fileName)
}
} else {
name = Exec("jq -r '.name' " + fileName)
version2 = Exec("jq -r '.tag_name' " + fileName)
body = Exec("jq -r '.body' " + fileName)
date = Exec("jq -r '.published_at' " + fileName)
checksums = Exec("jq -r '.assets[] | select(.name | contains(\"checksums\")) | .name' " + fileName)
checksumsUrl = Exec("jq -r '.assets[] | select(.name | contains(\"checksums\")) | .browser_download_url' " + fileName)
if IsArm() {
downloadName = Exec("jq -r '.assets[] | select(.name | contains(\"arm64\")) | .name' " + fileName)
downloadUrl = Exec("jq -r '.assets[] | select(.name | contains(\"arm64\")) | .browser_download_url' " + fileName)
} else {
downloadName = Exec("jq -r '.assets[] | select(.name | contains(\"amd64v2\")) | .name' " + fileName)
downloadUrl = Exec("jq -r '.assets[] | select(.name | contains(\"amd64v2\")) | .browser_download_url' " + fileName)
}
}
info.Name = name
info.Version = version2
info.Body = body
info.Date = date
info.DownloadName = downloadName
info.DownloadUrl = downloadUrl
info.Checksums = checksums
info.ChecksumsUrl = checksumsUrl
return info, nil
}
// UpdatePanel 更新面板
func UpdatePanel(proxy bool) error {
panelInfo, err := GetLatestPanelVersion()
if err != nil {
return err
}
color.Greenln("最新版本: " + panelInfo.Version)
func UpdatePanel(panelInfo PanelInfo) error {
color.Greenln("目标版本: " + panelInfo.Version)
color.Greenln("下载链接: " + panelInfo.DownloadUrl)
color.Greenln("使用代理: " + strconv.FormatBool(proxy))
color.Greenln("备份面板配置...")
Exec("cp -f /www/panel/database/panel.db /tmp/panel.db.bak")
@@ -139,15 +331,26 @@ func UpdatePanel(proxy bool) error {
color.Greenln("清理完成")
color.Greenln("正在下载...")
if proxy {
Exec("wget -O /www/panel/panel.zip https://ghproxy.com/" + panelInfo.DownloadUrl)
} else {
Exec("wget -O /www/panel/panel.zip " + panelInfo.DownloadUrl)
Exec("wget -T 120 -t 3 -O /www/panel/" + panelInfo.DownloadName + " " + panelInfo.DownloadUrl)
Exec("wget -T 20 -t 3 -O /www/panel/" + panelInfo.Checksums + " " + panelInfo.ChecksumsUrl)
if !Exists("/www/panel/"+panelInfo.DownloadName) || !Exists("/www/panel/"+panelInfo.Checksums) {
return errors.New("下载失败")
}
color.Greenln("下载完成")
color.Greenln("校验下载文件...")
check := Exec("cd /www/panel && sha256sum -c " + panelInfo.Checksums + " --ignore-missing")
if check != panelInfo.DownloadName+": OK" {
return errors.New("下载文件校验失败")
}
Remove("/www/panel/" + panelInfo.Checksums)
color.Greenln("文件校验完成")
color.Greenln("更新新版本...")
Exec("cd /www/panel && unzip -o panel.zip && rm -rf panel.zip && chmod 700 panel && bash scripts/update_panel.sh")
Exec("cd /www/panel && unzip -o " + panelInfo.DownloadName + " && rm -rf " + panelInfo.DownloadName + " && chmod 700 panel && bash scripts/update_panel.sh")
if !Exists("/www/panel/panel") {
return errors.New("更新失败,可能是下载过程中出现了问题")
}
color.Greenln("更新完成")
color.Greenln("恢复面板配置...")
@@ -161,9 +364,33 @@ func UpdatePanel(proxy bool) error {
Exec("panel writeSetting version " + panelInfo.Version)
color.Greenln("重启面板...")
Exec("systemctl restart panel")
color.Greenln("重启完成")
Exec("rm -rf /tmp/panel.db.bak")
Exec("rm -rf /tmp/panel.conf.bak")
return nil
}
func RestartPanel() {
color.Greenln("重启面板...")
ExecAsync("sleep 2 && systemctl restart panel")
color.Greenln("重启完成")
}
// IsChina 是否中国大陆
func IsChina() bool {
client := req.C()
client.SetTimeout(5 * time.Second)
client.SetCommonRetryCount(2)
client.ImpersonateSafari()
resp, err := client.R().Get("https://www.cloudflare-cn.com/cdn-cgi/trace")
if err != nil || !resp.IsSuccessState() {
return false
}
if strings.Contains(resp.String(), "loc=CN") {
return true
}
return false
}
+77
View File
@@ -17,3 +17,80 @@ func TestHelperTestSuite(t *testing.T) {
func (s *HelperTestSuite) TestGetMonitoringInfo() {
s.NotNil(GetMonitoringInfo())
}
func (s *HelperTestSuite) TestVersionCompare() {
s.True(VersionCompare("1.0.0", "1.0.0", "=="))
s.True(VersionCompare("1.0.0", "1.0.0", ">="))
s.True(VersionCompare("1.0.0", "1.0.0", "<="))
s.False(VersionCompare("1.0.0", "1.0.0", ">"))
s.False(VersionCompare("1.0.0", "1.0.0", "<"))
s.False(VersionCompare("1.0.0", "1.0.0", "!="))
s.True(VersionCompare("1.0.0", "1.0.1", "<"))
s.True(VersionCompare("1.0.0", "1.0.1", "<="))
s.True(VersionCompare("1.0.0", "1.0.1", "!="))
s.False(VersionCompare("1.0.0", "1.0.1", "=="))
s.False(VersionCompare("1.0.0", "1.0.1", ">="))
s.False(VersionCompare("1.0.0", "1.0.1", ">"))
s.True(VersionCompare("1.0.1", "1.0.0", ">"))
s.True(VersionCompare("1.0.1", "1.0.0", ">="))
s.True(VersionCompare("1.0.1", "1.0.0", "!="))
s.False(VersionCompare("1.0.1", "1.0.0", "=="))
s.False(VersionCompare("1.0.1", "1.0.0", "<="))
s.False(VersionCompare("1.0.1", "1.0.0", "<"))
s.True(VersionCompare("v1.0.0", "1.0.0", "=="))
s.True(VersionCompare("1.0.0", "v1.0.0", "=="))
s.True(VersionCompare("v1.0.0", "v1.0.0", "=="))
}
func (s *HelperTestSuite) TestGenerateVersions() {
versions, err := GenerateVersions("1.0.0", "1.0.3")
s.NoError(err)
s.Equal([]string{"1.0.1", "1.0.2", "1.0.3"}, versions)
versions, err = GenerateVersions("v1.0.0", "v1.0.3")
s.NoError(err)
s.Equal([]string{"1.0.1", "1.0.2", "1.0.3"}, versions)
versions, err = GenerateVersions("1.0.0", "1.0.0")
s.NoError(err)
s.Equal([]string(nil), versions)
versions, err = GenerateVersions("1.0.0", "1.1.1")
s.NoError(err)
s.Equal([]string{
"1.0.1", "1.0.2", "1.0.3", "1.0.4", "1.0.5", "1.0.6", "1.0.7", "1.0.8", "1.0.9", "1.0.10",
"1.0.11", "1.0.12", "1.0.13", "1.0.14", "1.0.15", "1.0.16", "1.0.17", "1.0.18", "1.0.19", "1.0.20",
"1.0.21", "1.0.22", "1.0.23", "1.0.24", "1.0.25", "1.0.26", "1.0.27", "1.0.28", "1.0.29", "1.0.30",
"1.0.31", "1.0.32", "1.0.33", "1.0.34", "1.0.35", "1.0.36", "1.0.37", "1.0.38", "1.0.39", "1.0.40",
"1.0.41", "1.0.42", "1.0.43", "1.0.44", "1.0.45", "1.0.46", "1.0.47", "1.0.48", "1.0.49", "1.0.50",
"1.0.51", "1.0.52", "1.0.53", "1.0.54", "1.0.55", "1.0.56", "1.0.57", "1.0.58", "1.0.59", "1.0.60",
"1.0.61", "1.0.62", "1.0.63", "1.0.64", "1.0.65", "1.0.66", "1.0.67", "1.0.68", "1.0.69", "1.0.70",
"1.0.71", "1.0.72", "1.0.73", "1.0.74", "1.0.75", "1.0.76", "1.0.77", "1.0.78", "1.0.79", "1.0.80",
"1.0.81", "1.0.82", "1.0.83", "1.0.84", "1.0.85", "1.0.86", "1.0.87", "1.0.88", "1.0.89", "1.0.90",
"1.0.91", "1.0.92", "1.0.93", "1.0.94", "1.0.95", "1.0.96", "1.0.97", "1.0.98", "1.0.99", "1.1.0",
"1.1.1",
}, versions)
versions, err = GenerateVersions("1..0", "1.0.1")
s.Error(err)
s.Nil(versions)
versions, err = GenerateVersions("1.0.0", "1..1")
s.Error(err)
s.Nil(versions)
}
func (s *HelperTestSuite) TestGetLatestPanelVersion() {
version, err := GetLatestPanelVersion()
s.NotEmpty(version)
s.Nil(err)
}
func (s *HelperTestSuite) TestGetPanelVersion() {
version, err := GetPanelVersion("v2.0.58")
s.NotEmpty(version)
s.Nil(err)
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

-65
View File
@@ -1,65 +0,0 @@
<!--
////////////////////////////////////////////////////////////////////
// _ooOoo_ //
// o8888888o //
// 88" . "88 //
// (| ^_^ |) //
// O\ = /O //
// ____/`---'\____ //
// .' \\| |// `. //
// / \\||| : |||// \ //
// / _||||| -:- |||||- \ //
// | | \\\ - /// | | //
// | \_| ''\---/'' | | //
// \ .-\__ `-` ___/-. / //
// ___`. .' /--.--\ `. . ___ //
// ."" '< `.___\_<|>_/___.' >'"". //
// | | : `- \`.;`\ _ /`;.`/ - ` : | | //
// \ \ `-. \_ __\ /__ _/ .-` / / //
// ========`-.____`-.___\_____/___.-`____.-'======== //
// `=---=' //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// 佛祖保佑 永无Bug 永不宕机 //
// Name: 耗子Linux面板 Author: 耗子 Date: 2023-07-25 //
////////////////////////////////////////////////////////////////////
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>加载中...</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdnjs.cdn.haozi.net/layui/2.8.11/css/layui.min.css" rel="stylesheet">
</head>
<body>
<div id="Panel_app"></div>
<script src="https://cdnjs.cdn.haozi.net/layui/2.8.11/layui.min.js"></script>
<script src="https://cdnjs.cdn.haozi.net/ace/1.6.1/ace.js"></script>
<script src="https://cdnjs.cdn.haozi.net/echarts/5.4.2/echarts.min.js"></script>
<script src="https://registry.npmmirror.com/xterm/5.2.1/files/lib/xterm.js"></script>
<script src="https://registry.npmmirror.com/xterm-addon-fit/0.7.0/files/lib/xterm-addon-fit.js"></script>
<script src="https://cdnjs.cdn.haozi.net/crypto-js/4.1.1/crypto-js.min.js"></script>
<script>
layui.config({
base: 'panel/', // 静态资源所在路径
version: new Date().getTime()
}).use(['index', 'setter'], function () {
var admin = layui.admin
var setter = layui.setter
admin.req({
url: '/api/panel/info/name',
type: 'get',
success: function (res) {
if (res.code === 0) {
setter.name = res.data.name
document.title = setter.name
}
}
})
})
</script>
</body>
</html>
File diff suppressed because it is too large Load Diff
-182
View File
@@ -1,182 +0,0 @@
/**
* admin.login.css
*/
html, body, #Panel_app {
height: 100%;
}
.layui-layout-body {
overflow: auto;
}
#LAY-user-login,
.layadmin-user-display-show {
display: block !important;
}
.layadmin-user-login {
position: relative;
left: 0;
top: 0;
padding: 110px 0;
min-height: 100%;
box-sizing: border-box;
}
.layadmin-user-login-main {
width: 375px;
margin: 0 auto;
box-sizing: border-box;
}
.layadmin-user-login-box {
padding: 20px;
}
.layadmin-user-login-header {
text-align: center;
}
.layadmin-user-login-header h2 {
margin-bottom: 10px;
font-weight: 300;
font-size: 30px;
color: #000;
}
.layadmin-user-login-header p {
font-weight: 300;
color: #999;
}
.layadmin-user-login-body .layui-form-item {
position: relative;
}
.layadmin-user-login-icon {
position: absolute;
left: 1px;
top: 1px;
width: 38px;
line-height: 36px;
text-align: center;
color: #d2d2d2;
}
.layadmin-user-login-body .layui-form-item .layui-input {
padding-left: 38px;
}
.layadmin-user-login-codeimg {
max-height: 38px;
width: 100%;
cursor: pointer;
box-sizing: border-box;
}
.layadmin-user-login-other {
position: relative;
font-size: 0;
line-height: 38px;
padding-top: 20px;
}
.layadmin-user-login-other > * {
display: inline-block;
vertical-align: middle;
margin-right: 10px;
font-size: 14px;
}
.layadmin-user-login-other .layui-icon {
position: relative;
top: 2px;
font-size: 26px;
}
.layadmin-user-login-other a:hover {
opacity: 0.8;
}
.layadmin-user-jump-change {
float: right;
}
.layadmin-user-login-footer {
position: absolute;
left: 0;
bottom: 0;
width: 100%;
line-height: 30px;
padding: 20px;
text-align: center;
box-sizing: border-box;
color: rgba(0, 0, 0, .5)
}
.layadmin-user-login-footer span {
padding: 0 5px;
}
.layadmin-user-login-footer a {
padding: 0 5px;
color: rgba(0, 0, 0, .5);
}
.layadmin-user-login-footer a:hover {
color: rgba(0, 0, 0, 1);
}
/* 有背景图时 */
.layadmin-user-login-main[bgimg] {
background-color: #fff;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.05);
}
/* 主题背景 */
.ladmin-user-login-theme {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
text-align: center;
}
.ladmin-user-login-theme ul {
display: inline-block;
padding: 5px;
background-color: #fff;
}
.ladmin-user-login-theme ul li {
display: inline-block;
vertical-align: top;
width: 64px;
height: 43px;
cursor: pointer;
transition: all .3s;
-webkit-transition: all .3s;
background-color: #f2f2f2;
}
.ladmin-user-login-theme ul li:hover {
opacity: 0.9
}
@media screen and (max-width: 768px) {
.layadmin-user-login {
padding-top: 60px;
}
.layadmin-user-login-main {
width: 300px;
}
.layadmin-user-login-box {
padding: 10px;
}
}
-890
View File
@@ -1,890 +0,0 @@
/**
* 界面核心模块
*/
layui.define('view', function (exports) {
var $ = layui.jquery
, laytpl = layui.laytpl
, element = layui.element
, table = layui.table
, upload = layui.upload
, setter = layui.setter
, view = layui.view
, device = layui.device()
, $win = $(window), $body = $('body')
, container = $('#' + setter.container)
, SHOW = 'layui-show', HIDE = 'layui-hide', THIS = 'layui-this', DISABLED = 'layui-disabled', TEMP = 'template'
, APP_BODY = '#Panel_app_body', APP_FLEXIBLE = 'Panel_app_flexible'
, FILTER_TAB_TBAS = 'layadmin-layout-tabs'
, APP_SPREAD_SM = 'layadmin-side-spread-sm', TABS_BODY = 'layadmin-tabsbody-item'
, ICON_SHRINK = 'layui-icon-shrink-right', ICON_SPREAD = 'layui-icon-spread-left'
, SIDE_SHRINK = 'layadmin-side-shrink', SIDE_MENU = 'LAY-system-side-menu'
//通用方法
, admin = {
v: '2.0.0'
, mode: 'spa'
//数据的异步请求
, req: view.req
//清除本地 token,并跳转到登入页
, exit: view.exit
//xss 转义
, escape: function (html) {
return String(html || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
.replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/'/g, '&#39;').replace(/"/g, '&quot;')
}
//事件
, on: function (events, callback) {
return layui.onevent.call(this, setter.MOD_NAME, events, callback)
}
//弹出面板
, popup: view.popup
//右侧面板
, popupRight: function (options) {
//layer.close(admin.popup.index);
return admin.popup.index = layer.open($.extend({
type: 1
, id: 'LAY_adminPopupR'
, anim: -1
, title: false
, closeBtn: false
, offset: 'r'
, shade: 0.1
, shadeClose: true
, skin: 'layui-anim layui-anim-rl layui-layer-adminRight'
, area: '300px'
}, options))
}
//发送验证码
, sendAuthCode: function (options) {
options = $.extend({
seconds: 60
, elemPhone: '#LAY_phone'
, elemVercode: '#LAY_vercode'
}, options)
var seconds = options.seconds
, token = null
, timer, countDown = function (loop) {
var btn = $(options.elem)
seconds--
if (seconds < 0) {
btn.removeClass(DISABLED).html('获取验证码')
seconds = options.seconds
clearInterval(timer)
} else {
btn.addClass(DISABLED).html(seconds + '秒后重获')
}
if (!loop) {
timer = setInterval(function () {
countDown(true)
}, 1000)
}
}
$body.off('click', options.elem).on('click', options.elem, function () {
options.elemPhone = $(options.elemPhone)
options.elemVercode = $(options.elemVercode)
var elemPhone = options.elemPhone
, value = elemPhone.val()
if (seconds !== options.seconds || $(this).hasClass(DISABLED)) return
if (!/^1\d{10}$/.test(value)) {
elemPhone.focus()
return layer.msg('请输入正确的手机号')
}
if (typeof options.ajax === 'object') {
var success = options.ajax.success
delete options.ajax.success
}
admin.req($.extend(true, {
url: '/auth/code'
, type: 'get'
, data: {
phone: value
}
, success: function (res) {
layer.msg('验证码已发送至你的手机,请注意查收', {
icon: 1
, shade: 0
})
options.elemVercode.focus()
countDown()
success && success(res)
}
}, options.ajax))
})
}
//屏幕类型
, screen: function () {
var width = $win.width()
if (width > 1200) {
return 3 //大屏幕
} else if (width > 992) {
return 2 //中屏幕
} else if (width > 768) {
return 1 //小屏幕
} else {
return 0 //超小屏幕
}
}
//侧边伸缩
, sideFlexible: function (status) {
var app = container
, iconElem = $('#' + APP_FLEXIBLE)
, screen = admin.screen()
//设置状态,PC:默认展开、移动:默认收缩
if (status === 'spread') {
//切换到展开状态的 icon,箭头:←
iconElem.removeClass(ICON_SPREAD).addClass(ICON_SHRINK)
//移动:从左到右位移;PC:清除多余选择器恢复默认
if (screen < 2) {
app.addClass(APP_SPREAD_SM)
} else {
app.removeClass(APP_SPREAD_SM)
}
app.removeClass(SIDE_SHRINK)
} else {
//切换到搜索状态的 icon,箭头:→
iconElem.removeClass(ICON_SHRINK).addClass(ICON_SPREAD)
//移动:清除多余选择器恢复默认;PC:从右往左收缩
if (screen < 2) {
app.removeClass(SIDE_SHRINK)
} else {
app.addClass(SIDE_SHRINK)
}
app.removeClass(APP_SPREAD_SM)
}
layui.event.call(this, setter.MOD_NAME, 'side({*})', {
status: status
})
}
//重置主体区域表格尺寸
, resizeTable: function (delay) {
var that = this, runResizeTable = function () {
that.tabsBody(admin.tabsPage.index).find('.layui-table-view').each(function () {
var tableID = $(this).attr('lay-id')
layui.table.resize(tableID)
})
}
if (!layui.table) return
delay ? setTimeout(runResizeTable, delay) : runResizeTable()
}
//主题设置
, theme: function (options) {
var theme = setter.theme
, local = layui.data(setter.tableName)
, id = 'LAY_layadmin_theme'
, style = document.createElement('style')
, styleText = laytpl([
//主题色
'.layui-side-menu,'
, '.layui-layer-admin .layui-layer-title,'
, '.layadmin-side-shrink .layui-side-menu .layui-nav>.layui-nav-item>.layui-nav-child'
, '{background-color:{{d.color.main}} !important;}'
//背景选中色
, '.layadmin-pagetabs .layui-tab-title li:after,'
, '.layadmin-pagetabs .layui-tab-title li.layui-this:after,'
, '.layui-nav-tree .layui-this,'
, '.layui-nav-tree .layui-this>a,'
, '.layui-nav-tree .layui-nav-child dd.layui-this,'
, '.layui-nav-tree .layui-nav-child dd.layui-this a,'
, '.layui-nav-tree .layui-nav-bar'
, '{background-color:{{d.color.selected}} !important;}'
//logo
, '.layui-layout-admin .layui-logo{background-color:{{d.color.logo || d.color.main}} !important;}'
//文字选中色
, '.layadmin-pagetabs .layui-tab-title li:hover,'
, '.layadmin-pagetabs .layui-tab-title li.layui-this'
, '{color: {{d.color.selected}} !important;}'
//头部色
, '{{# if(d.color.header){ }}'
, '.layui-layout-admin .layui-header{background-color:{{ d.color.header }};}'
, '.layui-layout-admin .layui-header a,'
, '.layui-layout-admin .layui-header a cite{color: #f8f8f8;}'
, '.layui-layout-admin .layui-header a:hover{color: #fff;}'
, '.layui-layout-admin .layui-header .layui-nav .layui-nav-more{border-top-color: #fbfbfb;}'
, '.layui-layout-admin .layui-header .layui-nav .layui-nav-mored{border-color: transparent; border-bottom-color: #fbfbfb;}'
, '.layui-layout-admin .layui-header .layui-nav .layui-this:after, .layui-layout-admin .layui-header .layui-nav-bar{background-color: #fff; background-color: rgba(255,255,255,.5);}'
, '.layadmin-pagetabs .layui-tab-title li:after{display: none;}'
, '{{# } }}'
].join('')).render(options = $.extend({}, local.theme, options))
, styleElem = document.getElementById(id)
//添加主题样式
if ('styleSheet' in style) {
style.setAttribute('type', 'text/css')
style.styleSheet.cssText = styleText
} else {
style.innerHTML = styleText
}
style.id = id
styleElem && $body[0].removeChild(styleElem)
$body[0].appendChild(style)
$body.attr('layadmin-themealias', options.color.alias)
//本地存储记录
local.theme = local.theme || {}
layui.each(options, function (key, value) {
local.theme[key] = value
})
layui.data(setter.tableName, {
key: 'theme'
, value: local.theme
})
}
//初始化主题
, initTheme: function (index) {
var theme = setter.theme
index = index || 0
if (theme.color[index]) {
theme.color[index].index = index
admin.theme({
color: theme.color[index]
})
}
}
//记录最近一次点击的页面标签数据
, tabsPage: {}
//获取标签页的头元素
, tabsHeader: function (index) {
return $('#Panel_app_tabsheader').children('li').eq(index || 0)
}
//获取页面标签主体元素
, tabsBody: function (index) {
return $(APP_BODY).find('.' + TABS_BODY).eq(index || 0)
}
//切换页面标签主体
, tabsBodyChange: function (index) {
admin.tabsHeader(index).attr('lay-attr', layui.router().href)
admin.tabsBody(index).addClass(SHOW).siblings().removeClass(SHOW)
events.rollPage('auto', index)
}
//resize事件管理
, resize: function (fn) {
var router = layui.router()
, key = router.path.join('-')
if (admin.resizeFn[key]) {
$win.off('resize', admin.resizeFn[key])
delete admin.resizeFn[key]
}
if (fn === 'off') return //如果是清除 resize 事件,则终止往下执行
fn(), admin.resizeFn[key] = fn
$win.on('resize', admin.resizeFn[key])
}
, resizeFn: {}
, runResize: function () {
var router = layui.router()
, key = router.path.join('-')
admin.resizeFn[key] && admin.resizeFn[key]()
}
, delResize: function () {
this.resize('off')
}
//关闭当前 pageTabs
, closeThisTabs: function () {
if (!admin.tabsPage.index) return
$(TABS_HEADER).eq(admin.tabsPage.index).find('.layui-tab-close').trigger('click')
}
//全屏
, fullScreen: function () {
var ele = document.documentElement
, reqFullScreen = ele.requestFullScreen || ele.webkitRequestFullScreen
|| ele.mozRequestFullScreen || ele.msRequestFullscreen
if (typeof reqFullScreen !== 'undefined' && reqFullScreen) {
reqFullScreen.call(ele)
}
}
//退出全屏
, exitScreen: function () {
var ele = document.documentElement
if (document.exitFullscreen) {
document.exitFullscreen()
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen()
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen()
} else if (document.msExitFullscreen) {
document.msExitFullscreen()
}
}
//纠正单页路由格式
, correctRouter: function (href) {
if (!/^\//.test(href)) href = '/' + href
//纠正首尾
return href.replace(/^(\/+)/, '/')
.replace(new RegExp('\/' + setter.entry + '$'), '/') //过滤路由最后的默认视图文件名(如:index)
}
//……
}
//事件
var events = admin.events = {
//伸缩
flexible: function (othis) {
var iconElem = othis.find('#' + APP_FLEXIBLE)
, isSpread = iconElem.hasClass(ICON_SPREAD)
admin.sideFlexible(isSpread ? 'spread' : null) //控制伸缩
admin.resizeTable(350)
}
//刷新
, refresh: function () {
admin.render()
}
//输入框搜索
, serach: function (othis) {
othis.off('keypress').on('keypress', function (e) {
if (!this.value.replace(/\s/g, '')) return
//回车跳转
if (e.keyCode === 13) {
var href = othis.attr('lay-action')
, text = othis.attr('lay-text') || '搜索'
href = href + this.value
text = text + ' <span style="color: #FF5722;">' + admin.escape(this.value) + '</span>'
//打开标签页
location.hash = admin.correctRouter(href)
//如果搜索关键词已经打开,则刷新页面即可
events.serach.keys || (events.serach.keys = {})
events.serach.keys[admin.tabsPage.index] = this.value
if (this.value === events.serach.keys[admin.tabsPage.index]) {
events.refresh(othis)
}
//清空输入框
this.value = ''
}
})
}
//点击消息
, message: function (othis) {
othis.find('.layui-badge-dot').remove()
}
//弹出主题面板
, theme: function () {
admin.popupRight({
id: 'LAY_adminPopupTheme'
, success: function () {
view(this.id).render('ui/theme')
}
})
}
//便签
, note: function (othis) {
var mobile = admin.screen() < 2
, note = layui.data(setter.tableName).note
events.note.index = admin.popup({
title: '便签'
, shade: 0
, offset: [
'41px'
, (mobile ? null : (othis.offset().left - 250) + 'px')
]
, anim: -1
, id: 'LAY_adminNote'
, skin: 'layadmin-note layui-anim layui-anim-upbit'
, content: '<textarea placeholder="内容"></textarea>'
, resize: false
, success: function (layero, index) {
var textarea = layero.find('textarea')
,
value = note === undefined ? '便签中的内容会存储在本地,这样即便你关掉了浏览器,在下次打开时,依然会读取到上一次的记录。是个非常小巧实用的本地备忘录' : note
textarea.val(value).focus().on('keyup', function () {
layui.data(setter.tableName, {
key: 'note'
, value: this.value
})
})
}
})
}
//全屏
, fullscreen: function (othis, opts) {
var SCREEN_FULL = 'layui-icon-screen-full';
var SCREEN_REST = 'layui-icon-screen-restore';
var iconElem = othis.children("i");
var hasFull = iconElem.hasClass(SCREEN_FULL);
// 设置图标状态
var setIcon = function (status) {
if (status) {
iconElem.addClass(SCREEN_REST).removeClass(SCREEN_FULL);
} else {
iconElem.addClass(SCREEN_FULL).removeClass(SCREEN_REST);
}
};
// 设置全屏状态
var setScreen = function (status) {
status ? admin.fullScreen() : admin.exitScreen();
};
// 仅设置图标状态
if (opts) {
return setIcon(opts.status);
}
setIcon(hasFull);
setScreen(hasFull);
}
//弹出关于面板
, about: function () {
admin.popupRight({
id: 'LAY_adminPopupAbout'
, success: function () {
view(this.id).render('system/about')
}
})
}
//弹出更多面板
, more: function () {
admin.popupRight({
id: 'LAY_adminPopupMore'
, success: function () {
view(this.id).render('system/more')
}
})
}
//返回上一页
, back: function () {
history.back()
}
//主题设置
, setTheme: function (othis) {
var index = othis.data('index')
, nextIndex = othis.siblings('.layui-this').data('index')
if (othis.hasClass(THIS)) return
othis.addClass(THIS).siblings('.layui-this').removeClass(THIS)
admin.initTheme(index)
}
//左右滚动页面标签
, rollPage: function (type, index) {
var tabsHeader = $('#Panel_app_tabsheader')
, liItem = tabsHeader.children('li')
, scrollWidth = tabsHeader.prop('scrollWidth')
, outerWidth = tabsHeader.outerWidth()
, tabsLeft = parseFloat(tabsHeader.css('left'))
//右左往右
if (type === 'left') {
if (!tabsLeft && tabsLeft <= 0) return
//当前的left减去可视宽度,用于与上一轮的页标比较
var prefLeft = -tabsLeft - outerWidth
liItem.each(function (index, item) {
var li = $(item)
, left = li.position().left
if (left >= prefLeft) {
tabsHeader.css('left', -left)
return false
}
})
} else if (type === 'auto') { //自动滚动
(function () {
var thisLi = liItem.eq(index), thisLeft
if (!thisLi[0]) return
thisLeft = thisLi.position().left
//当目标标签在可视区域左侧时
if (thisLeft < -tabsLeft) {
return tabsHeader.css('left', -thisLeft)
}
//当目标标签在可视区域右侧时
if (thisLeft + thisLi.outerWidth() >= outerWidth - tabsLeft) {
var subLeft = thisLeft + thisLi.outerWidth() - (outerWidth - tabsLeft)
liItem.each(function (i, item) {
var li = $(item)
, left = li.position().left
//从当前可视区域的最左第二个节点遍历,如果减去最左节点的差 > 目标在右侧不可见的宽度,则将该节点放置可视区域最左
if (left + tabsLeft > 0) {
if (left - tabsLeft > subLeft) {
tabsHeader.css('left', -left)
return false
}
}
})
}
}())
} else {
//默认向左滚动
liItem.each(function (i, item) {
var li = $(item)
, left = li.position().left
if (left + li.outerWidth() >= outerWidth - tabsLeft) {
tabsHeader.css('left', -left)
return false
}
})
}
}
//向右滚动页面标签
, leftPage: function () {
events.rollPage('left')
}
//向左滚动页面标签
, rightPage: function () {
events.rollPage()
}
//关闭当前标签页
, closeThisTabs: function () {
admin.closeThisTabs()
}
//关闭其它标签页
, closeOtherTabs: function (type) {
var TABS_REMOVE = 'LAY-system-pagetabs-remove'
if (type === 'all') {
$(TABS_HEADER + ':gt(0)').remove()
$(APP_BODY).find('.' + TABS_BODY + ':gt(0)').remove()
} else {
$(TABS_HEADER).each(function (index, item) {
if (index && index != admin.tabsPage.index) {
$(item).addClass(TABS_REMOVE)
admin.tabsBody(index).addClass(TABS_REMOVE)
}
})
$('.' + TABS_REMOVE).remove()
}
}
//关闭全部标签页
, closeAllTabs: function () {
events.closeOtherTabs('all')
location.hash = ''
}
//遮罩
, shade: function () {
admin.sideFlexible()
}
}
//初始
!function () {
//主题初始化,本地主题记录优先,其次为 initColorIndex
var local = layui.data(setter.tableName)
if (local.theme) {
admin.theme(local.theme)
} else if (setter.theme) {
admin.initTheme(setter.theme.initColorIndex)
}
//禁止水平滚动
$body.addClass('layui-layout-body')
//移动端强制不开启页面标签功能
if (admin.screen() < 1) {
delete setter.pageTabs
}
//不开启页面标签时
if (!setter.pageTabs) {
container.addClass('layadmin-tabspage-none')
}
//低版本IE提示
if (device.ie && device.ie < 10) {
view.error('IE' + device.ie + '下访问可能不佳,推荐使用:Chrome / Firefox / Edge 等高级浏览器', {
offset: 'auto'
, id: 'LAY_errorIE'
})
}
}()
//admin.prevRouter = {}; //上一个路由
// hash 改变侧边状态
admin.on('hash(side)', function (router) {
var path = router.path, getData = function (item) {
return {
list: item.children('.layui-nav-child')
, name: item.data('name')
, jump: item.data('jump')
}
}
, sideMenu = $('#' + SIDE_MENU)
, SIDE_NAV_ITEMD = 'layui-nav-itemed'
//捕获对应菜单
, matchMenu = function (list) {
var pathURL = admin.correctRouter(path.join('/'))
list.each(function (index1, item1) {
var othis1 = $(item1)
, data1 = getData(othis1)
, listChildren1 = data1.list.children('dd')
, matched1 = path[0] == data1.name || (index1 === 0 && !path[0])
|| (data1.jump && pathURL == admin.correctRouter(data1.jump))
listChildren1.each(function (index2, item2) {
var othis2 = $(item2)
, data2 = getData(othis2)
, listChildren2 = data2.list.children('dd')
, matched2 = (path[0] == data1.name && path[1] == data2.name)
|| (data2.jump && pathURL == admin.correctRouter(data2.jump))
listChildren2.each(function (index3, item3) {
var othis3 = $(item3)
, data3 = getData(othis3)
, matched3 = (path[0] == data1.name && path[1] == data2.name && path[2] == data3.name)
|| (data3.jump && pathURL == admin.correctRouter(data3.jump))
if (matched3) {
var selected = data3.list[0] ? SIDE_NAV_ITEMD : THIS
othis3.addClass(selected).siblings().removeClass(selected) //标记选择器
return false
}
})
if (matched2) {
var selected = data2.list[0] ? SIDE_NAV_ITEMD : THIS
othis2.addClass(selected).siblings().removeClass(selected) //标记选择器
return false
}
})
if (matched1) {
var selected = data1.list[0] ? SIDE_NAV_ITEMD : THIS
othis1.addClass(selected).siblings().removeClass(selected) //标记选择器
return false
}
})
}
//重置状态
sideMenu.find('.' + THIS).removeClass(THIS)
//移动端点击菜单时自动收缩
if (admin.screen() < 2) admin.sideFlexible()
//开始捕获
matchMenu(sideMenu.children('li'))
})
//侧边导航点击事件
element.on('nav(layadmin-system-side-menu)', function (elem) {
if (elem.siblings('.layui-nav-child')[0] && container.hasClass(SIDE_SHRINK)) {
admin.sideFlexible('spread')
layer.close(elem.data('index'))
}
admin.tabsPage.type = 'nav'
})
//选项卡的更多操作
element.on('nav(layadmin-pagetabs-nav)', function (elem) {
var dd = elem.parent()
dd.removeClass(THIS)
dd.parent().removeClass(SHOW)
})
//同步路由
var setThisRouter = function (othis) {
var layid = othis.attr('lay-id')
, attr = othis.attr('lay-attr')
, index = othis.index()
location.hash = layid === setter.entry ? '/' : (attr || '/')
admin.tabsBodyChange(index)
}
, TABS_HEADER = '#Panel_app_tabsheader>li'
//页面标签点击
$body.on('click', TABS_HEADER, function () {
var othis = $(this)
, index = othis.index()
admin.tabsPage.type = 'tab'
admin.tabsPage.index = index
//如果是iframe类型的标签页
if (othis.attr('lay-attr') === 'iframe') {
return admin.tabsBodyChange(index)
}
setThisRouter(othis) //同步路由
admin.runResize() //执行resize事件,如果存在的话
admin.resizeTable() //重置当前主体区域的表格尺寸
})
// tabspage 删除
element.on('tabDelete(layadmin-layout-tabs)', function (obj) {
var othis = $(TABS_HEADER + '.layui-this')
obj.index && admin.tabsBody(obj.index).remove()
setThisRouter(othis)
//移除resize事件
admin.delResize()
})
// 页面跳转
$body.on('click', '*[lay-href]', function () {
var othis = $(this)
var href = othis.attr('lay-href')
var router = layui.router()
admin.tabsPage.elem = othis
// admin.prevRouter[router.path[0]] = router.href; //记录上一次各菜单的路由信息
// 执行跳转
location.hash = admin.correctRouter(href)
// 如果为当前页,则执行刷新
if (setter.refreshCurrPage) {
if (admin.correctRouter(href) === router.href) {
admin.events.refresh()
}
}
// 清理所有定时器
var highestTimeoutId = setTimeout(';')
for (var i = 0; i < highestTimeoutId; i++) {
clearTimeout(i)
}
})
//点击事件
$body.on('click', '*[layadmin-event]', function () {
var othis = $(this)
, attrEvent = othis.attr('layadmin-event')
events[attrEvent] && events[attrEvent].call(this, othis)
})
//tips
$body.on('mouseenter', '*[lay-tips]', function () {
var othis = $(this)
if (othis.parent().hasClass('layui-nav-item') && !container.hasClass(SIDE_SHRINK)) return
var tips = othis.attr('lay-tips')
, offset = othis.attr('lay-offset')
, direction = othis.attr('lay-direction')
, index = layer.tips(tips, this, {
tips: direction || 1
, time: -1
, success: function (layero, index) {
if (offset) {
layero.css('margin-left', offset + 'px')
}
}
})
othis.data('index', index)
}).on('mouseleave', '*[lay-tips]', function () {
layer.close($(this).data('index'))
})
//窗口resize事件
var resizeSystem = layui.data.resizeSystem = function () {
//layer.close(events.note.index);
layer.closeAll('tips')
if (!resizeSystem.lock) {
setTimeout(function () {
admin.sideFlexible(admin.screen() < 2 ? '' : 'spread')
delete resizeSystem.lock
}, 100)
}
resizeSystem.lock = true
}
$win.on('resize', layui.data.resizeSystem)
//设置组件全局 token
!function () {
var request = setter.request
if (request.tokenName) {
var obj = {}
obj[request.tokenName] = layui.data(setter.tableName)[request.tokenName] || ''
//table
table.set({
headers: obj, //通过 request 头传递
where: obj //通过参数传递
})
//upload
upload.set({
headers: obj, //通过 request 头传递
data: obj //通过参数传递
})
}
}()
//接口输出
exports('admin', admin)
})
-198
View File
@@ -1,198 +0,0 @@
/**
* 界面入口模块
*/
layui.define('admin', function (exports) {
var setter = layui.setter
var element = layui.element
var admin = layui.admin
var tabsPage = admin.tabsPage
var view = layui.view
//根据路由渲染页面
var renderPage = function () {
var router = layui.router()
, path = router.path
, pathURL = admin.correctRouter(router.path.join('/'))
//默认读取主页
if (!path.length) path = ['']
//如果最后一项为空字符,则读取默认文件
if (path[path.length - 1] === '') {
path[path.length - 1] = setter.entry
}
//重置状态
var reset = function (type) {
//renderPage.haveInit && layer.closeAll();
if (renderPage.haveInit) {
$('.layui-layer').each(function () {
var othis = $(this),
index = othis.attr('times')
if (!(othis.hasClass('layui-layim') || othis.hasClass('layui-layim-chat'))) {
layer.close(index)
}
})
}
renderPage.haveInit = true
$(APP_BODY).scrollTop(0)
delete tabsPage.type //重置页面标签的来源类型
}
//如果路由来自于 tab 切换,则不重新请求视图
if (tabsPage.type === 'tab') {
//切换到非主页、或者切换到主页且主页必须有内容。方可阻止请求
if (pathURL !== '/' || (pathURL === '/' && admin.tabsBody().html())) {
admin.tabsBodyChange(tabsPage.index)
return reset(tabsPage.type)
}
}
//请求视图渲染
view().render(path.join('/')).then(function (res) {
//遍历页签选项卡
var matchTo
, tabs = $('#Panel_app_tabsheader>li')
tabs.each(function (index) {
var li = $(this)
, layid = li.attr('lay-id')
if (layid === pathURL) {
matchTo = true
tabsPage.index = index
}
})
//如果未在选项卡中匹配到,则追加选项卡
if (setter.pageTabs && pathURL !== '/') {
if (!matchTo) {
$(APP_BODY).append('<div class="layadmin-tabsbody-item layui-show"></div>')
tabsPage.index = tabs.length
element.tabAdd(FILTER_TAB_TBAS, {
title: '<span>' + (res.title || '新标签页') + '</span>'
, id: pathURL
, attr: router.href
})
}
}
this.container = admin.tabsBody(tabsPage.index)
setter.pageTabs || this.container.scrollTop(0) //如果不开启标签页,则跳转时重置滚动条
//定位当前tabs
element.tabChange(FILTER_TAB_TBAS, pathURL)
admin.tabsBodyChange(tabsPage.index)
}).done(function () {
layui.use('common', layui.cache.callback.common)
$win.on('resize', layui.data.resize)
element.render('breadcrumb', 'breadcrumb')
//容器 scroll 事件,剔除吸附层
admin.tabsBody(tabsPage.index).on('scroll', function () {
var othis = $(this)
, elemDate = $('.layui-laydate')
, layerOpen = $('.layui-layer')[0]
//关闭 layDate
if (elemDate[0]) {
elemDate.each(function () {
var thisElemDate = $(this)
thisElemDate.hasClass('layui-laydate-static') || thisElemDate.remove()
})
othis.find('input').blur()
}
//关闭 Tips 层
layerOpen && layer.closeAll('tips')
})
})
reset()
}
//入口页面
var entryPage = function (fn) {
var router = layui.router()
, container = view(setter.container)
, pathURL = admin.correctRouter(router.path.join('/'))
, isIndPage
//检查是否属于独立页面
layui.each(setter.indPage, function (index, item) {
if (pathURL === item) {
return isIndPage = true
}
})
//将模块根路径设置为 modules 目录
layui.config({
base: setter.paths.base + 'modules/'
})
//独立页面
if (isIndPage) {
container.render(router.path.join('/')).done(function () {
admin.pageType = 'alone'
})
} else { //后台框架页面
//强制拦截未登入
if (setter.interceptor) {
var local = layui.data(setter.tableName)
if (!local[setter.request.tokenName]) {
return location.hash = '/login/redirect=' + encodeURIComponent(pathURL) //跳转到登入页
}
}
//渲染后台结构
if (admin.pageType === 'console') { //后台主体页
renderPage()
} else { //初始控制台结构
container.render('ui/layout').done(function () {
renderPage()
layui.element.render()
if (admin.screen() < 2) {
admin.sideFlexible()
}
admin.pageType = 'console'
})
}
}
}
var APP_BODY = '#Panel_app_body'
var FILTER_TAB_TBAS = 'layadmin-layout-tabs'
var $ = layui.$, $win = $(window)
//初始主体结构
layui.link(
setter.paths.core + 'css/admin.css?v=' + admin.v
, function () {
entryPage()
}
, 'layuiAdmin'
)
//Hash改变
window.onhashchange = function () {
entryPage()
//执行 {setter.MOD_NAME}.hash 下的事件
layui.event.call(this, setter.MOD_NAME, 'hash({*})', layui.router())
}
// 对外输出
var adminuiIndex = {
render: renderPage
}
$.extend(admin, adminuiIndex)
exports('adminIndex', adminuiIndex)
})
-325
View File
@@ -1,325 +0,0 @@
/**
* 界面视图模块
*/
layui.define(['laytpl', 'layer'], function (exports) {
var $ = layui.jquery, laytpl = layui.laytpl, layer = layui.layer, setter = layui.setter, device = layui.device(),
hint = layui.hint()
//对外接口
, view = function (id) {
return new Class(id)
}
, SHOW = 'layui-show', LAY_BODY = 'Panel_app_body'
//构造器
, Class = function (id) {
this.id = id
this.container = $('#' + (id || LAY_BODY))
}
//加载中
view.loading = function (elem) {
elem.append(this.elemLoad = $('<i class="layui-anim layui-anim-rotate layui-anim-loop layui-icon layui-icon-loading layadmin-loading"></i>'))
}
//移除加载
view.removeLoad = function () {
this.elemLoad && this.elemLoad.remove()
}
//清除 token,并跳转到登入页
view.exit = function () {
//清空本地记录的 token
layui.data(setter.tableName, {
key: setter.request.tokenName, remove: true
})
//跳转到登入页
location.hash = '/login'
}
//Ajax请求
view.req = function (options) {
var that = this, success = options.success, error = options.error, request = setter.request,
response = setter.response, debug = function () {
return setter.debug ? '<br><cite>URL</cite>' + options.url : ''
}
options.data = options.data || {}
options.headers = options.headers || {}
if (request.tokenName) {
var sendData = typeof options.data === 'string' ? JSON.parse(options.data) : options.data
//自动给参数传入默认 token
options.data[request.tokenName] = request.tokenName in sendData ? options.data[request.tokenName] : (layui.data(setter.tableName)[request.tokenName] || '')
//自动给 Request Headers 传入 token
options.headers[request.tokenName] = request.tokenName in options.headers ? options.headers[request.tokenName] : (layui.data(setter.tableName)[request.tokenName] || '')
}
delete options.success
delete options.error
if (options.type === 'post' || options.type === 'put' || options.type === 'delete' || options.type === 'patch' || options.type === 'POST' || options.type === 'PUT' || options.type === 'DELETE' || options.type === 'PATCH') {
options.contentType = 'application/json'
options.data = JSON.stringify(options.data)
}
return $.ajax($.extend({
type: 'get', dataType: 'json', success: function (res) {
var statusCode = response.statusCode
//只有 response 的 code 一切正常才执行 done
if (res[response.statusName] == statusCode.ok) {
typeof options.done === 'function' && options.done(res)
}
//登录状态失效,清除本地 access_token,并强制跳转到登入页
else if (res[response.statusName] == statusCode.logout) {
view.exit()
}
//其它异常
else {
var errorText = ['<cite>Error</cite> ' + (res[response.msgName] || '返回状态码异常'), debug()].join('')
view.error(errorText)
}
//只要 http 状态码正常,无论 response 的 code 是否正常都执行 success
typeof success === 'function' && success(res)
}, error: function (e, code) {
console.log('面板响应异常: ' + e.responseText)
if (e.status === 422) {
var errorText = ''
var res = e.responseText
try {
res = JSON.parse(res)
} catch (e) {
res = {}
}
if (typeof res.message === 'object' && res.message !== null) {
for (let key in res.message) {
if (res.message.hasOwnProperty(key)) {
for (let subKey in res.message[key]) {
if (res.message[key].hasOwnProperty(subKey)) {
errorText += '<cite>Error</cite> ' + res.message[key][subKey] + '<br>'
}
}
}
}
} else {
errorText = res.message
}
view.error(errorText)
return false
}
var errorText = ['请求异常,请重试<br><cite>错误信息:</cite>' + code, debug()].join('')
view.error(errorText)
typeof error === 'function' && error.apply(this, arguments)
}
}, options))
}
//弹窗
view.popup = function (options) {
var success = options.success, skin = options.skin
delete options.success
delete options.skin
return layer.open($.extend({
type: 1,
title: '提示',
content: '',
id: 'LAY-system-view-popup',
skin: 'layui-layer-admin' + (skin ? ' ' + skin : ''),
shadeClose: true,
closeBtn: false,
success: function (layero, index) {
var elemClose = $('<i class="layui-icon" close>&#x1006;</i>')
layero.append(elemClose)
elemClose.on('click', function () {
layer.close(index)
})
typeof success === 'function' && success.apply(this, arguments)
}
}, options))
}
//异常提示
view.error = function (content, options) {
return view.popup($.extend({
content: content, maxWidth: 300
//,shade: 0.01
, offset: 't', anim: 6, id: 'LAY_adminError'
}, options))
}
//请求模板文件渲染
Class.prototype.render = function (views, params) {
var that = this, router = layui.router()
views = (setter.paths && setter.paths.views ? setter.paths.views : setter.views) + views + setter.engine
$('#' + LAY_BODY).children('.layadmin-loading').remove()
view.loading(that.container) //loading
//请求模板
$.ajax({
url: views, type: 'get', dataType: 'html', data: {
v: layui.cache.version
}, success: function (html) {
html = '<div>' + html + '</div>'
var elemTitle = $(html).find('title'),
title = elemTitle.text() || (html.match(/\<title\>([\s\S]*)\<\/title>/) || [])[1]
var res = {
title: title, body: html
}
elemTitle.remove()
that.params = params || {} //获取参数
if (that.then) {
that.then(res)
delete that.then
}
that.parse(html)
view.removeLoad()
if (that.done) {
that.done(res)
delete that.done
}
}, error: function (e) {
view.removeLoad()
if (that.render.isError) {
return view.error('请求视图文件异常,状态:' + e.status)
}
if (e.status === 404) {
that.render('ui/404')
} else {
that.render('ui/error')
}
that.render.isError = true
}
})
return that
}
//解析模板
Class.prototype.parse = function (html, refresh, callback) {
var that = this, isScriptTpl = typeof html === 'object' //是否模板元素
, elem = isScriptTpl ? html : $(html), elemTemp = isScriptTpl ? html : elem.find('*[template]'),
fn = function (options) {
var tpl = laytpl(options.dataElem.html()), res = $.extend({
params: router.params
}, options.res)
options.dataElem.after(tpl.render(res))
typeof callback === 'function' && callback()
try {
options.done && new Function('d', options.done)(res)
} catch (e) {
console.error(options.dataElem[0], '\n存在错误回调脚本\n\n', e)
}
}, router = layui.router()
elem.find('title').remove()
that.container[refresh ? 'after' : 'html'](elem.children())
router.params = that.params || {}
//遍历模板区块
for (var i = elemTemp.length; i > 0; i--) {
(function () {
var dataElem = elemTemp.eq(i - 1), layDone = dataElem.attr('lay-done') || dataElem.attr('lay-then') //获取回调
, url = laytpl(dataElem.attr('lay-url') || '').render(router) //接口 url
, data = laytpl(dataElem.attr('lay-data') || '').render(router) //接口参数
, headers = laytpl(dataElem.attr('lay-headers') || '').render(router) //接口请求的头信息
try {
data = new Function('return ' + data + ';')()
} catch (e) {
hint.error('lay-data: ' + e.message)
data = {}
}
try {
headers = new Function('return ' + headers + ';')()
} catch (e) {
hint.error('lay-headers: ' + e.message)
headers = headers || {}
}
if (url) {
view.req({
type: dataElem.attr('lay-type') || 'get',
url: url,
data: data,
dataType: 'json',
headers: headers,
success: function (res) {
fn({
dataElem: dataElem, res: res, done: layDone
})
}
})
} else {
fn({
dataElem: dataElem, done: layDone
})
}
}())
}
return that
}
//直接渲染字符
Class.prototype.send = function (views, data) {
var tpl = laytpl(views || this.container.html()).render(data || {})
this.container.html(tpl)
return this
}
//局部刷新模板
Class.prototype.refresh = function (callback) {
var that = this, next = that.container.next(), templateid = next.attr('lay-templateid')
if (that.id != templateid) return that
that.parse(that.container, 'refresh', function () {
that.container.siblings('[lay-templateid="' + that.id + '"]:last').remove()
typeof callback === 'function' && callback()
})
return that
}
//视图请求成功后的回调
Class.prototype.then = function (callback) {
this.then = callback
return this
}
//视图渲染完毕后的回调
Class.prototype.done = function (callback) {
this.done = callback
return this
}
//对外接口
exports('view', view)
})
-99
View File
@@ -1,99 +0,0 @@
/**
* setter
*/
// 初始化配置
layui.define(['all'], function (exports) {
exports('setter', {
paths: { // v1.9.0 及以上版本的写法
core: layui.cache.base + 'adminui/src/', // 核心库所在目录
views: layui.cache.base + 'views/', // 业务视图所在目录
modules: layui.cache.base + 'modules/', // 业务模块所在目录
base: layui.cache.base // 记录静态资源所在基础目录
},
container: 'Panel_app', // 容器ID
entry: 'index', // 默认视图文件名
engine: '.html', // 视图文件后缀名
pageTabs: true, // 是否开启页面选项卡功能。单页版不推荐开启
refreshCurrPage: true, // 当跳转页面 url 与当前页 url 相同时,是否自动执行刷新
name: '耗子Linux面板', tableName: 'HaoZiPanel', // 本地存储表名
MOD_NAME: 'admin', // 模块事件名
debug: true, // 是否开启调试模式。如开启,接口异常时会抛出异常 URL 等信息
interceptor: true, // 是否开启未登入拦截
// 自定义请求字段
request: {
tokenName: 'access_token' // 自动携带 token 的字段名。可设置 false 不携带。
},
// 自定义响应字段
response: {
statusName: 'code', // 数据状态的字段名称
statusCode: {
ok: 0, // 数据状态一切正常的状态码
logout: 401 // 登录状态失效的状态码
}, msgName: 'message', // 状态信息的字段名称
dataName: 'data' // 数据详情的字段名称
},
// 独立页面路由,可随意添加(无需写参数)
indPage: [
'/login',
'/logout',
],
// 配置业务模块目录中的特殊模块
extend: {},
// 主题配置
theme: {
// 内置主题配色方案
color: [{
main: '#20222A', // 主题色
selected: '#16baaa', // 选中色
alias: 'default' // 默认别名
}, {
main: '#03152A', selected: '#3B91FF', alias: 'dark-blue' // 藏蓝
}, {
main: '#2E241B', selected: '#A48566', alias: 'coffee' // 咖啡
}, {
main: '#50314F', selected: '#7A4D7B', alias: 'purple-red' // 紫红
}, {
main: '#344058', logo: '#1E9FFF', selected: '#1E9FFF', alias: 'ocean' // 海洋
}, {
main: '#3A3D49', logo: '#2F9688', selected: '#16b777', alias: 'green' // 墨绿
}, {
main: '#20222A', logo: '#F78400', selected: '#F78400', alias: 'red' // 橙色
}, {
main: '#28333E', logo: '#AA3130', selected: '#AA3130', alias: 'fashion-red' // 时尚红
}, {
main: '#24262F', logo: '#3A3D49', selected: '#16baaa', alias: 'classic-black' // 经典黑
}, {
logo: '#226A62', header: '#2F9688', alias: 'green-header' // 墨绿头
}, {
main: '#344058', logo: '#0085E8', selected: '#1E9FFF', header: '#1E9FFF', alias: 'ocean-header' // 海洋头
}, {
header: '#393D49', alias: 'classic-black-header' // 经典黑
}, {
main: '#50314F', logo: '#50314F', selected: '#7A4D7B', header: '#50314F', alias: 'purple-red-header' // 紫红头
}, {
main: '#28333E', logo: '#28333E', selected: '#AA3130', header: '#AA3130', alias: 'fashion-red-header' // 时尚红头
}, {
main: '#28333E', logo: '#16baaa', selected: '#16baaa', header: '#16baaa', alias: 'green-header' // 墨绿头
}, {
main: '#393D49', logo: '#393D49', selected: '#16baaa', header: '#23262E', alias: 'Classic-style1' // 经典风格1
}, {
main: '#001529', logo: '#001529', selected: '#1890FF', header: '#1890FF', alias: 'Classic-style2' // 经典风格2
}, {
main: '#25282A', logo: '#25282A', selected: '#35BDB2', header: '#35BDB2', alias: 'Classic-style3' // 经典风格3
}],
// 初始的颜色索引,对应上面的配色方案数组索引
// 如果本地已经有主题色记录,则以本地记录为优先,除非请求本地数据(localStorage
initColorIndex: 0
}
})
})
-40
View File
@@ -1,40 +0,0 @@
/**
* 初始化主题入口模块
*/
layui.extend({
setter: 'config' // 将 config.js 扩展到 layui 模块
}).define(['setter'], function (exports) {
var setter = layui.setter
// 将核心库扩展到 layui 模块
layui.each({
admin: 'admin',
view: 'view',
adminIndex: 'index'
}, function (modName, fileName) {
var libs = {}
libs[modName] = '{/}' + setter.paths.core + '/modules/' + fileName
layui.extend(libs)
})
// 指定业务模块基础目录
layui.config({
base: setter.paths.modules
})
// 将业务模块中的特殊模块扩展到 layui 模块
layui.each(setter.extend, function (key, value) {
var mods = {}
mods[key] = '{/}' + layui.cache.base + value
layui.extend(mods)
})
// 加载主题核心库入口模块
layui.use('adminIndex', function () {
layui.use('common') // 加载公共业务模块,如不需要可剔除
// 输出模块 / 模块加载完毕标志
exports('index', layui.admin)
})
})
-33
View File
@@ -1,33 +0,0 @@
/**
* common
*/
layui.define(function (exports) {
var $ = layui.$
, layer = layui.layer
, laytpl = layui.laytpl
, setter = layui.setter
, view = layui.view
, admin = layui.admin
//公共业务的逻辑处理可以写在此处,切换任何页面都会执行
//……
//退出
admin.events.logout = function () {
//执行退出接口
admin.req({
url: './res/json/user/logout.js'
, type: 'get'
, data: {}
, done: function (res) { //这里要说明一下:done 是只有 response 的 code 正常才会执行。而 succese 则是只要 http 为 200 就会执行
//清空本地记录的 token,并跳转到登入页
admin.exit()
}
})
}
//对外暴露的接口
exports('common', {})
})
-194
View File
@@ -1,194 +0,0 @@
/* 样式加载完毕的标识 */
html #layuicss-cron {
display: none;
position: absolute;
width: 1989px;
}
/* 主体结构 */
.layui-cron {
width: 550px;
position: absolute;
z-index: 99999999;
margin: 5px 0;
border-radius: 2px;
font-size: 14px;
-webkit-animation-duration: 0.3s;
animation-duration: 0.3s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
background-color: white;
display: flex;
flex-direction: column;
box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 5px 0px;
-webkit-animation-name: cron-upbit;
animation-name: cron-upbit;
border: 1px solid #e6e6e6;
}
.layui-cron-main ul {
padding-left: 10px;
}
@-webkit-keyframes cron-upbit {
/* 微微往上滑入 */
from {
-webkit-transform: translate3d(0, 20px, 0);
opacity: 0.3;
}
to {
-webkit-transform: translate3d(0, 0, 0);
opacity: 1;
}
}
@keyframes cron-upbit {
from {
transform: translate3d(0, 20px, 0);
opacity: 0.3;
}
to {
transform: translate3d(0, 0, 0);
opacity: 1;
}
}
/* tabs */
.layui-cron>.layui-tab {
margin: 0;
box-shadow: none;
border: none;
}
/* 行 */
.cron-row {
padding-left: 13px;
}
/* 格 */
.cron-grid {
padding-left: 15px;
}
/* 表达式 */
.cron-title {
font-weight: 700;
font-size: 14px;
margin: 10px;
margin-bottom: 0;
}
.cron-box {
margin: 10px;
}
.cron-box+.cron-box {
margin-top: 0;
}
/* 按钮 */
.cron-footer-btns {
text-align: right;
margin-right: 10px;
margin-bottom: 10px;
}
.cron-footer-btns span {
height: 26px;
line-height: 26px;
margin: 0 0 0 -1px;
padding: 0 10px;
border: 1px solid #C9C9C9;
background-color: #fff;
white-space: nowrap;
vertical-align: top;
border-radius: 2px;
display: inline-block;
cursor: pointer;
font-size: 12px;
box-sizing: border-box;
color: #666;
}
.cron-footer-btns span:hover {
color: #5FB878;
}
/* 表单 */
.layui-cron .layui-form-radio {
margin-right: 0;
}
.cron-form {
line-height: 28px;
font-size: 14px;
}
.cron-input-mid {
display: inline-block;
vertical-align: middle;
margin-top: 6px;
background-color: #e5e5e5;
padding: 0 12px;
height: 28px;
line-height: 28px;
border: 1px solid #ccc;
box-sizing: border-box;
}
.cron-input {
display: inline-block;
vertical-align: middle;
margin-top: 6px;
padding: 0 8px;
background-color: #fff;
border: 1px solid #ccc;
height: 28px;
line-height: 28px;
box-sizing: border-box;
width: 80px;
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
}
.cron-input:focus {
outline: 0;
border: 1px solid #01AAED;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 4px 0px #01AAED;
translate: 1s;
}
.layui-cron .layui-form-checkbox[lay-skin="primary"] span {
padding-right: 10px;
min-width: 16px;
}
.layui-cron .layui-form-checkbox[lay-skin="primary"] {
padding-left: 22px;
margin-top: 5px;
}
.layui-cron input[type=number] {
-moz-appearance:textfield;
}
.layui-cron input[type=number]::-webkit-inner-spin-button,
.layui-cron input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
.cron-tips{
color: grey;
line-height: 28px;
height: 28px;
display: inline-block;
vertical-align: middle;
margin-top: 8px;
margin-left: 5px;
}
-970
View File
@@ -1,970 +0,0 @@
/**
@ Namelayui.cron Cron表达式解析器
@ Author:贝哥哥
@ LicenseMIT
*/
layui.define(['lay', 'element', 'form'], function (exports) { //假如该组件依赖 layui.form
var $ = layui.$, layer = layui.layer, lay = layui.lay, element = layui.element, form = layui.form
//字符常量
, MOD_NAME = 'cron', ELEM = '.layui-cron', THIS = 'layui-this', SHOW = 'layui-show', HIDE = 'layui-hide'
, ELEM_STATIC = 'layui-cron-static', ELEM_FOOTER = 'layui-cron-footer', ELEM_CONFIRM = '.cron-btns-confirm',
ELEM_HINT = 'layui-cron-hint'
, ELEM_RUN_HINT = 'layui-cron-run-hint'
//外部接口
, cron = {
v: '2.0.0' // cron 组件当前版本
, index: layui.cron ? (layui.cron.index + 10000) : 0 // corn 实例标识
//设置全局项
, set: function (options) {
var that = this;
that.config = $.extend({}, that.config, options);
return that;
}
//事件监听
, on: function (events, callback) {
return layui.onevent.call(this, MOD_NAME, events, callback);
}
//主体CSS等待事件
, ready: function (fn) {
var cssPath = layui.cache.base + "cron.css?v=" + cron.v;
layui.link(cssPath, fn, "cron"); //此处的“cron”要对应 cron.css 中的样式: html #layuicss-cron{}
return this;
}
}
//操作当前实例
, thisIns = function () {
var that = this, options = that.config, id = options.id || options.index;
return {
//提示框
hint: function (content) {
that.hint.call(that, content);
}, config: options
}
}
//构造器,创建实例
, Class = function (options) {
var that = this;
that.index = ++cron.index;
that.config = $.extend({}, that.config, cron.config, options);
cron.ready(function () {
that.init();
});
};
//默认配置
Class.prototype.config = {
value: null // 当前表达式值,每秒执行一次
,
isInitValue: true //用于控制是否自动向元素填充初始值(需配合 value 参数使用)
,
lang: "cn" //语言,只支持cn/en,即中文和英文
,
tabs: [{key: 'minutes', range: '0-59'}, {
key: 'hours', range: '0-23'
}, {key: 'days', range: '1-31'}, {key: 'months', range: '1-12'}, {key: 'weeks', range: '1-7'}],
defaultCron: {minutes: "*", hours: "*", days: "*", months: "*", weeks: "*"},
trigger: "click" //呼出控件的事件
,
btns: ['run', 'confirm'] //右下角显示的按钮,会按照数组顺序排列
,
position: null //控件定位方式定位, 默认absolute,支持:fixed/absolute/static
,
zIndex: null //控件层叠顺序
,
show: false //是否直接显示,如果设置 true,则默认直接显示控件
,
showBottom: true //是否显示底部栏
,
done: null //控件选择完毕后的回调,点击运行/确定也均会触发
,
run: null // 最近运行时间接口
};
//多语言
Class.prototype.lang = function () {
var that = this, options = that.config, text = {
cn: {
tabs: [{title: "分"}, {title: "时"}, {title: "日"}, {title: "月"}, {
title: "周",
rateBegin: "第",
rateMid: "周的星期",
rateEnd: ""
}],
every: "每",
unspecified: "不指定",
period: "周期",
periodFrom: "从",
rate: "按照",
rateBegin: "从",
rateMid: "开始,每",
rateEnd: "执行一次",
weekday: "工作日",
weekdayPrefix: "每月",
weekdaySuffix: "号最近的那个工作日",
lastday: "本月最后一日",
lastweek: "本月最后一个星期",
custom: "指定",
tools: {
confirm: '确定', run: '运行'
},
formatError: ['Cron格式不合法', '<br>已为你重置']
}, en: {
tabs: [{title: "Minutes"}, {title: "Hours"}, {title: "Days"}, {title: "Months"}, {title: "Weeks"}],
every: "Every ",
unspecified: "Unspecified",
period: "Period",
periodFrom: "From",
rate: "According to",
rateBegin: "begin at",
rateMid: ", every",
rateEnd: " execute once",
weekday: "Weekday",
weekdayPrefix: "Every month at ",
weekdaySuffix: "号最近的那个工作日",
lastday: "Last day of the month",
lastweek: "本月最后一个星期",
custom: "Custom",
tools: {
confirm: 'Confirm', run: 'Run'
},
formatError: ['The cron format error', '<br>It has been reset']
}
};
return text[options.lang] || text['cn'];
};
//初始准备
Class.prototype.init = function () {
var that = this, options = that.config, isStatic = options.position === 'static';
options.elem = lay(options.elem);
options.eventElem = lay(options.eventElem);
if (!options.elem[0]) return;
//如果不是input|textarea元素,则默认采用click事件
if (!that.isInput(options.elem[0])) {
if (options.trigger === 'focus') {
options.trigger = 'click';
}
}
// 设置渲染所绑定元素的唯一KEY
if (!options.elem.attr('lay-key')) {
options.elem.attr('lay-key', that.index);
options.eventElem.attr('lay-key', that.index);
}
// 当前实例主面板ID
that.elemID = 'layui-icon' + options.elem.attr('lay-key');
//默认赋值
if (options.value && options.isInitValue) {
that.setValue(options.value);
}
if (!options.value) {
options.value = options.elem[0].value || '';
}
var cronArr = options.value.split(' ');
if (cronArr.length >= 6) {
options.cron = {
minutes: cronArr[0],
hours: cronArr[1],
days: cronArr[2],
months: cronArr[3],
weeks: cronArr[4],
};
} else {
options.cron = lay.extend({}, options.defaultCron);
}
if (options.show || isStatic) that.render();
isStatic || that.events();
};
// 控件主体渲染
Class.prototype.render = function () {
var that = this, options = that.config, lang = that.lang(), isStatic = options.position === 'static',
tabFilter = 'cron-tab' + options.elem.attr('lay-key')
//主面板
, elem = that.elem = lay.elem('div', {
id: that.elemID, 'class': ['layui-cron', isStatic ? (' ' + ELEM_STATIC) : ''].join('')
})
// tab 内容区域
, elemTab = that.elemTab = lay.elem('div', {
'class': 'layui-tab layui-tab-card', 'lay-filter': tabFilter
}), tabHead = lay.elem('ul', {
'class': 'layui-tab-title'
}), tabContent = lay.elem('div', {
'class': 'layui-tab-content'
})
//底部区域
, divFooter = that.footer = lay.elem('div', {
'class': ELEM_FOOTER
});
if (options.zIndex) elem.style.zIndex = options.zIndex;
// 生成tab 内容区域
elemTab.appendChild(tabHead);
elemTab.appendChild(tabContent);
lay.each(lang.tabs, function (i, item) {
// 表头
var li = lay.elem('li', {
'class': i === 0 ? THIS : "", 'lay-id': i
});
li.innerHTML = item.title;
tabHead.appendChild(li);
// 表体
tabContent.appendChild(that.getTabContentChildElem(i));
});
// 主区域
elemMain = that.elemMain = lay.elem('div', {
'class': 'layui-cron-main'
});
elemMain.appendChild(elemTab);
//生成底部栏
lay(divFooter).html(function () {
var html = [], btns = [];
lay.each(options.btns, function (i, item) {
var title = lang.tools[item] || 'btn';
btns.push('<span lay-type="' + item + '" class="cron-btns-' + item + '">' + title + '</span>');
});
html.push('<div class="cron-footer-btns">' + btns.join('') + '</div>');
return html.join('');
}());
//插入到主区域
elem.appendChild(elemMain);
options.showBottom && elem.appendChild(divFooter);
//移除上一个控件
that.remove(Class.thisElemCron);
//如果是静态定位,则插入到指定的容器中,否则,插入到body
isStatic ? options.elem.append(elem) : (document.body.appendChild(elem)
, that.position());
that.checkCron();
that.elemEvent(); // 主面板事件
Class.thisElemCron = that.elemID;
form.render();
}
// 渲染 tab 子控件
Class.prototype.getTabContentChildElem = function (index) {
var that = this, options = that.config, tabItem = options.tabs[index], tabItemKey = tabItem.key,
lang = that.lang(), tabItemLang = lang.tabs[index], cron = options.cron,
formFilter = 'cronForm' + tabItemKey + options.elem.attr('lay-key'), data = function () {
if (cron[tabItemKey].indexOf('-') != -1) {
// 周期数据
var arr = cron[tabItemKey].split('-');
return {
type: 'range', start: arr[0], end: arr[1]
};
}
if (cron[tabItemKey].indexOf('/') != -1) {
// 频率数据
var arr = cron[tabItemKey].split('/');
return {
type: 'rate', begin: arr[0], rate: arr[1]
};
}
if (cron[tabItemKey].indexOf(',') != -1 || /^\+?[0-9][0-9]*$/.test(cron[tabItemKey])) {
// 按照指定执行
var arr = cron[tabItemKey].split(',').map(Number);
return {
type: 'custom', values: arr
};
}
if (cron[tabItemKey].indexOf('W') != -1) {
// 最近的工作日
var value = cron[tabItemKey].replace('W', '');
return {
type: 'weekday', value: value
};
}
if (index === 2 && cron[tabItemKey] === 'L') {
// 本月最后一日
return {
type: 'lastday', value: 'L'
};
}
if (index === 4 && cron[tabItemKey].indexOf('L') != -1) {
// 本月最后一个周 value
var value = cron[tabItemKey].replace('L', '');
return {
type: 'lastweek', value: value
};
}
if (cron[tabItemKey] === '*') {
// 每次
return {
type: 'every', value: '*'
};
}
if (cron[tabItemKey] === '?' || cron[tabItemKey] === undefined || cron[tabItemKey] === '') {
// 不指定
return {
//type: 'unspecified', value: cron[tabItemKey]
type: 'every', value: '*'
};
}
}(), rangeData = function () {
if (tabItem.range) {
var arr = tabItem.range.split('-');
return {
min: parseInt(arr[0]), max: parseInt(arr[1])
};
}
}();
var elem = lay.elem('div', {
'class': 'layui-tab-item layui-form ' + (index === 0 ? SHOW : ""), 'lay-filter': formFilter
});
// 每次
elem.appendChild(function () {
var everyRadio = lay.elem('input', {
'name': tabItemKey + '[type]',
'type': 'radio',
'value': 'every',
'title': lang.every + tabItemLang.title
});
if (data.type === 'every') {
lay(everyRadio).attr('checked', true);
}
var everyDiv = lay.elem('div', {
'class': 'cron-row'
});
everyDiv.appendChild(everyRadio);
return everyDiv;
}());
// 不指定,从日开始
/*if (index >= 2) {
elem.appendChild(function () {
var unspecifiedRadio = lay.elem('input', {
'name': tabItemKey + '[type]', 'type': 'radio', 'value': 'unspecified', 'title': lang.unspecified
});
if (data.type === 'unspecified') {
lay(unspecifiedRadio).attr('checked', true);
}
var unspecifiedDiv = lay.elem('div', {
'class': 'cron-row'
});
unspecifiedDiv.appendChild(unspecifiedRadio);
return unspecifiedDiv;
}());
}*/
// 周期
var rangeChild = [function () {
var rangeRadio = lay.elem('input', {
'name': tabItemKey + '[type]', 'type': 'radio', 'value': 'range', 'title': lang.period
});
if (data.type === 'range') {
lay(rangeRadio).attr('checked', true);
}
return rangeRadio;
}(), function () {
var elem = lay.elem('div', {
'class': 'cron-input-mid'
});
elem.innerHTML = lang.periodFrom;
return elem;
}(), function () {
var elem = lay.elem('input', {
'class': 'cron-input', 'type': 'number', 'name': 'rangeStart', 'value': data.start || ''
});
return elem;
}(), function () {
var elem = lay.elem('div', {
'class': 'cron-input-mid'
});
elem.innerHTML = '-';
return elem;
}(), function () {
var elem = lay.elem('input', {
'class': 'cron-input', 'type': 'number', 'name': 'rangeEnd', 'value': data.end || ''
});
return elem;
}(), function () {
var elem = lay.elem('div', {
'class': 'cron-input-mid'
});
elem.innerHTML = tabItemLang.title;
return elem;
}()]
, rangeDiv = lay.elem('div', {
'class': 'cron-row'
});
lay.each(rangeChild, function (i, item) {
rangeDiv.appendChild(item);
});
if (tabItem.range) {
var rangeTip = lay.elem('div', {
'class': 'cron-tips'
});
rangeTip.innerHTML = ['(', tabItem.range, ')'].join('');
rangeDiv.appendChild(rangeTip);
}
elem.appendChild(rangeDiv);
// 频率,年没有
if (index < 6) {
var rateChild = [function () {
var rateRadio = lay.elem('input', {
'name': tabItemKey + '[type]', 'type': 'radio', 'value': 'rate', 'title': lang.rate
});
if (data.type === 'rate') {
lay(rateRadio).attr('checked', true);
}
return rateRadio;
}(), function () {
var elem = lay.elem('div', {
'class': 'cron-input-mid'
});
elem.innerHTML = tabItemLang.rateBegin || lang.rateBegin;
return elem;
}(), function () {
var elem = lay.elem('input', {
'class': 'cron-input', 'type': 'number', 'name': 'begin', 'value': data.begin || ''
});
return elem;
}(), function () {
var elem = lay.elem('div', {
'class': 'cron-input-mid'
});
elem.innerHTML = tabItemLang.rateMid || (tabItemLang.title + lang.rateMid);
return elem;
}(), function () {
var elem = lay.elem('input', {
'class': 'cron-input', 'type': 'number', 'name': 'rate', 'value': data.rate || ''
});
return elem;
}(), function () {
var elem = lay.elem('div', {
'class': 'cron-input-mid'
});
elem.innerHTML = undefined != tabItemLang.rateEnd ? tabItemLang.rateEnd : (tabItemLang.title + lang.rateEnd);
if (undefined != tabItemLang.rateEnd && tabItemLang.rateEnd === '') {
lay(elem).addClass(HIDE);
}
return elem;
}()]
, rateDiv = lay.elem('div', {
'class': 'cron-row'
});
lay.each(rateChild, function (i, item) {
rateDiv.appendChild(item);
});
if (tabItem.range) {
var rateTip = lay.elem('div', {
'class': 'cron-tips'
});
if (index === 4) {
// 周
rateTip.innerHTML = '(1-4/1-7)';
} else {
rateTip.innerHTML = ['(', rangeData.min, '/', (rangeData.max + (index <= 1 ? 1 : 0)), ')'].join('');
}
rateDiv.appendChild(rateTip);
}
elem.appendChild(rateDiv);
}
// 特殊:日(最近的工作日、最后一日),周(最后一周)
/*if (index === 2) {
// 日
// 最近的工作日
var weekChild = [function () {
var weekRadio = lay.elem('input', {
'name': tabItemKey + '[type]', 'type': 'radio', 'value': 'weekday', 'title': lang.weekday
});
if (data.type === 'weekday') {
lay(weekRadio).attr('checked', true);
}
return weekRadio;
}(), function () {
var elem = lay.elem('div', {
'class': 'cron-input-mid'
});
elem.innerHTML = lang.weekdayPrefix;
return elem;
}(), function () {
var elem = lay.elem('input', {
'class': 'cron-input', 'type': 'number', 'name': 'weekday', 'value': data.value || ''
});
return elem;
}(), function () {
var elem = lay.elem('div', {
'class': 'cron-input-mid'
});
elem.innerHTML = lang.weekdaySuffix;
return elem;
}(), function () {
var elem = lay.elem('div', {
'class': 'cron-tips'
});
elem.innerHTML = ['(', tabItem.range, ')'].join('');
return elem;
}()]
, weekDiv = lay.elem('div', {
'class': 'cron-row'
});
lay.each(weekChild, function (i, item) {
weekDiv.appendChild(item);
});
elem.appendChild(weekDiv);
// 本月最后一日
elem.appendChild(function () {
var lastRadio = lay.elem('input', {
'name': tabItemKey + '[type]', 'type': 'radio', 'value': 'lastday', 'title': lang.lastday
});
if (data.type === 'lastday') {
lay(lastRadio).attr('checked', true);
}
var lastDiv = lay.elem('div', {
'class': 'cron-row'
});
lastDiv.appendChild(lastRadio);
return lastDiv;
}());
}
if (index === 4) {
// 本月最后一个周几
var lastWeekChild = [function () {
var lastWeekRadio = lay.elem('input', {
'name': tabItemKey + '[type]', 'type': 'radio', 'value': 'lastweek', 'title': lang.lastweek
});
if (data.type === 'lastweek') {
lay(lastWeekRadio).attr('checked', true);
}
return lastWeekRadio;
}(), function () {
var elem = lay.elem('input', {
'class': 'cron-input', 'type': 'number', 'name': 'lastweek', 'value': data.value || ''
});
return elem;
}(), function () {
var elem = lay.elem('div', {
'class': 'cron-tips'
});
elem.innerHTML = ['(', tabItem.range, ')'].join('');
return elem;
}()]
, lastWeekDiv = lay.elem('div', {
'class': 'cron-row'
});
lay.each(lastWeekChild, function (i, item) {
lastWeekDiv.appendChild(item);
});
elem.appendChild(lastWeekDiv);
}*/
// 指定
if (index <= 4) {
elem.appendChild(function () {
var customRadio = lay.elem('input', {
'name': tabItemKey + '[type]', 'type': 'radio', 'value': 'custom', 'title': lang.custom
});
if (data.type === 'custom') {
lay(customRadio).attr('checked', true);
}
var customDiv = lay.elem('div', {
'class': 'cron-row'
});
customDiv.appendChild(customRadio);
return customDiv;
}());
// 指定数值,时分秒显示两位数,自动补零
elem.appendChild(function () {
var customGrid = lay.elem('div', {
'class': 'cron-grid'
});
var i = rangeData.min;
while (i <= rangeData.max) {
// 时分秒显示两位数,自动补零
var gridItemValue = index <= 1 ? lay.digit(i, 2) : i;
var gridItem = lay.elem('input', {
'type': 'checkbox',
'title': gridItemValue,
'lay-skin': 'primary',
'name': tabItemKey + '[custom]',
'value': i
});
if (data.values && data.values.includes(i)) {
lay(gridItem).attr('checked', true);
}
customGrid.appendChild(gridItem);
i++;
}
return customGrid;
}());
}
return elem;
}
//是否输入框
Class.prototype.isInput = function (elem) {
return /input|textarea/.test(elem.tagName.toLocaleLowerCase());
};
// 绑定的元素事件处理
Class.prototype.events = function () {
var that = this, options = that.config
//绑定呼出控件事件
, showEvent = function (elem, bind) {
elem.on(options.trigger, function () {
bind && (that.bindElem = this);
that.render();
});
};
if (!options.elem[0] || options.elem[0].eventHandler) return;
showEvent(options.elem, 'bind');
showEvent(options.eventElem);
//绑定关闭控件事件
lay(document).on('click', function (e) {
if (e.target === options.elem[0] || e.target === options.eventElem[0] || e.target === lay(options.closeStop)[0]) {
return;
}
that.remove();
}).on('keydown', function (e) {
if (e.keyCode === 13) {
if (lay('#' + that.elemID)[0] && that.elemID === Class.thisElemDate) {
e.preventDefault();
lay(that.footer).find(ELEM_CONFIRM)[0].click();
}
}
});
//自适应定位
lay(window).on('resize', function () {
if (!that.elem || !lay(ELEM)[0]) {
return false;
}
that.position();
});
options.elem[0].eventHandler = true;
};
// 主面板事件
Class.prototype.elemEvent = function () {
var that = this, options = that.config, tabFilter = 'cron-tab' + options.elem.attr('lay-key');
// 阻止主面板点击冒泡,避免因触发文档事件而关闭主面
lay(that.elem).on('click', function (e) {
lay.stope(e);
});
// tab选项卡切换
var lis = lay(that.elemTab).find('li');
lis.on('click', function () {
var layid = lay(this).attr('lay-id');
if (undefined === layid) {
return;
}
element.tabChange(tabFilter, layid);
});
// cron选项点击
form.on('radio', function (data) {
var $parent = data.othis.parent();
var formFilter = $parent.parent().attr('lay-filter');
var formData = form.val(formFilter);
var radioType = data.value;
if ('range' === radioType) {
// 范围
form.val(formFilter, {
rangeStart: formData.rangeStart || 0, rangeEnd: formData.rangeEnd || 2
});
}
if ('rate' === radioType) {
// 频率
form.val(formFilter, {
begin: formData.begin || 0, rate: formData.rate || 2
});
}
if ('custom' === radioType) {
// custom
var $grid = $parent.next();
if ($grid.find(':checkbox:checked').length <= 0) {
$grid.children(':checkbox:first').next().click()
}
}
if ('weekday' === radioType) {
// weekday
form.val(formFilter, {
weekday: formData.weekday || 1
});
}
if ('lastweek' === radioType) {
// lastweek
form.val(formFilter, {
lastweek: formData.lastweek || 1
});
}
});
//gird checkbox点击时,自动选中radio
form.on('checkbox', function (data) {
//触发选项的点击事件
var $parent = data.othis.parent().parent();
//循环父级,找到子级的子级找到value="custom"的radio
var $radio = $parent.children().find('input[value="custom"]');
//触发radio的点击事件
$radio.next().click();
});
//点击底部按钮
lay(that.footer).find('span').on('click', function () {
var type = lay(this).attr('lay-type');
that.tool(this, type);
});
};
//底部按钮点击事件
Class.prototype.tool = function (btn, type) {
var that = this, options = that.config, lang = that.lang(), isStatic = options.position === 'static', active = {
//运行
run: function () {
var value = that.parse();
var loading = layer.load();
$.get(options.run, {cron: value}, function (res) {
layer.close(loading);
if (res.code !== 0) {
return that.hint(res.msg);
}
that.runHint(res.data);
}, 'json').fail(function () {
layer.close(loading);
that.hint('服务器异常!');
});
}
//确定
, confirm: function () {
var value = that.parse();
that.done([value]);
that.setValue(value).remove()
}
};
active[type] && active[type]();
};
//执行 done/change 回调
Class.prototype.done = function (param, type) {
var that = this, options = that.config;
param = param || [that.parse()];
typeof options[type || 'done'] === 'function' && options[type || 'done'].apply(options, param);
return that;
};
// 解析cron表达式
Class.prototype.parse = function () {
var that = this, options = that.config, valueArr = [];
lay.each(options.tabs, function (index, item) {
var key = item.key;
var formFilter = 'cronForm' + key + options.elem.attr('lay-key');
var formData = form.val(formFilter);
var radioType = (key + '[type]');
var current = "";
if (formData[radioType] === 'every') {
// 每次
current = "*";
}
if (formData[radioType] === 'range') {
// 范围
current = formData.rangeStart + "-" + formData.rangeEnd;
}
if (formData[radioType] === 'rate') {
// 频率
current = formData.begin + "/" + formData.rate;
}
if (formData[radioType] === 'custom') {
// 指定
var checkboxName = (item.key + '[custom]');
var customArr = [];
$('input[name="' + checkboxName + '"]:checked').each(function () {
customArr.push($(this).val());
});
current = customArr.join(',');
}
if (formData[radioType] === 'weekday') {
// 每月 formData.weekday 号最近的那个工作日
current = formData.weekday + "W";
}
if (formData[radioType] === 'lastday') {
// 本月最后一日
current = "L";
}
if (formData[radioType] === 'lastweek') {
// 本月最后星期
current = formData.lastweek + "L";
}
if (formData[radioType] === 'unspecified' && index != 6) {
// 不指定
current = "?";
}
if (current !== "") {
valueArr.push(current);
options.cron[key] = current;
}
});
return valueArr.join(' ');
};
//控件移除
Class.prototype.remove = function (prev) {
var that = this, options = that.config, elem = lay('#' + (prev || that.elemID));
if (!elem[0]) return that;
if (!elem.hasClass(ELEM_STATIC)) {
that.checkCron(function () {
elem.remove();
});
}
return that;
};
//定位算法
Class.prototype.position = function () {
var that = this, options = that.config;
lay.position(that.bindElem || options.elem[0], that.elem, {
position: options.position
});
return that;
};
//提示
Class.prototype.hint = function (content) {
var that = this, options = that.config, div = lay.elem('div', {
'class': ELEM_HINT
});
if (!that.elem) return;
div.innerHTML = content || '';
lay(that.elem).find('.' + ELEM_HINT).remove();
that.elem.appendChild(div);
clearTimeout(that.hinTimer);
that.hinTimer = setTimeout(function () {
lay(that.elem).find('.' + ELEM_HINT).remove();
}, 3000);
};
//运行提示
Class.prototype.runHint = function (runList) {
var that = this, options = that.config, div = lay.elem('div', {
'class': ELEM_RUN_HINT
});
// debugger;
if (!that.elem || !runList || !runList.length) return;
lay(div).html(function () {
var html = [];
lay.each(runList, function (i, item) {
html.push('<div class="cron-run-list">' + item + '</div>');
});
return html.join('');
}());
lay(that.elem).find('.' + ELEM_RUN_HINT).remove();
that.elem.appendChild(div);
};
//赋值
Class.prototype.setValue = function (value = '') {
var that = this, options = that.config, elem = that.bindElem || options.elem[0],
valType = that.isInput(elem) ? 'val' : 'html'
options.position === 'static' || lay(elem)[valType](value || '');
elem.textContent = '生成';
return this;
};
//cron校验
Class.prototype.checkCron = function (fn) {
var that = this, options = that.config, lang = that.lang(), elem = that.bindElem || options.elem[0],
value = that.isInput(elem) ? elem.value : (options.position === 'static' ? '' : elem.innerHTML)
, checkValid = function (value = "") {
};
// cron 值,多个空格替换为一个空格,去掉首尾空格
value = value || options.value;
if (typeof value === 'string') {
value = value.replace(/\s+/g, ' ').replace(/^\s|\s$/g, '');
}
if (fn === 'init') return checkValid(value), that;
value = that.parse();
if (value) {
that.setValue(value);
}
fn && fn();
return that;
};
//核心入口
cron.render = function (options) {
var ins = new Class(options);
return thisIns.call(ins);
};
exports('cron', cron);
});
-261
View File
@@ -1,261 +0,0 @@
/**
* Set echarts theme
*/
layui.define(function (exports) {
exports('echartsTheme', {
// 默认色板
color: [
'#16baaa', '#1E9FFF', '#16b777', '#FFB980', '#D87A80',
'#8d98b3', '#e5cf0d', '#97b552', '#95706d', '#dc69aa',
'#07a2a4', '#9a7fd1', '#588dd5', '#f5994e', '#c05050',
'#59678c', '#c9ab00', '#7eb00a', '#6f5553', '#c14089'
],
// 图表标题
title: {
textStyle: {
fontWeight: 'normal',
color: '#5F5F5F' // 主标题文字颜色
}
},
// 值域
dataRange: {
itemWidth: 15,
color: ['#16baaa', '#e0ffff']
},
// 工具箱
toolbox: {
color: ['#1e90ff', '#1e90ff', '#1e90ff', '#1e90ff'],
effectiveColor: '#ff4500'
},
// 提示框
tooltip: {
backgroundColor: 'rgba(50,50,50,0.5)', // 提示背景颜色,默认为透明度为0.7的黑色
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'line', // 默认为直线,可选为:'line' | 'shadow'
lineStyle: { // 直线指示器样式设置
color: '#16baaa'
},
crossStyle: {
color: '#008acd'
},
shadowStyle: { // 阴影指示器样式设置
color: 'rgba(200,200,200,0.2)'
}
}
},
// 区域缩放控制器
dataZoom: {
dataBackgroundColor: '#efefff', // 数据背景颜色
fillerColor: 'rgba(182,162,222,0.2)', // 填充颜色
handleColor: '#008acd' // 手柄颜色
},
// 网格
grid: {
borderColor: '#eee'
},
// 类目轴 - X轴
categoryAxis: {
axisLine: { // 坐标轴线
lineStyle: { // 属性lineStyle控制线条样式
color: '#16baaa'
}
},
axisTick: { //小标记
show: false
},
splitLine: { // 分隔线
lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式
color: ['#eee']
}
}
},
// 数值型坐标轴默认参数 - Y轴
valueAxis: {
axisLine: { // 坐标轴线
lineStyle: { // 属性lineStyle控制线条样式
color: '#16baaa'
}
},
splitArea: {
show: true,
areaStyle: {
color: ['rgba(250,250,250,0.1)', 'rgba(200,200,200,0.1)']
}
},
splitLine: { // 分隔线
lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式
color: ['#eee']
}
}
},
polar: {
axisLine: { // 坐标轴线
lineStyle: { // 属性lineStyle控制线条样式
color: '#ddd'
}
},
splitArea: {
show: true,
areaStyle: {
color: ['rgba(250,250,250,0.2)', 'rgba(200,200,200,0.2)']
}
},
splitLine: {
lineStyle: {
color: '#ddd'
}
}
},
timeline: {
lineStyle: {
color: '#16baaa'
},
controlStyle: {
normal: { color: '#16baaa' },
emphasis: { color: '#16baaa' }
},
symbol: 'emptyCircle',
symbolSize: 3
},
// 柱形图默认参数
bar: {
itemStyle: {
normal: {
barBorderRadius: 2
},
emphasis: {
barBorderRadius: 2
}
}
},
// 折线图默认参数
line: {
smooth: true,
symbol: 'emptyCircle', // 拐点图形类型
symbolSize: 3 // 拐点图形大小
},
// K线图默认参数
k: {
itemStyle: {
normal: {
color: '#d87a80', // 阳线填充颜色
color0: '#2ec7c9', // 阴线填充颜色
lineStyle: {
color: '#d87a80', // 阳线边框颜色
color0: '#2ec7c9' // 阴线边框颜色
}
}
}
},
// 散点图默认参数
scatter: {
symbol: 'circle', // 图形类型
symbolSize: 4 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
},
// 雷达图默认参数
radar: {
symbol: 'emptyCircle', // 图形类型
symbolSize: 3
//symbol: null, // 拐点图形类型
//symbolRotate : null, // 图形旋转控制
},
map: {
itemStyle: {
normal: {
areaStyle: {
color: '#ddd'
},
label: {
textStyle: {
color: '#d87a80'
}
}
},
emphasis: { // 也是选中样式
areaStyle: {
color: '#fe994e'
}
}
}
},
force: {
itemStyle: {
normal: {
linkStyle: {
color: '#1e90ff'
}
}
}
},
chord: {
itemStyle: {
normal: {
borderWidth: 1,
borderColor: 'rgba(128, 128, 128, 0.5)',
chordStyle: {
lineStyle: {
color: 'rgba(128, 128, 128, 0.5)'
}
}
},
emphasis: {
borderWidth: 1,
borderColor: 'rgba(128, 128, 128, 0.5)',
chordStyle: {
lineStyle: {
color: 'rgba(128, 128, 128, 0.5)'
}
}
}
}
},
gauge: {
axisLine: { // 坐标轴线
lineStyle: { // 属性lineStyle控制线条样式
color: [[0.2, '#2ec7c9'], [0.8, '#5ab1ef'], [1, '#d87a80']],
width: 10
}
},
axisTick: { // 坐标轴小标记
splitNumber: 10, // 每份split细分多少段
length: 15, // 属性length控制线长
lineStyle: { // 属性lineStyle控制线条样式
color: 'auto'
}
},
splitLine: { // 分隔线
length: 22, // 属性length控制线长
lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式
color: 'auto'
}
},
pointer: {
width: 5
}
},
textStyle: {
fontFamily: '微软雅黑, Arial, Verdana, sans-serif'
}
})
})
Binary file not shown.

Before

Width:  |  Height:  |  Size: 832 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 455 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 457 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

-762
View File
@@ -1,762 +0,0 @@
/**
* admin.templte.css
*/
/********************************
模板开始
*******************************/
/* 产品版本选择面板 */
.layadmin-panel-selection {
width: 768px;
margin: 30px auto;
}
.layadmin-panel-selection .layui-panel-window {
padding: 30px 50px;
border-top-color: #ddd;
text-align: center;
}
.layadmin-panel-selection .layui-panel-window h2 {
padding-bottom: 15px;
font-size: 18px;
}
.layadmin-panel-selection .layui-panel-window ul {
margin-top: 15px;
text-align: left;
}
.layadmin-panel-selection .layui-btn-container {
margin-top: 30px;
}
.layadmin-panel-selection .layui-btn-container .layui-btn {
width: 100%;
}
/* 通讯录面板 */
.layadmin-maillist-fluid .layadmin-contact-box {
padding: 20px;
background-color: #fff;
border: 1px solid #e7eaec;
overflow: hidden;
}
.layadmin-maillist-fluid .layadmin-text-center {
text-align: center;
}
.layadmin-maillist-fluid .layadmin-text-center img {
max-width: 80%;
border-radius: 50%;
margin-top: 5px;
}
.layadmin-maillist-fluid .layadmin-font-blod {
font-weight: 600;
}
.layadmin-maillist-fluid .layadmin-maillist-img {
margin-top: 5px;
}
.layadmin-maillist-fluid .layadmin-title {
margin: 5px 0 10px 0;
}
.layadmin-maillist-fluid .layadmin-textimg {
line-height: 25px;
margin-bottom: 10px;
}
.layadmin-maillist-fluid .layadmin-address {
line-height: 1.5;
margin-bottom: 20px;
}
.layadmin-maillist-fluid .layadmin-padding-left20 {
padding-left: 20px;
}
/* 个人主页 */
.layadmin-homepage-shadow {
box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
background-color: #fff;
border-bottom: 1px solid rgba(0, 0, 0, 0.17);
border-radius: 0;
border: 1px solid #e7ecf3;
}
.layadmin-homepage-panel {
margin-bottom: 15px;
}
.layadmin-homepage-panel .text-center {
text-align: center;
}
.layadmin-homepage-information {
padding: 15px;
border-bottom: 1px solid #e9e9e9;
}
.layadmin-homepage-pad-ver {
padding-top: 15px;
padding-bottom: 15px;
}
.layadmin-homepage-pad-img {
box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.1);
border-radius: 50%;
}
.layadmin-homepage-font {
font-weight: 600;
color: #2b425b;
font-size: 1.2em;
}
.layadmin-homepage-min-font {
margin: 5px 0 10px 0;
font-size: 0.9em;
color: #afb9c3;
}
.layadmin-homepage-pad-ver a {
line-height: 1.1em;
font-size: 1.3em;
vertical-align: middle;
cursor: pointer;
background-color: transparent;
color: inherit;
padding: 6px 12px;
}
.layadmin-homepage-pad-ver a:hover {
background: #16b777;
color: #fff;
}
.layadmin-homepage-about {
padding: 15px;
font-weight: 600;
color: #2b425b;
}
.layadmin-homepage-list-group {
font-size: 0.9em;
line-height: 1.25;
margin-bottom: 5px;
}
.layadmin-homepage-list-group li {
padding: 5px 15px;
border: 1px solid #ddd;
margin-bottom: -1px;
border-width: 1px 0;
border-radius: 0;
background-color: transparent;
border-color: transparent;
color: inherit;
}
.layadmin-homepage-list-group li i {
font-size: 1.333em;
line-height: 1.095em;
vertical-align: middle;
margin-right: 4px;
}
.layadmin-homepage-list-group li a.color {
color: #337ab7;
}
.layadmin-homepage-pad-hor {
padding-left: 15px;
padding-right: 15px;
border-bottom: 15px;
color: #758697;
text-indent: 20px;
}
.layadmin-homepage-list-inline {
margin-left: 15px;
margin-right: 15px;
padding-bottom: 20px
}
.layadmin-homepage-list-inline a {
display: inline-block;
}
.layadmin-homepage-list-inline .layui-btn {
font-size: .9em;
line-height: 1.42857;
vertical-align: middle;
height: auto;
padding: 4px 7px;
margin-left: 0px;
margin: 0 10px 10px 0;
}
/* 左侧个人信息区域 */
.layadmin-homepage-text-center {
text-align: center;
margin-bottom: 15px;
}
.layadmin-homepage-padding15 {
padding: 15px;
margin-bottom: 15px;
}
.layadmin-homepage-padding8 {
padding: 0 8px;
}
.layadmin-homepage-paddingmb {
margin-bottom: 15px;
margin: 0 -7.5px;
}
.layadmin-homepage-content {
margin-left: 15px;
padding: 0;
}
.layadmin-homepage-content .new-section-xs {
margin: 12px 0;
color: inherit;
border: 0 !important;
height: 0px;
box-sizing: content-box;
}
.layadmin-homepage-content .h4 {
font-size: 16px;
font-weight: 600;
color: #2b425b;
}
.layadmin-homepage-content small {
color: #afb9c3
}
.layadmin-homepage-text-center .layui-icon {
color: #FFB800;
padding-right: 5px;
}
.layadmin-homepage-padding15 .layui-col-sm5 a {
font-size: 11px;
height: auto;
line-height: 1.5;
padding: 5px 10px;
float: right;
}
.layadmin-homepage-padding15 .layui-btn-normal {
margin: 0 15px;
}
.layadmin-homepage-list-imgtxt .layui-col-sm10, .layadmin-homepage-list-imgtxt .layui-col-sm2 {
background: none
}
.layadmin-homepage-list-imgtxt .panel-body {
padding: 15px 20px 25px;
overflow: hidden;
margin-bottom: 15px;
}
.layadmin-homepage-list-imgtxt .panel-body .media-left {
display: block;
float: left;
vertical-align: top;
padding-right: 10px;
}
.layadmin-homepage-list-imgtxt .panel-body .media-left img {
border-radius: 50%;
}
.layadmin-homepage-list-imgtxt .media-body {
width: auto;
display: block;
overflow: hidden;
}
.layadmin-homepage-list-imgtxt .media-body .pad-btm {
padding-bottom: 15px;
}
.layadmin-homepage-list-imgtxt .media-body .pad-btm p:first-child {
padding-bottom: 5px;
}
.layadmin-homepage-list-imgtxt .media-body .min-font {
margin-bottom: 10px;
}
.layadmin-homepage-list-imgtxt .media-body .min-font .layui-breadcrumb a {
font-size: 11px;
}
.layui-breadcrumb span[lay-separator] {
margin: 0 5px;
}
.layadmin-homepage-list-imgtxt .media-body .pad-btm .fontColor a {
font-weight: 600;
color: #337ab7;
}
.layadmin-homepage-list-imgtxt .media-body .pad-btm .fontColor span {
color: #758697;
font-weight: 600;
}
.layadmin-homepage-list-imgtxt .media-body .h-img {
display: block;
max-width: 100%;
height: auto;
margin-top: 10px;
}
.layadmin-homepage-list-imgtxt .img-xs {
width: 32px;
height: 32px;
border-radius: 50%;
}
.layadmin-homepage-list-imgtxt .media-body .media {
margin-top: 15px;
overflow: hidden;
}
.layadmin-homepage-list-imgtxt .media-body .media .media-right {
float: right;
padding-top: 10px;
}
.layadmin-homepage-list-imgtxt .media-body .media .media-right .list-inline {
margin-bottom: 10px;
}
.layadmin-homepage-list-imgtxt .media-body .media .list-inline li {
padding: 0 5px;
display: inline-block;
}
.layadmin-homepage-list-imgtxt .media-body .media .media-right .list-inline li span {
font-weight: 600;
}
.layadmin-homepage-list-imgtxt .media-body .media .media-left {
display: block;
overflow: hidden;
width: auto;
}
.layadmin-homepage-list-imgtxt .media-body .media .media-left .font-blod {
font-weight: 700;
color: #758697;
}
.layadmin-homepage-list-imgtxt .media-body .media-list {
padding-top: 15px;
margin-top: 15px;
border-top: 1px solid #e9e9e9;
}
.layadmin-homepage-list-imgtxt .media-body .media-list .media-item {
padding-bottom: 15px;
margin-top: 15px;
}
.layadmin-homepage-list-imgtxt .media-body .media-list .media-item-left {
display: inline-block;
padding-right: 10px;
margin-bottom: 5px;
}
.layadmin-homepage-list-imgtxt .media-body .media-list .media-item-left img {
display: block;
float: left;
}
.layadmin-homepage-list-imgtxt .media-body .media-list .media-text {
overflow: hidden;
width: auto;
display: inline-block;
}
.layadmin-homepage-list-imgtxt .media-body .media-list .media-text a {
margin-right: 10px;
font-weight: 600;
display: inline-block;
}
.layadmin-homepage-list-imgtxt .media-body .media-list .media-text div:nth-child(2) {
margin-top: 5px;
}
.layadmin-homepage-list-imgtxt .media-body .media-list .layui-btn {
height: 24px;
line-height: 24px;
font-size: 12px;
padding: 0 20px;
margin-bottom: 10px;
}
.layadmin-homepage-list-imgtxt .media-body .media-list .layui-btn {
height: 24px;
line-height: 24px;
font-size: 12px;
padding: 0 20px;
margin-bottom: 10px;
}
/* 个人内容区域 */
.homepage-top .layui-card-body img {
width: 100%
}
.homepage-top .layui-card-body .margin-top10 {
margin-top: 10px;
}
.homepage-top .layui-card-body .layui-btn {
width: 100%;
display: block;
}
.homepage-top {
padding-bottom: 20px;
}
.layadmin-privateletterlist-item {
position: relative;
display: block;
padding: 10px 15px;
}
.homepage-bottom .layui-card-body {
padding: 0;
}
.homepage-bottom .layui-card-body img {
width: 32px;
height: 32px;
border-radius: 50%;
margin-top: 10px;
}
.homepage-bottom .layui-card-body .meida-left {
display: table-cell;
padding-right: 10px;
}
.homepage-bottom .layui-card-body .meida-right {
display: table-cell;
vertical-align: top;
}
.homepage-bottom .layui-card-body a:hover {
background: #F2F2F2;
}
.homepage-bottom .layui-card-body {
background: #fff;
}
.layui-card-header .panel-title .layui-icon {
position: relative;
left: 0;
right: 0px;
}
/* 右侧信息栏 */
.layadmin-cmdlist-fluid {
padding-bottom: 60px;
}
.cmdlist-container {
background: #fff;
border: 1px solid transparent;
}
.cmdlist-container:hover {
border: 1px solid #e8e8e8;
}
.cmdlist-container img {
width: 100%;
}
.cmdlist-text {
padding: 20px;
}
.cmdlist-text .info {
height: 40px;
font-size: 14px;
line-height: 20px;
width: 100%;
overflow: hidden;
color: #5F5F5F;
margin-bottom: 10px;
}
.cmdlist-text .price {
font-size: 14px;
}
.cmdlist-text .price b {
margin-right: 20px;
}
.cmdlist-text .price p {
display: inline-block;
}
.cmdlist-text .flow {
text-align: right;
float: right;
}
#demo0 {
text-align: center;
}
/* 商品列表 */
.layadmin-message-fluid .layui-col-md12 {
background: #fff;
height: auto;
padding-bottom: 50px;
}
.layadmin-message-fluid .layui-input-block {
margin-left: 0;
}
.layadmin-message-fluid .layui-form {
padding: 45px 40px 0 40px;
}
.layadmin-message-fluid .layui-form-label {
text-align: left;
font-size: 18px;
padding-left: 10px;
}
.layadmin-message-fluid .layui-textarea {
min-height: 100px;
font-size: 16px;
}
.layadmin-message-fluid .layui-input-right {
float: right;
}
.layadmin-messag-icon {
overflow: hidden;
float: left;
}
.layadmin-messag-icon .layui-icon {
font-size: 24px;
line-height: 30px;
margin-right: 15px;
color: #C4CBCF;
}
.layadmin-messag-icon {
margin-top: 4px;
}
.message-content {
padding: 0 40px;
}
.message-content .media-body {
margin-bottom: 60px;
}
.message-content .media-body .pad-btm {
padding-bottom: 0;
}
.message-content .media-left {
float: left;
margin-right: 10px;
}
.message-content .media-left img {
border-radius: 50%;
}
.message-text {
padding-top: 10px;
}
.message-content-btn {
text-align: center;
}
.message-content .layui-btn {
height: auto;
line-height: 26px;
padding: 5px 30px;
font-size: 16px;
}
/* 搜索结果页面 */
.layadmin-serach-main .layui-card-header {
height: auto;
line-height: 24px;
padding: 15px;
}
.layadmin-serach-list {
margin-bottom: 10px;
padding: 10px 0;
border-bottom: 1px solid #f6f6f6;
}
.layadmin-serach-list h3 {
padding: 10px 0;
}
.layadmin-serach-list h3 .layui-badge {
top: -2px;
}
.layadmin-serach-list p {
color: #5F5F5F;
}
.layadmin-serach-list li {
margin-bottom: 20px;
padding-bottom: 20px;
clear: both;
}
.layui-serachlist-cover {
float: left;
margin-right: 15px;
}
.layui-serachlist-cover img {
width: 90px;
height: 90px;
}
/* 用户列表开始 */
.layadmin-caller {
background: #fff;
padding: 30px;
}
.layadmin-caller em {
font-style: normal;
}
.layadmin-caller .caller-fl {
float: left;
}
.layadmin-caller .caller-fr {
float: right;
}
.layadmin-caller .caller-seach {
position: relative;
padding-bottom: 40px;
}
.layadmin-caller .caller-seach .caller-icon {
font-size: 18px;
position: absolute;
top: 9px;
}
.layadmin-caller .caller-seach-icon {
left: 6px;
}
.layadmin-caller .caller-dump-icon {
right: 6px;
cursor: pointer;
}
.layadmin-caller .caller-pl32 {
padding: 0 32px;
}
.layadmin-caller .caller-tab {
margin: 0;
}
.layadmin-caller .caller-contar {
padding-bottom: 20px;
}
.layadmin-caller .caller-contar .caller-item {
padding: 25px 0;
overflow: hidden;
border-bottom: 1px solid #e0e0e0;
}
.layadmin-caller .caller-contar .caller-item .caller-main {
margin-left: 20px;
}
.layadmin-caller .caller-contar .caller-item .caller-main p {
line-height: 100%;
padding: 8px 0;
}
.layadmin-caller .caller-contar .caller-item .caller-main p:first-child {
padding-top: 0;
}
.layadmin-caller .caller-contar .caller-item .caller-main em {
margin-left: 5px;
}
.layadmin-caller .caller-contar .caller-item .caller-main .caller-adds i {
padding-right: 5px;
margin: 0;
}
.layadmin-caller .caller-contar .caller-item .caller-main .caller-adds {
padding-bottom: 12px;
}
.layadmin-caller .caller-contar .caller-iconset i {
margin: 0 5px;
}
.layadmin-caller .caller-contar .caller-iconset i:first-child {
margin-left: 0;
}
.layadmin-caller .caller-contar button {
margin-top: 22px;
}
.layadmin-caller .caller-contar .caller-img {
width: 40px;
height: 40px;
border-radius: 100%;
}
/****** 模板结束 ******/
-406
View File
@@ -1,406 +0,0 @@
<!--
Name: 计划任务
Author: 耗子
Date: 2023-07-21
-->
<title>计划任务</title>
<div class="layui-fluid">
<div class="layui-card">
<div class="layui-card-header">添加计划任务</div>
<div class="layui-card-body">
<blockquote class="layui-elem-quote">
<p>面板的计划任务均基于脚本运行,若任务类型满足不了需求,可自行修改对应的脚本。</p>
</blockquote>
<form class="layui-form" action="" lay-filter="cron-add-form">
<div class="layui-form-item">
<label class="layui-form-label">任务类型</label>
<div class="layui-input-inline">
<select name="type" lay-verify="required" lay-filter="cron-type">
<option value="shell">运行脚本</option>
<option value="backup">备份数据</option>
<option value="cutoff">切割日志</option>
</select>
</div>
<div class="layui-form-mid layui-word-aux">请选择任务类型</div>
</div>
<div class="layui-form-item" id="cron-add-name-input">
<label class="layui-form-label">任务名</label>
<div class="layui-input-inline">
<input type="text" name="name" lay-verify="required" placeholder="请输入任务名称"
autocomplete="off" class="layui-input">
</div>
<div class="layui-form-mid layui-word-aux">请填写任务名称</div>
</div>
<div class="layui-form-item" id="cron-add-backup-type-input" style="display: none;">
<label class="layui-form-label">备份类型</label>
<div class="layui-input-block">
<input type="radio" lay-filter="cron-add-backup-type-radio" name="backup_type" value="website"
title="网站目录" checked="">
<input type="radio" lay-filter="cron-add-backup-type-radio" name="backup_type" value="mysql"
title="MySQL数据库">
<input type="radio" lay-filter="cron-add-backup-type-radio" name="backup_type"
value="postgresql"
title="PostgreSQL数据库">
</div>
</div>
<div class="layui-form-item" id="cron-add-website-input" style="display: none;">
<label class="layui-form-label">网站</label>
<div class="layui-input-inline">
<script type="text/html" template lay-url="/api/panel/website/list?page=1&limit=10000">
<select name="website" lay-filter="cron-add-website">
{{# layui.each(d.data.items, function(index, item){ }}
{{# if(index == 0){ }}
<option value="{{ item.name }}" selected="">{{ item.name }}</option>
{{# }else{ }}
<option value="{{ item.name }}">{{ item.name }}</option>
{{# } }}
{{# }); }}
</select>
</script>
</div>
<div class="layui-form-mid layui-word-aux">请选择网站</div>
</div>
<div class="layui-form-item" id="cron-add-backup-database-input" style="display: none;">
<label class="layui-form-label">数据库名</label>
<div class="layui-input-inline">
<input type="text" name="backup_database" placeholder="请输入数据库名"
autocomplete="off" class="layui-input">
</div>
<div class="layui-form-mid layui-word-aux">请填写数据库名</div>
</div>
<div class="layui-form-item" id="cron-add-backup-path-input" style="display: none;">
<label class="layui-form-label">保存目录</label>
<div class="layui-input-inline">
<input type="text" name="backup_path" placeholder=""
autocomplete="off" class="layui-input">
</div>
<div class="layui-form-mid layui-word-aux">
目录可以为对象存储挂载目录,不填则默认为面板设置的备份目录
</div>
</div>
<div class="layui-form-item" id="cron-add-save-input" style="display: none;">
<label class="layui-form-label">保留份数</label>
<div class="layui-input-inline">
<input type="number" name="save" placeholder="10"
autocomplete="off" class="layui-input" min="0" step="1" lay-affix="number">
</div>
<div class="layui-form-mid layui-word-aux">请填写保留份数,会自动清理过剩的副本</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">执行周期</label>
<div class="layui-input-inline">
<input type="text" name="time" id="cron-add-time"
lay-verify="required" placeholder="请选择或输入cron表达式" class="layui-input">
</div>
<div class="layui-form-mid layui-word-aux">请务必正确填写执行周期</div>
</div>
<div class="layui-form-item layui-form-text" id="cron-add-shell">
<label class="layui-form-label">脚本内容</label>
<div class="layui-input-block">
<div id="cron-add-script-editor"
style="height: 250px;"># 在此输入你要执行的脚本内容</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit="" lay-filter="cron-add-submit">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
</div>
</div>
<div class="layui-card">
<div class="layui-card-header">计划任务列表</div>
<div class="layui-card-body">
<table id="panel-cron" lay-filter="panel-cron"></table>
<!-- 操作按钮模板 -->
<script type="text/html" id="cron-table-edit">
<a class="layui-btn layui-btn-xs" lay-event="log">日志</a>
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="del">删除</a>
</script>
<!-- 任务类型 -->
<script type="text/html" id="cron-table-type">
{{# if(d.type == 'shell'){ }}
运行脚本
{{# }else if(d.type == 'backup'){ }}
备份数据
{{# }else if(d.type == 'cutoff'){ }}
切割日志
{{# } }}
</script>
<!-- 运行开关 -->
<script type="text/html" id="cron-table-status">
<input type="checkbox" name="cron-status" lay-skin="switch" lay-text="ON|OFF"
lay-filter="cron-status"
value="{{ d.status }}" data-id="{{ d.id }}"
{{ d.status ? 'checked' : '' }}>
</script>
</div>
</div>
</div>
<script>
var cronAddScriptEditor = ace.edit("cron-add-script-editor", {
mode: "ace/mode/sh",
selectionStyle: "text"
});
var cronEditScriptEditor;
layui.use(['admin', 'table', 'jquery', 'cron'], function () {
var $ = layui.$
, form = layui.form
, table = layui.table
, admin = layui.admin
, cron = layui.cron;
cron.render({
elem: "#cron-add-time",
btns: ['confirm'],
show: false,
done: function (value) {
$('#cron-add-time').val(value);
}
});
form.render();
table.render({
elem: '#panel-cron'
, url: '/api/panel/cron/list'
, cols: [[
{field: 'id', hide: true, title: 'ID'}
, {field: 'name', width: 250, title: '任务名', sort: true}
, {field: 'type', width: 150, title: '任务类型', templet: '#cron-table-type', sort: true}
, {field: 'status', title: '启用', width: 100, templet: '#cron-table-status', unresize: true}
, {field: 'time', width: 200, title: '任务周期(cron表达式)'}
, {field: 'created_at', title: '创建时间'}
, {field: 'updated_at', title: '最后更新时间'}
, {
field: 'edit',
width: 180,
title: '操作',
templet: '#cron-table-edit',
fixed: 'right',
align: 'left'
}
]]
, page: true
, text: {
none: '暂无数据'
}
, parseData: function (res) {
return {
"code": res.code,
"msg": res.message,
"count": res.data.total,
"data": res.data.items
};
}
});
table.on('tool(panel-cron)', function (obj) {
let data = obj.data;
if (obj.event === 'log') {
// 打开日志弹窗
admin.popup({
title: '日志 - ' + data.name
,
area: ['80%', '80%']
,
id: 'cron-log'
,
content: '<pre id="cron-log-view" style="overflow: auto; height: 95%;border: 0 none; line-height:23px; padding: 15px; margin: 0; white-space: pre-wrap; background-color: rgb(51,51,51); color:#f1f1f1; border-radius:0;"></pre>'
,
success: function (layero, index) {
index2 = layer.msg('正在获取日志...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: '/api/panel/cron/log?id=' + data.id
, type: 'GET'
, success: function (res) {
layer.close(index2);
if (res.code === 0) {
$('#cron-log-view').html(res.data);
} else {
layer.msg(res.message, {icon: 2, time: 1000});
}
}
});
}
});
} else if (obj.event === 'edit') {
// 打开编辑弹窗
admin.req({
url: '/api/panel/cron/script?id=' + data.id
, type: 'GET'
, success: function (res) {
if (res.code === 0) {
admin.popup({
title: '编辑 - ' + data.name
,
area: ['80%', '80%']
,
id: 'cron-log'
,
content: '任务名&nbsp;&nbsp;&nbsp;&nbsp;<div class="layui-input-inline" style="width: 190px;"><input type="text" name="cron-edit-name" placeholder="请输入任务名称" autocomplete="off" class="layui-input" value="' + data.name + '"></div>&nbsp;&nbsp;&nbsp;&nbsp;执行周期&nbsp;&nbsp;&nbsp;&nbsp;<div class="layui-input-inline" style="width: 190px;"><input id="cron-edit-time-' + data.id + '" type="text" name="cron-edit-time" placeholder="请输入执行周期" autocomplete="off" class="layui-input" value="' + data.time + '"/></div><hr><div id="cron-edit-script-editor" style="height: 80%;">' + res.data + '</div><br><button id="cron-edit-' + data.id + '" class="layui-btn">保存</button>'
,
success: function (layero, index) {
cronEditScriptEditor = ace.edit("cron-edit-script-editor", {
mode: "ace/mode/sh",
selectionStyle: "text"
});
cron.render({
elem: "#cron-edit-time-" + data.id,
btns: ['confirm'],
show: false,
done: function (value) {
$('#cron-add-time').val(value);
}
});
$('#cron-edit-' + data.id).click(function () {
index2 = layer.msg('正在保存...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: '/api/panel/cron/update'
, type: 'POST'
, data: {
id: data.id,
name: $('input[name="cron-edit-name"]').val(),
time: $('input[name="cron-edit-time"]').val(),
script: cronEditScriptEditor.getValue()
}
, success: function (res) {
if (res.code === 0) {
layer.msg('保存成功', {icon: 1, time: 1000});
table.reload('panel-cron');
layer.close(index2);
layer.close(index);
} else {
layer.msg(res.message, {icon: 2, time: 1000});
}
}
});
});
}
});
} else {
layer.msg(res.message, {icon: 2, time: 1000});
}
}
});
} else if (obj.event === 'del') {
layer.confirm('确定删除计划任务' + data.name + '吗?', function (index) {
layer.close(index);
admin.req({
url: '/api/panel/cron/delete',
type: 'POST',
data: {
id: data.id
}
, success: function (res) {
if (res.code === 0) {
table.reload('panel-cron');
layer.msg('计划任务:' + data.name + ' 已删除', {
icon: 1,
time: 1000
});
} else {
layer.msg(res.message, {icon: 2, time: 1000});
}
}
});
});
}
});
form.on('select(cron-type)', function (data) {
if (data.value === 'shell') {
$("#cron-add-backup-type-input").hide();
$("#cron-add-save-input").hide();
$('#cron-add-website-input').hide();
$('#cron-add-backup-database-input').hide();
$('#cron-add-backup-path-input').hide();
$("#cron-add-shell").show();
} else if (data.value === 'backup') {
let selectedType = $('input[name="backup_type"]:checked').val();
if (selectedType === 'website') {
$('#cron-add-website-input').show();
$('#cron-add-backup-database-input').hide();
} else {
$('#cron-add-website-input').hide();
$('#cron-add-backup-database-input').show();
}
$("#cron-add-backup-type-input").show();
$('#cron-add-backup-path-input').show();
$("#cron-add-save-input").show();
$("#cron-add-shell").hide();
} else if (data.value === 'cutoff') {
$('#cron-add-website-input').show();
$('#cron-add-save-input').show();
$("#cron-add-shell").hide();
$('#cron-add-backup-database-input').hide();
$("#cron-add-backup-type-input").hide();
$('#cron-add-backup-path-input').hide();
}
form.render();
});
form.on('radio(cron-add-backup-type-radio)', function (data) {
if (data.value == 'website') {
$('#cron-add-website-input').show();
$('#cron-add-backup-database-input').hide();
} else {
$('#cron-add-website-input').hide();
$('#cron-add-backup-database-input').show();
}
form.render();
});
form.on('switch(cron-status)', function (obj) {
let $ = layui.$;
let id = $(this).data('id');
let status = obj.elem.checked;
admin.req({
url: '/api/panel/cron/status',
type: 'POST',
data: {
id: id,
status: status
}
, success: function (res) {
if (res.code === 0) {
layer.msg('设置成功', {icon: 1, time: 1000});
} else {
layer.msg(res.message, {icon: 2, time: 1000});
}
}
});
});
form.on('submit(cron-add-submit)', function (data) {
data.field.script = cronAddScriptEditor.getValue();
admin.req({
url: "/api/panel/cron/add"
, type: 'post'
, data: data.field
, success: function (result) {
if (result.code !== 0) {
layer.msg('计划任务添加失败!')
return false;
}
table.reload('panel-cron');
layer.alert('计划任务添加成功!', {
icon: 1
, title: '提示'
, btn: ['确定']
, yes: function (index) {
layer.closeAll();
}
});
}
});
return false;
});
});
</script>
-373
View File
@@ -1,373 +0,0 @@
<!--
Name: 主页模板
Author: 耗子
Date: 2023-06-22
-->
<div class="layui-fluid">
<div class="layui-row layui-col-space15">
<div id="ad1" class="layui-col-md12">
<div style="background: #fff;" class="layui-colla-content layui-show">
<div id="ad1-carousel" class="layui-carousel"
style="overflow: hidden;background: #fff;">
<div carousel-item>
<a style="background: #fff;" href="https://hzbk.net"
title="耗子博客" target="_blank"><i class="layui-icon layui-icon-release"></i> 耗子博客</a>
<a style="background: #fff;" href="https://weavatar.com"
title="WeAvatar" target="_blank"><i class="layui-icon layui-icon-release"></i>
WeAvatar - 互联网公共头像服务</a>
<a style="background: #fff;" href="https://wepublish.cn"
title="WePublish" target="_blank"><i class="layui-icon layui-icon-release"></i>
WePublish - WordPress 本土化平台</a>
</div>
</div>
</div>
</div>
<div id="monitor1" class="layui-col-md6">
<div class="layui-card">
<div class="layui-card-header">资源使用</div>
<div class="layui-card-body layadmin-takerates">
<div class="layui-progress" lay-showPercent="yes" lay-filter="home_cpu">
<h3 id="home_cpu">CPU信息加载中</h3>
<div class="layui-progress-bar" lay-percent="0%"></div>
</div>
<div class="layui-progress" lay-showPercent="yes" lay-filter="home_mem">
<h3 id="home_mem">内存信息加载中</h3>
<div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>
</div>
</div>
</div>
</div>
<div id="monitor2" class="layui-col-md3">
<div class="layui-card">
<div class="layui-card-header">系统负载</div>
<div class="layui-card-body layadmin-takerates">
<div class="layui-progress" lay-showPercent="yes" lay-filter="uptime_1">
<h3>近1分钟</h3>
<div class="layui-progress-bar" lay-percent="0%"></div>
</div>
<div class="layui-progress" lay-showPercent="yes" lay-filter="uptime_5">
<h3>近5分钟</h3>
<div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>
</div>
</div>
</div>
</div>
<div class="layui-col-md3">
<div class="layui-card">
<div class="layui-card-header">
实时流量
<span class="layui-badge layui-bg-blue layuiadmin-badge">发送 / 接收</span>
</div>
<div class="layui-card-body layuiadmin-card-list">
<p style="text-align: center;"><b id="home_net_now">获取中...</b></p>
</div>
<div class="layui-card-header">
累计流量
<span class="layui-badge layui-bg-blue layuiadmin-badge">发送 / 接收</span>
</div>
<div class="layui-card-body layuiadmin-card-list">
<p style="text-align: center;"><b id="home_net_total">获取中...</b></p>
</div>
</div>
</div>
<div class="layui-col-md8">
<div class="layui-card">
<div class="layui-card-header">应用</div>
<div class="layui-card-body">
<div class="layui-carousel layadmin-carousel layadmin-shortcut" lay-anim="">
<div carousel-item="">
<ul class="layui-row layui-col-space10 layui-this">
<script type="text/html" template lay-url="/api/panel/info/homePlugins">
{{# layui.each(d.data, function(index, item){ }}
<li class="layui-col-xs4 layui-col-md2 layui-col-sm4">
<a lay-href="/plugins/{{ item.slug }}">
<i class="layui-icon layui-icon-engine"></i>
<cite>{{ item.name }}</cite>
</a>
</li>
{{# }); }}
{{# if(d.data == null){ }}
这里好像啥也没有去插件中心看看吧
{{# } }}
</script>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="layui-col-md4">
<div class="layui-card">
<div class="layui-card-header">基本信息</div>
<div class="layui-card-body layui-text layadmin-version">
<table class="layui-table">
<tbody>
<tr>
<td>系统信息</td>
<td id="home_os_name">
获取中...
</td>
</tr>
<tr>
<td>面板版本</td>
<td id="home_panel_version">
获取中...
</td>
</tr>
<tr>
<td>运行时间</td>
<td id="home_uptime">
获取中...
</td>
</tr>
<tr>
<td>操作</td>
<td>
<button id="update_panel" class="layui-btn layui-btn-xs">更新</button>
<button id="restart_panel" class="layui-btn layui-btn-xs">重启</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="layui-col-md8">
<div class="layui-card">
<div class="layui-card-header">
磁盘信息
<i class="layui-icon layui-icon-tips" lay-tips="磁盘信息显示" lay-offset="5"></i>
</div>
<div class="layui-card-body layadmin-takerates">
<script type="text/html" template lay-url="/api/panel/info/nowMonitor">
{{# layui.each(d.data.disk_usage, function(index, item){ }}
{{# item.usedPercent = Number(item.usedPercent).toFixed(2) }}
<div class="layui-progress" lay-showPercent="yes">
<h3>{{index}}</h3>
<div class="layui-progress-bar" lay-percent="{{item.usedPercent}}%"></div>
</div>
{{# }); }}
{{# if(d.data.length === 0){ }}
这里好像啥也没有...
{{# } }}
{{# layui.element.render('collapse') }}
</script>
</div>
</div>
</div>
<div class="layui-col-md4">
<div class="layui-card">
<div class="layui-card-header">
关于面板
<i class="layui-icon layui-icon-tips" lay-tips="你干嘛,哎哟!" lay-offset="5"></i>
</div>
<div class="layui-card-body layui-text layadmin-text">
<blockquote class="layui-elem-quote">
<p style="color: red;">开发组祝大家2023端午快乐!永无Bug,永不宕机!</p>
</blockquote>
<blockquote class="layui-elem-quote">
<p>欢迎您使用耗子Linux面板。如遇到问题/Bug,可通过 <a
href="https://jq.qq.com/?_wv=1027&amp;k=I1oJKSTH">Q群12370907</a> / <a
target="_blank" href="https://pd.qq.com/s/fyol46wfy">QQ频道</a> 寻求帮助</p>
</blockquote>
</div>
</div>
</div>
</div>
</div>
<script>
var uptime_1 = '获取中', uptime_5 = '获取中', uptime_15 = '获取中'
var net_send = 0, net_recv = 0, net_send_last = 0, net_recv_last = 0
function formatBytes(size) {
size = Number(size)
var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
var i = 0
while (size >= 1024 && i < units.length) {
size /= 1024
i++
}
return size.toFixed(2) + ' ' + units[i]
}
function formatPercentage(num) {
num = Number(num)
return num.toFixed(2) + '%'
}
function refresh_home_info(first = false) {
layui.use(['index', 'jquery', 'admin'], function () {
let $ = layui.jquery
, admin = layui.admin
, element = layui.element
let device = layui.device()
let cpu_info
admin.req({
url: '/api/panel/info/nowMonitor'
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
layer.msg('系统资源获取失败,请刷新重试!')
return false
}
element.progress('home_cpu', formatPercentage(result.data.percent[0]))
element.progress('home_mem', formatPercentage(result.data.mem.usedPercent))
// 计算核心数
let cores = 0
for (let i = 0; i < result.data.cpus.length; i++) {
cores += result.data.cpus[i].cores
}
// 计算负载百分比
uptime_1 = formatPercentage(result.data.load.load1 / cores * 100)
uptime_5 = formatPercentage(result.data.load.load5 / cores * 100)
uptime_15 = formatPercentage(result.data.load.load15 / cores * 100)
element.progress('uptime_1', uptime_1)
element.progress('uptime_5', uptime_5)
// 计算网卡流量
for (let i = 0; i < result.data.net.length; i++) {
if (result.data.net[i].name === 'lo') {
continue
}
net_send += result.data.net[i].bytesSent
net_recv += result.data.net[i].bytesRecv
}
if (first) {
net_send_last = net_send
net_recv_last = net_recv
}
$('#home_net_now').html(formatBytes((net_send - net_send_last) / 3) + '/s / ' + formatBytes((net_recv - net_recv_last) / 3) + '/s')
$('#home_net_total').html(formatBytes(net_send) + ' / ' + formatBytes(net_recv))
net_send_last = net_send
net_recv_last = net_recv
net_send = 0
net_recv = 0
cpu_info = result.data.cpus[0].modelName + ' ' + cores + '线程'
$('#home_cpu').text(cpu_info)
$('#home_mem').text('使用 ' + formatBytes(result.data.mem.used) + ' / ' + '总计 ' + formatBytes(result.data.mem.total))
element.render('progress')
}
})
})
}
refresh_home_info(true)
setInterval(refresh_home_info, 3000)
// 获取系统信息,这部分信息无需更新。
layui.use(['index', 'jquery', 'admin', 'carousel'], function () {
let $ = layui.jquery
, admin = layui.admin
, carousel = layui.carousel
carousel.render({
elem: '#ad1-carousel'
, width: '100%'
, height: '22px'
, anim: 'fade'
, arrow: 'none'
, indicator: 'none'
})
admin.req({
url: '/api/panel/info/systemInfo'
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:系统信息获取失败,接口返回' + result)
layer.msg('系统信息获取失败,请刷新重试!')
return false
}
$('#home_os_name').text(result.data.os_name)
$('#home_panel_version').text(result.data.panel_version)
$('#home_uptime').text('已不间断运行 ' + result.data.uptime + ' 天')
}
})
})
layui.use(['jquery', 'layer'], function () {
let $ = layui.jquery
, layer = layui.layer
, admin = layui.admin
// 监听鼠标悬停到uptime上的事件
// 用于显示1分钟、5分钟、15分钟的负载
$('#monitor2').hover(function () {
layer.tips('1分钟负载:' + uptime_1 + '<br>5分钟负载:' + uptime_5 + '<br>15分钟负载:' + uptime_15, '#monitor2', {
tips: 1,
time: 0
})
}, function () {
layer.closeAll('tips')
})
$('#update_panel').click(function () {
index = layer.msg('正在获取版本信息...', {
icon: 16
, time: 0
})
admin.req(
{
url: '/api/panel/info/checkUpdate'
, type: 'get'
, success: function (result) {
layer.close(index)
if (result.code !== 0) {
layer.msg('获取版本信息失败,请刷新重试!')
return false
}
if (result.data.update) {
layer.confirm('更新日期: <br>' + new Date(result.data.date).toLocaleString() + '<br>更新日志: <pre>' + result.data.body + '</pre>', {
title: '最新版本: ' + result.data.version + ' ,是否更新?',
btn: ['更新', '取消']
}, function () {
let proxy = false
layer.confirm('对于大陆服务器,建议使用代理进行更新', {
title: '是否使用代理更新?',
btn: ['是', '否']
}, function () {
proxy = true
index = layer.msg('正在更新,稍后请手动刷新...', {icon: 16, time: 0, shade: 0.3})
admin.req({
url: '/api/panel/info/update'
, type: 'post'
, data: {proxy: proxy}
})
}, function () {
proxy = false
index = layer.msg('正在更新,稍后请手动刷新...', {icon: 16, time: 0, shade: 0.3})
admin.req({
url: '/api/panel/info/update'
, type: 'post'
, data: {proxy: proxy}
})
})
})
} else {
layer.msg('当前已是最新版本!')
}
}
}
)
})
$('#restart_panel').click(function () {
layer.confirm('真的要重启吗?', {
btn: ['是', '否']
}, function () {
proxy = true
index = layer.msg('正在重启,稍后请手动刷新...', {icon: 16, time: 0, shade: 0.3})
admin.req({
url: '/api/panel/info/restart'
, type: 'post'
})
})
})
})
</script>
-100
View File
@@ -1,100 +0,0 @@
<script type="text/html" template>
<link rel="stylesheet" href="panel/adminui/src/css/login.css?v={{ layui.admin.v }}" media="all">
</script>
<div class="layadmin-user-login layadmin-user-display-show" id="LAY-user-login" style="display: none;">
<div class="layadmin-user-login-main">
<div class="layadmin-user-login-box layadmin-user-login-header">
<h2 id="panel-login-name">加载中...</h2>
<p></p>
</div>
<div class="layadmin-user-login-box layadmin-user-login-body layui-form">
<div class="layui-form-item">
<label class="layadmin-user-login-icon layui-icon layui-icon-username"
for="username"></label>
<input type="text" name="username" id="username" lay-verify="required" placeholder="用户名"
class="layui-input">
</div>
<div class="layui-form-item">
<label class="layadmin-user-login-icon layui-icon layui-icon-password"
for="password"></label>
<input type="password" name="password" id="password" lay-verify="required"
placeholder="密码" class="layui-input">
</div>
<div class="layui-form-item" style="margin-bottom: 20px;">
<a target="_blank" href="https://jq.qq.com/?_wv=1027&amp;k=I1oJKSTH"
class="layadmin-user-jump-change layadmin-link"
style="margin-top: 7px;">忘记密码?</a>
</div>
<div class="layui-form-item">
<button class="layui-btn layui-btn-fluid" lay-submit lay-filter="panel-login-submit">登 入</button>
</div>
</div>
</div>
<div class="layui-trans layadmin-user-login-footer">
<p>耗子Linux面板 © 耗子 All Rights Reserved</p>
</div>
</div>
<script>
layui.use(['admin', 'form'], function () {
let $ = layui.$
, setter = layui.setter
, admin = layui.admin
, form = layui.form
, router = layui.router()
, search = router.search;
// 判断是否已登录
if (layui.data(setter.tableName)[setter.request.tokenName]) {
location.hash = search.redirect ? decodeURIComponent(search.redirect) : '/';
}
// 设置面板名称
$('#panel-login-name').text(setter.name);
form.render();
//提交
form.on('submit(panel-login-submit)', function (obj) {
// 判断obj.field.remember是否存在
if (obj.field.remember) {
obj.field.remember = 1;
} else {
obj.field.remember = 0;
}
admin.req({
url: '/api/panel/user/login'
, data: obj.field
, type: 'post'
, done: function (res) {
// 请求成功后,写入 access_token
layui.data(setter.tableName, {
key: setter.request.tokenName
, value: res.data.access_token
});
// 登入成功的提示与跳转
layer.msg('登录成功', {
offset: '15px'
, icon: 1
, time: 1000
}, function () {
/**
* 可能是LayuiAdmin的bug,如果直接跳转到主页,会出现表格无法获取access_token的问题
* 所以这里强制刷新一次页面
*/
location.reload();
});
}
});
});
});
</script>
-29
View File
@@ -1,29 +0,0 @@
<script type="text/html" template>
<link rel="stylesheet" href="panel/adminui/src/css/login.css?v={{ layui.admin.v }}" media="all">
</script>
<div class="layadmin-user-login layadmin-user-display-show" id="LAY-user-login" style="display: none;">
<div class="layadmin-user-login-main">
<div class="layadmin-user-login-box layadmin-user-login-header">
<h2>已退出登录</h2>
<p>页面即将自动跳转</p>
</div>
</div>
</div>
<div class="layui-trans layadmin-user-login-footer">
<p>耗子Linux面板 © 耗子 All Rights Reserved</p>
</div>
<script>
layui.use(['admin'], function () {
let admin = layui.admin
setTimeout(function () {
admin.exit()
location.hash = '/login'
}, 3000)
})
</script>
-404
View File
@@ -1,404 +0,0 @@
<!--
Name: 资源监控
Date: 2023-08-13
-->
<title>资源监控</title>
<div class="layui-fluid">
<div class="layui-card">
<div class="layui-form layui-card-body" style="overflow: hidden;">
<div class="layui-inline">
<span style="margin-right: 10px;">开启监控</span><input type="checkbox" id="monitor-switch"
lay-filter="monitor" lay-skin="switch"
lay-text="ON|OFF">
<span style="margin-left: 40px; margin-right: 10px;">保存天数</span>
<div class="layui-input-inline"><input type="number" name="monitor-save-days" class="layui-input"
style="height: 30px; margin-top: 5px;" min=0 max=30 disabled>
</div>
<div class="layui-input-inline">
<button id="save_monitor_date" class="layui-btn layui-btn-sm" style="margin-left: 10px;">确定
</button>
</div>
</div>
<div class="layui-inline" style="float: right;">
<span style="margin-right: 10px;">时间选择</span>
<div id="monitor-date" class="layui-input-inline">
<div class="layui-input-inline">
<input type="text" autocomplete="off" id="monitor-startDate"
class="layui-input"
placeholder="开始时间">
</div>
-
<div class="layui-input-inline">
<input type="text" autocomplete="off" id="monitor-endDate"
class="layui-input"
placeholder="结束时间">
</div>
</div>
<span style="margin-left: 40px;"></span>
<button id="clear_monitor_record" class="layui-btn layui-btn-sm layui-btn-danger">清空监控记录
</button>
</div>
</div>
</div>
<div class="layui-row layui-col-space10">
<div class="layui-col-xs12 layui-col-md6">
<div class="layui-card">
<div class="layui-card-header">
<span>负载</span>
</div>
<div class="layui-card-body">
<div id="load_monitor" style="width: 100%;height: 400px;"></div>
</div>
</div>
</div>
<div class="layui-col-xs12 layui-col-md6">
<div class="layui-card">
<div class="layui-card-header">
<span>CPU</span>
</div>
<div class="layui-card-body">
<div id="cpu_monitor" style="width: 100%;height: 400px;"></div>
</div>
</div>
</div>
</div>
<div class="layui-row layui-col-space10">
<div class="layui-col-xs12 layui-col-md6">
<div class="layui-card">
<div class="layui-card-header">
<span>内存</span>
</div>
<div class="layui-card-body">
<div id="memory_monitor" style="width: 100%;height: 400px;"></div>
</div>
</div>
</div>
<div class="layui-col-xs12 layui-col-md6">
<div class="layui-card">
<div class="layui-card-header">
<span>网络</span>
</div>
<div class="layui-card-body">
<div id="network_monitor" style="width: 100%;height: 400px;"></div>
</div>
</div>
</div>
</div>
</div>
<script>
layui.use(['admin', 'view', 'form', 'element', 'carousel'], function () {
var admin = layui.admin;
var $ = layui.jquery;
var form = layui.form;
var laydate = layui.laydate;
// 默认开始时间为今天0点,结束时间为当前时间
var startDate = new Date(new Date().setHours(0, 0, 0, 0));
var endDate = new Date();
// 拼接时间字符串
var startStr = startDate.getFullYear() + '-' + startDate.getMonth() + '-' + startDate.getDate() + ' ' + startDate.getHours() + ':' + startDate.getMinutes() + ':' + startDate.getSeconds();
var endStr = endDate.getFullYear() + '-' + endDate.getMonth() + '-' + endDate.getDate() + ' ' + endDate.getHours() + ':' + endDate.getMinutes() + ':' + endDate.getSeconds();
laydate.render({
elem: '#monitor-date'
, type: 'datetime'
, range: ['#monitor-startDate', '#monitor-endDate']
, value: startStr + ' - ' + endStr
, calendar: true
, done: function (value, date, endDate) {
let start_date,
end_date;
// 初始化时间日期对象
start_date = new Date(date.year, date.month, date.date, date.hours, date.minutes, date.seconds);
end_date = new Date(endDate.year, endDate.month, endDate.date, endDate.hours, endDate.minutes, endDate.seconds);
getMonitorData(start_date.getTime(), end_date.getTime());
}
});
// 获取监控开关和保存天数
admin.req({
url: '/api/panel/monitor/switchAndDays',
type: 'get',
dataType: 'json',
success: function (res) {
if (res.code === 0) {
if (res.data.switch) {
$('#monitor-switch').attr('checked', true);
} else {
$('#monitor-switch').attr('checked', false);
}
$('input[name="monitor-save-days"]').val(res.data.days);
$('input[name="monitor-save-days"]').removeAttr('disabled');
form.render();
}
}
});
form.on('switch(monitor)', function (data) {
admin.req({
url: '/api/panel/monitor/switch',
type: 'post',
dataType: 'json',
data: {switch: data.elem.checked},
success: function (res) {
if (res.code === 0) {
layer.msg('修改成功', {icon: 1});
} else {
layer.msg(res.message, {icon: 2});
}
}
});
});
$('#save_monitor_date').click(function () {
var days = $('input[name="monitor-save-days"]').val();
if (days == '') {
layer.msg('请输入保存天数', {icon: 2});
return false;
}
admin.req({
url: '/api/panel/monitor/saveDays',
type: 'post',
dataType: 'json',
data: {days: days},
success: function (res) {
if (res.code === 0) {
layer.msg('修改成功', {icon: 1});
} else {
layer.msg(res.message, {icon: 2});
}
}
});
});
$('#clear_monitor_record').click(function () {
layer.confirm('确定要清除监控数据吗?', function (index) {
admin.req({
url: '/api/panel/monitor/clear',
type: 'post',
dataType: 'json',
success: function (res) {
if (res.code === 0) {
layer.msg('清除成功', {icon: 1});
setTimeout(function () {
admin.render();
}, 1000);
} else {
layer.msg(res.message, {icon: 2});
}
}
});
layer.close(index);
});
});
getMonitorData(startDate.getTime(), endDate.getTime());
});
// 获取监控数据
function getMonitorData(startDate, endDate) {
layui.use(['admin'], function () {
let admin = layui.admin;
admin.req({
url: '/api/panel/monitor/list?start=' + startDate + '&end=' + endDate,
type: 'get',
dataType: 'json',
success: function (res) {
if (res.code !== 0) {
layer.msg(res.message, {icon: 2, shade: 0.3});
return false;
}
let loadChart = renderEcharts('load_monitor', '负载', {
x: 'left',
data: ["1分钟", "5分钟", "15分钟"]
}, res.data.times, [{
name: '1分钟',
type: 'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: res.data.load.load1,
markPoint: {
data: [{type: 'max', name: '最大值'}, {type: 'min', name: '最小值'}]
},
markLine: {
data: [{type: 'average', name: '平均值'}]
}
}, {
name: '5分钟',
type: 'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: res.data.load.load5,
markPoint: {
data: [{type: 'max', name: '最大值'}, {type: 'min', name: '最小值'}]
},
markLine: {
data: [{type: 'average', name: '平均值'}]
}
}, {
name: '15分钟',
type: 'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: res.data.load.load15,
markPoint: {
data: [{type: 'max', name: '最大值'}, {type: 'min', name: '最小值'}]
},
markLine: {
data: [{type: 'average', name: '平均值'}]
}
}], [{
type: 'value',
}]);
let cpuChart = renderEcharts('cpu_monitor', 'CPU', undefined, res.data.times, [{
name: '使用率',
type: 'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: res.data.cpu.percent,
markPoint: {
data: [{type: 'max', name: '最大值'}, {type: 'min', name: '最小值'}]
},
markLine: {
data: [{type: 'average', name: '平均值'}]
}
}], [{
name: '单位 %',
min: 0,
max: 100,
type: 'value',
axisLabel: {
formatter: '{value} %'
}
}]);
let memoryChart = renderEcharts('memory_monitor', '内存', {
x: 'left',
data: ["内存", "Swap"]
}, res.data.times, [{
name: '内存',
type: 'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: res.data.mem.used,
markPoint: {
data: [{type: 'max', name: '最大值'}, {type: 'min', name: '最小值'}]
},
markLine: {
data: [{type: 'average', name: '平均值'}]
}
}, {
name: 'Swap',
type: 'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: res.data.swap.used,
markPoint: {
data: [{type: 'max', name: '最大值'}, {type: 'min', name: '最小值'}]
},
markLine: {
data: [{type: 'average', name: '平均值'}]
}
}], [{
name: '单位 MB',
min: 0,
max: res.data.mem.total,
type: 'value',
axisLabel: {
formatter: '{value} M'
}
}]);
let networkChart = renderEcharts('network_monitor', '网络', {
x: 'left',
data: ["总计出", "总计入", "每秒出", "每秒入"]
}, res.data.times, [{
name: '总计出',
type: 'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: res.data.net.sent,
markPoint: {
data: [{type: 'max', name: '最大值'}, {type: 'min', name: '最小值'}]
},
markLine: {
data: [{type: 'average', name: '平均值'}]
}
}, {
name: '总计入',
type: 'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: res.data.net.recv,
markPoint: {
data: [{type: 'max', name: '最大值'}, {type: 'min', name: '最小值'}]
},
markLine: {
data: [{type: 'average', name: '平均值'}]
}
}, {
name: '每秒出',
type: 'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: res.data.net.tx,
markPoint: {
data: [{type: 'max', name: '最大值'}, {type: 'min', name: '最小值'}]
},
markLine: {
data: [{type: 'average', name: '平均值'}]
}
}, {
name: '每秒入',
type: 'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: res.data.net.rx,
markPoint: {
data: [{type: 'max', name: '最大值'}, {type: 'min', name: '最小值'}]
},
markLine: {
data: [{type: 'average', name: '平均值'}]
}
}], [{
name: '单位 Mb',
type: 'value',
axisLabel: {
formatter: '{value} Mb'
}
}]);
// 在窗口大小改变时,重置图表大小
window.addEventListener("resize", function () {
loadChart.resize();
cpuChart.resize();
memoryChart.resize();
networkChart.resize();
});
}, error: function (xhr, status, error) {
console.log('耗子Linux面板:ajax请求出错,错误' + error);
}
});
});
}
// 渲染图表
function renderEcharts(element_id, title, legend = undefined, data_xAxis, series, yAxis = undefined) {
var Chart = echarts.init(document.getElementById(element_id), layui.echartsTheme);
var option = {
title: {text: title, x: 'center', textStyle: {fontSize: 20}},
tooltip: {trigger: 'axis'},
legend: legend,
xAxis: [{type: 'category', boundaryGap: false, data: data_xAxis}],
yAxis: yAxis,
dataZoom: {
show: true,
realtime: true,
start: 0,
end: 100
},
series: series
};
Chart.setOption(option);
return Chart;
}
</script>
-185
View File
@@ -1,185 +0,0 @@
<title>插件中心</title>
<div class="layui-fluid">
<div class="layui-card">
<div class="layui-card-header">
按钮点击一次即可,请勿重复点击以免重复操作,任务中心在右上方!
</div>
<div class="layui-card-body">
<table id="panel-plugin" lay-filter="panel-plugin"></table>
<!-- 操作按钮模板 -->
<script type="text/html" id="panel-plugin-control">
{{# if(d.installed && d.installed_version != d.version){ }}
<a class="layui-btn layui-btn-xs" lay-event="update">更新</a>
{{# } }}
{{# if(d.installed && d.installed_version == d.version){ }}
<a class="layui-btn layui-btn-xs" lay-event="open">管理</a>
{{# } }}
{{# if(d.installed && d.installed_version == d.version){ }}
<a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="uninstall">卸载</a>
{{# } }}
{{# if(!d.installed){ }}
<a class="layui-btn layui-btn-xs" lay-event="install">安装</a>
{{# } }}
</script>
<!-- 首页显示开关 -->
<script type="text/html" id="plugin-show">
<input type="checkbox" name="plugin-show-home" lay-skin="switch" lay-text="ON|OFF"
lay-filter="plugin-show-home"
value="{{ d.show }}" data-plugin-slug="{{ d.slug }}"
{{ d.show==
1 ? 'checked' : '' }}>
</script>
</div>
</div>
</div>
<script>
layui.use(['admin', 'table', 'jquery'], function () {
var $ = layui.$
, form = layui.form
, table = layui.table
, admin = layui.admin
table.render({
elem: '#panel-plugin'
, url: '/api/panel/plugin/list'
, cols: [[
{field: 'slug', hide: true, title: 'Slug'}
, {field: 'name', width: 150, title: '插件名', sort: true}
, {field: 'description', title: '描述'}
, {field: 'installed_version', width: 140, title: '已装版本'}
, {field: 'version', width: 140, title: '最新版本'}
, {field: 'show', title: '首页显示', width: 90, templet: '#plugin-show', unresize: true}
, {
field: 'control',
width: 180,
title: '操作',
templet: '#panel-plugin-control',
fixed: 'right',
align: 'left'
}
]]
, page: false
, text: {
none: '无数据'
}
, done: function () {
//element.render('progress');
}
})
// 工具条
table.on('tool(panel-plugin)', function (obj) {
let data = obj.data
if (obj.event === 'open') {
location.hash = '/plugins/' + data.slug
} else if (obj.event === 'install') {
layer.confirm('确定安装该插件吗?', function (index) {
layer.close(index)
admin.req({
url: '/api/panel/plugin/install',
type: 'POST',
data: {
slug: data.slug
}
, success: function (res) {
if (res.code === 0) {
table.reload('panel-plugin')
layer.msg('安装:' + data.name + ' 成功加入任务队列', {
icon: 1,
time: 1000
})
} else {
layer.msg(res.message, {icon: 2, time: 1000})
}
}
})
})
} else if (obj.event === 'uninstall') {
layer.confirm('确定卸载该插件吗?', function (index) {
layer.close(index)
admin.req({
url: '/api/panel/plugin/uninstall',
type: 'POST',
data: {
slug: data.slug
}
, success: function (res) {
if (res.code === 0) {
table.reload('panel-plugin')
layer.msg('卸载:' + data.name + ' 成功加入任务队列', {
icon: 1,
time: 1000
})
} else {
layer.msg(res.message, {icon: 2, time: 1000})
}
}
})
})
} else if (obj.event === 'update') {
layer.confirm('确定升级该插件吗?', function (index) {
layer.close(index)
admin.req({
url: '/api/panel/plugin/update',
type: 'POST',
data: {
slug: data.slug
}
, success: function (res) {
if (res.code === 0) {
table.reload('panel-plugin')
layer.msg('升级:' + data.name + ' 成功加入任务队列', {
icon: 1,
time: 1000
})
} else {
layer.msg(res.message, {icon: 2, time: 1000})
}
}
})
})
}
})
form.on('switch(plugin-show-home)', function (obj) {
let $ = layui.$
let plugin_slug = $(this).data('plugin-slug')
let show = obj.elem.checked ? 1 : 0
admin.req({
url: '/api/panel/plugin/updateShow',
type: 'POST',
data: {
slug: plugin_slug,
show: show
}
, success: function (res) {
if (res.code === 0) {
layer.msg('设置成功', {icon: 1, time: 1000})
} else {
// 还原开关状态
obj.elem.checked = !obj.elem.checked
form.render('checkbox')
layer.msg(res.message, {icon: 2, time: 1000})
}
}
, error: function (xhr, status, error) {
console.log('耗子Linux面板:ajax请求出错,错误' + error)
}
})
})
/*form.render(null, 'plugin-form');
//搜索
form.on('submit(plugin-search-submit)', function (data) {
var field = data.field;
//执行重载
table.reload('plugin-search-submit', {
where: field
});
});*/
})
</script>
-335
View File
@@ -1,335 +0,0 @@
<!--
Name: Fail2ban管理器
Author: 耗子
Date: 2023-07-30
-->
<title>Fail2ban</title>
<div class="layui-fluid" id="component-tabs">
<div class="layui-row">
<div class="layui-col-md12">
<div class="layui-card">
<div class="layui-card-header">Fail2ban 运行状态</div>
<div class="layui-card-body">
<blockquote id="fail2ban-status" class="layui-elem-quote layui-quote-nm">当前状态:<span
class="layui-badge layui-bg-black">获取中</span></blockquote>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="fail2ban-start" class="layui-btn">启动</button>
<button id="fail2ban-stop" class="layui-btn layui-btn-danger">停止</button>
<button id="fail2ban-restart" class="layui-btn layui-btn-warm">重启</button>
<button id="fail2ban-reload" class="layui-btn layui-btn-normal">重载</button>
</div>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>基本设置</legend>
</fieldset>
<div class="layui-form" lay-filter="fail2ban_setting">
<div class="layui-form-item">
<label class="layui-form-label" style="font-size: 13px;">IP白名单</label>
<div class="layui-input-inline">
<input type="text" name="fail2ban_white_list" value="获取中ing..." class="layui-input"
disabled>
</div>
<div class="layui-form-mid layui-word-aux">IP白名单,以英文逗号,分隔</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn layui-btn-sm" lay-submit lay-filter="fail2ban_setting_submit">
确认修改
</button>
</div>
</div>
</div>
</div>
</div>
<div class="layui-card">
<div class="layui-card-header">Fail2ban 规则列表</div>
<div class="layui-card-body">
<table class="layui-hide" id="fail2ban-rule-list" lay-filter="fail2ban-rule-list"></table>
<!-- 顶部工具栏 -->
<script type="text/html" id="fail2ban-rule-list-bar">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="add_rule">新建规则</button>
</div>
</script>
<!-- 右侧管理 -->
<script type="text/html" id="fail2ban-rule-list-control">
<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="view">查看</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
</div>
</div>
</div>
</div>
</div>
<script>
layui.use(['index', 'form', 'table', 'view'], function () {
let $ = layui.$
, admin = layui.admin
, table = layui.table
, form = layui.form
, view = layui.view;
// 获取运行状态并渲染
admin.req({
url: "/api/plugins/fail2ban/status"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
return false;
}
if (result.data) {
$('#fail2ban-status').html('当前状态:<span class="layui-badge layui-bg-green">运行中</span>');
} else {
$('#fail2ban-status').html('当前状态:<span class="layui-badge layui-bg-red">已停止</span>');
}
}
});
// 获取白名单并渲染
admin.req({
url: "/api/plugins/fail2ban/whiteList"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
return false;
}
$('input[name=fail2ban_white_list]').val(result.data);
$('input').attr('disabled', false);
form.render();
}
});
// 监听提交
form.on('submit(fail2ban_setting_submit)', function (data) {
data.field.ip = $('input[name=fail2ban_white_list]').val();
index = layer.msg('请稍候...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: "/api/plugins/fail2ban/whiteList"
, type: 'post'
, data: data.field
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.msg('设置成功', {icon: 1});
}
});
return false;
});
let websiteList = [];
admin.req({
url: '/api/panel/website/list?page=1&limit=10000'
, type: 'get'
, async: false
, success: function (res) {
websiteList = res.data.items;
}
});
// 获取规则列表
table.render({
elem: '#fail2ban-rule-list'
, url: '/api/plugins/fail2ban/list'
, toolbar: '#fail2ban-rule-list-bar'
, title: 'Fail2ban 规则列表'
, cols: [[
{field: 'name', title: '规则名', fixed: 'left', unresize: true, sort: true}
, {
field: 'enabled', title: '状态', templet: function (d) {
if (d.enabled) {
return '<span class="layui-badge layui-bg-green">启用</span>';
} else {
return '<span class="layui-badge layui-bg-gray">禁用</span>';
}
}, sort: true
}
, {field: 'max_retry', title: '最大尝试次数', sort: true}
, {field: 'ban_time', title: '封禁时间', sort: true}
, {field: 'find_time', title: '查找时间', sort: true}
, {field: 'log_path', title: '日志路径'}
, {fixed: 'right', title: '操作', toolbar: '#fail2ban-rule-list-control', width: 150}
]]
, page: true
, text: {
none: '无数据'
}
, parseData: function (res) {
return {
"code": res.code,
"msg": res.message,
"count": res.data.total,
"data": res.data.items
};
}
});
// 头工具栏事件
table.on('toolbar(fail2ban-rule-list)', function (obj) {
if (obj.event === 'add_rule') {
index = layer.msg('加载中...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.popup({
title: '新建Fail2ban规则'
, area: ['600px', '600px']
, id: 'LAY-popup-fail2ban-rule-add'
, success: function () {
layer.close(index);
view(this.id).render('plugins/fail2ban/add_rule', {
websiteList: websiteList
}).done(function () {
form.render(null, 'LAY-popup-fail2ban-rule-add');
});
}
});
}
});
// 行工具事件
table.on('tool(fail2ban-rule-list)', function (obj) {
let data = obj.data;
if (obj.event === 'del') {
layer.confirm('确定要删除 <b style="color: red;">' + data.name + '</b> 吗?', function (index) {
index = layer.msg('请稍等...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/fail2ban/delete"
, type: 'post'
, data: data
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
obj.del();
layer.alert(data.name + '删除成功!');
}
});
});
} else if (obj.event === 'view') {
index = layer.msg('加载中...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/fail2ban/ban?name=" + data.name
, type: 'get'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.popup({
title: '查看Fail2ban规则'
, area: ['600px', '600px']
, id: 'LAY-popup-fail2ban-rule-view'
, success: function () {
layer.close(index);
view(this.id).render('plugins/fail2ban/view_rule', {
data: data
, banList: result.data
}).done(function () {
form.render(null, 'LAY-popup-fail2ban-rule-view');
});
}
});
}
});
}
});
$('#fail2ban-start').click(function () {
layer.confirm('确定要启动Fail2ban吗?', {
btn: ['启动', '取消']
}, function () {
index = layer.msg('请稍等...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/fail2ban/start"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('Fail2ban启动成功!');
}
});
});
});
$('#fail2ban-stop').click(function () {
layer.confirm('停止Fail2ban将导致Fail2ban防护失效,是否继续停止?', {
btn: ['停止', '取消']
}, function () {
index = layer.msg('请稍等...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/fail2ban/stop"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('Fail2ban停止成功!');
}
});
});
});
$('#fail2ban-restart').click(function () {
layer.confirm('确定要重启Fail2ban吗?', {
btn: ['重启', '取消']
}, function () {
index = layer.msg('请稍等...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/fail2ban/restart"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('Fail2ban重启成功!');
}
});
});
});
$('#fail2ban-reload').click(function () {
index = layer.msg('请稍等...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/fail2ban/reload"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('Fail2ban重载成功!');
}
});
});
});
</script>
@@ -1,170 +0,0 @@
<!--
Name: Fail2ban管理器 - 新建规则
Author: 耗子
Date: 2023-07-30
-->
<script type="text/html" template lay-done="layui.data.sendParams(d.params)">
<form class="layui-form" action="" lay-filter="add-pure-ftpd-user-form">
<div class="layui-form-item">
<label class="layui-form-label">类型</label>
<div class="layui-input-block">
<input type="radio" lay-filter="add-fail2ban-rule-type-radio" name="type" value="website"
title="网站" checked="">
<input type="radio" lay-filter="add-fail2ban-rule-type-radio" name="type" value="service"
title="服务">
</div>
</div>
<div id="add-fail2ban-rule-website-input" class="layui-form-item">
<label class="layui-form-label">网站</label>
<div class="layui-input-block">
<select name="website" lay-filter="add-fail2ban-rule-website">
{{# layui.each(d.params.websiteList, function(index, item){ }}
{{# if(index == 0){ }}
<option value="{{ item.name }}" selected="">{{ item.name }}</option>
{{# }else{ }}
<option value="{{ item.name }}">{{ item.name }}</option>
{{# } }}
{{# }); }}
</select>
</div>
</div>
<div id="add-fail2ban-rule-service-input" class="layui-form-item">
<label class="layui-form-label">服务</label>
<div class="layui-input-block">
<select name="service" lay-filter="add-fail2ban-rule-service">
<option value="ssh" selected="">ssh</option>
<option value="mysql">mysql</option>
<option value="pure-ftpd">pure-ftpd</option>
</select>
</div>
</div>
<div id="add-fail2ban-rule-website-mode-input" class="layui-form-item">
<label class="layui-form-label">网站模式</label>
<div class="layui-input-block">
<input type="radio" lay-filter="add-fail2ban-rule-website-mode-radio" name="website_mode" value="cc"
title="CC" checked="">
<input type="radio" lay-filter="add-fail2ban-rule-website-mode-radio" name="website_mode" value="path"
title="目录">
</div>
</div>
<div id="add-fail2ban-rule-website-path-input" class="layui-form-item">
<label class="layui-form-label">网站目录</label>
<div class="layui-input-block">
<input type="text" name="website_path"
lay-verify="required" placeholder="输入一个禁止访问的目录" class="layui-input"
value="/admin">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">最大重试</label>
<div class="layui-input-block">
<input type="text" name="maxretry"
lay-verify="required" placeholder="单位:次" class="layui-input"
value="30">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">周期</label>
<div class="layui-input-block">
<input type="text" name="findtime"
lay-verify="required" placeholder="单位:秒" class="layui-input"
value="300">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">禁止时间</label>
<div class="layui-input-block">
<input type="text" name="bantime"
lay-verify="required" placeholder="单位:秒" class="layui-input"
value="600">
</div>
<div class="layui-form-mid layui-word-aux">
在设置周期内()有超过最大重试()的IP访问将禁止该IP禁止时间()
</div>
<div class="layui-form-mid layui-word-aux">
<span style="color: red;">防护端口自动获取如果修改了规则项对应的端口请删除重新添加否则防护可能不会生效</span>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<div class="layui-footer">
<button class="layui-btn" lay-submit="" lay-filter="add-fail2ban-rule-submit">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</div>
</form>
</script>
<script>
layui.data.sendParams = function (params) {
layui.use(['admin', 'form', 'jquery', 'table'], function () {
var $ = layui.jquery
, admin = layui.admin
, layer = layui.layer
, form = layui.form
, table = layui.table;
form.render();
// 监听类型选择
$('#add-fail2ban-rule-service-input').hide();
form.on('radio(add-fail2ban-rule-type-radio)', function (data) {
if (data.value == 'website') {
$('#add-fail2ban-rule-website-input').show();
$('#add-fail2ban-rule-website-mode-input').show();
$('#add-fail2ban-rule-service-input').hide();
if ($('input[name="website_mode"]:checked').val() == 'cc') {
$('#add-fail2ban-rule-website-path-input').hide();
} else {
$('#add-fail2ban-rule-website-path-input').show();
}
} else if (data.value == 'service') {
$('#add-fail2ban-rule-website-input').hide();
$('#add-fail2ban-rule-website-mode-input').hide();
$('#add-fail2ban-rule-service-input').show();
$('#add-fail2ban-rule-website-path-input').hide();
}
});
// 监听网站模式选择
$('#add-fail2ban-rule-website-path-input').hide();
form.on('radio(add-fail2ban-rule-website-mode-radio)', function (data) {
if (data.value == 'cc') {
$('#add-fail2ban-rule-website-path-input').hide();
} else if (data.value == 'path') {
$('#add-fail2ban-rule-website-path-input').show();
}
});
// 提交
form.on('submit(add-fail2ban-rule-submit)', function (data) {
if (data.field.type === 'website') {
data.field.name = data.field.website;
} else if (data.field.type === 'service') {
data.field.name = data.field.service;
}
index = layer.msg('提交中...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/fail2ban/add"
, type: 'post'
, data: data.field
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
table.reload('fail2ban-rule-list');
layer.alert('Fail2ban规则添加成功!', {
icon: 1
, title: '提示'
, btn: ['确定']
, yes: function (index) {
layer.closeAll();
}
});
}
});
return false;
});
});
};
</script>
@@ -1,101 +0,0 @@
<!--
Name: Fail2ban管理器 - 查看规则
Author: 耗子
Date: 2023-07-30
-->
<script type="text/html" template lay-done="layui.data.sendParams(d.params)">
{{# console.log(d.params) }}
<div class="layui-fluid">
<div class="layui-row layui-col-space15">
<div class="layui-col-sm6 layui-col-md6">
<div class="layui-card">
<div class="layui-card-body layuiadmin-card-list">
<p class="layuiadmin-big-font">{{ d.params.banList.currentlyBan }}</p>
<p>当前封禁IP数</p>
</div>
</div>
</div>
<div class="layui-col-sm6 layui-col-md6">
<div class="layui-card">
<div class="layui-card-body layuiadmin-card-list">
<p class="layuiadmin-big-font">{{ d.params.banList.totalBan }}</p>
<p>累计封禁IP数</p>
</div>
</div>
</div>
</div>
<div class="layui-row layui-col-space15">
<div class="layui-col-sm12 layui-col-md12">
<div class="layui-card">
<div class="layui-card-body layuiadmin-card-list">
<table class="layui-table" id="fail2ban-view-rule-table"
lay-filter="fail2ban-view-rule-table"></table>
</div>
</div>
</div>
</div>
</div>
</script>
<script type="text/html" id="fail2ban-view-rule-ip-control">
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="unBan">解封</a>
</script>
<script>
layui.data.sendParams = function (params) {
if (params.banList.bannedIpList === null) {
params.banList.bannedIpList = [];
}
layui.use(['admin', 'jquery'], function () {
var admin = layui.admin
, layer = layui.layer
, table = layui.table;
table.render({
elem: '#fail2ban-view-rule-table'
, cols: [[
{field: 'name', title: '规则名', unresize: true, hide: true}
, {field: 'ip', title: 'IP', unresize: true, sort: true}
, {
fixed: 'right',
title: '操作',
width: 150,
unresize: true,
toolbar: '#fail2ban-view-rule-ip-control'
}
]]
, data: params.banList.bannedIpList
, page: true
, text: {
none: '无数据'
}
});
// 监听工具条
table.on('tool(fail2ban-view-rule-table)', function (obj) {
var data = obj.data;
if (obj.event === 'unBan') {
layer.confirm('确定要解封 <b style="color: red;">' + data.ip + '</b> 吗?', function (index) {
index = layer.msg('请稍等...', {
icon: 16
, time: 0
});
admin.req({
url: "/api/plugins/fail2ban/unban"
, type: 'post'
, data: data
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
obj.del();
layer.alert(data.ip + '解封成功!');
}
});
layer.close(index);
});
}
});
});
};
</script>
-576
View File
@@ -1,576 +0,0 @@
<!--
Name: MySQL管理器
Author: 耗子
Date: 2022-07-22
-->
<title>MySQL</title>
<div class="layui-fluid" id="component-tabs">
<div class="layui-row">
<div class="layui-col-md12">
<div class="layui-card">
<div class="layui-card-header">MySQL管理</div>
<div class="layui-card-body">
<div class="layui-tab">
<ul class="layui-tab-title">
<li class="layui-this">基本信息</li>
<li>管理</li>
<li>配置修改</li>
<li>负载状态</li>
<li>错误日志</li>
<li>慢查询日志</li>
</ul>
<div class="layui-tab-content">
<div class="layui-tab-item layui-show">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>运行状态</legend>
</fieldset>
<blockquote id="mysql-status" class="layui-elem-quote layui-quote-nm">当前状态:<span
class="layui-badge layui-bg-black">获取中</span></blockquote>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="mysql-start" class="layui-btn">启动</button>
<button id="mysql-stop" class="layui-btn layui-btn-danger">停止</button>
<button id="mysql-restart" class="layui-btn layui-btn-warm">重启</button>
<button id="mysql-reload" class="layui-btn layui-btn-normal">重载</button>
</div>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>基本设置</legend>
</fieldset>
<div class="layui-form" lay-filter="mysql_setting">
<div class="layui-form-item">
<label class="layui-form-label" style="font-size: 13px;">root 密码</label>
<div class="layui-input-inline">
<input type="text" name="mysql_root_password" value="获取中ing..."
class="layui-input" disabled>
</div>
<div class="layui-form-mid layui-word-aux">查看/修改MySQL的root密码</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn layui-btn-sm" lay-submit
lay-filter="mysql_setting_submit">确认修改
</button>
</div>
</div>
</div>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">面板仅集成了部分常用功能,如需更多功能,建议安装
phpMyAdmin 使用。
</blockquote>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>数据库列表</legend>
</fieldset>
<table class="layui-hide" id="mysql-database-list"
lay-filter="mysql-database-list"></table>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>用户列表</legend>
</fieldset>
<table class="layui-hide" id="mysql-user-list" lay-filter="mysql-user-list"></table>
<!-- 数据库顶部工具栏 -->
<script type="text/html" id="mysql-database-list-bar">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="add_database">新建数据库
</button>
</div>
</script>
<!-- 用户顶部工具栏 -->
<script type="text/html" id="mysql-user-list-bar">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="add_user">新建用户</button>
</div>
</script>
<!-- 数据库右侧管理 -->
<script type="text/html" id="mysql-database-list-control">
<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="backup">备份</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<!-- 用户右侧管理 -->
<script type="text/html" id="mysql-user-list-control">
<a class="layui-btn layui-btn-normal layui-btn-xs"
lay-event="change_password">改密</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">此处修改的是MySQL主配置文件,如果你不了解各参数的含义,请不要随意修改!<br>
提示:Ctrl+F 搜索关键字,Ctrl+S 保存,Ctrl+H 查找替换!
</blockquote>
<div id="mysql-config-editor"
style="height: 600px;"></div>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="mysql-config-save" class="layui-btn">保存</button>
</div>
</div>
<div class="layui-tab-item">
<table class="layui-hide" id="mysql-load-status"></table>
</div>
<div class="layui-tab-item">
<div class="layui-btn-container">
<button id="mysql-clean-error-log" class="layui-btn">清空日志</button>
</div>
<pre id="mysql-error-log" class="layui-code">
获取中...
</pre>
</div>
<div class="layui-tab-item">
<div class="layui-btn-container">
<button id="mysql-clean-slow-log" class="layui-btn">清空日志</button>
</div>
<pre id="mysql-slow-log" class="layui-code">
获取中...
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
let mysql_config_editor;// 定义mysql配置编辑器的全局变量
layui.use(['index', 'code', 'table'], function () {
let $ = layui.$
, admin = layui.admin
, element = layui.element
, code = layui.code
, table = layui.table
, form = layui.form
, view = layui.view;
// 渲染表单
form.render();
admin.req({
url: "/api/plugins/mysql57/rootPassword"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:系统信息获取失败,接口返回' + result);
return false;
}
form.val("mysql_setting", {
"mysql_root_password": result.data
});
$('input').attr('disabled', false);
}
});
// 提交修改
form.on('submit(mysql_setting_submit)', function (data) {
index = layer.msg('请稍候...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql57/rootPassword"
, type: 'post'
, data: data.field
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL设置保存失败,接口返回' + result);
return false;
}
layer.msg('修改成功!')
}
});
return false;
});
// 获取mysql运行状态并渲染
admin.req({
url: "/api/plugins/mysql57/status"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL运行状态获取失败,接口返回' + result);
return false;
}
if (result.data) {
$('#mysql-status').html('当前状态:<span class="layui-badge layui-bg-green">运行中</span>');
} else {
$('#mysql-status').html('当前状态:<span class="layui-badge layui-bg-red">已停止</span>');
}
}
});
// 获取数据库列表
table.render({
elem: '#mysql-database-list'
, url: '/api/plugins/mysql57/database'
, toolbar: '#mysql-database-list-bar'
, title: '数据库列表'
, cols: [[
{field: 'name', title: '库名', fixed: 'left', unresize: true, sort: true}
, {fixed: 'right', title: '操作', toolbar: '#mysql-database-list-control', width: 150}
]]
, parseData: function (res) {
return {
"code": res.code,
"msg": res.message,
"count": res.data.total,
"data": res.data.items
};
}
, page: true
});
// 头工具栏事件
table.on('toolbar(mysql-database-list)', function (obj) {
if (obj.event === 'add_database') {
admin.popup({
title: '新建数据库'
, area: ['600px', '300px']
, id: 'LAY-popup-mysql-database-add'
, success: function (layer, index) {
view(this.id).render('plugins/mysql57/add_database', {}).done(function () {
form.render(null, 'LAY-popup-mysql-database-add');
});
}
});
}
});
// 行工具事件
table.on('tool(mysql-database-list)', function (obj) {
let data = obj.data;
if (obj.event === 'del') {
layer.confirm('高风险操作,确定要删除数据库 <b style="color: red;">' + data.name + '</b> 吗?', function (index) {
index = layer.msg('请稍候...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: "/api/plugins/mysql57/deleteDatabase"
, type: 'post'
, data: {
database: data.name
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:数据库删除失败,接口返回' + result);
return false;
}
obj.del();
layer.alert('数据库' + data.name + '删除成功!');
}
});
layer.close(index);
});
} else if (obj.event === 'backup') {
// 打开备份页面
admin.popup({
title: '备份管理 - ' + data.name
, area: ['70%', '80%']
, id: 'LAY-popup-mysql-backup'
, success: function (layero, index) {
view(this.id).render('plugins/mysql57/backup', {
data: data
}).done(function () {
form.render(null, 'LAY-popup-mysql-backup');
});
}
});
}
});
// 获取数据库用户列表
table.render({
elem: '#mysql-user-list'
, url: '/api/plugins/mysql57/user'
, toolbar: '#mysql-user-list-bar'
, title: '用户列表'
, cols: [[
{field: 'user', title: '用户名', fixed: 'left', width: 300, sort: true}
, {field: 'host', title: '主机', width: 250, sort: true}
, {field: 'grants', title: '权限'}
, {fixed: 'right', title: '操作', toolbar: '#mysql-user-list-control', width: 150}
]]
, parseData: function (res) {
return {
"code": res.code,
"msg": res.message,
"count": res.data.total,
"data": res.data.items
};
}
, page: true
});
// 头工具栏事件
table.on('toolbar(mysql-user-list)', function (obj) {
if (obj.event === 'add_user') {
admin.popup({
title: '新建用户'
, area: ['600px', '300px']
, id: 'LAY-popup-mysql-user-add'
, success: function (layer, index) {
view(this.id).render('plugins/mysql57/add_user', {}).done(function () {
form.render(null, 'LAY-popup-mysql-user-add');
});
}
});
}
});
// 行工具事件
table.on('tool(mysql-user-list)', function (obj) {
let data = obj.data;
if (obj.event === 'del') {
layer.confirm('高风险操作,确定要删除用户 <b style="color: red;">' + data.user + '</b> 吗?', function (index) {
index = layer.msg('正在提交...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: "/api/plugins/mysql57/deleteUser"
, type: 'post'
, data: data
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:用户删除失败,接口返回' + result);
return false;
}
obj.del();
layer.alert('用户' + data.user + '删除成功!');
}
});
layer.close(index);
});
} else if (obj.event === 'change_password') {
// 弹出输入密码框
layer.prompt({
formType: 1
, title: '请输入新密码(8位以上大小写数字特殊符号混合)'
}, function (value, index) {
layer.close(index);
index = layer.msg('正在提交...', {icon: 16, time: 0});
// 发送请求
admin.req({
url: "/api/plugins/mysql57/userPassword"
, type: 'post'
, data: {
user: data.user,
password: value
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:密码修改失败,接口返回' + result);
return false;
}
layer.alert('用户' + data.user + '密码修改成功!');
}
});
});
}
});
// 获取mysql错误日志并渲染
admin.req({
url: "/api/plugins/mysql57/errorLog"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL错误日志获取失败,接口返回' + result);
$('#mysql-error-log').text('MySQL错误日志获取失败,请刷新重试!');
code({
elem: '#mysql-error-log'
, title: 'error.log'
, encode: true
, about: false
});
return false;
}
$('#mysql-error-log').text(result.data);
code({
elem: '#mysql-error-log'
, title: 'error.log'
, encode: true
, about: false
});
}
});
// 获取mysql慢查询日志并渲染
admin.req({
url: "/api/plugins/mysql57/slowLog"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL慢查询日志获取失败,接口返回' + result);
$('#mysql-slow-log').text('MySQL慢查询日志获取失败,请刷新重试!');
code({
elem: '#mysql-slow-log'
, title: 'slow.log'
, encode: true
, about: false
});
return false;
}
$('#mysql-slow-log').text(result.data);
code({
elem: '#mysql-slow-log'
, title: 'slow.log'
, encode: true
, about: false
});
}
});
// 获取mysql配置并渲染
admin.req({
url: "/api/plugins/mysql57/config"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL主配置获取失败,接口返回' + result);
return false;
}
$('#mysql-config-editor').text(result.data);
mysql_config_editor = ace.edit("mysql-config-editor", {
mode: "ace/mode/ini",
selectionStyle: "text"
});
}
});
// 获取mysql负载状态并渲染
table.render({
elem: '#mysql-load-status'
, url: '/api/plugins/mysql57/load'
, cols: [[
{field: 'name', width: '80%', title: '属性',}
, {field: 'value', width: '20%', title: '当前值'}
]]
});
element.render();
// 事件监听
$('#mysql-start').click(function () {
layer.confirm('确定要启动MySQL吗?', {
btn: ['启动', '取消']
}, function () {
index = layer.msg('正在启动MySQL...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql57/start"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL启动失败,接口返回' + result);
return false;
}
admin.events.refresh();
layer.alert('MySQL启动成功!');
}
});
});
});
$('#mysql-stop').click(function () {
layer.confirm('停止MySQL将导致使用MySQL的网站无法访问,是否继续停止?', {
btn: ['停止', '取消']
}, function () {
index = layer.msg('正在停止MySQL...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql57/stop"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL停止失败,接口返回' + result);
return false;
}
admin.events.refresh();
layer.alert('MySQL停止成功!');
}
});
});
});
$('#mysql-restart').click(function () {
layer.confirm('重启MySQL将导致使用MySQL的网站短时间无法访问,是否继续重启?', {
btn: ['重启', '取消']
}, function () {
index = layer.msg('正在重启MySQL...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql57/restart"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL重启失败,接口返回' + result);
return false;
}
admin.events.refresh();
layer.alert('MySQL重启成功!');
}
});
});
});
$('#mysql-reload').click(function () {
index = layer.msg('正在重载MySQL...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql57/reload"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL重载失败,接口返回' + result);
return false;
}
admin.events.refresh();
layer.alert('MySQL重载成功!');
}
});
});
$('#mysql-config-save').click(function () {
index = layer.msg('正在保存配置...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql57/config"
, type: 'post'
, data: {
config: mysql_config_editor.getValue()
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL配置保存失败,接口返回' + result);
return false;
}
layer.alert('MySQL配置保存成功!');
}
});
});
$('#mysql-clean-error-log').click(function () {
index = layer.msg('正在清空错误日志...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql57/clearErrorLog"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL错误日志清空失败,接口返回' + result);
return false;
}
layer.msg('MySQL错误日志已清空!');
setTimeout(function () {
admin.events.refresh();
}, 1000);
}
});
});
$('#mysql-clean-slow-log').click(function () {
index = layer.msg('正在清空慢查询日志...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql57/clearSlowLog"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL慢查询日志清空失败,接口返回' + result);
return false;
}
layer.msg('MySQL慢查询日志已清空!');
setTimeout(function () {
admin.events.refresh();
}, 1000);
}
});
});
});
</script>
@@ -1,80 +0,0 @@
<!--
Name: MySQL管理器 - 添加数据库
Author: 耗子
Date: 2023-07-22
-->
<script type="text/html" template lay-done="layui.data.sendParams(d.params)">
<form class="layui-form" action="" lay-filter="add-mysql-database-form">
<div class="layui-form-item">
<label class="layui-form-label">数据库名</label>
<div class="layui-input-block">
<input type="text" name="database" lay-verify="required" placeholder="请输入数据库名"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" name="user" lay-verify="required" placeholder="请输入用户名"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">密码</label>
<div class="layui-input-block">
<input type="text" name="password" lay-verify="required" placeholder="请输入密码(8位以上大小写数字特殊符号混合)"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<div class="layui-footer">
<button class="layui-btn" lay-submit="" lay-filter="add-mysql-database-submit">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</div>
</form>
</script>
<script>
layui.data.sendParams = function (params) {
layui.use(['admin', 'form'], function () {
var $ = layui.$
, admin = layui.admin
, layer = layui.layer
, form = layui.form
, table = layui.table
form.render();
// 提交
form.on('submit(add-mysql-database-submit)', function (data) {
index = layer.msg('正在提交...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: "/api/plugins/mysql57/addDatabase"
, type: 'post'
, data: data.field
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:数据库添加失败,接口返回' + result);
layer.msg('数据库添加失败,请刷新重试!')
return false;
}
table.reload('mysql-database-list');
table.reload('mysql-user-list');
layer.alert('数据库添加成功!', {
icon: 1
, title: '提示'
, btn: ['确定']
, yes: function (index) {
layer.closeAll();
}
});
}
});
return false;
});
});
};
</script>
@@ -1,80 +0,0 @@
<!--
Name: MySQL管理器 - 添加用户
Author: 耗子
Date: 2023-07-22
-->
<script type="text/html" template lay-done="layui.data.sendParams(d.params)">
<form class="layui-form" action="" lay-filter="add-mysql-user-form">
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" name="user" lay-verify="required" placeholder="请输入用户名"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">密码</label>
<div class="layui-input-block">
<input type="text" name="password" lay-verify="required" placeholder="请输入密码(8位以上大小写数字特殊符号混合)"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">数据库</label>
<div class="layui-input-block">
<input type="text" name="database" lay-verify="required" placeholder="输入授权给该用户的数据库名"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<div class="layui-footer">
<button class="layui-btn" lay-submit="" lay-filter="add-mysql-user-submit">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</div>
</form>
</script>
<script>
layui.data.sendParams = function (params) {
layui.use(['admin', 'form'], function () {
var $ = layui.$
, admin = layui.admin
, layer = layui.layer
, form = layui.form
, table = layui.table
form.render();
// 提交
form.on('submit(add-mysql-user-submit)', function (data) {
index = layer.msg('正在提交...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: "/api/plugins/mysql57/addUser"
, type: 'post'
, data: data.field
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:用户添加失败,接口返回' + result);
layer.msg('用户添加失败,请刷新重试!')
return false;
}
table.reload('mysql-database-list');
table.reload('mysql-user-list');
layer.alert('用户添加成功!', {
icon: 1
, title: '提示'
, btn: ['确定']
, yes: function (index) {
layer.closeAll();
}
});
}
});
return false;
});
});
};
</script>
@@ -1,145 +0,0 @@
<!--
Name: MySQL管理器 - 数据库备份
Author: 耗子
Date: 2023-07-22
-->
<script type="text/html" template lay-done="layui.data.sendParams(d.params)">
<div class="layui-row">
<div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
<table class="layui-hide" id="mysql-backup-list" lay-filter="mysql-backup-list"></table>
</div>
</div>
</script>
<!-- 备份顶部工具栏 -->
<script type="text/html" id="mysql-database-backup-bar">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="backup_database">备份数据库</button>
<button class="layui-btn layui-btn-sm" id="upload_mysql_backup">上传备份</button>
</div>
</script>
<!-- 备份右侧管理 -->
<script type="text/html" id="mysql-database-backup-control">
<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="restore">恢复</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>
layui.data.sendParams = function (params) {
layui.use(['admin', 'form', 'laydate', 'code'], function () {
var $ = layui.$
, admin = layui.admin
, layer = layui.layer
, table = layui.table
, upload = layui.upload;
// 渲染表格
table.render({
elem: '#mysql-backup-list'
, url: '/api/plugins/mysql57/backup'
, toolbar: '#mysql-database-backup-bar'
, title: '备份列表'
, cols: [[
{field: 'name', title: '备份名称', width: 500}
, {field: 'size', title: '文件大小'}
, {field: 'right', title: '操作', width: 150, toolbar: '#mysql-database-backup-control'}
]]
, text: {
none: '无备份数据'
}
, done: function (res, curr, count) {
upload.render({
elem: '#upload_mysql_backup'
, url: '/api/plugins/mysql57/uploadBackup'
, accept: 'file'
, ext: 'sql|zip|rar|tar|gz|bz2'
, before: function (obj) {
index = layer.msg('正在上传备份文件,可能需要较长时间,请勿操作...', {
icon: 16
, time: 0
});
}
, done: function (res) {
layer.close(index);
layer.msg('上传成功!', {icon: 1});
table.reload('mysql-backup-list');
}
});
}
});
// 头工具栏事件
table.on('toolbar(mysql-backup-list)', function (obj) {
if (obj.event === 'backup_database') {
index = layer.msg('正在备份数据库,请稍等...', {
icon: 16
, time: 0
});
admin.req({
url: '/api/plugins/mysql57/createBackup'
, type: 'post'
, data: {
database: params.data.name
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:备份数据库失败,接口返回' + result);
layer.alert('备份失败!');
return false;
}
table.reload('mysql-backup-list');
layer.msg('备份成功!', {icon: 1});
}
});
}
});
// 行工具事件
table.on('tool(mysql-backup-list)', function (obj) {
let data = obj.data;
if (obj.event === 'del') {
layer.confirm('确定要删除数据库备份 <b style="color: red;">' + data.name + '</b> 吗?', function (index) {
index = layer.msg('正在删除数据库备份,请稍等...', {
icon: 16
, time: 0
});
admin.req({
url: "/api/plugins/mysql57/deleteBackup"
, type: 'post'
, data: data
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:数据库备份删除失败,接口返回' + result);
layer.msg('数据库备份删除失败,请刷新重试!')
return false;
}
obj.del();
layer.alert('数据库备份' + data.name + '删除成功!');
}
});
});
} else if (obj.event === 'restore') {
layer.confirm('高风险操作,确定要恢复数据库备份 <b style="color: red;">' + data.name + '</b> 吗?', function (index) {
index = layer.msg('正在恢复数据库备份,可能需要较长时间,请勿操作...', {
icon: 16
, time: 0
});
data.database = params.data.name;
admin.req({
url: "/api/plugins/mysql57/restoreBackup"
, type: 'post'
, data: data
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:数据库恢复失败,接口返回' + result);
layer.msg('数据库备份恢复失败,请刷新重试!')
return false;
}
layer.alert('数据库备份' + data.name + '恢复成功!');
}
});
});
}
});
});
};
</script>
-576
View File
@@ -1,576 +0,0 @@
<!--
Name: MySQL管理器
Author: 耗子
Date: 2022-07-22
-->
<title>MySQL</title>
<div class="layui-fluid" id="component-tabs">
<div class="layui-row">
<div class="layui-col-md12">
<div class="layui-card">
<div class="layui-card-header">MySQL管理</div>
<div class="layui-card-body">
<div class="layui-tab">
<ul class="layui-tab-title">
<li class="layui-this">基本信息</li>
<li>管理</li>
<li>配置修改</li>
<li>负载状态</li>
<li>错误日志</li>
<li>慢查询日志</li>
</ul>
<div class="layui-tab-content">
<div class="layui-tab-item layui-show">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>运行状态</legend>
</fieldset>
<blockquote id="mysql-status" class="layui-elem-quote layui-quote-nm">当前状态:<span
class="layui-badge layui-bg-black">获取中</span></blockquote>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="mysql-start" class="layui-btn">启动</button>
<button id="mysql-stop" class="layui-btn layui-btn-danger">停止</button>
<button id="mysql-restart" class="layui-btn layui-btn-warm">重启</button>
<button id="mysql-reload" class="layui-btn layui-btn-normal">重载</button>
</div>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>基本设置</legend>
</fieldset>
<div class="layui-form" lay-filter="mysql_setting">
<div class="layui-form-item">
<label class="layui-form-label" style="font-size: 13px;">root 密码</label>
<div class="layui-input-inline">
<input type="text" name="mysql_root_password" value="获取中ing..."
class="layui-input" disabled>
</div>
<div class="layui-form-mid layui-word-aux">查看/修改MySQL的root密码</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn layui-btn-sm" lay-submit
lay-filter="mysql_setting_submit">确认修改
</button>
</div>
</div>
</div>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">面板仅集成了部分常用功能,如需更多功能,建议安装
phpMyAdmin 使用。
</blockquote>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>数据库列表</legend>
</fieldset>
<table class="layui-hide" id="mysql-database-list"
lay-filter="mysql-database-list"></table>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>用户列表</legend>
</fieldset>
<table class="layui-hide" id="mysql-user-list" lay-filter="mysql-user-list"></table>
<!-- 数据库顶部工具栏 -->
<script type="text/html" id="mysql-database-list-bar">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="add_database">新建数据库
</button>
</div>
</script>
<!-- 用户顶部工具栏 -->
<script type="text/html" id="mysql-user-list-bar">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="add_user">新建用户</button>
</div>
</script>
<!-- 数据库右侧管理 -->
<script type="text/html" id="mysql-database-list-control">
<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="backup">备份</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<!-- 用户右侧管理 -->
<script type="text/html" id="mysql-user-list-control">
<a class="layui-btn layui-btn-normal layui-btn-xs"
lay-event="change_password">改密</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">此处修改的是MySQL主配置文件,如果你不了解各参数的含义,请不要随意修改!<br>
提示:Ctrl+F 搜索关键字,Ctrl+S 保存,Ctrl+H 查找替换!
</blockquote>
<div id="mysql-config-editor"
style="height: 600px;"></div>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="mysql-config-save" class="layui-btn">保存</button>
</div>
</div>
<div class="layui-tab-item">
<table class="layui-hide" id="mysql-load-status"></table>
</div>
<div class="layui-tab-item">
<div class="layui-btn-container">
<button id="mysql-clean-error-log" class="layui-btn">清空日志</button>
</div>
<pre id="mysql-error-log" class="layui-code">
获取中...
</pre>
</div>
<div class="layui-tab-item">
<div class="layui-btn-container">
<button id="mysql-clean-slow-log" class="layui-btn">清空日志</button>
</div>
<pre id="mysql-slow-log" class="layui-code">
获取中...
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
let mysql_config_editor;// 定义mysql配置编辑器的全局变量
layui.use(['index', 'code', 'table'], function () {
let $ = layui.$
, admin = layui.admin
, element = layui.element
, code = layui.code
, table = layui.table
, form = layui.form
, view = layui.view;
// 渲染表单
form.render();
admin.req({
url: "/api/plugins/mysql80/rootPassword"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:系统信息获取失败,接口返回' + result);
return false;
}
form.val("mysql_setting", {
"mysql_root_password": result.data
});
$('input').attr('disabled', false);
}
});
// 提交修改
form.on('submit(mysql_setting_submit)', function (data) {
index = layer.msg('请稍候...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql80/rootPassword"
, type: 'post'
, data: data.field
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL设置保存失败,接口返回' + result);
return false;
}
layer.msg('修改成功!')
}
});
return false;
});
// 获取mysql运行状态并渲染
admin.req({
url: "/api/plugins/mysql80/status"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL运行状态获取失败,接口返回' + result);
return false;
}
if (result.data) {
$('#mysql-status').html('当前状态:<span class="layui-badge layui-bg-green">运行中</span>');
} else {
$('#mysql-status').html('当前状态:<span class="layui-badge layui-bg-red">已停止</span>');
}
}
});
// 获取数据库列表
table.render({
elem: '#mysql-database-list'
, url: '/api/plugins/mysql80/database'
, toolbar: '#mysql-database-list-bar'
, title: '数据库列表'
, cols: [[
{field: 'name', title: '库名', fixed: 'left', unresize: true, sort: true}
, {fixed: 'right', title: '操作', toolbar: '#mysql-database-list-control', width: 150}
]]
, parseData: function (res) {
return {
"code": res.code,
"msg": res.message,
"count": res.data.total,
"data": res.data.items
};
}
, page: true
});
// 头工具栏事件
table.on('toolbar(mysql-database-list)', function (obj) {
if (obj.event === 'add_database') {
admin.popup({
title: '新建数据库'
, area: ['600px', '300px']
, id: 'LAY-popup-mysql-database-add'
, success: function (layer, index) {
view(this.id).render('plugins/mysql80/add_database', {}).done(function () {
form.render(null, 'LAY-popup-mysql-database-add');
});
}
});
}
});
// 行工具事件
table.on('tool(mysql-database-list)', function (obj) {
let data = obj.data;
if (obj.event === 'del') {
layer.confirm('高风险操作,确定要删除数据库 <b style="color: red;">' + data.name + '</b> 吗?', function (index) {
index = layer.msg('请稍候...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: "/api/plugins/mysql80/deleteDatabase"
, type: 'post'
, data: {
database: data.name
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:数据库删除失败,接口返回' + result);
return false;
}
obj.del();
layer.alert('数据库' + data.name + '删除成功!');
}
});
layer.close(index);
});
} else if (obj.event === 'backup') {
// 打开备份页面
admin.popup({
title: '备份管理 - ' + data.name
, area: ['70%', '80%']
, id: 'LAY-popup-mysql-backup'
, success: function (layero, index) {
view(this.id).render('plugins/mysql80/backup', {
data: data
}).done(function () {
form.render(null, 'LAY-popup-mysql-backup');
});
}
});
}
});
// 获取数据库用户列表
table.render({
elem: '#mysql-user-list'
, url: '/api/plugins/mysql80/user'
, toolbar: '#mysql-user-list-bar'
, title: '用户列表'
, cols: [[
{field: 'user', title: '用户名', fixed: 'left', width: 300, sort: true}
, {field: 'host', title: '主机', width: 250, sort: true}
, {field: 'grants', title: '权限'}
, {fixed: 'right', title: '操作', toolbar: '#mysql-user-list-control', width: 150}
]]
, parseData: function (res) {
return {
"code": res.code,
"msg": res.message,
"count": res.data.total,
"data": res.data.items
};
}
, page: true
});
// 头工具栏事件
table.on('toolbar(mysql-user-list)', function (obj) {
if (obj.event === 'add_user') {
admin.popup({
title: '新建用户'
, area: ['600px', '300px']
, id: 'LAY-popup-mysql-user-add'
, success: function (layer, index) {
view(this.id).render('plugins/mysql80/add_user', {}).done(function () {
form.render(null, 'LAY-popup-mysql-user-add');
});
}
});
}
});
// 行工具事件
table.on('tool(mysql-user-list)', function (obj) {
let data = obj.data;
if (obj.event === 'del') {
layer.confirm('高风险操作,确定要删除用户 <b style="color: red;">' + data.user + '</b> 吗?', function (index) {
index = layer.msg('正在提交...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: "/api/plugins/mysql80/deleteUser"
, type: 'post'
, data: data
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:用户删除失败,接口返回' + result);
return false;
}
obj.del();
layer.alert('用户' + data.user + '删除成功!');
}
});
layer.close(index);
});
} else if (obj.event === 'change_password') {
// 弹出输入密码框
layer.prompt({
formType: 1
, title: '请输入新密码(8位以上大小写数字特殊符号混合)'
}, function (value, index) {
layer.close(index);
index = layer.msg('正在提交...', {icon: 16, time: 0});
// 发送请求
admin.req({
url: "/api/plugins/mysql80/userPassword"
, type: 'post'
, data: {
user: data.user,
password: value
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:密码修改失败,接口返回' + result);
return false;
}
layer.alert('用户' + data.user + '密码修改成功!');
}
});
});
}
});
// 获取mysql错误日志并渲染
admin.req({
url: "/api/plugins/mysql80/errorLog"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL错误日志获取失败,接口返回' + result);
$('#mysql-error-log').text('MySQL错误日志获取失败,请刷新重试!');
code({
elem: '#mysql-error-log'
, title: 'error.log'
, encode: true
, about: false
});
return false;
}
$('#mysql-error-log').text(result.data);
code({
elem: '#mysql-error-log'
, title: 'error.log'
, encode: true
, about: false
});
}
});
// 获取mysql慢查询日志并渲染
admin.req({
url: "/api/plugins/mysql80/slowLog"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL慢查询日志获取失败,接口返回' + result);
$('#mysql-slow-log').text('MySQL慢查询日志获取失败,请刷新重试!');
code({
elem: '#mysql-slow-log'
, title: 'slow.log'
, encode: true
, about: false
});
return false;
}
$('#mysql-slow-log').text(result.data);
code({
elem: '#mysql-slow-log'
, title: 'slow.log'
, encode: true
, about: false
});
}
});
// 获取mysql配置并渲染
admin.req({
url: "/api/plugins/mysql80/config"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL主配置获取失败,接口返回' + result);
return false;
}
$('#mysql-config-editor').text(result.data);
mysql_config_editor = ace.edit("mysql-config-editor", {
mode: "ace/mode/ini",
selectionStyle: "text"
});
}
});
// 获取mysql负载状态并渲染
table.render({
elem: '#mysql-load-status'
, url: '/api/plugins/mysql80/load'
, cols: [[
{field: 'name', width: '80%', title: '属性',}
, {field: 'value', width: '20%', title: '当前值'}
]]
});
element.render();
// 事件监听
$('#mysql-start').click(function () {
layer.confirm('确定要启动MySQL吗?', {
btn: ['启动', '取消']
}, function () {
index = layer.msg('正在启动MySQL...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql80/start"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL启动失败,接口返回' + result);
return false;
}
admin.events.refresh();
layer.alert('MySQL启动成功!');
}
});
});
});
$('#mysql-stop').click(function () {
layer.confirm('停止MySQL将导致使用MySQL的网站无法访问,是否继续停止?', {
btn: ['停止', '取消']
}, function () {
index = layer.msg('正在停止MySQL...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql80/stop"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL停止失败,接口返回' + result);
return false;
}
admin.events.refresh();
layer.alert('MySQL停止成功!');
}
});
});
});
$('#mysql-restart').click(function () {
layer.confirm('重启MySQL将导致使用MySQL的网站短时间无法访问,是否继续重启?', {
btn: ['重启', '取消']
}, function () {
index = layer.msg('正在重启MySQL...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql80/restart"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL重启失败,接口返回' + result);
return false;
}
admin.events.refresh();
layer.alert('MySQL重启成功!');
}
});
});
});
$('#mysql-reload').click(function () {
index = layer.msg('正在重载MySQL...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql80/reload"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL重载失败,接口返回' + result);
return false;
}
admin.events.refresh();
layer.alert('MySQL重载成功!');
}
});
});
$('#mysql-config-save').click(function () {
index = layer.msg('正在保存配置...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql80/config"
, type: 'post'
, data: {
config: mysql_config_editor.getValue()
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL配置保存失败,接口返回' + result);
return false;
}
layer.alert('MySQL配置保存成功!');
}
});
});
$('#mysql-clean-error-log').click(function () {
index = layer.msg('正在清空错误日志...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql80/clearErrorLog"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL错误日志清空失败,接口返回' + result);
return false;
}
layer.msg('MySQL错误日志已清空!');
setTimeout(function () {
admin.events.refresh();
}, 1000);
}
});
});
$('#mysql-clean-slow-log').click(function () {
index = layer.msg('正在清空慢查询日志...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/mysql80/clearSlowLog"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:MySQL慢查询日志清空失败,接口返回' + result);
return false;
}
layer.msg('MySQL慢查询日志已清空!');
setTimeout(function () {
admin.events.refresh();
}, 1000);
}
});
});
});
</script>
@@ -1,80 +0,0 @@
<!--
Name: MySQL管理器 - 添加数据库
Author: 耗子
Date: 2023-07-22
-->
<script type="text/html" template lay-done="layui.data.sendParams(d.params)">
<form class="layui-form" action="" lay-filter="add-mysql-database-form">
<div class="layui-form-item">
<label class="layui-form-label">数据库名</label>
<div class="layui-input-block">
<input type="text" name="database" lay-verify="required" placeholder="请输入数据库名"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" name="user" lay-verify="required" placeholder="请输入用户名"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">密码</label>
<div class="layui-input-block">
<input type="text" name="password" lay-verify="required" placeholder="请输入密码(8位以上大小写数字特殊符号混合)"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<div class="layui-footer">
<button class="layui-btn" lay-submit="" lay-filter="add-mysql-database-submit">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</div>
</form>
</script>
<script>
layui.data.sendParams = function (params) {
layui.use(['admin', 'form'], function () {
var $ = layui.$
, admin = layui.admin
, layer = layui.layer
, form = layui.form
, table = layui.table
form.render();
// 提交
form.on('submit(add-mysql-database-submit)', function (data) {
index = layer.msg('正在提交...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: "/api/plugins/mysql80/addDatabase"
, type: 'post'
, data: data.field
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:数据库添加失败,接口返回' + result);
layer.msg('数据库添加失败,请刷新重试!')
return false;
}
table.reload('mysql-database-list');
table.reload('mysql-user-list');
layer.alert('数据库添加成功!', {
icon: 1
, title: '提示'
, btn: ['确定']
, yes: function (index) {
layer.closeAll();
}
});
}
});
return false;
});
});
};
</script>
@@ -1,80 +0,0 @@
<!--
Name: MySQL管理器 - 添加用户
Author: 耗子
Date: 2023-07-22
-->
<script type="text/html" template lay-done="layui.data.sendParams(d.params)">
<form class="layui-form" action="" lay-filter="add-mysql-user-form">
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" name="user" lay-verify="required" placeholder="请输入用户名"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">密码</label>
<div class="layui-input-block">
<input type="text" name="password" lay-verify="required" placeholder="请输入密码(8位以上大小写数字特殊符号混合)"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">数据库</label>
<div class="layui-input-block">
<input type="text" name="database" lay-verify="required" placeholder="输入授权给该用户的数据库名"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<div class="layui-footer">
<button class="layui-btn" lay-submit="" lay-filter="add-mysql-user-submit">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</div>
</form>
</script>
<script>
layui.data.sendParams = function (params) {
layui.use(['admin', 'form'], function () {
var $ = layui.$
, admin = layui.admin
, layer = layui.layer
, form = layui.form
, table = layui.table
form.render();
// 提交
form.on('submit(add-mysql-user-submit)', function (data) {
index = layer.msg('正在提交...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: "/api/plugins/mysql80/addUser"
, type: 'post'
, data: data.field
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:用户添加失败,接口返回' + result);
layer.msg('用户添加失败,请刷新重试!')
return false;
}
table.reload('mysql-database-list');
table.reload('mysql-user-list');
layer.alert('用户添加成功!', {
icon: 1
, title: '提示'
, btn: ['确定']
, yes: function (index) {
layer.closeAll();
}
});
}
});
return false;
});
});
};
</script>
@@ -1,145 +0,0 @@
<!--
Name: MySQL管理器 - 数据库备份
Author: 耗子
Date: 2023-07-22
-->
<script type="text/html" template lay-done="layui.data.sendParams(d.params)">
<div class="layui-row">
<div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
<table class="layui-hide" id="mysql-backup-list" lay-filter="mysql-backup-list"></table>
</div>
</div>
</script>
<!-- 备份顶部工具栏 -->
<script type="text/html" id="mysql-database-backup-bar">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="backup_database">备份数据库</button>
<button class="layui-btn layui-btn-sm" id="upload_mysql_backup">上传备份</button>
</div>
</script>
<!-- 备份右侧管理 -->
<script type="text/html" id="mysql-database-backup-control">
<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="restore">恢复</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>
layui.data.sendParams = function (params) {
layui.use(['admin', 'form', 'laydate', 'code'], function () {
var $ = layui.$
, admin = layui.admin
, layer = layui.layer
, table = layui.table
, upload = layui.upload;
// 渲染表格
table.render({
elem: '#mysql-backup-list'
, url: '/api/plugins/mysql80/backup'
, toolbar: '#mysql-database-backup-bar'
, title: '备份列表'
, cols: [[
{field: 'name', title: '备份名称', width: 500}
, {field: 'size', title: '文件大小'}
, {field: 'right', title: '操作', width: 150, toolbar: '#mysql-database-backup-control'}
]]
, text: {
none: '无备份数据'
}
, done: function (res, curr, count) {
upload.render({
elem: '#upload_mysql_backup'
, url: '/api/plugins/mysql80/uploadBackup'
, accept: 'file'
, ext: 'sql|zip|rar|tar|gz|bz2'
, before: function (obj) {
index = layer.msg('正在上传备份文件,可能需要较长时间,请勿操作...', {
icon: 16
, time: 0
});
}
, done: function (res) {
layer.close(index);
layer.msg('上传成功!', {icon: 1});
table.reload('mysql-backup-list');
}
});
}
});
// 头工具栏事件
table.on('toolbar(mysql-backup-list)', function (obj) {
if (obj.event === 'backup_database') {
index = layer.msg('正在备份数据库,请稍等...', {
icon: 16
, time: 0
});
admin.req({
url: '/api/plugins/mysql80/createBackup'
, type: 'post'
, data: {
database: params.data.name
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:备份数据库失败,接口返回' + result);
layer.alert('备份失败!');
return false;
}
table.reload('mysql-backup-list');
layer.msg('备份成功!', {icon: 1});
}
});
}
});
// 行工具事件
table.on('tool(mysql-backup-list)', function (obj) {
let data = obj.data;
if (obj.event === 'del') {
layer.confirm('确定要删除数据库备份 <b style="color: red;">' + data.name + '</b> 吗?', function (index) {
index = layer.msg('正在删除数据库备份,请稍等...', {
icon: 16
, time: 0
});
admin.req({
url: "/api/plugins/mysql80/deleteBackup"
, type: 'post'
, data: data
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:数据库备份删除失败,接口返回' + result);
layer.msg('数据库备份删除失败,请刷新重试!')
return false;
}
obj.del();
layer.alert('数据库备份' + data.name + '删除成功!');
}
});
});
} else if (obj.event === 'restore') {
layer.confirm('高风险操作,确定要恢复数据库备份 <b style="color: red;">' + data.name + '</b> 吗?', function (index) {
index = layer.msg('正在恢复数据库备份,可能需要较长时间,请勿操作...', {
icon: 16
, time: 0
});
data.database = params.data.name;
admin.req({
url: "/api/plugins/mysql80/restoreBackup"
, type: 'post'
, data: data
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
console.log('耗子Linux面板:数据库恢复失败,接口返回' + result);
layer.msg('数据库备份恢复失败,请刷新重试!')
return false;
}
layer.alert('数据库备份' + data.name + '恢复成功!');
}
});
});
}
});
});
};
</script>
-245
View File
@@ -1,245 +0,0 @@
<!--
Name: Openresty管理器
Author: 耗子
Date: 2023-06-24
-->
<title>OpenResty</title>
<div class="layui-fluid" id="component-tabs">
<div class="layui-row">
<div class="layui-col-md12">
<div class="layui-card">
<div class="layui-card-header">OpenResty管理</div>
<div class="layui-card-body">
<div class="layui-tab">
<ul class="layui-tab-title">
<li class="layui-this">运行状态</li>
<li>配置修改</li>
<li>负载状态</li>
<li>错误日志</li>
</ul>
<div class="layui-tab-content">
<div class="layui-tab-item layui-show">
<blockquote id="openresty-status" class="layui-elem-quote layui-quote-nm">当前状态:<span
class="layui-badge layui-bg-black">获取中</span></blockquote>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="openresty-start" class="layui-btn">启动</button>
<button id="openresty-stop" class="layui-btn layui-btn-danger">停止</button>
<button id="openresty-restart" class="layui-btn layui-btn-warm">重启</button>
<button id="openresty-reload" class="layui-btn layui-btn-normal">重载</button>
</div>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">此处修改的是OpenResty主配置文件,如果你不了解各参数的含义,请不要随意修改!<br>
提示:Ctrl+F 搜索关键字,Ctrl+S 保存,Ctrl+H 查找替换!
</blockquote>
<div id="openresty-config-editor"
style="height: 600px;"></div>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="openresty-config-save" class="layui-btn">保存</button>
</div>
</div>
<div class="layui-tab-item">
<table class="layui-hide" id="openresty-load-status"></table>
</div>
<div class="layui-tab-item">
<div class="layui-btn-container">
<button id="openresty-clear-error-log" class="layui-btn">清空日志</button>
</div>
<pre id="openresty-error-log" class="layui-code">
获取中...
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
let openresty_config_editor
layui.use(['index', 'code', 'table'], function () {
let $ = layui.$
, admin = layui.admin
, element = layui.element
, code = layui.code
, table = layui.table
admin.req({
url: '/api/plugins/openresty/status'
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:OpenResty运行状态获取失败,接口返回' + result)
return false
}
if (result.data) {
$('#openresty-status').html('当前状态:<span class="layui-badge layui-bg-green">运行中</span>')
} else {
$('#openresty-status').html('当前状态:<span class="layui-badge layui-bg-red">已停止</span>')
}
}
})
// 获取openresty错误日志并渲染
admin.req({
url: '/api/plugins/openresty/errorLog'
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:OpenResty错误日志获取失败,接口返回' + result)
$('#openresty-error-log').text('OpenResty错误日志获取失败,请刷新重试!')
code({
elem: '#openresty-error-log'
, title: 'error.log'
, encode: true
, about: false
})
return false
}
$('#openresty-error-log').text(result.data)
code({
elem: '#openresty-error-log'
, title: 'error.log'
, encode: true
, about: false
})
}
})
// 获取openresty配置并渲染
admin.req({
url: '/api/plugins/openresty/config'
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:OpenResty主配置获取失败,接口返回' + result)
return false
}
$('#openresty-config-editor').text(result.data)
openresty_config_editor = ace.edit('openresty-config-editor', {
mode: 'ace/mode/nginx',
selectionStyle: 'text'
})
}
})
// 获取openresty负载状态并渲染
table.render({
elem: '#openresty-load-status'
, url: '/api/plugins/openresty/load'
, cols: [[
{ field: 'name', width: '80%', title: '属性', }
, { field: 'value', width: '20%', title: '当前值' }
]]
})
element.render()
// 事件监听
$('#openresty-start').click(function () {
index = layer.msg('正在启动OpenResty...', { icon: 16, time: 0, shade: 0.3 })
admin.req({
url: '/api/plugins/openresty/start'
, type: 'post'
, success: function (result) {
layer.close(index)
if (result.code !== 0) {
return false
}
admin.events.refresh()
layer.alert('OpenResty启动成功!')
}
})
})
$('#openresty-stop').click(function () {
layer.confirm('停止OpenResty将导致网站无法访问,是否继续停止?', {
btn: ['停止', '取消']
}, function () {
index = layer.msg('正在停止OpenResty...', { icon: 16, time: 0, shade: 0.3 })
admin.req({
url: '/api/plugins/openresty/stop'
, type: 'post'
, success: function (result) {
layer.close(index)
if (result.code !== 0) {
return false
}
admin.events.refresh()
layer.alert('OpenResty停止成功!')
}
})
})
})
$('#openresty-restart').click(function () {
layer.confirm('重启OpenResty将导致网站短时间无法访问,是否继续重启?', {
btn: ['重启', '取消']
}, function () {
index = layer.msg('正在重启OpenResty...', { icon: 16, time: 0, shade: 0.3 })
admin.req({
url: '/api/plugins/openresty/restart'
, type: 'post'
, success: function (result) {
layer.close(index)
if (result.code !== 0) {
return false
}
admin.events.refresh()
layer.alert('OpenResty重启成功!')
}
})
})
})
$('#openresty-reload').click(function () {
index = layer.msg('正在重载OpenResty...', { icon: 16, time: 0, shade: 0.3 })
admin.req({
url: '/api/plugins/openresty/reload'
, type: 'post'
, success: function (result) {
layer.close(index)
if (result.code !== 0) {
return false
}
admin.events.refresh()
layer.alert('OpenResty重载成功!')
}
})
})
$('#openresty-config-save').click(function () {
index = layer.msg('正在保存OpenResty主配置...', { icon: 16, time: 0, shade: 0.3 })
admin.req({
url: '/api/plugins/openresty/config'
, type: 'post'
, data: {
config: openresty_config_editor.getValue()
}
, success: function (result) {
layer.close(index)
if (result.code !== 0) {
return false
}
layer.alert('OpenResty配置保存成功!')
}
})
})
$('#openresty-clear-error-log').click(function () {
index = layer.msg('正在清空OpenResty错误日志...', { icon: 16, time: 0, shade: 0.3 })
admin.req({
url: '/api/plugins/openresty/clearErrorLog'
, type: 'post'
, success: function (result) {
layer.close(index)
if (result.code !== 0) {
console.log('耗子Linux面板:OpenResty错误日志清空失败,接口返回' + result)
return false
}
admin.events.refresh()
layer.msg('OpenResty错误日志已清空!')
}
})
})
})
</script>
-381
View File
@@ -1,381 +0,0 @@
<!--
Name: PHP管理器
Author: 耗子
Date: 2023-07-22
-->
<title>PHP-7.4</title>
<div class="layui-fluid" id="component-tabs">
<div class="layui-row">
<div class="layui-col-md12">
<div class="layui-card">
<div class="layui-card-header">PHP-7.4管理</div>
<div class="layui-card-body">
<div class="layui-tab">
<ul class="layui-tab-title">
<li class="layui-this">运行状态</li>
<li>拓展管理</li>
<li>配置修改</li>
<li>负载状态</li>
<li>运行日志</li>
<li>慢日志</li>
</ul>
<div class="layui-tab-content">
<div class="layui-tab-item layui-show">
<blockquote id="php74-status" class="layui-elem-quote layui-quote-nm">当前状态:<span
class="layui-badge layui-bg-black">获取中</span></blockquote>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="php74-start" class="layui-btn">启动</button>
<button id="php74-stop" class="layui-btn layui-btn-danger">停止</button>
<button id="php74-restart" class="layui-btn layui-btn-warm">重启</button>
<button id="php74-reload" class="layui-btn layui-btn-normal">重载</button>
</div>
</div>
<div class="layui-tab-item">
<table id="php74-extension" lay-filter="php74-extension"></table>
<!-- 操作按钮模板 -->
<script type="text/html" id="php74-extension-control">
{{# if(d.installed == true){ }}
<a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="uninstall">卸载</a>
{{# } else{ }}
<a class="layui-btn layui-btn-xs" lay-event="install">安装</a>
{{# } }}
</script>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">此处修改的是PHP主配置文件,如果你不了解各参数的含义,请不要随意修改!<br>
提示:Ctrl+F 搜索关键字,Ctrl+S 保存,Ctrl+H 查找替换!
</blockquote>
<div id="php74-config-editor"
style="height: 600px;"></div>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="php74-config-save" class="layui-btn">保存</button>
</div>
</div>
<div class="layui-tab-item">
<table class="layui-hide" id="php74-load-status"></table>
</div>
<div class="layui-tab-item">
<div class="layui-btn-container">
<button id="php74-clean-error-log" class="layui-btn">清空日志</button>
</div>
<pre id="php74-error-log" class="layui-code">
获取中...
</pre>
</div>
<div class="layui-tab-item">
<div class="layui-btn-container">
<button id="php74-clean-slow-log" class="layui-btn">清空日志</button>
</div>
<pre id="php74-slow-log" class="layui-code">
获取中...
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
let php74_config_editor;
layui.use(['index', 'code', 'table'], function () {
let $ = layui.$
, admin = layui.admin
, element = layui.element
, code = layui.code
, table = layui.table;
// 获取php74运行状态并渲染
admin.req({
url: "/api/plugins/php74/status"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:PHP运行状态获取失败,接口返回' + result);
return false;
}
if (result.data) {
$('#php74-status').html('当前状态:<span class="layui-badge layui-bg-green">运行中</span>');
} else {
$('#php74-status').html('当前状态:<span class="layui-badge layui-bg-red">已停止</span>');
}
}
});
// 获取php74错误日志并渲染
admin.req({
url: "/api/plugins/php74/errorLog"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
$('#php74-error-log').text('PHP日志获取失败,请刷新重试!');
code({
elem: '#php74-error-log'
, title: 'php-fpm.log'
, encode: true
, about: false
});
return false;
}
$('#php74-error-log').text(result.data);
code({
elem: '#php74-error-log'
, title: 'php-fpm.log'
, encode: true
, about: false
});
}
});
// 获取php74慢日志并渲染
admin.req({
url: "/api/plugins/php74/slowLog"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
$('#php74-slow-log').text('PHP慢日志获取失败,请刷新重试!');
code({
elem: '#php74-slow-log'
, title: 'slow.log'
, encode: true
, about: false
});
return false;
}
$('#php74-slow-log').text(result.data);
code({
elem: '#php74-slow-log'
, title: 'slow.log'
, encode: true
, about: false
});
}
});
// 获取php74配置并渲染
admin.req({
url: "/api/plugins/php74/config"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:PHP主配置获取失败,接口返回' + result);
return false;
}
$('#php74-config-editor').text(result.data);
php74_config_editor = ace.edit("php74-config-editor", {
mode: "ace/mode/ini",
selectionStyle: "text"
});
}
});
// 获取php74负载状态并渲染
table.render({
elem: '#php74-load-status'
, url: '/api/plugins/php74/load'
, cols: [[
{field: 'name', width: '80%', title: '属性',}
, {field: 'value', width: '20%', title: '当前值'}
]]
});
element.render();
// 获取php74扩展并渲染
table.render({
elem: '#php74-extension'
, url: '/api/plugins/php74/extensions'
, cols: [[
{field: 'slug', hide: true, title: 'Slug', sort: true}
, {field: 'name', width: '20%', title: '拓展名'}
, {field: 'description', width: '70%', title: '描述'}
, {
field: 'control',
title: '操作',
templet: '#php74-extension-control',
fixed: 'right',
align: 'left'
}
]]
, page: false
, text: {
none: '暂无拓展'
}
});
// 工具条
table.on('tool(php74-extension)', function (obj) {
let data = obj.data;
if (obj.event === 'install') {
layer.confirm('确定安装该拓展吗?', function (index) {
layer.close(index);
index = layer.msg('请稍后...', {icon: 16, time: 0});
admin.req({
url: '/api/plugins/php74/installExtension',
type: 'POST',
data: {
slug: data.slug
}
, success: function (res) {
if (res.code === 0) {
layer.close(index);
table.reload('php74-extension');
layer.msg('安装:' + data.name + ' 成功加入任务队列', {
icon: 1,
time: 1000
});
} else {
layer.msg(res.msg, {icon: 2, time: 1000});
}
}
});
});
} else if (obj.event === 'uninstall') {
layer.confirm('确定卸载该拓展吗?', function (index) {
layer.close(index);
index = layer.msg('请稍后...', {icon: 16, time: 0});
admin.req({
url: '/api/plugins/php74/uninstallExtension',
type: 'POST',
data: {
slug: data.slug
}
, success: function (res) {
layer.close(index);
if (res.code === 0) {
table.reload('php74-extension');
layer.msg('卸载:' + data.name + ' 成功加入任务队列', {icon: 1, time: 1000});
} else {
layer.msg(res.msg, {icon: 2, time: 1000});
}
}
});
});
}
});
// 事件监听
$('#php74-start').click(function () {
index = layer.msg('正在启动PHP,请稍后...', {icon: 16, time: 0});
layer.confirm('确定要启动PHP吗?', {
btn: ['启动', '取消']
}, function () {
admin.req({
url: "/api/plugins/php74/start"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PHP启动成功!');
}
});
});
});
$('#php74-stop').click(function () {
layer.confirm('停止PHP将导致使用PHP的网站无法访问,是否继续停止?', {
btn: ['停止', '取消']
}, function () {
index = layer.msg('正在停止PHP,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php74/stop"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PHP停止成功!');
}
});
});
});
$('#php74-restart').click(function () {
layer.confirm('重启PHP将导致使用PHP的网站短时间无法访问,是否继续重启?', {
btn: ['重启', '取消']
}, function () {
index = layer.msg('正在重启PHP,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php74/restart"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PHP重启成功!');
}
});
});
});
$('#php74-reload').click(function () {
index = layer.msg('正在重载PHP,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php74/reload"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('PHP重载成功!');
}
});
});
$('#php74-config-save').click(function () {
index = layer.msg('正在保存配置,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php74/config"
, type: 'post'
, data: {
config: php74_config_editor.getValue()
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('PHP配置保存成功!');
}
});
});
$('#php74-clean-error-log').click(function () {
index = layer.msg('正在清空错误日志,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php74/clearErrorLog"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.msg('PHP日志已清空!');
}
});
});
$('#php74-clean-slow-log').click(function () {
index = layer.msg('正在清空慢日志,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php74/clearSlowLog"
, type: 'post'
, success: function (result) {
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.msg('PHP慢日志已清空!');
}
});
});
});
</script>
-381
View File
@@ -1,381 +0,0 @@
<!--
Name: PHP管理器
Author: 耗子
Date: 2023-07-22
-->
<title>PHP-8.0</title>
<div class="layui-fluid" id="component-tabs">
<div class="layui-row">
<div class="layui-col-md12">
<div class="layui-card">
<div class="layui-card-header">PHP-8.0管理</div>
<div class="layui-card-body">
<div class="layui-tab">
<ul class="layui-tab-title">
<li class="layui-this">运行状态</li>
<li>拓展管理</li>
<li>配置修改</li>
<li>负载状态</li>
<li>运行日志</li>
<li>慢日志</li>
</ul>
<div class="layui-tab-content">
<div class="layui-tab-item layui-show">
<blockquote id="php80-status" class="layui-elem-quote layui-quote-nm">当前状态:<span
class="layui-badge layui-bg-black">获取中</span></blockquote>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="php80-start" class="layui-btn">启动</button>
<button id="php80-stop" class="layui-btn layui-btn-danger">停止</button>
<button id="php80-restart" class="layui-btn layui-btn-warm">重启</button>
<button id="php80-reload" class="layui-btn layui-btn-normal">重载</button>
</div>
</div>
<div class="layui-tab-item">
<table id="php80-extension" lay-filter="php80-extension"></table>
<!-- 操作按钮模板 -->
<script type="text/html" id="php80-extension-control">
{{# if(d.installed == true){ }}
<a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="uninstall">卸载</a>
{{# } else{ }}
<a class="layui-btn layui-btn-xs" lay-event="install">安装</a>
{{# } }}
</script>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">此处修改的是PHP主配置文件,如果你不了解各参数的含义,请不要随意修改!<br>
提示:Ctrl+F 搜索关键字,Ctrl+S 保存,Ctrl+H 查找替换!
</blockquote>
<div id="php80-config-editor"
style="height: 600px;"></div>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="php80-config-save" class="layui-btn">保存</button>
</div>
</div>
<div class="layui-tab-item">
<table class="layui-hide" id="php80-load-status"></table>
</div>
<div class="layui-tab-item">
<div class="layui-btn-container">
<button id="php80-clean-error-log" class="layui-btn">清空日志</button>
</div>
<pre id="php80-error-log" class="layui-code">
获取中...
</pre>
</div>
<div class="layui-tab-item">
<div class="layui-btn-container">
<button id="php80-clean-slow-log" class="layui-btn">清空日志</button>
</div>
<pre id="php80-slow-log" class="layui-code">
获取中...
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
let php80_config_editor;
layui.use(['index', 'code', 'table'], function () {
let $ = layui.$
, admin = layui.admin
, element = layui.element
, code = layui.code
, table = layui.table;
// 获取php80运行状态并渲染
admin.req({
url: "/api/plugins/php80/status"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:PHP运行状态获取失败,接口返回' + result);
return false;
}
if (result.data) {
$('#php80-status').html('当前状态:<span class="layui-badge layui-bg-green">运行中</span>');
} else {
$('#php80-status').html('当前状态:<span class="layui-badge layui-bg-red">已停止</span>');
}
}
});
// 获取php80错误日志并渲染
admin.req({
url: "/api/plugins/php80/errorLog"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
$('#php80-error-log').text('PHP日志获取失败,请刷新重试!');
code({
elem: '#php80-error-log'
, title: 'php-fpm.log'
, encode: true
, about: false
});
return false;
}
$('#php80-error-log').text(result.data);
code({
elem: '#php80-error-log'
, title: 'php-fpm.log'
, encode: true
, about: false
});
}
});
// 获取php80慢日志并渲染
admin.req({
url: "/api/plugins/php80/slowLog"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
$('#php80-slow-log').text('PHP慢日志获取失败,请刷新重试!');
code({
elem: '#php80-slow-log'
, title: 'slow.log'
, encode: true
, about: false
});
return false;
}
$('#php80-slow-log').text(result.data);
code({
elem: '#php80-slow-log'
, title: 'slow.log'
, encode: true
, about: false
});
}
});
// 获取php80配置并渲染
admin.req({
url: "/api/plugins/php80/config"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:PHP主配置获取失败,接口返回' + result);
return false;
}
$('#php80-config-editor').text(result.data);
php80_config_editor = ace.edit("php80-config-editor", {
mode: "ace/mode/ini",
selectionStyle: "text"
});
}
});
// 获取php80负载状态并渲染
table.render({
elem: '#php80-load-status'
, url: '/api/plugins/php80/load'
, cols: [[
{field: 'name', width: '80%', title: '属性',}
, {field: 'value', width: '20%', title: '当前值'}
]]
});
element.render();
// 获取php80扩展并渲染
table.render({
elem: '#php80-extension'
, url: '/api/plugins/php80/extensions'
, cols: [[
{field: 'slug', hide: true, title: 'Slug', sort: true}
, {field: 'name', width: '20%', title: '拓展名'}
, {field: 'description', width: '70%', title: '描述'}
, {
field: 'control',
title: '操作',
templet: '#php80-extension-control',
fixed: 'right',
align: 'left'
}
]]
, page: false
, text: {
none: '暂无拓展'
}
});
// 工具条
table.on('tool(php80-extension)', function (obj) {
let data = obj.data;
if (obj.event === 'install') {
layer.confirm('确定安装该拓展吗?', function (index) {
layer.close(index);
index = layer.msg('请稍后...', {icon: 16, time: 0});
admin.req({
url: '/api/plugins/php80/installExtension',
type: 'POST',
data: {
slug: data.slug
}
, success: function (res) {
if (res.code === 0) {
layer.close(index);
table.reload('php80-extension');
layer.msg('安装:' + data.name + ' 成功加入任务队列', {
icon: 1,
time: 1000
});
} else {
layer.msg(res.msg, {icon: 2, time: 1000});
}
}
});
});
} else if (obj.event === 'uninstall') {
layer.confirm('确定卸载该拓展吗?', function (index) {
layer.close(index);
index = layer.msg('请稍后...', {icon: 16, time: 0});
admin.req({
url: '/api/plugins/php80/uninstallExtension',
type: 'POST',
data: {
slug: data.slug
}
, success: function (res) {
layer.close(index);
if (res.code === 0) {
table.reload('php80-extension');
layer.msg('卸载:' + data.name + ' 成功加入任务队列', {icon: 1, time: 1000});
} else {
layer.msg(res.msg, {icon: 2, time: 1000});
}
}
});
});
}
});
// 事件监听
$('#php80-start').click(function () {
index = layer.msg('正在启动PHP,请稍后...', {icon: 16, time: 0});
layer.confirm('确定要启动PHP吗?', {
btn: ['启动', '取消']
}, function () {
admin.req({
url: "/api/plugins/php80/start"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PHP启动成功!');
}
});
});
});
$('#php80-stop').click(function () {
layer.confirm('停止PHP将导致使用PHP的网站无法访问,是否继续停止?', {
btn: ['停止', '取消']
}, function () {
index = layer.msg('正在停止PHP,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php80/stop"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PHP停止成功!');
}
});
});
});
$('#php80-restart').click(function () {
layer.confirm('重启PHP将导致使用PHP的网站短时间无法访问,是否继续重启?', {
btn: ['重启', '取消']
}, function () {
index = layer.msg('正在重启PHP,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php80/restart"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PHP重启成功!');
}
});
});
});
$('#php80-reload').click(function () {
index = layer.msg('正在重载PHP,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php80/reload"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('PHP重载成功!');
}
});
});
$('#php80-config-save').click(function () {
index = layer.msg('正在保存配置,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php80/config"
, type: 'post'
, data: {
config: php80_config_editor.getValue()
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('PHP配置保存成功!');
}
});
});
$('#php80-clean-error-log').click(function () {
index = layer.msg('正在清空错误日志,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php80/clearErrorLog"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.msg('PHP日志已清空!');
}
});
});
$('#php80-clean-slow-log').click(function () {
index = layer.msg('正在清空慢日志,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php80/clearSlowLog"
, type: 'post'
, success: function (result) {
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.msg('PHP慢日志已清空!');
}
});
});
});
</script>
-381
View File
@@ -1,381 +0,0 @@
<!--
Name: PHP管理器
Author: 耗子
Date: 2023-07-22
-->
<title>PHP-8.1</title>
<div class="layui-fluid" id="component-tabs">
<div class="layui-row">
<div class="layui-col-md12">
<div class="layui-card">
<div class="layui-card-header">PHP-8.1管理</div>
<div class="layui-card-body">
<div class="layui-tab">
<ul class="layui-tab-title">
<li class="layui-this">运行状态</li>
<li>拓展管理</li>
<li>配置修改</li>
<li>负载状态</li>
<li>运行日志</li>
<li>慢日志</li>
</ul>
<div class="layui-tab-content">
<div class="layui-tab-item layui-show">
<blockquote id="php81-status" class="layui-elem-quote layui-quote-nm">当前状态:<span
class="layui-badge layui-bg-black">获取中</span></blockquote>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="php81-start" class="layui-btn">启动</button>
<button id="php81-stop" class="layui-btn layui-btn-danger">停止</button>
<button id="php81-restart" class="layui-btn layui-btn-warm">重启</button>
<button id="php81-reload" class="layui-btn layui-btn-normal">重载</button>
</div>
</div>
<div class="layui-tab-item">
<table id="php81-extension" lay-filter="php81-extension"></table>
<!-- 操作按钮模板 -->
<script type="text/html" id="php81-extension-control">
{{# if(d.installed == true){ }}
<a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="uninstall">卸载</a>
{{# } else{ }}
<a class="layui-btn layui-btn-xs" lay-event="install">安装</a>
{{# } }}
</script>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">此处修改的是PHP主配置文件,如果你不了解各参数的含义,请不要随意修改!<br>
提示:Ctrl+F 搜索关键字,Ctrl+S 保存,Ctrl+H 查找替换!
</blockquote>
<div id="php81-config-editor"
style="height: 600px;"></div>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="php81-config-save" class="layui-btn">保存</button>
</div>
</div>
<div class="layui-tab-item">
<table class="layui-hide" id="php81-load-status"></table>
</div>
<div class="layui-tab-item">
<div class="layui-btn-container">
<button id="php81-clean-error-log" class="layui-btn">清空日志</button>
</div>
<pre id="php81-error-log" class="layui-code">
获取中...
</pre>
</div>
<div class="layui-tab-item">
<div class="layui-btn-container">
<button id="php81-clean-slow-log" class="layui-btn">清空日志</button>
</div>
<pre id="php81-slow-log" class="layui-code">
获取中...
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
let php81_config_editor;
layui.use(['index', 'code', 'table'], function () {
let $ = layui.$
, admin = layui.admin
, element = layui.element
, code = layui.code
, table = layui.table;
// 获取php81运行状态并渲染
admin.req({
url: "/api/plugins/php81/status"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:PHP运行状态获取失败,接口返回' + result);
return false;
}
if (result.data) {
$('#php81-status').html('当前状态:<span class="layui-badge layui-bg-green">运行中</span>');
} else {
$('#php81-status').html('当前状态:<span class="layui-badge layui-bg-red">已停止</span>');
}
}
});
// 获取php81错误日志并渲染
admin.req({
url: "/api/plugins/php81/errorLog"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
$('#php81-error-log').text('PHP日志获取失败,请刷新重试!');
code({
elem: '#php81-error-log'
, title: 'php-fpm.log'
, encode: true
, about: false
});
return false;
}
$('#php81-error-log').text(result.data);
code({
elem: '#php81-error-log'
, title: 'php-fpm.log'
, encode: true
, about: false
});
}
});
// 获取php81慢日志并渲染
admin.req({
url: "/api/plugins/php81/slowLog"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
$('#php81-slow-log').text('PHP慢日志获取失败,请刷新重试!');
code({
elem: '#php81-slow-log'
, title: 'slow.log'
, encode: true
, about: false
});
return false;
}
$('#php81-slow-log').text(result.data);
code({
elem: '#php81-slow-log'
, title: 'slow.log'
, encode: true
, about: false
});
}
});
// 获取php81配置并渲染
admin.req({
url: "/api/plugins/php81/config"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:PHP主配置获取失败,接口返回' + result);
return false;
}
$('#php81-config-editor').text(result.data);
php81_config_editor = ace.edit("php81-config-editor", {
mode: "ace/mode/ini",
selectionStyle: "text"
});
}
});
// 获取php81负载状态并渲染
table.render({
elem: '#php81-load-status'
, url: '/api/plugins/php81/load'
, cols: [[
{field: 'name', width: '81%', title: '属性',}
, {field: 'value', width: '20%', title: '当前值'}
]]
});
element.render();
// 获取php81扩展并渲染
table.render({
elem: '#php81-extension'
, url: '/api/plugins/php81/extensions'
, cols: [[
{field: 'slug', hide: true, title: 'Slug', sort: true}
, {field: 'name', width: '20%', title: '拓展名'}
, {field: 'description', width: '70%', title: '描述'}
, {
field: 'control',
title: '操作',
templet: '#php81-extension-control',
fixed: 'right',
align: 'left'
}
]]
, page: false
, text: {
none: '暂无拓展'
}
});
// 工具条
table.on('tool(php81-extension)', function (obj) {
let data = obj.data;
if (obj.event === 'install') {
layer.confirm('确定安装该拓展吗?', function (index) {
layer.close(index);
index = layer.msg('请稍后...', {icon: 16, time: 0});
admin.req({
url: '/api/plugins/php81/installExtension',
type: 'POST',
data: {
slug: data.slug
}
, success: function (res) {
if (res.code === 0) {
layer.close(index);
table.reload('php81-extension');
layer.msg('安装:' + data.name + ' 成功加入任务队列', {
icon: 1,
time: 1000
});
} else {
layer.msg(res.msg, {icon: 2, time: 1000});
}
}
});
});
} else if (obj.event === 'uninstall') {
layer.confirm('确定卸载该拓展吗?', function (index) {
layer.close(index);
index = layer.msg('请稍后...', {icon: 16, time: 0});
admin.req({
url: '/api/plugins/php81/uninstallExtension',
type: 'POST',
data: {
slug: data.slug
}
, success: function (res) {
layer.close(index);
if (res.code === 0) {
table.reload('php81-extension');
layer.msg('卸载:' + data.name + ' 成功加入任务队列', {icon: 1, time: 1000});
} else {
layer.msg(res.msg, {icon: 2, time: 1000});
}
}
});
});
}
});
// 事件监听
$('#php81-start').click(function () {
index = layer.msg('正在启动PHP,请稍后...', {icon: 16, time: 0});
layer.confirm('确定要启动PHP吗?', {
btn: ['启动', '取消']
}, function () {
admin.req({
url: "/api/plugins/php81/start"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PHP启动成功!');
}
});
});
});
$('#php81-stop').click(function () {
layer.confirm('停止PHP将导致使用PHP的网站无法访问,是否继续停止?', {
btn: ['停止', '取消']
}, function () {
index = layer.msg('正在停止PHP,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php81/stop"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PHP停止成功!');
}
});
});
});
$('#php81-restart').click(function () {
layer.confirm('重启PHP将导致使用PHP的网站短时间无法访问,是否继续重启?', {
btn: ['重启', '取消']
}, function () {
index = layer.msg('正在重启PHP,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php81/restart"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PHP重启成功!');
}
});
});
});
$('#php81-reload').click(function () {
index = layer.msg('正在重载PHP,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php81/reload"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('PHP重载成功!');
}
});
});
$('#php81-config-save').click(function () {
index = layer.msg('正在保存配置,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php81/config"
, type: 'post'
, data: {
config: php81_config_editor.getValue()
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('PHP配置保存成功!');
}
});
});
$('#php81-clean-error-log').click(function () {
index = layer.msg('正在清空错误日志,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php81/clearErrorLog"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.msg('PHP日志已清空!');
}
});
});
$('#php81-clean-slow-log').click(function () {
index = layer.msg('正在清空慢日志,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php81/clearSlowLog"
, type: 'post'
, success: function (result) {
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.msg('PHP慢日志已清空!');
}
});
});
});
</script>
-381
View File
@@ -1,381 +0,0 @@
<!--
Name: PHP管理器
Author: 耗子
Date: 2023-07-22
-->
<title>PHP-8.2</title>
<div class="layui-fluid" id="component-tabs">
<div class="layui-row">
<div class="layui-col-md12">
<div class="layui-card">
<div class="layui-card-header">PHP-8.2管理</div>
<div class="layui-card-body">
<div class="layui-tab">
<ul class="layui-tab-title">
<li class="layui-this">运行状态</li>
<li>拓展管理</li>
<li>配置修改</li>
<li>负载状态</li>
<li>运行日志</li>
<li>慢日志</li>
</ul>
<div class="layui-tab-content">
<div class="layui-tab-item layui-show">
<blockquote id="php82-status" class="layui-elem-quote layui-quote-nm">当前状态:<span
class="layui-badge layui-bg-black">获取中</span></blockquote>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="php82-start" class="layui-btn">启动</button>
<button id="php82-stop" class="layui-btn layui-btn-danger">停止</button>
<button id="php82-restart" class="layui-btn layui-btn-warm">重启</button>
<button id="php82-reload" class="layui-btn layui-btn-normal">重载</button>
</div>
</div>
<div class="layui-tab-item">
<table id="php82-extension" lay-filter="php82-extension"></table>
<!-- 操作按钮模板 -->
<script type="text/html" id="php82-extension-control">
{{# if(d.installed == true){ }}
<a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="uninstall">卸载</a>
{{# } else{ }}
<a class="layui-btn layui-btn-xs" lay-event="install">安装</a>
{{# } }}
</script>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">此处修改的是PHP主配置文件,如果你不了解各参数的含义,请不要随意修改!<br>
提示:Ctrl+F 搜索关键字,Ctrl+S 保存,Ctrl+H 查找替换!
</blockquote>
<div id="php82-config-editor"
style="height: 600px;"></div>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="php82-config-save" class="layui-btn">保存</button>
</div>
</div>
<div class="layui-tab-item">
<table class="layui-hide" id="php82-load-status"></table>
</div>
<div class="layui-tab-item">
<div class="layui-btn-container">
<button id="php82-clean-error-log" class="layui-btn">清空日志</button>
</div>
<pre id="php82-error-log" class="layui-code">
获取中...
</pre>
</div>
<div class="layui-tab-item">
<div class="layui-btn-container">
<button id="php82-clean-slow-log" class="layui-btn">清空日志</button>
</div>
<pre id="php82-slow-log" class="layui-code">
获取中...
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
let php82_config_editor;
layui.use(['index', 'code', 'table'], function () {
let $ = layui.$
, admin = layui.admin
, element = layui.element
, code = layui.code
, table = layui.table;
// 获取php82运行状态并渲染
admin.req({
url: "/api/plugins/php82/status"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:PHP运行状态获取失败,接口返回' + result);
return false;
}
if (result.data) {
$('#php82-status').html('当前状态:<span class="layui-badge layui-bg-green">运行中</span>');
} else {
$('#php82-status').html('当前状态:<span class="layui-badge layui-bg-red">已停止</span>');
}
}
});
// 获取php82错误日志并渲染
admin.req({
url: "/api/plugins/php82/errorLog"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
$('#php82-error-log').text('PHP日志获取失败,请刷新重试!');
code({
elem: '#php82-error-log'
, title: 'php-fpm.log'
, encode: true
, about: false
});
return false;
}
$('#php82-error-log').text(result.data);
code({
elem: '#php82-error-log'
, title: 'php-fpm.log'
, encode: true
, about: false
});
}
});
// 获取php82慢日志并渲染
admin.req({
url: "/api/plugins/php82/slowLog"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
$('#php82-slow-log').text('PHP慢日志获取失败,请刷新重试!');
code({
elem: '#php82-slow-log'
, title: 'slow.log'
, encode: true
, about: false
});
return false;
}
$('#php82-slow-log').text(result.data);
code({
elem: '#php82-slow-log'
, title: 'slow.log'
, encode: true
, about: false
});
}
});
// 获取php82配置并渲染
admin.req({
url: "/api/plugins/php82/config"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
console.log('耗子Linux面板:PHP主配置获取失败,接口返回' + result);
return false;
}
$('#php82-config-editor').text(result.data);
php82_config_editor = ace.edit("php82-config-editor", {
mode: "ace/mode/ini",
selectionStyle: "text"
});
}
});
// 获取php82负载状态并渲染
table.render({
elem: '#php82-load-status'
, url: '/api/plugins/php82/load'
, cols: [[
{field: 'name', width: '82%', title: '属性',}
, {field: 'value', width: '20%', title: '当前值'}
]]
});
element.render();
// 获取php82扩展并渲染
table.render({
elem: '#php82-extension'
, url: '/api/plugins/php82/extensions'
, cols: [[
{field: 'slug', hide: true, title: 'Slug', sort: true}
, {field: 'name', width: '20%', title: '拓展名'}
, {field: 'description', width: '70%', title: '描述'}
, {
field: 'control',
title: '操作',
templet: '#php82-extension-control',
fixed: 'right',
align: 'left'
}
]]
, page: false
, text: {
none: '暂无拓展'
}
});
// 工具条
table.on('tool(php82-extension)', function (obj) {
let data = obj.data;
if (obj.event === 'install') {
layer.confirm('确定安装该拓展吗?', function (index) {
layer.close(index);
index = layer.msg('请稍后...', {icon: 16, time: 0});
admin.req({
url: '/api/plugins/php82/installExtension',
type: 'POST',
data: {
slug: data.slug
}
, success: function (res) {
if (res.code === 0) {
layer.close(index);
table.reload('php82-extension');
layer.msg('安装:' + data.name + ' 成功加入任务队列', {
icon: 1,
time: 1000
});
} else {
layer.msg(res.msg, {icon: 2, time: 1000});
}
}
});
});
} else if (obj.event === 'uninstall') {
layer.confirm('确定卸载该拓展吗?', function (index) {
layer.close(index);
index = layer.msg('请稍后...', {icon: 16, time: 0});
admin.req({
url: '/api/plugins/php82/uninstallExtension',
type: 'POST',
data: {
slug: data.slug
}
, success: function (res) {
layer.close(index);
if (res.code === 0) {
table.reload('php82-extension');
layer.msg('卸载:' + data.name + ' 成功加入任务队列', {icon: 1, time: 1000});
} else {
layer.msg(res.msg, {icon: 2, time: 1000});
}
}
});
});
}
});
// 事件监听
$('#php82-start').click(function () {
index = layer.msg('正在启动PHP,请稍后...', {icon: 16, time: 0});
layer.confirm('确定要启动PHP吗?', {
btn: ['启动', '取消']
}, function () {
admin.req({
url: "/api/plugins/php82/start"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PHP启动成功!');
}
});
});
});
$('#php82-stop').click(function () {
layer.confirm('停止PHP将导致使用PHP的网站无法访问,是否继续停止?', {
btn: ['停止', '取消']
}, function () {
index = layer.msg('正在停止PHP,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php82/stop"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PHP停止成功!');
}
});
});
});
$('#php82-restart').click(function () {
layer.confirm('重启PHP将导致使用PHP的网站短时间无法访问,是否继续重启?', {
btn: ['重启', '取消']
}, function () {
index = layer.msg('正在重启PHP,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php82/restart"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PHP重启成功!');
}
});
});
});
$('#php82-reload').click(function () {
index = layer.msg('正在重载PHP,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php82/reload"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('PHP重载成功!');
}
});
});
$('#php82-config-save').click(function () {
index = layer.msg('正在保存配置,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php82/config"
, type: 'post'
, data: {
config: php82_config_editor.getValue()
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('PHP配置保存成功!');
}
});
});
$('#php82-clean-error-log').click(function () {
index = layer.msg('正在清空错误日志,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php82/clearErrorLog"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.msg('PHP日志已清空!');
}
});
});
$('#php82-clean-slow-log').click(function () {
index = layer.msg('正在清空慢日志,请稍后...', {icon: 16, time: 0});
admin.req({
url: "/api/plugins/php82/clearSlowLog"
, type: 'post'
, success: function (result) {
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.msg('PHP慢日志已清空!');
}
});
});
});
</script>
@@ -1,92 +0,0 @@
<!--
Name: phpMyAdmin 管理器
Author: 耗子
Date: 2023-07-22
-->
<title>phpMyAdmin</title>
<div class="layui-fluid" id="component-tabs">
<div class="layui-row">
<div class="layui-col-md12">
<div class="layui-card">
<div class="layui-card-header">phpMyAdmin 信息</div>
<div class="layui-card-body">
<blockquote class="layui-elem-quote layui-quote-nm">访问地址:<span
id="phpmyadmin-info">获取中...</span></blockquote>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>基本设置</legend>
</fieldset>
<div class="layui-form" lay-filter="phpmyadmin_setting">
<div class="layui-form-item">
<label class="layui-form-label" style="font-size: 13px;">访问端口</label>
<div class="layui-input-inline">
<input type="text" name="phpmyadmin_port" value="获取中ing..." class="layui-input"
disabled>
</div>
<div class="layui-form-mid layui-word-aux">查看 / 修改 phpMyAdmin 访问端口</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn layui-btn-sm" lay-submit
lay-filter="phpmyadmin_setting_submit">确认修改
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
layui.use(['index', 'code', 'table', 'form'], function () {
let $ = layui.$
, form = layui.form
, admin = layui.admin;
// 获取phpmyadmin信息
admin.req({
url: "/api/plugins/phpmyadmin/info"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
layer.alert('phpMyAdmin 信息获取失败,可能已损坏!', {
icon: 2
});
return false;
}
// 获取当前域名
let hostname = window.location.hostname;
// 拼接phpmyadmin访问地址
let phpmyadmin_url = 'http://' + hostname + ':' + result.data.port + '/' + result.data.phpmyadmin;
$('#phpmyadmin-info').html('<a href="' + phpmyadmin_url + '" target="_blank">' + phpmyadmin_url + '</a>');
$('input[name=phpmyadmin_port]').val(result.data.port);
$('input').attr('disabled', false);
form.render();
}
});
// 监听phpmyadmin设置提交
form.on('submit(phpmyadmin_setting_submit)', function (data) {
data.field.port = data.field.phpmyadmin_port;
index = layer.msg('请稍候...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: "/api/plugins/phpmyadmin/port"
, type: 'post'
, data: data.field
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
layer.alert('phpMyAdmin设置失败,可能已损坏!', {
icon: 2
});
return false;
}
layer.msg('设置成功', {
icon: 1
});
}
});
});
});
</script>
@@ -1,524 +0,0 @@
<!--
Name: PostgreSQL管理器
Author: 耗子
Date: 2023-08-13
-->
<title>PostgreSQL</title>
<div class="layui-fluid" id="component-tabs">
<div class="layui-row">
<div class="layui-col-md12">
<div class="layui-card">
<div class="layui-card-header">PostgreSQL管理</div>
<div class="layui-card-body">
<div class="layui-tab">
<ul class="layui-tab-title">
<li class="layui-this">基本信息</li>
<li>管理</li>
<li>主配置</li>
<li>用户配置</li>
<li>负载状态</li>
<li>日志</li>
</ul>
<div class="layui-tab-content">
<div class="layui-tab-item layui-show">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>运行状态</legend>
</fieldset>
<blockquote id="postgresql-status" class="layui-elem-quote layui-quote-nm">
当前状态:<span
class="layui-badge layui-bg-black">获取中</span></blockquote>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="postgresql-start" class="layui-btn">启动</button>
<button id="postgresql-stop" class="layui-btn layui-btn-danger">停止</button>
<button id="postgresql-restart" class="layui-btn layui-btn-warm">重启</button>
<button id="postgresql-reload" class="layui-btn layui-btn-normal">重载</button>
</div>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">面板仅集成了部分常用功能,如需更多功能,请使用
pgAdmin 客户端。
</blockquote>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>数据库列表</legend>
</fieldset>
<table class="layui-hide" id="postgresql-database-list"
lay-filter="postgresql-database-list"></table>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>用户列表</legend>
</fieldset>
<table class="layui-hide" id="postgresql-user-list"
lay-filter="postgresql-user-list"></table>
<!-- 数据库顶部工具栏 -->
<script type="text/html" id="postgresql-database-list-bar">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="add_database">新建数据库
</button>
</div>
</script>
<!-- 用户顶部工具栏 -->
<script type="text/html" id="postgresql-user-list-bar">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="add_user">新建用户</button>
</div>
</script>
<!-- 数据库右侧管理 -->
<script type="text/html" id="postgresql-database-list-control">
<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="backup">备份</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<!-- 用户右侧管理 -->
<script type="text/html" id="postgresql-user-list-control">
<a class="layui-btn layui-btn-normal layui-btn-xs"
lay-event="change_password">改密</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">此处修改的是PostgreSQL主配置文件,如果你不了解各参数的含义,请不要随意修改!<br>
提示:Ctrl+F 搜索关键字,Ctrl+S 保存,Ctrl+H 查找替换!
</blockquote>
<div id="postgresql-config-editor"
style="height: 600px;"></div>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="postgresql-config-save" class="layui-btn">保存</button>
</div>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">此处修改的是PostgreSQL用户配置文件,如果你不了解各参数的含义,请不要随意修改!<br>
提示:Ctrl+F 搜索关键字,Ctrl+S 保存,Ctrl+H 查找替换!
</blockquote>
<div id="postgresql-user-config-editor"
style="height: 600px;"></div>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="postgresql-user-config-save" class="layui-btn">保存</button>
</div>
</div>
<div class="layui-tab-item">
<table class="layui-hide" id="postgresql-load-status"></table>
</div>
<div class="layui-tab-item">
<pre id="postgresql-log" class="layui-code">
获取中...
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
let postgresql_config_editor;
let postgresql_user_config_editor;
layui.use(['index', 'admin', 'element', 'form', 'view', 'code', 'table'], function () {
let $ = layui.$
, admin = layui.admin
, element = layui.element
, code = layui.code
, table = layui.table
, form = layui.form
, view = layui.view;
form.render();
admin.req({
url: "/api/plugins/postgresql15/status"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
return false;
}
if (result.data) {
$('#postgresql-status').html('当前状态:<span class="layui-badge layui-bg-green">运行中</span>');
} else {
$('#postgresql-status').html('当前状态:<span class="layui-badge layui-bg-red">已停止</span>');
}
}
});
// 获取数据库列表
table.render({
elem: '#postgresql-database-list'
, url: '/api/plugins/postgresql15/database'
, toolbar: '#postgresql-database-list-bar'
, title: '数据库列表'
, cols: [[
{field: 'name', title: '库名', fixed: 'left', unresize: true, sort: true}
, {field: 'owner', title: '所有者', unresize: true, sort: true}
, {field: 'encoding', title: '编码', unresize: true, sort: true}
, {fixed: 'right', title: '操作', toolbar: '#postgresql-database-list-control', width: 150}
]]
, page: true
, text: {
none: '暂无数据'
}
, parseData: function (res) {
return {
"code": res.code,
"msg": res.message,
"count": res.data.total,
"data": res.data.items
};
}
});
// 头工具栏事件
table.on('toolbar(postgresql-database-list)', function (obj) {
if (obj.event === 'add_database') {
admin.popup({
title: '新建数据库'
, area: ['600px', '300px']
, id: 'LAY-popup-postgresql-database-add'
, success: function (layer, index) {
view(this.id).render('plugins/postgresql15/add_database', {}).done(function () {
form.render(null, 'LAY-popup-postgresql-database-add');
});
}
});
}
});
// 行工具事件
table.on('tool(postgresql-database-list)', function (obj) {
let data = obj.data;
if (obj.event === 'del') {
layer.confirm('高风险操作,确定要删除数据库 <b style="color: red;">' + data.name + '</b> 吗?', function (index) {
index = layer.msg('正在删除数据库 <b style="color: red;">' + data.name + '</b> ...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql15/deleteDatabase"
, type: 'post'
, data: {
database: data.name
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
obj.del();
layer.alert('数据库' + data.name + '删除成功!');
}
});
layer.close(index);
});
} else if (obj.event === 'backup') {
// 打开备份页面
admin.popup({
title: '备份管理 - ' + data.name
, area: ['70%', '80%']
, id: 'LAY-popup-postgresql-backup'
, success: function (layero, index) {
view(this.id).render('plugins/postgresql15/backup', {
data: data
}).done(function () {
form.render(null, 'LAY-popup-postgresql-backup');
});
}
});
}
});
// 获取数据库用户列表
table.render({
elem: '#postgresql-user-list'
, url: '/api/plugins/postgresql15/user'
, toolbar: '#postgresql-user-list-bar'
, title: '用户列表'
, cols: [[
{field: 'user', title: '用户名', fixed: 'left', width: 300, sort: true}
, {field: 'role', title: '权限'}
, {fixed: 'right', title: '操作', toolbar: '#postgresql-user-list-control', width: 150}
]]
, page: true
, text: {
none: '暂无数据'
}
, parseData: function (res) {
return {
"code": res.code,
"msg": res.message,
"count": res.data.total,
"data": res.data.items
};
}
});
// 头工具栏事件
table.on('toolbar(postgresql-user-list)', function (obj) {
if (obj.event === 'add_user') {
admin.popup({
title: '新建用户'
, area: ['600px', '300px']
, id: 'LAY-popup-postgresql-user-add'
, success: function (layer, index) {
view(this.id).render('plugins/postgresql15/add_user', {}).done(function () {
form.render(null, 'LAY-popup-postgresql-user-add');
});
}
});
}
});
// 行工具事件
table.on('tool(postgresql-user-list)', function (obj) {
let data = obj.data;
if (obj.event === 'del') {
layer.confirm('高风险操作,确定要删除用户 <b style="color: red;">' + data.user + '</b> 吗?', function (index) {
index = layer.msg('正在删除用户 <b style="color: red;">' + data.user + '</b> ...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql15/deleteUser"
, type: 'post'
, data: data
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
obj.del();
layer.alert('用户' + data.user + '删除成功!');
}
});
layer.close(index);
});
} else if (obj.event === 'change_password') {
// 弹出输入密码框
layer.prompt({
formType: 1
, title: '请输入新密码(建议8位以上大小写数字特殊符号混合)'
}, function (value, index) {
layer.close(index);
layer.msg('正在修改密码 ...', {
icon: 16
, time: 0
, shade: 0.3
});
// 发送请求
admin.req({
url: "/api/plugins/postgresql15/changePassword"
, type: 'post'
, data: {
user: data.user,
password: value
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('用户' + data.user + '密码修改成功!');
}
});
});
}
});
// 获取postgresql日志并渲染
admin.req({
url: "/api/plugins/postgresql15/log"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
$('#postgresql-log').text('PostgreSQL日志获取失败,请刷新重试!');
code({
elem: '#postgresql-log'
, title: 'error.log'
, encode: true
, about: false
});
return false;
}
$('#postgresql-log').text(result.data);
code({
elem: '#postgresql-log'
, title: 'postgresql.log'
, encode: true
, about: false
});
}
});
// 获取postgresql配置并渲染
admin.req({
url: "/api/plugins/postgresql15/config"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
return false;
}
$('#postgresql-config-editor').text(result.data);
postgresql_config_editor = ace.edit("postgresql-config-editor", {
mode: "ace/mode/ini",
selectionStyle: "text"
});
}
});
// 获取postgresql用户配置并渲染
admin.req({
url: "/api/plugins/postgresql15/userConfig"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
return false;
}
$('#postgresql-user-config-editor').text(result.data);
postgresql_user_config_editor = ace.edit("postgresql-user-config-editor", {
mode: "ace/mode/ini",
selectionStyle: "text"
});
}
});
// 获取postgresql负载状态并渲染
table.render({
elem: '#postgresql-load-status'
, url: '/api/plugins/postgresql15/load'
, cols: [[
{field: 'name', width: '80%', title: '属性',}
, {field: 'value', width: '20%', title: '当前值'}
]]
});
element.render();
// 事件监听
$('#postgresql-start').click(function () {
layer.confirm('确定要启动PostgreSQL吗?', {
btn: ['启动', '取消']
}, function () {
index = layer.msg('正在启动PostgreSQL...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql15/start"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PostgreSQL启动成功!');
}
});
});
});
$('#postgresql-stop').click(function () {
layer.confirm('停止PostgreSQL将导致使用PostgreSQL的网站无法访问,是否继续停止?', {
btn: ['停止', '取消']
}, function () {
index = layer.msg('正在停止PostgreSQL...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql15/stop"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PostgreSQL停止成功!');
}
});
});
});
$('#postgresql-restart').click(function () {
layer.confirm('重启PostgreSQL将导致使用PostgreSQL的网站短时间无法访问,是否继续重启?', {
btn: ['重启', '取消']
}, function () {
index = layer.msg('正在重启PostgreSQL...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql15/restart"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PostgreSQL重启成功!');
}
});
});
});
$('#postgresql-reload').click(function () {
index = layer.msg('正在重载PostgreSQL...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql15/reload"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PostgreSQL重载成功!');
}
});
});
$('#postgresql-config-save').click(function () {
index = layer.msg('正在保存配置...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql15/config"
, type: 'post'
, data: {
config: postgresql_config_editor.getValue()
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('PostgreSQL配置保存成功!');
}
});
});
$('#postgresql-user-config-save').click(function () {
index = layer.msg('正在保存配置...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql15/userConfig"
, type: 'post'
, data: {
config: postgresql_user_config_editor.getValue()
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('PostgreSQL用户配置保存成功!');
}
});
});
});
</script>
@@ -1,77 +0,0 @@
<!--
Name: PostgreSQL管理器 - 添加数据库
Author: 耗子
Date: 2023-08-13
-->
<script type="text/html" template lay-done="layui.data.sendParams(d.params)">
<form class="layui-form" action="" lay-filter="add-postgresql-database-form">
<div class="layui-form-item">
<label class="layui-form-label">数据库名</label>
<div class="layui-input-block">
<input type="text" name="database" lay-verify="required" placeholder="请输入数据库名"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" name="user" lay-verify="required" placeholder="请输入用户名"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">密码</label>
<div class="layui-input-block">
<input type="text" name="password" lay-verify="required" placeholder="请输入密码(8位以上大小写数字特殊符号混合)"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<div class="layui-footer">
<button class="layui-btn" lay-submit="" lay-filter="add-postgresql-database-submit">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</div>
</form>
</script>
<script>
layui.data.sendParams = function (params) {
layui.use(['admin', 'form', 'table'], function () {
var admin = layui.admin
, layer = layui.layer
, form = layui.form
, table = layui.table
form.render();
// 提交
form.on('submit(add-postgresql-database-submit)', function (data) {
index = layer.msg('正在提交...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: "/api/plugins/postgresql15/addDatabase"
, type: 'post'
, data: data.field
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
table.reload('postgresql-database-list');
table.reload('postgresql-user-list');
layer.alert('数据库添加成功!', {
icon: 1
, title: '提示'
, btn: ['确定']
, yes: function (index) {
layer.closeAll();
}
});
}
});
return false;
});
});
};
</script>
@@ -1,79 +0,0 @@
<!--
Name: PostgreSQL管理器 - 添加用户
Author: 耗子
Date: 2023-08-13
-->
<script type="text/html" template lay-done="layui.data.sendParams(d.params)">
<form class="layui-form" action="" lay-filter="add-postgresql-user-form">
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" name="user" lay-verify="required" placeholder="请输入用户名"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">密码</label>
<div class="layui-input-block">
<input type="text" name="password" lay-verify="required"
placeholder="请输入密码(8位以上大小写数字特殊符号混合)"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">数据库</label>
<div class="layui-input-block">
<input type="text" name="database" lay-verify="required" placeholder="输入授权给该用户的数据库名"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<div class="layui-footer">
<button class="layui-btn" lay-submit="" lay-filter="add-postgresql-user-submit">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</div>
</form>
</script>
<script>
layui.data.sendParams = function (params) {
layui.use(['admin', 'form', 'table'], function () {
var $ = layui.$
, admin = layui.admin
, layer = layui.layer
, form = layui.form
, table = layui.table
form.render();
// 提交
form.on('submit(add-postgresql-user-submit)', function (data) {
index = layer.msg('正在提交...', {icon: 16, time: 0, shade: 0.3});
admin.req({
url: "/api/plugins/postgresql15/addUser"
, type: 'post'
, data: data.field
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
table.reload('postgresql-database-list');
table.reload('postgresql-user-list');
layer.alert('用户添加成功!', {
icon: 1
, title: '提示'
, btn: ['确定']
, yes: function (index) {
layer.closeAll();
}
});
}
});
return false;
});
});
};
</script>
@@ -1,141 +0,0 @@
<!--
Name: PostgreSQL管理器 - 数据库备份
Author: 耗子
Date: 2023-08-13
-->
<script type="text/html" template lay-done="layui.data.sendParams(d.params)">
<div class="layui-row">
<div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
<table class="layui-hide" id="postgresql-backup-list" lay-filter="postgresql-backup-list"></table>
</div>
</div>
</script>
<!-- 备份顶部工具栏 -->
<script type="text/html" id="postgresql-database-backup-bar">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="backup_database">备份数据库</button>
<button class="layui-btn layui-btn-sm" id="upload_postgresql_backup">上传备份</button>
</div>
</script>
<!-- 备份右侧管理 -->
<script type="text/html" id="postgresql-database-backup-control">
<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="restore">恢复</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>
layui.data.sendParams = function (params) {
layui.use(['admin', 'form', 'laydate', 'code'], function () {
var admin = layui.admin
, layer = layui.layer
, table = layui.table
, upload = layui.upload;
// 渲染表格
table.render({
elem: '#postgresql-backup-list'
, url: '/api/plugins/postgresql15/backup'
, toolbar: '#postgresql-database-backup-bar'
, title: '备份列表'
, cols: [[
{field: 'name', title: '备份名称', width: 500}
, {field: 'size', title: '文件大小'}
, {field: 'right', title: '操作', width: 150, toolbar: '#postgresql-database-backup-control'}
]]
, text: {
none: '无备份数据'
}
, done: function (res, curr, count) {
upload.render({
elem: '#upload_postgresql_backup'
, url: '/api/plugins/postgresql15/uploadBackup'
, accept: 'file'
, ext: 'sql|zip|rar|tar|gz|bz2'
, before: function (obj) {
index = layer.msg('正在上传备份文件,可能需要较长时间,请勿操作...', {
icon: 16
, time: 0
});
}
, done: function (res) {
layer.close(index);
layer.msg('上传成功!', {icon: 1});
table.reload('postgresql-backup-list');
}
});
}
});
// 头工具栏事件
table.on('toolbar(postgresql-backup-list)', function (obj) {
if (obj.event === 'backup_database') {
index = layer.msg('正在备份数据库,请稍等...', {
icon: 16
, time: 0
});
admin.req({
url: '/api/plugins/postgresql15/createBackup'
, type: 'post'
, data: {
database: params.data.name
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
layer.alert('备份失败!');
return false;
}
table.reload('postgresql-backup-list');
layer.msg('备份成功!', {icon: 1});
}
});
}
});
// 行工具事件
table.on('tool(postgresql-backup-list)', function (obj) {
let data = obj.data;
if (obj.event === 'del') {
layer.confirm('确定要删除数据库备份 <b style="color: red;">' + data.name + '</b> 吗?', function (index) {
index = layer.msg('正在删除数据库备份,请稍等...', {
icon: 16
, time: 0
});
admin.req({
url: "/api/plugins/postgresql15/deleteBackup"
, type: 'post'
, data: data
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
layer.msg('数据库备份删除失败,请刷新重试!')
return false;
}
obj.del();
layer.alert('数据库备份' + data.name + '删除成功!');
}
});
});
} else if (obj.event === 'restore') {
layer.confirm('高风险操作,确定要恢复数据库备份 <b style="color: red;">' + data.name + '</b> 吗?', function (index) {
index = layer.msg('正在恢复数据库备份,可能需要较长时间,请勿操作...', {
icon: 16
, time: 0
});
data.database = params.data.name;
admin.req({
url: "/api/plugins/postgresql15/restoreBackup"
, type: 'post'
, data: data
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
layer.msg('数据库备份恢复失败,请刷新重试!')
return false;
}
layer.alert('数据库备份' + data.name + '恢复成功!');
}
});
});
}
});
});
};
</script>
@@ -1,524 +0,0 @@
<!--
Name: PostgreSQL管理器
Author: 耗子
Date: 2023-08-13
-->
<title>PostgreSQL</title>
<div class="layui-fluid" id="component-tabs">
<div class="layui-row">
<div class="layui-col-md12">
<div class="layui-card">
<div class="layui-card-header">PostgreSQL管理</div>
<div class="layui-card-body">
<div class="layui-tab">
<ul class="layui-tab-title">
<li class="layui-this">基本信息</li>
<li>管理</li>
<li>主配置</li>
<li>用户配置</li>
<li>负载状态</li>
<li>日志</li>
</ul>
<div class="layui-tab-content">
<div class="layui-tab-item layui-show">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>运行状态</legend>
</fieldset>
<blockquote id="postgresql-status" class="layui-elem-quote layui-quote-nm">
当前状态:<span
class="layui-badge layui-bg-black">获取中</span></blockquote>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="postgresql-start" class="layui-btn">启动</button>
<button id="postgresql-stop" class="layui-btn layui-btn-danger">停止</button>
<button id="postgresql-restart" class="layui-btn layui-btn-warm">重启</button>
<button id="postgresql-reload" class="layui-btn layui-btn-normal">重载</button>
</div>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">面板仅集成了部分常用功能,如需更多功能,请使用
pgAdmin 客户端。
</blockquote>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>数据库列表</legend>
</fieldset>
<table class="layui-hide" id="postgresql-database-list"
lay-filter="postgresql-database-list"></table>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>用户列表</legend>
</fieldset>
<table class="layui-hide" id="postgresql-user-list"
lay-filter="postgresql-user-list"></table>
<!-- 数据库顶部工具栏 -->
<script type="text/html" id="postgresql-database-list-bar">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="add_database">新建数据库
</button>
</div>
</script>
<!-- 用户顶部工具栏 -->
<script type="text/html" id="postgresql-user-list-bar">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="add_user">新建用户</button>
</div>
</script>
<!-- 数据库右侧管理 -->
<script type="text/html" id="postgresql-database-list-control">
<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="backup">备份</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<!-- 用户右侧管理 -->
<script type="text/html" id="postgresql-user-list-control">
<a class="layui-btn layui-btn-normal layui-btn-xs"
lay-event="change_password">改密</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">此处修改的是PostgreSQL主配置文件,如果你不了解各参数的含义,请不要随意修改!<br>
提示:Ctrl+F 搜索关键字,Ctrl+S 保存,Ctrl+H 查找替换!
</blockquote>
<div id="postgresql-config-editor"
style="height: 600px;"></div>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="postgresql-config-save" class="layui-btn">保存</button>
</div>
</div>
<div class="layui-tab-item">
<blockquote class="layui-elem-quote">此处修改的是PostgreSQL用户配置文件,如果你不了解各参数的含义,请不要随意修改!<br>
提示:Ctrl+F 搜索关键字,Ctrl+S 保存,Ctrl+H 查找替换!
</blockquote>
<div id="postgresql-user-config-editor"
style="height: 600px;"></div>
<div class="layui-btn-container" style="padding-top: 30px;">
<button id="postgresql-user-config-save" class="layui-btn">保存</button>
</div>
</div>
<div class="layui-tab-item">
<table class="layui-hide" id="postgresql-load-status"></table>
</div>
<div class="layui-tab-item">
<pre id="postgresql-log" class="layui-code">
获取中...
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
let postgresql_config_editor;
let postgresql_user_config_editor;
layui.use(['index', 'admin', 'element', 'form', 'view', 'code', 'table'], function () {
let $ = layui.$
, admin = layui.admin
, element = layui.element
, code = layui.code
, table = layui.table
, form = layui.form
, view = layui.view;
form.render();
admin.req({
url: "/api/plugins/postgresql16/status"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
return false;
}
if (result.data) {
$('#postgresql-status').html('当前状态:<span class="layui-badge layui-bg-green">运行中</span>');
} else {
$('#postgresql-status').html('当前状态:<span class="layui-badge layui-bg-red">已停止</span>');
}
}
});
// 获取数据库列表
table.render({
elem: '#postgresql-database-list'
, url: '/api/plugins/postgresql16/database'
, toolbar: '#postgresql-database-list-bar'
, title: '数据库列表'
, cols: [[
{field: 'name', title: '库名', fixed: 'left', unresize: true, sort: true}
, {field: 'owner', title: '所有者', unresize: true, sort: true}
, {field: 'encoding', title: '编码', unresize: true, sort: true}
, {fixed: 'right', title: '操作', toolbar: '#postgresql-database-list-control', width: 150}
]]
, page: true
, text: {
none: '暂无数据'
}
, parseData: function (res) {
return {
"code": res.code,
"msg": res.message,
"count": res.data.total,
"data": res.data.items
};
}
});
// 头工具栏事件
table.on('toolbar(postgresql-database-list)', function (obj) {
if (obj.event === 'add_database') {
admin.popup({
title: '新建数据库'
, area: ['600px', '300px']
, id: 'LAY-popup-postgresql-database-add'
, success: function (layer, index) {
view(this.id).render('plugins/postgresql16/add_database', {}).done(function () {
form.render(null, 'LAY-popup-postgresql-database-add');
});
}
});
}
});
// 行工具事件
table.on('tool(postgresql-database-list)', function (obj) {
let data = obj.data;
if (obj.event === 'del') {
layer.confirm('高风险操作,确定要删除数据库 <b style="color: red;">' + data.name + '</b> 吗?', function (index) {
index = layer.msg('正在删除数据库 <b style="color: red;">' + data.name + '</b> ...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql16/deleteDatabase"
, type: 'post'
, data: {
database: data.name
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
obj.del();
layer.alert('数据库' + data.name + '删除成功!');
}
});
layer.close(index);
});
} else if (obj.event === 'backup') {
// 打开备份页面
admin.popup({
title: '备份管理 - ' + data.name
, area: ['70%', '80%']
, id: 'LAY-popup-postgresql-backup'
, success: function (layero, index) {
view(this.id).render('plugins/postgresql16/backup', {
data: data
}).done(function () {
form.render(null, 'LAY-popup-postgresql-backup');
});
}
});
}
});
// 获取数据库用户列表
table.render({
elem: '#postgresql-user-list'
, url: '/api/plugins/postgresql16/user'
, toolbar: '#postgresql-user-list-bar'
, title: '用户列表'
, cols: [[
{field: 'user', title: '用户名', fixed: 'left', width: 300, sort: true}
, {field: 'role', title: '权限'}
, {fixed: 'right', title: '操作', toolbar: '#postgresql-user-list-control', width: 150}
]]
, page: true
, text: {
none: '暂无数据'
}
, parseData: function (res) {
return {
"code": res.code,
"msg": res.message,
"count": res.data.total,
"data": res.data.items
};
}
});
// 头工具栏事件
table.on('toolbar(postgresql-user-list)', function (obj) {
if (obj.event === 'add_user') {
admin.popup({
title: '新建用户'
, area: ['600px', '300px']
, id: 'LAY-popup-postgresql-user-add'
, success: function (layer, index) {
view(this.id).render('plugins/postgresql16/add_user', {}).done(function () {
form.render(null, 'LAY-popup-postgresql-user-add');
});
}
});
}
});
// 行工具事件
table.on('tool(postgresql-user-list)', function (obj) {
let data = obj.data;
if (obj.event === 'del') {
layer.confirm('高风险操作,确定要删除用户 <b style="color: red;">' + data.user + '</b> 吗?', function (index) {
index = layer.msg('正在删除用户 <b style="color: red;">' + data.user + '</b> ...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql16/deleteUser"
, type: 'post'
, data: data
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
obj.del();
layer.alert('用户' + data.user + '删除成功!');
}
});
layer.close(index);
});
} else if (obj.event === 'change_password') {
// 弹出输入密码框
layer.prompt({
formType: 1
, title: '请输入新密码(建议8位以上大小写数字特殊符号混合)'
}, function (value, index) {
layer.close(index);
layer.msg('正在修改密码 ...', {
icon: 16
, time: 0
, shade: 0.3
});
// 发送请求
admin.req({
url: "/api/plugins/postgresql16/changePassword"
, type: 'post'
, data: {
user: data.user,
password: value
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('用户' + data.user + '密码修改成功!');
}
});
});
}
});
// 获取postgresql日志并渲染
admin.req({
url: "/api/plugins/postgresql16/log"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
$('#postgresql-log').text('PostgreSQL日志获取失败,请刷新重试!');
code({
elem: '#postgresql-log'
, title: 'error.log'
, encode: true
, about: false
});
return false;
}
$('#postgresql-log').text(result.data);
code({
elem: '#postgresql-log'
, title: 'postgresql.log'
, encode: true
, about: false
});
}
});
// 获取postgresql配置并渲染
admin.req({
url: "/api/plugins/postgresql16/config"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
return false;
}
$('#postgresql-config-editor').text(result.data);
postgresql_config_editor = ace.edit("postgresql-config-editor", {
mode: "ace/mode/ini",
selectionStyle: "text"
});
}
});
// 获取postgresql用户配置并渲染
admin.req({
url: "/api/plugins/postgresql16/userConfig"
, type: 'get'
, success: function (result) {
if (result.code !== 0) {
return false;
}
$('#postgresql-user-config-editor').text(result.data);
postgresql_user_config_editor = ace.edit("postgresql-user-config-editor", {
mode: "ace/mode/ini",
selectionStyle: "text"
});
}
});
// 获取postgresql负载状态并渲染
table.render({
elem: '#postgresql-load-status'
, url: '/api/plugins/postgresql16/load'
, cols: [[
{field: 'name', width: '80%', title: '属性',}
, {field: 'value', width: '20%', title: '当前值'}
]]
});
element.render();
// 事件监听
$('#postgresql-start').click(function () {
layer.confirm('确定要启动PostgreSQL吗?', {
btn: ['启动', '取消']
}, function () {
index = layer.msg('正在启动PostgreSQL...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql16/start"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PostgreSQL启动成功!');
}
});
});
});
$('#postgresql-stop').click(function () {
layer.confirm('停止PostgreSQL将导致使用PostgreSQL的网站无法访问,是否继续停止?', {
btn: ['停止', '取消']
}, function () {
index = layer.msg('正在停止PostgreSQL...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql16/stop"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PostgreSQL停止成功!');
}
});
});
});
$('#postgresql-restart').click(function () {
layer.confirm('重启PostgreSQL将导致使用PostgreSQL的网站短时间无法访问,是否继续重启?', {
btn: ['重启', '取消']
}, function () {
index = layer.msg('正在重启PostgreSQL...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql16/restart"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PostgreSQL重启成功!');
}
});
});
});
$('#postgresql-reload').click(function () {
index = layer.msg('正在重载PostgreSQL...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql16/reload"
, type: 'post'
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
admin.events.refresh();
layer.alert('PostgreSQL重载成功!');
}
});
});
$('#postgresql-config-save').click(function () {
index = layer.msg('正在保存配置...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql16/config"
, type: 'post'
, data: {
config: postgresql_config_editor.getValue()
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('PostgreSQL配置保存成功!');
}
});
});
$('#postgresql-user-config-save').click(function () {
index = layer.msg('正在保存配置...', {
icon: 16
, time: 0
, shade: 0.3
});
admin.req({
url: "/api/plugins/postgresql16/userConfig"
, type: 'post'
, data: {
config: postgresql_user_config_editor.getValue()
}
, success: function (result) {
layer.close(index);
if (result.code !== 0) {
return false;
}
layer.alert('PostgreSQL用户配置保存成功!');
}
});
});
});
</script>

Some files were not shown because too many files have changed in this diff Show More