Skip to content

Commit

Permalink
使用 OffsetDateTime
Browse files Browse the repository at this point in the history
  • Loading branch information
Ghost-chu committed Oct 7, 2024
1 parent 34c31cc commit 8217ed8
Show file tree
Hide file tree
Showing 31 changed files with 129 additions and 108 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import org.springframework.web.bind.annotation.GetMapping;

import java.io.Serializable;
import java.sql.Timestamp;
import java.time.OffsetDateTime;

@Controller
public class IndexController extends SparkleController {
Expand Down Expand Up @@ -62,7 +62,7 @@ public String index(Model model) {
return "index";
}

public IndexBtnMetrics btnMetrics(Timestamp from, Timestamp to) {
public IndexBtnMetrics btnMetrics(OffsetDateTime from, OffsetDateTime to) {
var banHistory = banHistoryService.getMetrics(from, to);
var snapshot = snapshotService.getMetrics(from, to);
var clientDiscovery = clientDiscoveryService.getMetrics(from, to);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.ghostchu.btn.sparkle.util.IPMerger;
import com.ghostchu.btn.sparkle.util.IPUtil;
import com.ghostchu.btn.sparkle.util.MsgUtil;
import com.ghostchu.btn.sparkle.util.TimeUtil;
import inet.ipaddr.IPAddress;
import inet.ipaddr.IPAddressString;
import jakarta.persistence.EntityManager;
Expand All @@ -21,6 +22,8 @@

import java.net.InetAddress;
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -57,7 +60,7 @@ public class AnalyseService {
@Scheduled(fixedDelayString = "${analyse.overdownload.interval}")
public void cronUntrustedIPAddresses() {
var list = ipMerger.merge(banHistoryRepository
.generateUntrustedIPAddresses(new Timestamp(System.currentTimeMillis() - untrustedIpAddressGenerateOffset), new Timestamp(System.currentTimeMillis()), untrustedIpAddressGenerateThreshold)
.generateUntrustedIPAddresses(TimeUtil.toUTC(System.currentTimeMillis() - untrustedIpAddressGenerateOffset), new Timestamp(System.currentTimeMillis()), untrustedIpAddressGenerateThreshold)
.stream()
.map(IPUtil::toString)
.collect(Collectors.toList()))
Expand Down Expand Up @@ -220,11 +223,11 @@ public Collection<IPAddress> filterIP(Collection<IPAddress> ips) {
return list;
}

private Timestamp nowTimestamp() {
return new Timestamp(System.currentTimeMillis());
private OffsetDateTime nowTimestamp() {
return OffsetDateTime.now();
}

private Timestamp pastTimestamp(long offset) {
return new Timestamp(System.currentTimeMillis() - offset);
private OffsetDateTime pastTimestamp(long offset) {
return OffsetDateTime.now().minus(offset, ChronoUnit.MILLIS);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;

import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
Expand All @@ -22,7 +22,7 @@ public AuditService(AuditRepository auditRepository) {
}

public Audit log(HttpServletRequest req, String action, boolean success, Map<String, Object> node) {
var audit = new Audit(null, new Timestamp(System.currentTimeMillis()), IPUtil.toInet(ServletUtil.getIP(req)), action, success, getHeaders(req), node);
var audit = new Audit(null, OffsetDateTime.now(), IPUtil.toInet(ServletUtil.getIP(req)), action, success, getHeaders(req), node);
return auditRepository.save(audit);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import org.hibernate.annotations.Type;

import java.net.InetAddress;
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Map;

Expand All @@ -27,7 +27,7 @@ public class Audit {
@Column(nullable = false, unique = true)
private Long id;
@Column(nullable = false)
private Timestamp timestamp;
private OffsetDateTime timestamp;
@Column
private InetAddress ip;
@Column(nullable = false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.ghostchu.btn.sparkle.exception.RequestPageSizeTooLargeException;
import com.ghostchu.btn.sparkle.module.banhistory.internal.BanHistory;
import com.ghostchu.btn.sparkle.module.torrent.internal.Torrent;
import com.ghostchu.btn.sparkle.util.TimeUtil;
import com.ghostchu.btn.sparkle.util.compare.NumberCompareMethod;
import com.ghostchu.btn.sparkle.util.compare.StringCompareMethod;
import com.ghostchu.btn.sparkle.util.paging.SparklePage;
Expand All @@ -22,7 +23,6 @@
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

Expand All @@ -48,10 +48,10 @@ public BanHistoryController(BanHistoryService banHistoryService) {
Specification<BanHistory> specification = (root, query, cb) -> {
List<Predicate> predicates = new ArrayList<>();
if(q.getTimeFrom() != null){
predicates.add(cb.greaterThanOrEqualTo(root.get("insertTime"), new Timestamp(q.getTimeFrom())));
predicates.add(cb.greaterThanOrEqualTo(root.get("insertTime"), TimeUtil.toUTC(q.getTimeFrom())));
}
if(q.getTimeTo() != null){
predicates.add(cb.lessThanOrEqualTo(root.get("insertTime"), new Timestamp(q.getTimeTo())));
predicates.add(cb.lessThanOrEqualTo(root.get("insertTime"), TimeUtil.toUTC(q.getTimeTo())));
}
if (StringUtils.isNotBlank(q.getPeerId())) {
predicates.add(q.getPeerIdCompareMethod().criteriaBuilder(cb, root.get("peerId"), q.getPeerId()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.util.List;

@Service
Expand Down Expand Up @@ -47,7 +47,7 @@ public BanHistoryService(BanHistoryRepository banHistoryRepository,
}

@Cacheable(value = "banHistoryMetrics#1800000", key = "#from+'-'+#to")
public BanHistoryMetrics getMetrics(Timestamp from, Timestamp to) {
public BanHistoryMetrics getMetrics(OffsetDateTime from, OffsetDateTime to) {
return new BanHistoryMetrics(
banHistoryRepository.count(),
banHistoryRepository.countByInsertTimeBetween(from, to)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import org.hibernate.annotations.Type;

import java.net.InetAddress;
import java.sql.Timestamp;
import java.time.OffsetDateTime;

@Entity
@Table(name = "banhistory", indexes = {
Expand All @@ -32,9 +32,9 @@ public class BanHistory {
@Column(nullable = false, unique = true)
private Long id;
@Column(nullable = false)
private Timestamp insertTime;
private OffsetDateTime insertTime;
@Column(nullable = false)
private Timestamp populateTime;
private OffsetDateTime populateTime;
@JoinColumn(name = "userApplication")
@ManyToOne(fetch = FetchType.LAZY)
private UserApplication userApplication;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import org.springframework.stereotype.Repository;

import java.net.InetAddress;
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.util.List;

@Repository
Expand All @@ -22,9 +22,9 @@ public interface BanHistoryRepository extends SparkleCommonRepository<BanHistory
HAVING COUNT (DISTINCT ban.userApplication.appId) >= ?3
""")
@Transactional
List<InetAddress> generateUntrustedIPAddresses(Timestamp from, Timestamp to, int threshold);
List<InetAddress> generateUntrustedIPAddresses(OffsetDateTime from, OffsetDateTime to, int threshold);

Page<BanHistory> findByInsertTimeBetweenOrderByInsertTimeDesc(Timestamp from, Timestamp to, Pageable pageable);
Page<BanHistory> findByInsertTimeBetweenOrderByInsertTimeDesc(OffsetDateTime from, OffsetDateTime to, Pageable pageable);

@Query("""
SELECT DISTINCT ban.peerIp FROM BanHistory ban
Expand All @@ -35,19 +35,19 @@ HAVING COUNT (DISTINCT ban.userApplication.appId) >= ?3
GROUP BY ban.peerIp
""")
@Transactional
List<InetAddress> findByInsertTimeBetweenOrderByInsertTimeDescIPVx(Timestamp from, Timestamp to, int family);
List<InetAddress> findByInsertTimeBetweenOrderByInsertTimeDescIPVx(OffsetDateTime from, OffsetDateTime to, int family);

List<BanHistory> findByInsertTimeBetweenOrderByInsertTimeDesc(Timestamp from, Timestamp to);
List<BanHistory> findByInsertTimeBetweenOrderByInsertTimeDesc(OffsetDateTime from, OffsetDateTime to);

Page<BanHistory> findByInsertTimeBetweenAndPeerIdLikeIgnoreCaseOrderByInsertTimeDesc(Timestamp from, Timestamp to, String peerId, Pageable pageable);
Page<BanHistory> findByInsertTimeBetweenAndPeerIdLikeIgnoreCaseOrderByInsertTimeDesc(OffsetDateTime from, OffsetDateTime to, String peerId, Pageable pageable);

Page<BanHistory> findByInsertTimeBetweenAndPeerClientNameLikeIgnoreCaseOrderByInsertTimeDesc(Timestamp from, Timestamp to, String peerClientName, Pageable pageable);
Page<BanHistory> findByInsertTimeBetweenAndPeerClientNameLikeIgnoreCaseOrderByInsertTimeDesc(OffsetDateTime from, OffsetDateTime to, String peerClientName, Pageable pageable);

Page<BanHistory> findByInsertTimeBetweenAndPeerIpEqualsOrderByInsertTimeDesc(Timestamp from, Timestamp to, InetAddress peerIp, Pageable pageable);
Page<BanHistory> findByInsertTimeBetweenAndPeerIpEqualsOrderByInsertTimeDesc(OffsetDateTime from, OffsetDateTime to, InetAddress peerIp, Pageable pageable);

Page<BanHistory> findByOrderByInsertTimeDesc(Pageable pageable);

long countByInsertTimeBetween(Timestamp insertTimeStart, Timestamp insertTimeEnd);
long countByInsertTimeBetween(OffsetDateTime insertTimeStart, OffsetDateTime insertTimeEnd);

@Query("""
SELECT DISTINCT ban FROM BanHistory ban
Expand All @@ -56,15 +56,15 @@ HAVING COUNT (DISTINCT ban.userApplication.appId) >= ?3
AND ban.insertTime >= ?3 AND ban.insertTime <= ?4
""")
@Transactional
List<BanHistory> findDistinctByPeerIdLikeOrPeerClientNameLike(String peerId, String peerClientName, Timestamp from, Timestamp to);
List<BanHistory> findDistinctByPeerIdLikeOrPeerClientNameLike(String peerId, String peerClientName, OffsetDateTime from, OffsetDateTime to);

List<BanHistory> findDistinctByPeerIdLikeAndInsertTimeBetween(String peerId, Timestamp from, Timestamp to);
List<BanHistory> findDistinctByPeerIdLikeAndInsertTimeBetween(String peerId, OffsetDateTime from, OffsetDateTime to);

@Query(nativeQuery = true, value = "SELECT * from banhistory ban WHERE ban.insert_time >= ?2 AND ban.insert_time <= ?3 AND host(ban.peer_ip) LIKE ?1")
@Transactional
List<BanHistory> findByPeerIp(String peerIp,Timestamp insertTimeStart, Timestamp insertTimeEnd);
List<BanHistory> findByPeerIp(String peerIp, OffsetDateTime insertTimeStart, OffsetDateTime insertTimeEnd);

List<BanHistory> findDistinctByPeerClientNameLikeAndInsertTimeBetween(String peerClientName, Timestamp from, Timestamp to);
List<BanHistory> findDistinctByPeerClientNameLikeAndInsertTimeBetween(String peerClientName, OffsetDateTime from, OffsetDateTime to);

List<BanHistory> findDistinctByPeerClientNameAndModuleLikeAndInsertTimeBetween(String peerClientName, String module, Timestamp from, Timestamp to);
List<BanHistory> findDistinctByPeerClientNameAndModuleLikeAndInsertTimeBetween(String peerClientName, String module, OffsetDateTime from, OffsetDateTime to);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.time.temporal.ChronoField;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
Expand All @@ -34,7 +35,7 @@ public ClientDiscoveryService(ClientDiscoveryRepository clientDiscoveryRepositor
@Transactional
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Async
public void handleIdentities(User user, Timestamp timeForFoundAt, Timestamp timeForLastSeenAt, Set<ClientIdentity> clientIdentities) {
public void handleIdentities(User user, OffsetDateTime timeForFoundAt, OffsetDateTime timeForLastSeenAt, Set<ClientIdentity> clientIdentities) {
clientDiscoveryRepository.updateLastSeen(clientIdentities.stream().map(ClientIdentity::hash).toList(), timeForLastSeenAt, user);
var found = clientDiscoveryRepository.findAllById(clientIdentities.stream().map(ClientIdentity::hash).toList());
List<Long> hashInDatabase = new ArrayList<>();
Expand All @@ -50,7 +51,7 @@ public void handleIdentities(User user, Timestamp timeForFoundAt, Timestamp time
}

@Cacheable(value = "clientDiscoveryMetrics#1800000", key = "#from+'-'+#to")
public ClientDiscoveryMetrics getMetrics(Timestamp from, Timestamp to){
public ClientDiscoveryMetrics getMetrics(OffsetDateTime from, OffsetDateTime to) {
return new ClientDiscoveryMetrics(
clientDiscoveryRepository.count(),
clientDiscoveryRepository.countByFoundAtBetween(from,to)
Expand All @@ -62,9 +63,9 @@ public ClientDiscoveryDto toDto(ClientDiscovery clientDiscovery) {
.hash(clientDiscovery.getHash())
.clientName(clientDiscovery.getClientName())
.peerId(clientDiscovery.getPeerId())
.foundAt(clientDiscovery.getFoundAt().getTime())
.foundAt(clientDiscovery.getFoundAt().getLong(ChronoField.MILLI_OF_DAY))
.foundBy(userService.toDto(clientDiscovery.getFoundBy()))
.lastSeenAt(clientDiscovery.getLastSeenAt().getTime())
.lastSeenAt(clientDiscovery.getLastSeenAt().getLong(ChronoField.MILLI_OF_DAY))
.lastSeenBy(userService.toDto(clientDiscovery.getLastSeenBy()))
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;

import java.sql.Timestamp;
import java.time.OffsetDateTime;

@Entity
@Table(name = "clientdiscovery")
Expand All @@ -24,12 +24,12 @@ public class ClientDiscovery {
@Column(nullable = false)
private String peerId;
@Column(nullable = false)
private Timestamp foundAt;
private OffsetDateTime foundAt;
@JoinColumn(name = "foundBy")
@ManyToOne(fetch = FetchType.LAZY)
private User foundBy;
@Column(nullable = false)
private Timestamp lastSeenAt;
private OffsetDateTime lastSeenAt;
@JoinColumn(name = "lastSeenBy")
@ManyToOne(fetch = FetchType.LAZY)
private User lastSeenBy;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,17 @@
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.util.Collection;

@Repository
public interface ClientDiscoveryRepository extends SparkleCommonRepository<ClientDiscovery, Long> {
@Modifying
@Transactional
@Query("UPDATE ClientDiscovery cd SET cd.lastSeenAt = ?2, cd.lastSeenBy = ?3 WHERE cd.hash IN ?1")
int updateLastSeen(Collection<Long> ids, Timestamp lastSeenAt, User lastSeenBy);
int updateLastSeen(Collection<Long> ids, OffsetDateTime lastSeenAt, User lastSeenBy);

Page<ClientDiscovery> findByOrderByFoundAtDesc(Pageable pageable);

long countByFoundAtBetween(Timestamp foundAtStart, Timestamp foundAtEnd);
long countByFoundAtBetween(OffsetDateTime foundAtStart, OffsetDateTime foundAtEnd);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Locale;
import java.util.StringJoiner;
Expand Down Expand Up @@ -226,11 +227,11 @@ private String generateOverDownloadIps() {
return String.join("\n", analyseService.getOverDownloadIPAddresses().stream().map(AnalysedRule::getIp).toList());
}

private Timestamp nowTimestamp() {
return new Timestamp(System.currentTimeMillis());
private OffsetDateTime nowTimestamp() {
return OffsetDateTime.now();
}

private Timestamp pastTimestamp() {
return new Timestamp(System.currentTimeMillis() - pastInterval);
private OffsetDateTime pastTimestamp() {
return OffsetDateTime.now().minus(pastInterval, ChronoUnit.MILLIS);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,7 @@
import com.ghostchu.btn.sparkle.module.torrent.TorrentService;
import com.ghostchu.btn.sparkle.module.user.UserService;
import com.ghostchu.btn.sparkle.module.userapp.internal.UserApplication;
import com.ghostchu.btn.sparkle.util.ByteUtil;
import com.ghostchu.btn.sparkle.util.IPMerger;
import com.ghostchu.btn.sparkle.util.IPUtil;
import com.ghostchu.btn.sparkle.util.PeerUtil;
import com.ghostchu.btn.sparkle.util.*;
import com.ghostchu.btn.sparkle.util.ipdb.GeoIPManager;
import jakarta.transaction.Transactional;
import lombok.Data;
Expand All @@ -31,7 +28,7 @@
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.stream.Collectors;

Expand All @@ -57,7 +54,7 @@ public class PingService {
@Modifying
@Transactional
public long handlePeers(InetAddress submitterIp, UserApplication userApplication, BtnPeerPing ping) {
Timestamp now = new Timestamp(System.currentTimeMillis());
OffsetDateTime now = OffsetDateTime.now();
var usr = userApplication.getUser();
usr.setLastAccessAt(now);
userService.saveUser(usr);
Expand All @@ -68,7 +65,7 @@ public long handlePeers(InetAddress submitterIp, UserApplication userApplication
try {
return Snapshot.builder()
.insertTime(now)
.populateTime(new Timestamp(ping.getPopulateTime()))
.populateTime(TimeUtil.toUTC(ping.getPopulateTime()))
.userApplication(userApplication)
.submitId(UUID.randomUUID().toString())
.peerIp(IPUtil.toInet(peer.getIpAddress()))
Expand Down Expand Up @@ -101,7 +98,7 @@ public long handlePeers(InetAddress submitterIp, UserApplication userApplication
@Modifying
@Transactional
public long handleBans(InetAddress submitterIp, UserApplication userApplication, BtnBanPing ping) {
Timestamp now = new Timestamp(System.currentTimeMillis());
OffsetDateTime now = OffsetDateTime.now();
var usr = userApplication.getUser();
usr.setLastAccessAt(now);
userService.saveUser(usr);
Expand All @@ -113,7 +110,7 @@ public long handleBans(InetAddress submitterIp, UserApplication userApplication,
try {
return BanHistory.builder()
.insertTime(now)
.populateTime(new Timestamp(ping.getPopulateTime()))
.populateTime(TimeUtil.toUTC(ping.getPopulateTime()))
.userApplication(userApplication)
.submitId(UUID.randomUUID().toString())
.peerIp(IPUtil.toInet(peer.getIpAddress()))
Expand Down
Loading

0 comments on commit 8217ed8

Please sign in to comment.