Compare commits

...
10 Commits
Author SHA1 Message Date
天爱有情 e7b9fd923b 1.5.5 2026-02-28 09:58:04 +08:00
天爱有情 a7fca6ee57 solon插件暂时无人维护,先考虑单独搬迁项目到另一个仓库 2026-02-10 08:47:28 +08:00
tianai cfab8ce3ac fix: TacBuilder中添加资源只能添加一条的bug 2026-02-09 19:28:56 +08:00
天爱有情 387ed937f8 1.5.4 2026-01-26 16:43:15 +08:00
天爱有情 fbbf3e8204 fix: springboot4的适配。上次代码被覆盖了,重新提交一下。 2026-01-26 11:58:02 +08:00
tianai 655b7faf57 fix: 修复点选验证码图片文字缩放的bug 2026-01-24 18:12:13 +08:00
tianai 356d3ab62c feat: CacheImageCaptchaGenerator支持自定义忽略某些参数不参与校验
fix: 修复TACBuilder.builder无法创建的bug
perf: 优化AnyMap结构
2026-01-24 13:39:30 +08:00
天爱有情 a4f8a99093 增加可配置自定义容错值的选项
cloud.tianai.captcha.generator.common.model.dto.ParamKeyEnum#TOLERANT
2026-01-23 17:24:25 +08:00
天爱有情 16e517c69e 修复资源泄露问题并优化资源管理
- 添加 AutoCloseable 接口实现,支持自动资源释放
   - 修复 Graphics2D、ImageOutputStream 等资源未正确关闭的问题
   - 为 Spring Bean 添加 destroyMethod 配置
   - 添加定时任务线程池的正确关闭逻辑
   - FontCache 添加缓存大小限制防止内存泄露
   - 优化 StandardWordClickImageCaptchaGenerator 代码结构
2026-01-14 17:14:45 +08:00
天爱有情 29279e8c56 修复资源泄露问题并优化资源管理
- 添加 AutoCloseable 接口实现,支持自动资源释放
   - 修复 Graphics2D、ImageOutputStream 等资源未正确关闭的问题
   - 为 Spring Bean 添加 destroyMethod 配置
   - 添加定时任务线程池的正确关闭逻辑
   - FontCache 添加缓存大小限制防止内存泄露
   - 优化 StandardWordClickImageCaptchaGenerator 代码结构
2026-01-14 17:09:59 +08:00
47 changed files with 1613 additions and 924 deletions

No files matched your search

+233
View File
@@ -0,0 +1,233 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
必须用中文回复我
## Project Overview
tianai-captcha (天爱验证码/TAC) is a Java-based behavioral CAPTCHA library supporting multiple verification types:
- **SLIDER**: Slide-to-fit puzzle captcha
- **ROTATE**: Rotation verification captcha
- **CONCAT**: Slide-to-restore captcha
- **WORD_IMAGE_CLICK**: Text-click verification captcha
The project is a multi-module Maven project with Java 8 compatibility.
## Build Commands
```bash
# Build the entire project (skips tests by default)
mvn clean install
# Build without skipping tests
mvn clean install -DskipTests=false
# Build specific module
cd tianai-captcha
mvn clean install
# Package for deployment
mvn clean package
# Generate javadoc
mvn javadoc:javadoc
```
## Testing
```bash
# Run all tests
mvn test
# Run tests for specific module
cd tianai-captcha
mvn test
# Run a specific test class
mvn test -Dtest=TACBuilderTest
# Run a specific test method
mvn test -Dtest=TACBuilderTest#testMethod
```
## Project Structure
### Modules
1. **tianai-captcha** (core module)
- Core captcha generation and validation logic
- Generator implementations for each captcha type
- Resource management system
- Cache and storage abstractions
2. **tianai-captcha-springboot-starter**
- Spring Boot auto-configuration
- Redis integration support
- Configuration properties binding
3. **tianai-captcha-solon-plugin**
- Solon framework integration
4. **tianai-captcha-web-sdk**
- Frontend JavaScript SDK
## Core Architecture
### Key Components
**ImageCaptchaApplication** (cloud.tianai.captcha.application.ImageCaptchaApplication)
- Main entry point for captcha operations
- Handles captcha generation via `generateCaptcha(type)`
- Handles validation via `matching(id, matchParam)`
- Manages lifecycle of generators, validators, and cache
**TACBuilder** (cloud.tianai.captcha.application.TACBuilder)
- Builder pattern for constructing ImageCaptchaApplication
- Fluent API for configuration
- Key methods:
- `addDefaultTemplate()`: Load built-in templates
- `addResource(type, resource)`: Add background images
- `addTemplate(type, resourceMap)`: Add custom templates
- `addFont(resource)`: Add fonts for WORD_IMAGE_CLICK
- `cached(size, waitTime, period, expireTime)`: Enable pre-generation cache
- `setCacheStore(store)`: Set cache implementation (local or distributed)
- `setResourceStore(store)`: Set resource storage
- `setTransform(transform)`: Set image transformation (default: Base64)
### Generator Layer
**MultiImageCaptchaGenerator** (cloud.tianai.captcha.generator.impl.MultiImageCaptchaGenerator)
- Delegates to specific generators based on captcha type
- Manages resource loading and image transformation
**Specific Generators**:
- `StandardSliderImageCaptchaGenerator`: Generates slider puzzles
- `StandardRotateImageCaptchaGenerator`: Generates rotation captchas
- `StandardConcatImageCaptchaGenerator`: Generates slide-to-restore captchas
- `StandardWordClickImageCaptchaGenerator`: Generates text-click captchas
**CacheImageCaptchaGenerator** (cloud.tianai.captcha.generator.impl.CacheImageCaptchaGenerator)
- Wrapper that pre-generates captchas for improved performance
- Configurable cache size and refresh intervals
### Validator Layer
**ImageCaptchaValidator** (cloud.tianai.captcha.validator.ImageCaptchaValidator)
- Interface for captcha validation logic
- Default implementation: `SimpleImageCaptchaValidator`
**BasicCaptchaTrackValidator** (cloud.tianai.captcha.validator.impl.BasicCaptchaTrackValidator)
- Validates mouse/touch track data
- Checks for suspicious behavior patterns
### Resource Management
**ResourceStore** (cloud.tianai.captcha.resource.ResourceStore)
- Abstraction for storing captcha resources (images, templates)
- Implementations:
- `LocalMemoryResourceStore`: In-memory storage
- Custom implementations for distributed scenarios
**ImageCaptchaResourceManager** (cloud.tianai.captcha.resource.ImageCaptchaResourceManager)
- Manages resource loading and retrieval
- Default implementation: `DefaultImageCaptchaResourceManager`
**Resource** (cloud.tianai.captcha.resource.common.model.dto.Resource)
- Represents a resource with type and location
- Types: "classpath", "file", "url"
### Cache Layer
**CacheStore** (cloud.tianai.captcha.cache.CacheStore)
- Abstraction for caching captcha data
- Implementations:
- `LocalCacheStore`: Local in-memory cache
- Redis-based implementation in Spring Boot starter
### Image Transformation
**ImageTransform** (cloud.tianai.captcha.generator.ImageTransform)
- Converts generated images to desired format
- Default: `Base64ImageTransform` (JPG for background, PNG for template)
## Configuration
### Non-Spring Projects
Use TACBuilder to configure:
```java
ImageCaptchaApplication app = TACBuilder.builder()
.addDefaultTemplate()
.addResource("SLIDER", new Resource("classpath", "path/to/image.jpg"))
.cached(20, 5000, 2000, 120000L)
.build();
```
### Spring Boot Projects
Configure via application.yml:
```yaml
captcha:
prefix: captcha # Cache key prefix
expire:
default: 120000 # Default expiration (ms)
WORD_IMAGE_CLICK: 180000 # Type-specific expiration
init-default-resource: false # Load built-in resources
local-cache-enabled: true # Enable pre-generation cache
local-cache-size: 20 # Cache size
local-cache-wait-time: 5000 # Wait time on cache miss (ms)
local-cache-period: 2000 # Cache refresh interval (ms)
font-path: # Font files for WORD_IMAGE_CLICK
- classpath:font/simhei.ttf
```
## Important Constants
**CaptchaTypeConstant** (cloud.tianai.captcha.common.constant.CaptchaTypeConstant)
- `SLIDER`: Slide-to-fit captcha
- `ROTATE`: Rotation captcha
- `CONCAT`: Slide-to-restore captcha
- `WORD_IMAGE_CLICK`: Text-click captcha
**ParamKeyEnum** (cloud.tianai.captcha.generator.common.model.dto.ParamKeyEnum)
- `TOLERANT`: Configurable tolerance value for validation (added in recent commit)
## Key Data Flow
### Generation Flow
1. Client calls `ImageCaptchaApplication.generateCaptcha(type)`
2. `MultiImageCaptchaGenerator` selects appropriate generator
3. Generator loads resources via `ImageCaptchaResourceManager`
4. Generator creates captcha with random parameters
5. `ImageTransform` converts images to Base64 (or custom format)
6. Captcha data cached in `CacheStore` with unique ID
7. Returns `ImageCaptchaVO` with ID and image data
### Validation Flow
1. Client submits ID and track data via `matching(id, matchParam)`
2. Application retrieves cached captcha data by ID
3. `ImageCaptchaValidator` validates track against expected answer
4. `BasicCaptchaTrackValidator` checks track behavior patterns
5. Returns `ApiResponse` with success/failure status
## Extension Points
- **Custom Generators**: Implement `ImageCaptchaGenerator` interface
- **Custom Validators**: Implement `ImageCaptchaValidator` interface
- **Custom Cache**: Implement `CacheStore` (e.g., Redis, Memcached)
- **Custom Resources**: Implement `ResourceStore` for centralized resource management
- **Custom Transform**: Implement `ImageTransform` for different image formats
- **Interceptors**: Implement `CaptchaInterceptor` for pre/post processing
## Recent Changes
- Added support for Spring Boot 4 (commit: db0603a, 7c8730f)
- Fixed resource leak issues (commits: 16e517c, 29279e8)
- Added configurable tolerance value via `ParamKeyEnum.TOLERANT` (commit: a4f8a99)
## Documentation
- Online Demo: http://captcha.tianai.cloud
- Online Documentation: http://doc.captcha.tianai.cloud
- License: MulanPSL-2.0
+1 -2
View File
@@ -12,11 +12,10 @@
<modules>
<module>tianai-captcha</module>
<module>tianai-captcha-springboot-starter</module>
<module>tianai-captcha-solon-plugin</module>
</modules>
<properties>
<revision>1.5.3</revision>
<revision>1.5.5</revision>
<java.version>1.8</java.version>
<!-- 打包跳过单元测试 -->
<skipTests>true</skipTests>
+3 -3
View File
@@ -32,7 +32,7 @@
<dependency>
<groupId>cloud.tianai.captcha</groupId>
<artifactId>tianai-captcha-springboot-starter</artifactId>
<version>1.5.3</version>
<version>1.5.5</version>
</dependency>
```
@@ -109,7 +109,7 @@
<dependency>
<groupId>cloud.tianai.captcha</groupId>
<artifactId>tianai-captcha</artifactId>
<version>1.5.3</version>
<version>1.5.4</version>
</dependency>
```
@@ -167,7 +167,7 @@ public class ApplicationTest {
### 安装
1. 将打包好的`tac`目录放到自己项目中,如果是vue、react等框架,将tac目录放到public目录中、或者放到某个可以访问到地方,比如oss之类的可以被浏览器访问到的地方 (tac下载地址 [https://gitee.com/dromara/tianai-captcha/releases/tag/tianai-captcha-1.5.3](https://gitee.com/dromara/tianai-captcha/releases/tag/tianai-captcha-1.5.3))
1. 将打包好的`tac`目录放到自己项目中,如果是vue、react等框架,将tac目录放到public目录中、或者放到某个可以访问到地方,比如oss之类的可以被浏览器访问到的地方 (tac下载地址 [https://gitee.com/dromara/tianai-captcha/releases/tag/tianai-captcha-1.5.4](https://gitee.com/dromara/tianai-captcha/releases/tag/tianai-captcha-1.5.4))
2. 引入初始化函数 (load.js下载地址 [https://minio.tianai.cloud/public/static/captcha/js/load.min.js](https://minio.tianai.cloud/public/static/captcha/js/load.min.js)) 可自己将load.js下载到本地
-63
View File
@@ -1,63 +0,0 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cloud.tianai.captcha</groupId>
<artifactId>tianai-captcha-parent</artifactId>
<version>${revision}</version>
</parent>
<artifactId>tianai-captcha-solon-plugin</artifactId>
<name>tianai-captcha-solon-plugin</name>
<description>行为验证码的solon插件</description>
<url>https://gitee.com/tianai/tianai-captcha-solon-plugin</url>
<properties>
<solon.version>3.5.2</solon.version>
<maven.compiler.source>8</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<!-- 打包跳过单元测试 -->
<skipTests>true</skipTests>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.noear</groupId>
<artifactId>solon</artifactId>
<version>${solon.version}</version>
</dependency>
<dependency>
<groupId>org.noear</groupId>
<artifactId>solon-web</artifactId>
<version>${solon.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>cloud.tianai.captcha</groupId>
<artifactId>tianai-captcha</artifactId>
<version>${revision}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -1,21 +0,0 @@
package cloud.tianai.captcha.solon;
import cloud.tianai.captcha.solon.config.ImageCaptchaAutoConfiguration;
import cloud.tianai.captcha.solon.properties.CaptchaProperties;
import org.noear.solon.core.AppContext;
import org.noear.solon.core.Plugin;
/**
* 插件启动类
* @Author XT
* @Date 2024.09.03
*/
public class XPluginImp implements Plugin {
@Override
public void start(AppContext context) {
context.beanMake(CaptchaProperties.class);
context.beanMake(ImageCaptchaAutoConfiguration.class);
}
}
@@ -1,95 +0,0 @@
package cloud.tianai.captcha.solon.config;
import cloud.tianai.captcha.application.ImageCaptchaApplication;
import cloud.tianai.captcha.application.TACBuilder;
import cloud.tianai.captcha.cache.CacheStore;
import cloud.tianai.captcha.cache.impl.LocalCacheStore;
import cloud.tianai.captcha.resource.common.model.dto.Resource;
import cloud.tianai.captcha.solon.plugins.secondary.SecondaryVerificationApplication;
import cloud.tianai.captcha.solon.properties.CaptchaProperties;
import cloud.tianai.captcha.solon.service.CaptchaRedisCacheService;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Inject;
import java.util.List;
/**
* @Author XT
* @Date 2024.09.03
*/
@Configuration
public class ImageCaptchaAutoConfiguration {
@Bean
public ImageCaptchaApplication imageCaptchaApplication(CaptchaProperties captchaProperties, @Inject(required = false) CaptchaRedisCacheService cacheService) {
TACBuilder tacBuilder = TACBuilder.builder();
tacBuilder.addDefaultTemplate();
tacBuilder.expire("default", captchaProperties.getExpire());
tacBuilder.prefix(captchaProperties.getPrefix());
// 注入背景图资源
if (captchaProperties.getResources().getAuto()) {
String[] split = captchaProperties.getResources().getAutoType().split(",");
List<String> wordImageClickList = captchaProperties.getResources().getImages();
for (String type : split) {
for (String path : wordImageClickList) {
tacBuilder.addResource(type, new Resource("classpath", path));
}
}
} else {
List<String> wordImageClickList = captchaProperties.getResources().getWORD_IMAGE_CLICK();
if (!wordImageClickList.isEmpty()) {
for (String path : wordImageClickList) {
tacBuilder.addResource("WORD_IMAGE_CLICK", new Resource("classpath", path));
}
}
List<String> concatList = captchaProperties.getResources().getCONCAT();
if (!concatList.isEmpty()) {
for (String path : concatList) {
tacBuilder.addResource("CONCAT", new Resource("classpath", path));
}
}
List<String> sliderList = captchaProperties.getResources().getSLIDER();
if (!sliderList.isEmpty()) {
for (String path : sliderList) {
tacBuilder.addResource("SLIDER", new Resource("classpath", path));
}
}
List<String> rotateList = captchaProperties.getResources().getROTATE();
if (!rotateList.isEmpty()) {
for (String path : rotateList) {
tacBuilder.addResource("ROTATE", new Resource("classpath", path));
}
}
}
// 注入字体包
if (null != captchaProperties.getFontPath()) {
List<String> fontPathList = captchaProperties.getFontPath();
if (!fontPathList.isEmpty()) {
for (String path : fontPathList) {
try {
tacBuilder.addFont(new Resource("classpath", path));
} catch (Exception e) {
throw new RuntimeException("读取字体包失败,path=" + path, e);
}
}
}
}
CacheStore cacheStore = cacheService;
// 注入缓存器
if (null == cacheStore) {
cacheStore = new LocalCacheStore();
}
tacBuilder.setCacheStore(cacheStore);
ImageCaptchaApplication target = tacBuilder.build();
// 二次验证
if (captchaProperties.getSecondary().getEnabled()) {
target = new SecondaryVerificationApplication(target, captchaProperties, cacheStore);
}
return target;
}
}
@@ -1,109 +0,0 @@
package cloud.tianai.captcha.solon.plugins.secondary;
import cloud.tianai.captcha.application.FilterImageCaptchaApplication;
import cloud.tianai.captcha.application.ImageCaptchaApplication;
import cloud.tianai.captcha.application.vo.ImageCaptchaVO;
import cloud.tianai.captcha.cache.CacheStore;
import cloud.tianai.captcha.common.AnyMap;
import cloud.tianai.captcha.common.exception.ImageCaptchaException;
import cloud.tianai.captcha.common.response.ApiResponse;
import cloud.tianai.captcha.solon.properties.CaptchaLimit;
import cloud.tianai.captcha.solon.properties.CaptchaProperties;
import cloud.tianai.captcha.solon.properties.CaptchaSecondary;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import org.noear.solon.core.handle.Context;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @Author XT
* @Date 2024.09.03
*/
public class SecondaryVerificationApplication extends FilterImageCaptchaApplication {
private final CaptchaSecondary prop;
private final CaptchaProperties captchaProperties;
private final CacheStore redisCacheService;
public SecondaryVerificationApplication(ImageCaptchaApplication target, CaptchaProperties captchaProperties, CacheStore redisCacheService) {
super(target);
this.captchaProperties = captchaProperties;
this.prop = captchaProperties.getSecondary();
this.redisCacheService = redisCacheService;
}
@Override
public ApiResponse<ImageCaptchaVO> generateCaptcha(String type) {
// 检查是否每分钟超过限制
CaptchaLimit limit = captchaProperties.getLimit();
if (null != limit && limit.getEnable()) {
Context current = Context.current();
String errLimitKey = getLimitKey(current, "error");
Long errLimit = redisCacheService.getLong(errLimitKey);
if (null != errLimit && errLimit >= limit.getErrorLimit()) {
throw new ImageCaptchaException("验证次数过多,请稍后再试");
}
String reqLimitKey = getLimitKey(current, "req");
Long reqLimit = redisCacheService.getLong(reqLimitKey);
if (null != reqLimit && reqLimit >= limit.getReqLimit()) {
throw new ImageCaptchaException("获取验证码频繁,请稍后再试");
}
redisCacheService.incr(reqLimitKey, 1, 60L, TimeUnit.SECONDS);
}
return super.generateCaptcha(type);
}
@Override
public ApiResponse<?> matching(String id, ImageCaptchaTrack imageCaptchaTrack) {
ApiResponse<?> match = super.matching(id, imageCaptchaTrack);
if (match.isSuccess()) {
// 如果匹配成功, 添加二次验证记录
addSecondaryVerification(id + getRemoteId(Context.current()), imageCaptchaTrack);
} else {
CaptchaLimit limit = captchaProperties.getLimit();
if (null != limit && limit.getEnable()) {
Context current = Context.current();
String limitKey = getLimitKey(current, "error");
redisCacheService.incr(limitKey, 1, 60L, TimeUnit.SECONDS);
}
}
return match;
}
/**
* 二次缓存验证
* @param id id
* @return boolean
*/
public boolean secondaryVerification(String id) {
Map<String, Object> cache = target.getCacheStore().getAndRemoveCache(getKey(id + getRemoteId(Context.current())));
return cache != null;
}
/**
* 添加二次缓存验证记录
* @param id id
* @param imageCaptchaTrack sliderCaptchaTrack
*/
protected void addSecondaryVerification(String id, ImageCaptchaTrack imageCaptchaTrack) {
target.getCacheStore().setCache(getKey(id), new AnyMap(), prop.getExpire(), TimeUnit.MILLISECONDS);
}
protected String getKey(String id) {
return prop.getKeyPrefix().concat(":").concat(id);
}
protected String getLimitKey(Context ctx, String type) {
return prop.getKeyPrefix().concat(":limit:")
.concat(type)
.concat(":")
.concat(getRemoteId(ctx));
}
public static String getRemoteId(Context ctx) {
return ctx.realIp() + ctx.userAgent();
}
}
@@ -1,38 +0,0 @@
package cloud.tianai.captcha.solon.properties;
/**
* @Author XT
* @Date 2024.09.04
*/
public class CaptchaLimit {
private Boolean enable;
private Long reqLimit;
private Long errorLimit;
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
public Long getReqLimit() {
return reqLimit;
}
public void setReqLimit(Long reqLimit) {
this.reqLimit = reqLimit;
}
public Long getErrorLimit() {
return errorLimit;
}
public void setErrorLimit(Long errorLimit) {
this.errorLimit = errorLimit;
}
}
@@ -1,93 +0,0 @@
package cloud.tianai.captcha.solon.properties;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Inject;
import java.util.List;
/**
* @Author XT
* @Date 2024.09.03
*/
@Inject("${captcha}")
@Configuration
public class CaptchaProperties {
/**
* redis 前缀
*/
private String prefix;
/**
* 有效期
*/
private Long expire;
/**
* 字体路径
*/
private List<String> fontPath;
/**
* 资源路径
*/
private CaptchaResource resources;
/**
* 二次验证
*/
private CaptchaSecondary secondary;
/**
* 每分限流
*/
private CaptchaLimit limit;
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public Long getExpire() {
return expire;
}
public void setExpire(Long expire) {
this.expire = expire;
}
public List<String> getFontPath() {
return fontPath;
}
public void setFontPath(List<String> fontPath) {
this.fontPath = fontPath;
}
public CaptchaResource getResources() {
return resources;
}
public void setResources(CaptchaResource resources) {
this.resources = resources;
}
public CaptchaSecondary getSecondary() {
return secondary;
}
public void setSecondary(CaptchaSecondary secondary) {
this.secondary = secondary;
}
public CaptchaLimit getLimit() {
return limit;
}
public void setLimit(CaptchaLimit limit) {
this.limit = limit;
}
}
@@ -1,80 +0,0 @@
package cloud.tianai.captcha.solon.properties;
import java.util.List;
/**
* @Author XT
* @Date 2024.09.03
*/
public class CaptchaResource {
private Boolean auto;
private String autoType;
private List<String> images;
private List<String> SLIDER;
private List<String> WORD_IMAGE_CLICK;
private List<String> ROTATE;
private List<String> CONCAT;
public List<String> getSLIDER() {
return SLIDER;
}
public void setSLIDER(List<String> SLIDER) {
this.SLIDER = SLIDER;
}
public List<String> getWORD_IMAGE_CLICK() {
return WORD_IMAGE_CLICK;
}
public void setWORD_IMAGE_CLICK(List<String> WORD_IMAGE_CLICK) {
this.WORD_IMAGE_CLICK = WORD_IMAGE_CLICK;
}
public List<String> getROTATE() {
return ROTATE;
}
public void setROTATE(List<String> ROTATE) {
this.ROTATE = ROTATE;
}
public List<String> getCONCAT() {
return CONCAT;
}
public void setCONCAT(List<String> CONCAT) {
this.CONCAT = CONCAT;
}
public Boolean getAuto() {
return auto;
}
public void setAuto(Boolean auto) {
this.auto = auto;
}
public String getAutoType() {
return autoType;
}
public void setAutoType(String autoType) {
this.autoType = autoType;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
}
@@ -1,38 +0,0 @@
package cloud.tianai.captcha.solon.properties;
/**
* @Author XT
* @Date 2024.09.03
*/
public class CaptchaSecondary {
private Boolean enabled;
private Long expire;
private String keyPrefix;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Long getExpire() {
return expire;
}
public void setExpire(Long expire) {
this.expire = expire;
}
public String getKeyPrefix() {
return keyPrefix;
}
public void setKeyPrefix(String keyPrefix) {
this.keyPrefix = keyPrefix;
}
}
@@ -1,7 +0,0 @@
package cloud.tianai.captcha.solon.service;
import cloud.tianai.captcha.cache.CacheStore;
public interface CaptchaRedisCacheService extends CacheStore {
}
@@ -2,6 +2,9 @@ package cloud.tianai.captcha.spring.autoconfiguration;
import cloud.tianai.captcha.cache.CacheStore;
import cloud.tianai.captcha.cache.impl.LocalCacheStore;
import cloud.tianai.captcha.resource.ResourceStore;
import cloud.tianai.captcha.resource.impl.LocalMemoryResourceStore;
import cloud.tianai.captcha.spring.plugins.RedisResourceStore;
import cloud.tianai.captcha.spring.store.impl.RedisCacheStore;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
@@ -33,13 +36,20 @@ public class CacheStoreAutoConfiguration {
@ConditionalOnClass(StringRedisTemplate.class)
public static class RedisCacheStoreConfiguration {
@Bean
@Bean(destroyMethod = "close")
@ConditionalOnBean(StringRedisTemplate.class)
@ConditionalOnMissingBean(CacheStore.class)
public CacheStore redis(StringRedisTemplate redisTemplate) {
return new RedisCacheStore(redisTemplate);
}
@Bean
@ConditionalOnBean(StringRedisTemplate.class)
@ConditionalOnMissingBean(ResourceStore.class)
public ResourceStore redisResourceStore(StringRedisTemplate redisTemplate) {
return new RedisResourceStore(redisTemplate);
}
}
/**
@@ -52,12 +62,18 @@ public class CacheStoreAutoConfiguration {
@Configuration(proxyBeanMethods = false)
public static class LocalCacheStoreConfiguration {
@Bean
@Bean(destroyMethod = "close")
@ConditionalOnMissingBean(CacheStore.class)
public CacheStore local() {
return new LocalCacheStore();
}
@Bean
@ConditionalOnMissingBean(ResourceStore.class)
public ResourceStore resourceStore() {
return new LocalMemoryResourceStore();
}
}
}
@@ -4,33 +4,31 @@ package cloud.tianai.captcha.spring.autoconfiguration;
import cloud.tianai.captcha.application.ImageCaptchaApplication;
import cloud.tianai.captcha.application.TACBuilder;
import cloud.tianai.captcha.cache.CacheStore;
import cloud.tianai.captcha.common.util.CollectionUtils;
import cloud.tianai.captcha.generator.ImageCaptchaGenerator;
import cloud.tianai.captcha.generator.ImageTransform;
import cloud.tianai.captcha.generator.impl.transform.Base64ImageTransform;
import cloud.tianai.captcha.interceptor.CaptchaInterceptor;
import cloud.tianai.captcha.interceptor.CaptchaInterceptorGroup;
import cloud.tianai.captcha.interceptor.impl.ParamCheckCaptchaInterceptor;
import cloud.tianai.captcha.interceptor.EmptyCaptchaInterceptor;
import cloud.tianai.captcha.resource.ImageCaptchaResourceManager;
import cloud.tianai.captcha.resource.ResourceProviders;
import cloud.tianai.captcha.resource.ResourceStore;
import cloud.tianai.captcha.resource.impl.DefaultImageCaptchaResourceManager;
import cloud.tianai.captcha.resource.impl.LocalMemoryResourceStore;
import cloud.tianai.captcha.spring.common.util.URL;
import cloud.tianai.captcha.spring.plugins.SpringMultiImageCaptchaGenerator;
import cloud.tianai.captcha.spring.plugins.secondary.SecondaryVerificationApplication;
import cloud.tianai.captcha.validator.ImageCaptchaValidator;
import cloud.tianai.captcha.validator.impl.SimpleImageCaptchaValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;
/**
* @Author: 天爱有情
@@ -44,17 +42,13 @@ import org.springframework.core.annotation.Order;
@EnableConfigurationProperties({SpringImageCaptchaProperties.class})
public class ImageCaptchaAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ResourceStore resourceStore() {
return new LocalMemoryResourceStore();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(ResourceStore.class)
public ImageCaptchaResourceManager imageCaptchaResourceManager(ResourceStore resourceStore) {
ResourceProviders resourceProviders = new ResourceProviders();
return new DefaultImageCaptchaResourceManager(resourceStore,resourceProviders);
return new DefaultImageCaptchaResourceManager(resourceStore, resourceProviders);
}
@Bean
@@ -70,7 +64,9 @@ public class ImageCaptchaAutoConfiguration {
ImageCaptchaResourceManager captchaResourceManager,
ImageTransform imageTransform,
BeanFactory beanFactory) {
return new SpringMultiImageCaptchaGenerator(captchaResourceManager, imageTransform, beanFactory);
// 构建多验证码生成器
ImageCaptchaGenerator captchaGenerator = new SpringMultiImageCaptchaGenerator(captchaResourceManager, imageTransform, beanFactory);
return captchaGenerator;
}
@Bean
@@ -80,26 +76,24 @@ public class ImageCaptchaAutoConfiguration {
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@ConditionalOnMissingBean
public CaptchaInterceptor captchaInterceptor() {
CaptchaInterceptorGroup group = new CaptchaInterceptorGroup();
group.addInterceptor(new ParamCheckCaptchaInterceptor());
// group.addInterceptor(new BasicTrackCaptchaInterceptor());
return group;
return new EmptyCaptchaInterceptor();
}
@Bean
@Bean(destroyMethod = "close")
@ConditionalOnMissingBean
@ConditionalOnBean(CacheStore.class)
public ImageCaptchaApplication imageCaptchaApplication(ImageCaptchaGenerator captchaGenerator,
ImageCaptchaValidator imageCaptchaValidator,
CacheStore cacheStore,
ResourceStore resourceStore,
SpringImageCaptchaProperties prop,
CaptchaInterceptor captchaInterceptor,
ApplicationContext applicationContext) {
TACBuilder tacBuilder = TACBuilder.builder(resourceStore)
ApplicationContext applicationContext
) {
TACBuilder tacBuilder = TACBuilder.builder()
.setResourceStore(resourceStore)
.setGenerator(captchaGenerator)
.setValidator(imageCaptchaValidator)
.setCacheStore(cacheStore)
@@ -116,7 +110,10 @@ public class ImageCaptchaAutoConfiguration {
String[] split = index > 0 ? new String[]{fontPath.substring(0, index), fontPath.substring(index + 1)} : new String[]{"", fontPath};
String type = split[0];
String path = split[1];
tacBuilder.addFont(new cloud.tianai.captcha.resource.common.model.dto.Resource(type, path));
URL fontUrl = URL.valueOf(fontPath);
String tag = fontUrl.getParam(URL.PARAM_TAG_KEY, null);
tacBuilder.addFont(new cloud.tianai.captcha.resource.common.model.dto.Resource(type, path, tag));
}
}
ImageCaptchaApplication target = tacBuilder.build();
@@ -0,0 +1,59 @@
package cloud.tianai.captcha.spring.common.util;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
@Getter
@AllArgsConstructor
public class URL {
public static final String PARAM_TAG_KEY = "tag";
private String protocol;
private String path;
private Map<String, String> params;
public String getParam(String key, String defaultValue) {
return params.getOrDefault(key, defaultValue);
}
public static URL valueOf(String input) {
// 分割协议和剩余部分
String[] parts = input.split(":", 2);
String protocol = parts[0];
String remaining = parts[1];
// 分割路径和查询参数
String path;
String query = null;
if (remaining.contains("?")) {
String[] pathQuerySplit = remaining.split("\\?", 2);
path = pathQuerySplit[0];
query = pathQuerySplit[1];
} else {
path = remaining;
}
if (path.startsWith("//")) {
path = path.substring(2);
}
// 处理查询参数,提取键值对
Map<String, String> queryParams = new HashMap<>();
if (query != null) {
for (String param : query.split("&")) {
String[] keyValue = param.split("=", 2);
String key = keyValue[0];
String value = keyValue.length > 1 ? keyValue[1] : "";
queryParams.put(key, value);
}
}
return new URL(protocol, path, queryParams);
}
}
@@ -1,41 +0,0 @@
package cloud.tianai.captcha.spring.exception;
import cloud.tianai.captcha.common.exception.ImageCaptchaException;
import lombok.Getter;
import lombok.Setter;
/**
* @Author: 天爱有情
* @Date 2020/6/19 16:36
* @Description 验证码验证失败异常
*/
@Getter
@Setter
public class CaptchaValidException extends ImageCaptchaException {
private String captchaType;
private Integer code;
public CaptchaValidException() {
}
public CaptchaValidException(String captchaType,String message) {
super(message);
this.captchaType = captchaType;
}
public CaptchaValidException(String captchaType,Integer code, String message) {
super(message);
this.code = code;
this.captchaType = captchaType;
}
public CaptchaValidException(String message, Throwable cause) {
super(message, cause);
}
public CaptchaValidException(Throwable cause) {
super(cause);
}
public CaptchaValidException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@@ -0,0 +1,286 @@
package cloud.tianai.captcha.spring.plugins;
import cloud.tianai.captcha.common.constant.CommonConstant;
import cloud.tianai.captcha.common.util.CollectionUtils;
import cloud.tianai.captcha.resource.CrudResourceStore;
import cloud.tianai.captcha.resource.ImageCaptchaResourceManager;
import cloud.tianai.captcha.resource.common.model.dto.Resource;
import cloud.tianai.captcha.resource.common.model.dto.ResourceMap;
import com.google.gson.Gson;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
/**
* @Author: 天爱有情
* @date 2023/8/23 10:52
* @Description 基于redis的store
*/
@RequiredArgsConstructor
public class RedisResourceStore implements CrudResourceStore {
private final StringRedisTemplate redisTemplate;
@Getter
@Setter
private String resourcePrefix = "captcha:config:resource:";
@Getter
@Setter
private String templatePrefix = "captcha:config:template:";
private Gson gson = new Gson();
public String joinResourceKey(String type, String tag) {
if (tag == null) {
tag = CommonConstant.DEFAULT_TAG;
}
type = type.toUpperCase();
return resourcePrefix + tag + ":" + type;
}
public String joinTemplateKey(String type, String tag) {
if (tag == null) {
tag = CommonConstant.DEFAULT_TAG;
}
type = type.toUpperCase();
return templatePrefix + tag + ":" + type;
}
public List<Resource> getResources(String type, String tag) {
String key = joinResourceKey(type, tag);
Long size = redisTemplate.opsForList().size(key);
if (size == null || size < 1) {
return Collections.emptyList();
}
List<String> range = redisTemplate.opsForList().range(key, 0, size);
List<Resource> result = new ArrayList<>(range.size());
for (String json : range) {
result.add(gson.fromJson(json, Resource.class));
}
return result;
}
public List<ResourceMap> getTemplates(String type, String tag) {
String key = joinTemplateKey(type, tag);
Long size = redisTemplate.opsForList().size(key);
if (size == null || size < 1) {
return Collections.emptyList();
}
List<String> range = redisTemplate.opsForList().range(key, 0, size);
List<ResourceMap> result = new ArrayList<>(range.size());
for (String json : range) {
result.add(gson.fromJson(json, ResourceMap.class));
}
return result;
}
public void setResources(String type, String tag, List<Resource> resources) {
String key = joinResourceKey(type, tag);
Long size = redisTemplate.opsForList().size(key);
if (size != null && size > 0) {
redisTemplate.delete(key);
}
for (Resource resource : resources) {
addResource(type, resource);
}
}
public void setTemplates(String type, String tag, List<ResourceMap> templates) {
String key = joinTemplateKey(type, tag);
Long size = redisTemplate.opsForList().size(key);
if (size != null && size > 0) {
redisTemplate.delete(key);
}
for (ResourceMap template : templates) {
addTemplate(type, template);
}
}
@Override
public void addResource(String type, Resource resource) {
// 添加tag标签字典
redisTemplate.opsForList().rightPush(joinResourceKey(type, resource.getTag()), gson.toJson(resource));
}
@Override
public void addTemplate(String type, ResourceMap template) {
// 添加tag标签字典
redisTemplate.opsForList().rightPush(joinTemplateKey(type, template.getTag()), gson.toJson(template));
}
@Override
public Resource deleteResource(String type, String id) {
Set<String> keys = redisTemplate.keys(joinResourceKey(type, "*"));
if (!CollectionUtils.isEmpty(keys)) {
for (String key : keys) {
Long size = redisTemplate.opsForList().size(key);
if (size == null || size < 1) {
continue;
}
List<String> range = redisTemplate.opsForList().range(key, 0, size);
if (range != null) {
for (String json : range) {
Resource resource = gson.fromJson(json, Resource.class);
if (resource.getId().equals(id)) {
redisTemplate.opsForList().remove(key, 1, json);
return resource;
}
}
}
}
}
return null;
}
@Override
public ResourceMap deleteTemplate(String type, String id) {
Set<String> keys = redisTemplate.keys(joinTemplateKey(type, "*"));
if (!CollectionUtils.isEmpty(keys)) {
for (String key : keys) {
Long size = redisTemplate.opsForList().size(key);
if (size == null || size < 1) {
continue;
}
List<String> range = redisTemplate.opsForList().range(key, 0, size);
if (range != null) {
for (String json : range) {
ResourceMap resourceMap = gson.fromJson(json, ResourceMap.class);
if (resourceMap.getId().equals(id)) {
redisTemplate.opsForList().remove(key, 1, json);
return resourceMap;
}
}
}
}
}
return null;
}
@Override
public List<Resource> listResourcesByTypeAndTag(String type, String tag) {
if (StringUtils.isNotBlank(tag)) {
return getResources(type, tag);
}
Set<String> keys = redisTemplate.keys(joinResourceKey(type, "*"));
if (!CollectionUtils.isEmpty(keys)) {
List<Resource> resources = new ArrayList<>();
for (String key : keys) {
Long size1 = redisTemplate.opsForList().size(key);
if (size1 == null || size1 < 1) {
continue;
}
List<String> range = redisTemplate.opsForList().range(key, 0, size1);
if (range != null) {
for (String json : range) {
Resource resource = gson.fromJson(json, Resource.class);
resources.add(resource);
}
}
}
return resources;
}
return Collections.emptyList();
}
@Override
public List<ResourceMap> listTemplatesByTypeAndTag(String type, String tag) {
if (StringUtils.isNotBlank(tag)) {
return getTemplates(type, tag);
}
Set<String> keys = redisTemplate.keys(joinTemplateKey(type, "*"));
if (!CollectionUtils.isEmpty(keys)) {
List<ResourceMap> templates = new ArrayList<>();
for (String key : keys) {
Long size1 = redisTemplate.opsForList().size(key);
if (size1 == null || size1 < 1) {
continue;
}
List<String> range = redisTemplate.opsForList().range(key, 0, size1);
if (range != null) {
for (String json : range) {
ResourceMap template = gson.fromJson(json, ResourceMap.class);
templates.add(template);
}
}
}
return templates;
}
return Collections.emptyList();
}
@Override
public void init(ImageCaptchaResourceManager resourceManager) {
}
@Override
public List<Resource> randomGetResourceByTypeAndTag(String type, String tag, Integer quantity) {
String key = joinResourceKey(type, tag);
Long size = redisTemplate.opsForList().size(key);
if (size == null || quantity > size) {
throw new IllegalArgumentException("请求的资源数量超过可用资源总数");
}
Set<Long> indexes = new HashSet<>(quantity);
while (indexes.size() < quantity) {
indexes.add(ThreadLocalRandom.current().nextLong(size));
}
List<Resource> result = new ArrayList<>(quantity);
for (Long index : indexes) {
String resourceJson = redisTemplate.opsForList().index(key, index);
result.add(gson.fromJson(resourceJson, Resource.class));
}
return result;
}
@Override
public List<ResourceMap> randomGetTemplateByTypeAndTag(String type, String tag, Integer quantity) {
String key = joinTemplateKey(type, tag);
Long size = redisTemplate.opsForList().size(key);
if (size == null || size < 1) {
throw new IllegalStateException("随机获取模板错误,store中模板为空, type:" + type);
}
if (quantity > size) {
throw new IllegalArgumentException("请求的模板数量超过可用模板总数");
}
Set<Long> indexes = new HashSet<>(quantity);
while (indexes.size() < quantity) {
indexes.add(ThreadLocalRandom.current().nextLong(size));
}
List<ResourceMap> result = new ArrayList<>(quantity);
for (Long index : indexes) {
String resourceJson = redisTemplate.opsForList().index(key, index);
result.add(gson.fromJson(resourceJson, ResourceMap.class));
}
return result;
}
@Override
public void clearAllTemplates() {
Set<String> keys = redisTemplate.keys(templatePrefix + "*");
if (!CollectionUtils.isEmpty(keys)) {
redisTemplate.delete(keys);
}
}
@Override
public void clearAllResources() {
Set<String> keys = redisTemplate.keys(resourcePrefix + "*");
if (!CollectionUtils.isEmpty(keys)) {
redisTemplate.delete(keys);
}
}
}
@@ -68,4 +68,9 @@ public class RedisCacheStore implements CacheStore {
}
return Long.valueOf(value);
}
@Override
public void close() throws Exception {
}
}
@@ -2,16 +2,17 @@ package cloud.tianai.captcha.application;
import cloud.tianai.captcha.application.vo.ImageCaptchaVO;
import cloud.tianai.captcha.cache.CacheStore;
import cloud.tianai.captcha.cache.StoreCacheKeyPrefix;
import cloud.tianai.captcha.common.AnyMap;
import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import cloud.tianai.captcha.common.exception.ImageCaptchaException;
import cloud.tianai.captcha.common.response.ApiResponse;
import cloud.tianai.captcha.common.response.ApiResponseStatusConstant;
import cloud.tianai.captcha.common.util.CollectionUtils;
import cloud.tianai.captcha.common.util.ObjectUtils;
import cloud.tianai.captcha.generator.ImageCaptchaGenerator;
import cloud.tianai.captcha.generator.common.model.dto.GenerateParam;
import cloud.tianai.captcha.generator.common.model.dto.ImageCaptchaInfo;
import cloud.tianai.captcha.generator.common.model.dto.ParamKeyEnum;
import cloud.tianai.captcha.generator.impl.CacheImageCaptchaGenerator;
import cloud.tianai.captcha.interceptor.CaptchaInterceptor;
import cloud.tianai.captcha.interceptor.EmptyCaptchaInterceptor;
@@ -34,17 +35,25 @@ import java.util.concurrent.TimeUnit;
@Slf4j
public class DefaultImageCaptchaApplication implements ImageCaptchaApplication {
private CaptchaInterceptor captchaInterceptor;
/** 图片验证码生成器. */
/**
* 图片验证码生成器.
*/
private ImageCaptchaGenerator captchaGenerator;
/** 图片验证码校验器. */
/**
* 图片验证码校验器.
*/
private ImageCaptchaValidator imageCaptchaValidator;
/** 缓冲存储. */
/**
* 缓冲存储.
*/
private CacheStore cacheStore;
/** 验证码配置属性. */
/**
* 验证码配置属性.
*/
private final ImageCaptchaProperties prop;
/** 缓存key 前缀处理器. */
private StoreCacheKeyPrefix storeCacheKeyPrefix;
/** 默认的过期时间. */
/**
* 默认的过期时间.
*/
private long defaultExpire = 20000L;
public static final String ID_SPLIT = "_";
@@ -53,10 +62,9 @@ public class DefaultImageCaptchaApplication implements ImageCaptchaApplication {
ImageCaptchaValidator imageCaptchaValidator,
CacheStore cacheStore,
ImageCaptchaProperties prop,
CaptchaInterceptor captchaInterceptor,
StoreCacheKeyPrefix storeCacheKeyPrefix) {
CaptchaInterceptor captchaInterceptor) {
this.prop = prop;
this.storeCacheKeyPrefix = null != storeCacheKeyPrefix? storeCacheKeyPrefix: StoreCacheKeyPrefix.prefixed(prop.getPrefix());
setImageCaptchaValidator(imageCaptchaValidator);
setCacheStore(cacheStore);
// 默认过期时间
@@ -71,9 +79,11 @@ public class DefaultImageCaptchaApplication implements ImageCaptchaApplication {
}
captchaGenerator.setInterceptor(this.captchaInterceptor);
if (prop.isLocalCacheEnabled()) {
captchaGenerator = new CacheImageCaptchaGenerator(captchaGenerator,
CacheImageCaptchaGenerator cacheImageCaptchaGenerator = new CacheImageCaptchaGenerator(captchaGenerator,
prop.getLocalCacheSize(), prop.getLocalCacheWaitTime(),
prop.getLocalCachePeriod(), prop.getLocalCacheExpireTime());
cacheImageCaptchaGenerator.setIgnoredCacheFields(prop.getLocalCacheIgnoredCacheFields());
captchaGenerator = cacheImageCaptchaGenerator;
}
// 初始化生成器
captchaGenerator.init();
@@ -99,9 +109,13 @@ public class DefaultImageCaptchaApplication implements ImageCaptchaApplication {
if (captchaResponse != null) {
return captchaResponse;
}
String id = generatorId(param);
ImageCaptchaInfo imageCaptchaInfo = getImageCaptchaGenerator().generateCaptchaImage(param);
captchaResponse = convertToCaptchaResponse(imageCaptchaInfo);
captchaResponse = convertToCaptchaResponse(id, imageCaptchaInfo);
afterGenerateCaptcha(imageCaptchaInfo, captchaResponse);
param.removeParam(ParamKeyEnum.ID);
return captchaResponse;
}
@@ -125,13 +139,13 @@ public class DefaultImageCaptchaApplication implements ImageCaptchaApplication {
}
public ApiResponse<ImageCaptchaVO> convertToCaptchaResponse(ImageCaptchaInfo imageCaptchaInfo) {
public ApiResponse<ImageCaptchaVO> convertToCaptchaResponse(String id, ImageCaptchaInfo imageCaptchaInfo) {
if (imageCaptchaInfo == null) {
// 要是生成失败
throw new ImageCaptchaException("生成验证码失败,验证码生成为空");
}
// 生成ID
String id = generatorId(imageCaptchaInfo);
ApiResponse<ImageCaptchaVO> response = beforeGenerateImageCaptchaValidData(imageCaptchaInfo);
if (response != null) {
return response;
@@ -209,8 +223,14 @@ public class DefaultImageCaptchaApplication implements ImageCaptchaApplication {
return null;
}
protected String generatorId(ImageCaptchaInfo imageCaptchaInfo) {
return imageCaptchaInfo.getType() + ID_SPLIT + UUID.randomUUID().toString().replace("-", "");
protected String generatorId(GenerateParam param) {
String id = param.getParam(ParamKeyEnum.ID);
if (ObjectUtils.isEmpty(id)) {
id = param.getType() + ID_SPLIT + UUID.randomUUID().toString().replace("-", "");
param.addParam(ParamKeyEnum.ID, id);
}
return id;
}
/**
@@ -239,8 +259,7 @@ public class DefaultImageCaptchaApplication implements ImageCaptchaApplication {
}
protected String getKey(String id) {
// 改为通过接口扩展
return storeCacheKeyPrefix.compute(id);
return prop.getPrefix().concat(":").concat(id);
}
@Override
@@ -292,6 +311,7 @@ public class DefaultImageCaptchaApplication implements ImageCaptchaApplication {
// ============== 一些模板方法 ================
private void afterGenerateCaptcha(ImageCaptchaInfo imageCaptchaInfo, ApiResponse<ImageCaptchaVO> captchaResponse) {
captchaInterceptor.afterGenerateCaptcha(captchaInterceptor.createContext(), imageCaptchaInfo.getType(), imageCaptchaInfo, captchaResponse);
}
@@ -315,4 +335,24 @@ public class DefaultImageCaptchaApplication implements ImageCaptchaApplication {
return captchaInterceptor.afterValid(captchaInterceptor.createContext(), getCaptchaTypeById(id), matchParam, validData, basicValid);
}
/**
* 销毁应用程序,释放资源
* 建议在不再使用或应用关闭时调用
*/
@Override
public void close() {
// 如果生成器是 CacheImageCaptchaGenerator,需要关闭其定时任务
if (captchaGenerator instanceof CacheImageCaptchaGenerator) {
((CacheImageCaptchaGenerator) captchaGenerator).destroy();
}
// 如果缓存存储是 AutoCloseable,关闭它
if (cacheStore instanceof AutoCloseable) {
try {
((AutoCloseable) cacheStore).close();
} catch (Exception e) {
log.warn("关闭 CacheStore 时出错", e);
}
}
}
}
@@ -114,4 +114,9 @@ public class FilterImageCaptchaApplication implements ImageCaptchaApplication {
public CacheStore getCacheStore() {
return target.getCacheStore();
}
@Override
public void close() throws Exception {
target.close();
}
}
@@ -17,7 +17,7 @@ import cloud.tianai.captcha.validator.common.model.dto.MatchParam;
* @Date 2020/5/29 8:33
* @Description 滑块验证码应用程序
*/
public interface ImageCaptchaApplication {
public interface ImageCaptchaApplication extends AutoCloseable{
/**
* 生成滑块验证码
@@ -4,6 +4,7 @@ import lombok.Data;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @Author: 天爱有情
@@ -23,4 +24,5 @@ public class ImageCaptchaProperties {
private int localCacheWaitTime = 1000;
private int localCachePeriod = 5000;
private Long localCacheExpireTime;
private Set<String> localCacheIgnoredCacheFields;
}
@@ -3,6 +3,7 @@ package cloud.tianai.captcha.application;
import cloud.tianai.captcha.cache.CacheStore;
import cloud.tianai.captcha.cache.StoreCacheKeyPrefix;
import cloud.tianai.captcha.cache.impl.LocalCacheStore;
import cloud.tianai.captcha.common.util.CollectionUtils;
import cloud.tianai.captcha.generator.ImageCaptchaGenerator;
import cloud.tianai.captcha.generator.ImageTransform;
import cloud.tianai.captcha.generator.impl.MultiImageCaptchaGenerator;
@@ -16,6 +17,8 @@ import cloud.tianai.captcha.resource.impl.LocalMemoryResourceStore;
import cloud.tianai.captcha.validator.ImageCaptchaValidator;
import cloud.tianai.captcha.validator.impl.SimpleImageCaptchaValidator;
import java.util.*;
/**
* @Author: 天爱有情
* @date 2024/7/14 16:41
@@ -30,26 +33,26 @@ public class TACBuilder {
private ImageCaptchaProperties prop = new ImageCaptchaProperties();
private ResourceStore resourceStore;
private ImageTransform imageTransform;
private StoreCacheKeyPrefix cacheKeyPrefix;
// private List<FontWrapper> fontWrappers = new ArrayList<>();
// private List<FontWrapper> fontWrappers = new ArrayList<>();
private Map<String, List<Resource>> resourceCache = new HashMap<>(8);
private Map<String, List<ResourceMap>> templateCache = new HashMap<>(8);
private String defaultTemplatePrefix = null;
public static TACBuilder builder() {
return TACBuilder.builder(new LocalMemoryResourceStore());
return new TACBuilder();
}
public static TACBuilder builder(ResourceStore resourceStore) {
TACBuilder builder = new TACBuilder(resourceStore);
builder.prop = new ImageCaptchaProperties();
return builder;
private TACBuilder() {
}
private TACBuilder(ResourceStore resourceStore) {
public TACBuilder setResourceStore(ResourceStore resourceStore) {
this.resourceStore = resourceStore;
return this;
}
public TACBuilder addDefaultTemplate(String defaultPathPrefix) {
DefaultBuiltInResources defaultBuiltInResources = new DefaultBuiltInResources(defaultPathPrefix);
defaultBuiltInResources.addDefaultTemplate(resourceStore);
this.defaultTemplatePrefix = defaultPathPrefix;
return this;
}
@@ -77,10 +80,6 @@ public class TACBuilder {
return this;
}
public TACBuilder setCacheKeyPrefix(StoreCacheKeyPrefix cacheKeyPrefix) {
this.cacheKeyPrefix = cacheKeyPrefix;
return this;
}
public TACBuilder addFont(Resource resource) {
this.addResource(FontCache.FONT_TYPE, resource);
return this;
@@ -88,11 +87,17 @@ public class TACBuilder {
public TACBuilder cached(int size, int waitTime, int period, Long expireTime) {
cached(size, waitTime, period, expireTime, null);
return this;
}
public TACBuilder cached(int size, int waitTime, int period, Long expireTime, Set<String> ignoredCacheFields) {
prop.setLocalCacheEnabled(true);
prop.setLocalCacheSize(size);
prop.setLocalCacheWaitTime(waitTime);
prop.setLocalCachePeriod(period);
prop.setLocalCacheExpireTime(expireTime);
prop.setLocalCacheIgnoredCacheFields(ignoredCacheFields);
return this;
}
@@ -118,16 +123,18 @@ public class TACBuilder {
public TACBuilder addResource(String captchaType, Resource imageResource) {
if (resourceStore instanceof CrudResourceStore) {
((CrudResourceStore) resourceStore).addResource(captchaType, imageResource);
}
// if (resourceStore instanceof CrudResourceStore) {
// ((CrudResourceStore) resourceStore).addResource(captchaType, imageResource);
// }
cacheResource(captchaType, imageResource);
return this;
}
public TACBuilder addTemplate(String captchaType, ResourceMap resourceMap) {
if (resourceStore instanceof CrudResourceStore) {
((CrudResourceStore) resourceStore).addTemplate(captchaType, resourceMap);
}
// if (resourceStore instanceof CrudResourceStore) {
// ((CrudResourceStore) resourceStore).addTemplate(captchaType, resourceMap);
// }
cacheTemplate(captchaType, resourceMap);
return this;
}
@@ -140,6 +147,29 @@ public class TACBuilder {
if (cacheStore == null) {
cacheStore = new LocalCacheStore();
}
if (resourceStore == null) {
resourceStore = new LocalMemoryResourceStore();
}
if (resourceStore instanceof CrudResourceStore) {
CrudResourceStore crudResourceStore = (CrudResourceStore) resourceStore;
if (!CollectionUtils.isEmpty(resourceCache)) {
resourceCache.forEach((type,resources) -> {
resources.forEach(resource -> crudResourceStore.addResource(type,resource));
});
resourceCache.clear();
}
if (!CollectionUtils.isEmpty(templateCache)) {
templateCache.forEach((type, templates) -> {
templates.forEach(template -> crudResourceStore.addTemplate(type, template));
});
templateCache.clear();
}
}
// 添加默认模板
if (defaultTemplatePrefix != null) {
DefaultBuiltInResources defaultBuiltInResources = new DefaultBuiltInResources(defaultTemplatePrefix);
defaultBuiltInResources.addDefaultTemplate(resourceStore);
}
if (generator == null) {
ResourceProviders resourceProviders = new ResourceProviders();
DefaultImageCaptchaResourceManager resourceManager = new DefaultImageCaptchaResourceManager(resourceStore, resourceProviders);
@@ -155,7 +185,15 @@ public class TACBuilder {
interceptor = EmptyCaptchaInterceptor.INSTANCE;
}
// 增加前缀处理接口
DefaultImageCaptchaApplication application = new DefaultImageCaptchaApplication(generator, validator, cacheStore, prop, interceptor, cacheKeyPrefix);
DefaultImageCaptchaApplication application = new DefaultImageCaptchaApplication(generator, validator, cacheStore, prop, interceptor);
return application;
}
private void cacheResource(String captchaType, Resource imageResource) {
resourceCache.computeIfAbsent(captchaType, k -> new ArrayList<>(4)).add(imageResource);
}
private void cacheTemplate(String captchaType, ResourceMap resourceMap) {
templateCache.computeIfAbsent(captchaType, k -> new ArrayList<>(4)).add(resourceMap);
}
}
@@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit;
* @date 2022/3/2 14:35
* @Description 提取出用于缓存的接口
*/
public interface CacheStore {
public interface CacheStore extends AutoCloseable {
/**
* 读取缓存数据通过key
@@ -12,11 +12,10 @@ import java.util.stream.Collectors;
/**
* @Author: 天爱有情
* @date 2020/10/12 10:02
* @Description 给予本人以前写的 expiring-map(redis淘汰策略的java实现) 项目进行改造
*/
@Slf4j
@Accessors(chain = true)
public class ConCurrentExpiringMap<K, V> implements ExpiringMap<K, V> {
public class ConCurrentExpiringMap<K, V> implements ExpiringMap<K, V>, AutoCloseable {
private ConcurrentHashMap<K, TimeMapEntity<K, V>> storage;
private SortedMap<Long, LinkedList<K>> sortedMap = new ConcurrentSkipListMap<>();
@@ -198,6 +197,37 @@ public class ConCurrentExpiringMap<K, V> implements ExpiringMap<K, V> {
throw new IllegalArgumentException("timemap not impl entrySet.");
}
/**
* 销毁方法,关闭定时任务线程池
* 应该在不再使用此 Map 时调用,以防止线程泄露
*
* @since 0.0.3
*/
public void destroy() {
try {
scheduledExecutor.shutdown();
if (!scheduledExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
scheduledExecutor.shutdownNow();
if (!scheduledExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
log.warn("ConCurrentExpiringMap 定时任务线程池未能正常关闭");
}
}
} catch (InterruptedException e) {
scheduledExecutor.shutdownNow();
Thread.currentThread().interrupt();
log.warn("ConCurrentExpiringMap 定时任务线程池关闭时被中断", e);
}
}
/**
* 实现 AutoCloseable 接口,支持 try-with-resources 语法
* 调用 destroy() 方法释放资源
*/
@Override
public void close() {
destroy();
}
/**
* 定时执行任务
*
@@ -63,4 +63,15 @@ public class LocalCacheStore implements CacheStore {
}
return null;
}
/**
* 关闭缓存存储,释放资源
* 建议在不再使用时调用,或在 Spring Bean 销毁时自动调用
*/
@Override
public void close() {
if (cache instanceof ConCurrentExpiringMap) {
((ConCurrentExpiringMap<?, ?>) cache).destroy();
}
}
}
@@ -10,75 +10,258 @@ import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* @Author: 天爱有情
* @Description 通用Map包装类,提供类型安全的get/set方法
*/
@EqualsAndHashCode
public class AnyMap implements Map<String, Object> {
private Map<String, Object> target;
private final Map<String, Object> target;
public AnyMap() {
target = new LinkedHashMap<>();
}
/**
* 构造函数 - 防御性拷贝
* @param map 源Map(会被复制,不会共享引用)
*/
public AnyMap(Map<String, Object> map) {
this.target = map;
this.target = map != null ? new LinkedHashMap<>(map) : new LinkedHashMap<>();
}
// ================== 类型转换方法 =======================
/**
* 获取Float值
*/
public Float getFloat(String key) {
return getFloat(key, null);
}
public Float getFloat(String key, Float defaultData) {
/**
* 获取Float值,支持默认值
*/
public Float getFloat(String key, Float defaultValue) {
return convertToNumber(key, defaultValue, Number::floatValue, Float::parseFloat);
}
/**
* 获取Integer值
*/
public Integer getInt(String key) {
return getInt(key, null);
}
/**
* 获取Integer值,支持默认值
*/
public Integer getInt(String key, Integer defaultValue) {
return convertToNumber(key, defaultValue, Number::intValue, Integer::parseInt);
}
/**
* 获取Long值
*/
public Long getLong(String key) {
return getLong(key, null);
}
/**
* 获取Long值,支持默认值
*/
public Long getLong(String key, Long defaultValue) {
return convertToNumber(key, defaultValue, Number::longValue, Long::parseLong);
}
/**
* 获取Double值
*/
public Double getDouble(String key) {
return getDouble(key, null);
}
/**
* 获取Double值,支持默认值
*/
public Double getDouble(String key, Double defaultValue) {
return convertToNumber(key, defaultValue, Number::doubleValue, Double::parseDouble);
}
/**
* 获取Boolean值
*/
public Boolean getBoolean(String key) {
return getBoolean(key, null);
}
/**
* 获取Boolean值,支持默认值
*/
public Boolean getBoolean(String key, Boolean defaultValue) {
Object data = get(key);
if (data != null) {
if (data instanceof Number) {
return ((Number) data).floatValue();
}
if (data == null) {
return defaultValue;
}
if (data instanceof Boolean) {
return (Boolean) data;
}
if (data instanceof String) {
return Boolean.parseBoolean((String) data);
}
if (data instanceof Number) {
return ((Number) data).intValue() != 0;
}
return defaultValue;
}
/**
* 获取String值
*/
public String getString(String key) {
return getString(key, null);
}
/**
* 获取String值,支持默认值
*/
public String getString(String key, String defaultValue) {
Object data = get(key);
if (data == null) {
return defaultValue;
}
if (data instanceof String) {
return (String) data;
}
return String.valueOf(data);
}
/**
* 通用数字类型转换方法(减少重复代码)
*/
private <T extends Number> T convertToNumber(
String key,
T defaultValue,
Function<Number, T> numberConverter,
Function<String, T> stringParser) {
Object data = get(key);
if (data == null) {
return defaultValue;
}
if (data instanceof Number) {
return numberConverter.apply((Number) data);
}
if (data instanceof String) {
try {
if (data instanceof String) {
return Float.parseFloat((String) data);
}
return stringParser.apply((String) data);
} catch (NumberFormatException e) {
throw e;
return defaultValue;
}
}
return defaultData;
return defaultValue;
}
public Integer getInt(String key, Integer defaultData) {
Object data = get(key);
if (data != null) {
if (data instanceof Number) {
return ((Number) data).intValue();
}
try {
if (data instanceof String) {
return Integer.parseInt((String) data);
}
} catch (NumberFormatException e) {
throw e;
}
}
return defaultData;
// ================== ParamKey 相关方法 =======================
/**
* 添加参数(使用ParamKey)
*/
public <T> void addParam(ParamKey<T> paramKey, T value) {
put(paramKey.getKey(), value);
}
public String getString(String key, String defaultData) {
Object data = get(key);
if (data != null) {
if (data instanceof String) {
return (String) data;
}
return String.valueOf(data);
}
return defaultData;
/**
* 获取参数(使用ParamKey)
*/
public <T> T getParam(ParamKey<T> paramKey) {
return getParam(paramKey, null);
}
/**
* 获取参数(使用ParamKey),支持默认值
*/
@SuppressWarnings("unchecked")
public <T> T getParam(ParamKey<T> paramKey, T defaultValue) {
Object value = get(paramKey.getKey());
return value != null ? (T) value : defaultValue;
}
/**
* 移除参数(使用ParamKey)
*/
public <T> Object removeParam(ParamKey<T> paramKey) {
return remove(paramKey.getKey());
}
/**
* 获取参数或默认值(使用ParamKey)
*/
@SuppressWarnings("unchecked")
public <T> T getOrDefault(ParamKey<T> paramKey, T defaultValue) {
return (T) getOrDefault(paramKey.getKey(), defaultValue);
}
// ================== 便捷方法 =======================
/**
* 添加参数(String key)
* 注意:这个方法等价于put(),保留是为了向后兼容
*/
public void addParam(String key, Object value) {
put(key, value);
}
/**
* 获取参数(String key)
* 注意:这个方法等价于get(),保留是为了向后兼容
*/
public Object getParam(String key) {
return get(key);
}
/**
* 移除参数(String key)
* 注意:这个方法等价于remove(),保留是为了向后兼容
*/
public Object removeParam(String key) {
return remove(key);
}
/**
* 链式调用 - 设置值并返回this
* @param key 键
* @param value 值
* @return this,支持链式调用
*/
public AnyMap set(String key, Object value) {
put(key, value);
return this;
}
/**
* 链式调用 - 使用ParamKey设置值
*/
public <T> AnyMap set(ParamKey<T> paramKey, T value) {
put(paramKey.getKey(), value);
return this;
}
/**
* 静态工厂方法
*/
public static AnyMap of(Map<String, Object> map) {
return new AnyMap(map);
}
// ================== implement Map =======================
/**
* 静态工厂方法 - 创建空Map
*/
public static AnyMap create() {
return new AnyMap();
}
// ================== implement Map =======================
@Override
public int size() {
@@ -0,0 +1,12 @@
package cloud.tianai.captcha.common;
/**
* @Author: 天爱有情
* @date 2024/11/20 11:34
* @Description 此接口的作用是在给 {@link AnyMap} 添加/获取参数时做一个类型限制和转换
*/
public interface ParamKey<T> {
String getKey();
}
@@ -1,5 +1,6 @@
package cloud.tianai.captcha.common.util;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@@ -10,15 +11,22 @@ import java.util.Set;
*/
public class CaptchaTypeClassifier {
/**
* 每个类型集合的最大容量,防止内存泄漏
*/
private static final int MAX_TYPE_SIZE = 100;
private static final Set<String> SLIDER_CAPTCHA_TYPES = new HashSet<>();
private static final Set<String> CLICK_CAPTCHA_TYPES = new HashSet<>();
private static final Set<String> JIGSAW_CAPTCHA_TYPES = new HashSet<>();
public static void addSliderCaptchaType(String type) {
checkCapacity(SLIDER_CAPTCHA_TYPES, "SLIDER_CAPTCHA_TYPES");
SLIDER_CAPTCHA_TYPES.add(type.toUpperCase());
}
public static void addClickCaptchaType(String type) {
checkCapacity(CLICK_CAPTCHA_TYPES, "CLICK_CAPTCHA_TYPES");
CLICK_CAPTCHA_TYPES.add(type.toUpperCase());
}
@@ -31,11 +39,11 @@ public class CaptchaTypeClassifier {
}
public static Set<String> getSliderCaptchaTypes() {
return SLIDER_CAPTCHA_TYPES;
return Collections.unmodifiableSet(SLIDER_CAPTCHA_TYPES);
}
public static Set<String> getClickCaptchaTypes() {
return CLICK_CAPTCHA_TYPES;
return Collections.unmodifiableSet(CLICK_CAPTCHA_TYPES);
}
public static void removeSliderCaptchaType(String type) {
@@ -51,6 +59,7 @@ public class CaptchaTypeClassifier {
}
public static void addJigsawCaptchaType(String type) {
checkCapacity(JIGSAW_CAPTCHA_TYPES, "JIGSAW_CAPTCHA_TYPES");
JIGSAW_CAPTCHA_TYPES.add(type.toUpperCase());
}
@@ -59,6 +68,19 @@ public class CaptchaTypeClassifier {
}
public static Set<String> getJigsawCaptchaTypes() {
return JIGSAW_CAPTCHA_TYPES;
return Collections.unmodifiableSet(JIGSAW_CAPTCHA_TYPES);
}
/**
* 检查集合容量,防止内存泄漏
* @param set 要检查的集合
* @param name 集合名称,用于日志
*/
private static void checkCapacity(Set<String> set, String name) {
if (set.size() >= MAX_TYPE_SIZE) {
throw new IllegalStateException(
String.format("验证码类型集合 %s 已达到最大容量 %d,无法继续添加", name, MAX_TYPE_SIZE)
);
}
}
}
@@ -2,10 +2,7 @@ package cloud.tianai.captcha.generator;
import cloud.tianai.captcha.common.exception.ImageCaptchaException;
import cloud.tianai.captcha.common.util.CollectionUtils;
import cloud.tianai.captcha.generator.common.model.dto.CaptchaExchange;
import cloud.tianai.captcha.generator.common.model.dto.CustomData;
import cloud.tianai.captcha.generator.common.model.dto.GenerateParam;
import cloud.tianai.captcha.generator.common.model.dto.ImageCaptchaInfo;
import cloud.tianai.captcha.generator.common.model.dto.*;
import cloud.tianai.captcha.generator.common.util.CaptchaImageUtils;
import cloud.tianai.captcha.generator.impl.transform.Base64ImageTransform;
import cloud.tianai.captcha.interceptor.CaptchaInterceptor;
@@ -136,6 +133,11 @@ public abstract class AbstractImageCaptchaGenerator implements ImageCaptchaGener
public ImageCaptchaInfo wrapImageCaptchaInfo(CaptchaExchange captchaExchange) {
ImageCaptchaInfo imageCaptchaInfo = doWrapImageCaptchaInfo(captchaExchange);
imageCaptchaInfo.setData(captchaExchange.getCustomData());
// 设置自定义容错值
Number tolerant = captchaExchange.getParam().getParam(ParamKeyEnum.TOLERANT);
if (tolerant != null) {
imageCaptchaInfo.setTolerant(tolerant.floatValue());
}
return imageCaptchaInfo;
}
@@ -166,17 +168,21 @@ public abstract class AbstractImageCaptchaGenerator implements ImageCaptchaGener
protected BufferedImage getTemplateImage(ResourceMap templateImages, String imageName) {
InputStream stream = getTemplateFile(templateImages, imageName);
BufferedImage bufferedImage = CaptchaImageUtils.wrapFile2BufferedImage(stream);
closeStream(stream);
return bufferedImage;
try {
return CaptchaImageUtils.wrapFile2BufferedImage(stream);
} finally {
closeStream(stream);
}
}
protected BufferedImage getResourceImage(Resource resource) {
InputStream stream = getResourceInputStream(resource, null);
BufferedImage bufferedImage = CaptchaImageUtils.wrapFile2BufferedImage(stream);
closeStream(stream);
return bufferedImage;
try {
return CaptchaImageUtils.wrapFile2BufferedImage(stream);
} finally {
closeStream(stream);
}
}
protected int randomInt(int origin, int bound) {
@@ -5,28 +5,34 @@ import lombok.Data;
import lombok.NoArgsConstructor;
import java.awt.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FontWrapper {
private Font font;
private Float currentFontTopCoef;
// private Font font;
// private Float currentFontTopCoef;
private Map<Float, Font> fontCache = new ConcurrentHashMap<>(4);
private Font baseFont;
public static final int DEFAULT_FONT_SIZE = 70;
public Font getFont() {
return getFont(DEFAULT_FONT_SIZE);
}
public Font getFont(float size) {
return fontCache.computeIfAbsent(size, k -> baseFont.deriveFont(Font.BOLD, size));
}
public FontWrapper(Font font) {
this(font, 70);
this.baseFont = font;
}
public FontWrapper(Font font, int fontSize) {
this.font = font;
this.font = font.deriveFont(Font.BOLD, fontSize);
}
public float getCurrentFontTopCoef() {
if (currentFontTopCoef != null) {
return currentFontTopCoef;
}
currentFontTopCoef = 0.14645833f * font.getSize() + 0.39583333f;
return currentFontTopCoef;
public float getFontTopCoef(Font font) {
return 0.14645833f * font.getSize() + 0.39583333f;
}
}
@@ -0,0 +1,69 @@
package cloud.tianai.captcha.generator.common.model.dto;
import java.util.*;
/**
* @Author: 天爱有情
* @Description 缓存键包装类,支持忽略指定字段
*/
public class CacheKey {
private final GenerateParam generateParam;
private final Set<String> ignoredFields;
/**
* 构造函数
*
* @param generateParam 生成参数
* @param ignoredFields 需要忽略的字段集合(不参与equals和hashCode计算)
*/
public CacheKey(GenerateParam generateParam, Set<String> ignoredFields) {
if (generateParam == null) {
throw new IllegalArgumentException("generateParam 不能为 null");
}
this.generateParam = generateParam;
this.ignoredFields = ignoredFields != null ? ignoredFields : Collections.emptySet();
}
/**
* 获取原始的GenerateParam
*/
public GenerateParam getGenerateParam() {
return generateParam;
}
/**
* 获取参与缓存计算的有效字段
*/
private Map<String, Object> getEffectiveFields() {
Map<String, Object> effectiveMap = new LinkedHashMap<>();
for (Map.Entry<String, Object> entry : generateParam.entrySet()) {
if (!ignoredFields.contains(entry.getKey())) {
effectiveMap.put(entry.getKey(), entry.getValue());
}
}
return effectiveMap;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CacheKey cacheKey = (CacheKey) o;
return Objects.equals(getEffectiveFields(), cacheKey.getEffectiveFields());
}
@Override
public int hashCode() {
return Objects.hash(getEffectiveFields());
}
@Override
public String toString() {
return "CacheKey{effectiveFields=" + getEffectiveFields() + "}";
}
}
@@ -1,6 +1,7 @@
package cloud.tianai.captcha.generator.common.model.dto;
import cloud.tianai.captcha.common.AnyMap;
import cloud.tianai.captcha.common.ParamKey;
import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -11,86 +12,93 @@ import lombok.EqualsAndHashCode;
* @Description 生成参数
*/
@Data
// param作为扩展字段暂时将param从equals和toString中移除掉 以适应 CacheImageCaptchaGenerator
@EqualsAndHashCode(exclude = "param")
public class GenerateParam {
@EqualsAndHashCode(callSuper = true)
public class GenerateParam extends AnyMap {
public GenerateParam() {
// 设置一些默认值
setBackgroundFormatName("jpeg");
setTemplateFormatName("png");
setObfuscate(false);
setType(CaptchaTypeConstant.SLIDER);
}
/**
* 背景格式化类型.
*/
private String backgroundFormatName = "jpeg";
private static final ParamKey<String> backgroundFormatName = () -> "backgroundFormatName";
/**
* 模板图片格式化类型.
*/
private String templateFormatName = "png";
private static final ParamKey<String> templateFormatName = () -> "templateFormatName";
/**
* 是否混淆.
*/
private Boolean obfuscate = false;
private static final ParamKey<Boolean> obfuscate = () -> "obfuscate";
/**
* 类型.
*/
private String type = CaptchaTypeConstant.SLIDER;
private static final ParamKey<String> type = () -> "type";
/**
* 背景图片标签, 用户二级过滤背景图片,或指定某背景图片.
*/
private String backgroundImageTag;
private static final ParamKey<String> backgroundImageTag = () -> "backgroundImageTag";
/**
* 滑动图片标签,用户二级过滤模板图片,或指定某模板图片..
*/
private String templateImageTag;
/**
* 扩展参数.
*/
private AnyMap param = new AnyMap();
private static final ParamKey<String> templateImageTag = () -> "templateImageTag";
public void addParam(String key, Object value) {
doGetOrCreateParam().put(key, value);
// =============== getter and setter ====================
public void setBackgroundFormatName(String backgroundFormatName) {
addParam(GenerateParam.backgroundFormatName, backgroundFormatName);
}
public Object getParam(String key) {
return param == null ? null : param.get(key);
public void setTemplateFormatName(String templateFormatName) {
addParam(GenerateParam.templateFormatName, templateFormatName);
}
private AnyMap doGetOrCreateParam() {
if (param == null) {
param = new AnyMap();
}
return param;
public void setObfuscate(boolean obfuscate) {
addParam(GenerateParam.obfuscate, obfuscate);
}
public Object removeParam(String key) {
if (param == null) {
return null;
}
return param.remove(key);
public void setType(String type) {
addParam(GenerateParam.type, type);
}
public Object getOrDefault(String key, Object defaultValue) {
if (param == null) {
return defaultValue;
}
return param.getOrDefault(key, defaultValue);
public void setBackgroundImageTag(String backgroundImageTag) {
addParam(GenerateParam.backgroundImageTag, backgroundImageTag);
}
public Object putIfAbsent(String key, Object value) {
return doGetOrCreateParam().putIfAbsent(key, value);
public void setTemplateImageTag(String templateImageTag) {
addParam(GenerateParam.templateImageTag, templateImageTag);
}
public <T> void addParam(ParamKey<T> paramKey, T value) {
addParam(paramKey.getKey(), value);
public String getBackgroundFormatName() {
return getParam(GenerateParam.backgroundFormatName);
}
public <T> T getParam(ParamKey<T> paramKey) {
return (T) getParam(paramKey.getKey());
public String getTemplateFormatName() {
return getParam(GenerateParam.templateFormatName);
}
public <T> T getOrDefault(ParamKey<T> paramKey, T defaultValue) {
return (T) getOrDefault(paramKey.getKey(), defaultValue);
public boolean getObfuscate() {
return getParam(GenerateParam.obfuscate);
}
public String getType() {
return getParam(GenerateParam.type);
}
public String getBackgroundImageTag() {
return getParam(GenerateParam.backgroundImageTag);
}
public String getTemplateImageTag() {
return getParam(GenerateParam.templateImageTag);
}
public static Builder builder() {
return new Builder();
}
@@ -102,7 +110,6 @@ public class GenerateParam {
private String type = CaptchaTypeConstant.SLIDER;
private String backgroundImageTag;
private String templateImageTag;
private AnyMap param = new AnyMap();
private Builder() {
}
@@ -137,20 +144,15 @@ public class GenerateParam {
return this;
}
public Builder param(AnyMap param) {
this.param = param;
return this;
}
public GenerateParam build() {
GenerateParam generateParam = new GenerateParam();
generateParam.backgroundFormatName = backgroundFormatName;
generateParam.templateFormatName = templateFormatName;
generateParam.obfuscate = obfuscate;
generateParam.type = type;
generateParam.backgroundImageTag = backgroundImageTag;
generateParam.templateImageTag = templateImageTag;
generateParam.param = param;
generateParam.setBackgroundFormatName(backgroundFormatName);
generateParam.setTemplateFormatName(templateFormatName);
generateParam.setObfuscate(obfuscate);
generateParam.setType(type);
generateParam.setBackgroundImageTag(backgroundImageTag);
generateParam.setTemplateImageTag(templateImageTag);
return generateParam;
}
}
@@ -1,12 +0,0 @@
package cloud.tianai.captcha.generator.common.model.dto;
/**
* @Author: 天爱有情
* @date 2024/11/20 11:34
* @Description 此接口的作用是在给 {@link GenerateParam} 添加/获取参数时做一个类型限制和转换
*/
public interface ParamKey<T> {
String getKey();
}
@@ -1,6 +1,7 @@
package cloud.tianai.captcha.generator.common.model.dto;
import cloud.tianai.captcha.common.ParamKey;
import lombok.AllArgsConstructor;
import lombok.Getter;
@@ -15,6 +16,11 @@ public class ParamKeyEnum<T> implements ParamKey<T> {
public static final ParamKey<Integer> CLICK_INTERFERENCE_COUNT = new ParamKeyEnum<>("interferenceCount");
/** 读取字体时,可指定字体TAG,可用于给不同的验证码指定不同的字体包.*/
public static final ParamKey<String> FONT_TAG = new ParamKeyEnum<>("fontTag");
/** 容错值.*/
public static final ParamKey<Number> TOLERANT = new ParamKeyEnum<>("tolerant");
/** 验证码ID,内部使用.*/
public static final ParamKey<String> ID = new ParamKeyEnum<>("_id");
private String key;
}
@@ -4,6 +4,7 @@ import lombok.SneakyThrows;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.CubicCurve2D;
import java.awt.geom.QuadCurve2D;
@@ -387,24 +388,29 @@ public class CaptchaImageUtils {
int interferencePointNum) {
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bufferedImage.createGraphics();
ThreadLocalRandom random = ThreadLocalRandom.current();
g.setFont(font);
char[] chars = data.toCharArray();
try {
ThreadLocalRandom random = ThreadLocalRandom.current();
g.setFont(font);
char[] chars = data.toCharArray();
for (int i = 0; i < chars.length; i++) {
g.setColor(Color.gray);
g.drawString(String.valueOf(chars[i]), startX + i * font.getSize(), startY);
for (int i = 0; i < chars.length; i++) {
g.setColor(Color.gray);
g.drawString(String.valueOf(chars[i]), startX + i * font.getSize(), startY);
}
// 干扰点
if (interferencePointNum > 0) {
drawOval(interferencePointNum, null, g, width, height, random);
}
if (interferencePointNum > 0) {
g.setStroke(new BasicStroke(1.2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
// 干扰线
drawBesselLine(interferenceLineNum, null, g, width, height, random);
}
return bufferedImage;
} finally {
// bugfix #IDIG16
g.dispose();
}
// 干扰点
if (interferencePointNum > 0) {
drawOval(interferencePointNum, null, g, width, height, random);
}
if (interferencePointNum > 0) {
g.setStroke(new BasicStroke(1.2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
// 干扰线
drawBesselLine(interferenceLineNum, null, g, width, height, random);
}
return bufferedImage;
}
@@ -520,5 +526,81 @@ public class CaptchaImageUtils {
return TYPE_PNG.equalsIgnoreCase(type);
}
}
/**
* 绘制水印
* @param bgImage 背景图片
* @param watermark 水印文字
* @param x x坐标起始位置
* @param y y坐标起始位置
* @param color 水印颜色
* @param font 水印字体
*/
public static void drawWatermark(BufferedImage bgImage, String watermark, int x, int y, Color color, Font font) {
// 参数校验
if (bgImage == null || watermark == null || watermark.isEmpty() || font == null) {
return;
}
// 获取Graphics2D对象
Graphics2D g2d = bgImage.createGraphics();
try {
// 设置渲染质量
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setColor(color);
// 设置字体
g2d.setFont(font);
// 计算文字尺寸
FontMetrics fontMetrics = g2d.getFontMetrics();
int textWidth = fontMetrics.stringWidth(watermark);
int textHeight = fontMetrics.getHeight();
// 计算旋转角度(45度角倾斜)
double angle = Math.toRadians(45);
// 计算水印间距,确保铺满整个图片
int spacingX = textWidth + 50;
int spacingY = textHeight + 50;
// 获取图片尺寸
int imageWidth = bgImage.getWidth();
int imageHeight = bgImage.getHeight();
// 计算需要绘制的水印数量
int rows = (int) Math.ceil((double) imageHeight / spacingY) + 2;
int cols = (int) Math.ceil((double) imageWidth / spacingX) + 2;
// 绘制水印,铺满整个图片
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
// 计算当前水印位置
int currentX = col * spacingX + x;
int currentY = row * spacingY + y;
// 保存当前坐标系
AffineTransform originalTransform = g2d.getTransform();
try {
// 平移到当前位置
g2d.translate(currentX, currentY);
// 旋转文字
g2d.rotate(angle);
// 绘制文字
g2d.drawString(watermark, 0, fontMetrics.getAscent());
} finally {
// 恢复原始坐标系
g2d.setTransform(originalTransform);
}
}
}
} finally {
// 释放资源
g2d.dispose();
}
}
}
@@ -34,10 +34,22 @@ public class ImgWriter {
if (ObjectUtils.isEmpty(imageType)) {
imageType = CaptchaImageUtils.TYPE_JPG;
}
ImageOutputStream imageOutputStream = transformImageOutputStream(destImageStream);
final BufferedImage bufferedImage = CaptchaImageUtils.toBufferedImage(image, imageType);
final ImageWriter writer = getWriter(bufferedImage, imageType);
return write(bufferedImage, writer, imageOutputStream, quality);
ImageOutputStream imageOutputStream = null;
try {
imageOutputStream = transformImageOutputStream(destImageStream);
final BufferedImage bufferedImage = CaptchaImageUtils.toBufferedImage(image, imageType);
final ImageWriter writer = getWriter(bufferedImage, imageType);
return write(bufferedImage, writer, imageOutputStream, quality);
} finally {
// 关闭 ImageOutputStream 防止资源泄露
if (imageOutputStream != null) {
try {
imageOutputStream.close();
} catch (IOException e) {
// 忽略关闭异常
}
}
}
}
/**
@@ -65,7 +65,7 @@ public abstract class AbstractClickImageCaptchaGenerator extends AbstractImageCa
}
// 随机获取点击图片
ClickImageCheckDefinition.ImgWrapper imgWrapper = getClickImg(param, clickResource, null);
ClickImageCheckDefinition.ImgWrapper imgWrapper = getClickImg(param, clickResource, null, bgImage);
BufferedImage image = imgWrapper.getImage();
// 增加功能,是否需要扭曲图片
image = obfuscateImage(image, param);
@@ -143,7 +143,7 @@ public abstract class AbstractClickImageCaptchaGenerator extends AbstractImageCa
* @param tip 提示数据,根据改数据生成图片
* @return ImgWrapper
*/
public abstract ClickImageCheckDefinition.ImgWrapper getClickImg(GenerateParam param, Resource tip, Color randomColor);
public abstract ClickImageCheckDefinition.ImgWrapper getClickImg(GenerateParam param, Resource tip, Color randomColor, BufferedImage bgImage);
@Data
@@ -3,6 +3,7 @@ package cloud.tianai.captcha.generator.impl;
import cloud.tianai.captcha.common.util.NamedThreadFactory;
import cloud.tianai.captcha.generator.ImageCaptchaGenerator;
import cloud.tianai.captcha.generator.ImageTransform;
import cloud.tianai.captcha.generator.common.model.dto.CacheKey;
import cloud.tianai.captcha.generator.common.model.dto.GenerateParam;
import cloud.tianai.captcha.generator.common.model.dto.ImageCaptchaInfo;
import cloud.tianai.captcha.interceptor.CaptchaInterceptor;
@@ -12,7 +13,7 @@ import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
@@ -22,19 +23,31 @@ import java.util.concurrent.atomic.AtomicInteger;
* @Description 滑块验证码缓冲器
*/
@Slf4j
public class CacheImageCaptchaGenerator implements ImageCaptchaGenerator {
public class CacheImageCaptchaGenerator implements ImageCaptchaGenerator, AutoCloseable {
protected final ScheduledExecutorService scheduledExecutor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("slider-captcha-queue"));
protected Map<GenerateParam, ConcurrentLinkedQueue<ImageCaptchaInfo>> queueMap = new ConcurrentHashMap<>(8);
protected Map<GenerateParam, AtomicInteger> posMap = new ConcurrentHashMap<>(8);
protected Map<GenerateParam, Long> lastUpdateMap = new ConcurrentHashMap<>(8);
protected Map<CacheKey, ConcurrentLinkedQueue<ImageCaptchaInfo>> queueMap = new ConcurrentHashMap<>(8);
protected Map<CacheKey, AtomicInteger> posMap = new ConcurrentHashMap<>(8);
protected Map<CacheKey, Long> lastUpdateMap = new ConcurrentHashMap<>(8);
/**
* 忽略的字段集合(不参与缓存key计算),默认为空
*/
@Getter
@Setter
protected Set<String> ignoredCacheFields = Collections.emptySet();
protected ImageCaptchaGenerator target;
protected int size;
/** 等待时间,一般报错或者拉取为空时会休眠一段时间再试. */
/**
* 等待时间,一般报错或者拉取为空时会休眠一段时间再试.
*/
protected int waitTime = 1000;
/** 调度器检查缓存的间隔时间. */
/**
* 调度器检查缓存的间隔时间.
*/
protected int period = 5000;
/** 10天内没有任何操作就删除已缓存的数据. */
/**
* 10天内没有任何操作就删除已缓存的数据.
*/
protected long expireTime = TimeUnit.DAYS.toMillis(10);
@Getter
@Setter
@@ -59,7 +72,7 @@ public class CacheImageCaptchaGenerator implements ImageCaptchaGenerator {
this.size = size;
this.waitTime = waitTime;
this.period = period;
if (expireTime != null){
if (expireTime != null) {
this.expireTime = expireTime;
}
}
@@ -77,15 +90,18 @@ public class CacheImageCaptchaGenerator implements ImageCaptchaGenerator {
}
this.size = z;
// 初始化一个队列扫描
scheduledExecutor.scheduleAtFixedRate(() -> queueMap.forEach((k, queue) -> {
scheduledExecutor.scheduleAtFixedRate(() -> queueMap.forEach((cacheKey, queue) -> {
try {
AtomicInteger pos = posMap.computeIfAbsent(k, k1 -> new AtomicInteger(0));
AtomicInteger pos = posMap.computeIfAbsent(cacheKey, k1 -> new AtomicInteger(0));
int addCount = 0;
while (pos.get() < this.size) {
if (pos.get() >= size) {
return;
}
ImageCaptchaInfo slideImageInfo = target.generateCaptchaImage(k);
GenerateParam generateParam = cacheKey.getGenerateParam();
generateParam = beforeGenerateCaptchaImage(generateParam);
// 使用原始GenerateParam生成验证码
ImageCaptchaInfo slideImageInfo = target.generateCaptchaImage(generateParam);
if (slideImageInfo != null) {
boolean addStatus = queue.offer(slideImageInfo);
addCount++;
@@ -99,20 +115,20 @@ public class CacheImageCaptchaGenerator implements ImageCaptchaGenerator {
}
if (addCount == 0) {
// 没有添加,检测最新更新时间 如果时间过长,直接清除数据
Long lastUpdate = lastUpdateMap.get(k);
Long lastUpdate = lastUpdateMap.get(cacheKey);
if (lastUpdate != null && System.currentTimeMillis() - lastUpdate > expireTime) {
queueMap.remove(k);
posMap.remove(k);
lastUpdateMap.remove(k);
queueMap.remove(cacheKey);
posMap.remove(cacheKey);
lastUpdateMap.remove(cacheKey);
}
}
} catch (Exception e) {
// cache所有
log.error("缓存队列扫描时出错, ex", e);
// 删掉它
queueMap.remove(k);
posMap.remove(k);
lastUpdateMap.remove(k);
queueMap.remove(cacheKey);
posMap.remove(cacheKey);
lastUpdateMap.remove(cacheKey);
// 休眠
sleep();
}
@@ -120,6 +136,7 @@ public class CacheImageCaptchaGenerator implements ImageCaptchaGenerator {
init = true;
}
private void sleep() {
try {
TimeUnit.MILLISECONDS.sleep(waitTime);
@@ -131,7 +148,8 @@ public class CacheImageCaptchaGenerator implements ImageCaptchaGenerator {
public ImageCaptchaGenerator init() {
ImageCaptchaGenerator captchaGenerator = target.init();
// 初始化缓存
init(size);;
init(size);
return captchaGenerator;
}
@@ -145,21 +163,25 @@ public class CacheImageCaptchaGenerator implements ImageCaptchaGenerator {
@SneakyThrows
public ImageCaptchaInfo generateCaptchaImage(GenerateParam generateParam, boolean requiredGetCaptcha) {
ConcurrentLinkedQueue<ImageCaptchaInfo> queue = queueMap.get(generateParam);
// 创建CacheKey
CacheKey cacheKey = new CacheKey(generateParam, ignoredCacheFields);
ConcurrentLinkedQueue<ImageCaptchaInfo> queue = queueMap.get(cacheKey);
ImageCaptchaInfo captchaInfo = null;
if (queue != null) {
captchaInfo = queue.poll();
if (captchaInfo == null) {
log.warn("滑块验证码缓存不足, genParam:{}", generateParam);
} else {
AtomicInteger pos = posMap.get(generateParam);
AtomicInteger pos = posMap.get(cacheKey);
if (pos != null) {
pos.decrementAndGet();
}
}
} else {
queueMap.putIfAbsent(generateParam, new ConcurrentLinkedQueue<>());
posMap.putIfAbsent(generateParam, new AtomicInteger(0));
cacheKey = beforeAddQueue(cacheKey);
queueMap.putIfAbsent(cacheKey, new ConcurrentLinkedQueue<>());
posMap.putIfAbsent(cacheKey, new AtomicInteger(0));
}
if (captchaInfo == null && requiredGetCaptcha) {
// 直接生成 不走缓存
@@ -167,11 +189,12 @@ public class CacheImageCaptchaGenerator implements ImageCaptchaGenerator {
}
if (captchaInfo != null) {
// 记录最新时间
lastUpdateMap.put(generateParam, System.currentTimeMillis());
lastUpdateMap.put(cacheKey, System.currentTimeMillis());
}
return captchaInfo;
}
@Override
public ImageCaptchaInfo generateCaptchaImage(String type, String targetFormatName, String matrixFormatName) {
return generateCaptchaImage(GenerateParam.builder().type(type).backgroundFormatName(targetFormatName).templateFormatName(matrixFormatName).build(), true);
@@ -212,4 +235,61 @@ public class CacheImageCaptchaGenerator implements ImageCaptchaGenerator {
target.setInterceptor(interceptor);
}
/**
* 销毁方法,关闭定时任务线程池并清理缓存
* 应该在不再使用此 Generator 时调用,以防止线程和内存泄露
*/
public void destroy() {
try {
scheduledExecutor.shutdown();
if (!scheduledExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
scheduledExecutor.shutdownNow();
if (!scheduledExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
log.warn("CacheImageCaptchaGenerator 定时任务线程池未能正常关闭");
}
}
} catch (InterruptedException e) {
scheduledExecutor.shutdownNow();
Thread.currentThread().interrupt();
log.warn("CacheImageCaptchaGenerator 定时任务线程池关闭时被中断", e);
}
// 清理缓存
queueMap.clear();
posMap.clear();
lastUpdateMap.clear();
}
/**
* 实现 AutoCloseable 接口,支持 try-with-resources 语法
* 调用 destroy() 方法释放资源
*/
@Override
public void close() {
destroy();
}
//=============== 模板方法 =============
/**
* 添加到队列前扩展的函数
*
* @param cacheKey cacheKey
* @return CacheKey
*/
public CacheKey beforeAddQueue(CacheKey cacheKey) {
return cacheKey;
}
/**
* 生成验证码前调用的函数, 方便子类扩展
*
* @param generateParam generateParam
* @return GenerateParam
*/
public GenerateParam beforeGenerateCaptchaImage(GenerateParam generateParam) {
return generateParam;
}
}
@@ -113,11 +113,15 @@ public class StandardSliderImageCaptchaGenerator extends AbstractImageCaptchaGen
int type = fixedImage.getColorModel().getTransparency();
BufferedImage image = new BufferedImage(width, height, type);
Graphics2D graphics = image.createGraphics();
// 透明度
double alpha = ThreadLocalRandom.current().nextDouble(0.5, 0.8);
AlphaComposite alphaComposite = AlphaComposite.Src.derive((float) alpha);
graphics.setComposite(alphaComposite);
graphics.drawImage(fixedImage, 0, 0, width, height, null);
try {
// 透明度
double alpha = ThreadLocalRandom.current().nextDouble(0.5, 0.8);
AlphaComposite alphaComposite = AlphaComposite.Src.derive((float) alpha);
graphics.setComposite(alphaComposite);
graphics.drawImage(fixedImage, 0, 0, width, height, null);
} finally {
graphics.dispose();
}
return image;
}
@@ -35,11 +35,7 @@ public class StandardWordClickImageCaptchaGenerator extends AbstractClickImageCa
// @Getter
// @Setter
// protected List<FontWrapper> fonts = new ArrayList<>();
@Getter
@Setter
protected Integer clickImgWidth = 100;
@Getter
@Setter
protected Integer clickImgHeight = 100;
@Getter
@Setter
@@ -95,6 +91,33 @@ public class StandardWordClickImageCaptchaGenerator extends AbstractClickImageCa
return tipList;
}
@Override
public ClickImageCheckDefinition.ImgWrapper getClickImg(GenerateParam param, Resource tip, Color randomColor, BufferedImage bgImage) {
if (randomColor == null) {
ThreadLocalRandom random = ThreadLocalRandom.current();
randomColor = CaptchaImageUtils.getRandomColor(random);
}
// 随机角度
int randomDeg = randomInt(0, 85);
// 缩放
double factor = (double) bgImage.getWidth(null) / 600d;
FontWrapper fontWrapper = randomFont(param);
Font font = fontWrapper.getFont((float) (FontWrapper.DEFAULT_FONT_SIZE * factor));
float currentFontTopCoef = fontWrapper.getFontTopCoef(font);
// 图片点击宽度
int clickImgWidth = (int) (font.getSize() * 1.428571428571429);
BufferedImage fontImage = CaptchaImageUtils.drawWordImg(randomColor,
tip.getData(),
font,
currentFontTopCoef,
clickImgWidth,
clickImgWidth,
randomDeg);
return new ClickImageCheckDefinition.ImgWrapper(fontImage, tip, randomColor);
}
@Override
protected void doInit() {
// if (CollectionUtils.isEmpty(fonts)) {
@@ -115,10 +138,12 @@ public class StandardWordClickImageCaptchaGenerator extends AbstractClickImageCa
throw new ImageCaptchaException("随机获取字体失败, resource中没有读到字体包, resource=" + resource);
}
public ClickImageCheckDefinition.ImgWrapper genTipImage(List<ClickImageCheckDefinition> imageCheckDefinitions, GenerateParam param) {
FontWrapper fontWrapper = randomFont(param);
Font font = fontWrapper.getFont();
float currentFontTopCoef = fontWrapper.getCurrentFontTopCoef();
float currentFontTopCoef = fontWrapper.getFontTopCoef(font);
String tips = imageCheckDefinitions.stream().map(c -> c.getTip().getData()).collect(Collectors.joining());
// 生成随机颜色
int fontWidth = tips.length() * font.getSize();
@@ -140,27 +165,6 @@ public class StandardWordClickImageCaptchaGenerator extends AbstractClickImageCa
// }
@Override
public ClickImageCheckDefinition.ImgWrapper getClickImg(GenerateParam param, Resource tip, Color randomColor) {
if (randomColor == null) {
ThreadLocalRandom random = ThreadLocalRandom.current();
randomColor = CaptchaImageUtils.getRandomColor(random);
}
// 随机角度
int randomDeg = randomInt(0, 85);
FontWrapper fontWrapper = randomFont(param);
Font font = fontWrapper.getFont();
float currentFontTopCoef = fontWrapper.getCurrentFontTopCoef();
BufferedImage fontImage = CaptchaImageUtils.drawWordImg(randomColor,
tip.getData(),
font,
currentFontTopCoef,
clickImgWidth,
clickImgHeight,
randomDeg);
return new ClickImageCheckDefinition.ImgWrapper(fontImage, tip, randomColor);
}
@Override
protected List<ClickImageCheckDefinition> filterAndSortClickImageCheckDefinition(CaptchaExchange captchaExchange, List<ClickImageCheckDefinition> allCheckDefinitionList) {
GenerateParam param = captchaExchange.getParam();
@@ -29,16 +29,24 @@ public class Base64ImageTransform implements ImageTransform {
return result;
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
if (CaptchaImageUtils.isPng(transformType) || CaptchaImageUtils.isJpeg(transformType)) {
// 如果是 jpg 或者 png图片的话 用hutool的生成
ImgWriter.write(bufferedImage, transformType, byteArrayOutputStream, -1);
} else {
ImageIO.write(bufferedImage, transformType, byteArrayOutputStream);
try {
if (CaptchaImageUtils.isPng(transformType) || CaptchaImageUtils.isJpeg(transformType)) {
// 如果是 jpg 或者 png图片的话 用hutool的生成
ImgWriter.write(bufferedImage, transformType, byteArrayOutputStream, -1);
} else {
ImageIO.write(bufferedImage, transformType, byteArrayOutputStream);
}
//转换成字节码
byte[] data = byteArrayOutputStream.toByteArray();
String base64 = Base64.getEncoder().encodeToString(data);
return "data:image/" + transformType + ";base64,".concat(base64);
} finally {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
// 忽略关闭异常
}
}
//转换成字节码
byte[] data = byteArrayOutputStream.toByteArray();
String base64 = Base64.getEncoder().encodeToString(data);
return "data:image/" + transformType + ";base64,".concat(base64);
}
public String beforeTransform(BufferedImage bufferedImage, String formatType) {
@@ -3,8 +3,6 @@ package cloud.tianai.captcha.resource;
import cloud.tianai.captcha.generator.common.FontWrapper;
import cloud.tianai.captcha.resource.common.model.dto.Resource;
import cloud.tianai.captcha.resource.common.model.dto.ResourceMap;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import java.awt.*;
@@ -24,15 +22,14 @@ public class FontCache implements ResourceStore {
public static final String FONT_TYPE = "font";
/**
* 字体缓存最大数量,防止内存泄露
*/
private static final int MAX_FONT_CACHE_SIZE = 100;
private final Map<String, FontWrapper> fontMap = new ConcurrentHashMap<>();
private ResourceStore resourceStore;
private ImageCaptchaResourceManager resourceManager;
@Setter
@Getter
private int fontSize = 70;
public FontCache(ResourceStore resourceStore) {
this.resourceStore = resourceStore;
@@ -48,7 +45,7 @@ public class FontCache implements ResourceStore {
public FontWrapper getFont(Resource resource) {
try (InputStream stream = resourceManager.getResourceInputStream(resource)) {
Font font = Font.createFont(0, stream);
return new FontWrapper(font, fontSize);
return new FontWrapper(font);
} catch (FontFormatException | IOException e) {
throw new RuntimeException(e);
}
@@ -60,11 +57,25 @@ public class FontCache implements ResourceStore {
return resource.getType() + "_" + resource.getData();
}
/**
* 检查缓存大小,如果超过限制则清理
*/
private void checkCacheSize() {
if (fontMap.size() > MAX_FONT_CACHE_SIZE) {
log.warn("字体缓存超过限制大小: {},执行清理", fontMap.size());
// 简单清理策略:清空缓存
// 如果需要更精细的 LRU 策略,可以使用 LinkedHashMap 或第三方缓存库
fontMap.clear();
}
}
@Override
public List<Resource> randomGetResourceByTypeAndTag(String type, String tag, Integer quantity) {
List<Resource> resources = resourceStore.randomGetResourceByTypeAndTag(type, tag, quantity);
// 字体增强
if (FONT_TYPE.equalsIgnoreCase(type)) {
// 在添加新字体前检查缓存大小
checkCacheSize();
for (Resource resource : resources) {
FontWrapper fontWrapper = fontMap.computeIfAbsent(calcId(resource), v -> getFont(resource));
resource.setExtra(fontWrapper);
@@ -1,18 +1,7 @@
package cloud.tianai.captcha.validator.common.model.dto;
import lombok.Data;
import cloud.tianai.captcha.common.AnyMap;
public class Drives extends AnyMap {
@Data
public class Drives {
private Integer hardwareConcurrency;
private Boolean hasXhr = false;
private String href;
private String language;
private Long start;
private Long now;
private String platform;
private Integer scripts;
private String userAgent;
private Integer windowHeight;
private Integer windowWidth;
}
@@ -1,5 +1,7 @@
package cloud.tianai.captcha.validator.common.model.dto;
import cloud.tianai.captcha.common.AnyMap;
import cloud.tianai.captcha.common.ParamKey;
import lombok.Data;
import lombok.NoArgsConstructor;
@@ -10,22 +12,35 @@ import lombok.NoArgsConstructor;
*/
@Data
@NoArgsConstructor
public class MatchParam {
/** 轨迹信息. */
private ImageCaptchaTrack track;
/** 检测到的设备信息. */
private Drives drives;
/** 留一个扩展属性. */
private Object extendData;
public class MatchParam extends AnyMap {
private static final ParamKey<ImageCaptchaTrack> track = () -> "track";
private static final ParamKey<Drives> drives = () -> "drives";
public ImageCaptchaTrack getTrack() {
return getParam(MatchParam.track);
}
public Drives getDrives() {
return getParam(MatchParam.drives);
}
public void setTrack(ImageCaptchaTrack track) {
addParam(MatchParam.track, track);
}
public void setDrives(Drives drives) {
addParam(MatchParam.drives, drives);
}
public MatchParam(ImageCaptchaTrack track) {
this.track = track;
this.setTrack(track);
}
public MatchParam(ImageCaptchaTrack track, Drives drives) {
this.track = track;
this.drives = drives;
this.setTrack(track);
this.setDrives(drives);
}
}
@@ -66,7 +66,7 @@ public class ApplicationTest {
ImageCaptchaProperties prop = new ImageCaptchaProperties();
// application 验证码封装, prop为所需的一些扩展参数
ImageCaptchaApplication application = new DefaultImageCaptchaApplication(generator, imageCaptchaValidator, cacheStore, prop, group, null);
ImageCaptchaApplication application = new DefaultImageCaptchaApplication(generator, imageCaptchaValidator, cacheStore, prop, group);
return application;
}
}
@@ -14,47 +14,101 @@ import cloud.tianai.captcha.resource.common.model.dto.Resource;
import cloud.tianai.captcha.resource.common.model.dto.ResourceMap;
import cloud.tianai.captcha.resource.impl.LocalMemoryResourceStore;
import cloud.tianai.captcha.resource.impl.provider.ClassPathResourceProvider;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import java.awt.*;
import static cloud.tianai.captcha.common.constant.CommonConstant.DEFAULT_TAG;
import static cloud.tianai.captcha.generator.impl.StandardSliderImageCaptchaGenerator.TEMPLATE_ACTIVE_IMAGE_NAME;
import static cloud.tianai.captcha.generator.impl.StandardSliderImageCaptchaGenerator.TEMPLATE_FIXED_IMAGE_NAME;
public class TACBuilderTest {
public void test() {
ResourceMap template1 = new ResourceMap(DEFAULT_TAG, 2);
// 滑块轮廓图片
template1.put(TEMPLATE_ACTIVE_IMAGE_NAME, new Resource("classpath", "META-INF/cut-image/template/slider_1/active.png"));
// 滑块凹槽图片
template1.put(TEMPLATE_FIXED_IMAGE_NAME, new Resource("classpath", "META-INF/cut-image/template/slider_1/fixed.png"));
// 给旋转验证码配置模板
ResourceMap template2 = new ResourceMap(DEFAULT_TAG, 2);
// 旋转验证码轮廓图片
template2.put(TEMPLATE_ACTIVE_IMAGE_NAME, new Resource("classpath", "META-INF/cut-image/template/rotate_1/active.png"));
// 旋转验证码凹槽图片
template2.put(TEMPLATE_FIXED_IMAGE_NAME, new Resource("classpath", "META-INF/cut-image/template/rotate_1/fixed.png"));
ImageCaptchaApplication application = TACBuilder.builder()
// 设置资源存储器,默认是 LocalMemoryResourceStore
.setResourceStore(new LocalMemoryResourceStore())
// 配置模板
.addTemplate(CaptchaTypeConstant.SLIDER,template1)
.addTemplate(CaptchaTypeConstant.ROTATE,template2)
// ...其他配置
.build();
}
public static void main(String[] args) throws InterruptedException {
Font font= null;
Font font = null;
// ResourceMap template1 = new ResourceMap("default", 4);
// template1.put(StandardSliderImageCaptchaGenerator.TEMPLATE_ACTIVE_IMAGE_NAME, new Resource(ClassPathResourceProvider.NAME, "/active.png"));
// template1.put(StandardSliderImageCaptchaGenerator.TEMPLATE_FIXED_IMAGE_NAME, new Resource(ClassPathResourceProvider.NAME, "/fixed.png"));
ImageCaptchaApplication application = TACBuilder.builder(new LocalMemoryResourceStore())
// 加载系统自带的默认资源
ImageCaptchaApplication application = TACBuilder.builder()
// 设置资源存储器,默认是 LocalMemoryResourceStore
// .setResourceStore(new LocalMemoryResourceStore())
// 加载系统自带的默认资源(系统内置了几个滑块验证码缺口模板图,调用此函数加载)
.addDefaultTemplate()
// 设置验证码过期时间
// 设置验证码过期时间, 单位毫秒, default 是默认验证码过期时间,当前设置为10秒,
// 可以自定义某些验证码类型单独的过期时间, 比如把点选验证码的过期时间设置为60秒
.expire("default", 10000L)
.expire("WORD_IMAGE_CLICK", 60000L)
// 设置拦截器
.expire(CaptchaTypeConstant.WORD_IMAGE_CLICK, 60000L)
// 设置拦截器,默认是 EmptyCaptchaInterceptor.INSTANCE
.setInterceptor(EmptyCaptchaInterceptor.INSTANCE)
// 添加验证码背景图片
.addResource("SLIDER", new Resource("classpath", "META-INF/cut-image/resource/1.jpg"))
.addResource("WORD_IMAGE_CLICK", new Resource("classpath", "META-INF/cut-image/resource/1.jpg"))
.addResource("ROTATE", new Resource("classpath", "META-INF/cut-image/resource/1.jpg"))
// arg1 验证码类型(SLIDER、WORD_IMAGE_CLICK、ROTATE、CONCAT),
// arg2 验证码背景图片资源
.addResource(CaptchaTypeConstant.SLIDER, new Resource("classpath", "META-INF/cut-image/resource/1.jpg"))
.addResource(CaptchaTypeConstant.SLIDER, new Resource("classpath", "META-INF/cut-image/resource/1.jpg"))
.addResource(CaptchaTypeConstant.WORD_IMAGE_CLICK, new Resource("classpath", "META-INF/cut-image/resource/1.jpg"))
.addResource(CaptchaTypeConstant.ROTATE, new Resource("classpath", "META-INF/cut-image/resource/1.jpg"))
.addResource(CaptchaTypeConstant.CONCAT, new Resource("classpath", "META-INF/cut-image/resource/1.jpg"))
// 添加验证码模板图片
// .addTemplate("SLIDER",template1)
// 设置缓冲器,可提前生成验证码,用于增加并发性
// 设置缓存器,可提前生成验证码,用于增加并发性,可以不设置,默认是不开启缓存
.cached(10, 1000, 5000, 10000L)
// 添加字体包,用于给文字点选验证码提供字体
.addFont(new Resource("file", "C:\\Users\\Thinkpad\\Desktop\\captcha\\手写字体\\ttf\\千图小兔体.ttf"))
// 设置缓存存储器,如果要支持分布式,需要把这里改成分布式缓存,比如通过redis实现的 CacheStore 缓存
.setCacheStore(new LocalCacheStore())
// 设置资源存储器,如果想在分布式环境或者想统一管理以及扩展 实现 ResourceStore 接口,自定义
// .setResourceStore(new LocalMemoryResourceStore())
// 图片转换器,默认是将图片转换成base64格式, 背景图为jpg, 模板图为png, 如果想要扩展,可替换成自己实现的
.setTransform(new Base64ImageTransform())
.build();
while (true){
while (true) {
long start = System.currentTimeMillis();
ApiResponse<ImageCaptchaVO> response = application.generateCaptcha("SLIDER");
// 生成验证码
// arg1 验证码类型(SLIDER、WORD_IMAGE_CLICK、ROTATE、CONCAT)
// response 为生成的验证码数据,可直接返回给前端
ApiResponse<ImageCaptchaVO> response = application.generateCaptcha(CaptchaTypeConstant.SLIDER);
// 校验验证码
// captchaId 和 track 数据应该是前端传来的验证数据
String captchaId = "";
ImageCaptchaTrack track = null;
ApiResponse<?> matching = application.matching(captchaId, track);
if (matching.isSuccess()) {
System.out.println("校验成功");
} else {
System.out.println("校验失败:" + matching.getMsg());
}
System.out.println("耗时:" + (System.currentTimeMillis() - start));
// System.out.println(response);
Thread.sleep(1000);