Skip to content

Commit

Permalink
Merge pull request #675 from PBH-BTN/master
Browse files Browse the repository at this point in the history
7.0.2
  • Loading branch information
Ghost-chu authored Nov 2, 2024
2 parents e21d2fb + a6d173c commit f190c6f
Show file tree
Hide file tree
Showing 18 changed files with 352 additions and 354 deletions.
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/web_ui.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: "WebUI"
description: "报告与 WebUI 有关的程序错误 - Report the errors that related to WebUI"
description: "报告与 WebUI 有关的错误,如页面错误、链接或按钮无效 - Report the errors that related to WebUI, E.g page error or buttom doesnt work"

title: "[WebUI] "
labels:
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>com.ghostchu.peerbanhelper</groupId>
<artifactId>peerbanhelper</artifactId>
<version>7.0.1</version>
<version>7.0.2</version>
<packaging>jar</packaging>

<name>PeerBanHelper</name>
Expand Down
1 change: 1 addition & 0 deletions renovate.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"org.xerial:sqlite-jdbc",
"com.ghostchu.peerbanhelper.external-libs:sqlite-jdbc-loongarch64"
],
"baseBranches":["dev"],
"packageRules": [
{
"matchPackageNames": [
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/ghostchu/peerbanhelper/btn/BtnNetwork.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ public BtnNetwork(PeerBanHelperServer server, String userAgent, String configUrl
this.userAgent = userAgent;
this.configUrl = configUrl;
this.submit = submit;
this.appId = appId;
this.appSecret = appSecret;
this.appId = appId.trim();
this.appSecret = appSecret.trim();
this.moduleMatchCache = moduleMatchCache;
setupHttpClient();
resetScheduler();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ public List<Torrent> getTorrents() {
}
List<DownloadRecord> torrentDetail = JsonUtil.getGson().fromJson(request.body(), new TypeToken<List<DownloadRecord>>() {
}.getType());
List<Torrent> torrents = new ArrayList<>();
List<Torrent> torrents = new LinkedList<>();
for (DownloadRecord detail : torrentDetail) {
if (config.isIgnorePrivate() && detail.getTorrent().isPrivateTorrent()) {
continue;
Expand Down Expand Up @@ -216,7 +216,7 @@ public List<Peer> getPeers(Torrent torrent) {
throw new IllegalStateException(tlUI(Lang.DOWNLOADER_BIGLYBT_FAILED_REQUEST_PEERS_LIST_IN_TORRENT, resp.statusCode(), resp.body()));
}
PeerManagerRecord peerManagerRecord = JsonUtil.getGson().fromJson(resp.body(), PeerManagerRecord.class);
List<Peer> peersList = new ArrayList<>();
List<Peer> peersList = new LinkedList<>();
for (PeerRecord peer : peerManagerRecord.getPeers()) {
var peerId = new String(ByteUtil.hexToByteArray(peer.getPeerId()), StandardCharsets.ISO_8859_1);
if (peerId.length() > 8) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
import org.slf4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.http.HttpClient;
Expand Down Expand Up @@ -225,14 +227,15 @@ private boolean queryNeedReConfigureIpFilter() throws IOException, InterruptedEx
private void enableIpFilter() throws IOException, InterruptedException {
Map<String, Object> settings = new HashMap<>() {{
put("ip_filter_config", new HashMap<>() {{
put("enable_ipfilter", true);
put("enable_ip_filter", true);
put("enable_whitelist_mode", false); // 2.10
put("ipfilter_mode", "blacklist"); // 2.11
}});
}};
HttpResponse<String> updatePreferencesToEnableIpFilter =
httpClient.send(
MutableRequest.POST(apiEndpoint + BCEndpoint.GET_IP_FILTER_CONFIG.getEndpoint(),
MutableRequest.POST(apiEndpoint + BCEndpoint.SET_IP_FILTER_CONFIG.getEndpoint(),
HttpRequest.BodyPublishers.ofString(JsonUtil.standard().toJson(settings)))
.header("Authorization", "Bearer " + this.deviceToken),
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)
Expand Down Expand Up @@ -274,7 +277,7 @@ public List<Torrent> getTorrents() {
try {
semaphore.acquire();
Map<String, String> taskIds = new HashMap<>();
taskIds.put("task_id", torrent.getTaskId().toString());
taskIds.put("task_id", String.valueOf(torrent.getTaskId()));
HttpResponse<String> fetch = httpClient.send(MutableRequest.POST(apiEndpoint + BCEndpoint.GET_TASK_SUMMARY.getEndpoint(),
HttpRequest.BodyPublishers.ofString(JsonUtil.standard().toJson(taskIds)))
.header("Authorization", "Bearer " + this.deviceToken),
Expand All @@ -288,7 +291,7 @@ public List<Torrent> getTorrents() {
}
}));
}
return torrentResponses.stream().map(torrent -> new TorrentImpl(torrent.getTask().getTaskId().toString(),
return torrentResponses.stream().map(torrent -> new TorrentImpl(Long.toString(torrent.getTask().getTaskId()),
torrent.getTask().getTaskName(),
torrent.getTaskDetail().getInfohash() != null ? torrent.getTaskDetail().getInfohash() : torrent.getTaskDetail().getInfohashV2(),
torrent.getTaskDetail().getTotalSize(),
Expand All @@ -306,7 +309,7 @@ public DownloaderStatistics getStatistics() {

@Override
public List<Peer> getPeers(Torrent torrent) {
HttpResponse<String> resp;
HttpResponse<InputStream> resp;
try {
Map<String, Object> requirements = new HashMap<>();
requirements.put("groups", List.of("peers_connected")); // 2.11 Beta 3 可以限制获取哪一类 Peers,注意下面仍需要检查,因为旧版本不支持
Expand All @@ -315,38 +318,39 @@ public List<Peer> getPeers(Torrent torrent) {
resp = httpClient.send(MutableRequest.POST(apiEndpoint + BCEndpoint.GET_TASK_PEERS.getEndpoint(),
HttpRequest.BodyPublishers.ofString(JsonUtil.standard().toJson(requirements)))
.header("Authorization", "Bearer " + this.deviceToken),
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
HttpResponse.BodyHandlers.ofInputStream());
} catch (Exception e) {
throw new IllegalStateException(e);
}
if (resp.statusCode() != 200) {
throw new IllegalStateException(tlUI(Lang.DOWNLOADER_BC_FAILED_REQUEST_PEERS_LIST_IN_TORRENT, resp.statusCode(), resp.body()));
}
var peers = JsonUtil.standard().fromJson(resp.body(), BCTaskPeersResponse.class);
//noinspection UnusedAssignment
resp = null; // 立即手动释放 resp 的对象引用,你可能觉得这非常夸张,但部分版本 BitComet 一个响应能高达 12 MB,考虑到 PBH 的设计运行内存上限仅 386MB ,所以辅助 GC 完成垃圾回收是值得的。
if (peers.getPeers() == null) {
return Collections.emptyList();
}
var noGroupField = peers.getPeers().stream().noneMatch(dto -> dto.getGroup() != null); // 2.10 的一些版本没有 group 字段
var stream = peers.getPeers().stream();
try (InputStreamReader reader = new InputStreamReader(resp.body())) {
var peers = JsonUtil.standard().fromJson(reader, BCTaskPeersResponse.class);
if (peers.getPeers() == null) {
return Collections.emptyList();
}
var noGroupField = peers.getPeers().stream().noneMatch(dto -> dto.getGroup() != null); // 2.10 的一些版本没有 group 字段
var stream = peers.getPeers().stream();

if (!noGroupField) { // 对于新版本,添加一个 group 过滤
stream = stream.filter(dto -> dto.getGroup().equals("connected") // 2.10 正式版
|| dto.getGroup().equals("connected_peers") // 2.11 Beta 1-2
|| dto.getGroup().equals("peers_connected")); // 2.11 Beta 3
if (!noGroupField) { // 对于新版本,添加一个 group 过滤
stream = stream.filter(dto -> dto.getGroup().equals("connected") // 2.10 正式版
|| dto.getGroup().equals("connected_peers") // 2.11 Beta 1-2
|| dto.getGroup().equals("peers_connected")); // 2.11 Beta 3
}
return stream.map(peer -> new PeerImpl(parseAddress(peer.getIp(), peer.getRemotePort(), peer.getListenPort()),
peer.getIp(),
new String(ByteUtil.hexToByteArray(peer.getPeerId()), StandardCharsets.ISO_8859_1),
peer.getClientType(),
peer.getDlRate(),
peer.getDlSize() != null ? peer.getDlSize() : -1, // 兼容 2.10
peer.getUpRate(),
peer.getUpSize() != null ? peer.getUpSize() : -1, // 兼容 2.10
peer.getPermillage() / 1000.0d, null, Collections.emptyList())
).collect(Collectors.toList());
} catch (Exception e) {
throw new IllegalStateException(e);
}

return stream.map(peer -> new PeerImpl(parseAddress(peer.getIp(), peer.getRemotePort(), peer.getListenPort()),
peer.getIp(),
new String(ByteUtil.hexToByteArray(peer.getPeerId()), StandardCharsets.ISO_8859_1),
peer.getClientType(),
peer.getDlRate(),
peer.getDlSize() != null ? peer.getDlSize() : -1, // 兼容 2.10
peer.getUpRate(),
peer.getUpSize() != null ? peer.getUpSize() : -1, // 兼容 2.10
peer.getPermillage() / 1000.0d, null, Collections.emptyList())
).collect(Collectors.toList());
}

@Override
Expand All @@ -364,23 +368,13 @@ public void setBanList(@NotNull Collection<PeerAddress> fullList, @Nullable Coll
private void setBanListIncrement(Collection<BanMetadata> added) {
StringJoiner joiner = new StringJoiner("\n");
added.forEach(p -> joiner.add(p.getPeer().getAddress().getIp()));
if (is211Newer()) {
operateBanListNew("data_file", joiner.toString());
} else {
operateBanListLegacy("merge", joiner.toString());
}
operateBanListLegacy("merge", joiner.toString());
}

protected void setBanListFull(Collection<PeerAddress> peerAddresses) {
StringJoiner joiner = new StringJoiner("\n");
peerAddresses.forEach(p -> joiner.add(p.getIp()));
if (is211Newer()) {
operateBanListNew("data_file", joiner.toString());
//unbanAllPeers();
} else {
operateBanListLegacy("replace", joiner.toString());
}

operateBanListLegacy("replace", joiner.toString());
}

private boolean is211Newer() {
Expand Down Expand Up @@ -409,6 +403,7 @@ private void unbanPeers(List<String> peerAddresses) {
private void operateBanListLegacy(String mode, String content) {
Map<String, String> banListSettings = new HashMap<>();
banListSettings.put("import_type", mode);
banListSettings.put("data_type", "data_file");
banListSettings.put("content_base64", Base64.getEncoder().encodeToString(content.getBytes(StandardCharsets.UTF_8)));
try {
HttpResponse<String> request = httpClient.send(MutableRequest.POST(apiEndpoint + BCEndpoint.IP_FILTER_UPLOAD.getEndpoint(),
Expand All @@ -425,24 +420,24 @@ private void operateBanListLegacy(String mode, String content) {
}
}

private void operateBanListNew(String mode, String content) {
Map<String, String> banListSettings = new HashMap<>();
banListSettings.put("data_type", "manual_list");
banListSettings.put("content_base64", Base64.getEncoder().encodeToString(content.getBytes(StandardCharsets.UTF_8)));
try {
HttpResponse<String> request = httpClient.send(MutableRequest.POST(apiEndpoint + BCEndpoint.IP_FILTER_UPLOAD.getEndpoint(),
HttpRequest.BodyPublishers.ofString(JsonUtil.standard().toJson(banListSettings)))
.header("Authorization", "Bearer " + this.deviceToken),
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (request.statusCode() != 200) {
log.error(tlUI(DOWNLOADER_BC_FAILED_SAVE_BANLIST, name, apiEndpoint, request.statusCode(), "HTTP ERROR", request.body()));
throw new IllegalStateException("Save BitComet banlist error: statusCode=" + request.statusCode());
}
} catch (Exception e) {
log.error(tlUI(DOWNLOADER_BC_FAILED_SAVE_BANLIST, name, apiEndpoint, "N/A", e.getClass().getName(), e.getMessage()), e);
throw new IllegalStateException(e);
}
}
// private void operateBanListNew(String mode, String content) {
// Map<String, String> banListSettings = new HashMap<>();
// banListSettings.put("data_type", "manual_list");
// banListSettings.put("content_base64", Base64.getEncoder().encodeToString(content.getBytes(StandardCharsets.UTF_8)));
// try {
// HttpResponse<String> request = httpClient.send(MutableRequest.POST(apiEndpoint + BCEndpoint.IP_FILTER_UPLOAD.getEndpoint(),
// HttpRequest.BodyPublishers.ofString(JsonUtil.standard().toJson(banListSettings)))
// .header("Authorization", "Bearer " + this.deviceToken),
// HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
// if (request.statusCode() != 200) {
// log.error(tlUI(DOWNLOADER_BC_FAILED_SAVE_BANLIST, name, apiEndpoint, request.statusCode(), "HTTP ERROR", request.body()));
// throw new IllegalStateException("Save BitComet banlist error: statusCode=" + request.statusCode());
// }
// } catch (Exception e) {
// log.error(tlUI(DOWNLOADER_BC_FAILED_SAVE_BANLIST, name, apiEndpoint, "N/A", e.getClass().getName(), e.getMessage()), e);
// throw new IllegalStateException(e);
// }
// }

@Override
public void close() throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,39 +12,37 @@ public class BCTaskListResponse {

@SerializedName("tasks")
private List<TasksDTO> tasks;
@SerializedName("version")
private String version;
// @SerializedName("version")
// private String version;

@NoArgsConstructor
@Data
public static class TasksDTO {
@SerializedName("task_id")
private Long taskId;
@SerializedName("task_guid")
private String taskGuid;
private long taskId;
@SerializedName("type")
private String type;
@SerializedName("task_name")
private String taskName;
@SerializedName("status")
private String status;
@SerializedName("total_size")
private Long totalSize;
@SerializedName("selected_size")
private Long selectedSize;
@SerializedName("selected_downloaded_size")
private Long selectedDownloadedSize;
@SerializedName("download_rate")
private Long downloadRate;
@SerializedName("upload_rate")
private Long uploadRate;
@SerializedName("error_code")
private String errorCode;
@SerializedName("error_message")
private String errorMessage;
@SerializedName("permillage")
private Long permillage;
@SerializedName("left_time")
private String leftTime;
// @SerializedName("task_name")
// private String taskName;
// @SerializedName("status")
// private String status;
// @SerializedName("total_size")
// private Long totalSize;
// @SerializedName("selected_size")
// private Long selectedSize;
// @SerializedName("selected_downloaded_size")
// private Long selectedDownloadedSize;
// @SerializedName("download_rate")
// private Long downloadRate;
// @SerializedName("upload_rate")
// private Long uploadRate;
// @SerializedName("error_code")
// private String errorCode;
// @SerializedName("error_message")
// private String errorMessage;
// @SerializedName("permillage")
// private Long permillage;
// @SerializedName("left_time")
// private String leftTime;
}
}
Loading

0 comments on commit f190c6f

Please sign in to comment.