Compare commits

..

8 Commits

Author SHA1 Message Date
xxk 038cfe53bc 更新 .gitignore 2026-06-26 09:04:11 +08:00
xxk f02522a559 更新 .gitignore 2026-06-26 09:04:04 +08:00
xxk e4863cbe9d 删除目录「core」 2026-06-26 09:03:08 +08:00
xxk 186181ff07 删除目录「desktop-client-废弃」 2026-06-26 09:03:01 +08:00
xxk a1b8dece99 更新 .gitignore 2026-06-26 09:02:17 +08:00
xxk 545f630729 Remove local environment files 2026-06-25 16:30:14 +08:00
xxk 039c7ea335 Initial commit 2026-06-25 15:05:52 +08:00
xxk 46b922bdc5 Initial commit 2026-06-25 14:58:52 +08:00
1301 changed files with 147088 additions and 214 deletions
+15 -212
View File
@@ -1,213 +1,16 @@
# ---> Java .codex/
# Compiled class file .agents/
*.class **/node_modules/
**/dist/
# Log file **/build/
**/target/
**/out/
local-controller/data/
**/.venv/
**/__pycache__/
**/*.pyc
**/*.pyo
**/*.pyd
*.log *.log
core/
# BlueJ files desktop-client-废弃/
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
# ---> Vue
# gitignore template for Vue.js projects
#
# Recommended template: Node.gitignore
# TODO: where does this rule come from?
docs/_book
# TODO: where does this rule come from?
test/
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc
-2
View File
@@ -1,2 +0,0 @@
# Browser
+18
View File
@@ -0,0 +1,18 @@
# http://editorconfig.org
root = true
# 空格替代Tab缩进在各种编辑工具下效果一致
[*]
indent_style = space
indent_size = 4
charset = utf-8
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
[*.{json,yml,yaml}]
indent_size = 2
[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
+46
View File
@@ -0,0 +1,46 @@
######################################################################
# Build Tools
.gradle
/build/
!gradle/wrapper/gradle-wrapper.jar
target/
!.mvn/wrapper/maven-wrapper.jar
######################################################################
# IDE
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### JRebel ###
rebel.xml
### NetBeans ###
nbproject/private/
build/*
nbbuild/
nbdist/
.nb-gradle/
######################################################################
# Others
*.log
*.xml.versionsBackup
*.swp
!*/build/*.java
!*/build/*.html
!*/build/*.xml
+20
View File
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2019 RuoYi-Vue-Plus
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+443
View File
@@ -0,0 +1,443 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-vue-plus</artifactId>
<version>4.8.2</version>
<name>RuoYi-Vue-Plus</name>
<url>https://gitee.com/dromara/RuoYi-Vue-Plus</url>
<description>RuoYi-Vue-Plus后台管理系统</description>
<properties>
<ruoyi-vue-plus.version>4.8.2</ruoyi-vue-plus.version>
<spring-boot.version>2.7.18</spring-boot.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.2.2</maven-jar-plugin.version>
<spring-boot.mybatis>2.2.2</spring-boot.mybatis>
<springdoc.version>1.6.15</springdoc.version>
<poi.version>5.2.3</poi.version>
<easyexcel.version>3.3.2</easyexcel.version>
<velocity.version>2.3</velocity.version>
<satoken.version>1.37.0</satoken.version>
<mybatis-plus.version>3.5.4</mybatis-plus.version>
<p6spy.version>3.9.1</p6spy.version>
<hutool.version>5.8.22</hutool.version>
<okhttp.version>4.10.0</okhttp.version>
<spring-boot-admin.version>2.7.11</spring-boot-admin.version>
<redisson.version>3.20.1</redisson.version>
<lock4j.version>2.2.3</lock4j.version>
<dynamic-ds.version>3.5.2</dynamic-ds.version>
<alibaba-ttl.version>2.14.2</alibaba-ttl.version>
<xxl-job.version>2.4.0</xxl-job.version>
<lombok.version>1.18.30</lombok.version>
<bouncycastle.version>1.72</bouncycastle.version>
<!-- 离线IP地址定位库 -->
<ip2region.version>2.7.0</ip2region.version>
<!-- OSS 配置 -->
<aws-java-sdk-s3.version>1.12.540</aws-java-sdk-s3.version>
<!-- SMS 配置 -->
<sms4j.version>2.2.0</sms4j.version>
<geoip2.version>4.2.1</geoip2.version>
</properties>
<profiles>
<profile>
<id>local</id>
<properties>
<!-- 环境标识,需要与配置文件的名称相对应 -->
<profiles.active>local</profiles.active>
<logging.level>info</logging.level>
</properties>
</profile>
<profile>
<id>dev</id>
<properties>
<!-- 环境标识,需要与配置文件的名称相对应 -->
<profiles.active>dev</profiles.active>
<logging.level>info</logging.level>
</properties>
<activation>
<!-- 默认环境 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>prod</id>
<properties>
<profiles.active>prod</profiles.active>
<logging.level>warn</logging.level>
</properties>
</profile>
</profiles>
<!-- 依赖声明 -->
<dependencyManagement>
<dependencies>
<!-- SpringBoot的依赖配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- hutool 的依赖配置-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-bom</artifactId>
<version>${hutool.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-webmvc-core</artifactId>
<version>${springdoc.version}</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-javadoc</artifactId>
<version>${springdoc.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easyexcel.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- velocity代码生成使用模板 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity.version}</version>
</dependency>
<!-- Sa-Token 权限认证, 在线文档:http://sa-token.dev33.cn/ -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>${satoken.version}</version>
</dependency>
<!-- Sa-Token 整合 jwt -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-jwt</artifactId>
<version>${satoken.version}</version>
<exclusions>
<exclusion>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- dynamic-datasource 多数据源-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>${dynamic-ds.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- sql性能分析插件 -->
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>${p6spy.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>${aws-java-sdk-s3.version}</version>
</dependency>
<!--短信sms4j-->
<dependency>
<groupId>org.dromara.sms4j</groupId>
<artifactId>sms4j-spring-boot-starter</artifactId>
<version>${sms4j.version}</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>${spring-boot-admin.version}</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>${spring-boot-admin.version}</version>
</dependency>
<!--redisson-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>${redisson.version}</version>
<exclusions>
<exclusion>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-data-30</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-data-27</artifactId>
<version>${redisson.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>lock4j-redisson-spring-boot-starter</artifactId>
<version>${lock4j.version}</version>
</dependency>
<!-- xxl-job-core -->
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
<version>${xxl-job.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>transmittable-thread-local</artifactId>
<version>${alibaba-ttl.version}</version>
</dependency>
<!-- 离线IP地址定位库 ip2region -->
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>${ip2region.version}</version>
</dependency>
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>${geoip2.version}</version>
</dependency>
<!-- 加密包引入 -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15to18</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<!-- 定时任务 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-job</artifactId>
<version>${ruoyi-vue-plus.version}</version>
</dependency>
<!-- 代码生成-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-generator</artifactId>
<version>${ruoyi-vue-plus.version}</version>
</dependency>
<!-- 核心模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-framework</artifactId>
<version>${ruoyi-vue-plus.version}</version>
</dependency>
<!-- 系统模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-system</artifactId>
<version>${ruoyi-vue-plus.version}</version>
</dependency>
<!-- 通用工具-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
<version>${ruoyi-vue-plus.version}</version>
</dependency>
<!-- OSS对象存储模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-oss</artifactId>
<version>${ruoyi-vue-plus.version}</version>
</dependency>
<!-- SMS短信模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-sms</artifactId>
<version>${ruoyi-vue-plus.version}</version>
</dependency>
<!-- demo模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-demo</artifactId>
<version>${ruoyi-vue-plus.version}</version>
</dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-browser</artifactId>
<version>${ruoyi-vue-plus.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>ruoyi-admin</module>
<module>ruoyi-framework</module>
<module>ruoyi-system</module>
<module>ruoyi-job</module>
<module>ruoyi-generator</module>
<module>ruoyi-common</module>
<module>ruoyi-demo</module>
<module>ruoyi-extend</module>
<module>ruoyi-oss</module>
<module>ruoyi-sms</module>
<module>ruoyi-browser</module>
</modules>
<packaging>pom</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.9.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
<annotationProcessorPaths>
<path>
<groupId>com.github.therapi</groupId>
<artifactId>therapi-runtime-javadoc-scribe</artifactId>
<version>0.15.0</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring-boot.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<!-- 单元测试使用 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<argLine>-Dfile.encoding=UTF-8</argLine>
<!-- 根据打包环境执行对应的@Tag测试方法 -->
<groups>${profiles.active}</groups>
<!-- 排除标签 -->
<excludedGroups>exclude</excludedGroups>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<!-- 关闭过滤 -->
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<!-- 引入所有 匹配文件进行过滤 -->
<includes>
<include>application*</include>
<include>bootstrap*</include>
<include>banner*</include>
</includes>
<!-- 启用过滤 即该资源中的变量将会被过滤器中的值替换 -->
<filtering>true</filtering>
</resource>
</resources>
</build>
<repositories>
<repository>
<id>public</id>
<name>huawei nexus</name>
<url>https://mirrors.huaweicloud.com/repository/maven/</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>huawei nexus</name>
<url>https://mirrors.huaweicloud.com/repository/maven/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
@@ -0,0 +1,23 @@
FROM anapsix/alpine-java:8_server-jre_unlimited
MAINTAINER Lion Li
RUN mkdir -p /ruoyi/server/logs \
/ruoyi/server/temp \
/ruoyi/skywalking/agent
WORKDIR /ruoyi/server
ENV SERVER_PORT=8080
EXPOSE ${SERVER_PORT}
ADD ./target/ruoyi-admin.jar ./app.jar
ENTRYPOINT ["java", \
"-Djava.security.egd=file:/dev/./urandom", \
"-Dserver.port=${SERVER_PORT}", \
# 应用名称 如果想区分集群节点监控 改成不同的名称即可
# "-Dskywalking.agent.service_name=ruoyi-server", \
# "-javaagent:/ruoyi/skywalking/agent/skywalking-agent.jar", \
"-jar", "app.jar"]
+136
View File
@@ -0,0 +1,136 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ruoyi-vue-plus</artifactId>
<groupId>com.ruoyi</groupId>
<version>4.8.2</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>ruoyi-admin</artifactId>
<description>
web服务入口
</description>
<dependencies>
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 表示依赖不会传递 -->
</dependency>
<!-- Mysql驱动包 -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<!-- Oracle -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
</dependency>
<!-- PostgreSql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<!-- SqlServer -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
</dependency>
<!-- 核心模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-framework</artifactId>
</dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-system</artifactId>
</dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-job</artifactId>
</dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-oss</artifactId>
</dependency>
<!-- 代码生成-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-generator</artifactId>
</dependency>
<!-- demo模块 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-demo</artifactId>
</dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-browser</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- skywalking 整合 logback -->
<!-- <dependency>-->
<!-- <groupId>org.apache.skywalking</groupId>-->
<!-- <artifactId>apm-toolkit-logback-1.x</artifactId>-->
<!-- <version>${与你的agent探针版本保持一致}</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.apache.skywalking</groupId>-->
<!-- <artifactId>apm-toolkit-trace</artifactId>-->
<!-- <version>${与你的agent探针版本保持一致}</version>-->
<!-- </dependency>-->
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<fork>true</fork> <!-- 如果没有该配置,devtools不会生效 -->
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<warName>${project.artifactId}</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,24 @@
package com.ruoyi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
/**
* 启动程序
*
* @author ruoyi
*/
@SpringBootApplication
public class RuoYiApplication {
public static void main(String[] args) {
System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication application = new SpringApplication(RuoYiApplication.class);
application.setApplicationStartup(new BufferingApplicationStartup(2048));
application.run(args);
System.out.println("(♥◠‿◠)ノ゙ RuoYi-Vue-Plus启动成功 ლ(´ڡ`ლ)゙");
}
}
@@ -0,0 +1,18 @@
package com.ruoyi;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* web容器中进行部署
*
* @author ruoyi
*/
public class RuoYiServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(RuoYiApplication.class);
}
}
@@ -0,0 +1,134 @@
package com.ruoyi.web.controller.common;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.CaptchaType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.email.MailUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.common.utils.reflect.ReflectUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.config.properties.CaptchaProperties;
import com.ruoyi.framework.config.properties.MailProperties;
import com.ruoyi.system.service.ISysConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.dromara.sms4j.provider.enumerate.SupplierType;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotBlank;
import java.time.Duration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 验证码操作处理
*
* @author Lion Li
*/
@SaIgnore
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
public class CaptchaController {
private final CaptchaProperties captchaProperties;
private final ISysConfigService configService;
private final MailProperties mailProperties;
/**
* 短信验证码
*
* @param phonenumber 用户手机号
*/
@GetMapping("/captchaSms")
public R<Void> smsCaptcha(@NotBlank(message = "{user.phonenumber.not.blank}") String phonenumber) {
String key = CacheConstants.CAPTCHA_CODE_KEY + phonenumber;
String code = RandomUtil.randomNumbers(4);
RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
// 验证码模板id 自行处理 (查数据库或写死均可)
String templateId = "";
LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
map.put("code", code);
SmsBlend smsBlend = SmsFactory.createSmsBlend(SupplierType.ALIBABA);
SmsResponse smsResponse = smsBlend.sendMessage(phonenumber, templateId, map);
if (!"OK".equals(smsResponse.getCode())) {
log.error("验证码短信发送异常 => {}", smsResponse);
return R.fail(smsResponse.getMessage());
}
return R.ok();
}
/**
* 邮箱验证码
*
* @param email 邮箱
*/
@GetMapping("/captchaEmail")
public R<Void> emailCode(@NotBlank(message = "{user.email.not.blank}") String email) {
if (!mailProperties.getEnabled()) {
return R.fail("当前系统没有开启邮箱功能!");
}
String key = CacheConstants.CAPTCHA_CODE_KEY + email;
String code = RandomUtil.randomNumbers(4);
RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
try {
MailUtils.sendText(email, "登录验证码", "您本次验证码为:" + code + ",有效性为" + Constants.CAPTCHA_EXPIRATION + "分钟,请尽快填写。");
} catch (Exception e) {
log.error("验证码短信发送异常 => {}", e.getMessage());
return R.fail(e.getMessage());
}
return R.ok();
}
/**
* 生成验证码
*/
@GetMapping("/captchaImage")
public R<Map<String, Object>> getCode() {
Map<String, Object> ajax = new HashMap<>();
boolean captchaEnabled = configService.selectCaptchaEnabled();
ajax.put("captchaEnabled", captchaEnabled);
if (!captchaEnabled) {
return R.ok(ajax);
}
// 保存验证码信息
String uuid = IdUtil.simpleUUID();
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
// 生成验证码
CaptchaType captchaType = captchaProperties.getType();
boolean isMath = CaptchaType.MATH == captchaType;
Integer length = isMath ? captchaProperties.getNumberLength() : captchaProperties.getCharLength();
CodeGenerator codeGenerator = ReflectUtils.newInstance(captchaType.getClazz(), length);
AbstractCaptcha captcha = SpringUtils.getBean(captchaProperties.getCategory().getClazz());
captcha.setGenerator(codeGenerator);
captcha.createCode();
String code = captcha.getCode();
if (isMath) {
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(StringUtils.remove(code, "="));
code = exp.getValue(String.class);
}
RedisUtils.setCacheObject(verifyKey, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
ajax.put("uuid", uuid);
ajax.put("img", captcha.getImageBase64());
return R.ok(ajax);
}
}
@@ -0,0 +1,168 @@
package com.ruoyi.web.controller.monitor;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.CacheNames;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.CacheUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.system.domain.SysCache;
import lombok.RequiredArgsConstructor;
import org.redisson.spring.data.connection.RedissonConnectionFactory;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.stream.Collectors;
/**
* 缓存监控
*
* @author Lion Li
*/
@RequiredArgsConstructor
@RestController
@RequestMapping("/monitor/cache")
public class CacheController {
private final RedissonConnectionFactory connectionFactory;
private final static List<SysCache> CACHES = new ArrayList<>();
static {
CACHES.add(new SysCache(CacheConstants.ONLINE_TOKEN_KEY, "在线用户"));
CACHES.add(new SysCache(CacheNames.SYS_CONFIG, "配置信息"));
CACHES.add(new SysCache(CacheNames.SYS_DICT, "数据字典"));
CACHES.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
CACHES.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
CACHES.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
CACHES.add(new SysCache(CacheNames.SYS_OSS_CONFIG, "OSS配置"));
CACHES.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
}
/**
* 获取缓存监控列表
*/
@SaCheckPermission("monitor:cache:list")
@GetMapping()
public R<Map<String, Object>> getInfo() throws Exception {
RedisConnection connection = connectionFactory.getConnection();
Properties info = connection.info();
Properties commandStats = connection.info("commandstats");
Long dbSize = connection.dbSize();
Map<String, Object> result = new HashMap<>(3);
result.put("info", info);
result.put("dbSize", dbSize);
List<Map<String, String>> pieList = new ArrayList<>();
if (commandStats != null) {
commandStats.stringPropertyNames().forEach(key -> {
Map<String, String> data = new HashMap<>(2);
String property = commandStats.getProperty(key);
data.put("name", StringUtils.removeStart(key, "cmdstat_"));
data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
pieList.add(data);
});
}
result.put("commandStats", pieList);
return R.ok(result);
}
/**
* 获取缓存监控缓存名列表
*/
@SaCheckPermission("monitor:cache:list")
@GetMapping("/getNames")
public R<List<SysCache>> cache() {
return R.ok(CACHES);
}
/**
* 获取缓存监控Key列表
*
* @param cacheName 缓存名
*/
@SaCheckPermission("monitor:cache:list")
@GetMapping("/getKeys/{cacheName}")
public R<Collection<String>> getCacheKeys(@PathVariable String cacheName) {
Collection<String> cacheKeys = new HashSet<>(0);
if (isCacheNames(cacheName)) {
Set<Object> keys = CacheUtils.keys(cacheName);
if (CollUtil.isNotEmpty(keys)) {
cacheKeys = keys.stream().map(Object::toString).collect(Collectors.toList());
}
} else {
cacheKeys = RedisUtils.keys(cacheName + "*");
}
return R.ok(cacheKeys);
}
/**
* 获取缓存监控缓存值详情
*
* @param cacheName 缓存名
* @param cacheKey 缓存key
*/
@SaCheckPermission("monitor:cache:list")
@GetMapping("/getValue/{cacheName}/{cacheKey}")
public R<SysCache> getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey) {
Object cacheValue;
if (isCacheNames(cacheName)) {
cacheValue = CacheUtils.get(cacheName, cacheKey);
} else {
cacheValue = RedisUtils.getCacheObject(cacheKey);
}
SysCache sysCache = new SysCache(cacheName, cacheKey, JsonUtils.toJsonString(cacheValue));
return R.ok(sysCache);
}
/**
* 清理缓存监控缓存名
*
* @param cacheName 缓存名
*/
@SaCheckPermission("monitor:cache:list")
@DeleteMapping("/clearCacheName/{cacheName}")
public R<Void> clearCacheName(@PathVariable String cacheName) {
if (isCacheNames(cacheName)) {
CacheUtils.clear(cacheName);
} else {
RedisUtils.deleteKeys(cacheName + "*");
}
return R.ok();
}
/**
* 清理缓存监控Key
*
* @param cacheKey key名
*/
@SaCheckPermission("monitor:cache:list")
@DeleteMapping("/clearCacheKey/{cacheName}/{cacheKey}")
public R<Void> clearCacheKey(@PathVariable String cacheName, @PathVariable String cacheKey) {
if (isCacheNames(cacheName)) {
CacheUtils.evict(cacheName, cacheKey);
} else {
RedisUtils.deleteObject(cacheKey);
}
return R.ok();
}
/**
* 清理全部缓存监控
*/
@SaCheckPermission("monitor:cache:list")
@DeleteMapping("/clearCacheAll")
public R<Void> clearCacheAll() {
RedisUtils.deleteKeys("*");
return R.ok();
}
private boolean isCacheNames(String cacheName) {
return !StringUtils.contains(cacheName, ":");
}
}
@@ -0,0 +1,88 @@
package com.ruoyi.web.controller.monitor;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.system.domain.SysLogininfor;
import com.ruoyi.system.service.ISysLogininforService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 系统访问记录
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/monitor/logininfor")
public class SysLogininforController extends BaseController {
private final ISysLogininforService logininforService;
/**
* 获取系统访问记录列表
*/
@SaCheckPermission("monitor:logininfor:list")
@GetMapping("/list")
public TableDataInfo<SysLogininfor> list(SysLogininfor logininfor, PageQuery pageQuery) {
return logininforService.selectPageLogininforList(logininfor, pageQuery);
}
/**
* 导出系统访问记录列表
*/
@Log(title = "登录日志", businessType = BusinessType.EXPORT)
@SaCheckPermission("monitor:logininfor:export")
@PostMapping("/export")
public void export(SysLogininfor logininfor, HttpServletResponse response) {
List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
ExcelUtil.exportExcel(list, "登录日志", SysLogininfor.class, response);
}
/**
* 批量删除登录日志
* @param infoIds 日志ids
*/
@SaCheckPermission("monitor:logininfor:remove")
@Log(title = "登录日志", businessType = BusinessType.DELETE)
@DeleteMapping("/{infoIds}")
public R<Void> remove(@PathVariable Long[] infoIds) {
return toAjax(logininforService.deleteLogininforByIds(infoIds));
}
/**
* 清理系统访问记录
*/
@SaCheckPermission("monitor:logininfor:remove")
@Log(title = "登录日志", businessType = BusinessType.CLEAN)
@DeleteMapping("/clean")
public R<Void> clean() {
logininforService.cleanLogininfor();
return R.ok();
}
@SaCheckPermission("monitor:logininfor:unlock")
@Log(title = "账户解锁", businessType = BusinessType.OTHER)
@GetMapping("/unlock/{userName}")
public R<Void> unlock(@PathVariable("userName") String userName) {
String loginName = CacheConstants.PWD_ERR_CNT_KEY + userName;
if (RedisUtils.hasKey(loginName)) {
RedisUtils.deleteObject(loginName);
}
return R.ok();
}
}
@@ -0,0 +1,74 @@
package com.ruoyi.web.controller.monitor;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysOperLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 操作日志记录
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/monitor/operlog")
public class SysOperlogController extends BaseController {
private final ISysOperLogService operLogService;
/**
* 获取操作日志记录列表
*/
@SaCheckPermission("monitor:operlog:list")
@GetMapping("/list")
public TableDataInfo<SysOperLog> list(SysOperLog operLog, PageQuery pageQuery) {
return operLogService.selectPageOperLogList(operLog, pageQuery);
}
/**
* 导出操作日志记录列表
*/
@Log(title = "操作日志", businessType = BusinessType.EXPORT)
@SaCheckPermission("monitor:operlog:export")
@PostMapping("/export")
public void export(SysOperLog operLog, HttpServletResponse response) {
List<SysOperLog> list = operLogService.selectOperLogList(operLog);
ExcelUtil.exportExcel(list, "操作日志", SysOperLog.class, response);
}
/**
* 批量删除操作日志记录
* @param operIds 日志ids
*/
@Log(title = "操作日志", businessType = BusinessType.DELETE)
@SaCheckPermission("monitor:operlog:remove")
@DeleteMapping("/{operIds}")
public R<Void> remove(@PathVariable Long[] operIds) {
return toAjax(operLogService.deleteOperLogByIds(operIds));
}
/**
* 清理操作日志记录
*/
@Log(title = "操作日志", businessType = BusinessType.CLEAN)
@SaCheckPermission("monitor:operlog:remove")
@DeleteMapping("/clean")
public R<Void> clean() {
operLogService.cleanOperLog();
return R.ok();
}
}
@@ -0,0 +1,90 @@
package com.ruoyi.web.controller.monitor;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.dto.UserOnlineDTO;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StreamUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.system.domain.SysUserOnline;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 在线用户监控
*
* @author Lion Li
*/
@RequiredArgsConstructor
@RestController
@RequestMapping("/monitor/online")
public class SysUserOnlineController extends BaseController {
/**
* 获取在线用户监控列表
*
* @param ipaddr IP地址
* @param userName 用户名
*/
@SaCheckPermission("monitor:online:list")
@GetMapping("/list")
public TableDataInfo<SysUserOnline> list(String ipaddr, String userName) {
// 获取所有未过期的 token
List<String> keys = StpUtil.searchTokenValue("", 0, -1, false);
List<UserOnlineDTO> userOnlineDTOList = new ArrayList<>();
for (String key : keys) {
String token = StringUtils.substringAfterLast(key, ":");
// 如果已经过期则跳过
if (StpUtil.stpLogic.getTokenActiveTimeoutByToken(token) < -1) {
continue;
}
userOnlineDTOList.add(RedisUtils.getCacheObject(CacheConstants.ONLINE_TOKEN_KEY + token));
}
if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) {
userOnlineDTOList = StreamUtils.filter(userOnlineDTOList, userOnline ->
StringUtils.equals(ipaddr, userOnline.getIpaddr()) &&
StringUtils.equals(userName, userOnline.getUserName())
);
} else if (StringUtils.isNotEmpty(ipaddr)) {
userOnlineDTOList = StreamUtils.filter(userOnlineDTOList, userOnline ->
StringUtils.equals(ipaddr, userOnline.getIpaddr())
);
} else if (StringUtils.isNotEmpty(userName)) {
userOnlineDTOList = StreamUtils.filter(userOnlineDTOList, userOnline ->
StringUtils.equals(userName, userOnline.getUserName())
);
}
Collections.reverse(userOnlineDTOList);
userOnlineDTOList.removeAll(Collections.singleton(null));
List<SysUserOnline> userOnlineList = BeanUtil.copyToList(userOnlineDTOList, SysUserOnline.class);
return TableDataInfo.build(userOnlineList);
}
/**
* 强退用户
*
* @param tokenId token值
*/
@SaCheckPermission("monitor:online:forceLogout")
@Log(title = "在线用户", businessType = BusinessType.FORCE)
@DeleteMapping("/{tokenId}")
public R<Void> forceLogout(@PathVariable String tokenId) {
try {
StpUtil.kickoutByTokenValue(tokenId);
} catch (NotLoginException ignored) {
}
return R.ok();
}
}
@@ -0,0 +1,137 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 参数配置 信息操作处理
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/config")
public class SysConfigController extends BaseController {
private final ISysConfigService configService;
/**
* 获取参数配置列表
*/
@SaCheckPermission("system:config:list")
@GetMapping("/list")
public TableDataInfo<SysConfig> list(SysConfig config, PageQuery pageQuery) {
return configService.selectPageConfigList(config, pageQuery);
}
/**
* 导出参数配置列表
*/
@Log(title = "参数管理", businessType = BusinessType.EXPORT)
@SaCheckPermission("system:config:export")
@PostMapping("/export")
public void export(SysConfig config, HttpServletResponse response) {
List<SysConfig> list = configService.selectConfigList(config);
ExcelUtil.exportExcel(list, "参数数据", SysConfig.class, response);
}
/**
* 根据参数编号获取详细信息
*
* @param configId 参数ID
*/
@SaCheckPermission("system:config:query")
@GetMapping(value = "/{configId}")
public R<SysConfig> getInfo(@PathVariable Long configId) {
return R.ok(configService.selectConfigById(configId));
}
/**
* 根据参数键名查询参数值
*
* @param configKey 参数Key
*/
@GetMapping(value = "/configKey/{configKey}")
public R<Void> getConfigKey(@PathVariable String configKey) {
return R.ok(configService.selectConfigByKey(configKey));
}
/**
* 新增参数配置
*/
@SaCheckPermission("system:config:add")
@Log(title = "参数管理", businessType = BusinessType.INSERT)
@PostMapping
public R<Void> add(@Validated @RequestBody SysConfig config) {
if (!configService.checkConfigKeyUnique(config)) {
return R.fail("新增参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
configService.insertConfig(config);
return R.ok();
}
/**
* 修改参数配置
*/
@SaCheckPermission("system:config:edit")
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
@PutMapping
public R<Void> edit(@Validated @RequestBody SysConfig config) {
if (!configService.checkConfigKeyUnique(config)) {
return R.fail("修改参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
configService.updateConfig(config);
return R.ok();
}
/**
* 根据参数键名修改参数配置
*/
@SaCheckPermission("system:config:edit")
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
@PutMapping("/updateByKey")
public R<Void> updateByKey(@RequestBody SysConfig config) {
configService.updateConfig(config);
return R.ok();
}
/**
* 删除参数配置
*
* @param configIds 参数ID串
*/
@SaCheckPermission("system:config:remove")
@Log(title = "参数管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{configIds}")
public R<Void> remove(@PathVariable Long[] configIds) {
configService.deleteConfigByIds(configIds);
return R.ok();
}
/**
* 刷新参数缓存
*/
@SaCheckPermission("system:config:remove")
@Log(title = "参数管理", businessType = BusinessType.CLEAN)
@DeleteMapping("/refreshCache")
public R<Void> refreshCache() {
configService.resetConfigCache();
return R.ok();
}
}
@@ -0,0 +1,122 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.convert.Convert;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 部门信息
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
private final ISysDeptService deptService;
/**
* 获取部门列表
*/
@SaCheckPermission("system:dept:list")
@GetMapping("/list")
public R<List<SysDept>> list(SysDept dept) {
List<SysDept> depts = deptService.selectDeptList(dept);
return R.ok(depts);
}
/**
* 查询部门列表(排除节点)
*
* @param deptId 部门ID
*/
@SaCheckPermission("system:dept:list")
@GetMapping("/list/exclude/{deptId}")
public R<List<SysDept>> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
List<SysDept> depts = deptService.selectDeptList(new SysDept());
depts.removeIf(d -> d.getDeptId().equals(deptId)
|| StringUtils.splitList(d.getAncestors()).contains(Convert.toStr(deptId)));
return R.ok(depts);
}
/**
* 根据部门编号获取详细信息
*
* @param deptId 部门ID
*/
@SaCheckPermission("system:dept:query")
@GetMapping(value = "/{deptId}")
public R<SysDept> getInfo(@PathVariable Long deptId) {
deptService.checkDeptDataScope(deptId);
return R.ok(deptService.selectDeptById(deptId));
}
/**
* 新增部门
*/
@SaCheckPermission("system:dept:add")
@Log(title = "部门管理", businessType = BusinessType.INSERT)
@PostMapping
public R<Void> add(@Validated @RequestBody SysDept dept) {
if (!deptService.checkDeptNameUnique(dept)) {
return R.fail("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在");
}
return toAjax(deptService.insertDept(dept));
}
/**
* 修改部门
*/
@SaCheckPermission("system:dept:edit")
@Log(title = "部门管理", businessType = BusinessType.UPDATE)
@PutMapping
public R<Void> edit(@Validated @RequestBody SysDept dept) {
Long deptId = dept.getDeptId();
deptService.checkDeptDataScope(deptId);
if (!deptService.checkDeptNameUnique(dept)) {
return R.fail("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在");
} else if (dept.getParentId().equals(deptId)) {
return R.fail("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己");
} else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())) {
if (deptService.selectNormalChildrenDeptById(deptId) > 0) {
return R.fail("该部门包含未停用的子部门!");
} else if (deptService.checkDeptExistUser(deptId)) {
return R.fail("该部门下存在已分配用户,不能禁用!");
}
}
return toAjax(deptService.updateDept(dept));
}
/**
* 删除部门
*
* @param deptId 部门ID
*/
@SaCheckPermission("system:dept:remove")
@Log(title = "部门管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{deptId}")
public R<Void> remove(@PathVariable Long deptId) {
if (deptService.hasChildByDeptId(deptId)) {
return R.warn("存在下级部门,不允许删除");
}
if (deptService.checkDeptExistUser(deptId)) {
return R.warn("部门存在用户,不允许删除");
}
deptService.checkDeptDataScope(deptId);
return toAjax(deptService.deleteDeptById(deptId));
}
}
@@ -0,0 +1,116 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
* 数据字典信息
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/dict/data")
public class SysDictDataController extends BaseController {
private final ISysDictDataService dictDataService;
private final ISysDictTypeService dictTypeService;
/**
* 查询字典数据列表
*/
@SaCheckPermission("system:dict:list")
@GetMapping("/list")
public TableDataInfo<SysDictData> list(SysDictData dictData, PageQuery pageQuery) {
return dictDataService.selectPageDictDataList(dictData, pageQuery);
}
/**
* 导出字典数据列表
*/
@Log(title = "字典数据", businessType = BusinessType.EXPORT)
@SaCheckPermission("system:dict:export")
@PostMapping("/export")
public void export(SysDictData dictData, HttpServletResponse response) {
List<SysDictData> list = dictDataService.selectDictDataList(dictData);
ExcelUtil.exportExcel(list, "字典数据", SysDictData.class, response);
}
/**
* 查询字典数据详细
*
* @param dictCode 字典code
*/
@SaCheckPermission("system:dict:query")
@GetMapping(value = "/{dictCode}")
public R<SysDictData> getInfo(@PathVariable Long dictCode) {
return R.ok(dictDataService.selectDictDataById(dictCode));
}
/**
* 根据字典类型查询字典数据信息
*
* @param dictType 字典类型
*/
@GetMapping(value = "/type/{dictType}")
public R<List<SysDictData>> dictType(@PathVariable String dictType) {
List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
if (ObjectUtil.isNull(data)) {
data = new ArrayList<>();
}
return R.ok(data);
}
/**
* 新增字典类型
*/
@SaCheckPermission("system:dict:add")
@Log(title = "字典数据", businessType = BusinessType.INSERT)
@PostMapping
public R<Void> add(@Validated @RequestBody SysDictData dict) {
dictDataService.insertDictData(dict);
return R.ok();
}
/**
* 修改保存字典类型
*/
@SaCheckPermission("system:dict:edit")
@Log(title = "字典数据", businessType = BusinessType.UPDATE)
@PutMapping
public R<Void> edit(@Validated @RequestBody SysDictData dict) {
dictDataService.updateDictData(dict);
return R.ok();
}
/**
* 删除字典类型
*
* @param dictCodes 字典code串
*/
@SaCheckPermission("system:dict:remove")
@Log(title = "字典类型", businessType = BusinessType.DELETE)
@DeleteMapping("/{dictCodes}")
public R<Void> remove(@PathVariable Long[] dictCodes) {
dictDataService.deleteDictDataByIds(dictCodes);
return R.ok();
}
}
@@ -0,0 +1,125 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 数据字典信息
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/dict/type")
public class SysDictTypeController extends BaseController {
private final ISysDictTypeService dictTypeService;
/**
* 查询字典类型列表
*/
@SaCheckPermission("system:dict:list")
@GetMapping("/list")
public TableDataInfo<SysDictType> list(SysDictType dictType, PageQuery pageQuery) {
return dictTypeService.selectPageDictTypeList(dictType, pageQuery);
}
/**
* 导出字典类型列表
*/
@Log(title = "字典类型", businessType = BusinessType.EXPORT)
@SaCheckPermission("system:dict:export")
@PostMapping("/export")
public void export(SysDictType dictType, HttpServletResponse response) {
List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
ExcelUtil.exportExcel(list, "字典类型", SysDictType.class, response);
}
/**
* 查询字典类型详细
*
* @param dictId 字典ID
*/
@SaCheckPermission("system:dict:query")
@GetMapping(value = "/{dictId}")
public R<SysDictType> getInfo(@PathVariable Long dictId) {
return R.ok(dictTypeService.selectDictTypeById(dictId));
}
/**
* 新增字典类型
*/
@SaCheckPermission("system:dict:add")
@Log(title = "字典类型", businessType = BusinessType.INSERT)
@PostMapping
public R<Void> add(@Validated @RequestBody SysDictType dict) {
if (!dictTypeService.checkDictTypeUnique(dict)) {
return R.fail("新增字典'" + dict.getDictName() + "'失败,字典类型已存在");
}
dictTypeService.insertDictType(dict);
return R.ok();
}
/**
* 修改字典类型
*/
@SaCheckPermission("system:dict:edit")
@Log(title = "字典类型", businessType = BusinessType.UPDATE)
@PutMapping
public R<Void> edit(@Validated @RequestBody SysDictType dict) {
if (!dictTypeService.checkDictTypeUnique(dict)) {
return R.fail("修改字典'" + dict.getDictName() + "'失败,字典类型已存在");
}
dictTypeService.updateDictType(dict);
return R.ok();
}
/**
* 删除字典类型
*
* @param dictIds 字典ID串
*/
@SaCheckPermission("system:dict:remove")
@Log(title = "字典类型", businessType = BusinessType.DELETE)
@DeleteMapping("/{dictIds}")
public R<Void> remove(@PathVariable Long[] dictIds) {
dictTypeService.deleteDictTypeByIds(dictIds);
return R.ok();
}
/**
* 刷新字典缓存
*/
@SaCheckPermission("system:dict:remove")
@Log(title = "字典类型", businessType = BusinessType.CLEAN)
@DeleteMapping("/refreshCache")
public R<Void> refreshCache() {
dictTypeService.resetDictCache();
return R.ok();
}
/**
* 获取字典选择框列表
*/
@GetMapping("/optionselect")
public R<List<SysDictType>> optionselect() {
List<SysDictType> dictTypes = dictTypeService.selectDictTypeAll();
return R.ok(dictTypes);
}
}
@@ -0,0 +1,32 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaIgnore;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 首页
*
* @author Lion Li
*/
@RequiredArgsConstructor
@RestController
public class SysIndexController {
/**
* 系统基础配置
*/
private final RuoYiConfig ruoyiConfig;
/**
* 访问首页,提示语
*/
@SaIgnore
@GetMapping("/")
public String index() {
return StringUtils.format("欢迎使用{}后台管理框架,当前版本:v{},请通过前端地址访问。", ruoyiConfig.getName(), ruoyiConfig.getVersion());
}
}
@@ -0,0 +1,144 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaIgnore;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.EmailLoginBody;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.SmsLoginBody;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.system.domain.vo.RouterVo;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.SysLoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 登录验证
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
public class SysLoginController {
private final SysLoginService loginService;
private final ISysMenuService menuService;
private final ISysUserService userService;
/**
* 登录方法
*
* @param loginBody 登录信息
* @return 结果
*/
@SaIgnore
@PostMapping("/login")
public R<Map<String, Object>> login(@Validated @RequestBody LoginBody loginBody) {
Map<String, Object> ajax = new HashMap<>();
// 生成令牌
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
loginBody.getUuid());
ajax.put(Constants.TOKEN, token);
return R.ok(ajax);
}
/**
* 短信登录
*
* @param smsLoginBody 登录信息
* @return 结果
*/
@SaIgnore
@PostMapping("/smsLogin")
public R<Map<String, Object>> smsLogin(@Validated @RequestBody SmsLoginBody smsLoginBody) {
Map<String, Object> ajax = new HashMap<>();
// 生成令牌
String token = loginService.smsLogin(smsLoginBody.getPhonenumber(), smsLoginBody.getSmsCode());
ajax.put(Constants.TOKEN, token);
return R.ok(ajax);
}
/**
* 邮件登录
*
* @param body 登录信息
* @return 结果
*/
@PostMapping("/emailLogin")
public R<Map<String, Object>> emailLogin(@Validated @RequestBody EmailLoginBody body) {
Map<String, Object> ajax = new HashMap<>();
// 生成令牌
String token = loginService.emailLogin(body.getEmail(), body.getEmailCode());
ajax.put(Constants.TOKEN, token);
return R.ok(ajax);
}
/**
* 小程序登录(示例)
*
* @param xcxCode 小程序code
* @return 结果
*/
@SaIgnore
@PostMapping("/xcxLogin")
public R<Map<String, Object>> xcxLogin(@NotBlank(message = "{xcx.code.not.blank}") String xcxCode) {
Map<String, Object> ajax = new HashMap<>();
// 生成令牌
String token = loginService.xcxLogin(xcxCode);
ajax.put(Constants.TOKEN, token);
return R.ok(ajax);
}
/**
* 退出登录
*/
@SaIgnore
@PostMapping("/logout")
public R<Void> logout() {
loginService.logout();
return R.ok("退出成功");
}
/**
* 获取用户信息
*
* @return 用户信息
*/
@GetMapping("getInfo")
public R<Map<String, Object>> getInfo() {
LoginUser loginUser = LoginHelper.getLoginUser();
SysUser user = userService.selectUserById(loginUser.getUserId());
Map<String, Object> ajax = new HashMap<>();
ajax.put("user", user);
ajax.put("roles", loginUser.getRolePermission());
ajax.put("permissions", loginUser.getMenuPermission());
return R.ok(ajax);
}
/**
* 获取路由信息
*
* @return 路由信息
*/
@GetMapping("getRouters")
public R<List<RouterVo>> getRouters() {
Long userId = LoginHelper.getUserId();
List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
return R.ok(menuService.buildMenus(menus));
}
}
@@ -0,0 +1,127 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.lang.tree.Tree;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 菜单信息
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {
private final ISysMenuService menuService;
/**
* 获取菜单列表
*/
@SaCheckPermission("system:menu:list")
@GetMapping("/list")
public R<List<SysMenu>> list(SysMenu menu) {
List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
return R.ok(menus);
}
/**
* 根据菜单编号获取详细信息
*
* @param menuId 菜单ID
*/
@SaCheckPermission("system:menu:query")
@GetMapping(value = "/{menuId}")
public R<SysMenu> getInfo(@PathVariable Long menuId) {
return R.ok(menuService.selectMenuById(menuId));
}
/**
* 获取菜单下拉树列表
*/
@GetMapping("/treeselect")
public R<List<Tree<Long>>> treeselect(SysMenu menu) {
List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
return R.ok(menuService.buildMenuTreeSelect(menus));
}
/**
* 加载对应角色菜单列表树
*
* @param roleId 角色ID
*/
@GetMapping(value = "/roleMenuTreeselect/{roleId}")
public R<Map<String, Object>> roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
List<SysMenu> menus = menuService.selectMenuList(getUserId());
Map<String, Object> ajax = new HashMap<>();
ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
ajax.put("menus", menuService.buildMenuTreeSelect(menus));
return R.ok(ajax);
}
/**
* 新增菜单
*/
@SaCheckPermission("system:menu:add")
@Log(title = "菜单管理", businessType = BusinessType.INSERT)
@PostMapping
public R<Void> add(@Validated @RequestBody SysMenu menu) {
if (!menuService.checkMenuNameUnique(menu)) {
return R.fail("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
} else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
return R.fail("新增菜单'" + menu.getMenuName() + "'失败,地址必须以http(s)://开头");
}
return toAjax(menuService.insertMenu(menu));
}
/**
* 修改菜单
*/
@SaCheckPermission("system:menu:edit")
@Log(title = "菜单管理", businessType = BusinessType.UPDATE)
@PutMapping
public R<Void> edit(@Validated @RequestBody SysMenu menu) {
if (!menuService.checkMenuNameUnique(menu)) {
return R.fail("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
} else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
return R.fail("修改菜单'" + menu.getMenuName() + "'失败,地址必须以http(s)://开头");
} else if (menu.getMenuId().equals(menu.getParentId())) {
return R.fail("修改菜单'" + menu.getMenuName() + "'失败,上级菜单不能选择自己");
}
return toAjax(menuService.updateMenu(menu));
}
/**
* 删除菜单
*
* @param menuId 菜单ID
*/
@SaCheckPermission("system:menu:remove")
@Log(title = "菜单管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{menuId}")
public R<Void> remove(@PathVariable("menuId") Long menuId) {
if (menuService.hasChildByMenuId(menuId)) {
return R.warn("存在子菜单,不允许删除");
}
if (menuService.checkMenuExistRole(menuId)) {
return R.warn("菜单已分配,不允许删除");
}
return toAjax(menuService.deleteMenuById(menuId));
}
}
@@ -0,0 +1,80 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* 公告 信息操作处理
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/notice")
public class SysNoticeController extends BaseController {
private final ISysNoticeService noticeService;
/**
* 获取通知公告列表
*/
@SaCheckPermission("system:notice:list")
@GetMapping("/list")
public TableDataInfo<SysNotice> list(SysNotice notice, PageQuery pageQuery) {
return noticeService.selectPageNoticeList(notice, pageQuery);
}
/**
* 根据通知公告编号获取详细信息
*
* @param noticeId 公告ID
*/
@SaCheckPermission("system:notice:query")
@GetMapping(value = "/{noticeId}")
public R<SysNotice> getInfo(@PathVariable Long noticeId) {
return R.ok(noticeService.selectNoticeById(noticeId));
}
/**
* 新增通知公告
*/
@SaCheckPermission("system:notice:add")
@Log(title = "通知公告", businessType = BusinessType.INSERT)
@PostMapping
public R<Void> add(@Validated @RequestBody SysNotice notice) {
return toAjax(noticeService.insertNotice(notice));
}
/**
* 修改通知公告
*/
@SaCheckPermission("system:notice:edit")
@Log(title = "通知公告", businessType = BusinessType.UPDATE)
@PutMapping
public R<Void> edit(@Validated @RequestBody SysNotice notice) {
return toAjax(noticeService.updateNotice(notice));
}
/**
* 删除通知公告
*
* @param noticeIds 公告ID串
*/
@SaCheckPermission("system:notice:remove")
@Log(title = "通知公告", businessType = BusinessType.DELETE)
@DeleteMapping("/{noticeIds}")
public R<Void> remove(@PathVariable Long[] noticeIds) {
return toAjax(noticeService.deleteNoticeByIds(noticeIds));
}
}
@@ -0,0 +1,105 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.bo.SysOssConfigBo;
import com.ruoyi.system.domain.vo.SysOssConfigVo;
import com.ruoyi.system.service.ISysOssConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
/**
* 对象存储配置
*
* @author Lion Li
* @author 孤舟烟雨
* @date 2021-08-13
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/oss/config")
public class SysOssConfigController extends BaseController {
private final ISysOssConfigService iSysOssConfigService;
/**
* 查询对象存储配置列表
*/
@SaCheckPermission("system:oss:list")
@GetMapping("/list")
public TableDataInfo<SysOssConfigVo> list(@Validated(QueryGroup.class) SysOssConfigBo bo, PageQuery pageQuery) {
return iSysOssConfigService.queryPageList(bo, pageQuery);
}
/**
* 获取对象存储配置详细信息
*
* @param ossConfigId OSS配置ID
*/
@SaCheckPermission("system:oss:query")
@GetMapping("/{ossConfigId}")
public R<SysOssConfigVo> getInfo(@NotNull(message = "主键不能为空")
@PathVariable Long ossConfigId) {
return R.ok(iSysOssConfigService.queryById(ossConfigId));
}
/**
* 新增对象存储配置
*/
@SaCheckPermission("system:oss:add")
@Log(title = "对象存储配置", businessType = BusinessType.INSERT)
@RepeatSubmit()
@PostMapping()
public R<Void> add(@Validated(AddGroup.class) @RequestBody SysOssConfigBo bo) {
return toAjax(iSysOssConfigService.insertByBo(bo));
}
/**
* 修改对象存储配置
*/
@SaCheckPermission("system:oss:edit")
@Log(title = "对象存储配置", businessType = BusinessType.UPDATE)
@RepeatSubmit()
@PutMapping()
public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysOssConfigBo bo) {
return toAjax(iSysOssConfigService.updateByBo(bo));
}
/**
* 删除对象存储配置
*
* @param ossConfigIds OSS配置ID串
*/
@SaCheckPermission("system:oss:remove")
@Log(title = "对象存储配置", businessType = BusinessType.DELETE)
@DeleteMapping("/{ossConfigIds}")
public R<Void> remove(@NotEmpty(message = "主键不能为空")
@PathVariable Long[] ossConfigIds) {
return toAjax(iSysOssConfigService.deleteWithValidByIds(Arrays.asList(ossConfigIds), true));
}
/**
* 状态修改
*/
@SaCheckPermission("system:oss:edit")
@Log(title = "对象存储状态修改", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public R<Void> changeStatus(@RequestBody SysOssConfigBo bo) {
return toAjax(iSysOssConfigService.updateOssConfigStatus(bo));
}
}
@@ -0,0 +1,109 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.bo.SysOssBo;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 文件上传 控制层
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/oss")
public class SysOssController extends BaseController {
private final ISysOssService iSysOssService;
/**
* 查询OSS对象存储列表
*/
@SaCheckPermission("system:oss:list")
@GetMapping("/list")
public TableDataInfo<SysOssVo> list(@Validated(QueryGroup.class) SysOssBo bo, PageQuery pageQuery) {
return iSysOssService.queryPageList(bo, pageQuery);
}
/**
* 查询OSS对象基于id串
*
* @param ossIds OSS对象ID串
*/
@SaCheckPermission("system:oss:list")
@GetMapping("/listByIds/{ossIds}")
public R<List<SysOssVo>> listByIds(@NotEmpty(message = "主键不能为空")
@PathVariable Long[] ossIds) {
List<SysOssVo> list = iSysOssService.listByIds(Arrays.asList(ossIds));
return R.ok(list);
}
/**
* 上传OSS对象存储
*
* @param file 文件
*/
@SaCheckPermission("system:oss:upload")
@Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public R<Map<String, String>> upload(@RequestPart("file") MultipartFile file) {
if (ObjectUtil.isNull(file)) {
return R.fail("上传文件不能为空");
}
SysOssVo oss = iSysOssService.upload(file);
Map<String, String> map = new HashMap<>(2);
map.put("url", oss.getUrl());
map.put("fileName", oss.getOriginalName());
map.put("ossId", oss.getOssId().toString());
return R.ok(map);
}
/**
* 下载OSS对象
*
* @param ossId OSS对象ID
*/
@SaCheckPermission("system:oss:download")
@GetMapping("/download/{ossId}")
public void download(@PathVariable Long ossId, HttpServletResponse response) throws IOException {
iSysOssService.download(ossId,response);
}
/**
* 删除OSS对象存储
*
* @param ossIds OSS对象ID串
*/
@SaCheckPermission("system:oss:remove")
@Log(title = "OSS对象存储", businessType = BusinessType.DELETE)
@DeleteMapping("/{ossIds}")
public R<Void> remove(@NotEmpty(message = "主键不能为空")
@PathVariable Long[] ossIds) {
return toAjax(iSysOssService.deleteWithValidByIds(Arrays.asList(ossIds), true));
}
}
@@ -0,0 +1,120 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysPostService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 岗位信息操作处理
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/post")
public class SysPostController extends BaseController {
private final ISysPostService postService;
/**
* 获取岗位列表
*/
@SaCheckPermission("system:post:list")
@GetMapping("/list")
public TableDataInfo<SysPost> list(SysPost post, PageQuery pageQuery) {
return postService.selectPagePostList(post, pageQuery);
}
/**
* 导出岗位列表
*/
@Log(title = "岗位管理", businessType = BusinessType.EXPORT)
@SaCheckPermission("system:post:export")
@PostMapping("/export")
public void export(SysPost post, HttpServletResponse response) {
List<SysPost> list = postService.selectPostList(post);
ExcelUtil.exportExcel(list, "岗位数据", SysPost.class, response);
}
/**
* 根据岗位编号获取详细信息
*
* @param postId 岗位ID
*/
@SaCheckPermission("system:post:query")
@GetMapping(value = "/{postId}")
public R<SysPost> getInfo(@PathVariable Long postId) {
return R.ok(postService.selectPostById(postId));
}
/**
* 新增岗位
*/
@SaCheckPermission("system:post:add")
@Log(title = "岗位管理", businessType = BusinessType.INSERT)
@PostMapping
public R<Void> add(@Validated @RequestBody SysPost post) {
if (!postService.checkPostNameUnique(post)) {
return R.fail("新增岗位'" + post.getPostName() + "'失败,岗位名称已存在");
} else if (!postService.checkPostCodeUnique(post)) {
return R.fail("新增岗位'" + post.getPostName() + "'失败,岗位编码已存在");
}
return toAjax(postService.insertPost(post));
}
/**
* 修改岗位
*/
@SaCheckPermission("system:post:edit")
@Log(title = "岗位管理", businessType = BusinessType.UPDATE)
@PutMapping
public R<Void> edit(@Validated @RequestBody SysPost post) {
if (!postService.checkPostNameUnique(post)) {
return R.fail("修改岗位'" + post.getPostName() + "'失败,岗位名称已存在");
} else if (!postService.checkPostCodeUnique(post)) {
return R.fail("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在");
} else if (UserConstants.POST_DISABLE.equals(post.getStatus())
&& postService.countUserPostById(post.getPostId()) > 0) {
return R.fail("该岗位下存在已分配用户,不能禁用!");
}
return toAjax(postService.updatePost(post));
}
/**
* 删除岗位
*
* @param postIds 岗位ID串
*/
@SaCheckPermission("system:post:remove")
@Log(title = "岗位管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{postIds}")
public R<Void> remove(@PathVariable Long[] postIds) {
return toAjax(postService.deletePostByIds(postIds));
}
/**
* 获取岗位选择框列表
*/
@GetMapping("/optionselect")
public R<List<SysPost>> optionselect() {
SysPost post = new SysPost();
post.setStatus(UserConstants.POST_NORMAL);
List<SysPost> posts = postService.selectPostList(post);
return R.ok(posts);
}
}
@@ -0,0 +1,126 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.io.FileUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.system.domain.SysOss;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.service.ISysOssService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* 个人信息 业务处理
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {
private final ISysUserService userService;
private final ISysOssService iSysOssService;
/**
* 个人信息
*/
@GetMapping
public R<Map<String, Object>> profile() {
SysUser user = userService.selectUserById(getUserId());
Map<String, Object> ajax = new HashMap<>();
ajax.put("user", user);
ajax.put("roleGroup", userService.selectUserRoleGroup(user.getUserName()));
ajax.put("postGroup", userService.selectUserPostGroup(user.getUserName()));
return R.ok(ajax);
}
/**
* 修改用户
*/
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping
public R<Void> updateProfile(@RequestBody SysUser user) {
if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
return R.fail("修改用户'" + user.getUserName() + "'失败,手机号码已存在");
}
if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
return R.fail("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
user.setUserId(getUserId());
user.setUserName(null);
user.setPassword(null);
user.setAvatar(null);
user.setDeptId(null);
if (userService.updateUserProfile(user) > 0) {
return R.ok();
}
return R.fail("修改个人信息异常,请联系管理员");
}
/**
* 重置密码
*
* @param newPassword 新密码
* @param oldPassword 旧密码
*/
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping("/updatePwd")
public R<Void> updatePwd(String oldPassword, String newPassword) {
SysUser user = userService.selectUserById(LoginHelper.getUserId());
String userName = user.getUserName();
String password = user.getPassword();
if (!BCrypt.checkpw(oldPassword, password)) {
return R.fail("修改密码失败,旧密码错误");
}
if (BCrypt.checkpw(newPassword, password)) {
return R.fail("新密码不能与旧密码相同");
}
if (userService.resetUserPwd(userName, BCrypt.hashpw(newPassword)) > 0) {
return R.ok();
}
return R.fail("修改密码异常,请联系管理员");
}
/**
* 头像上传
*
* @param avatarfile 用户头像
*/
@Log(title = "用户头像", businessType = BusinessType.UPDATE)
@PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public R<Map<String, Object>> avatar(@RequestPart("avatarfile") MultipartFile avatarfile) {
Map<String, Object> ajax = new HashMap<>();
if (!avatarfile.isEmpty()) {
String extension = FileUtil.extName(avatarfile.getOriginalFilename());
if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
return R.fail("文件格式不正确,请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
}
SysOssVo oss = iSysOssService.upload(avatarfile);
String avatar = oss.getUrl();
if (userService.updateUserAvatar(getUsername(), avatar)) {
ajax.put("imgUrl", avatar);
return R.ok(ajax);
}
}
return R.fail("上传图片异常,请联系管理员");
}
}
@@ -0,0 +1,40 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaIgnore;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.SysRegisterService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
/**
* 注册验证
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
public class SysRegisterController extends BaseController {
private final SysRegisterService registerService;
private final ISysConfigService configService;
/**
* 用户注册
*/
@SaIgnore
@PostMapping("/register")
public R<Void> register(@Validated @RequestBody RegisterBody user) {
if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
return R.fail("当前系统没有开启注册功能!");
}
registerService.register(user);
return R.ok();
}
}
@@ -0,0 +1,228 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.SysPermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 角色信息
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
private final ISysRoleService roleService;
private final ISysUserService userService;
private final ISysDeptService deptService;
private final SysPermissionService permissionService;
/**
* 获取角色信息列表
*/
@SaCheckPermission("system:role:list")
@GetMapping("/list")
public TableDataInfo<SysRole> list(SysRole role, PageQuery pageQuery) {
return roleService.selectPageRoleList(role, pageQuery);
}
/**
* 导出角色信息列表
*/
@Log(title = "角色管理", businessType = BusinessType.EXPORT)
@SaCheckPermission("system:role:export")
@PostMapping("/export")
public void export(SysRole role, HttpServletResponse response) {
List<SysRole> list = roleService.selectRoleList(role);
ExcelUtil.exportExcel(list, "角色数据", SysRole.class, response);
}
/**
* 根据角色编号获取详细信息
*
* @param roleId 角色ID
*/
@SaCheckPermission("system:role:query")
@GetMapping(value = "/{roleId}")
public R<SysRole> getInfo(@PathVariable Long roleId) {
roleService.checkRoleDataScope(roleId);
return R.ok(roleService.selectRoleById(roleId));
}
/**
* 新增角色
*/
@SaCheckPermission("system:role:add")
@Log(title = "角色管理", businessType = BusinessType.INSERT)
@PostMapping
public R<Void> add(@Validated @RequestBody SysRole role) {
roleService.checkRoleAllowed(role);
if (!roleService.checkRoleNameUnique(role)) {
return R.fail("新增角色'" + role.getRoleName() + "'失败,角色名称已存在");
} else if (!roleService.checkRoleKeyUnique(role)) {
return R.fail("新增角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
return toAjax(roleService.insertRole(role));
}
/**
* 修改保存角色
*/
@SaCheckPermission("system:role:edit")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping
public R<Void> edit(@Validated @RequestBody SysRole role) {
roleService.checkRoleAllowed(role);
roleService.checkRoleDataScope(role.getRoleId());
if (!roleService.checkRoleNameUnique(role)) {
return R.fail("修改角色'" + role.getRoleName() + "'失败,角色名称已存在");
} else if (!roleService.checkRoleKeyUnique(role)) {
return R.fail("修改角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
if (roleService.updateRole(role) > 0) {
roleService.cleanOnlineUserByRole(role.getRoleId());
return R.ok();
}
return R.fail("修改角色'" + role.getRoleName() + "'失败,请联系管理员");
}
/**
* 修改保存数据权限
*/
@SaCheckPermission("system:role:edit")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/dataScope")
public R<Void> dataScope(@RequestBody SysRole role) {
roleService.checkRoleAllowed(role);
roleService.checkRoleDataScope(role.getRoleId());
return toAjax(roleService.authDataScope(role));
}
/**
* 状态修改
*/
@SaCheckPermission("system:role:edit")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public R<Void> changeStatus(@RequestBody SysRole role) {
roleService.checkRoleAllowed(role);
roleService.checkRoleDataScope(role.getRoleId());
return toAjax(roleService.updateRoleStatus(role));
}
/**
* 删除角色
*
* @param roleIds 角色ID串
*/
@SaCheckPermission("system:role:remove")
@Log(title = "角色管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{roleIds}")
public R<Void> remove(@PathVariable Long[] roleIds) {
return toAjax(roleService.deleteRoleByIds(roleIds));
}
/**
* 获取角色选择框列表
*/
@SaCheckPermission("system:role:query")
@GetMapping("/optionselect")
public R<List<SysRole>> optionselect() {
return R.ok(roleService.selectRoleAll());
}
/**
* 查询已分配用户角色列表
*/
@SaCheckPermission("system:role:list")
@GetMapping("/authUser/allocatedList")
public TableDataInfo<SysUser> allocatedList(SysUser user, PageQuery pageQuery) {
return userService.selectAllocatedList(user, pageQuery);
}
/**
* 查询未分配用户角色列表
*/
@SaCheckPermission("system:role:list")
@GetMapping("/authUser/unallocatedList")
public TableDataInfo<SysUser> unallocatedList(SysUser user, PageQuery pageQuery) {
return userService.selectUnallocatedList(user, pageQuery);
}
/**
* 取消授权用户
*/
@SaCheckPermission("system:role:edit")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/cancel")
public R<Void> cancelAuthUser(@RequestBody SysUserRole userRole) {
return toAjax(roleService.deleteAuthUser(userRole));
}
/**
* 批量取消授权用户
*
* @param roleId 角色ID
* @param userIds 用户ID串
*/
@SaCheckPermission("system:role:edit")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/cancelAll")
public R<Void> cancelAuthUserAll(Long roleId, Long[] userIds) {
return toAjax(roleService.deleteAuthUsers(roleId, userIds));
}
/**
* 批量选择用户授权
*
* @param roleId 角色ID
* @param userIds 用户ID串
*/
@SaCheckPermission("system:role:edit")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/selectAll")
public R<Void> selectAuthUserAll(Long roleId, Long[] userIds) {
roleService.checkRoleDataScope(roleId);
return toAjax(roleService.insertAuthUsers(roleId, userIds));
}
/**
* 获取对应角色部门树列表
*
* @param roleId 角色ID
*/
@SaCheckPermission("system:role:list")
@GetMapping(value = "/deptTree/{roleId}")
public R<Map<String, Object>> roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
Map<String, Object> ajax = new HashMap<>();
ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
return R.ok(ajax);
}
}
@@ -0,0 +1,256 @@
package com.ruoyi.web.controller.system;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StreamUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.vo.SysUserExportVo;
import com.ruoyi.system.domain.vo.SysUserImportVo;
import com.ruoyi.system.listener.SysUserImportListener;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 用户信息
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
private final ISysUserService userService;
private final ISysRoleService roleService;
private final ISysPostService postService;
private final ISysDeptService deptService;
/**
* 获取用户列表
*/
@SaCheckPermission("system:user:list")
@GetMapping("/list")
public TableDataInfo<SysUser> list(SysUser user, PageQuery pageQuery) {
return userService.selectPageUserList(user, pageQuery);
}
/**
* 导出用户列表
*/
@Log(title = "用户管理", businessType = BusinessType.EXPORT)
@SaCheckPermission("system:user:export")
@PostMapping("/export")
public void export(SysUser user, HttpServletResponse response) {
List<SysUser> list = userService.selectUserList(user);
List<SysUserExportVo> listVo = BeanUtil.copyToList(list, SysUserExportVo.class);
for (int i = 0; i < list.size(); i++) {
SysDept dept = list.get(i).getDept();
SysUserExportVo vo = listVo.get(i);
if (ObjectUtil.isNotEmpty(dept)) {
vo.setDeptName(dept.getDeptName());
vo.setLeader(dept.getLeader());
}
}
ExcelUtil.exportExcel(listVo, "用户数据", SysUserExportVo.class, response);
}
/**
* 导入数据
*
* @param file 导入文件
* @param updateSupport 是否更新已存在数据
*/
@Log(title = "用户管理", businessType = BusinessType.IMPORT)
@SaCheckPermission("system:user:import")
@PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public R<Void> importData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
ExcelResult<SysUserImportVo> result = ExcelUtil.importExcel(file.getInputStream(), SysUserImportVo.class, new SysUserImportListener(updateSupport));
return R.ok(result.getAnalysis());
}
/**
* 获取导入模板
*/
@PostMapping("/importTemplate")
public void importTemplate(HttpServletResponse response) {
ExcelUtil.exportExcel(new ArrayList<>(), "用户数据", SysUserImportVo.class, response);
}
/**
* 根据用户编号获取详细信息
*
* @param userId 用户ID
*/
@SaCheckPermission("system:user:query")
@GetMapping(value = {"/", "/{userId}"})
public R<Map<String, Object>> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
userService.checkUserDataScope(userId);
Map<String, Object> ajax = new HashMap<>();
SysRole role = new SysRole();
role.setStatus(UserConstants.ROLE_NORMAL);
SysPost post = new SysPost();
post.setStatus(UserConstants.POST_NORMAL);
List<SysRole> roles = roleService.selectRoleList(role);
ajax.put("roles", LoginHelper.isAdmin(userId) ? roles : StreamUtils.filter(roles, r -> !r.isAdmin()));
ajax.put("posts", postService.selectPostList(post));
if (ObjectUtil.isNotNull(userId)) {
SysUser sysUser = userService.selectUserById(userId);
ajax.put("user", sysUser);
ajax.put("postIds", postService.selectPostListByUserId(userId));
ajax.put("roleIds", StreamUtils.toList(sysUser.getRoles(), SysRole::getRoleId));
}
return R.ok(ajax);
}
/**
* 新增用户
*/
@SaCheckPermission("system:user:add")
@Log(title = "用户管理", businessType = BusinessType.INSERT)
@PostMapping
public R<Void> add(@Validated @RequestBody SysUser user) {
deptService.checkDeptDataScope(user.getDeptId());
if (!userService.checkUserNameUnique(user)) {
return R.fail("新增用户'" + user.getUserName() + "'失败,登录账号已存在");
} else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
return R.fail("新增用户'" + user.getUserName() + "'失败,手机号码已存在");
} else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
return R.fail("新增用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
user.setPassword(BCrypt.hashpw(user.getPassword()));
return toAjax(userService.insertUser(user));
}
/**
* 修改用户
*/
@SaCheckPermission("system:user:edit")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping
public R<Void> edit(@Validated @RequestBody SysUser user) {
userService.checkUserAllowed(user);
userService.checkUserDataScope(user.getUserId());
deptService.checkDeptDataScope(user.getDeptId());
if (!userService.checkUserNameUnique(user)) {
return R.fail("修改用户'" + user.getUserName() + "'失败,登录账号已存在");
} else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
return R.fail("修改用户'" + user.getUserName() + "'失败,手机号码已存在");
} else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
return R.fail("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
return toAjax(userService.updateUser(user));
}
/**
* 删除用户
*
* @param userIds 角色ID串
*/
@SaCheckPermission("system:user:remove")
@Log(title = "用户管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{userIds}")
public R<Void> remove(@PathVariable Long[] userIds) {
if (ArrayUtil.contains(userIds, getUserId())) {
return R.fail("当前用户不能删除");
}
return toAjax(userService.deleteUserByIds(userIds));
}
/**
* 重置密码
*/
@SaCheckPermission("system:user:resetPwd")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping("/resetPwd")
public R<Void> resetPwd(@RequestBody SysUser user) {
userService.checkUserAllowed(user);
userService.checkUserDataScope(user.getUserId());
user.setPassword(BCrypt.hashpw(user.getPassword()));
return toAjax(userService.resetPwd(user));
}
/**
* 状态修改
*/
@SaCheckPermission("system:user:edit")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public R<Void> changeStatus(@RequestBody SysUser user) {
userService.checkUserAllowed(user);
userService.checkUserDataScope(user.getUserId());
return toAjax(userService.updateUserStatus(user));
}
/**
* 根据用户编号获取授权角色
*
* @param userId 用户ID
*/
@SaCheckPermission("system:user:query")
@GetMapping("/authRole/{userId}")
public R<Map<String, Object>> authRole(@PathVariable Long userId) {
SysUser user = userService.selectUserById(userId);
List<SysRole> roles = roleService.selectRolesByUserId(userId);
Map<String, Object> ajax = new HashMap<>();
ajax.put("user", user);
ajax.put("roles", LoginHelper.isAdmin(userId) ? roles : StreamUtils.filter(roles, r -> !r.isAdmin()));
return R.ok(ajax);
}
/**
* 用户授权角色
*
* @param userId 用户Id
* @param roleIds 角色ID串
*/
@SaCheckPermission("system:user:edit")
@Log(title = "用户管理", businessType = BusinessType.GRANT)
@PutMapping("/authRole")
public R<Void> insertAuthRole(Long userId, Long[] roleIds) {
userService.checkUserDataScope(userId);
userService.insertUserAuth(userId, roleIds);
return R.ok();
}
/**
* 获取部门树列表
*/
@SaCheckPermission("system:user:list")
@GetMapping("/deptTree")
public R<List<Tree<Long>>> deptTree(SysDept dept) {
return R.ok(deptService.selectDeptTreeList(dept));
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 63 MiB

@@ -0,0 +1,162 @@
--- # 监控中心配置
spring.boot.admin.client:
# 增加客户端开关
enabled: true
url: http://localhost:9090/admin
instance:
service-host-type: IP
username: ruoyi
password: 123456
--- # 浏览器扩展配置
browser:
# GeoIP 数据库绝对路径,优先于 classpath 与相对路径搜索
geoip-db-path: D:/desk/指纹浏览器/RuoYi-Vue-Plus-v4.8.3/ruoyi-admin/src/main/resources/GeoLite2-City.mmdb
--- # xxl-job 配置
xxl.job:
# 执行器开关
enabled: false
# 调度中心地址:如调度中心集群部署存在多个地址则用逗号分隔。
admin-addresses: http://localhost:9100/xxl-job-admin
# 执行器通讯TOKEN:非空时启用
access-token: xxl-job
executor:
# 执行器AppName:执行器心跳注册分组依据;为空则关闭自动注册
appname: xxl-job-executor
# 28080 端口 随着主应用端口飘逸 避免集群冲突
port: 2${server.port}
# 执行器注册:默认IP:PORT
address:
# 执行器IP:默认自动获取IP
ip:
# 执行器运行日志文件存储磁盘路径
logpath: ./logs/xxl-job
# 执行器日志文件保存天数:大于3生效
logretentiondays: 30
--- # 数据源配置
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
# 动态数据源文档 https://www.kancloud.cn/tracy5546/dynamic-datasource/content
dynamic:
# 性能分析插件(有性能损耗 不建议生产环境使用)
p6spy: true
# 设置默认的数据源或者数据源组,默认值即为 master
primary: master
# 严格模式 匹配不到数据源则报错
strict: true
datasource:
# 主库数据源
master:
type: ${spring.datasource.type}
driverClassName: com.mysql.cj.jdbc.Driver
# jdbc 所有参数配置参考 https://lionli.blog.csdn.net/article/details/122018562
# rewriteBatchedStatements=true 批处理优化 大幅提升批量插入更新删除性能(对数据库有性能损耗 使用批量操作应考虑性能问题)
url: jdbc:mysql://localhost:3306/browserx?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true
username: root
password: root
# 从库数据源
hikari:
# 最大连接池数量
maxPoolSize: 20
# 最小空闲线程数量
minIdle: 10
# 配置获取连接等待超时的时间
connectionTimeout: 30000
# 校验超时时间
validationTimeout: 5000
# 空闲连接存活最大时间,默认10分钟
idleTimeout: 600000
# 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认30分钟
maxLifetime: 1800000
# 多久检查一次连接的活性
keepaliveTime: 30000
--- # redis 单机配置(单机与集群只能开启一个另一个需要注释掉)
spring:
redis:
# 地址
host: localhost
# 端口,默认为6379
port: 6379
# 数据库索引
database: 0
# 密码(如没有密码请注释掉)
# password:
# 连接超时时间
timeout: 10s
# 是否开启ssl
ssl: false
redisson:
# redis key前缀
keyPrefix:
# 线程池数量
threads: 4
# Netty线程池数量
nettyThreads: 8
# 单节点配置
singleServerConfig:
# 客户端名称
clientName: ${ruoyi.name}
# 最小空闲连接数
connectionMinimumIdleSize: 8
# 连接池大小
connectionPoolSize: 32
# 连接空闲超时,单位:毫秒
idleConnectionTimeout: 10000
# 命令等待超时,单位:毫秒
timeout: 3000
# 发布和订阅连接池大小
subscriptionConnectionPoolSize: 50
--- # mail 邮件发送
mail:
enabled: false
host: smtp.163.com
port: 465
# 是否需要用户名密码验证
auth: true
# 发送方,遵循RFC-822标准
from: xxx@163.com
# 用户名(注意:如果使用foxmail邮箱,此处user为qq号)
user: xxx@163.com
# 密码(注意,某些邮箱需要为SMTP服务单独设置密码,详情查看相关帮助)
pass: xxxxxxxxxx
# 使用 STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展。
starttlsEnable: true
# 使用SSL安全连接
sslEnable: true
# SMTP超时时长,单位毫秒,缺省值不超时
timeout: 0
# Socket连接超时值,单位毫秒,缺省值不超时
connectionTimeout: 0
--- # sms 短信 支持 阿里云 腾讯云 云片 等等各式各样的短信服务商
# https://wind.kim/doc/start 文档地址 各个厂商可同时使用
sms:
# 阿里云 dysmsapi.aliyuncs.com
alibaba:
#请求地址 默认为 dysmsapi.aliyuncs.com 如无特殊改变可以不用设置
requestUrl: dysmsapi.aliyuncs.com
#阿里云的accessKey
accessKeyId: xxxxxxx
#阿里云的accessKeySecret
accessKeySecret: xxxxxxx
#短信签名
signature: 测试
tencent:
#请求地址默认为 sms.tencentcloudapi.com 如无特殊改变可不用设置
requestUrl: sms.tencentcloudapi.com
#腾讯云的accessKey
accessKeyId: xxxxxxx
#腾讯云的accessKeySecret
accessKeySecret: xxxxxxx
#短信签名
signature: 测试
#短信sdkAppId
sdkAppId: appid
#地域信息默认为 ap-guangzhou 如无特殊改变可不用设置
territory: ap-guangzhou
@@ -0,0 +1,185 @@
--- # 临时文件存储位置 避免临时文件被系统清理报错
spring.servlet.multipart.location: /ruoyi/server/temp
--- # 监控中心配置
spring.boot.admin.client:
# 增加客户端开关
enabled: true
url: http://localhost:9090/admin
instance:
service-host-type: IP
username: ruoyi
password: 123456
--- # xxl-job 配置
xxl.job:
# 执行器开关
enabled: true
# 调度中心地址:如调度中心集群部署存在多个地址则用逗号分隔。
admin-addresses: http://localhost:9100/xxl-job-admin
# 执行器通讯TOKEN:非空时启用
access-token: xxl-job
executor:
# 执行器AppName:执行器心跳注册分组依据;为空则关闭自动注册
appname: xxl-job-executor
# 28080 端口 随着主应用端口飘逸 避免集群冲突
port: 2${server.port}
# 执行器注册:默认IP:PORT
address:
# 执行器IP:默认自动获取IP
ip:
# 执行器运行日志文件存储磁盘路径
logpath: ./logs/xxl-job
# 执行器日志文件保存天数:大于3生效
logretentiondays: 30
--- # 数据源配置
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
# 动态数据源文档 https://www.kancloud.cn/tracy5546/dynamic-datasource/content
dynamic:
# 性能分析插件(有性能损耗 不建议生产环境使用)
p6spy: false
# 设置默认的数据源或者数据源组,默认值即为 master
primary: master
# 严格模式 匹配不到数据源则报错
strict: true
datasource:
# 主库数据源
master:
type: ${spring.datasource.type}
driverClassName: com.mysql.cj.jdbc.Driver
# jdbc 所有参数配置参考 https://lionli.blog.csdn.net/article/details/122018562
# rewriteBatchedStatements=true 批处理优化 大幅提升批量插入更新删除性能(对数据库有性能损耗 使用批量操作应考虑性能问题)
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true
username: root
password: root
# 从库数据源
slave:
lazy: true
type: ${spring.datasource.type}
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true
username:
password:
# oracle:
# type: ${spring.datasource.type}
# driverClassName: oracle.jdbc.OracleDriver
# url: jdbc:oracle:thin:@//localhost:1521/XE
# username: ROOT
# password: root
# postgres:
# type: ${spring.datasource.type}
# driverClassName: org.postgresql.Driver
# url: jdbc:postgresql://localhost:5432/postgres?useUnicode=true&characterEncoding=utf8&useSSL=true&autoReconnect=true&reWriteBatchedInserts=true
# username: root
# password: root
# sqlserver:
# type: ${spring.datasource.type}
# driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
# url: jdbc:sqlserver://localhost:1433;DatabaseName=tempdb;SelectMethod=cursor;encrypt=false;rewriteBatchedStatements=true
# username: SA
# password: root
hikari:
# 最大连接池数量
maxPoolSize: 20
# 最小空闲线程数量
minIdle: 10
# 配置获取连接等待超时的时间
connectionTimeout: 30000
# 校验超时时间
validationTimeout: 5000
# 空闲连接存活最大时间,默认10分钟
idleTimeout: 600000
# 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认30分钟
maxLifetime: 1800000
# 多久检查一次连接的活性
keepaliveTime: 30000
--- # redis 单机配置(单机与集群只能开启一个另一个需要注释掉)
spring:
redis:
# 地址
host: localhost
# 端口,默认为6379
port: 6379
# 数据库索引
database: 0
# 密码(如没有密码请注释掉)
# password:
# 连接超时时间
timeout: 10s
# 是否开启ssl
ssl: false
redisson:
# redis key前缀
keyPrefix:
# 线程池数量
threads: 16
# Netty线程池数量
nettyThreads: 32
# 单节点配置
singleServerConfig:
# 客户端名称
clientName: ${ruoyi.name}
# 最小空闲连接数
connectionMinimumIdleSize: 32
# 连接池大小
connectionPoolSize: 64
# 连接空闲超时,单位:毫秒
idleConnectionTimeout: 10000
# 命令等待超时,单位:毫秒
timeout: 3000
# 发布和订阅连接池大小
subscriptionConnectionPoolSize: 50
--- # mail 邮件发送
mail:
enabled: false
host: smtp.163.com
port: 465
# 是否需要用户名密码验证
auth: true
# 发送方,遵循RFC-822标准
from: xxx@163.com
# 用户名(注意:如果使用foxmail邮箱,此处user为qq号)
user: xxx@163.com
# 密码(注意,某些邮箱需要为SMTP服务单独设置密码,详情查看相关帮助)
pass: xxxxxxxxxx
# 使用 STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展。
starttlsEnable: true
# 使用SSL安全连接
sslEnable: true
# SMTP超时时长,单位毫秒,缺省值不超时
timeout: 0
# Socket连接超时值,单位毫秒,缺省值不超时
connectionTimeout: 0
--- # sms 短信 支持 阿里云 腾讯云 云片 等等各式各样的短信服务商
# https://wind.kim/doc/start 文档地址 各个厂商可同时使用
sms:
# 阿里云 dysmsapi.aliyuncs.com
alibaba:
#请求地址 默认为 dysmsapi.aliyuncs.com 如无特殊改变可以不用设置
requestUrl: dysmsapi.aliyuncs.com
#阿里云的accessKey
accessKeyId: xxxxxxx
#阿里云的accessKeySecret
accessKeySecret: xxxxxxx
#短信签名
signature: 测试
tencent:
#请求地址默认为 sms.tencentcloudapi.com 如无特殊改变可不用设置
requestUrl: sms.tencentcloudapi.com
#腾讯云的accessKey
accessKeyId: xxxxxxx
#腾讯云的accessKeySecret
accessKeySecret: xxxxxxx
#短信签名
signature: 测试
#短信sdkAppId
sdkAppId: appid
#地域信息默认为 ap-guangzhou 如无特殊改变可不用设置
territory: ap-guangzhou
@@ -0,0 +1,268 @@
# 项目相关配置
ruoyi:
# 名称
name: RuoYi-Vue-Plus
# 版本
version: ${ruoyi-vue-plus.version}
# 版权年份
copyrightYear: 2023
# 缓存懒加载
cacheLazy: false
captcha:
# 页面 <参数设置> 可开启关闭 验证码校验
# 验证码类型 math 数组计算 char 字符验证
type: MATH
# line 线段干扰 circle 圆圈干扰 shear 扭曲干扰
category: CIRCLE
# 数字验证码位数
numberLength: 1
# 字符验证码长度
charLength: 4
# 开发环境配置
server:
# 服务器的HTTP端口,默认为8080
port: 7796
servlet:
# 应用的访问路径
context-path: /
# undertow 配置
undertow:
# HTTP post内容的最大大小。当值为-1时,默认值为大小是无限的
max-http-post-size: -1
# 以下的配置会影响buffer,这些buffer会用于服务器连接的IO操作,有点类似netty的池化内存管理
# 每块buffer的空间大小,越小的空间被利用越充分
buffer-size: 512
# 是否分配的直接内存
direct-buffers: true
threads:
# 设置IO线程数, 它主要执行非阻塞的任务,它们会负责多个连接, 默认设置每个CPU核心一个线程
io: 8
# 阻塞任务线程池, 当执行类似servlet请求阻塞操作, undertow会从这个线程池中取得线程,它的值设置取决于系统的负载
worker: 256
# 日志配置
logging:
level:
com.ruoyi: @logging.level@
org.springframework: warn
config: classpath:logback-plus.xml
# 用户配置
user:
password:
# 密码最大错误次数
maxRetryCount: 5
# 密码锁定时间(默认10分钟)
lockTime: 10
# Spring配置
spring:
application:
name: ${ruoyi.name}
# 资源信息
messages:
# 国际化资源文件路径
basename: i18n/messages
profiles:
active: @profiles.active@
# 文件上传
servlet:
multipart:
# 单个文件大小
max-file-size: 10MB
# 设置总上传的文件大小
max-request-size: 20MB
# 服务模块
devtools:
restart:
# 热部署开关
enabled: true
mvc:
format:
date-time: yyyy-MM-dd HH:mm:ss
jackson:
# 日期格式化
date-format: yyyy-MM-dd HH:mm:ss
serialization:
# 格式化输出
indent_output: false
# 忽略无法转换的对象
fail_on_empty_beans: false
deserialization:
# 允许对象忽略json中不存在的属性
fail_on_unknown_properties: false
# Sa-Token配置
sa-token:
# token名称 (同时也是cookie名称)
token-name: Authorization
# token有效期 设为一天 (必定过期) 单位: 秒
timeout: 86400
# 多端不同 token 有效期 可查看 LoginHelper.loginByDevice 方法自定义
# token最低活跃时间 (指定时间无操作就过期) 单位: 秒
active-timeout: 1800
# 允许动态设置 token 有效期
dynamic-active-timeout: true
# 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录)
is-concurrent: true
# 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token)
is-share: false
# 是否尝试从header里读取token
is-read-header: true
# 是否尝试从cookie里读取token
is-read-cookie: false
# token前缀
token-prefix: "Bearer"
# jwt秘钥
jwt-secret-key: abcdefghijklmnopqrstuvwxyz
# security配置
security:
# 排除路径
excludes:
# 静态资源
- /*.html
- /**/*.html
- /**/*.css
- /**/*.js
# 公共路径
- /favicon.ico
- /error
# swagger 文档配置
- /*/api-docs
- /*/api-docs/**
# actuator 监控配置
- /actuator
- /actuator/**
# MyBatisPlus配置
# https://baomidou.com/config/
mybatis-plus:
# 不支持多包, 如有需要可在注解配置 或 提升扫包等级
# 例如 com.**.**.mapper
mapperPackage: com.ruoyi.**.mapper
# 对应的 XML 文件位置
mapperLocations: classpath*:mapper/**/*Mapper.xml
# 实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.ruoyi.**.domain
# 启动时是否检查 MyBatis XML 文件的存在,默认不检查
checkConfigLocation: false
configuration:
# 自动驼峰命名规则(camel case)映射
mapUnderscoreToCamelCase: true
# MyBatis 自动映射策略
# NONE:不启用 PARTIAL:只对非嵌套 resultMap 自动映射 FULL:对所有 resultMap 自动映射
autoMappingBehavior: PARTIAL
# MyBatis 自动映射时未知列或未知属性处理策
# NONE:不做处理 WARNING:打印相关警告 FAILING:抛出异常和详细信息
autoMappingUnknownColumnBehavior: NONE
# 更详细的日志输出 会有性能损耗 org.apache.ibatis.logging.stdout.StdOutImpl
# 关闭日志记录 (可单纯使用 p6spy 分析) org.apache.ibatis.logging.nologging.NoLoggingImpl
# 默认日志输出 org.apache.ibatis.logging.slf4j.Slf4jImpl
logImpl: org.apache.ibatis.logging.nologging.NoLoggingImpl
global-config:
# 是否打印 Logo banner
banner: true
dbConfig:
# 主键类型
# AUTO 自增 NONE 空 INPUT 用户输入 ASSIGN_ID 雪花 ASSIGN_UUID 唯一 UUID
idType: ASSIGN_ID
# 逻辑已删除值
logicDeleteValue: 2
# 逻辑未删除值
logicNotDeleteValue: 0
# 字段验证策略之 insert,在 insert 的时候的字段验证策略
# IGNORED 忽略 NOT_NULL 非NULL NOT_EMPTY 非空 DEFAULT 默认 NEVER 不加入 SQL
insertStrategy: NOT_NULL
# 字段验证策略之 update,在 update 的时候的字段验证策略
updateStrategy: NOT_NULL
# 字段验证策略之 select,在 select 的时候的字段验证策略既 wrapper 根据内部 entity 生成的 where 条件
where-strategy: NOT_NULL
# 数据加密
mybatis-encryptor:
# 是否开启加密
enable: false
# 默认加密算法
algorithm: BASE64
# 编码方式 BASE64/HEX。默认BASE64
encode: BASE64
# 安全秘钥 对称算法的秘钥 如:AES,SM4
password:
# 公私钥 非对称算法的公私钥 如:SM2,RSA
publicKey:
privateKey:
springdoc:
api-docs:
# 是否开启接口文档
enabled: true
# swagger-ui:
# # 持久化认证数据
# persistAuthorization: true
info:
# 标题
title: '标题:${ruoyi.name}后台管理系统_接口文档'
# 描述
description: '描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...'
# 版本
version: '版本号: ${ruoyi-vue-plus.version}'
# 作者信息
contact:
name: Lion Li
email: crazylionli@163.com
url: https://gitee.com/dromara/RuoYi-Vue-Plus
components:
# 鉴权方式配置
security-schemes:
apiKey:
type: APIKEY
in: HEADER
name: ${sa-token.token-name}
#这里定义了两个分组,可定义多个,也可以不定义
group-configs:
- group: 1.演示模块
packages-to-scan: com.ruoyi.demo
- group: 2.系统模块
packages-to-scan: com.ruoyi.web
- group: 3.代码生成模块
packages-to-scan: com.ruoyi.generator
# 防止XSS攻击
xss:
# 过滤开关
enabled: true
# 排除链接(多个用逗号分隔)
excludes: /system/notice
# 匹配链接
urlPatterns: /system/*,/monitor/*,/tool/*
# 全局线程池相关配置
thread-pool:
# 是否开启线程池
enabled: false
# 队列最大长度
queueCapacity: 128
# 线程池维护线程所允许的空闲时间
keepAliveSeconds: 300
--- # 分布式锁 lock4j 全局配置
lock4j:
# 获取分布式锁超时时间,默认为 3000 毫秒
acquire-timeout: 3000
# 分布式锁的超时时间,默认为 30 秒
expire: 30000
--- # Actuator 监控端点的配置项
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: ALWAYS
logfile:
external-file: ./logs/sys-console.log
@@ -0,0 +1,8 @@
Application Version: ${ruoyi-vue-plus.version}
Spring Boot Version: ${spring-boot.version}
__________ _____.___.__ ____ ____ __________.__
\______ \__ __ ____\__ | |__| \ \ / /_ __ ____ \______ \ | __ __ ______
| _/ | \/ _ \/ | | | ______ \ Y / | \_/ __ \ ______ | ___/ | | | \/ ___/
| | \ | ( <_> )____ | | /_____/ \ /| | /\ ___/ /_____/ | | | |_| | /\___ \
|____|_ /____/ \____// ______|__| \___/ |____/ \___ > |____| |____/____//____ >
\/ \/ \/ \/
@@ -0,0 +1,49 @@
#错误消息
not.null=* 必须填写
user.jcaptcha.error=验证码错误
user.jcaptcha.expire=验证码已失效
user.not.exists=对不起, 您的账号:{0} 不存在.
user.password.not.match=用户不存在/密码错误
user.password.retry.limit.count=密码输入错误{0}次
user.password.retry.limit.exceed=密码输入错误{0}次,帐户锁定{1}分钟
user.password.delete=对不起,您的账号:{0} 已被删除
user.blocked=对不起,您的账号:{0} 已禁用,请联系管理员
role.blocked=角色已封禁,请联系管理员
user.logout.success=退出成功
length.not.valid=长度必须在{min}到{max}个字符之间
user.username.not.blank=用户名不能为空
user.username.not.valid=* 2到20个汉字、字母、数字或下划线组成,且必须以非数字开头
user.username.length.valid=账户长度必须在{min}到{max}个字符之间
user.password.not.blank=用户密码不能为空
user.password.length.valid=用户密码长度必须在{min}到{max}个字符之间
user.password.not.valid=* 5-50个字符
user.email.not.valid=邮箱格式错误
user.email.not.blank=邮箱不能为空
user.phonenumber.not.blank=用户手机号不能为空
user.mobile.phone.number.not.valid=手机号格式错误
user.login.success=登录成功
user.register.success=注册成功
user.register.save.error=保存用户 {0} 失败,注册账号已存在
user.register.error=注册失败,请联系系统管理人员
user.notfound=请重新登录
user.forcelogout=管理员强制退出,请重新登录
user.unknown.error=未知错误,请重新登录
##文件上传消息
upload.exceed.maxSize=上传的文件大小超出限制的文件大小!<br/>允许的文件最大大小是:{0}MB!
upload.filename.exceed.length=上传的文件名最长{0}个字符
##权限
no.permission=您没有数据的权限,请联系管理员添加权限 [{0}]
no.create.permission=您没有创建数据的权限,请联系管理员添加权限 [{0}]
no.update.permission=您没有修改数据的权限,请联系管理员添加权限 [{0}]
no.delete.permission=您没有删除数据的权限,请联系管理员添加权限 [{0}]
no.export.permission=您没有导出数据的权限,请联系管理员添加权限 [{0}]
no.view.permission=您没有查看数据的权限,请联系管理员添加权限 [{0}]
repeat.submit.message=不允许重复提交,请稍候再试
rate.limiter.message=访问过于频繁,请稍候再试
sms.code.not.blank=短信验证码不能为空
sms.code.retry.limit.count=短信验证码输入错误{0}次
sms.code.retry.limit.exceed=短信验证码输入错误{0}次,帐户锁定{1}分钟
email.code.not.blank=邮箱验证码不能为空
email.code.retry.limit.count=邮箱验证码输入错误{0}次
email.code.retry.limit.exceed=邮箱验证码输入错误{0}次,帐户锁定{1}分钟
xcx.code.not.blank=小程序code不能为空
@@ -0,0 +1,49 @@
#错误消息
not.null=* Required fill in
user.jcaptcha.error=Captcha error
user.jcaptcha.expire=Captcha invalid
user.not.exists=Sorry, your account: {0} does not exist
user.password.not.match=User does not exist/Password error
user.password.retry.limit.count=Password input error {0} times
user.password.retry.limit.exceed=Password input error {0} times, account locked for {1} minutes
user.password.delete=Sorry, your account:{0} has been deleted
user.blocked=Sorry, your account: {0} has been disabled. Please contact the administrator
role.blocked=Role disabled,please contact administrators
user.logout.success=Exit successful
length.not.valid=The length must be between {min} and {max} characters
user.username.not.blank=Username cannot be blank
user.username.not.valid=* 2 to 20 chinese characters, letters, numbers or underscores, and must start with a non number
user.username.length.valid=Account length must be between {min} and {max} characters
user.password.not.blank=Password cannot be empty
user.password.length.valid=Password length must be between {min} and {max} characters
user.password.not.valid=* 5-50 characters
user.email.not.valid=Mailbox format error
user.email.not.blank=Mailbox cannot be blank
user.phonenumber.not.blank=Phone number cannot be blank
user.mobile.phone.number.not.valid=Phone number format error
user.login.success=Login successful
user.register.success=Register successful
user.register.save.error=Failed to save user {0}, The registered account already exists
user.register.error=Register failed, please contact system administrator
user.notfound=Please login again
user.forcelogout=The administrator is forced to exit,please login again
user.unknown.error=Unknown error, please login again
##文件上传消息
upload.exceed.maxSize=The uploaded file size exceeds the limit file size!<br/>the maximum allowed file size is:{0}MB!
upload.filename.exceed.length=The maximum length of uploaded file name is {0} characters
##权限
no.permission=You do not have permission to the data,please contact your administrator to add permissions [{0}]
no.create.permission=You do not have permission to create data,please contact your administrator to add permissions [{0}]
no.update.permission=You do not have permission to modify data,please contact your administrator to add permissions [{0}]
no.delete.permission=You do not have permission to delete data,please contact your administrator to add permissions [{0}]
no.export.permission=You do not have permission to export data,please contact your administrator to add permissions [{0}]
no.view.permission=You do not have permission to view data,please contact your administrator to add permissions [{0}]
repeat.submit.message=Repeat submit is not allowed, please try again later
rate.limiter.message=Visit too frequently, please try again later
sms.code.not.blank=Sms code cannot be blank
sms.code.retry.limit.count=Sms code input error {0} times
sms.code.retry.limit.exceed=Sms code input error {0} times, account locked for {1} minutes
email.code.not.blank=Email code cannot be blank
email.code.retry.limit.count=Email code input error {0} times
email.code.retry.limit.exceed=Email code input error {0} times, account locked for {1} minutes
xcx.code.not.blank=Mini program code cannot be blank
@@ -0,0 +1,49 @@
#错误消息
not.null=* 必须填写
user.jcaptcha.error=验证码错误
user.jcaptcha.expire=验证码已失效
user.not.exists=对不起, 您的账号:{0} 不存在.
user.password.not.match=用户不存在/密码错误
user.password.retry.limit.count=密码输入错误{0}次
user.password.retry.limit.exceed=密码输入错误{0}次,帐户锁定{1}分钟
user.password.delete=对不起,您的账号:{0} 已被删除
user.blocked=对不起,您的账号:{0} 已禁用,请联系管理员
role.blocked=角色已封禁,请联系管理员
user.logout.success=退出成功
length.not.valid=长度必须在{min}到{max}个字符之间
user.username.not.blank=用户名不能为空
user.username.not.valid=* 2到20个汉字、字母、数字或下划线组成,且必须以非数字开头
user.username.length.valid=账户长度必须在{min}到{max}个字符之间
user.password.not.blank=用户密码不能为空
user.password.length.valid=用户密码长度必须在{min}到{max}个字符之间
user.password.not.valid=* 5-50个字符
user.email.not.valid=邮箱格式错误
user.email.not.blank=邮箱不能为空
user.phonenumber.not.blank=用户手机号不能为空
user.mobile.phone.number.not.valid=手机号格式错误
user.login.success=登录成功
user.register.success=注册成功
user.register.save.error=保存用户 {0} 失败,注册账号已存在
user.register.error=注册失败,请联系系统管理人员
user.notfound=请重新登录
user.forcelogout=管理员强制退出,请重新登录
user.unknown.error=未知错误,请重新登录
##文件上传消息
upload.exceed.maxSize=上传的文件大小超出限制的文件大小!<br/>允许的文件最大大小是:{0}MB!
upload.filename.exceed.length=上传的文件名最长{0}个字符
##权限
no.permission=您没有数据的权限,请联系管理员添加权限 [{0}]
no.create.permission=您没有创建数据的权限,请联系管理员添加权限 [{0}]
no.update.permission=您没有修改数据的权限,请联系管理员添加权限 [{0}]
no.delete.permission=您没有删除数据的权限,请联系管理员添加权限 [{0}]
no.export.permission=您没有导出数据的权限,请联系管理员添加权限 [{0}]
no.view.permission=您没有查看数据的权限,请联系管理员添加权限 [{0}]
repeat.submit.message=不允许重复提交,请稍候再试
rate.limiter.message=访问过于频繁,请稍候再试
sms.code.not.blank=短信验证码不能为空
sms.code.retry.limit.count=短信验证码输入错误{0}次
sms.code.retry.limit.exceed=短信验证码输入错误{0}次,帐户锁定{1}分钟
email.code.not.blank=邮箱验证码不能为空
email.code.retry.limit.count=邮箱验证码输入错误{0}次
email.code.retry.limit.exceed=邮箱验证码输入错误{0}次,帐户锁定{1}分钟
xcx.code.not.blank=小程序code不能为空
@@ -0,0 +1,129 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="log.path" value="./logs"/>
<property name="console.log.pattern"
value="%red(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}%n) - %msg%n"/>
<property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"/>
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${console.log.pattern}</pattern>
<charset>utf-8</charset>
</encoder>
</appender>
<!-- 控制台输出 -->
<appender name="file_console" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-console.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-console.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大 1天 -->
<maxHistory>1</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
<charset>utf-8</charset>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
</filter>
</appender>
<!-- 系统日志输出 -->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- info异步输出 -->
<appender name="async_info" class="ch.qos.logback.classic.AsyncAppender">
<!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
<discardingThreshold>0</discardingThreshold>
<!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
<queueSize>512</queueSize>
<!-- 添加附加的appender,最多只能添加一个 -->
<appender-ref ref="file_info"/>
</appender>
<!-- error异步输出 -->
<appender name="async_error" class="ch.qos.logback.classic.AsyncAppender">
<!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
<discardingThreshold>0</discardingThreshold>
<!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
<queueSize>512</queueSize>
<!-- 添加附加的appender,最多只能添加一个 -->
<appender-ref ref="file_error"/>
</appender>
<!-- 整合 skywalking 控制台输出 tid -->
<!-- <appender name="console" class="ch.qos.logback.core.ConsoleAppender">-->
<!-- <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">-->
<!-- <layout class="org.apache.skywalking.apm.toolkit.log.logback.v1.x.TraceIdPatternLogbackLayout">-->
<!-- <pattern>[%tid] ${console.log.pattern}</pattern>-->
<!-- </layout>-->
<!-- <charset>utf-8</charset>-->
<!-- </encoder>-->
<!-- </appender>-->
<!-- 整合 skywalking 推送采集日志 -->
<!-- <appender name="sky_log" class="org.apache.skywalking.apm.toolkit.log.logback.v1.x.log.GRPCLogClientAppender">-->
<!-- <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">-->
<!-- <layout class="org.apache.skywalking.apm.toolkit.log.logback.v1.x.TraceIdPatternLogbackLayout">-->
<!-- <pattern>[%tid] ${console.log.pattern}</pattern>-->
<!-- </layout>-->
<!-- <charset>utf-8</charset>-->
<!-- </encoder>-->
<!-- </appender>-->
<!--系统操作日志-->
<root level="info">
<appender-ref ref="console" />
<appender-ref ref="async_info" />
<appender-ref ref="async_error" />
<appender-ref ref="file_console" />
<!-- <appender-ref ref="sky_log"/>-->
</root>
</configuration>
@@ -0,0 +1,28 @@
# p6spy 性能分析插件配置文件
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
#deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# SQL语句打印时间格式
databaseDialectTimestampFormat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2
# 是否过滤 Log
filter=true
# 过滤 Log 时所排除的 sql 关键字,以逗号分隔
exclude=SELECT 1
@@ -0,0 +1,45 @@
package com.ruoyi.test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* 断言单元测试案例
*
* @author Lion Li
*/
@DisplayName("断言单元测试案例")
public class AssertUnitTest {
@DisplayName("测试 assertEquals 方法")
@Test
public void testAssertEquals() {
Assertions.assertEquals("666", new String("666"));
Assertions.assertNotEquals("666", new String("666"));
}
@DisplayName("测试 assertSame 方法")
@Test
public void testAssertSame() {
Object obj = new Object();
Object obj1 = obj;
Assertions.assertSame(obj, obj1);
Assertions.assertNotSame(obj, obj1);
}
@DisplayName("测试 assertTrue 方法")
@Test
public void testAssertTrue() {
Assertions.assertTrue(true);
Assertions.assertFalse(true);
}
@DisplayName("测试 assertNull 方法")
@Test
public void testAssertNull() {
Assertions.assertNull(null);
Assertions.assertNotNull(null);
}
}
@@ -0,0 +1,70 @@
package com.ruoyi.test;
import com.ruoyi.common.config.RuoYiConfig;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.concurrent.TimeUnit;
/**
* 单元测试案例
*
* @author Lion Li
*/
@SpringBootTest // 此注解只能在 springboot 主包下使用 需包含 main 方法与 yml 配置文件
@DisplayName("单元测试案例")
public class DemoUnitTest {
@Autowired
private RuoYiConfig ruoYiConfig;
@DisplayName("测试 @SpringBootTest @Test @DisplayName 注解")
@Test
public void testTest() {
System.out.println(ruoYiConfig);
}
@Disabled
@DisplayName("测试 @Disabled 注解")
@Test
public void testDisabled() {
System.out.println(ruoYiConfig);
}
@Timeout(value = 2L, unit = TimeUnit.SECONDS)
@DisplayName("测试 @Timeout 注解")
@Test
public void testTimeout() throws InterruptedException {
Thread.sleep(3000);
System.out.println(ruoYiConfig);
}
@DisplayName("测试 @RepeatedTest 注解")
@RepeatedTest(3)
public void testRepeatedTest() {
System.out.println(666);
}
@BeforeAll
public static void testBeforeAll() {
System.out.println("@BeforeAll ==================");
}
@BeforeEach
public void testBeforeEach() {
System.out.println("@BeforeEach ==================");
}
@AfterEach
public void testAfterEach() {
System.out.println("@AfterEach ==================");
}
@AfterAll
public static void testAfterAll() {
System.out.println("@AfterAll ==================");
}
}
@@ -0,0 +1,72 @@
package com.ruoyi.test;
import com.ruoyi.common.enums.UserType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* 带参数单元测试案例
*
* @author Lion Li
*/
@DisplayName("带参数单元测试案例")
public class ParamUnitTest {
@DisplayName("测试 @ValueSource 注解")
@ParameterizedTest
@ValueSource(strings = {"t1", "t2", "t3"})
public void testValueSource(String str) {
System.out.println(str);
}
@DisplayName("测试 @NullSource 注解")
@ParameterizedTest
@NullSource
public void testNullSource(String str) {
System.out.println(str);
}
@DisplayName("测试 @EnumSource 注解")
@ParameterizedTest
@EnumSource(UserType.class)
public void testEnumSource(UserType type) {
System.out.println(type.getUserType());
}
@DisplayName("测试 @MethodSource 注解")
@ParameterizedTest
@MethodSource("getParam")
public void testMethodSource(String str) {
System.out.println(str);
}
public static Stream<String> getParam() {
List<String> list = new ArrayList<>();
list.add("t1");
list.add("t2");
list.add("t3");
return list.stream();
}
@BeforeEach
public void testBeforeEach() {
System.out.println("@BeforeEach ==================");
}
@AfterEach
public void testAfterEach() {
System.out.println("@AfterEach ==================");
}
}
@@ -0,0 +1,54 @@
package com.ruoyi.test;
import org.junit.jupiter.api.*;
import org.springframework.boot.test.context.SpringBootTest;
/**
* 标签单元测试案例
*
* @author Lion Li
*/
@SpringBootTest
@DisplayName("标签单元测试案例")
public class TagUnitTest {
@Tag("dev")
@DisplayName("测试 @Tag dev")
@Test
public void testTagDev() {
System.out.println("dev");
}
@Tag("prod")
@DisplayName("测试 @Tag prod")
@Test
public void testTagProd() {
System.out.println("prod");
}
@Tag("local")
@DisplayName("测试 @Tag local")
@Test
public void testTagLocal() {
System.out.println("local");
}
@Tag("exclude")
@DisplayName("测试 @Tag exclude")
@Test
public void testTagExclude() {
System.out.println("exclude");
}
@BeforeEach
public void testBeforeEach() {
System.out.println("@BeforeEach ==================");
}
@AfterEach
public void testAfterEach() {
System.out.println("@AfterEach ==================");
}
}
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ruoyi-vue-plus</artifactId>
<groupId>com.ruoyi</groupId>
<version>4.8.2</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ruoyi-browser</artifactId>
<dependencies>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
</dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-system</artifactId>
</dependency>
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,52 @@
package com.ruoyi.browser.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.ruoyi.common.core.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("fp_fingerprint_config")
public class BrowserFingerprint extends BaseEntity {
@TableId(value = "fingerprint_id")
private Long fingerprintId;
private Long userId;
private Long profileId;
private String browserFamily;
private String browserVersion;
private String userAgent;
private String geoMode;
private String locale;
private String timezone;
private String geoCountry;
private Integer screenWidth;
private Integer screenHeight;
private String webRtcPolicy;
private String canvasPolicy;
private String webglPolicy;
private String audioPolicy;
private String fontPolicy;
private String cookieConfig;
private String encryptedPayload;
}
@@ -0,0 +1,42 @@
package com.ruoyi.browser.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.ruoyi.common.core.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("fp_browser_kernel_package")
public class BrowserKernelPackage extends BaseEntity {
@TableId(value = "kernel_id")
private Long kernelId;
private String browserEngine;
private String browserVersion;
private String fullVersion;
private String osType;
private String archType;
private String packageUrl;
private String packageSha256;
private String archiveRootDir;
private String executablePath;
private Integer sortOrder;
private String isDefault;
private String status;
private String remark;
}
@@ -0,0 +1,41 @@
package com.ruoyi.browser.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.core.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("fp_member_user")
public class BrowserMemberUser extends BaseEntity {
@TableId(value = "member_id")
private Long memberId;
private String username;
private String password;
private String nickName;
private String email;
private String phonenumber;
private String status;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date expireTime;
private String lastLoginIp;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date lastLoginTime;
private String remark;
}
@@ -0,0 +1,28 @@
package com.ruoyi.browser.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.ruoyi.common.core.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("fp_platform")
public class BrowserPlatform extends BaseEntity {
@TableId(value = "platform_id")
private Long platformId;
private String platformName;
private String websiteUrl;
private String iconFileName;
private Integer sortOrder;
private String status;
private String remark;
}
@@ -0,0 +1,77 @@
package com.ruoyi.browser.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.ruoyi.common.core.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("fp_profile")
public class BrowserProfile extends BaseEntity {
@TableId(value = "profile_id")
private Long profileId;
private Long userId;
private String profileName;
private Long groupId;
private String groupName;
private String tags;
private Long platformId;
private String platform;
private String customWebsiteUrl;
private String browserEngine;
private String browserChannel;
private String browserVersion;
private String browserOsType;
private String browserArchType;
private String proxyName;
private Long proxyId;
private String launchDiagnostics;
private Long fingerprintId;
@TableField(exist = false)
private String proxyType;
@TableField(exist = false)
private String proxyHost;
@TableField(exist = false)
private Integer proxyPort;
@TableField(exist = false)
private String fingerprintPayload;
private String localProfileKey;
private String syncStatus;
private String purityStatus;
private Date lastLaunchTime;
private String status;
private String remark;
}
@@ -0,0 +1,28 @@
package com.ruoyi.browser.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.ruoyi.common.core.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("fp_profile_group")
public class BrowserProfileGroup extends BaseEntity {
@TableId(value = "group_id")
private Long groupId;
private Long userId;
private String groupName;
private String isDefault;
private String groupColor;
private Integer sortOrder;
private String remark;
}
@@ -0,0 +1,38 @@
package com.ruoyi.browser.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.ruoyi.common.core.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("fp_proxy")
public class BrowserProxy extends BaseEntity {
@TableId(value = "proxy_id")
private Long proxyId;
private Long userId;
private String proxyName;
private String proxyType;
private String host;
private Integer port;
private String geoCountry;
private String geoRegion;
private String geoCity;
private String username;
private String passwordEncrypted;
private String status;
}
@@ -0,0 +1,36 @@
package com.ruoyi.browser.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.ruoyi.common.core.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("fp_runtime_record")
public class BrowserRuntimeRecord extends BaseEntity {
@TableId(value = "runtime_id")
private Long runtimeId;
private Long userId;
private Long profileId;
private Integer pid;
private Integer port;
private String status;
private Date startedAt;
private Date stoppedAt;
private String runtimePath;
private String profileDir;
}
@@ -0,0 +1,44 @@
package com.ruoyi.browser.domain.bo;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Data
@EqualsAndHashCode(callSuper = true)
public class BrowserFingerprintBo extends BaseEntity {
@NotNull(message = "主键不能为空", groups = {EditGroup.class})
private Long fingerprintId;
private Long userId;
private Long profileId;
@NotBlank(message = "浏览器家族不能为空", groups = {AddGroup.class, EditGroup.class})
private String browserFamily;
private String browserVersion;
private String userAgent;
private String geoMode;
private String locale;
private String timezone;
private String geoCountry;
private Integer screenWidth;
private Integer screenHeight;
private String webRtcPolicy;
private String canvasPolicy;
private String webglPolicy;
private String audioPolicy;
private String fontPolicy;
private String cookieConfig;
private String encryptedPayload;
}
@@ -0,0 +1,50 @@
package com.ruoyi.browser.domain.bo;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Data
@EqualsAndHashCode(callSuper = true)
public class BrowserKernelPackageBo extends BaseEntity {
@NotNull(message = "主键不能为空", groups = {EditGroup.class})
private Long kernelId;
@NotBlank(message = "浏览器内核不能为空", groups = {AddGroup.class, EditGroup.class})
private String browserEngine;
@NotBlank(message = "浏览器版本不能为空", groups = {AddGroup.class, EditGroup.class})
private String browserVersion;
@NotBlank(message = "完整版本号不能为空", groups = {AddGroup.class, EditGroup.class})
private String fullVersion;
@NotBlank(message = "系统类型不能为空", groups = {AddGroup.class, EditGroup.class})
private String osType;
@NotBlank(message = "架构类型不能为空", groups = {AddGroup.class, EditGroup.class})
private String archType;
@NotBlank(message = "压缩包地址不能为空", groups = {AddGroup.class, EditGroup.class})
private String packageUrl;
private String packageSha256;
private String archiveRootDir;
@NotBlank(message = "可执行文件路径不能为空", groups = {AddGroup.class, EditGroup.class})
private String executablePath;
private Integer sortOrder;
private String isDefault;
private String status;
}
@@ -0,0 +1,26 @@
package com.ruoyi.browser.domain.bo;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
@Data
public class BrowserMemberRegisterBo {
@NotBlank(message = "会员账号不能为空")
@Length(min = 2, max = 20, message = "会员账号长度必须介于 2 和 20 之间")
private String username;
@NotBlank(message = "会员密码不能为空")
@Length(min = 5, max = 20, message = "会员密码长度必须介于 5 和 20 之间")
private String password;
private String confirmPassword;
private String nickName;
private String email;
private String phonenumber;
}
@@ -0,0 +1,43 @@
package com.ruoyi.browser.domain.bo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
@Data
@EqualsAndHashCode(callSuper = true)
public class BrowserMemberUserBo extends BaseEntity {
@NotNull(message = "会员ID不能为空", groups = {EditGroup.class})
private Long memberId;
@NotBlank(message = "会员账号不能为空", groups = {AddGroup.class, EditGroup.class})
@Length(min = 2, max = 20, message = "会员账号长度必须介于 2 和 20 之间", groups = {AddGroup.class, EditGroup.class, QueryGroup.class})
private String username;
@NotBlank(message = "会员密码不能为空", groups = {AddGroup.class})
@Length(min = 5, max = 20, message = "会员密码长度必须介于 5 和 20 之间", groups = {AddGroup.class})
private String password;
private String nickName;
private String email;
private String phonenumber;
private String status;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date expireTime;
private String remark;
}
@@ -0,0 +1,32 @@
package com.ruoyi.browser.domain.bo;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Data
@EqualsAndHashCode(callSuper = true)
public class BrowserPlatformBo extends BaseEntity {
@NotNull(message = "主键不能为空", groups = {EditGroup.class})
private Long platformId;
@NotBlank(message = "平台名称不能为空", groups = {AddGroup.class, EditGroup.class})
private String platformName;
@NotBlank(message = "网站地址不能为空", groups = {AddGroup.class, EditGroup.class})
private String websiteUrl;
private String iconFileName;
private Integer sortOrder;
private String status;
private String remark;
}
@@ -0,0 +1,77 @@
package com.ruoyi.browser.domain.bo;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Data
@EqualsAndHashCode(callSuper = true)
public class BrowserProfileBo extends BaseEntity {
@NotNull(message = "主键不能为空", groups = {EditGroup.class})
private Long profileId;
private Long userId;
private String memberUsername;
@NotBlank(message = "环境名称不能为空", groups = {AddGroup.class, EditGroup.class})
@Size(min = 2, max = 64, message = "环境名称长度必须介于{min}和{max}之间")
private String profileName;
private Long groupId;
private String groupName;
private String tags;
private Long platformId;
private String platform;
private String customWebsiteUrl;
@NotBlank(message = "浏览器内核不能为空", groups = {AddGroup.class, EditGroup.class})
private String browserEngine;
private String browserChannel;
private String browserVersion;
private String browserOsType;
private String browserArchType;
private String proxyName;
private Long proxyId;
private String launchDiagnostics;
private Long fingerprintId;
private String proxyType;
private String proxyHost;
private Integer proxyPort;
private String fingerprintPayload;
private String localProfileKey;
private String syncStatus;
private String purityStatus;
private String status;
private String remark;
}
@@ -0,0 +1,34 @@
package com.ruoyi.browser.domain.bo;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Data
@EqualsAndHashCode(callSuper = true)
public class BrowserProfileGroupBo extends BaseEntity {
@NotNull(message = "分组主键不能为空", groups = {EditGroup.class})
private Long groupId;
private Long userId;
@NotBlank(message = "分组名称不能为空", groups = {AddGroup.class, EditGroup.class})
@Size(min = 1, max = 64, message = "分组名称长度必须介于{min}和{max}之间", groups = {AddGroup.class, EditGroup.class, QueryGroup.class})
private String groupName;
private String isDefault;
private String groupColor;
private Integer sortOrder;
private String remark;
}
@@ -0,0 +1,17 @@
package com.ruoyi.browser.domain.bo;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
@Data
public class BrowserProfileGroupMoveBo {
@NotNull(message = "目标分组不能为空")
private Long targetGroupId;
@NotEmpty(message = "环境列表不能为空")
private List<Long> profileIds;
}
@@ -0,0 +1,18 @@
package com.ruoyi.browser.domain.bo;
import lombok.Data;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
@Data
public class BrowserProfileQuickSaveBo {
@Valid
@NotNull(message = "环境信息不能为空")
private BrowserProfileBo profile;
@Valid
@NotNull(message = "指纹信息不能为空")
private BrowserFingerprintBo fingerprint;
}
@@ -0,0 +1,42 @@
package com.ruoyi.browser.domain.bo;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Data
@EqualsAndHashCode(callSuper = true)
public class BrowserProxyBo extends BaseEntity {
@NotNull(message = "主键不能为空", groups = {EditGroup.class})
private Long proxyId;
private Long userId;
@NotBlank(message = "代理名称不能为空", groups = {AddGroup.class, EditGroup.class})
private String proxyName;
@NotBlank(message = "代理类型不能为空", groups = {AddGroup.class, EditGroup.class})
private String proxyType;
private String host;
private Integer port;
private String geoCountry;
private String geoRegion;
private String geoCity;
private String username;
private String passwordEncrypted;
private String status;
}
@@ -0,0 +1,30 @@
package com.ruoyi.browser.domain.vo;
import lombok.Data;
import java.util.Date;
@Data
public class BrowserFingerprintVo {
private Long fingerprintId;
private Long userId;
private Long profileId;
private String browserFamily;
private String browserVersion;
private String userAgent;
private String geoMode;
private String locale;
private String timezone;
private String geoCountry;
private Integer screenWidth;
private Integer screenHeight;
private String webRtcPolicy;
private String canvasPolicy;
private String webglPolicy;
private String audioPolicy;
private String fontPolicy;
private String cookieConfig;
private String encryptedPayload;
private String createBy;
private Date createTime;
}
@@ -0,0 +1,41 @@
package com.ruoyi.browser.domain.vo;
import lombok.Data;
import java.util.Date;
@Data
public class BrowserKernelPackageVo {
private Long kernelId;
private String browserEngine;
private String browserVersion;
private String fullVersion;
private String osType;
private String archType;
private String packageUrl;
private String packageSha256;
private String archiveRootDir;
private String executablePath;
private Integer sortOrder;
private String isDefault;
private String status;
private String remark;
private String createBy;
private Date createTime;
}
@@ -0,0 +1,37 @@
package com.ruoyi.browser.domain.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
public class BrowserMemberUserVo {
private Long memberId;
private String username;
private String nickName;
private String email;
private String phonenumber;
private String status;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date expireTime;
private String lastLoginIp;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date lastLoginTime;
private String createBy;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
private String remark;
}
@@ -0,0 +1,29 @@
package com.ruoyi.browser.domain.vo;
import lombok.Data;
import java.util.Date;
@Data
public class BrowserPlatformVo {
private Long platformId;
private String platformName;
private String websiteUrl;
private String iconFileName;
private String iconUrl;
private Integer sortOrder;
private String status;
private String remark;
private String createBy;
private Date createTime;
}
@@ -0,0 +1,29 @@
package com.ruoyi.browser.domain.vo;
import lombok.Data;
import java.util.Date;
@Data
public class BrowserProfileGroupVo {
private Long groupId;
private Long userId;
private String groupName;
private String isDefault;
private String groupColor;
private Integer sortOrder;
private String remark;
private Long profileCount;
private String createBy;
private Date createTime;
}
@@ -0,0 +1,13 @@
package com.ruoyi.browser.domain.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class BrowserProfileQuickSaveVo {
private Long profileId;
private Long fingerprintId;
}
@@ -0,0 +1,81 @@
package com.ruoyi.browser.domain.vo;
import lombok.Data;
import java.util.Date;
@Data
public class BrowserProfileVo {
private Long profileId;
private Long userId;
private String memberUsername;
private String memberNickName;
private String profileName;
private Long groupId;
private String groupName;
private String tags;
private Long platformId;
private String platform;
private String customWebsiteUrl;
private String platformWebsiteUrl;
private String platformIconFileName;
private String platformIconUrl;
private String resolvedWebsiteUrl;
private String browserEngine;
private String browserChannel;
private String browserVersion;
private String browserOsType;
private String browserArchType;
private String proxyName;
private Long proxyId;
private String launchDiagnostics;
private Long fingerprintId;
private String proxyType;
private String proxyHost;
private Integer proxyPort;
private String fingerprintPayload;
private String localProfileKey;
private String syncStatus;
private String purityStatus;
private Date lastLaunchTime;
private String status;
private String remark;
private String createBy;
private Date createTime;
}
@@ -0,0 +1,22 @@
package com.ruoyi.browser.domain.vo;
import lombok.Data;
import java.util.Date;
@Data
public class BrowserProxyVo {
private Long proxyId;
private Long userId;
private String proxyName;
private String proxyType;
private String host;
private Integer port;
private String geoCountry;
private String geoRegion;
private String geoCity;
private String username;
private String status;
private String createBy;
private Date createTime;
}
@@ -0,0 +1,24 @@
package com.ruoyi.browser.domain.vo;
import lombok.Data;
import java.util.List;
import java.util.Map;
@Data
public class BrowserRuntimeVo {
private String profileId;
private String browserEngine;
private String runtimePath;
private String profileDir;
private String startUrl;
private Boolean headless;
private List<String> browserArgs;
private Map<String, Object> proxy;
private Map<String, Object> fingerprint;
private Map<String, Object> kernelPackage;
private String proxyType;
private String proxyHost;
private Integer proxyPort;
}
@@ -0,0 +1,8 @@
package com.ruoyi.browser.mapper;
import com.ruoyi.browser.domain.BrowserFingerprint;
import com.ruoyi.browser.domain.vo.BrowserFingerprintVo;
import com.ruoyi.common.core.mapper.BaseMapperPlus;
public interface BrowserFingerprintMapper extends BaseMapperPlus<BrowserFingerprintMapper, BrowserFingerprint, BrowserFingerprintVo> {
}
@@ -0,0 +1,8 @@
package com.ruoyi.browser.mapper;
import com.ruoyi.browser.domain.BrowserKernelPackage;
import com.ruoyi.browser.domain.vo.BrowserKernelPackageVo;
import com.ruoyi.common.core.mapper.BaseMapperPlus;
public interface BrowserKernelPackageMapper extends BaseMapperPlus<BrowserKernelPackageMapper, BrowserKernelPackage, BrowserKernelPackageVo> {
}
@@ -0,0 +1,8 @@
package com.ruoyi.browser.mapper;
import com.ruoyi.browser.domain.BrowserMemberUser;
import com.ruoyi.browser.domain.vo.BrowserMemberUserVo;
import com.ruoyi.common.core.mapper.BaseMapperPlus;
public interface BrowserMemberUserMapper extends BaseMapperPlus<BrowserMemberUserMapper, BrowserMemberUser, BrowserMemberUserVo> {
}
@@ -0,0 +1,8 @@
package com.ruoyi.browser.mapper;
import com.ruoyi.browser.domain.BrowserPlatform;
import com.ruoyi.browser.domain.vo.BrowserPlatformVo;
import com.ruoyi.common.core.mapper.BaseMapperPlus;
public interface BrowserPlatformMapper extends BaseMapperPlus<BrowserPlatformMapper, BrowserPlatform, BrowserPlatformVo> {
}
@@ -0,0 +1,8 @@
package com.ruoyi.browser.mapper;
import com.ruoyi.browser.domain.BrowserProfileGroup;
import com.ruoyi.browser.domain.vo.BrowserProfileGroupVo;
import com.ruoyi.common.core.mapper.BaseMapperPlus;
public interface BrowserProfileGroupMapper extends BaseMapperPlus<BrowserProfileGroupMapper, BrowserProfileGroup, BrowserProfileGroupVo> {
}
@@ -0,0 +1,8 @@
package com.ruoyi.browser.mapper;
import com.ruoyi.browser.domain.BrowserProfile;
import com.ruoyi.browser.domain.vo.BrowserProfileVo;
import com.ruoyi.common.core.mapper.BaseMapperPlus;
public interface BrowserProfileMapper extends BaseMapperPlus<BrowserProfileMapper, BrowserProfile, BrowserProfileVo> {
}
@@ -0,0 +1,8 @@
package com.ruoyi.browser.mapper;
import com.ruoyi.browser.domain.BrowserProxy;
import com.ruoyi.browser.domain.vo.BrowserProxyVo;
import com.ruoyi.common.core.mapper.BaseMapperPlus;
public interface BrowserProxyMapper extends BaseMapperPlus<BrowserProxyMapper, BrowserProxy, BrowserProxyVo> {
}
@@ -0,0 +1,7 @@
package com.ruoyi.browser.mapper;
import com.ruoyi.browser.domain.BrowserRuntimeRecord;
import com.ruoyi.common.core.mapper.BaseMapperPlus;
public interface BrowserRuntimeRecordMapper extends BaseMapperPlus<BrowserRuntimeRecordMapper, BrowserRuntimeRecord, BrowserRuntimeRecord> {
}
@@ -0,0 +1,16 @@
package com.ruoyi.browser.service;
import com.ruoyi.browser.domain.bo.BrowserFingerprintBo;
import com.ruoyi.browser.domain.vo.BrowserFingerprintVo;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import java.util.Collection;
public interface IBrowserFingerprintService {
TableDataInfo<BrowserFingerprintVo> queryPageList(BrowserFingerprintBo bo, PageQuery pageQuery);
BrowserFingerprintVo queryById(Long fingerprintId);
Boolean insertByBo(BrowserFingerprintBo bo);
Boolean updateByBo(BrowserFingerprintBo bo);
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
}
@@ -0,0 +1,26 @@
package com.ruoyi.browser.service;
import com.ruoyi.browser.domain.bo.BrowserKernelPackageBo;
import com.ruoyi.browser.domain.vo.BrowserKernelPackageVo;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import java.util.Collection;
import java.util.List;
public interface IBrowserKernelPackageService {
TableDataInfo<BrowserKernelPackageVo> queryPageList(BrowserKernelPackageBo bo, PageQuery pageQuery);
List<BrowserKernelPackageVo> queryEnabledOptions(BrowserKernelPackageBo bo);
BrowserKernelPackageVo queryById(Long kernelId);
Boolean insertByBo(BrowserKernelPackageBo bo);
Boolean updateByBo(BrowserKernelPackageBo bo);
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
BrowserKernelPackageVo resolvePackage(String browserEngine, String browserVersion, String osType, String archType);
}
@@ -0,0 +1,31 @@
package com.ruoyi.browser.service;
import com.ruoyi.browser.domain.bo.BrowserMemberRegisterBo;
import com.ruoyi.browser.domain.bo.BrowserMemberUserBo;
import com.ruoyi.browser.domain.vo.BrowserMemberUserVo;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.page.TableDataInfo;
import java.util.Collection;
public interface IBrowserMemberUserService {
TableDataInfo<BrowserMemberUserVo> queryPageList(BrowserMemberUserBo bo, PageQuery pageQuery);
BrowserMemberUserVo queryById(Long memberId);
Boolean insertByBo(BrowserMemberUserBo bo);
Boolean updateByBo(BrowserMemberUserBo bo);
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
Boolean changeStatus(BrowserMemberUserBo bo);
String login(LoginBody loginBody);
void register(BrowserMemberRegisterBo bo);
BrowserMemberUserVo currentMember();
}
@@ -0,0 +1,24 @@
package com.ruoyi.browser.service;
import com.ruoyi.browser.domain.bo.BrowserPlatformBo;
import com.ruoyi.browser.domain.vo.BrowserPlatformVo;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import java.util.Collection;
import java.util.List;
public interface IBrowserPlatformService {
TableDataInfo<BrowserPlatformVo> queryPageList(BrowserPlatformBo bo, PageQuery pageQuery);
List<BrowserPlatformVo> queryEnabledOptions();
BrowserPlatformVo queryById(Long platformId);
Boolean insertByBo(BrowserPlatformBo bo);
Boolean updateByBo(BrowserPlatformBo bo);
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
}
@@ -0,0 +1,27 @@
package com.ruoyi.browser.service;
import com.ruoyi.browser.domain.BrowserProfileGroup;
import com.ruoyi.browser.domain.bo.BrowserProfileGroupBo;
import com.ruoyi.browser.domain.bo.BrowserProfileGroupMoveBo;
import com.ruoyi.browser.domain.vo.BrowserProfileGroupVo;
import java.util.List;
public interface IBrowserProfileGroupService {
List<BrowserProfileGroupVo> queryList(BrowserProfileGroupBo bo);
Boolean insertByBo(BrowserProfileGroupBo bo);
Boolean updateByBo(BrowserProfileGroupBo bo);
Boolean deleteById(Long groupId);
Boolean moveProfiles(BrowserProfileGroupMoveBo bo);
BrowserProfileGroup ensureDefaultGroup(Long userId);
void prepareGroupsForUser(Long userId);
BrowserProfileGroup resolveGroupForProfile(Long userId, Long groupId, String groupName);
}
@@ -0,0 +1,31 @@
package com.ruoyi.browser.service;
import com.ruoyi.browser.domain.bo.BrowserProfileBo;
import com.ruoyi.browser.domain.bo.BrowserProfileQuickSaveBo;
import com.ruoyi.browser.domain.vo.BrowserProfileVo;
import com.ruoyi.browser.domain.vo.BrowserProfileQuickSaveVo;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import java.util.Collection;
public interface IBrowserProfileService {
TableDataInfo<BrowserProfileVo> queryPageList(BrowserProfileBo bo, PageQuery pageQuery);
BrowserProfileVo queryById(Long profileId);
Boolean insertByBo(BrowserProfileBo bo);
Boolean updateByBo(BrowserProfileBo bo);
BrowserProfileQuickSaveVo quickCreate(BrowserProfileQuickSaveBo bo);
BrowserProfileQuickSaveVo quickUpdate(BrowserProfileQuickSaveBo bo);
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
void launch(Long profileId);
boolean close(Long profileId);
}
@@ -0,0 +1,17 @@
package com.ruoyi.browser.service;
import com.ruoyi.browser.domain.bo.BrowserProxyBo;
import com.ruoyi.browser.domain.vo.BrowserProxyVo;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import java.util.Collection;
public interface IBrowserProxyService {
TableDataInfo<BrowserProxyVo> queryPageList(BrowserProxyBo bo, PageQuery pageQuery);
BrowserProxyVo queryById(Long proxyId);
Boolean insertByBo(BrowserProxyBo bo);
Boolean updateByBo(BrowserProxyBo bo);
Boolean refreshGeoById(Long proxyId);
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
}
@@ -0,0 +1,6 @@
package com.ruoyi.browser.service;
public interface IBrowserRuntimeRecordService {
void recordLaunch(Long userId, Long profileId, Integer pid, Integer port, String runtimePath, String profileDir);
void recordClose(Long userId, Long profileId);
}
@@ -0,0 +1,17 @@
package com.ruoyi.browser.service;
import com.ruoyi.browser.domain.vo.BrowserRuntimeVo;
import com.ruoyi.browser.domain.vo.BrowserProfileVo;
import java.util.List;
public interface IBrowserRuntimeService {
BrowserProfileVo launch(Long profileId);
boolean close(Long profileId);
List<Object> running();
BrowserRuntimeVo buildLaunchPayload(BrowserProfileVo profileVo);
}
@@ -0,0 +1,122 @@
package com.ruoyi.browser.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.browser.domain.BrowserFingerprint;
import com.ruoyi.browser.domain.bo.BrowserFingerprintBo;
import com.ruoyi.browser.domain.vo.BrowserFingerprintVo;
import com.ruoyi.browser.mapper.BrowserFingerprintMapper;
import com.ruoyi.browser.service.IBrowserFingerprintService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Collection;
@RequiredArgsConstructor
@Service
public class BrowserFingerprintServiceImpl implements IBrowserFingerprintService {
private final BrowserFingerprintMapper baseMapper;
@Override
public TableDataInfo<BrowserFingerprintVo> queryPageList(BrowserFingerprintBo bo, PageQuery pageQuery) {
Page<BrowserFingerprintVo> result = baseMapper.selectVoPage(pageQuery.build(), buildQueryWrapper(bo));
return TableDataInfo.build(result);
}
@Override
public BrowserFingerprintVo queryById(Long fingerprintId) {
BrowserFingerprintVo vo = baseMapper.selectVoById(fingerprintId);
checkAccess(vo);
return vo;
}
@Override
public Boolean insertByBo(BrowserFingerprintBo bo) {
BrowserFingerprint entity = BeanUtil.toBean(bo, BrowserFingerprint.class);
Long userId = LoginHelper.getUserId();
if (ObjectUtil.isNull(userId)) {
throw new ServiceException("未获取到当前登录会员信息");
}
entity.setUserId(userId);
if (!checkUnique(entity)) {
throw new ServiceException("指纹配置已存在");
}
return baseMapper.insert(entity) > 0;
}
@Override
public Boolean updateByBo(BrowserFingerprintBo bo) {
BrowserFingerprint entity = BeanUtil.toBean(bo, BrowserFingerprint.class);
BrowserFingerprint old = baseMapper.selectById(entity.getFingerprintId());
checkAccess(old);
entity.setUserId(old.getUserId());
if (!checkUnique(entity)) {
throw new ServiceException("指纹配置已存在");
}
return baseMapper.updateById(entity) > 0;
}
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
for (Long id : ids) {
checkAccess(baseMapper.selectById(id));
}
return baseMapper.deleteBatchIds(ids) > 0;
}
private LambdaQueryWrapper<BrowserFingerprint> buildQueryWrapper(BrowserFingerprintBo bo) {
LambdaQueryWrapper<BrowserFingerprint> lqw = new LambdaQueryWrapper<>();
Long userId = LoginHelper.getUserId();
if (isSystemAdmin()) {
lqw.eq(ObjectUtil.isNotNull(bo.getUserId()), BrowserFingerprint::getUserId, bo.getUserId());
} else {
if (ObjectUtil.isNull(userId)) {
throw new ServiceException("未获取到当前登录会员信息");
}
lqw.eq(BrowserFingerprint::getUserId, userId);
}
lqw.eq(ObjectUtil.isNotNull(bo.getProfileId()), BrowserFingerprint::getProfileId, bo.getProfileId());
lqw.eq(StringUtils.isNotBlank(bo.getBrowserFamily()), BrowserFingerprint::getBrowserFamily, bo.getBrowserFamily());
return lqw;
}
private void checkAccess(BrowserFingerprintVo vo) {
if (ObjectUtil.isNull(vo)) {
throw new ServiceException("指纹数据不存在");
}
if (!isSystemAdmin() && !ObjectUtil.equal(LoginHelper.getUserId(), vo.getUserId())) {
throw new ServiceException("无权限访问该指纹数据");
}
}
private void checkAccess(BrowserFingerprint entity) {
if (ObjectUtil.isNull(entity)) {
throw new ServiceException("指纹数据不存在");
}
if (!isSystemAdmin() && !ObjectUtil.equal(LoginHelper.getUserId(), entity.getUserId())) {
throw new ServiceException("无权限操作该指纹数据");
}
}
private boolean isSystemAdmin() {
return LoginHelper.isAdmin() && LoginHelper.getUserType() == UserType.SYS_USER;
}
private boolean checkUnique(BrowserFingerprint entity) {
long fingerprintId = ObjectUtil.isNull(entity.getFingerprintId()) ? -1L : entity.getFingerprintId();
return !baseMapper.exists(new LambdaQueryWrapper<BrowserFingerprint>()
.eq(BrowserFingerprint::getUserId, entity.getUserId())
.eq(BrowserFingerprint::getProfileId, entity.getProfileId())
.ne(ObjectUtil.isNotNull(entity.getFingerprintId()), BrowserFingerprint::getFingerprintId, fingerprintId));
}
}
@@ -0,0 +1,184 @@
package com.ruoyi.browser.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.browser.domain.BrowserKernelPackage;
import com.ruoyi.browser.domain.bo.BrowserKernelPackageBo;
import com.ruoyi.browser.domain.vo.BrowserKernelPackageVo;
import com.ruoyi.browser.mapper.BrowserKernelPackageMapper;
import com.ruoyi.browser.service.IBrowserKernelPackageService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
@RequiredArgsConstructor
@Service
public class BrowserKernelPackageServiceImpl implements IBrowserKernelPackageService {
private final BrowserKernelPackageMapper baseMapper;
@Override
public TableDataInfo<BrowserKernelPackageVo> queryPageList(BrowserKernelPackageBo bo, PageQuery pageQuery) {
Page<BrowserKernelPackageVo> result = baseMapper.selectVoPage(pageQuery.build(), buildQueryWrapper(bo, false));
return TableDataInfo.build(result);
}
@Override
public List<BrowserKernelPackageVo> queryEnabledOptions(BrowserKernelPackageBo bo) {
return baseMapper.selectVoList(buildQueryWrapper(bo, true));
}
@Override
public BrowserKernelPackageVo queryById(Long kernelId) {
BrowserKernelPackageVo vo = baseMapper.selectVoById(kernelId);
if (ObjectUtil.isNull(vo)) {
throw new ServiceException("内核包配置不存在");
}
return vo;
}
@Override
public Boolean insertByBo(BrowserKernelPackageBo bo) {
BrowserKernelPackage entity = normalizeEntity(BeanUtil.toBean(bo, BrowserKernelPackage.class));
entity.setKernelId(null);
ensureUnique(entity);
resetDefaultIfNeeded(entity);
return baseMapper.insert(entity) > 0;
}
@Override
public Boolean updateByBo(BrowserKernelPackageBo bo) {
BrowserKernelPackage old = baseMapper.selectById(bo.getKernelId());
if (ObjectUtil.isNull(old)) {
throw new ServiceException("内核包配置不存在");
}
BrowserKernelPackage entity = normalizeEntity(BeanUtil.toBean(bo, BrowserKernelPackage.class));
ensureUnique(entity);
resetDefaultIfNeeded(entity);
return baseMapper.updateById(entity) > 0;
}
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
if (CollUtil.isEmpty(ids)) {
return false;
}
return baseMapper.deleteBatchIds(ids) > 0;
}
@Override
public BrowserKernelPackageVo resolvePackage(String browserEngine, String browserVersion, String osType, String archType) {
String normalizedEngine = StringUtils.trimToEmpty(browserEngine);
String normalizedVersion = StringUtils.trimToEmpty(browserVersion);
String normalizedOs = StringUtils.trimToEmpty(osType);
String normalizedArch = StringUtils.trimToEmpty(archType);
if (StringUtils.isAnyBlank(normalizedEngine, normalizedOs, normalizedArch)) {
return null;
}
BrowserKernelPackage kernelPackage = null;
if (StringUtils.isNotBlank(normalizedVersion)) {
kernelPackage = baseMapper.selectOne(new LambdaQueryWrapper<BrowserKernelPackage>()
.eq(BrowserKernelPackage::getBrowserEngine, normalizedEngine)
.eq(BrowserKernelPackage::getBrowserVersion, normalizedVersion)
.eq(BrowserKernelPackage::getOsType, normalizedOs)
.eq(BrowserKernelPackage::getArchType, normalizedArch)
.eq(BrowserKernelPackage::getStatus, "0")
.last("limit 1"));
}
if (ObjectUtil.isNull(kernelPackage)) {
kernelPackage = baseMapper.selectOne(new LambdaQueryWrapper<BrowserKernelPackage>()
.eq(BrowserKernelPackage::getBrowserEngine, normalizedEngine)
.eq(BrowserKernelPackage::getOsType, normalizedOs)
.eq(BrowserKernelPackage::getArchType, normalizedArch)
.eq(BrowserKernelPackage::getIsDefault, "1")
.eq(BrowserKernelPackage::getStatus, "0")
.last("limit 1"));
}
return ObjectUtil.isNull(kernelPackage) ? null : BeanUtil.toBean(kernelPackage, BrowserKernelPackageVo.class);
}
private LambdaQueryWrapper<BrowserKernelPackage> buildQueryWrapper(BrowserKernelPackageBo bo, boolean enabledOnly) {
LambdaQueryWrapper<BrowserKernelPackage> lqw = new LambdaQueryWrapper<>();
lqw.eq(StringUtils.isNotBlank(bo.getBrowserEngine()), BrowserKernelPackage::getBrowserEngine, bo.getBrowserEngine());
lqw.eq(StringUtils.isNotBlank(bo.getBrowserVersion()), BrowserKernelPackage::getBrowserVersion, bo.getBrowserVersion());
lqw.eq(StringUtils.isNotBlank(bo.getOsType()), BrowserKernelPackage::getOsType, bo.getOsType());
lqw.eq(StringUtils.isNotBlank(bo.getArchType()), BrowserKernelPackage::getArchType, bo.getArchType());
lqw.eq(StringUtils.isNotBlank(bo.getStatus()), BrowserKernelPackage::getStatus, bo.getStatus());
if (enabledOnly) {
lqw.eq(BrowserKernelPackage::getStatus, "0");
}
lqw.orderByAsc(BrowserKernelPackage::getBrowserEngine)
.orderByAsc(BrowserKernelPackage::getOsType)
.orderByAsc(BrowserKernelPackage::getArchType)
.orderByDesc(BrowserKernelPackage::getIsDefault)
.orderByAsc(BrowserKernelPackage::getSortOrder)
.orderByAsc(BrowserKernelPackage::getCreateTime);
return lqw;
}
private BrowserKernelPackage normalizeEntity(BrowserKernelPackage entity) {
entity.setBrowserEngine(StringUtils.trim(entity.getBrowserEngine()));
entity.setBrowserVersion(StringUtils.trim(entity.getBrowserVersion()));
entity.setFullVersion(StringUtils.trim(entity.getFullVersion()));
entity.setOsType(StringUtils.lowerCase(StringUtils.trim(entity.getOsType())));
entity.setArchType(StringUtils.lowerCase(StringUtils.trim(entity.getArchType())));
entity.setPackageUrl(normalizeUrl(entity.getPackageUrl(), "压缩包地址"));
entity.setPackageSha256(StringUtils.trim(entity.getPackageSha256()));
entity.setArchiveRootDir(StringUtils.trim(entity.getArchiveRootDir()));
entity.setExecutablePath(StringUtils.trim(entity.getExecutablePath()));
entity.setSortOrder(ObjectUtil.defaultIfNull(entity.getSortOrder(), 0));
entity.setIsDefault(StringUtils.equals(entity.getIsDefault(), "1") ? "1" : "0");
entity.setStatus(StringUtils.isBlank(entity.getStatus()) ? "0" : entity.getStatus());
return entity;
}
private void ensureUnique(BrowserKernelPackage entity) {
long kernelId = ObjectUtil.defaultIfNull(entity.getKernelId(), -1L);
boolean exists = baseMapper.exists(new LambdaQueryWrapper<BrowserKernelPackage>()
.eq(BrowserKernelPackage::getBrowserEngine, entity.getBrowserEngine())
.eq(BrowserKernelPackage::getBrowserVersion, entity.getBrowserVersion())
.eq(BrowserKernelPackage::getOsType, entity.getOsType())
.eq(BrowserKernelPackage::getArchType, entity.getArchType())
.ne(ObjectUtil.isNotNull(entity.getKernelId()), BrowserKernelPackage::getKernelId, kernelId));
if (exists) {
throw new ServiceException("同系统架构下该内核版本已存在");
}
}
private void resetDefaultIfNeeded(BrowserKernelPackage entity) {
if (!StringUtils.equals(entity.getIsDefault(), "1")) {
return;
}
baseMapper.update(
null,
new LambdaUpdateWrapper<BrowserKernelPackage>()
.eq(BrowserKernelPackage::getBrowserEngine, entity.getBrowserEngine())
.eq(BrowserKernelPackage::getOsType, entity.getOsType())
.eq(BrowserKernelPackage::getArchType, entity.getArchType())
.set(BrowserKernelPackage::getIsDefault, "0")
.ne(ObjectUtil.isNotNull(entity.getKernelId()), BrowserKernelPackage::getKernelId, entity.getKernelId())
);
}
private String normalizeUrl(String value, String fieldName) {
String normalized = StringUtils.trim(value);
if (StringUtils.isBlank(normalized)) {
throw new ServiceException(fieldName + "不能为空");
}
if (!(StringUtils.startsWithIgnoreCase(normalized, "http://")
|| StringUtils.startsWithIgnoreCase(normalized, "https://"))) {
throw new ServiceException(fieldName + "必须以 http:// 或 https:// 开头");
}
return normalized;
}
}
@@ -0,0 +1,232 @@
package com.ruoyi.browser.service.impl;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.browser.domain.BrowserMemberUser;
import com.ruoyi.browser.domain.bo.BrowserMemberRegisterBo;
import com.ruoyi.browser.domain.bo.BrowserMemberUserBo;
import com.ruoyi.browser.domain.vo.BrowserMemberUserVo;
import com.ruoyi.browser.mapper.BrowserMemberUserMapper;
import com.ruoyi.browser.service.IBrowserProfileGroupService;
import com.ruoyi.browser.service.IBrowserMemberUserService;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.DeviceType;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
@RequiredArgsConstructor
@Service
public class BrowserMemberUserServiceImpl implements IBrowserMemberUserService {
private static final Set<String> MEMBER_MENU_PERMISSION = new HashSet<>(Arrays.asList(
"browser:profile:list",
"browser:profile:query",
"browser:profile:add",
"browser:profile:edit",
"browser:profile:remove",
"browser:profile:launch",
"browser:profile:close",
"browser:platform:list",
"browser:platform:query",
"browser:profile-group:list",
"browser:profile-group:add",
"browser:profile-group:edit",
"browser:profile-group:remove",
"browser:proxy:list",
"browser:proxy:query",
"browser:proxy:add",
"browser:proxy:edit",
"browser:proxy:remove",
"browser:proxy:refresh-geo",
"browser:fingerprint:list",
"browser:fingerprint:query",
"browser:fingerprint:add",
"browser:fingerprint:edit",
"browser:fingerprint:remove"
));
private final BrowserMemberUserMapper baseMapper;
private final IBrowserProfileGroupService profileGroupService;
@Override
public TableDataInfo<BrowserMemberUserVo> queryPageList(BrowserMemberUserBo bo, PageQuery pageQuery) {
Page<BrowserMemberUserVo> result = baseMapper.selectVoPage(pageQuery.build(), buildQueryWrapper(bo));
return TableDataInfo.build(result);
}
@Override
public BrowserMemberUserVo queryById(Long memberId) {
BrowserMemberUserVo vo = baseMapper.selectVoById(memberId);
if (ObjectUtil.isNull(vo)) {
throw new ServiceException("会员数据不存在");
}
return vo;
}
@Override
public Boolean insertByBo(BrowserMemberUserBo bo) {
BrowserMemberUser entity = BeanUtil.toBean(bo, BrowserMemberUser.class);
entity.setMemberId(null);
entity.setPassword(BCrypt.hashpw(bo.getPassword()));
if (StringUtils.isBlank(entity.getNickName())) {
entity.setNickName(entity.getUsername());
}
if (!checkUsernameUnique(entity)) {
throw new ServiceException("会员账号已存在");
}
if (StringUtils.isBlank(entity.getStatus())) {
entity.setStatus(UserConstants.USER_NORMAL);
}
boolean inserted = baseMapper.insert(entity) > 0;
if (inserted) {
profileGroupService.ensureDefaultGroup(entity.getMemberId());
}
return inserted;
}
@Override
public Boolean updateByBo(BrowserMemberUserBo bo) {
BrowserMemberUser entity = BeanUtil.toBean(bo, BrowserMemberUser.class);
BrowserMemberUser old = baseMapper.selectById(entity.getMemberId());
if (ObjectUtil.isNull(old)) {
throw new ServiceException("会员数据不存在");
}
if (!checkUsernameUnique(entity)) {
throw new ServiceException("会员账号已存在");
}
if (StringUtils.isBlank(entity.getPassword())) {
entity.setPassword(null);
} else {
entity.setPassword(BCrypt.hashpw(entity.getPassword()));
}
if (StringUtils.isBlank(entity.getNickName())) {
entity.setNickName(entity.getUsername());
}
return baseMapper.updateById(entity) > 0;
}
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
if (CollUtil.isEmpty(ids)) {
return false;
}
return baseMapper.deleteBatchIds(ids) > 0;
}
@Override
public Boolean changeStatus(BrowserMemberUserBo bo) {
BrowserMemberUser entity = new BrowserMemberUser();
entity.setMemberId(bo.getMemberId());
entity.setStatus(bo.getStatus());
return baseMapper.updateById(entity) > 0;
}
@Override
public String login(LoginBody loginBody) {
BrowserMemberUser user = baseMapper.selectOne(new LambdaQueryWrapper<BrowserMemberUser>()
.eq(BrowserMemberUser::getUsername, loginBody.getUsername()));
if (ObjectUtil.isNull(user)) {
throw new ServiceException("会员账号不存在");
}
if (UserConstants.USER_DISABLE.equals(user.getStatus())) {
throw new ServiceException("会员账号已被停用");
}
if (ObjectUtil.isNotNull(user.getExpireTime()) && user.getExpireTime().before(DateUtils.getNowDate())) {
throw new ServiceException("会员账号已过期");
}
if (!BCrypt.checkpw(loginBody.getPassword(), user.getPassword())) {
throw new ServiceException("会员账号或密码错误");
}
profileGroupService.ensureDefaultGroup(user.getMemberId());
LoginUser loginUser = buildLoginUser(user);
LoginHelper.loginByDevice(loginUser, DeviceType.PC);
BrowserMemberUser update = new BrowserMemberUser();
update.setMemberId(user.getMemberId());
update.setLastLoginIp(ServletUtils.getClientIP());
update.setLastLoginTime(new Date());
baseMapper.updateById(update);
return StpUtil.getTokenValue();
}
@Override
@Transactional(rollbackFor = Exception.class)
public void register(BrowserMemberRegisterBo bo) {
if (StringUtils.isNotBlank(bo.getConfirmPassword()) && !StringUtils.equals(bo.getPassword(), bo.getConfirmPassword())) {
throw new ServiceException("两次输入的密码不一致");
}
BrowserMemberUser entity = new BrowserMemberUser();
entity.setUsername(bo.getUsername());
entity.setPassword(BCrypt.hashpw(bo.getPassword()));
entity.setNickName(StringUtils.isBlank(bo.getNickName()) ? bo.getUsername() : bo.getNickName());
entity.setEmail(bo.getEmail());
entity.setPhonenumber(bo.getPhonenumber());
entity.setStatus(UserConstants.USER_NORMAL);
if (!checkUsernameUnique(entity)) {
throw new ServiceException("会员账号已存在");
}
if (baseMapper.insert(entity) <= 0) {
throw new ServiceException("会员注册失败");
}
profileGroupService.ensureDefaultGroup(entity.getMemberId());
}
@Override
public BrowserMemberUserVo currentMember() {
if (LoginHelper.getUserType() != UserType.MEMBER_USER) {
throw new ServiceException("当前登录身份不是会员用户");
}
Long memberId = LoginHelper.getUserId();
if (ObjectUtil.isNull(memberId)) {
throw new ServiceException("未获取到会员登录信息");
}
return queryById(memberId);
}
private LambdaQueryWrapper<BrowserMemberUser> buildQueryWrapper(BrowserMemberUserBo bo) {
LambdaQueryWrapper<BrowserMemberUser> lqw = new LambdaQueryWrapper<>();
lqw.like(StringUtils.isNotBlank(bo.getUsername()), BrowserMemberUser::getUsername, bo.getUsername());
lqw.like(StringUtils.isNotBlank(bo.getNickName()), BrowserMemberUser::getNickName, bo.getNickName());
lqw.eq(StringUtils.isNotBlank(bo.getStatus()), BrowserMemberUser::getStatus, bo.getStatus());
lqw.orderByDesc(BrowserMemberUser::getCreateTime);
return lqw;
}
private boolean checkUsernameUnique(BrowserMemberUser entity) {
long memberId = ObjectUtil.isNull(entity.getMemberId()) ? -1L : entity.getMemberId();
return !baseMapper.exists(new LambdaQueryWrapper<BrowserMemberUser>()
.eq(BrowserMemberUser::getUsername, entity.getUsername())
.ne(ObjectUtil.isNotNull(entity.getMemberId()), BrowserMemberUser::getMemberId, memberId));
}
private LoginUser buildLoginUser(BrowserMemberUser user) {
LoginUser loginUser = new LoginUser();
loginUser.setUserId(user.getMemberId());
loginUser.setUsername(user.getUsername());
loginUser.setUserType(UserType.MEMBER_USER.getUserType());
loginUser.setMenuPermission(new HashSet<>(MEMBER_MENU_PERMISSION));
loginUser.setRolePermission(new HashSet<>(CollUtil.newArrayList("member")));
return loginUser;
}
}
@@ -0,0 +1,166 @@
package com.ruoyi.browser.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.browser.domain.BrowserPlatform;
import com.ruoyi.browser.domain.BrowserProfile;
import com.ruoyi.browser.domain.bo.BrowserPlatformBo;
import com.ruoyi.browser.domain.vo.BrowserPlatformVo;
import com.ruoyi.browser.mapper.BrowserPlatformMapper;
import com.ruoyi.browser.mapper.BrowserProfileMapper;
import com.ruoyi.browser.service.IBrowserPlatformService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
@RequiredArgsConstructor
@Service
public class BrowserPlatformServiceImpl implements IBrowserPlatformService {
public static final String ICON_BASE_URL_KEY = "browser.platform.iconBaseUrl";
private final BrowserPlatformMapper baseMapper;
private final BrowserProfileMapper profileMapper;
private final ISysConfigService configService;
@Override
public TableDataInfo<BrowserPlatformVo> queryPageList(BrowserPlatformBo bo, PageQuery pageQuery) {
Page<BrowserPlatformVo> result = baseMapper.selectVoPage(pageQuery.build(), buildQueryWrapper(bo));
enrichIconUrl(result.getRecords());
return TableDataInfo.build(result);
}
@Override
public List<BrowserPlatformVo> queryEnabledOptions() {
List<BrowserPlatformVo> rows = baseMapper.selectVoList(new LambdaQueryWrapper<BrowserPlatform>()
.eq(BrowserPlatform::getStatus, "0")
.orderByAsc(BrowserPlatform::getSortOrder)
.orderByAsc(BrowserPlatform::getCreateTime));
enrichIconUrl(rows);
return rows;
}
@Override
public BrowserPlatformVo queryById(Long platformId) {
BrowserPlatformVo vo = baseMapper.selectVoById(platformId);
if (ObjectUtil.isNull(vo)) {
throw new ServiceException("平台数据不存在");
}
enrichIconUrl(CollUtil.newArrayList(vo));
return vo;
}
@Override
public Boolean insertByBo(BrowserPlatformBo bo) {
BrowserPlatform entity = normalizeEntity(BeanUtil.toBean(bo, BrowserPlatform.class));
entity.setPlatformId(null);
if (!checkNameUnique(entity)) {
throw new ServiceException("平台名称已存在");
}
return baseMapper.insert(entity) > 0;
}
@Override
public Boolean updateByBo(BrowserPlatformBo bo) {
BrowserPlatform old = baseMapper.selectById(bo.getPlatformId());
if (ObjectUtil.isNull(old)) {
throw new ServiceException("平台数据不存在");
}
BrowserPlatform entity = normalizeEntity(BeanUtil.toBean(bo, BrowserPlatform.class));
if (!checkNameUnique(entity)) {
throw new ServiceException("平台名称已存在");
}
return baseMapper.updateById(entity) > 0;
}
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
if (CollUtil.isEmpty(ids)) {
return false;
}
for (Long id : ids) {
long count = profileMapper.selectCount(new LambdaQueryWrapper<BrowserProfile>()
.eq(BrowserProfile::getPlatformId, id));
if (count > 0) {
throw new ServiceException("平台已被环境使用,不能删除");
}
}
return baseMapper.deleteBatchIds(ids) > 0;
}
private LambdaQueryWrapper<BrowserPlatform> buildQueryWrapper(BrowserPlatformBo bo) {
LambdaQueryWrapper<BrowserPlatform> lqw = new LambdaQueryWrapper<>();
lqw.like(StringUtils.isNotBlank(bo.getPlatformName()), BrowserPlatform::getPlatformName, bo.getPlatformName());
lqw.like(StringUtils.isNotBlank(bo.getWebsiteUrl()), BrowserPlatform::getWebsiteUrl, bo.getWebsiteUrl());
lqw.eq(StringUtils.isNotBlank(bo.getStatus()), BrowserPlatform::getStatus, bo.getStatus());
lqw.orderByAsc(BrowserPlatform::getSortOrder);
lqw.orderByAsc(BrowserPlatform::getCreateTime);
return lqw;
}
private BrowserPlatform normalizeEntity(BrowserPlatform entity) {
entity.setPlatformName(StringUtils.trim(entity.getPlatformName()));
entity.setWebsiteUrl(normalizeWebsiteUrl(entity.getWebsiteUrl(), "平台网站地址"));
entity.setIconFileName(normalizeIconFileName(entity.getIconFileName()));
entity.setSortOrder(ObjectUtil.defaultIfNull(entity.getSortOrder(), 0));
entity.setStatus(StringUtils.isBlank(entity.getStatus()) ? "0" : entity.getStatus());
return entity;
}
private boolean checkNameUnique(BrowserPlatform entity) {
long platformId = ObjectUtil.isNull(entity.getPlatformId()) ? -1L : entity.getPlatformId();
return !baseMapper.exists(new LambdaQueryWrapper<BrowserPlatform>()
.eq(BrowserPlatform::getPlatformName, entity.getPlatformName())
.ne(ObjectUtil.isNotNull(entity.getPlatformId()), BrowserPlatform::getPlatformId, platformId));
}
private void enrichIconUrl(List<BrowserPlatformVo> rows) {
if (CollUtil.isEmpty(rows)) {
return;
}
String baseUrl = normalizeBaseUrl(configService.selectConfigByKey(ICON_BASE_URL_KEY));
rows.forEach(item -> item.setIconUrl(buildIconUrl(baseUrl, item.getIconFileName())));
}
public static String normalizeWebsiteUrl(String value, String fieldName) {
String normalized = StringUtils.trim(value);
if (StringUtils.isBlank(normalized)) {
throw new ServiceException(fieldName + "不能为空");
}
if (!(StringUtils.startsWithIgnoreCase(normalized, "http://")
|| StringUtils.startsWithIgnoreCase(normalized, "https://"))) {
throw new ServiceException(fieldName + "必须以 http:// 或 https:// 开头");
}
return normalized;
}
public static String normalizeBaseUrl(String value) {
String normalized = StringUtils.trim(value);
if (StringUtils.isBlank(normalized)) {
return null;
}
return StringUtils.stripEnd(normalized, "/");
}
public static String normalizeIconFileName(String value) {
String normalized = StringUtils.trim(value);
return StringUtils.isBlank(normalized) ? null : normalized;
}
public static String buildIconUrl(String baseUrl, String iconFileName) {
if (StringUtils.isAnyBlank(baseUrl, iconFileName)) {
return null;
}
return baseUrl + "/" + iconFileName;
}
}
@@ -0,0 +1,336 @@
package com.ruoyi.browser.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.browser.domain.BrowserProfile;
import com.ruoyi.browser.domain.BrowserProfileGroup;
import com.ruoyi.browser.domain.bo.BrowserProfileGroupBo;
import com.ruoyi.browser.domain.bo.BrowserProfileGroupMoveBo;
import com.ruoyi.browser.domain.vo.BrowserProfileGroupVo;
import com.ruoyi.browser.mapper.BrowserProfileGroupMapper;
import com.ruoyi.browser.mapper.BrowserProfileMapper;
import com.ruoyi.browser.service.IBrowserProfileGroupService;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RequiredArgsConstructor
@Service
public class BrowserProfileGroupServiceImpl implements IBrowserProfileGroupService {
private static final String DEFAULT_GROUP_FLAG = "1";
private static final String NORMAL_GROUP_FLAG = "0";
private static final String DEFAULT_GROUP_NAME = "默认分组";
private static final String DEFAULT_GROUP_COLOR = "#2563eb";
private final BrowserProfileGroupMapper baseMapper;
private final BrowserProfileMapper profileMapper;
@Override
public List<BrowserProfileGroupVo> queryList(BrowserProfileGroupBo bo) {
Long userId = resolveQueryUserId(bo.getUserId());
prepareGroupsForUser(userId);
List<BrowserProfileGroupVo> groups = baseMapper.selectVoList(new LambdaQueryWrapper<BrowserProfileGroup>()
.eq(BrowserProfileGroup::getUserId, userId)
.like(StringUtils.isNotBlank(bo.getGroupName()), BrowserProfileGroup::getGroupName, bo.getGroupName())
.orderByDesc(BrowserProfileGroup::getIsDefault)
.orderByAsc(BrowserProfileGroup::getSortOrder)
.orderByAsc(BrowserProfileGroup::getCreateTime));
Map<Long, Long> countMap = queryProfileCountMap(userId);
groups.forEach(group -> group.setProfileCount(countMap.getOrDefault(group.getGroupId(), 0L)));
return groups;
}
@Override
public Boolean insertByBo(BrowserProfileGroupBo bo) {
Long userId = LoginHelper.getUserId();
prepareGroupsForUser(userId);
BrowserProfileGroup entity = BeanUtil.toBean(bo, BrowserProfileGroup.class);
entity.setGroupId(null);
entity.setUserId(userId);
entity.setIsDefault(NORMAL_GROUP_FLAG);
entity.setGroupName(normalizeGroupName(bo.getGroupName()));
entity.setGroupColor(normalizeGroupColor(bo.getGroupColor(), DEFAULT_GROUP_COLOR));
entity.setSortOrder(ObjectUtil.defaultIfNull(bo.getSortOrder(), nextSortOrder(userId)));
if (!checkNameUnique(entity)) {
throw new ServiceException("分组名称已存在");
}
return baseMapper.insert(entity) > 0;
}
@Transactional(rollbackFor = Exception.class)
@Override
public Boolean updateByBo(BrowserProfileGroupBo bo) {
BrowserProfileGroup old = baseMapper.selectById(bo.getGroupId());
checkAccess(old);
BrowserProfileGroup entity = BeanUtil.toBean(bo, BrowserProfileGroup.class);
entity.setUserId(old.getUserId());
entity.setIsDefault(old.getIsDefault());
entity.setGroupName(normalizeGroupName(StringUtils.blankToDefault(bo.getGroupName(), old.getGroupName())));
entity.setGroupColor(normalizeGroupColor(StringUtils.blankToDefault(bo.getGroupColor(), old.getGroupColor()), DEFAULT_GROUP_COLOR));
entity.setSortOrder(ObjectUtil.defaultIfNull(bo.getSortOrder(), old.getSortOrder()));
if (!checkNameUnique(entity)) {
throw new ServiceException("分组名称已存在");
}
boolean updated = baseMapper.updateById(entity) > 0;
if (updated && !StringUtils.equals(old.getGroupName(), entity.getGroupName())) {
syncProfilesToGroupName(entity.getGroupId(), entity.getGroupName());
}
return updated;
}
@Transactional(rollbackFor = Exception.class)
@Override
public Boolean deleteById(Long groupId) {
BrowserProfileGroup entity = baseMapper.selectById(groupId);
checkAccess(entity);
if (DEFAULT_GROUP_FLAG.equals(entity.getIsDefault())) {
throw new ServiceException("默认分组不允许删除");
}
BrowserProfileGroup defaultGroup = ensureDefaultGroup(entity.getUserId());
moveProfilesToGroup(fetchProfilesByGroup(entity.getGroupId()), defaultGroup);
return baseMapper.deleteById(groupId) > 0;
}
@Transactional(rollbackFor = Exception.class)
@Override
public Boolean moveProfiles(BrowserProfileGroupMoveBo bo) {
BrowserProfileGroup targetGroup = baseMapper.selectById(bo.getTargetGroupId());
checkAccess(targetGroup);
List<BrowserProfile> profiles = profileMapper.selectBatchIds(bo.getProfileIds());
if (CollUtil.isEmpty(profiles) || profiles.size() != bo.getProfileIds().size()) {
throw new ServiceException("存在环境数据不存在");
}
for (BrowserProfile profile : profiles) {
checkProfileAccess(profile);
if (!ObjectUtil.equal(profile.getUserId(), targetGroup.getUserId())) {
throw new ServiceException("不能移动到其他用户的分组");
}
}
moveProfilesToGroup(profiles, targetGroup);
return true;
}
@Override
public BrowserProfileGroup ensureDefaultGroup(Long userId) {
BrowserProfileGroup group = baseMapper.selectOne(new LambdaQueryWrapper<BrowserProfileGroup>()
.eq(BrowserProfileGroup::getUserId, userId)
.eq(BrowserProfileGroup::getIsDefault, DEFAULT_GROUP_FLAG)
.last("limit 1"));
if (ObjectUtil.isNotNull(group)) {
return group;
}
BrowserProfileGroup existing = findByUserAndName(userId, DEFAULT_GROUP_NAME);
if (ObjectUtil.isNotNull(existing)) {
BrowserProfileGroup update = new BrowserProfileGroup();
update.setGroupId(existing.getGroupId());
update.setIsDefault(DEFAULT_GROUP_FLAG);
update.setSortOrder(ObjectUtil.defaultIfNull(existing.getSortOrder(), 0));
update.setGroupColor(normalizeGroupColor(existing.getGroupColor(), DEFAULT_GROUP_COLOR));
baseMapper.updateById(update);
existing.setIsDefault(DEFAULT_GROUP_FLAG);
existing.setSortOrder(ObjectUtil.defaultIfNull(existing.getSortOrder(), 0));
existing.setGroupColor(normalizeGroupColor(existing.getGroupColor(), DEFAULT_GROUP_COLOR));
return existing;
}
BrowserProfileGroup entity = new BrowserProfileGroup();
entity.setUserId(userId);
entity.setGroupName(DEFAULT_GROUP_NAME);
entity.setIsDefault(DEFAULT_GROUP_FLAG);
entity.setGroupColor(DEFAULT_GROUP_COLOR);
entity.setSortOrder(0);
baseMapper.insert(entity);
return entity;
}
@Transactional(rollbackFor = Exception.class)
@Override
public void prepareGroupsForUser(Long userId) {
if (ObjectUtil.isNull(userId)) {
return;
}
BrowserProfileGroup defaultGroup = ensureDefaultGroup(userId);
syncLegacyProfiles(userId, defaultGroup);
}
@Override
public BrowserProfileGroup resolveGroupForProfile(Long userId, Long groupId, String groupName) {
prepareGroupsForUser(userId);
if (ObjectUtil.isNotNull(groupId)) {
BrowserProfileGroup group = baseMapper.selectById(groupId);
if (ObjectUtil.isNull(group) || !ObjectUtil.equal(group.getUserId(), userId)) {
throw new ServiceException("分组数据不存在或无权限访问");
}
return group;
}
if (StringUtils.isNotBlank(groupName)) {
String normalizedName = normalizeGroupName(groupName);
BrowserProfileGroup exists = findByUserAndName(userId, normalizedName);
return ObjectUtil.isNotNull(exists) ? exists : createGroup(userId, normalizedName, NORMAL_GROUP_FLAG);
}
return ensureDefaultGroup(userId);
}
private void syncLegacyProfiles(Long userId, BrowserProfileGroup defaultGroup) {
List<BrowserProfile> legacyProfiles = profileMapper.selectList(new LambdaQueryWrapper<BrowserProfile>()
.eq(BrowserProfile::getUserId, userId)
.isNull(BrowserProfile::getGroupId));
if (CollUtil.isEmpty(legacyProfiles)) {
return;
}
for (BrowserProfile profile : legacyProfiles) {
BrowserProfileGroup targetGroup = StringUtils.isNotBlank(profile.getGroupName())
? findOrCreateNamedGroup(userId, profile.getGroupName())
: defaultGroup;
BrowserProfile update = new BrowserProfile();
update.setProfileId(profile.getProfileId());
update.setGroupId(targetGroup.getGroupId());
update.setGroupName(targetGroup.getGroupName());
profileMapper.updateById(update);
}
}
private BrowserProfileGroup findOrCreateNamedGroup(Long userId, String groupName) {
String normalizedName = normalizeGroupName(groupName);
BrowserProfileGroup exists = findByUserAndName(userId, normalizedName);
return ObjectUtil.isNotNull(exists) ? exists : createGroup(userId, normalizedName, NORMAL_GROUP_FLAG);
}
private BrowserProfileGroup createGroup(Long userId, String groupName, String isDefault) {
BrowserProfileGroup entity = new BrowserProfileGroup();
entity.setUserId(userId);
entity.setGroupName(groupName);
entity.setIsDefault(isDefault);
entity.setGroupColor(DEFAULT_GROUP_COLOR);
entity.setSortOrder(DEFAULT_GROUP_FLAG.equals(isDefault) ? 0 : nextSortOrder(userId));
baseMapper.insert(entity);
return entity;
}
private BrowserProfileGroup findByUserAndName(Long userId, String groupName) {
return baseMapper.selectOne(new LambdaQueryWrapper<BrowserProfileGroup>()
.eq(BrowserProfileGroup::getUserId, userId)
.eq(BrowserProfileGroup::getGroupName, groupName)
.last("limit 1"));
}
private int nextSortOrder(Long userId) {
BrowserProfileGroup lastGroup = baseMapper.selectOne(new LambdaQueryWrapper<BrowserProfileGroup>()
.eq(BrowserProfileGroup::getUserId, userId)
.orderByDesc(BrowserProfileGroup::getSortOrder)
.last("limit 1"));
return ObjectUtil.isNull(lastGroup) || ObjectUtil.isNull(lastGroup.getSortOrder())
? 10
: lastGroup.getSortOrder() + 10;
}
private Map<Long, Long> queryProfileCountMap(Long userId) {
List<Map<String, Object>> rows = profileMapper.selectMaps(new QueryWrapper<BrowserProfile>()
.select("group_id", "count(*) as total")
.eq("user_id", userId)
.isNotNull("group_id")
.groupBy("group_id"));
Map<Long, Long> result = new HashMap<>();
for (Map<String, Object> row : rows) {
Object groupIdValue = row.get("group_id");
Object totalValue = row.get("total");
if (groupIdValue instanceof Number && totalValue instanceof Number) {
result.put(((Number) groupIdValue).longValue(), ((Number) totalValue).longValue());
}
}
return result;
}
private List<BrowserProfile> fetchProfilesByGroup(Long groupId) {
return profileMapper.selectList(new LambdaQueryWrapper<BrowserProfile>()
.eq(BrowserProfile::getGroupId, groupId));
}
private void moveProfilesToGroup(Collection<BrowserProfile> profiles, BrowserProfileGroup targetGroup) {
if (CollUtil.isEmpty(profiles)) {
return;
}
for (BrowserProfile profile : profiles) {
BrowserProfile update = new BrowserProfile();
update.setProfileId(profile.getProfileId());
update.setGroupId(targetGroup.getGroupId());
update.setGroupName(targetGroup.getGroupName());
profileMapper.updateById(update);
}
}
private void syncProfilesToGroupName(Long groupId, String groupName) {
List<BrowserProfile> profiles = fetchProfilesByGroup(groupId);
for (BrowserProfile profile : profiles) {
BrowserProfile update = new BrowserProfile();
update.setProfileId(profile.getProfileId());
update.setGroupName(groupName);
profileMapper.updateById(update);
}
}
private Long resolveQueryUserId(Long requestedUserId) {
if (isSystemAdmin() && ObjectUtil.isNotNull(requestedUserId)) {
return requestedUserId;
}
return LoginHelper.getUserId();
}
private void checkAccess(BrowserProfileGroup entity) {
if (ObjectUtil.isNull(entity)) {
throw new ServiceException("分组数据不存在");
}
if (!isSystemAdmin() && !ObjectUtil.equal(LoginHelper.getUserId(), entity.getUserId())) {
throw new ServiceException("无权限操作该分组");
}
}
private void checkProfileAccess(BrowserProfile entity) {
if (ObjectUtil.isNull(entity)) {
throw new ServiceException("环境数据不存在");
}
if (!isSystemAdmin() && !ObjectUtil.equal(LoginHelper.getUserId(), entity.getUserId())) {
throw new ServiceException("无权限操作该环境数据");
}
}
private boolean checkNameUnique(BrowserProfileGroup entity) {
long groupId = ObjectUtil.isNull(entity.getGroupId()) ? -1L : entity.getGroupId();
return !baseMapper.exists(new LambdaQueryWrapper<BrowserProfileGroup>()
.eq(BrowserProfileGroup::getUserId, entity.getUserId())
.eq(BrowserProfileGroup::getGroupName, entity.getGroupName())
.ne(ObjectUtil.isNotNull(entity.getGroupId()), BrowserProfileGroup::getGroupId, groupId));
}
private String normalizeGroupName(String groupName) {
String normalized = StringUtils.trim(groupName);
if (StringUtils.isBlank(normalized)) {
throw new ServiceException("分组名称不能为空");
}
return normalized;
}
private String normalizeGroupColor(String groupColor, String fallback) {
String normalized = StringUtils.trim(groupColor);
if (StringUtils.isBlank(normalized)) {
return fallback;
}
return normalized;
}
private boolean isSystemAdmin() {
return LoginHelper.isAdmin() && LoginHelper.getUserType() == UserType.SYS_USER;
}
}
@@ -0,0 +1,457 @@
package com.ruoyi.browser.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.browser.domain.BrowserFingerprint;
import com.ruoyi.browser.domain.BrowserKernelPackage;
import com.ruoyi.browser.domain.BrowserMemberUser;
import com.ruoyi.browser.domain.BrowserPlatform;
import com.ruoyi.browser.domain.BrowserProfile;
import com.ruoyi.browser.domain.BrowserProfileGroup;
import com.ruoyi.browser.domain.BrowserProxy;
import com.ruoyi.browser.domain.bo.BrowserFingerprintBo;
import com.ruoyi.browser.domain.bo.BrowserProfileBo;
import com.ruoyi.browser.domain.bo.BrowserProfileQuickSaveBo;
import com.ruoyi.browser.domain.vo.BrowserProfileQuickSaveVo;
import com.ruoyi.browser.domain.vo.BrowserProfileVo;
import com.ruoyi.browser.mapper.BrowserFingerprintMapper;
import com.ruoyi.browser.mapper.BrowserKernelPackageMapper;
import com.ruoyi.browser.mapper.BrowserMemberUserMapper;
import com.ruoyi.browser.mapper.BrowserPlatformMapper;
import com.ruoyi.browser.mapper.BrowserProfileMapper;
import com.ruoyi.browser.mapper.BrowserProxyMapper;
import com.ruoyi.browser.service.IBrowserProfileGroupService;
import com.ruoyi.browser.service.IBrowserProfileService;
import com.ruoyi.browser.service.IBrowserRuntimeService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StreamUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
@RequiredArgsConstructor
@Service
public class BrowserProfileServiceImpl implements IBrowserProfileService {
private final BrowserProfileMapper baseMapper;
private final BrowserFingerprintMapper fingerprintMapper;
private final BrowserKernelPackageMapper kernelPackageMapper;
private final BrowserProxyMapper proxyMapper;
private final BrowserPlatformMapper platformMapper;
private final BrowserMemberUserMapper memberUserMapper;
private final IBrowserProfileGroupService profileGroupService;
private final IBrowserRuntimeService runtimeService;
private final ISysConfigService configService;
@Override
public TableDataInfo<BrowserProfileVo> queryPageList(BrowserProfileBo bo, PageQuery pageQuery) {
prepareGroupsForQuery(bo);
LambdaQueryWrapper<BrowserProfile> lqw = buildQueryWrapper(bo);
Page<BrowserProfileVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
List<BrowserProfileVo> records = result.getRecords();
enrichMemberInfo(records);
enrichPlatformInfo(records);
return TableDataInfo.build(result);
}
@Override
public BrowserProfileVo queryById(Long profileId) {
BrowserProfileVo vo = baseMapper.selectVoById(profileId);
checkAccess(vo);
if (ObjectUtil.isNotNull(vo) && ObjectUtil.isNotNull(vo.getUserId()) && ObjectUtil.isNull(vo.getGroupId())) {
profileGroupService.prepareGroupsForUser(vo.getUserId());
vo = baseMapper.selectVoById(profileId);
}
enrichMemberInfo(CollUtil.newArrayList(vo));
enrichPlatformInfo(CollUtil.newArrayList(vo));
return vo;
}
@Override
public Boolean insertByBo(BrowserProfileBo bo) {
BrowserProfile entity = buildProfileEntity(bo, null);
entity.setProfileId(null);
entity.setUserId(LoginHelper.getUserId());
if (!checkNameUnique(entity)) {
throw new ServiceException("环境名称已存在");
}
return baseMapper.insert(entity) > 0;
}
@Override
public Boolean updateByBo(BrowserProfileBo bo) {
BrowserProfile old = baseMapper.selectById(bo.getProfileId());
checkAccess(old);
BrowserProfile entity = buildProfileEntity(bo, old);
entity.setUserId(old.getUserId());
if (!checkNameUnique(entity)) {
throw new ServiceException("环境名称已存在");
}
return persistProfileUpdate(entity) > 0;
}
@Transactional(rollbackFor = Exception.class)
@Override
public BrowserProfileQuickSaveVo quickCreate(BrowserProfileQuickSaveBo bo) {
BrowserProfile profile = buildProfileEntity(bo.getProfile(), null);
profile.setUserId(LoginHelper.getUserId());
if (!checkNameUnique(profile)) {
throw new ServiceException("环境名称已存在");
}
baseMapper.insert(profile);
BrowserFingerprint fingerprint = buildFingerprintEntity(bo.getFingerprint(), profile, null);
fingerprintMapper.insert(fingerprint);
profile.setFingerprintId(fingerprint.getFingerprintId());
baseMapper.updateById(profile);
return new BrowserProfileQuickSaveVo(profile.getProfileId(), fingerprint.getFingerprintId());
}
@Transactional(rollbackFor = Exception.class)
@Override
public BrowserProfileQuickSaveVo quickUpdate(BrowserProfileQuickSaveBo bo) {
BrowserProfileBo profileBo = bo.getProfile();
if (ObjectUtil.isNull(profileBo.getProfileId())) {
throw new ServiceException("环境主键不能为空");
}
BrowserProfile oldProfile = baseMapper.selectById(profileBo.getProfileId());
checkAccess(oldProfile);
BrowserProfile profile = buildProfileEntity(profileBo, oldProfile);
profile.setUserId(oldProfile.getUserId());
if (!checkNameUnique(profile)) {
throw new ServiceException("环境名称已存在");
}
persistProfileUpdate(profile);
BrowserFingerprint currentFingerprint = resolveFingerprint(oldProfile);
BrowserFingerprint fingerprint = buildFingerprintEntity(
bo.getFingerprint(),
profile,
currentFingerprint
);
if (ObjectUtil.isNull(currentFingerprint)) {
fingerprintMapper.insert(fingerprint);
profile.setFingerprintId(fingerprint.getFingerprintId());
baseMapper.updateById(profile);
} else {
fingerprintMapper.updateById(fingerprint);
profile.setFingerprintId(fingerprint.getFingerprintId());
if (ObjectUtil.isNull(oldProfile.getFingerprintId())) {
baseMapper.updateById(profile);
}
}
return new BrowserProfileQuickSaveVo(
oldProfile.getProfileId(),
ObjectUtil.defaultIfNull(profile.getFingerprintId(), fingerprint.getFingerprintId())
);
}
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
if (CollUtil.isEmpty(ids)) {
return false;
}
for (Long id : ids) {
checkAccess(baseMapper.selectById(id));
}
return baseMapper.deleteBatchIds(ids) > 0;
}
@Override
public void launch(Long profileId) {
runtimeService.launch(profileId);
}
@Override
public boolean close(Long profileId) {
return runtimeService.close(profileId);
}
private LambdaQueryWrapper<BrowserProfile> buildQueryWrapper(BrowserProfileBo bo) {
LambdaQueryWrapper<BrowserProfile> lqw = new LambdaQueryWrapper<>();
Long userId = LoginHelper.getUserId();
if (isSystemAdmin()) {
lqw.eq(ObjectUtil.isNotNull(bo.getUserId()), BrowserProfile::getUserId, bo.getUserId());
if (StringUtils.isNotBlank(bo.getMemberUsername())) {
BrowserMemberUser memberUser = memberUserMapper.selectOne(new LambdaQueryWrapper<BrowserMemberUser>()
.select(BrowserMemberUser::getMemberId)
.eq(BrowserMemberUser::getUsername, bo.getMemberUsername()));
lqw.eq(BrowserProfile::getUserId, ObjectUtil.isNull(memberUser) ? -1L : memberUser.getMemberId());
}
} else {
lqw.eq(BrowserProfile::getUserId, userId);
}
lqw.like(StringUtils.isNotBlank(bo.getProfileName()), BrowserProfile::getProfileName, bo.getProfileName());
lqw.eq(ObjectUtil.isNotNull(bo.getGroupId()), BrowserProfile::getGroupId, bo.getGroupId());
lqw.eq(ObjectUtil.isNotNull(bo.getPlatformId()), BrowserProfile::getPlatformId, bo.getPlatformId());
lqw.eq(StringUtils.isNotBlank(bo.getBrowserEngine()), BrowserProfile::getBrowserEngine, bo.getBrowserEngine());
lqw.eq(StringUtils.isNotBlank(bo.getStatus()), BrowserProfile::getStatus, bo.getStatus());
lqw.orderByDesc(BrowserProfile::getCreateTime);
return lqw;
}
private void checkAccess(BrowserProfileVo vo) {
if (ObjectUtil.isNull(vo)) {
throw new ServiceException("环境数据不存在");
}
if (!isSystemAdmin() && !ObjectUtil.equal(LoginHelper.getUserId(), vo.getUserId())) {
throw new ServiceException("无权限访问该环境数据");
}
}
private void checkAccess(BrowserProfile entity) {
if (ObjectUtil.isNull(entity)) {
throw new ServiceException("环境数据不存在");
}
if (!isSystemAdmin() && !ObjectUtil.equal(LoginHelper.getUserId(), entity.getUserId())) {
throw new ServiceException("无权限操作该环境数据");
}
}
private void checkAccess(BrowserFingerprint entity) {
if (ObjectUtil.isNull(entity)) {
throw new ServiceException("指纹数据不存在");
}
if (!isSystemAdmin() && !ObjectUtil.equal(LoginHelper.getUserId(), entity.getUserId())) {
throw new ServiceException("无权限操作该指纹数据");
}
}
private boolean isSystemAdmin() {
return LoginHelper.isAdmin() && LoginHelper.getUserType() == UserType.SYS_USER;
}
private void enrichMemberInfo(List<BrowserProfileVo> rows) {
if (CollUtil.isEmpty(rows)) {
return;
}
List<Long> memberIds = StreamUtils.toList(rows, BrowserProfileVo::getUserId);
Map<Long, BrowserMemberUser> memberMap = StreamUtils.toMap(
memberUserMapper.selectBatchIds(memberIds),
BrowserMemberUser::getMemberId,
member -> member
);
rows.forEach(item -> {
BrowserMemberUser member = memberMap.get(item.getUserId());
if (ObjectUtil.isNotNull(member)) {
item.setMemberUsername(member.getUsername());
item.setMemberNickName(member.getNickName());
}
});
}
private void enrichPlatformInfo(List<BrowserProfileVo> rows) {
if (CollUtil.isEmpty(rows)) {
return;
}
Set<Long> platformIds = StreamUtils.toSet(rows, BrowserProfileVo::getPlatformId);
platformIds.remove(null);
Map<Long, BrowserPlatform> platformMap = StreamUtils.toMap(
platformIds.isEmpty() ? CollUtil.newArrayList() : platformMapper.selectBatchIds(platformIds),
BrowserPlatform::getPlatformId,
item -> item
);
String iconBaseUrl = BrowserPlatformServiceImpl.normalizeBaseUrl(
configService.selectConfigByKey(BrowserPlatformServiceImpl.ICON_BASE_URL_KEY)
);
rows.forEach(item -> {
BrowserPlatform platform = platformMap.get(item.getPlatformId());
if (ObjectUtil.isNotNull(platform)) {
item.setPlatform(platform.getPlatformName());
item.setPlatformWebsiteUrl(platform.getWebsiteUrl());
item.setPlatformIconFileName(platform.getIconFileName());
item.setPlatformIconUrl(BrowserPlatformServiceImpl.buildIconUrl(iconBaseUrl, platform.getIconFileName()));
}
item.setResolvedWebsiteUrl(resolveWebsiteUrl(item.getCustomWebsiteUrl(), item.getPlatformWebsiteUrl()));
});
}
private boolean checkNameUnique(BrowserProfile entity) {
long profileId = ObjectUtil.isNull(entity.getProfileId()) ? -1L : entity.getProfileId();
boolean exist = baseMapper.exists(new LambdaQueryWrapper<BrowserProfile>()
.eq(BrowserProfile::getUserId, entity.getUserId())
.eq(BrowserProfile::getProfileName, entity.getProfileName())
.ne(ObjectUtil.isNotNull(entity.getProfileId()), BrowserProfile::getProfileId, profileId));
return !exist;
}
private BrowserProfile buildProfileEntity(BrowserProfileBo bo, BrowserProfile oldProfile) {
BrowserProfile entity = BeanUtil.toBean(bo, BrowserProfile.class);
BrowserProfileGroup group = resolveProfileGroup(bo, oldProfile);
entity.setGroupId(group.getGroupId());
entity.setGroupName(group.getGroupName());
if (ObjectUtil.isNotNull(oldProfile)) {
entity.setProfileId(oldProfile.getProfileId());
entity.setFingerprintId(oldProfile.getFingerprintId());
entity.setLastLaunchTime(oldProfile.getLastLaunchTime());
}
BrowserPlatform platform = resolvePlatform(bo.getPlatformId());
if (ObjectUtil.isNotNull(platform)) {
entity.setPlatformId(platform.getPlatformId());
entity.setPlatform(platform.getPlatformName());
entity.setCustomWebsiteUrl(null);
} else {
String customWebsiteUrl = normalizeOptionalWebsiteUrl(bo.getCustomWebsiteUrl());
entity.setPlatformId(null);
entity.setPlatform(StringUtils.isBlank(bo.getPlatform()) ? "其它" : StringUtils.trim(bo.getPlatform()));
entity.setCustomWebsiteUrl(customWebsiteUrl);
}
entity.setBrowserOsType(StringUtils.lowerCase(StringUtils.trim(entity.getBrowserOsType())));
entity.setBrowserArchType(StringUtils.lowerCase(StringUtils.trim(entity.getBrowserArchType())));
entity.setBrowserVersion(resolveBrowserVersion(entity));
BrowserProxy proxy = resolveProxy(bo.getProxyId());
if (ObjectUtil.isNull(proxy)) {
entity.setProxyId(null);
entity.setProxyName(null);
entity.setProxyType(null);
entity.setProxyHost(null);
entity.setProxyPort(null);
} else {
entity.setProxyId(proxy.getProxyId());
entity.setProxyName(proxy.getProxyName());
entity.setProxyType(proxy.getProxyType());
entity.setProxyHost(proxy.getHost());
entity.setProxyPort(proxy.getPort());
}
return entity;
}
private int persistProfileUpdate(BrowserProfile profile) {
int rows = baseMapper.updateById(profile);
if (ObjectUtil.isNull(profile.getProxyId())) {
rows += baseMapper.update(
null,
new LambdaUpdateWrapper<BrowserProfile>()
.eq(BrowserProfile::getProfileId, profile.getProfileId())
.set(BrowserProfile::getProxyId, null)
.set(BrowserProfile::getProxyName, null)
);
}
return rows;
}
private BrowserProfileGroup resolveProfileGroup(BrowserProfileBo bo, BrowserProfile oldProfile) {
Long userId = ObjectUtil.isNotNull(oldProfile) ? oldProfile.getUserId() : LoginHelper.getUserId();
Long groupId = bo.getGroupId();
String groupName = bo.getGroupName();
if (ObjectUtil.isNull(groupId) && StringUtils.isBlank(groupName) && ObjectUtil.isNotNull(oldProfile)) {
groupId = oldProfile.getGroupId();
groupName = oldProfile.getGroupName();
}
return profileGroupService.resolveGroupForProfile(userId, groupId, groupName);
}
private void prepareGroupsForQuery(BrowserProfileBo bo) {
if (!isSystemAdmin()) {
profileGroupService.prepareGroupsForUser(LoginHelper.getUserId());
return;
}
if (ObjectUtil.isNotNull(bo.getUserId())) {
profileGroupService.prepareGroupsForUser(bo.getUserId());
}
}
private BrowserFingerprint buildFingerprintEntity(BrowserFingerprintBo bo, BrowserProfile profile, BrowserFingerprint oldFingerprint) {
BrowserFingerprint entity = BeanUtil.toBean(bo, BrowserFingerprint.class);
entity.setBrowserFamily(StringUtils.blankToDefault(profile.getBrowserEngine(), "chromium"));
entity.setBrowserVersion(profile.getBrowserVersion());
entity.setGeoMode(StringUtils.defaultIfBlank(entity.getGeoMode(), "auto"));
entity.setProfileId(profile.getProfileId());
entity.setUserId(LoginHelper.getUserId());
if (ObjectUtil.isNotNull(oldFingerprint)) {
checkAccess(oldFingerprint);
entity.setFingerprintId(oldFingerprint.getFingerprintId());
} else {
entity.setFingerprintId(null);
}
return entity;
}
private String resolveBrowserVersion(BrowserProfile profile) {
String version = StringUtils.trim(profile.getBrowserVersion());
if (StringUtils.isNotBlank(version)) {
return version;
}
if (StringUtils.isAnyBlank(profile.getBrowserEngine(), profile.getBrowserOsType(), profile.getBrowserArchType())) {
return version;
}
BrowserKernelPackage kernelPackage = kernelPackageMapper.selectOne(new LambdaQueryWrapper<BrowserKernelPackage>()
.eq(BrowserKernelPackage::getBrowserEngine, profile.getBrowserEngine())
.eq(BrowserKernelPackage::getOsType, profile.getBrowserOsType())
.eq(BrowserKernelPackage::getArchType, profile.getBrowserArchType())
.eq(BrowserKernelPackage::getIsDefault, "1")
.eq(BrowserKernelPackage::getStatus, "0")
.last("limit 1"));
return ObjectUtil.isNull(kernelPackage) ? version : kernelPackage.getBrowserVersion();
}
private BrowserProxy resolveProxy(Long proxyId) {
if (ObjectUtil.isNull(proxyId)) {
return null;
}
BrowserProxy proxy = proxyMapper.selectById(proxyId);
if (ObjectUtil.isNull(proxy)) {
throw new ServiceException("代理数据不存在");
}
if (!isSystemAdmin() && !ObjectUtil.equal(LoginHelper.getUserId(), proxy.getUserId())) {
throw new ServiceException("无权限使用该代理");
}
return proxy;
}
private BrowserFingerprint resolveFingerprint(BrowserProfile profile) {
if (ObjectUtil.isNull(profile.getFingerprintId())) {
return fingerprintMapper.selectOne(new LambdaQueryWrapper<BrowserFingerprint>()
.eq(BrowserFingerprint::getUserId, profile.getUserId())
.eq(BrowserFingerprint::getProfileId, profile.getProfileId())
.last("limit 1"));
}
return fingerprintMapper.selectById(profile.getFingerprintId());
}
private BrowserPlatform resolvePlatform(Long platformId) {
if (ObjectUtil.isNull(platformId)) {
return null;
}
BrowserPlatform platform = platformMapper.selectById(platformId);
if (ObjectUtil.isNull(platform)) {
throw new ServiceException("平台数据不存在");
}
return platform;
}
private String normalizeOptionalWebsiteUrl(String value) {
String normalized = StringUtils.trim(value);
if (StringUtils.isBlank(normalized)) {
return null;
}
return BrowserPlatformServiceImpl.normalizeWebsiteUrl(normalized, "自定义网站地址");
}
private String resolveWebsiteUrl(String customWebsiteUrl, String platformWebsiteUrl) {
if (StringUtils.isNotBlank(customWebsiteUrl)) {
return customWebsiteUrl;
}
String normalized = StringUtils.trim(platformWebsiteUrl);
return StringUtils.isBlank(normalized) ? null : normalized;
}
}
@@ -0,0 +1,390 @@
package com.ruoyi.browser.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.maxmind.db.CHMCache;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.AddressNotFoundException;
import com.maxmind.geoip2.model.CountryResponse;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Subdivision;
import com.maxmind.geoip2.model.CityResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.browser.domain.BrowserProxy;
import com.ruoyi.browser.domain.bo.BrowserProxyBo;
import com.ruoyi.browser.domain.vo.BrowserProxyVo;
import com.ruoyi.browser.mapper.BrowserProxyMapper;
import com.ruoyi.browser.service.IBrowserProxyService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import javax.annotation.PreDestroy;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.List;
@RequiredArgsConstructor
@Service
public class BrowserProxyServiceImpl implements IBrowserProxyService {
private final BrowserProxyMapper baseMapper;
@Value("${browser.geoip-db-path:}")
private String geoIpDbPath;
private volatile DatabaseReader geoIpReader;
@Override
public TableDataInfo<BrowserProxyVo> queryPageList(BrowserProxyBo bo, PageQuery pageQuery) {
Page<BrowserProxyVo> result = baseMapper.selectVoPage(pageQuery.build(), buildQueryWrapper(bo));
return TableDataInfo.build(result);
}
@Override
public BrowserProxyVo queryById(Long proxyId) {
BrowserProxyVo vo = baseMapper.selectVoById(proxyId);
checkAccess(vo);
return vo;
}
@Override
public Boolean insertByBo(BrowserProxyBo bo) {
BrowserProxy entity = BeanUtil.toBean(bo, BrowserProxy.class);
entity.setUserId(LoginHelper.getUserId());
normalizeProxy(entity);
if (!checkUnique(entity)) {
throw new ServiceException("代理名称已存在");
}
return baseMapper.insert(entity) > 0;
}
@Override
public Boolean updateByBo(BrowserProxyBo bo) {
BrowserProxy entity = BeanUtil.toBean(bo, BrowserProxy.class);
BrowserProxy old = baseMapper.selectById(entity.getProxyId());
checkAccess(old);
entity.setUserId(old.getUserId());
normalizeProxy(entity, old);
if (!checkUnique(entity)) {
throw new ServiceException("代理名称已存在");
}
return baseMapper.updateById(entity) > 0;
}
@Override
public Boolean refreshGeoById(Long proxyId) {
BrowserProxy entity = baseMapper.selectById(proxyId);
checkAccess(entity);
normalizeProxyGeo(entity, null);
return baseMapper.updateById(entity) > 0;
}
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
for (Long id : ids) {
checkAccess(baseMapper.selectById(id));
}
return baseMapper.deleteBatchIds(ids) > 0;
}
private LambdaQueryWrapper<BrowserProxy> buildQueryWrapper(BrowserProxyBo bo) {
LambdaQueryWrapper<BrowserProxy> lqw = new LambdaQueryWrapper<>();
Long userId = LoginHelper.getUserId();
if (isSystemAdmin()) {
lqw.eq(ObjectUtil.isNotNull(bo.getUserId()), BrowserProxy::getUserId, bo.getUserId());
} else {
lqw.eq(BrowserProxy::getUserId, userId);
}
lqw.like(StringUtils.isNotBlank(bo.getProxyName()), BrowserProxy::getProxyName, bo.getProxyName());
lqw.eq(StringUtils.isNotBlank(bo.getProxyType()), BrowserProxy::getProxyType, bo.getProxyType());
lqw.eq(StringUtils.isNotBlank(bo.getGeoCountry()), BrowserProxy::getGeoCountry, bo.getGeoCountry());
lqw.like(StringUtils.isNotBlank(bo.getGeoRegion()), BrowserProxy::getGeoRegion, bo.getGeoRegion());
lqw.like(StringUtils.isNotBlank(bo.getGeoCity()), BrowserProxy::getGeoCity, bo.getGeoCity());
lqw.eq(StringUtils.isNotBlank(bo.getStatus()), BrowserProxy::getStatus, bo.getStatus());
return lqw;
}
private void checkAccess(BrowserProxyVo vo) {
if (ObjectUtil.isNull(vo)) {
throw new ServiceException("代理数据不存在");
}
if (!isSystemAdmin() && !ObjectUtil.equal(LoginHelper.getUserId(), vo.getUserId())) {
throw new ServiceException("无权限访问该代理数据");
}
}
private void checkAccess(BrowserProxy entity) {
if (ObjectUtil.isNull(entity)) {
throw new ServiceException("代理数据不存在");
}
if (!isSystemAdmin() && !ObjectUtil.equal(LoginHelper.getUserId(), entity.getUserId())) {
throw new ServiceException("无权限操作该代理数据");
}
}
private boolean isSystemAdmin() {
return LoginHelper.isAdmin() && LoginHelper.getUserType() == UserType.SYS_USER;
}
private void normalizeProxy(BrowserProxy entity) {
normalizeProxy(entity, null);
}
private void normalizeProxy(BrowserProxy entity, BrowserProxy old) {
String proxyType = StringUtils.blankToDefault(entity.getProxyType(), "").trim().toLowerCase();
entity.setProxyType(proxyType);
entity.setProxyName(StringUtils.trim(entity.getProxyName()));
entity.setHost(StringUtils.trim(entity.getHost()));
entity.setUsername(StringUtils.trim(entity.getUsername()));
if ("direct".equals(proxyType)) {
entity.setHost(null);
entity.setPort(null);
entity.setGeoCountry(null);
entity.setGeoRegion(null);
entity.setGeoCity(null);
entity.setUsername(null);
entity.setPasswordEncrypted(null);
return;
}
if (!("http".equals(proxyType) || "https".equals(proxyType) || "socks5".equals(proxyType))) {
throw new ServiceException("代理类型仅支持 direct/http/https/socks5");
}
if (StringUtils.isBlank(entity.getHost())) {
throw new ServiceException("IP代理模式下代理主机不能为空");
}
if (ObjectUtil.isNull(entity.getPort())) {
throw new ServiceException("IP代理模式下代理端口不能为空");
}
normalizeProxyGeo(entity, old);
}
private boolean checkUnique(BrowserProxy entity) {
long proxyId = ObjectUtil.isNull(entity.getProxyId()) ? -1L : entity.getProxyId();
return !baseMapper.exists(new LambdaQueryWrapper<BrowserProxy>()
.eq(BrowserProxy::getUserId, entity.getUserId())
.eq(BrowserProxy::getProxyName, entity.getProxyName())
.ne(ObjectUtil.isNotNull(entity.getProxyId()), BrowserProxy::getProxyId, proxyId));
}
private void normalizeProxyGeo(BrowserProxy entity, BrowserProxy old) {
GeoInfo fallback = GeoInfo.fromEntity(old != null ? old : entity);
GeoInfo resolved = resolveGeoInfo(entity.getHost(), fallback);
entity.setGeoCountry(resolved.geoCountry);
entity.setGeoRegion(resolved.geoRegion);
entity.setGeoCity(resolved.geoCity);
}
private GeoInfo resolveGeoInfo(String host, GeoInfo fallback) {
GeoInfo normalizedFallback = GeoInfo.normalized(fallback);
if (StringUtils.isBlank(host)) {
return normalizedFallback;
}
try {
DatabaseReader reader = getGeoIpReader();
if (ObjectUtil.isNull(reader)) {
return normalizedFallback;
}
InetAddress address = resolveHostAddress(host);
if (ObjectUtil.isNull(address)) {
return normalizedFallback;
}
try {
CityResponse response = reader.city(address);
return GeoInfo.fromResponse(response, normalizedFallback);
} catch (UnsupportedOperationException ignored) {
CountryResponse response = reader.country(address);
return GeoInfo.fromCountryResponse(response, normalizedFallback);
}
} catch (AddressNotFoundException ignored) {
return normalizedFallback;
} catch (Exception ignored) {
return normalizedFallback;
}
}
private InetAddress resolveHostAddress(String host) {
try {
InetAddress[] addresses = InetAddress.getAllByName(host);
if (addresses == null || addresses.length == 0) {
return null;
}
for (InetAddress address : addresses) {
if (address instanceof Inet6Address) {
return address;
}
if (StringUtils.equals(host, address.getHostAddress())) {
return address;
}
}
return addresses[0];
} catch (UnknownHostException ignored) {
return null;
}
}
private DatabaseReader getGeoIpReader() {
if (ObjectUtil.isNotNull(geoIpReader)) {
return geoIpReader;
}
synchronized (this) {
if (ObjectUtil.isNotNull(geoIpReader)) {
return geoIpReader;
}
try {
File dbFile = resolveGeoIpDbFile();
if (ObjectUtil.isNotNull(dbFile) && dbFile.exists() && dbFile.isFile()) {
geoIpReader = new DatabaseReader.Builder(dbFile)
.withCache(new CHMCache())
.build();
return geoIpReader;
}
InputStream inputStream = resolveGeoIpDbStream();
if (ObjectUtil.isNull(inputStream)) {
return null;
}
geoIpReader = new DatabaseReader.Builder(inputStream)
.withCache(new CHMCache())
.build();
return geoIpReader;
} catch (IOException ignored) {
return null;
}
}
}
private File resolveGeoIpDbFile() {
if (StringUtils.isNotBlank(geoIpDbPath)) {
return new File(geoIpDbPath.trim());
}
String[] candidates = {
"GeoLite2-City.mmdb",
"data/GeoLite2-City.mmdb",
"geoip/GeoLite2-City.mmdb",
"resources/GeoLite2-City.mmdb",
"GeoLite2-Country.mmdb",
"data/GeoLite2-Country.mmdb",
"geoip/GeoLite2-Country.mmdb",
"resources/GeoLite2-Country.mmdb"
};
for (String candidate : candidates) {
File file = new File(candidate);
if (file.exists() && file.isFile()) {
return file;
}
}
return null;
}
private InputStream resolveGeoIpDbStream() throws IOException {
String[] candidates = {
"GeoLite2-City.mmdb",
"GeoLite2-Country.mmdb"
};
for (String candidate : candidates) {
ClassPathResource resource = new ClassPathResource(candidate);
if (resource.exists()) {
return resource.getInputStream();
}
}
return null;
}
@PreDestroy
public void destroy() {
if (ObjectUtil.isNull(geoIpReader)) {
return;
}
try {
geoIpReader.close();
} catch (IOException ignored) {
// ignore close failure
}
}
private static final class GeoInfo {
private final String geoCountry;
private final String geoRegion;
private final String geoCity;
private GeoInfo(String geoCountry, String geoRegion, String geoCity) {
this.geoCountry = geoCountry;
this.geoRegion = geoRegion;
this.geoCity = geoCity;
}
private static GeoInfo fromEntity(BrowserProxy entity) {
if (ObjectUtil.isNull(entity)) {
return empty();
}
return new GeoInfo(entity.getGeoCountry(), entity.getGeoRegion(), entity.getGeoCity());
}
private static GeoInfo fromResponse(CityResponse response, GeoInfo fallback) {
if (ObjectUtil.isNull(response)) {
return fallback;
}
Country country = response.getCountry();
List<Subdivision> subdivisions = response.getSubdivisions();
City city = response.getCity();
String geoCountry = ObjectUtil.isNull(country) ? fallback.geoCountry : fallback.normalizeCountryCode(country.getIsoCode());
String geoRegion = CollUtil.isEmpty(subdivisions)
? fallback.geoRegion
: fallback.normalizeGeoText(subdivisions.get(0).getName());
String geoCity = ObjectUtil.isNull(city) ? fallback.geoCity : fallback.normalizeGeoText(city.getName());
return new GeoInfo(geoCountry, geoRegion, geoCity);
}
private static GeoInfo fromCountryResponse(CountryResponse response, GeoInfo fallback) {
if (ObjectUtil.isNull(response)) {
return fallback;
}
Country country = response.getCountry();
String geoCountry = ObjectUtil.isNull(country) ? fallback.geoCountry : fallback.normalizeCountryCode(country.getIsoCode());
return new GeoInfo(geoCountry, fallback.geoRegion, fallback.geoCity);
}
private static GeoInfo normalized(GeoInfo info) {
GeoInfo source = ObjectUtil.defaultIfNull(info, empty());
return new GeoInfo(
source.normalizeCountryCode(source.geoCountry),
source.normalizeGeoText(source.geoRegion),
source.normalizeGeoText(source.geoCity)
);
}
private static GeoInfo empty() {
return new GeoInfo(null, null, null);
}
private String normalizeCountryCode(String value) {
if (StringUtils.isBlank(value)) {
return null;
}
return value.trim().toUpperCase();
}
private String normalizeGeoText(String value) {
if (StringUtils.isBlank(value)) {
return null;
}
return value.trim();
}
}
}
@@ -0,0 +1,47 @@
package com.ruoyi.browser.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.browser.domain.BrowserRuntimeRecord;
import com.ruoyi.browser.mapper.BrowserRuntimeRecordMapper;
import com.ruoyi.browser.service.IBrowserRuntimeRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Date;
@RequiredArgsConstructor
@Service
public class BrowserRuntimeRecordServiceImpl implements IBrowserRuntimeRecordService {
private final BrowserRuntimeRecordMapper baseMapper;
@Override
public void recordLaunch(Long userId, Long profileId, Integer pid, Integer port, String runtimePath, String profileDir) {
BrowserRuntimeRecord record = new BrowserRuntimeRecord();
record.setUserId(userId);
record.setProfileId(profileId);
record.setPid(pid);
record.setPort(port);
record.setStatus("0");
record.setStartedAt(new Date());
record.setRuntimePath(runtimePath);
record.setProfileDir(profileDir);
baseMapper.insert(record);
}
@Override
public void recordClose(Long userId, Long profileId) {
BrowserRuntimeRecord record = baseMapper.selectOne(new LambdaQueryWrapper<BrowserRuntimeRecord>()
.eq(BrowserRuntimeRecord::getUserId, userId)
.eq(BrowserRuntimeRecord::getProfileId, profileId)
.eq(BrowserRuntimeRecord::getStatus, "0")
.orderByDesc(BrowserRuntimeRecord::getCreateTime)
.last("limit 1"));
if (record == null) {
return;
}
record.setStatus("1");
record.setStoppedAt(new Date());
baseMapper.updateById(record);
}
}
@@ -0,0 +1,292 @@
package com.ruoyi.browser.service.impl;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.ruoyi.browser.domain.BrowserPlatform;
import com.ruoyi.browser.domain.vo.BrowserKernelPackageVo;
import com.ruoyi.browser.domain.vo.BrowserProfileVo;
import com.ruoyi.browser.domain.vo.BrowserFingerprintVo;
import com.ruoyi.browser.domain.vo.BrowserProxyVo;
import com.ruoyi.browser.domain.vo.BrowserRuntimeVo;
import com.ruoyi.browser.mapper.BrowserFingerprintMapper;
import com.ruoyi.browser.mapper.BrowserPlatformMapper;
import com.ruoyi.browser.mapper.BrowserProfileMapper;
import com.ruoyi.browser.mapper.BrowserProxyMapper;
import com.ruoyi.browser.service.IBrowserKernelPackageService;
import com.ruoyi.browser.service.IBrowserRuntimeService;
import com.ruoyi.browser.service.IBrowserRuntimeRecordService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
@RequiredArgsConstructor
@Service
public class BrowserRuntimeServiceImpl implements IBrowserRuntimeService {
private final BrowserProfileMapper profileMapper;
private final BrowserProxyMapper proxyMapper;
private final BrowserFingerprintMapper fingerprintMapper;
private final BrowserPlatformMapper platformMapper;
private final IBrowserKernelPackageService kernelPackageService;
private final IBrowserRuntimeRecordService runtimeRecordService;
@Value("${browser.local-controller-url:http://127.0.0.1:8001}")
private String localControllerUrl;
@Value("${browser.chromium-runtime-path:}")
private String chromiumRuntimePath;
@Value("${browser.camoufox-runtime-path:}")
private String camoufoxRuntimePath;
@Override
public BrowserProfileVo launch(Long profileId) {
BrowserProfileVo profileVo = queryProfile(profileId);
BrowserRuntimeVo payload = buildLaunchPayload(profileVo);
HttpResponse response = HttpRequest.post(localControllerUrl + "/profiles/" + profileId + "/launch")
.body(JSONUtil.toJsonStr(toLocalControllerPayload(payload)))
.contentType("application/json")
.timeout(15000)
.execute();
if (!response.isOk()) {
throw new ServiceException("启动本地浏览器失败: " + response.body());
}
cn.hutool.json.JSONObject body = JSONUtil.parseObj(response.body());
cn.hutool.json.JSONObject data = body.getJSONObject("data");
if (data == null) {
throw new ServiceException("本地浏览器启动返回数据为空");
}
String runtimePath = data.getStr("runtime_path");
String profileDir = data.getStr("profile_dir");
runtimeRecordService.recordLaunch(
profileVo.getUserId(),
profileId,
data.getInt("pid"),
data.getInt("port"),
ObjectUtil.isNotEmpty(runtimePath) ? runtimePath : payload.getRuntimePath(),
ObjectUtil.isNotEmpty(profileDir) ? profileDir : payload.getProfileDir()
);
return profileVo;
}
@Override
public boolean close(Long profileId) {
HttpResponse response = HttpRequest.post(localControllerUrl + "/profiles/" + profileId + "/close")
.timeout(15000)
.execute();
if (!response.isOk()) {
return false;
}
cn.hutool.json.JSONObject body = JSONUtil.parseObj(response.body());
boolean closed = body.getBool("ok", false);
if (closed) {
BrowserProfileVo profileVo = queryProfile(profileId);
runtimeRecordService.recordClose(profileVo.getUserId(), profileId);
}
return closed;
}
@Override
public List<Object> running() {
HttpResponse response = HttpRequest.get(localControllerUrl + "/profiles/running")
.timeout(15000)
.execute();
if (!response.isOk()) {
return new ArrayList<>();
}
return JSONUtil.parseObj(response.body()).getJSONArray("items").toList(Object.class);
}
@Override
public BrowserRuntimeVo buildLaunchPayload(BrowserProfileVo profileVo) {
BrowserRuntimeVo vo = new BrowserRuntimeVo();
vo.setProfileId(String.valueOf(profileVo.getProfileId()));
vo.setBrowserEngine(profileVo.getBrowserEngine());
vo.setProfileDir(buildProfileDir(profileVo));
vo.setStartUrl(resolveStartUrl(profileVo));
vo.setHeadless(false);
vo.setBrowserArgs(new ArrayList<>());
vo.setRuntimePath(resolveRuntimePath(profileVo.getBrowserEngine()));
vo.setKernelPackage(buildKernelPackage(profileVo));
BrowserProxyVo proxy = resolveProxy(profileVo);
BrowserFingerprintVo fingerprint = resolveFingerprint(profileVo);
vo.setProxy(buildProxy(proxy));
vo.setFingerprint(buildFingerprint(profileVo, fingerprint));
vo.setProxyType(proxy == null ? null : proxy.getProxyType());
vo.setProxyHost(proxy == null ? null : proxy.getHost());
vo.setProxyPort(proxy == null ? null : proxy.getPort());
return vo;
}
private BrowserProxyVo resolveProxy(BrowserProfileVo profileVo) {
if (ObjectUtil.isNull(profileVo.getProxyId())) {
return null;
}
BrowserProxyVo proxy = proxyMapper.selectVoById(profileVo.getProxyId());
if (ObjectUtil.isNull(proxy)) {
throw new ServiceException("代理配置不存在");
}
if (!LoginHelper.isAdmin() && !ObjectUtil.equal(LoginHelper.getUserId(), proxy.getUserId())) {
throw new ServiceException("无权限使用该代理配置");
}
return proxy;
}
private BrowserProfileVo queryProfile(Long profileId) {
BrowserProfileVo profileVo = profileMapper.selectVoById(profileId);
if (ObjectUtil.isNull(profileVo)) {
throw new ServiceException("环境数据不存在");
}
if (!LoginHelper.isAdmin() && !ObjectUtil.equal(LoginHelper.getUserId(), profileVo.getUserId())) {
throw new ServiceException("无权限访问该环境数据");
}
if (ObjectUtil.isNotNull(profileVo.getPlatformId())) {
BrowserPlatform platform = platformMapper.selectById(profileVo.getPlatformId());
if (ObjectUtil.isNotNull(platform)) {
profileVo.setPlatform(platform.getPlatformName());
profileVo.setPlatformWebsiteUrl(platform.getWebsiteUrl());
}
}
if (ObjectUtil.isNotEmpty(profileVo.getCustomWebsiteUrl())) {
profileVo.setResolvedWebsiteUrl(profileVo.getCustomWebsiteUrl());
} else {
profileVo.setResolvedWebsiteUrl(profileVo.getPlatformWebsiteUrl());
}
return profileVo;
}
private BrowserFingerprintVo resolveFingerprint(BrowserProfileVo profileVo) {
if (ObjectUtil.isNull(profileVo.getFingerprintId())) {
return null;
}
BrowserFingerprintVo fingerprint = fingerprintMapper.selectVoById(profileVo.getFingerprintId());
if (ObjectUtil.isNull(fingerprint)) {
throw new ServiceException("指纹配置不存在");
}
if (!LoginHelper.isAdmin() && !ObjectUtil.equal(LoginHelper.getUserId(), fingerprint.getUserId())) {
throw new ServiceException("无权限使用该指纹配置");
}
return fingerprint;
}
private Map<String, Object> buildProxy(BrowserProxyVo proxy) {
if (ObjectUtil.isNull(proxy)) {
return null;
}
Map<String, Object> result = new HashMap<>();
result.put("proxyId", proxy.getProxyId());
result.put("proxyName", proxy.getProxyName());
result.put("proxyType", proxy.getProxyType());
result.put("host", proxy.getHost());
result.put("port", proxy.getPort());
result.put("geoCountry", proxy.getGeoCountry());
result.put("username", proxy.getUsername());
return result;
}
private Map<String, Object> buildFingerprint(BrowserProfileVo profileVo, BrowserFingerprintVo fingerprint) {
if (ObjectUtil.isNull(fingerprint)) {
return null;
}
Map<String, Object> result = new HashMap<>();
result.put("fingerprintId", fingerprint.getFingerprintId());
result.put("browserFamily", fingerprint.getBrowserFamily());
result.put("browserVersion", fingerprint.getBrowserVersion());
result.put("userAgent", fingerprint.getUserAgent());
result.put("geoMode", fingerprint.getGeoMode());
result.put("locale", fingerprint.getLocale());
result.put("timezone", fingerprint.getTimezone());
result.put("geoCountry", fingerprint.getGeoCountry());
result.put("screenWidth", fingerprint.getScreenWidth());
result.put("screenHeight", fingerprint.getScreenHeight());
result.put("webRtcPolicy", fingerprint.getWebRtcPolicy());
result.put("canvasPolicy", fingerprint.getCanvasPolicy());
result.put("webglPolicy", fingerprint.getWebglPolicy());
result.put("audioPolicy", fingerprint.getAudioPolicy());
result.put("fontPolicy", fingerprint.getFontPolicy());
result.put("cookieConfig", fingerprint.getCookieConfig());
result.put("payload", fingerprint.getEncryptedPayload());
result.put("profileId", profileVo.getProfileId());
return result;
}
private Map<String, Object> buildKernelPackage(BrowserProfileVo profileVo) {
BrowserKernelPackageVo kernelPackage = kernelPackageService.resolvePackage(
profileVo.getBrowserEngine(),
profileVo.getBrowserVersion(),
profileVo.getBrowserOsType(),
profileVo.getBrowserArchType()
);
if (ObjectUtil.isNull(kernelPackage)) {
return null;
}
Map<String, Object> result = new HashMap<>();
result.put("kernelId", kernelPackage.getKernelId());
result.put("browserEngine", kernelPackage.getBrowserEngine());
result.put("browserVersion", kernelPackage.getBrowserVersion());
result.put("fullVersion", kernelPackage.getFullVersion());
result.put("osType", kernelPackage.getOsType());
result.put("archType", kernelPackage.getArchType());
result.put("packageUrl", kernelPackage.getPackageUrl());
result.put("packageSha256", kernelPackage.getPackageSha256());
result.put("archiveRootDir", kernelPackage.getArchiveRootDir());
result.put("executablePath", kernelPackage.getExecutablePath());
return result;
}
private String buildProfileDir(BrowserProfileVo profileVo) {
return "data/profiles/" + profileVo.getUserId() + "/" + profileVo.getProfileId() + "/" + profileVo.getBrowserEngine();
}
private String resolveRuntimePath(String engine) {
if ("firefox".equalsIgnoreCase(engine)) {
return ObjectUtil.isNotEmpty(camoufoxRuntimePath) ? camoufoxRuntimePath : null;
}
return ObjectUtil.isNotEmpty(chromiumRuntimePath) ? chromiumRuntimePath : null;
}
private String resolveStartUrl(BrowserProfileVo profileVo) {
if ("1".equals(profileVo.getLaunchDiagnostics())) {
return localControllerUrl + "/diagnostics/fingerprint";
}
if (ObjectUtil.isNotEmpty(profileVo.getResolvedWebsiteUrl())) {
return profileVo.getResolvedWebsiteUrl();
}
if (ObjectUtil.isNotEmpty(profileVo.getCustomWebsiteUrl())) {
return profileVo.getCustomWebsiteUrl();
}
if (ObjectUtil.isNotEmpty(profileVo.getPlatformWebsiteUrl())) {
return profileVo.getPlatformWebsiteUrl();
}
return "about:blank";
}
private Map<String, Object> toLocalControllerPayload(BrowserRuntimeVo payload) {
Map<String, Object> result = new HashMap<>();
result.put("profile_id", payload.getProfileId());
result.put("browser_engine", payload.getBrowserEngine());
result.put("runtime_path", payload.getRuntimePath());
result.put("profile_dir", payload.getProfileDir());
result.put("start_url", payload.getStartUrl());
result.put("headless", payload.getHeadless());
result.put("browser_args", payload.getBrowserArgs());
result.put("proxy", payload.getProxy());
result.put("fingerprint", payload.getFingerprint());
result.put("kernel_package", payload.getKernelPackage());
result.put("proxy_type", payload.getProxyType());
result.put("proxy_host", payload.getProxyHost());
result.put("proxy_port", payload.getProxyPort());
return result;
}
}
@@ -0,0 +1,63 @@
package com.ruoyi.web.controller.browser;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.browser.domain.bo.BrowserFingerprintBo;
import com.ruoyi.browser.domain.vo.BrowserFingerprintVo;
import com.ruoyi.browser.service.IBrowserFingerprintService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotEmpty;
import java.util.Arrays;
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/browser/fingerprint")
public class BrowserFingerprintController extends BaseController {
private final IBrowserFingerprintService service;
@SaCheckPermission("browser:fingerprint:list")
@GetMapping("/list")
public TableDataInfo<BrowserFingerprintVo> list(@Validated(QueryGroup.class) BrowserFingerprintBo bo, PageQuery pageQuery) {
return service.queryPageList(bo, pageQuery);
}
@SaCheckPermission("browser:fingerprint:query")
@GetMapping("/{fingerprintId}")
public R<BrowserFingerprintVo> getInfo(@PathVariable Long fingerprintId) {
return R.ok(service.queryById(fingerprintId));
}
@SaCheckPermission("browser:fingerprint:add")
@Log(title = "指纹管理", businessType = BusinessType.INSERT)
@PostMapping
public R<Void> add(@Validated(AddGroup.class) @RequestBody BrowserFingerprintBo bo) {
return toAjax(service.insertByBo(bo));
}
@SaCheckPermission("browser:fingerprint:edit")
@Log(title = "指纹管理", businessType = BusinessType.UPDATE)
@PutMapping
public R<Void> edit(@Validated(EditGroup.class) @RequestBody BrowserFingerprintBo bo) {
return toAjax(service.updateByBo(bo));
}
@SaCheckPermission("browser:fingerprint:remove")
@Log(title = "指纹管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{fingerprintIds}")
public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] fingerprintIds) {
return toAjax(service.deleteWithValidByIds(Arrays.asList(fingerprintIds), true));
}
}

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