Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 656ee0bcb4 | |||
| 3e9d0b4441 | |||
| 5a13068143 | |||
| b1f30b374f |
@@ -1,3 +1,27 @@
|
||||
# anian-plugin-friends
|
||||
|
||||
> 基于原作者v1.4.3代码修改
|
||||
|
||||
#### v1.4.3-4
|
||||
1. 控制台新增并行处理数量、图片下载开关、图片下载位置、图片下载代理等配置
|
||||
2. 修改图片列表字段为imageFiles(不再覆盖title)
|
||||
|
||||
#### v1.4.3-3
|
||||
1. title字段改为微博图片列表
|
||||
2. 图片列表内文件将自动下载至/upload/image-host
|
||||
|
||||
#### v1.4.3-2
|
||||
1. 新增URL参数author用于查询作者
|
||||
2. 模板参数新增${authors}返回所有作者
|
||||
|
||||
#### v1.4.3-1
|
||||
1. 大幅增加description字段的字符数上限
|
||||
2. 去除description字段内的微博视频提示
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# plugin-friends
|
||||
> 1.3.4版本重构朋友圈插件
|
||||
> 如果使用了之前版本,请清掉之前的所有数据,不然会有问题
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ repositories {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation platform('run.halo.tools.platform:plugin:2.20.0-SNAPSHOT')
|
||||
implementation platform('run.halo.tools.platform:plugin:2.20.11')
|
||||
compileOnly 'run.halo.app:api'
|
||||
|
||||
testImplementation 'run.halo.app:api'
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
version=1.3.7
|
||||
version=1.4.3-4
|
||||
|
||||
Generated
+9982
File diff suppressed because it is too large
Load Diff
@@ -9,12 +9,24 @@ import java.util.List;
|
||||
public class RssFeedSyncEvent extends ApplicationEvent {
|
||||
private final Link link;
|
||||
private final int sum;
|
||||
private final int parallelCount;
|
||||
private final boolean enableWeiboImageRecordAndDownload;
|
||||
private final List<String> disableSyncList;
|
||||
private final String imageSavePath;
|
||||
private final String imageBaseUrl;
|
||||
private final String imageReferer;
|
||||
|
||||
public RssFeedSyncEvent(Object source, Link link, int sum, List<String> disableSyncList) {
|
||||
public RssFeedSyncEvent(Object source, Link link, int sum, int parallelCount,
|
||||
boolean enableWeiboImageRecordAndDownload, List<String> disableSyncList,
|
||||
String imageSavePath, String imageBaseUrl, String imageReferer) {
|
||||
super(source);
|
||||
this.link = link;
|
||||
this.sum = sum;
|
||||
this.parallelCount = parallelCount;
|
||||
this.enableWeiboImageRecordAndDownload = enableWeiboImageRecordAndDownload;
|
||||
this.disableSyncList = disableSyncList;
|
||||
this.imageSavePath = imageSavePath;
|
||||
this.imageBaseUrl = imageBaseUrl;
|
||||
this.imageReferer = imageReferer;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,11 @@ public class CronFriendPost extends AbstractExtension {
|
||||
private String cron;
|
||||
private String timezone;
|
||||
private boolean suspend;
|
||||
private boolean enableWeiboImageRecordAndDownload;
|
||||
private int parallelCount;
|
||||
private String imageSavePath;
|
||||
private String imageBaseUrl;
|
||||
private String imageReferer;
|
||||
|
||||
@Schema(
|
||||
minimum = "0"
|
||||
|
||||
@@ -38,6 +38,9 @@ public class FriendPost extends AbstractExtension {
|
||||
private Instant pubDate;
|
||||
|
||||
private String linkName;
|
||||
|
||||
// Comma-separated image file names extracted from content.
|
||||
private String imageFiles;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -25,4 +25,6 @@ public interface FriendFinder {
|
||||
Mono<FriendPostVo> getByName(String friendPostName);
|
||||
|
||||
Flux<LinkGroupVo> linkGroupBy();
|
||||
|
||||
Flux<String> listAllAuthors();
|
||||
}
|
||||
|
||||
@@ -96,6 +96,22 @@ public class FriendFinderImpl implements FriendFinder {
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<String> listAllAuthors() {
|
||||
var listOptions = new ListOptions();
|
||||
// 只查有数据的,排除已删除的
|
||||
var query = isNull("metadata.deletionTimestamp");
|
||||
listOptions.setFieldSelector(FieldSelector.of(query));
|
||||
|
||||
return client.listAll(FriendPost.class, listOptions, defaultSort())
|
||||
// 提取作者名
|
||||
.map(friendPost -> friendPost.getSpec().getAuthor())
|
||||
// 过滤掉空值
|
||||
.filter(StringUtils::isNotBlank)
|
||||
// 去重
|
||||
.distinct();
|
||||
}
|
||||
|
||||
private Mono<ListResult<FriendPostVo>> pageFriendPost(ListOptions queryOptions, PageRequest page){
|
||||
var listOptions = new ListOptions();
|
||||
var query = all();
|
||||
@@ -220,6 +236,8 @@ public class FriendFinderImpl implements FriendFinder {
|
||||
private Integer page;
|
||||
private Integer size;
|
||||
private String linkName;
|
||||
// 作者查询
|
||||
private String author;
|
||||
private List<String> sort;
|
||||
|
||||
public ListOptions toListOptions() {
|
||||
@@ -227,6 +245,10 @@ public class FriendFinderImpl implements FriendFinder {
|
||||
if (StringUtils.isNotBlank(linkName)) {
|
||||
builder.andQuery(equal("spec.linkName", linkName));
|
||||
}
|
||||
// 作者查询
|
||||
if (StringUtils.isNotBlank(author)) {
|
||||
builder.andQuery(equal("spec.author", author));
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,12 @@ public class FriendPostQuery extends SortableRequest {
|
||||
return queryParams.getFirst("linkName");
|
||||
}
|
||||
|
||||
// 作者查询
|
||||
@Nullable
|
||||
public String getAuthor() {
|
||||
return StringUtils.defaultIfBlank(queryParams.getFirst("author"), null);
|
||||
}
|
||||
|
||||
|
||||
public ListOptions toListOptions() {
|
||||
var builder = ListOptions.builder(super.toListOptions());
|
||||
@@ -55,6 +61,11 @@ public class FriendPostQuery extends SortableRequest {
|
||||
.filter(StringUtils::isNotBlank)
|
||||
.ifPresent(linkName -> builder.andQuery(equal("spec.linkName", linkName)));
|
||||
|
||||
// 作者查询
|
||||
Optional.ofNullable(getAuthor())
|
||||
.filter(StringUtils::isNotBlank)
|
||||
.ifPresent(author -> builder.andQuery(equal("spec.author", author)));
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@@ -102,6 +113,13 @@ public class FriendPostQuery extends SortableRequest {
|
||||
.name("keyword")
|
||||
.description("CronFriendPost filtered by keyword.")
|
||||
.implementation(String.class)
|
||||
.required(false))
|
||||
// 作者查询
|
||||
.parameter(parameterBuilder()
|
||||
.in(ParameterIn.QUERY)
|
||||
.name("author")
|
||||
.description("FriendPost filtered by exact author name.")
|
||||
.implementation(String.class)
|
||||
.required(false));
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import com.rometools.rome.feed.synd.SyndFeed;
|
||||
import com.rometools.rome.io.SyndFeedInput;
|
||||
import com.rometools.rome.io.XmlReader;
|
||||
import la.moony.friends.RssFeedSyncEvent;
|
||||
import la.moony.friends.extension.CronFriendPost;
|
||||
import la.moony.friends.extension.FriendPost;
|
||||
import la.moony.friends.extension.Link;
|
||||
import la.moony.friends.extension.RssFeedSyncLog;
|
||||
@@ -27,16 +26,32 @@ import run.halo.app.extension.ListResult;
|
||||
import run.halo.app.extension.Metadata;
|
||||
import run.halo.app.extension.PageRequestImpl;
|
||||
import run.halo.app.extension.Unstructured;
|
||||
import run.halo.app.extension.controller.*;
|
||||
import run.halo.app.extension.controller.Controller;
|
||||
import run.halo.app.extension.controller.ControllerBuilder;
|
||||
import run.halo.app.extension.controller.DefaultController;
|
||||
import run.halo.app.extension.controller.DefaultQueue;
|
||||
import run.halo.app.extension.controller.Reconciler;
|
||||
import run.halo.app.extension.controller.RequestQueue;
|
||||
import run.halo.app.extension.router.selector.FieldSelector;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.springframework.data.domain.Sort.Order.asc;
|
||||
import static run.halo.app.extension.MetadataUtil.nullSafeAnnotations;
|
||||
@@ -45,17 +60,33 @@ import static run.halo.app.extension.index.query.QueryFactory.equal;
|
||||
import static run.halo.app.extension.index.query.QueryFactory.isNull;
|
||||
|
||||
@Component
|
||||
public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>,SmartLifecycle {
|
||||
public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>, SmartLifecycle {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RssSyncReconciler.class);
|
||||
|
||||
// 新增:正则匹配所有img标签的src属性
|
||||
private static final Pattern IMG_SRC_PATTERN = Pattern.compile(
|
||||
"<img[^>]*?src\\s*=\\s*(['\"])(.*?)\\1[^>]*?>",
|
||||
Pattern.CASE_INSENSITIVE
|
||||
);
|
||||
|
||||
private static final Pattern MW2000_IMAGE_FILE_PATTERN = Pattern.compile(
|
||||
".*/mw2000/([^/?#]+)(?:[?#].*)?$",
|
||||
Pattern.CASE_INSENSITIVE
|
||||
);
|
||||
|
||||
private static final String DEFAULT_IMAGE_BASE_URL = "https://wx3.sinaimg.cn/middle/";
|
||||
private static final String DEFAULT_IMAGE_REFERER = "https://weibo.com/";
|
||||
private static final String DEFAULT_IMAGE_HOST_PATH = "/root/.halo2/attachments/upload/image-host/";
|
||||
|
||||
private volatile boolean running = false;
|
||||
|
||||
private final ExtensionClient client;
|
||||
private final RequestQueue<Request> queue;
|
||||
private final Controller controller;
|
||||
private final ObjectMapper objectMapper = Unstructured.OBJECT_MAPPER;
|
||||
|
||||
private volatile int configuredParallelCount = 1;
|
||||
private volatile Semaphore syncSemaphore = new Semaphore(1, true);
|
||||
|
||||
public RssSyncReconciler(ExtensionClient client) {
|
||||
this.client = client;
|
||||
@@ -65,9 +96,22 @@ public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>,
|
||||
|
||||
@Override
|
||||
public Result reconcile(Request request) {
|
||||
int parallelCount = normalizeParallelCount(request.parallelCount());
|
||||
refreshSyncSemaphore(parallelCount);
|
||||
Semaphore semaphore = this.syncSemaphore;
|
||||
boolean acquired = false;
|
||||
try {
|
||||
semaphore.acquire();
|
||||
acquired = true;
|
||||
|
||||
Link link = request.link();
|
||||
int sum = request.sum();
|
||||
List<String> disableSyncList = request.disableSyncList();
|
||||
boolean enableWeiboImageRecordAndDownload =
|
||||
request.enableWeiboImageRecordAndDownload();
|
||||
String imageSavePath = request.imageSavePath();
|
||||
String imageBaseUrl = request.imageBaseUrl();
|
||||
String imageReferer = request.imageReferer();
|
||||
var linkName = link.getMetadata().getName();
|
||||
String rssUrl = getRss(link);
|
||||
boolean isContains = false;
|
||||
@@ -81,13 +125,14 @@ public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>,
|
||||
newRssFeedSyncLog.setMetadata(metadata);
|
||||
newRssFeedSyncLog.setLinkName(linkName);
|
||||
if (StringUtils.isNotEmpty(rssUrl) && !isContains) {
|
||||
tryToSynchronizeFriendPost(newRssFeedSyncLog, link, sum);
|
||||
}else if (StringUtils.isEmpty(rssUrl)) {
|
||||
tryToSynchronizeFriendPost(newRssFeedSyncLog, link, sum, imageSavePath,
|
||||
imageBaseUrl, imageReferer, enableWeiboImageRecordAndDownload);
|
||||
} else if (StringUtils.isEmpty(rssUrl)) {
|
||||
newRssFeedSyncLog.setSyncTime(Instant.now());
|
||||
newRssFeedSyncLog.setState(RssFeedSyncLog.RssFeedSyncLogState.nolink);
|
||||
newRssFeedSyncLog.setFailureReason("No RSS link");
|
||||
newRssFeedSyncLog.setFailureMessage("无 RSS 链接.");
|
||||
}else if (isContains) {
|
||||
} else if (isContains) {
|
||||
newRssFeedSyncLog.setSyncTime(Instant.now());
|
||||
newRssFeedSyncLog.setState(RssFeedSyncLog.RssFeedSyncLogState.failed);
|
||||
newRssFeedSyncLog.setFailureReason("admin disables sync");
|
||||
@@ -101,10 +146,31 @@ public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>,
|
||||
rssFeedSyncLog.setFailureReason(newRssFeedSyncLog.getFailureReason());
|
||||
rssFeedSyncLog.setFailureMessage(newRssFeedSyncLog.getFailureMessage());
|
||||
client.update(rssFeedSyncLog);
|
||||
}else {
|
||||
} else {
|
||||
client.create(newRssFeedSyncLog);
|
||||
}
|
||||
return Result.doNotRetry();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("Interrupted while waiting for sync permit.", e);
|
||||
return Result.doNotRetry();
|
||||
} finally {
|
||||
if (acquired) {
|
||||
semaphore.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void refreshSyncSemaphore(int parallelCount) {
|
||||
if (parallelCount == configuredParallelCount) {
|
||||
return;
|
||||
}
|
||||
configuredParallelCount = parallelCount;
|
||||
syncSemaphore = new Semaphore(parallelCount, true);
|
||||
}
|
||||
|
||||
private int normalizeParallelCount(int parallelCount) {
|
||||
return parallelCount <= 0 ? 1 : parallelCount;
|
||||
}
|
||||
|
||||
public String getRss(Link link) {
|
||||
@@ -121,10 +187,10 @@ public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>,
|
||||
linkRss = rssUri;
|
||||
annotations.remove("rss_uri");
|
||||
annotations.put("rss_url", rssUri);
|
||||
}else {
|
||||
annotations.put("is_request","true");
|
||||
} else {
|
||||
annotations.put("is_request", "true");
|
||||
if (StringUtils.isNotEmpty(linkRss)) {
|
||||
annotations.put("rss_url",linkRss);
|
||||
annotations.put("rss_url", linkRss);
|
||||
}
|
||||
}
|
||||
updateLink(link);
|
||||
@@ -133,22 +199,18 @@ public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>,
|
||||
return rssUrl;
|
||||
}
|
||||
|
||||
|
||||
public void updateLink(Link link) {
|
||||
Map extensionMap = objectMapper.convertValue(link, Map.class);
|
||||
var extension = new Unstructured(extensionMap);
|
||||
client.update(extension);
|
||||
}
|
||||
|
||||
private void tryToSynchronizeFriendPost(RssFeedSyncLog syncLog, Link link, int sum) {
|
||||
private void tryToSynchronizeFriendPost(RssFeedSyncLog syncLog, Link link, int sum,
|
||||
String imageSavePath, String imageBaseUrl, String imageReferer,
|
||||
boolean enableWeiboImageRecordAndDownload) {
|
||||
var linkName = link.getMetadata().getName();
|
||||
var annotations = nullSafeAnnotations(link);
|
||||
var rssUrl = annotations.get("rss_url");
|
||||
|
||||
CronFriendPost cron = new CronFriendPost();
|
||||
var spec = new CronFriendPost.CronSpec();
|
||||
spec.setSuccessfulRetainLimit(5);
|
||||
cron.setSpec(spec);
|
||||
syncLog.setSyncTime(Instant.now());
|
||||
List<FriendPost> friendPostList = fetchFriendPost(rssUrl, sum, syncLog);
|
||||
|
||||
@@ -158,12 +220,12 @@ public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>,
|
||||
var friendPostListOptions = new ListOptions();
|
||||
friendPostListOptions.setFieldSelector(FieldSelector.of(
|
||||
and(isNull("metadata.deletionTimestamp"),
|
||||
equal("spec.postLink",rssPost.getSpec().getPostLink())
|
||||
equal("spec.postLink", rssPost.getSpec().getPostLink())
|
||||
)
|
||||
));
|
||||
long total = client.listBy(FriendPost.class, friendPostListOptions,
|
||||
PageRequestImpl.ofSize(1)).getTotal();
|
||||
if (total==0) {
|
||||
if (total == 0) {
|
||||
FriendPost friendPost = new FriendPost();
|
||||
// 设置元数据才能保存
|
||||
friendPost.setMetadata(new Metadata());
|
||||
@@ -175,21 +237,43 @@ public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>,
|
||||
friendPostSpec.setAuthorUrl(link.getSpec().getUrl());
|
||||
friendPostSpec.setLinkName(linkName);
|
||||
String description = friendPost.getSpec().getDescription();
|
||||
//解析html内容转换成文本
|
||||
if (StringUtils.isNotEmpty(description)){
|
||||
description = CommonUtils.parseAndTruncateHtml2Text(description, 200);
|
||||
String regexp = "[ *|\\s*]*";
|
||||
description = description.replaceFirst(regexp, "").trim();
|
||||
friendPostSpec.setDescription(description);
|
||||
}
|
||||
client.create(friendPost);
|
||||
}
|
||||
}
|
||||
delFriendPost(linkName,sum);
|
||||
|
||||
// 先提取图片文件名覆盖标题,再将 HTML 描述转换为纯文本
|
||||
if (StringUtils.isNotEmpty(description)) {
|
||||
List<String> imageFileNames = new ArrayList<>();
|
||||
Matcher matcher = IMG_SRC_PATTERN.matcher(description);
|
||||
while (matcher.find()) {
|
||||
String imgSrc = matcher.group(2);
|
||||
Matcher mw2000Matcher = MW2000_IMAGE_FILE_PATTERN.matcher(imgSrc);
|
||||
if (mw2000Matcher.matches()) {
|
||||
imageFileNames.add(mw2000Matcher.group(1));
|
||||
}
|
||||
}
|
||||
|
||||
public List<FriendPost> fetchFriendPost(String rssAddress,int postsLimit, RssFeedSyncLog sync) {
|
||||
if (enableWeiboImageRecordAndDownload && !imageFileNames.isEmpty()) {
|
||||
String imageFiles = String.join(",", imageFileNames);
|
||||
friendPostSpec.setImageFiles(imageFiles);
|
||||
// 通知图片处理服务
|
||||
notifyImageService(imageFiles, imageSavePath, imageBaseUrl,
|
||||
imageReferer);
|
||||
}
|
||||
|
||||
String pureText = CommonUtils.parseAndTruncateHtml2Text(description, 100000);
|
||||
String regexp = "[ *|\\s*]*";
|
||||
pureText = pureText.replaceFirst(regexp, "").trim();
|
||||
String weiboVideoRegex = "\\s[^\\s]*的微博视频 视频无法显示,请前往微博视频观看。";
|
||||
pureText = pureText.replaceAll(weiboVideoRegex, "");
|
||||
friendPostSpec.setDescription(pureText);
|
||||
}
|
||||
|
||||
client.create(friendPost);
|
||||
}
|
||||
}
|
||||
delFriendPost(linkName, sum);
|
||||
}
|
||||
}
|
||||
|
||||
public List<FriendPost> fetchFriendPost(String rssAddress, int postsLimit, RssFeedSyncLog sync) {
|
||||
List<FriendPost> friendPostList = new ArrayList<>();
|
||||
try {
|
||||
SyndFeed feed = new SyndFeedInput().build(new XmlReader(new URL(rssAddress)));
|
||||
@@ -203,7 +287,7 @@ public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>,
|
||||
SyndContent content = entry.getDescription();
|
||||
if (content != null) {
|
||||
description = content.getValue();
|
||||
}else {
|
||||
} else {
|
||||
List<SyndContent> contents = entry.getContents();
|
||||
if (!contents.isEmpty()) {
|
||||
description = contents.get(0).getValue();
|
||||
@@ -233,10 +317,10 @@ public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>,
|
||||
return friendPostList;
|
||||
}
|
||||
|
||||
public void delFriendPost(String linkName,Integer sum) {
|
||||
public void delFriendPost(String linkName, Integer sum) {
|
||||
var friendPostListOptions = new ListOptions();
|
||||
friendPostListOptions.setFieldSelector(FieldSelector.of(
|
||||
equal("spec.linkName",linkName)
|
||||
equal("spec.linkName", linkName)
|
||||
));
|
||||
long total = client.listBy(FriendPost.class, friendPostListOptions, PageRequestImpl.ofSize(1)).getTotal();
|
||||
if (total > sum) {
|
||||
@@ -251,6 +335,84 @@ public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通知图片处理服务有新的图片需要处理
|
||||
* @param imageFiles 图片文件名,英文逗号分隔,如 "file1,file2,..."
|
||||
*/
|
||||
private void notifyImageService(String imageFiles, String imageSavePath, String imageBaseUrl,
|
||||
String imageReferer) {
|
||||
if (StringUtils.isBlank(imageFiles)) {
|
||||
return;
|
||||
}
|
||||
new Thread(() -> downloadImagesByFiles(imageFiles, imageSavePath, imageBaseUrl,
|
||||
imageReferer)).start();
|
||||
}
|
||||
|
||||
private void downloadImagesByFiles(String imageFiles, String imageSavePath,
|
||||
String imageBaseUrl, String imageReferer) {
|
||||
if (StringUtils.isBlank(imageFiles)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Path imageHostDir = resolveImageHostDir(imageSavePath);
|
||||
String resolvedBaseUrl = resolveImageBaseUrl(imageBaseUrl);
|
||||
String resolvedReferer = resolveImageReferer(imageBaseUrl, imageReferer);
|
||||
Files.createDirectories(imageHostDir);
|
||||
String[] fileNames = imageFiles.split(",");
|
||||
for (String fileName : fileNames) {
|
||||
String trimmedName = fileName.trim();
|
||||
if (StringUtils.isEmpty(trimmedName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String encodedFileName = URLEncoder.encode(trimmedName, StandardCharsets.UTF_8)
|
||||
.replace("+", "%20");
|
||||
String downloadUrl = resolvedBaseUrl + encodedFileName;
|
||||
Path targetPath = imageHostDir.resolve(trimmedName);
|
||||
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(downloadUrl)
|
||||
.openConnection();
|
||||
if (StringUtils.isNotBlank(resolvedReferer)) {
|
||||
connection.setRequestProperty("Referer", resolvedReferer);
|
||||
}
|
||||
try (InputStream inputStream = connection.getInputStream()) {
|
||||
Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
|
||||
} finally {
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to download images for files: {}", imageFiles, e);
|
||||
}
|
||||
}
|
||||
|
||||
private Path resolveImageHostDir(String imageSavePath) {
|
||||
if (StringUtils.isBlank(imageSavePath)) {
|
||||
return Path.of(DEFAULT_IMAGE_HOST_PATH);
|
||||
}
|
||||
return Path.of(imageSavePath.trim());
|
||||
}
|
||||
|
||||
private String resolveImageBaseUrl(String imageBaseUrl) {
|
||||
String resolvedBaseUrl = StringUtils.isBlank(imageBaseUrl)
|
||||
? DEFAULT_IMAGE_BASE_URL
|
||||
: imageBaseUrl.trim();
|
||||
if (!resolvedBaseUrl.endsWith("/")) {
|
||||
return resolvedBaseUrl + "/";
|
||||
}
|
||||
return resolvedBaseUrl;
|
||||
}
|
||||
|
||||
private String resolveImageReferer(String imageBaseUrl, String imageReferer) {
|
||||
if (StringUtils.isBlank(imageBaseUrl)) {
|
||||
return DEFAULT_IMAGE_REFERER;
|
||||
}
|
||||
if (StringUtils.isBlank(imageReferer)) {
|
||||
return null;
|
||||
}
|
||||
return imageReferer.trim();
|
||||
}
|
||||
|
||||
static int pageNullSafe(Integer page) {
|
||||
return ObjectUtils.defaultIfNull(page, 1);
|
||||
}
|
||||
@@ -259,7 +421,6 @@ public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>,
|
||||
return ObjectUtils.defaultIfNull(size, 10);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Controller setupWith(ControllerBuilder builder) {
|
||||
return new DefaultController<>(
|
||||
@@ -291,10 +452,16 @@ public class RssSyncReconciler implements Reconciler<RssSyncReconciler.Request>,
|
||||
|
||||
@EventListener(RssFeedSyncEvent.class)
|
||||
public void onReplyEvent(RssFeedSyncEvent event) {
|
||||
var request = new Request(event.getLink(),event.getSum(),event.getDisableSyncList());
|
||||
var request = new Request(event.getLink(), event.getSum(), event.getDisableSyncList(),
|
||||
event.isEnableWeiboImageRecordAndDownload(),
|
||||
event.getImageSavePath(), event.getImageBaseUrl(), event.getImageReferer(),
|
||||
event.getParallelCount());
|
||||
queue.addImmediately(request);
|
||||
}
|
||||
|
||||
public record Request(Link link,int sum,List<String> disableSyncList) {
|
||||
public record Request(Link link, int sum, List<String> disableSyncList,
|
||||
boolean enableWeiboImageRecordAndDownload,
|
||||
String imageSavePath, String imageBaseUrl,
|
||||
String imageReferer, int parallelCount) {
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,7 @@ public class FriendRouter {
|
||||
.flatMap( templateName -> ServerResponse.ok().render(templateName,
|
||||
java.util.Map.of(ModelConst.TEMPLATE_ID, templateName,
|
||||
"friends", friendPostList(request),
|
||||
"authors", friendFinder.listAllAuthors().collectList(),
|
||||
"title",getFriendTitle())
|
||||
));
|
||||
}
|
||||
@@ -65,6 +66,24 @@ public class FriendRouter {
|
||||
String linkName = request.queryParam("linkName")
|
||||
.filter(StringUtils::isNotBlank)
|
||||
.orElse(null);
|
||||
// --- 新增:获取 author 参数 ---
|
||||
String author = request.queryParam("author")
|
||||
.filter(StringUtils::isNotBlank)
|
||||
.orElse(null);
|
||||
|
||||
// --- 新增:构建查询参数字符串 ---
|
||||
StringBuilder queryString = new StringBuilder();
|
||||
if (StringUtils.isNotBlank(linkName)) {
|
||||
queryString.append("linkName=").append(linkName);
|
||||
}
|
||||
if (StringUtils.isNotBlank(author)) {
|
||||
if (queryString.length() > 0) {
|
||||
queryString.append("&");
|
||||
}
|
||||
queryString.append("author=").append(author);
|
||||
}
|
||||
final String finalQueryString = queryString.toString();
|
||||
|
||||
return this.settingFetcher.get("base")
|
||||
.map(item -> item.get("pageSize").asInt(10))
|
||||
.defaultIfEmpty(10)
|
||||
@@ -75,16 +94,40 @@ public class FriendRouter {
|
||||
if(StringUtils.isNotBlank(linkName)){
|
||||
params.put("linkName",linkName);
|
||||
}
|
||||
// --- 新增:把 author 也放进 params ---
|
||||
if(StringUtils.isNotBlank(author)){
|
||||
params.put("author",author);
|
||||
}
|
||||
|
||||
return friendFinder.list(params)
|
||||
.map(list -> new UrlContextListResult.Builder<FriendPostVo>()
|
||||
.map(list -> {
|
||||
// --- 修改:生成链接时带上查询参数 ---
|
||||
String baseNextUrl = PageUrlUtils.nextPageUrl(path, totalPage(list));
|
||||
String basePrevUrl = PageUrlUtils.prevPageUrl(path);
|
||||
|
||||
String nextUrl = appendQueryString(baseNextUrl, finalQueryString);
|
||||
String prevUrl = appendQueryString(basePrevUrl, finalQueryString);
|
||||
|
||||
return new UrlContextListResult.Builder<FriendPostVo>()
|
||||
.listResult(list)
|
||||
.nextUrl(PageUrlUtils.nextPageUrl(path, totalPage(list)))
|
||||
.prevUrl(PageUrlUtils.prevPageUrl(path))
|
||||
.build()
|
||||
);
|
||||
.nextUrl(nextUrl)
|
||||
.prevUrl(prevUrl)
|
||||
.build();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// --- 新增:辅助方法,用于拼接查询参数 ---
|
||||
private String appendQueryString(String url, String queryString) {
|
||||
if (StringUtils.isBlank(queryString)) {
|
||||
return url;
|
||||
}
|
||||
if (url.contains("?")) {
|
||||
return url + "&" + queryString;
|
||||
} else {
|
||||
return url + "?" + queryString;
|
||||
}
|
||||
}
|
||||
|
||||
private int pageNumInPathVariable(ServerRequest request) {
|
||||
String page = request.pathVariables().get("page");
|
||||
|
||||
@@ -74,14 +74,25 @@ public class RssFeedSyncLogServiceImpl implements RssFeedSyncLogService {
|
||||
CronFriendPost cron = new CronFriendPost();
|
||||
CronFriendPost.CronSpec cronSpec = new CronFriendPost.CronSpec();
|
||||
cronSpec.setSuccessfulRetainLimit(5);
|
||||
cronSpec.setParallelCount(1);
|
||||
cronSpec.setEnableWeiboImageRecordAndDownload(false);
|
||||
cronSpec.setDisableSyncList(new ArrayList<>());
|
||||
cronSpec.setImageSavePath("");
|
||||
cronSpec.setImageBaseUrl("");
|
||||
cronSpec.setImageReferer("");
|
||||
cron.setSpec(cronSpec);
|
||||
return client.fetch(CronFriendPost.class, "cron-friends-default")
|
||||
.defaultIfEmpty(cron)
|
||||
.flatMap(cronFriendPost -> {
|
||||
var spec = cronFriendPost.getSpec();
|
||||
int successfulRetainLimit = spec.getSuccessfulRetainLimit();
|
||||
int parallelCount = spec.getParallelCount();
|
||||
boolean enableWeiboImageRecordAndDownload =
|
||||
spec.isEnableWeiboImageRecordAndDownload();
|
||||
List<String> disableSyncList = spec.getDisableSyncList();
|
||||
String imageSavePath = spec.getImageSavePath();
|
||||
String imageBaseUrl = spec.getImageBaseUrl();
|
||||
String imageReferer = spec.getImageReferer();
|
||||
int sum = successfulRetainLimit == 0 ? 5 : successfulRetainLimit;
|
||||
var listOptions = new ListOptions();
|
||||
FieldSelector fieldSelector = FieldSelector.of(isNull("metadata.deletionTimestamp"));
|
||||
@@ -90,7 +101,11 @@ public class RssFeedSyncLogServiceImpl implements RssFeedSyncLogService {
|
||||
}
|
||||
listOptions.setFieldSelector(fieldSelector);
|
||||
return client.listAll(Link.class, listOptions, Sort.by("metadata.creationTimestamp"))
|
||||
.doOnNext(link -> eventPublisher.publishEvent(new RssFeedSyncEvent(this, link,sum,disableSyncList)))
|
||||
.doOnNext(link -> eventPublisher.publishEvent(
|
||||
new RssFeedSyncEvent(this, link, sum, parallelCount,
|
||||
enableWeiboImageRecordAndDownload, disableSyncList, imageSavePath,
|
||||
imageBaseUrl, imageReferer)
|
||||
))
|
||||
.then();
|
||||
});
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -32,6 +32,36 @@ export interface CronSpec {
|
||||
* @memberof CronSpec
|
||||
*/
|
||||
'disableSyncList'?: Array<string>;
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
* @memberof CronSpec
|
||||
*/
|
||||
'parallelCount'?: number;
|
||||
/**
|
||||
*
|
||||
* @type {boolean}
|
||||
* @memberof CronSpec
|
||||
*/
|
||||
'enableWeiboImageRecordAndDownload'?: boolean;
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof CronSpec
|
||||
*/
|
||||
'imageSavePath'?: string;
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof CronSpec
|
||||
*/
|
||||
'imageBaseUrl'?: string;
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof CronSpec
|
||||
*/
|
||||
'imageReferer'?: string;
|
||||
/**
|
||||
*
|
||||
* @type {number}
|
||||
|
||||
@@ -38,6 +38,12 @@ export interface FriendPostSpec {
|
||||
* @memberof FriendPostSpec
|
||||
*/
|
||||
'description'?: string;
|
||||
/**
|
||||
* Comma-separated image file names.
|
||||
* @type {string}
|
||||
* @memberof FriendPostSpec
|
||||
*/
|
||||
'imageFiles'?: string;
|
||||
/**
|
||||
*
|
||||
* @type {string}
|
||||
|
||||
@@ -18,7 +18,12 @@ const initialFormState: CronFriendPost = {
|
||||
cron: "@daily",
|
||||
timezone:"Asia/Shanghai",
|
||||
suspend: false,
|
||||
enableWeiboImageRecordAndDownload: false,
|
||||
parallelCount: 1,
|
||||
successfulRetainLimit: 0,
|
||||
imageSavePath: "",
|
||||
imageBaseUrl: "",
|
||||
imageReferer: "",
|
||||
disableSyncList: undefined,
|
||||
},
|
||||
kind: "CronFriendPost",
|
||||
@@ -130,6 +135,20 @@ const { mutate:save, isLoading:saveIsLoading } = useMutation({
|
||||
},
|
||||
]"
|
||||
/>
|
||||
<FormKit
|
||||
type="number"
|
||||
name="parallelCount"
|
||||
label="并行请求数量"
|
||||
number="integer"
|
||||
validation="required|number|min:1"
|
||||
help="默认 1(串行),大于 1 为并行"
|
||||
/>
|
||||
<FormKit
|
||||
type="checkbox"
|
||||
name="enableWeiboImageRecordAndDownload"
|
||||
label="记录并下载微博图片"
|
||||
help="默认关闭,开启后才会记录 imageFiles 字段并下载微博图片"
|
||||
/>
|
||||
<FormKit
|
||||
type="number"
|
||||
name="successfulRetainLimit"
|
||||
@@ -138,6 +157,24 @@ const { mutate:save, isLoading:saveIsLoading } = useMutation({
|
||||
validation="required|number|min:0"
|
||||
help="设置之后会保留的数据条数,设置为 0 即为5条"
|
||||
/>
|
||||
<FormKit
|
||||
type="text"
|
||||
name="imageSavePath"
|
||||
label="图片保存路径"
|
||||
help="为空时使用默认路径 /root/.halo2/attachments/upload/image-host/"
|
||||
/>
|
||||
<FormKit
|
||||
type="text"
|
||||
name="imageBaseUrl"
|
||||
label="图片下载 Base URL"
|
||||
help="为空时默认 https://wx3.sinaimg.cn/middle/"
|
||||
/>
|
||||
<FormKit
|
||||
type="text"
|
||||
name="imageReferer"
|
||||
label="图片下载 Referer"
|
||||
help="当 Base URL 为空时默认 https://weibo.com/;当 Base URL 不为空时可留空"
|
||||
/>
|
||||
<LinkFormKit
|
||||
name="disableSyncList"
|
||||
label="禁止同步名单"
|
||||
|
||||
Reference in New Issue
Block a user