Skip to content

Commit

Permalink
1. 优化插件配置加载逻辑,使用ReactiveSettingFetcher获取配置
Browse files Browse the repository at this point in the history
2. 更新插件和依赖版本,删除无用的注解和工具类,重构图片上传相关逻辑,优化异常处理,提升代码可读性和可维护性。
  • Loading branch information
liuyiwuqing committed Dec 19, 2024
1 parent 15e9857 commit 850e9ed
Show file tree
Hide file tree
Showing 11 changed files with 294 additions and 332 deletions.
6 changes: 3 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ plugins {
id 'java'
id "com.github.node-gradle.node" version "7.0.2"
id "io.freefair.lombok" version "8.0.1"
id "run.halo.plugin.devtools" version "0.3.0"
id "run.halo.plugin.devtools" version "0.4.1"
}

group 'site.muyin.picturebed'
Expand All @@ -18,7 +18,7 @@ repositories {
}

dependencies {
implementation platform('run.halo.tools.platform:plugin:2.20.0-SNAPSHOT')
implementation platform('run.halo.tools.platform:plugin:2.20.11-SNAPSHOT')
compileOnly 'run.halo.app:api'

testImplementation 'run.halo.app:api'
Expand Down Expand Up @@ -55,7 +55,7 @@ build {
}

halo {
version = '2.20.8'
version = '2.20.12'
debug = true
}

Expand Down
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
@@ -1 +1 @@
version=1.2.2
version=1.2.3
35 changes: 20 additions & 15 deletions src/main/java/site/muyin/picturebed/PictureBedEndpoint.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,23 @@
import reactor.core.publisher.Mono;
import run.halo.app.core.extension.endpoint.CustomEndpoint;
import run.halo.app.extension.GroupVersion;
import run.halo.app.plugin.ReactiveSettingFetcher;
import site.muyin.picturebed.config.PictureBedConfig;
import site.muyin.picturebed.query.CommonQuery;
import site.muyin.picturebed.service.PictureBedService;
import site.muyin.picturebed.utils.PluginCacheManager;
import site.muyin.picturebed.vo.AlbumVO;
import site.muyin.picturebed.vo.PageResult;
import site.muyin.picturebed.vo.PictureBedVO;
import site.muyin.picturebed.vo.ResultsVO;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.springdoc.core.fn.builders.apiresponse.Builder.responseBuilder;
import static org.springdoc.core.fn.builders.content.Builder.contentBuilder;
import static org.springdoc.core.fn.builders.requestbody.Builder.requestBodyBuilder;
import static org.springdoc.core.fn.builders.schema.Builder.schemaBuilder;
import static org.springframework.web.reactive.function.server.RequestPredicates.contentType;
import static site.muyin.picturebed.config.PictureBedConfig.GROUP;

/**
* @author: lywq
Expand All @@ -43,7 +43,7 @@ public class PictureBedEndpoint implements CustomEndpoint {

private final PictureBedService pictureBedService;

private final PluginCacheManager pluginCacheManager;
private final ReactiveSettingFetcher settingFetcher;

@Override
public RouterFunction<ServerResponse> endpoint() {
Expand Down Expand Up @@ -137,17 +137,22 @@ private Mono<ServerResponse> deleteImage(ServerRequest serverRequest) {
}

private Mono<ServerResponse> getPictureBeds(ServerRequest serverRequest) {
PictureBedConfig config = pluginCacheManager.getConfig(PictureBedConfig.class);
List<PictureBedVO> pictureBeds = new ArrayList<>();
config.getPictureBeds().forEach(pictureBed -> {
PictureBedVO pictureBedVO = new PictureBedVO();
pictureBedVO.setKey(pictureBed.getPictureBedType() + "_" + pictureBed.getPictureBedId())
.setName(pictureBed.getPictureBedName())
.setType(pictureBed.getPictureBedType())
.setEnabled(pictureBed.getPictureBedEnabled());
pictureBeds.add(pictureBedVO);
});
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8).bodyValue(pictureBeds);
return settingFetcher.fetch(GROUP, PictureBedConfig.class)
.map(config -> config.getPictureBeds().stream()
.map(this::convertToPictureBedVO)
.collect(Collectors.toList()))
.flatMap(pictureBeds -> ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(pictureBeds));
}

private PictureBedVO convertToPictureBedVO(PictureBedConfig.PictureBed pictureBed) {
PictureBedVO pictureBedVO = new PictureBedVO();
pictureBedVO.setKey(pictureBed.getPictureBedType() + "_" + pictureBed.getPictureBedId())
.setName(pictureBed.getPictureBedName())
.setType(pictureBed.getPictureBedType())
.setEnabled(pictureBed.getPictureBedEnabled());
return pictureBedVO;
}

@Override
Expand Down
18 changes: 0 additions & 18 deletions src/main/java/site/muyin/picturebed/annotation/GroupName.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import lombok.Data;
import lombok.experimental.Accessors;
import site.muyin.picturebed.annotation.GroupName;

import java.util.List;
import java.util.Map;
Expand All @@ -15,18 +14,17 @@
**/
@Data
@Accessors(chain = true)
@GroupName("basic")
public class PictureBedConfig {

public static final String GROUP = "basic";
public static final String CONFIG_MAP_NAME = "picture-bed-config";

private Map slots;

private Map<String, Object> slots;
private List<PictureBed> pictureBeds;

@Data
@Accessors(chain = true)
public class PictureBed {
public static class PictureBed {
private String pictureBedId;
private String pictureBedName;
private Boolean pictureBedEnabled;
Expand Down

This file was deleted.

114 changes: 78 additions & 36 deletions src/main/java/site/muyin/picturebed/service/Impl/ImgtpServiceImpl.java
Original file line number Diff line number Diff line change
@@ -1,32 +1,37 @@
package site.muyin.picturebed.service.Impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import io.netty.channel.ChannelOption;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;
import run.halo.app.plugin.ReactiveSettingFetcher;
import site.muyin.picturebed.config.PictureBedConfig;
import site.muyin.picturebed.domain.ImgtpImage;
import site.muyin.picturebed.query.CommonQuery;
import site.muyin.picturebed.service.ImgtpService;
import site.muyin.picturebed.utils.PluginCacheManager;
import site.muyin.picturebed.vo.PageResult;
import site.muyin.picturebed.vo.ResultsVO;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static site.muyin.picturebed.config.PictureBedConfig.GROUP;
import static site.muyin.picturebed.constant.CommonConstant.PictureBedType.IMGTP;

/**
Expand All @@ -35,11 +40,22 @@
* @version: v1.0.0
* @description: Imgtp图床服务接口
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class ImgtpServiceImpl implements ImgtpService {

private final PluginCacheManager pluginCacheManager;
private final ReactiveSettingFetcher settingFetcher;

private final WebClient webClient = WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(
HttpClient.create()
.responseTimeout(Duration.ofSeconds(5)) // 设置响应超时时间
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) // 设置连接超时时间
))
.defaultHeader(HttpHeaders.CACHE_CONTROL, "no-cache")
.defaultHeader(HttpHeaders.PRAGMA, "no-cache")
.build();

@Override
public Mono<ResultsVO> uploadImage(CommonQuery query, MultiValueMap<String, ?> multipartData) {
Expand All @@ -62,7 +78,7 @@ public Mono<PageResult<ImgtpImage>> getImageList(CommonQuery query) {
String params = HttpUtil.toParams(paramMap);

return req(query.getPictureBedId(), "images" + "?" + params, null)
.map(response -> {
.mapNotNull(response -> {
if (response.code == 200) {
ImgtpImagePageRes imgtpImagePageRes = JSONUtil.toBean(JSONUtil.toJsonStr(response.data), ImgtpImagePageRes.class);
return new PageResult<>(imgtpImagePageRes.current_page, imgtpImagePageRes.per_page, imgtpImagePageRes.total, imgtpImagePageRes.last_page, imgtpImagePageRes.data);
Expand All @@ -86,42 +102,68 @@ public Mono<Boolean> deleteImage(CommonQuery query) {
}

private Mono<ImgtpResponseRecord> req(String pictureBedId, String path, Map<String, Object> paramMap) {
PictureBedConfig pictureBedConfig = pluginCacheManager.getConfig(PictureBedConfig.class);
PictureBedConfig.PictureBed config = pictureBedConfig.getPictureBeds().stream().filter(p -> p.getPictureBedType().equals(IMGTP) && p.getPictureBedId().equals(pictureBedId)).findFirst().orElseThrow();
String url = config.getPictureBedUrl();
String authorization = config.getPictureBedToken();

WebClient WEB_CLIENT =
WebClient.builder()
.defaultHeader("token", authorization).build();

if (StrUtil.startWithAny(path, "images", "delete")) {
return WEB_CLIENT.post()
.uri(url + path)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {
});
} else if (StrUtil.equals(path, "upload")) {
MultiValueMap<String, ?> multiValueMap = (MultiValueMap<String, ?>) paramMap.get("file");
MultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>();
multipartData.add("image", multiValueMap.getFirst("file"));

return WEB_CLIENT.post()
.uri(url + path)
.header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE)
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData(multipartData))
.retrieve()
.bodyToMono(new ParameterizedTypeReference<>() {
});

} else {
throw new IllegalArgumentException("Unsupported path: " + path);
if (path == null) {
return Mono.error(new IllegalArgumentException("Path cannot be null"));
}

return settingFetcher.fetch(GROUP, PictureBedConfig.class)
.flatMap(pictureBedConfig -> {

PictureBedConfig.PictureBed config = pictureBedConfig.getPictureBeds().stream()
.filter(p -> p.getPictureBedType().equals(IMGTP) && p.getPictureBedId().equals(pictureBedId))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("PictureBed config not found for ID: " + pictureBedId));

String url = config.getPictureBedUrl();
String authorization = config.getPictureBedToken();

WebClient client = webClient.mutate()
.defaultHeader("token", authorization)
.build();

switch (path) {
case "images":
case "delete":
return client.post()
.uri(url + path)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<ImgtpResponseRecord>() {
})
.doOnError(error -> log.error("POST request failed", error))
.onErrorResume(error -> Mono.empty());

case "upload":
MultiValueMap<String, ?> multiValueMap = (MultiValueMap<String, ?>) paramMap.get("file");
if (multiValueMap == null || multiValueMap.isEmpty()) {
return Mono.error(new IllegalArgumentException("File parameter is missing"));
}

MultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>();
multipartData.add("image", multiValueMap.getFirst("file"));

return client.post()
.uri(url + path)
.header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE)
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData(multipartData))
.retrieve()
.bodyToMono(new ParameterizedTypeReference<ImgtpResponseRecord>() {
})
.doOnError(error -> log.error("POST request failed", error))
.onErrorResume(error -> Mono.empty());

default:
return Mono.error(new IllegalArgumentException("Unsupported path: " + path));
}
})
.onErrorResume(error -> {
log.error("Configuration fetch failed", error);
return Mono.empty();
});
}

@Data
class ImgtpImagePageRes {
static class ImgtpImagePageRes {
Integer total;
Integer per_page;
Integer current_page;
Expand Down
Loading

0 comments on commit 850e9ed

Please sign in to comment.