Browse Source

jdbc template migrate 2

master
gsd 1 year ago
parent
commit
3cc9f0a851
  1. 2
      src/main/java/app/configurations/DbRwConfigurarion.java
  2. 25
      src/main/java/app/entities/DonateStatistic.java
  3. 29
      src/main/java/app/entities/db/DonateStat.java
  4. 29
      src/main/java/app/entities/db/Gametime.java
  5. 19
      src/main/java/app/entities/db/freevip/FreeVIP.java
  6. 2
      src/main/java/app/services/db/BanService.java
  7. 30
      src/main/java/app/services/db/CollectStatisticService.java
  8. 2
      src/main/java/app/services/db/DBService.java
  9. 70
      src/main/java/app/services/db/DetectService.java
  10. 68
      src/main/java/app/services/db/DiscordAuthService.java
  11. 101
      src/main/java/app/services/db/DonateService.java
  12. 84
      src/main/java/app/services/db/FreeVIPService.java
  13. 241
      src/main/java/app/services/db/KillfeedService.java
  14. 107
      src/main/java/app/services/db/MessageService.java
  15. 30
      src/main/java/app/services/db/NicknameService.java
  16. 5
      src/main/java/app/services/db/PermitionService.java
  17. 120
      src/main/java/app/services/db/UsertimeService.java
  18. 71
      src/main/java/app/services/db/VIPService.java

2
src/main/java/app/configurations/DbRwConfigurarion.java

@ -8,6 +8,7 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@ -68,6 +69,7 @@ public class DbRwConfigurarion implements DbConfiguration{
@Bean(name = "jt_rw") @Bean(name = "jt_rw")
@Scope(value = "prototype") @Scope(value = "prototype")
@Primary
public JdbcTemplate getJT() { public JdbcTemplate getJT() {
return new JdbcTemplate(DataSource()); return new JdbcTemplate(DataSource());
} }

25
src/main/java/app/entities/DonateStatistic.java

@ -2,20 +2,41 @@ package app.entities;
import lombok.Data; import lombok.Data;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
CREATE TABLE `gived_vip` (
`id` int(11) NOT NULL,
`steam2` varchar(65) NOT NULL,
`amount` int(11) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT current_timestamp(),
`givemethod` int(11) NOT NULL COMMENT 'FREE, STEAM, QIWI, MANUAL',
`reserved` varchar(65) DEFAULT NULL,
`extend` tinyint(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
*/
@Data @Data
public class DonateStatistic { public class DonateStatistic {
VipGiveMethod giveMethod; VipGiveMethod giveMethod;
Integer count; Long count;
String reserved; String reserved;
Integer amount; Integer amount;
//sub //sub
public DonateStatistic(Object[] raw) { public DonateStatistic(Object[] raw) {
giveMethod = VipGiveMethod.values()[(int) raw[0]]; giveMethod = VipGiveMethod.values()[(int) raw[0]];
count = ((Long) raw[1]).intValue(); count = ((Long) raw[1]);
reserved = raw[2]==null?"": (String) raw[2]; reserved = raw[2]==null?"": (String) raw[2];
amount = (int) raw[3]; amount = (int) raw[3];
} }
public DonateStatistic(ResultSet rs) throws SQLException {
giveMethod = VipGiveMethod.values()[rs.getInt("givemethod")];
count = rs.getLong("count");
reserved = rs.getString("reserved");
amount = rs.getInt("amount");
}
public DonateStatistic(Object o) { public DonateStatistic(Object o) {
this((Object[]) o); this((Object[]) o);
} }

29
src/main/java/app/entities/db/DonateStat.java

@ -1,13 +1,24 @@
package app.entities.db; package app.entities.db;
import app.entities.DonateStatistic;
import app.entities.VipGiveMethod; import app.entities.VipGiveMethod;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.Data; import lombok.Data;
import java.util.List; import java.sql.ResultSet;
import java.sql.SQLException;
/*
CREATE TABLE `gived_vip` (
`id` int(11) NOT NULL,
`steam2` varchar(65) NOT NULL,
`amount` int(11) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT current_timestamp(),
`givemethod` int(11) NOT NULL COMMENT 'FREE, STEAM, QIWI, MANUAL',
`reserved` varchar(65) DEFAULT NULL,
`extend` tinyint(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
*/
@Data @Data
public class DonateStat { public class DonateStat {
@ -34,6 +45,16 @@ public class DonateStat {
this.utime = (long) obj[7]; this.utime = (long) obj[7];
} }
public DonateStat(ResultSet rs) throws SQLException {
id = rs.getInt("id");
steam2 = rs.getString("steam2");
amount = rs.getInt("amount");
giveMethod = VipGiveMethod.values()[rs.getInt("givemethod")];
reserved = rs.getString("reserved");
extended = rs.getBoolean("extend");
utime = rs.getLong("utime");
}
public DonateStat(Integer rubles, Integer keys, Integer refs) { public DonateStat(Integer rubles, Integer keys, Integer refs) {
//потом бля //потом бля
} }

29
src/main/java/app/entities/db/Gametime.java

@ -4,8 +4,24 @@ import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data; import lombok.Data;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp; import java.sql.Timestamp;
/*
CREATE TABLE `user_connections` (
`id` int(11) NOT NULL,
`player_name` varchar(64) NOT NULL,
`steam_id` varchar(32) NOT NULL,
`connect_ip` varchar(15) NOT NULL,
`account_id` bigint(20) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT current_timestamp(),
`map` varchar(128) NOT NULL,
`connection_type` varchar(10) NOT NULL,
`connect_duration` int(11) NOT NULL,
`reason` varchar(256) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
*/
@Data @Data
public class Gametime { public class Gametime {
@ -40,6 +56,19 @@ public class Gametime {
reason = (String) obj[9]; reason = (String) obj[9];
} }
public Gametime(ResultSet rs) throws SQLException {
id = rs.getInt("id");
player_name = rs.getString("player_name");
steam_id = rs.getString("steam_id");
connect_ip = rs.getString("connect_ip");
account_id = rs.getLong("account_id");
timestamp = rs.getTimestamp("timestamp");
map = rs.getString("map");
connection_type = rs.getString("connection_type");
connect_duration = rs.getInt("connect_duration");
reason = rs.getString("reason");
}
@JsonGetter @JsonGetter
public String getMap() { public String getMap() {
return map.replace("workshop/","").split(".ugc", 2)[0]; return map.replace("workshop/","").split(".ugc", 2)[0];

19
src/main/java/app/entities/db/freevip/FreeVIP.java

@ -3,8 +3,19 @@ package app.entities.db.freevip;
import app.entities.SocialAuth; import app.entities.SocialAuth;
import lombok.Data; import lombok.Data;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp; import java.sql.Timestamp;
/*
CREATE TABLE `free_vip` (
`id` int(11) NOT NULL,
`steam3` varchar(65) NOT NULL,
`vk_id` bigint(20) NOT NULL,
`discord_id` bigint(20) NOT NULL,
`date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
*/
@Data @Data
public class FreeVIP extends SocialAuth { public class FreeVIP extends SocialAuth {
int id; int id;
@ -18,4 +29,12 @@ public class FreeVIP extends SocialAuth {
discord_id = (long) obj[3]; discord_id = (long) obj[3];
timestamp = (Timestamp) obj[4]; timestamp = (Timestamp) obj[4];
} }
public FreeVIP(ResultSet rs) throws SQLException {
id = rs.getInt("id");
steam3 = rs.getString("steam3");
vk_id = rs.getInt("vk_id");
discord_id = rs.getLong("discord_id");
timestamp = rs.getTimestamp("date");
}
} }

2
src/main/java/app/services/db/BanService.java

@ -5,13 +5,11 @@ import app.entities.db.Ban;
import app.entities.other.SteamID; import app.entities.other.SteamID;
import app.services.ServerService; import app.services.ServerService;
import app.utils.CryptedCookie; import app.utils.CryptedCookie;
import jakarta.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;

30
src/main/java/app/services/db/CollectStatisticService.java

@ -2,33 +2,23 @@ package app.services.db;
import app.entities.db.CollectableStatistic; import app.entities.db.CollectableStatistic;
import app.updates.BaseUpdater; import app.updates.BaseUpdater;
import jakarta.annotation.PostConstruct;
import jakarta.persistence.EntityManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
@Service @Service
@Transactional("RwTransactionManager")
public class CollectStatisticService extends BaseUpdater { public class CollectStatisticService extends BaseUpdater {
private EntityManager entityManager; @Autowired
@Qualifier("jt_rw")
private JdbcTemplate jdbcTemplate;
private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
public CollectStatisticService(@Qualifier(value = "RwEntityManager") EntityManager entityManager) {
this.entityManager = entityManager;
}
@Transactional("RwTransactionManager")
public void add(CollectableStatistic collectableStatistic) { public void add(CollectableStatistic collectableStatistic) {
if (collectableStatistic.isServerRequest()) return; if (collectableStatistic.isServerRequest()) return;
if (collectableStatistic.isIgnoreRule()) return; if (collectableStatistic.isIgnoreRule()) return;
@ -36,14 +26,10 @@ public class CollectStatisticService extends BaseUpdater {
if (!collectableStatistic.isStatsRequests()) if (!collectableStatistic.isStatsRequests())
logger.info(collectableStatistic.toString()); logger.info(collectableStatistic.toString());
entityManager.createNativeQuery("INSERT INTO `web_statistic` (`steam64`, `client_ip`, `method`, `path`, `query`, `useragent`) VALUES (?1, ?2, ?3, ?4, ?5, ?6)") jdbcTemplate.update("INSERT INTO `web_statistic` (`steam64`, `client_ip`, `method`, `path`, `query`, `useragent`) VALUES (?, ?, ?, ?, ?, ?)",
.setParameter(1, collectableStatistic.getSteam64()) collectableStatistic.getSteam64(), collectableStatistic.getClient_ip(),
.setParameter(2, collectableStatistic.getClient_ip()) collectableStatistic.getMethod(), collectableStatistic.getPath(),
.setParameter(3, collectableStatistic.getMethod()) collectableStatistic.getQuery(), collectableStatistic.getUseragent());
.setParameter(4, collectableStatistic.getPath())
.setParameter(5, collectableStatistic.getQuery())
.setParameter(6, collectableStatistic.getUseragent())
.executeUpdate();
} catch (Exception err) { } catch (Exception err) {
logger.error("Ignoring add stats"); logger.error("Ignoring add stats");
} }

2
src/main/java/app/services/db/DBService.java

@ -1,7 +1,5 @@
package app.services.db; package app.services.db;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;

70
src/main/java/app/services/db/DetectService.java

@ -4,44 +4,50 @@ import app.entities.Stats;
import app.entities.other.SteamID; import app.entities.other.SteamID;
import app.entities.server.Server; import app.entities.server.Server;
import app.utils.SteamIDConverter; import app.utils.SteamIDConverter;
import jakarta.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*; import java.util.*;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
@Service @Service
public class DetectService { public class DetectService {
EntityManager entityManager_ro; @Autowired
EntityManager entityManager_rw; @Qualifier("jt_rw")
private JdbcTemplate jdbcTemplate_rw;
@Autowired
@Qualifier("jt_ro")
private JdbcTemplate jdbcTemplate_ro;
private Stats stats; private Stats stats;
@Autowired @Autowired
public DetectService( public DetectService(
Stats stats, Stats stats) {
@Qualifier(value = "RoEntityManager") EntityManager entityManager_ro,
@Qualifier(value = "RwEntityManager") EntityManager entityManager_rw) {
this.entityManager_ro = entityManager_ro;
this.entityManager_rw = entityManager_rw;
this.stats = stats; this.stats = stats;
} }
@Transactional("RoTransactionManager")
public List<SteamID> getAccountsPerSteamID(SteamID steamID) { public List<SteamID> getAccountsPerSteamID(SteamID steamID) {
List<String> founded_steamid = new ArrayList<>(); List<String> founded_steamid = new ArrayList<>();
for (Map.Entry<String, Server> stringServerEntry : stats.getServers().entrySet()) { for (Map.Entry<String, Server> stringServerEntry : stats.getServers().entrySet()) {
founded_steamid.addAll(entityManager_ro.createNativeQuery("SELECT `steam_id` FROM `"+stringServerEntry.getValue().getDb()+"`."+"`user_connections` WHERE `connect_ip` in (SELECT `connect_ip` FROM `" + stringServerEntry.getValue().getDb() + "`." +"`user_connections` WHERE `steam_id` LIKE ?1 AND `connect_ip` NOT LIKE '10.%' GROUP BY `connect_ip` ORDER BY `id` DESC) GROUP BY `steam_id`") founded_steamid.addAll(jdbcTemplate_ro.query("SELECT `steam_id` FROM `" + stringServerEntry.getValue().getDb() + "`." + "`user_connections` WHERE `connect_ip` in (SELECT `connect_ip` FROM `" + stringServerEntry.getValue().getDb() + "`." + "`user_connections` WHERE `steam_id` LIKE ? AND `connect_ip` NOT LIKE '10.%' GROUP BY `connect_ip` ORDER BY `id` DESC) GROUP BY `steam_id`",
.setParameter(1, steamID.steam2) new Object[]{steamID.steam2},
.getResultStream().map(String::valueOf).toList()); new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString("steam_id");
}
}));
} }
//SELECT `steam_id` FROM `tf2.facti13.five`.`user_connections` WHERE `connect_ip` in (SELECT `connect_ip` FROM `tf2.facti13.five`.`user_connections` WHERE `steam_id` LIKE 'STEAM_0:0:63666481' AND `connect_ip` NOT LIKE '10.%' GROUP BY `connect_ip` ORDER BY `id` DESC) GROUP BY `steam_id`; //SELECT `steam_id` FROM `tf2.facti13.five`.`user_connections` WHERE `connect_ip` in (SELECT `connect_ip` FROM `tf2.facti13.five`.`user_connections` WHERE `steam_id` LIKE 'STEAM_0:0:63666481' AND `connect_ip` NOT LIKE '10.%' GROUP BY `connect_ip` ORDER BY `id` DESC) GROUP BY `steam_id`;
return founded_steamid.stream().distinct().map(SteamIDConverter::getSteamID).filter(Objects::nonNull).toList(); return founded_steamid.stream().distinct().map(SteamIDConverter::getSteamID).filter(Objects::nonNull).toList();
@ -60,15 +66,21 @@ public class DetectService {
em_selector.set(0); em_selector.set(0);
} }
String sql = "SELECT `steam_id` FROM `"+stringServerEntry.getValue().getDb()+"`."+"`user_connections` WHERE `connect_ip` in (SELECT `connect_ip` FROM `" + stringServerEntry.getValue().getDb() + "`." +"`user_connections` WHERE `steam_id` LIKE ?1 AND `connect_ip` NOT LIKE '10.%' GROUP BY `connect_ip` ORDER BY `id` DESC) GROUP BY `steam_id`"; String sql = "SELECT `steam_id` FROM `"+stringServerEntry.getValue().getDb()+"`."+"`user_connections` WHERE `connect_ip` in (SELECT `connect_ip` FROM `" + stringServerEntry.getValue().getDb() + "`." +"`user_connections` WHERE `steam_id` LIKE ? AND `connect_ip` NOT LIKE '10.%' GROUP BY `connect_ip` ORDER BY `id` DESC) GROUP BY `steam_id`";
switch (em_selector.get()) { switch (em_selector.get()) {
case 0:return entityManager_ro.createNativeQuery(sql) case 0:return jdbcTemplate_ro.query(sql, new Object[]{steamID.steam2}, new RowMapper<String>() {
.setParameter(1, steamID.steam2) @Override
.getResultStream().map(String::valueOf).toList(); public String mapRow(ResultSet rs, int rowNum) throws SQLException {
case 1:return entityManager_rw.createNativeQuery(sql) return rs.getString("steam_id");
.setParameter(1, steamID.steam2) }
.getResultStream().map(String::valueOf).toList(); });
case 1:return jdbcTemplate_rw.query(sql, new Object[]{steamID.steam2}, new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString("steam_id");
}
});
default: return new ArrayList<>(); default: return new ArrayList<>();
} }
}); });
@ -76,18 +88,22 @@ public class DetectService {
List<String> founded_steamid = new ArrayList<>(); List<String> founded_steamid = new ArrayList<>();
try { try {
executor.invokeAll(tasks).stream().forEach(l -> founded_steamid.addAll(founded_steamid)); executor.invokeAll(tasks).forEach(l -> founded_steamid.addAll(founded_steamid));
} catch (InterruptedException err) { } catch (InterruptedException err) {
//pass //pass
} }
return founded_steamid.stream().distinct().map(SteamIDConverter::getSteamID).filter(Objects::nonNull).toList(); return founded_steamid.stream().distinct().map(SteamIDConverter::getSteamID).filter(Objects::nonNull).toList();
} }
@Transactional("RoTransactionManager") public List<Map<String, Object>> getAttachedDiscordAccountPerSteam(SteamID steamID) {
public List getAttachedDiscordAccountPerSteam(SteamID steamID) { return jdbcTemplate_ro.query("SELECT `discord_id`, UNIX_TIMESTAMP(`timestamp`) as utime, `active` FROM `steam2discord` WHERE `steam_id` LIKE ? GROUP BY `discord_id`",
return entityManager_ro.createNativeQuery("SELECT `discord_id`, UNIX_TIMESTAMP(`timestamp`) as utime, `active` FROM `steam2discord` WHERE `steam_id` LIKE ?1 GROUP BY `discord_id`") new Object[]{ steamID.steam2 },
.setParameter(1, steamID.steam2) new RowMapper<Map<String, Object>>() {
.getResultStream().map(d -> Map.of("discord_id", ((Object[]) d)[0], "utime", ((Object[]) d)[1], "active", ((Object[]) d)[2])).toList(); @Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
return Map.of("discord_id", rs.getObject("discord_id"), "utime", rs.getObject("utime"), "active", rs.getObject("active"));
}
});
} }
//SELECT CONCAT(SUBSTRING_INDEX(connect_ip,'.', 1),'.',SUBSTRING_INDEX(SUBSTRING_INDEX(connect_ip,'.', 2),'.',-1),'.',SUBSTRING_INDEX(SUBSTRING_INDEX(connect_ip,'.', 3),'.',-1),'.','%') FROM `all_users_con_2` WHERE `steam_id` LIKE 'STEAM_0:1:768781968'; //SELECT CONCAT(SUBSTRING_INDEX(connect_ip,'.', 1),'.',SUBSTRING_INDEX(SUBSTRING_INDEX(connect_ip,'.', 2),'.',-1),'.',SUBSTRING_INDEX(SUBSTRING_INDEX(connect_ip,'.', 3),'.',-1),'.','%') FROM `all_users_con_2` WHERE `steam_id` LIKE 'STEAM_0:1:768781968';
} }

68
src/main/java/app/services/db/DiscordAuthService.java

@ -2,68 +2,66 @@ package app.services.db;
import app.entities.other.SteamID; import app.entities.other.SteamID;
import app.utils.SteamIDConverter; import app.utils.SteamIDConverter;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
@Service @Service
@Transactional("RwTransactionManager")
public class DiscordAuthService { public class DiscordAuthService {
EntityManager entityManager;
@Autowired @Autowired
public DiscordAuthService(@Qualifier(value = "RwEntityManager") EntityManager entityManager) { JdbcTemplate jdbcTemplate;
this.entityManager = entityManager;
}
private HashMap<String, List<String>> processing_accounts = new HashMap<>(); private HashMap<String, List<String>> processing_accounts = new HashMap<>();
public SteamID getSteamIDofDiscordID(String discord_id) { public SteamID getSteamIDofDiscordID(String discord_id) {
return (SteamID) entityManager.createNativeQuery("SELECT steam_id FROM steam2discord WHERE discord_id = ?1 AND active = 1 LIMIT 1") return jdbcTemplate.query("SELECT steam_id FROM steam2discord WHERE discord_id = ? AND active = 1 LIMIT 1",
.setParameter(1, discord_id) new Object[]{ discord_id },
.getResultStream() new RowMapper<SteamID>() {
.map(obj -> SteamIDConverter.getSteamID((String) obj)) @Override
.findFirst() public SteamID mapRow(ResultSet rs, int numRow) throws SQLException {
.orElse(null); return SteamIDConverter.getSteamID(rs.getString("steam_id"));
}
}).stream().findFirst().orElse(null);
} }
public String getDiscordIDofSteamID(SteamID steamID) { public String getDiscordIDofSteamID(SteamID steamID) {
return (String) entityManager.createNativeQuery("SELECT discord_id FROM steam2discord WHERE steam_id = ?1 AND active = 1 LIMIT 1") return jdbcTemplate.query("SELECT discord_id FROM steam2discord WHERE steam_id = ?1 AND active = 1 LIMIT 1",
.setParameter(1, steamID.steam2) new Object[]{ steamID.steam2 },
.getResultStream() new RowMapper<String>() {
.map(String::valueOf) @Override
.findFirst() public String mapRow(ResultSet rs, int numRow) throws SQLException {
.orElse(null); return rs.getString("discord_id");
}
}).stream().findFirst().orElse(null);
} }
@Transactional("RwTransactionManager")
public boolean setSteamIDofDiscordID(SteamID steamID, String discord_id) { public boolean setSteamIDofDiscordID(SteamID steamID, String discord_id) {
return entityManager.createNativeQuery("INSERT INTO `steam2discord` (`id`, `steam_id`, `discord_id`, `timestamp`, `active`) VALUES (NULL, ?1, ?2, current_timestamp(), '1')") return jdbcTemplate.update("INSERT INTO `steam2discord` (`id`, `steam_id`, `discord_id`, `timestamp`, `active`) VALUES (NULL, ?, ?, current_timestamp(), '1')",
.setParameter(1, steamID.steam2) steamID.steam2, discord_id) > 0;
.setParameter(2, discord_id)
.executeUpdate() > 0;
} }
@Transactional("RwTransactionManager")
public boolean removeSteamIDofDiscordID(SteamID steamID) { public boolean removeSteamIDofDiscordID(SteamID steamID) {
return entityManager.createNativeQuery("UPDATE `steam2discord` SET `active` = '0' WHERE `steam_id` LIKE ?1") return jdbcTemplate.update("UPDATE `steam2discord` SET `active` = '0' WHERE `steam_id` LIKE ?",
.setParameter(1, steamID.steam2) steamID.steam2) > 0;
.executeUpdate() > 0;
} }
public List<String> getAccountsNotInList(List<String> discord_accounts) { public List<String> getAccountsNotInList(List<String> discord_accounts) {
return entityManager.createNativeQuery("SELECT `discord_id` FROM `steam2discord` WHERE `active` = 1 AND `discord_id` in ?1") return jdbcTemplate.query("SELECT `discord_id` FROM `steam2discord` WHERE `active` = 1 AND `discord_id` in ?",
.setParameter(1, discord_accounts) new Object[]{ discord_accounts },
.getResultStream().map(String::valueOf).toList(); new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString("discord_id");
}
});
} }
public HashMap<String, List<String>> getProcessing_accounts() { public HashMap<String, List<String>> getProcessing_accounts() {

101
src/main/java/app/services/db/DonateService.java

@ -7,76 +7,86 @@ import app.entities.VipGiveMethod;
import app.entities.db.DonateStat; import app.entities.db.DonateStat;
import app.entities.other.SteamID; import app.entities.other.SteamID;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal; import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
@Component @Component
@Transactional("RoTransactionManager")
public class DonateService { public class DonateService {
EntityManager entityManager; @Autowired
@Qualifier("jt_ro")
private JdbcTemplate jdbcTemplate;
Stats stats; private Stats stats;
@Autowired @Autowired
public DonateService(Stats stats, @Qualifier(value = "RoEntityManager") EntityManager entityManager) { public DonateService(Stats stats) {
this.entityManager = entityManager;
this.stats = stats; this.stats = stats;
} }
//KEY, METAL //KEY, METAL
public Pair<Integer, Integer> getSummarySteamDonateValue(StatisticRange statisticRange) { public Pair<Integer, Integer> getSummarySteamDonateValue(StatisticRange statisticRange) {
List<Object[]> steam = entityManager.createNativeQuery( return jdbcTemplate.query("SELECT SUM(CAST(REPLACE(REPLACE(substring_index(`reserved`,';',-2), 'metal=',''), ';','') AS INT)) as r," +
"SELECT SUM(CAST(REPLACE(REPLACE(substring_index(`reserved`,';',-2), 'metal=',''), ';','') AS INT)) as r," + " SUM(CAST(REPLACE(REPLACE(substring_index(`reserved`,';',1), 'keys=',''), ';','') as INT)) as k " +
" SUM(CAST(REPLACE(REPLACE(substring_index(`reserved`,';',1), 'keys=',''), ';','') as INT)) as k " + "FROM `gived_vip` WHERE `givemethod` = ? AND `timestamp` > CAST(DATE_FORMAT(NOW() ,?) as DATE)",
"FROM `gived_vip` WHERE `givemethod` = ?1 AND `timestamp` > CAST(DATE_FORMAT(NOW() ,?2) as DATE)") new Object[]{VipGiveMethod.STEAM.ordinal(), StatisticRange.cast(statisticRange)},
.setParameter(1, VipGiveMethod.STEAM.ordinal()) new RowMapper<Pair<Integer, Integer>>() {
.setParameter(2, StatisticRange.cast(statisticRange)) @Override
.getResultList(); public Pair<Integer, Integer> mapRow(ResultSet rs, int numRow) throws SQLException {
int metal = 0, key = 0; return Pair.of(
if(!steam.isEmpty()) { Optional.of(rs.getInt("k")).orElse(0),
metal = steam.get(0)==null||steam.get(0)[0]==null?0: Integer.parseInt(steam.get(0)[0].toString()); Optional.of(rs.getInt("r")).orElse(0)
key = steam.get(0)==null||steam.get(0)[1]==null?0: Integer.parseInt(steam.get(0)[1].toString()); );
} }
return Pair.of(key, metal); }).stream().findFirst().orElse(Pair.of(0,0));
} }
public Integer getSummaryQiwiDonateValue(StatisticRange statisticRange) { public Integer getSummaryQiwiDonateValue(StatisticRange statisticRange) {
List<Object> qiwi = entityManager.createNativeQuery( return jdbcTemplate.query("SELECT SUM(CAST(REPLACE(REPLACE(substring_index(`reserved`,';',1), 'rub=',''), ';','') as INT)) as k " +
"SELECT SUM(CAST(REPLACE(REPLACE(substring_index(`reserved`,';',1), 'rub=',''), ';','') as INT)) as k " + "FROM `gived_vip` WHERE `givemethod` = ? AND `timestamp` > CAST(DATE_FORMAT(NOW() ,?) as DATE)",
"FROM `gived_vip` WHERE `givemethod` = ?1 AND `timestamp` > CAST(DATE_FORMAT(NOW() ,?2) as DATE)") new Object[]{ VipGiveMethod.QIWI.ordinal(), StatisticRange.cast(statisticRange)},
.setParameter(1, VipGiveMethod.QIWI.ordinal()) new RowMapper<Integer>() {
.setParameter(2, StatisticRange.cast(statisticRange)) @Override
.getResultList(); public Integer mapRow(ResultSet rs, int numRow) throws SQLException {
return qiwi.get(0)==null?0: Integer.parseInt(qiwi.get(0).toString()); return rs.getInt("k");
}
}).stream().findFirst().orElse(0);
} }
//no need if use getGivedVipStatistic //no need if use getGivedVipStatistic
public Integer getSummaryGivedFreeVip(StatisticRange statisticRange) { public Long getSummaryGivedFreeVip(StatisticRange statisticRange) {
Long count = (Long) entityManager.createNativeQuery("SELECT COUNT(*) as count FROM `gived_vip` WHERE `givemethod` = ?1 AND `timestamp` > CAST(DATE_FORMAT(NOW() ,?2) as DATE)") return jdbcTemplate.query("SELECT COUNT(*) as count FROM `gived_vip` WHERE `givemethod` = ? AND `timestamp` > CAST(DATE_FORMAT(NOW() ,?) as DATE)",
.setParameter(1, VipGiveMethod.FREE.ordinal()) new Object[]{ VipGiveMethod.FREE.ordinal(), StatisticRange.cast(statisticRange) },
.setParameter(2, StatisticRange.cast(statisticRange)) new RowMapper<Long>() {
.getSingleResult(); @Override
return count.intValue(); public Long mapRow(ResultSet rs, int numRow) throws SQLException {
return rs.getLong("count");
}
}).stream().findFirst().orElse(0L);
} }
public HashMap getGivedVipStatistic(StatisticRange statisticRange) { public HashMap getGivedVipStatistic(StatisticRange statisticRange) {
List<Object[]> raw_donateStatistics = entityManager.createNativeQuery("SELECT `givemethod`,COUNT(*) as count,`reserved`, `amount` FROM `gived_vip` WHERE `givemethod` IN (0,1,2) AND `timestamp` > CAST(DATE_FORMAT(NOW() ,?1) as DATE) GROUP BY `givemethod`, `amount`") List<DonateStatistic> donateStatistics = jdbcTemplate.query("SELECT `givemethod`,COUNT(*) as count,`reserved`, `amount` FROM `gived_vip` WHERE `givemethod` IN (0,1,2) AND `timestamp` > CAST(DATE_FORMAT(NOW() ,?) as DATE) GROUP BY `givemethod`, `amount`",
.setParameter(1, StatisticRange.cast(statisticRange)) new Object[]{StatisticRange.cast(statisticRange)},
.getResultList(); new RowMapper<DonateStatistic>() {
List<DonateStatistic> donateStatistics = raw_donateStatistics.stream().map(DonateStatistic::new).toList(); @Override
public DonateStatistic mapRow(ResultSet rs, int rowNum) throws SQLException {
return new DonateStatistic(rs);
}
});
HashMap<String, HashMap> map = new HashMap<>(); HashMap<String, HashMap> map = new HashMap<>();
map.put("steam", new HashMap<>()); map.put("steam", new HashMap<>());
@ -106,9 +116,14 @@ public class DonateService {
} }
public List<DonateStat> getDonateStatistic(SteamID steamID) { public List<DonateStat> getDonateStatistic(SteamID steamID) {
return entityManager.createNativeQuery("SELECT *, UNIX_TIMESTAMP(`timestamp`) as utime FROM `gived_vip` WHERE `steam2` LIKE ?1") return jdbcTemplate.query("SELECT *, UNIX_TIMESTAMP(`timestamp`) as utime FROM `gived_vip` WHERE `steam2` LIKE ?",
.setParameter(1, steamID.steam2) new Object[]{steamID.steam2},
.getResultStream().map(obj -> new DonateStat((Object[]) obj)).toList(); new RowMapper<DonateStat>() {
@Override
public DonateStat mapRow(ResultSet rs, int rowNum) throws SQLException {
return new DonateStat(rs);
}
});
} }
public HashMap getDonateStatistic(StatisticRange statisticRange) { public HashMap getDonateStatistic(StatisticRange statisticRange) {

84
src/main/java/app/services/db/FreeVIPService.java

@ -4,55 +4,65 @@ import app.entities.SocialAuth;
import app.entities.VipGiveMethod; import app.entities.VipGiveMethod;
import app.entities.db.freevip.FreeVIP; import app.entities.db.freevip.FreeVIP;
import app.entities.other.SteamID; import app.entities.other.SteamID;
import app.entities.server.Server;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.annotation.Value; import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@Service @Service
@Transactional("RwTransactionManager")
public class FreeVIPService{ public class FreeVIPService{
EntityManager entityManager; @Autowired
private JdbcTemplate jdbcTemplate;
UsertimeService usertimeService; private UsertimeService usertimeService;
VIPService vipService; private VIPService vipService;
@Autowired @Autowired
public FreeVIPService(UsertimeService usertimeService, public FreeVIPService(UsertimeService usertimeService,
VIPService vipService, VIPService vipService) {
@Qualifier(value = "RwEntityManager") EntityManager entityManager) {
this.entityManager = entityManager;
this.usertimeService = usertimeService; this.usertimeService = usertimeService;
this.vipService = vipService; this.vipService = vipService;
} }
public Long getDBServerUTime() { public Long getDBServerUTime() {
return (Long) entityManager.createNativeQuery("SELECT UNIX_TIMESTAMP(NOW())") return jdbcTemplate.query("SELECT UNIX_TIMESTAMP(NOW()) as c",
.getSingleResult(); new RowMapper<Long>() {
@Override
public Long mapRow(ResultSet rs, int numRow) throws SQLException {
return rs.getLong("c");
}
}).stream().findFirst().orElse(0L);
} }
public List<FreeVIP> getSocial(SteamID steamID) { public List<FreeVIP> getSocial(SteamID steamID) {
return entityManager.createNativeQuery("SELECT id, steam3, vk_id, discord_id, date FROM free_vip WHERE steam3 = ?1 ORDER BY `free_vip`.`date` DESC") return jdbcTemplate.query("SELECT id, steam3, vk_id, discord_id, date FROM free_vip WHERE steam3 = ? ORDER BY `free_vip`.`date` DESC",
.setParameter(1, steamID.steam2) new Object[]{steamID.steam2},
.getResultList(); new RowMapper<FreeVIP>() {
@Override
public FreeVIP mapRow(ResultSet rs, int rowNum) throws SQLException {
return new FreeVIP(rs);
}
});
} }
public Long getLastGivedFreeVIP(SteamID steamID) { public Long getLastGivedFreeVIP(SteamID steamID) {
return (Long) entityManager.createNativeQuery("SELECT UNIX_TIMESTAMP(`date`) as u_time FROM free_vip WHERE steam3 LIKE ?1 ORDER BY `date` DESC") return jdbcTemplate.query("SELECT UNIX_TIMESTAMP(`date`) as u_time FROM free_vip WHERE steam3 LIKE ? ORDER BY `date` DESC",
.setParameter(1, steamID.steam2) new Object[]{ steamID.steam2 },
.getResultStream().findFirst().orElse(0L); new RowMapper<Long>() {
@Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong("u_time");
}
}).stream().findFirst().orElse(0L);
} }
public Long getLastGivedFreeVIP(SocialAuth socialAuth) { public Long getLastGivedFreeVIP(SocialAuth socialAuth) {
@ -60,26 +70,32 @@ public class FreeVIPService{
return 0L; return 0L;
} }
else if (socialAuth.getVk_id() != 0) { else if (socialAuth.getVk_id() != 0) {
return (Long) entityManager.createNativeQuery("SELECT UNIX_TIMESTAMP(`date`) as u_time FROM free_vip WHERE vk_id = ?1 ORDER BY `date` DESC") return jdbcTemplate.query("SELECT UNIX_TIMESTAMP(`date`) as u_time FROM free_vip WHERE vk_id = ? ORDER BY `date` DESC",
.setParameter(1, socialAuth.getVk_id()) new Object[]{ socialAuth.getVk_id() },
.getResultStream().findFirst().orElse(0L); new RowMapper<Long>() {
@Override
public Long mapRow(ResultSet rs, int numRow) throws SQLException {
return rs.getLong("u_time");
}
}).stream().findFirst().orElse(0L);
} else if (socialAuth.getDiscord_id() != 0) { } else if (socialAuth.getDiscord_id() != 0) {
return (Long) entityManager.createNativeQuery("SELECT UNIX_TIMESTAMP(`date`) as u_time FROM free_vip WHERE discord_id = ?1 ORDER BY `date` DESC") return jdbcTemplate.query("SELECT UNIX_TIMESTAMP(`date`) as u_time FROM free_vip WHERE discord_id = ? ORDER BY `date` DESC",
.setParameter(1, socialAuth.getDiscord_id()) new Object[]{ socialAuth.getDiscord_id() },
.getResultStream().findFirst().orElse(0L); new RowMapper<Long>() {
@Override
public Long mapRow(ResultSet rs, int numRow) throws SQLException {
return rs.getLong("u_time");
}
}).stream().findFirst().orElse(0L);
} else { } else {
return 0L; return 0L;
} }
} }
@Transactional("RwTransactionManager")
public boolean setGivedFreeVip(SteamID steamID, SocialAuth socialAuth) { public boolean setGivedFreeVip(SteamID steamID, SocialAuth socialAuth) {
if (socialAuth == null) socialAuth = new SocialAuth(); if (socialAuth == null) socialAuth = new SocialAuth();
return entityManager.createNativeQuery("INSERT INTO `free_vip` (`id`, `steam3`, `vk_id`, `discord_id`, `date`) VALUES (NULL, ?1, ?2, ?3, current_timestamp())") return jdbcTemplate.update("INSERT INTO `free_vip` (`id`, `steam3`, `vk_id`, `discord_id`, `date`) VALUES (NULL, ?, ?, ?, current_timestamp())",
.setParameter(1, steamID.steam2) steamID.steam2, socialAuth.getVk_id(), socialAuth.getDiscord_id()) > 0;
.setParameter(2, socialAuth.getVk_id())
.setParameter(3, socialAuth.getDiscord_id())
.executeUpdate() > 0;
} }
public Long addFreeVIP(SteamID steamID, SocialAuth socialAuth, Boolean test) { public Long addFreeVIP(SteamID steamID, SocialAuth socialAuth, Boolean test) {

241
src/main/java/app/services/db/KillfeedService.java

@ -2,83 +2,109 @@ package app.services.db;
import app.entities.Stats; import app.entities.Stats;
import app.entities.other.SteamID; import app.entities.other.SteamID;
import app.utils.SteamIDConverter;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import jakarta.persistence.EntityManager;
import lombok.Data; import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@Service @Service
@Transactional("RoTransactionManager")
public class KillfeedService { public class KillfeedService {
private EntityManager entityManager; @Autowired
@Qualifier("jt_ro")
private JdbcTemplate jdbcTemplate;
private Stats stats; private Stats stats;
private NicknameService nicknameService; private NicknameService nicknameService;
KillfeedService(Stats stats, @Qualifier(value = "RoEntityManager") EntityManager entityManager, NicknameService nicknameService) { KillfeedService(Stats stats, NicknameService nicknameService) {
this.entityManager = entityManager;
this.stats = stats; this.stats = stats;
this.nicknameService = nicknameService; this.nicknameService = nicknameService;
} }
public Long getKills(SteamID steamID, String server_id) { public Long getKills(SteamID steamID, String server_id) {
return (Long) entityManager.createNativeQuery("SELECT COUNT(*) FROM `user_killfeed` WHERE `attacker_id` = ?1 AND `attacker_id` != `victim_id` AND `server_id` like ?2") return jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `attacker_id` = ? AND `attacker_id` != `victim_id` AND `server_id` like ?",
.setParameter(1, steamID.account_id) new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id },
.setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) new RowMapper<Long>() {
.getSingleResult(); @Override
public Long mapRow(ResultSet rs, int numRow) throws SQLException {
return rs.getLong("c");
}
}).stream().findFirst().orElse(0L);
} }
public List<TopInFeed> getTopKills(String server_id) { public List<TopInFeed> getTopKills(String server_id) {
List<TopInFeed> result = entityManager.createNativeQuery("SELECT `attacker_id`, count(*) as c, `server_id` FROM `user_killfeed` WHERE `victim_id` != `attacker_id` AND `attacker_id` != 0 AND `server_id` LIKE ?1 GROUP BY `attacker_id` ORDER BY `c` DESC LIMIT 10") return jdbcTemplate.query("SELECT `attacker_id`, count(*) as c, `server_id` FROM `user_killfeed` WHERE `victim_id` != `attacker_id` AND `attacker_id` != 0 AND `server_id` LIKE ? GROUP BY `attacker_id` ORDER BY `c` DESC LIMIT 10",
.setParameter(1, server_id==null||server_id.isEmpty()?'%':server_id) new Object[]{server_id == null || server_id.isEmpty() ? '%' : server_id},
.getResultStream().map(obj -> new TopInFeed(obj)).toList(); new RowMapper<TopInFeed>() {
return result.stream().peek(kif -> kif.setNicknames(nicknameService)).toList(); @Override
public TopInFeed mapRow(ResultSet rs, int rowNum) throws SQLException {
return new TopInFeed(rs).setNicknames(nicknameService);
}
});
} }
public Long getDeads(SteamID steamID, String server_id) { public Long getDeads(SteamID steamID, String server_id) {
return (Long) entityManager.createNativeQuery("SELECT COUNT(*) FROM `user_killfeed` WHERE `victim_id` = ?1 AND `attacker_id` != `victim_id` AND `server_id` like ?2") return jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `victim_id` = ? AND `attacker_id` != `victim_id` AND `server_id` like ?",
.setParameter(1, steamID.account_id) new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id },
.setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) new RowMapper<Long>() {
.getSingleResult(); @Override
public Long mapRow(ResultSet rs, int numRow) throws SQLException {
return rs.getLong("rs");
}
}).stream().findFirst().orElse(0L);
} }
public List<TopInFeed> getTopDeads(String server_id) { public List<TopInFeed> getTopDeads(String server_id) {
List<TopInFeed> result = entityManager.createNativeQuery("SELECT `victim_id`, count(`id`) as c, `server_id` FROM `user_killfeed` WHERE `victim_id` != `attacker_id` AND `victim_id` != 0 AND `server_id` LIKE ?1 GROUP BY `victim_id` ORDER BY `c` DESC LIMIT 10") return jdbcTemplate.query("SELECT `victim_id`, count(`id`) as c, `server_id` FROM `user_killfeed` WHERE `victim_id` != `attacker_id` AND `victim_id` != 0 AND `server_id` LIKE ? GROUP BY `victim_id` ORDER BY `c` DESC LIMIT 10",
.setParameter(1, server_id==null||server_id.isEmpty()?'%':server_id) new Object[]{ server_id == null || server_id.isEmpty() ? '%' : server_id},
.getResultStream().map(obj -> new TopInFeed(obj)).toList(); new RowMapper<TopInFeed>() {
return result.stream().peek(kif -> kif.setNicknames(nicknameService)).toList(); @Override
public TopInFeed mapRow(ResultSet rs, int rowNum) throws SQLException {
return new TopInFeed(rs).setNicknames(nicknameService);
}
});
} }
public Long getSuicides(SteamID steamID, String server_id) { public Long getSuicides(SteamID steamID, String server_id) {
return (Long) entityManager.createNativeQuery("SELECT COUNT(*) FROM `user_killfeed` WHERE `victim_id` = ?1 AND `attacker_id` = `victim_id` AND `server_id` like ?2") return jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `victim_id` = ? AND `attacker_id` = `victim_id` AND `server_id` like ?",
.setParameter(1, steamID.account_id) new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id },
.setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) new RowMapper<Long>() {
.getSingleResult(); @Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong("c");
}
}).stream().findFirst().orElse(0L);
} }
public Long getAssists(SteamID steamID, String server_id) { public Long getAssists(SteamID steamID, String server_id) {
return (Long) entityManager.createNativeQuery("SELECT COUNT(*) FROM `user_killfeed` WHERE `assister_id` = ?1 AND `server_id` like ?2") return jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `assister_id` = ? AND `server_id` like ?",
.setParameter(1, steamID.account_id) new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id},
.setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) new RowMapper<Long>() {
.getSingleResult(); @Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong("c");
}
}).stream().findFirst().orElse(0L);
} }
public Map getPopulateWeapons(SteamID steamID, String server_id, int offset, int limit) { public Map getPopulateWeapons(SteamID steamID, String server_id, int offset, int limit) {
List<HypeWeapons> result = entityManager.createNativeQuery("SELECT COUNT(u.`weapon_index`) as c, i.`name`, u.`server_id`, u.`weapon_classname` FROM `user_killfeed` as u INNER JOIN `tf2idb`.`tf2idb_item` as i ON u.`weapon_index` = i.`id` WHERE u.`attacker_id` = ?1 AND `attacker_id` != `victim_id` AND u.server_id like ?2 GROUP BY u.`weapon_index` DESC ORDER BY `c` DESC LIMIT ?3 OFFSET ?4") List<HypeWeapons> result = jdbcTemplate.query("SELECT COUNT(u.`weapon_index`) as c, i.`name`, u.`server_id`, u.`weapon_classname` FROM `user_killfeed` as u INNER JOIN `tf2idb`.`tf2idb_item` as i ON u.`weapon_index` = i.`id` WHERE u.`attacker_id` = ? AND `attacker_id` != `victim_id` AND u.server_id like ? GROUP BY u.`weapon_index` DESC ORDER BY `c` DESC LIMIT ? OFFSET ?",
.setParameter(1, steamID.account_id) new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id, limit, offset },
.setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) new RowMapper<HypeWeapons>() {
.setParameter(3, limit) @Override
.setParameter(4, offset) public HypeWeapons mapRow(ResultSet rs, int rowNum) throws SQLException {
.getResultStream().map(obj -> new HypeWeapons(obj)).toList(); return new HypeWeapons(rs);
}
});
/*Long count = (Long) entityManager.createNativeQuery("SELECT COUNT(`weapon_index`) FROM `user_killfeed` WHERE `attacker_id` = ?1 AND server_id like ?2 GROUP BY `weapon_index`") /*Long count = (Long) entityManager.createNativeQuery("SELECT COUNT(`weapon_index`) FROM `user_killfeed` WHERE `attacker_id` = ?1 AND server_id like ?2 GROUP BY `weapon_index`")
.setParameter(1, steamID.account_id) .setParameter(1, steamID.account_id)
.setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) .setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id)
@ -87,45 +113,69 @@ public class KillfeedService {
} }
public Map getKills(SteamID steamID, String server_id, int offset, int limit) { public Map getKills(SteamID steamID, String server_id, int offset, int limit) {
List<KillsInFeed> result = entityManager.createNativeQuery("SELECT -1, u.victim_id, u.assister_id, u.utime, i.name, u.server_id, u.weapon_classname FROM `user_killfeed` as u INNER JOIN `tf2idb`.`tf2idb_item` as i ON u.`weapon_index` = i.`id` WHERE u.`attacker_id` = ?1 AND u.`attacker_id` != u.`victim_id` AND u.`server_id` like ?2 ORDER BY u.`id` DESC LIMIT ?3 OFFSET ?4") List<KillsInFeed> result = jdbcTemplate.query("SELECT -1, u.victim_id, u.assister_id, u.utime, i.name, u.server_id, u.weapon_classname FROM `user_killfeed` as u INNER JOIN `tf2idb`.`tf2idb_item` as i ON u.`weapon_index` = i.`id` WHERE u.`attacker_id` = ? AND u.`attacker_id` != u.`victim_id` AND u.`server_id` like ? ORDER BY u.`id` DESC LIMIT ? OFFSET ?",
.setParameter(1, steamID.account_id) new Object[]{steamID.account_id, server_id == null || server_id.isEmpty() ? '%' : server_id, limit, offset},
.setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) new RowMapper<KillsInFeed>() {
.setParameter(3, limit) @Override
.setParameter(4, offset) public KillsInFeed mapRow(ResultSet rs, int rowNum) throws SQLException {
.getResultStream().map(obj -> new KillsInFeed(obj)).toList(); return new KillsInFeed(rs).setNicknames(nicknameService);
Long count = (Long) entityManager.createNativeQuery("SELECT COUNT(*) FROM `user_killfeed` WHERE `attacker_id` = ?1 AND `attacker_id` != `victim_id` AND `server_id` like ?2") }
.setParameter(1, steamID.account_id) });
.setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id)
.getSingleResult(); Long count = jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `attacker_id` = ? AND `attacker_id` != `victim_id` AND `server_id` like ?",
return Map.of("result", result.stream().peek(kif -> kif.setNicknames(nicknameService)).toList(), "count", count, "type", FeedType.KILL.ordinal()); new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id },
new RowMapper<Long>() {
@Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong("c");
}
}).stream().findFirst().orElse(0L);
return Map.of("result", result, "count", count, "type", FeedType.KILL.ordinal());
} }
public Map getDeads(SteamID steamID, String server_id, int offset, int limit) { public Map getDeads(SteamID steamID, String server_id, int offset, int limit) {
List<KillsInFeed> result = entityManager.createNativeQuery("SELECT u.attacker_id, -1, u.assister_id, u.utime, i.name, u.server_id, u.weapon_classname FROM `user_killfeed` as u INNER JOIN `tf2idb`.`tf2idb_item` as i ON u.`weapon_index` = i.`id` WHERE u.`victim_id` = ?1 AND u.`attacker_id` != u.`victim_id` AND u.`server_id` like ?2 ORDER BY u.`id` DESC LIMIT ?3 OFFSET ?4") List<KillsInFeed> result = jdbcTemplate.query("SELECT u.attacker_id, -1, u.assister_id, u.utime, i.name, u.server_id, u.weapon_classname FROM `user_killfeed` as u INNER JOIN `tf2idb`.`tf2idb_item` as i ON u.`weapon_index` = i.`id` WHERE u.`victim_id` = ? AND u.`attacker_id` != u.`victim_id` AND u.`server_id` like ? ORDER BY u.`id` DESC LIMIT ? OFFSET ?",
.setParameter(1, steamID.account_id) new Object[]{steamID.account_id, server_id == null || server_id.isEmpty() ? '%' : server_id, limit, offset},
.setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) new RowMapper<KillsInFeed>() {
.setParameter(3, limit) @Override
.setParameter(4, offset) public KillsInFeed mapRow(ResultSet rs, int rowNum) throws SQLException {
.getResultStream().map(obj -> new KillsInFeed(obj)).toList(); return new KillsInFeed(rs).setNicknames(nicknameService);
Long count = (Long) entityManager.createNativeQuery("SELECT COUNT(*) FROM `user_killfeed` WHERE `victim_id` = ?1 AND `attacker_id` != `victim_id` AND `server_id` like ?2") }
.setParameter(1, steamID.account_id) });
.setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id)
.getSingleResult(); Long count = jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `victim_id` = ? AND `attacker_id` != `victim_id` AND `server_id` like ?",
return Map.of("result", result.stream().peek(kif -> kif.setNicknames(nicknameService)).toList(), "count", count, "type", FeedType.DEAD.ordinal()); new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id },
new RowMapper<Long>() {
@Override
public Long mapRow(ResultSet rs, int numRow) throws SQLException {
return rs.getLong("c");
}
}).stream().findFirst().orElse(0L);
return Map.of("result", result, "count", count, "type", FeedType.DEAD.ordinal());
} }
public Map getAssists(SteamID steamID, String server_id, int offset, int limit) { public Map getAssists(SteamID steamID, String server_id, int offset, int limit) {
List<KillsInFeed> result = entityManager.createNativeQuery("SELECT u.attacker_id, u.victim_id, -1, u.utime, i.name, u.server_id, u.weapon_classname FROM `user_killfeed` as u INNER JOIN `tf2idb`.`tf2idb_item` as i ON u.`weapon_index` = i.`id` WHERE u.`assister_id` = ?1 AND u.`server_id` like ?2 ORDER BY u.`id` DESC LIMIT ?3 OFFSET ?4") List<KillsInFeed> result = jdbcTemplate.query("SELECT u.attacker_id, u.victim_id, -1, u.utime, i.name, u.server_id, u.weapon_classname FROM `user_killfeed` as u INNER JOIN `tf2idb`.`tf2idb_item` as i ON u.`weapon_index` = i.`id` WHERE u.`assister_id` = ? AND u.`server_id` like ? ORDER BY u.`id` DESC LIMIT ? OFFSET ?",
.setParameter(1, steamID.account_id) new Object[]{steamID.account_id, server_id == null || server_id.isEmpty() ? '%' : server_id, limit, offset},
.setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) new RowMapper<KillsInFeed>() {
.setParameter(3, limit) @Override
.setParameter(4, offset) public KillsInFeed mapRow(ResultSet rs, int rowNum) throws SQLException {
.getResultStream().map(obj -> new KillsInFeed(obj)).toList(); return new KillsInFeed(rs).setNicknames(nicknameService);
Long count = (Long) entityManager.createNativeQuery("SELECT COUNT(*) FROM `user_killfeed` WHERE `assister_id` = ?1 AND `server_id` like ?2") }
.setParameter(1, steamID.account_id) });
.setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id)
.getSingleResult(); Long count = jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `assister_id` = ? AND `server_id` like ?",
return Map.of("result", result.stream().peek(kif -> kif.setNicknames(nicknameService)).toList(), "count", count, "type", FeedType.ASSIST.ordinal()); new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id },
new RowMapper<Long>() {
@Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong("c");
}
}).stream().findFirst().orElse(0L);
return Map.of("result", result, "count", count, "type", FeedType.ASSIST.ordinal());
} }
@Data @Data
@ -138,6 +188,12 @@ public class KillfeedService {
this.name = (String) ((Object[]) obj)[1]; this.name = (String) ((Object[]) obj)[1];
this.server_id = (String) ((Object[]) obj)[2]; this.server_id = (String) ((Object[]) obj)[2];
} }
HypeWeapons(ResultSet rs) throws SQLException {
count = rs.getLong(0);
name = rs.getString(1);
server_id = rs.getString(2);
}
} }
enum FeedType { enum FeedType {
@ -156,11 +212,35 @@ public class KillfeedService {
this.server_id = (String) ((Object[]) obj) [2]; this.server_id = (String) ((Object[]) obj) [2];
} }
public void setNicknames(NicknameService nicknameService) { //`attacker_id`, count(*) as c, `server_id`
TopInFeed(ResultSet resultSet) throws SQLException {
uid = resultSet.getInt(0);
count = resultSet.getLong("c");
server_id = resultSet.getString("server_id");
}
public TopInFeed setNicknames(NicknameService nicknameService) {
this.name = uid <= 0 || server_id.isEmpty() || server_id == null ?"":nicknameService.grabNickname(uid, server_id); this.name = uid <= 0 || server_id.isEmpty() || server_id == null ?"":nicknameService.grabNickname(uid, server_id);
return this;
} }
} }
/*
CREATE TABLE `user_killfeed` (
`id` bigint(11) NOT NULL,
`attacker_id` int(11) NOT NULL,
`victim_id` int(11) NOT NULL,
`assister_id` int(11) NOT NULL,
`utime` bigint(20) NOT NULL,
`weapon_name` varchar(128) NOT NULL,
`weapon_id` int(11) NOT NULL,
`weapon_classname` varchar(128) NOT NULL,
`weapon_index` int(11) NOT NULL,
`custom_kill` int(11) NOT NULL,
`crit_type` int(11) NOT NULL,
`server_id` varchar(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
*/
@Data @Data
class KillsInFeed { class KillsInFeed {
int attacker_id; int attacker_id;
@ -183,10 +263,21 @@ public class KillfeedService {
this.weapon_classname = (String) ((Object[]) obj)[6]; this.weapon_classname = (String) ((Object[]) obj)[6];
} }
public void setNicknames(NicknameService nicknameService) { KillsInFeed(ResultSet rs) throws SQLException {
assister_id = rs.getInt(0);
victim_id = rs.getInt(1);
assister_id = rs.getInt(2);
utime = rs.getLong(3);
weapon_name = rs.getString(4);
server_id = rs.getString(5);
weapon_classname = rs.getString(6);
}
public KillsInFeed setNicknames(NicknameService nicknameService) {
this.attacker_name = attacker_id == -1 || server_id.isEmpty() || server_id == null?"":nicknameService.grabNickname(attacker_id, server_id); this.attacker_name = attacker_id == -1 || server_id.isEmpty() || server_id == null?"":nicknameService.grabNickname(attacker_id, server_id);
this.victim_name = victim_id == -1 || server_id.isEmpty() || server_id == null?"":nicknameService.grabNickname(victim_id, server_id); this.victim_name = victim_id == -1 || server_id.isEmpty() || server_id == null?"":nicknameService.grabNickname(victim_id, server_id);
this.assister_name = assister_id == -1 || server_id.isEmpty() || server_id == null?"":nicknameService.grabNickname(assister_id, server_id); this.assister_name = assister_id == -1 || server_id.isEmpty() || server_id == null?"":nicknameService.grabNickname(assister_id, server_id);
return this;
} }
public String getWeapon_name(){ public String getWeapon_name(){

107
src/main/java/app/services/db/MessageService.java

@ -2,67 +2,98 @@ package app.services.db;
import app.entities.Stats; import app.entities.Stats;
import app.entities.other.SteamID; import app.entities.other.SteamID;
import jakarta.persistence.EntityManager;
import lombok.Data; import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@Service @Service
@Transactional("RoTransactionManager")
public class MessageService { public class MessageService {
private EntityManager entityManager; @Autowired
@Qualifier("jt_ro")
private JdbcTemplate jdbcTemplate;
private Stats stats; private Stats stats;
private NicknameService nicknameService; private NicknameService nicknameService;
MessageService(Stats stats, @Qualifier(value = "RoEntityManager") EntityManager entityManager, NicknameService nicknameService) { MessageService(Stats stats, NicknameService nicknameService) {
this.entityManager = entityManager;
this.stats = stats; this.stats = stats;
this.nicknameService = nicknameService; this.nicknameService = nicknameService;
} }
public Map getAllMessages(String server_id, String filter, int offset, int limit) { public Map getAllMessages(String server_id, String filter, int offset, int limit) {
List<Message> result = entityManager.createNativeQuery("SELECT `account_id`,`utime`,`message`,`server_id` FROM `user_messages` WHERE `server_id` like ?1 AND `message` LIKE ?2 ORDER BY `user_messages`.`id` DESC LIMIT ?3 OFFSET ?4") List<Message> result = jdbcTemplate.query("SELECT `account_id`,`utime`,`message`,`server_id` FROM `user_messages` WHERE `server_id` like ? AND `message` LIKE ? ORDER BY `user_messages`.`id` DESC LIMIT ? OFFSET ?",
.setParameter(1, server_id==null||server_id.isEmpty()?"%":server_id) new Object[]{ server_id == null || server_id.isEmpty() ? "%" : server_id, filter == null || filter.isEmpty() ? "%" : "%" + filter + "%", limit, offset},
.setParameter(2, filter==null||filter.isEmpty()?"%":"%" + filter + "%") new RowMapper<Message>() {
.setParameter(3, limit) @Override
.setParameter(4, offset) public Message mapRow(ResultSet rs, int rowNum) throws SQLException {
.getResultStream().map(obj -> new Message(obj)).toList(); return new Message(rs).setAccount_name(nicknameService);
Long count = (Long) entityManager.createNativeQuery("SELECT COUNT(*) FROM `user_messages` WHERE `server_id` like ?1 AND `message` LIKE ?2") }
.setParameter(1, server_id==null||server_id.isEmpty()?"%":server_id) });
.setParameter(2, filter==null||filter.isEmpty()?"%":"%" + filter + "%")
.getSingleResult(); Long count = jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_messages` WHERE `server_id` like ? AND `message` LIKE ?",
return Map.of("result", result.stream().peek(message -> message.setAccount_name(nicknameService)).toList(), "count", count); new Object[]{ server_id==null||server_id.isEmpty()?"%":server_id, filter==null||filter.isEmpty()?"%":"%" + filter + "%" },
new RowMapper<Long>() {
@Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong("c");
}
}).stream().findFirst().orElse(0L);
return Map.of("result", result, "count", count);
} }
public Map getAccountMessages(SteamID steamID, String server_id, String filter, int offset, int limit) { public Map getAccountMessages(SteamID steamID, String server_id, String filter, int offset, int limit) {
List<Message> result = entityManager.createNativeQuery("SELECT `account_id`,`utime`,`message`,`server_id` FROM `user_messages` WHERE `account_id` = ?1 AND `server_id` like ?2 AND `message` LIKE ?3 ORDER BY `user_messages`.`id` DESC LIMIT ?4 OFFSET ?5") List<Message> result = jdbcTemplate.query("SELECT `account_id`,`utime`,`message`,`server_id` FROM `user_messages` WHERE `account_id` = ? AND `server_id` like ? AND `message` LIKE ? ORDER BY `user_messages`.`id` DESC LIMIT ? OFFSET ?",
.setParameter(1, steamID.account_id) new Object[]{steamID.account_id, server_id == null || server_id.isEmpty() ? "%" : server_id, filter == null || filter.isEmpty() ? "%" : "%" + filter + "%", limit, offset},
.setParameter(2, server_id==null||server_id.isEmpty()?"%":server_id) new RowMapper<Message>() {
.setParameter(3, filter==null||filter.isEmpty()?"%":"%" + filter + "%") @Override
.setParameter(4, limit) public Message mapRow(ResultSet rs, int rowNum) throws SQLException {
.setParameter(5, offset) return new Message(rs);
.getResultStream().map(obj -> new Message(obj)).toList(); }
Long count = (Long) entityManager.createNativeQuery("SELECT COUNT(*) FROM `user_messages` WHERE `account_id` = ?1 AND `server_id` like ?2 AND `message` LIKE ?3") });
.setParameter(1, steamID.account_id)
.setParameter(2, server_id==null||server_id.isEmpty()?"%":server_id) Long count = jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_messages` WHERE `account_id` = ? AND `server_id` like ? AND `message` LIKE ?",
.setParameter(3, filter==null||filter.isEmpty()?"%":"%" + filter + "%") new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?"%":server_id, filter==null||filter.isEmpty()?"%":"%" + filter + "%"},
.getSingleResult(); new RowMapper<Long>() {
@Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong("c");
}
}).stream().findFirst().orElse(0L);
return Map.of("result", result, "count", count); return Map.of("result", result, "count", count);
} }
public Long getMessageCount(SteamID steamID, String server_id) { public Long getMessageCount(SteamID steamID, String server_id) {
return (Long) entityManager.createNativeQuery("SELECT COUNT(*) FROM `user_messages` WHERE `account_id` = ?1 AND `server_id` like ?2") return jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_messages` WHERE `account_id` = ? AND `server_id` like ?",
.setParameter(1, steamID.account_id) new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?"%":server_id },
.setParameter(2, server_id==null||server_id.isEmpty()?"%":server_id) new RowMapper<Long>() {
.getSingleResult(); @Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong("c");
}
}).stream().findFirst().orElse(0L);
} }
/*
CREATE TABLE `user_messages` (
`id` int(11) NOT NULL,
`account_id` int(11) NOT NULL,
`utime` bigint(20) NOT NULL,
`message` varchar(512) NOT NULL,
`server_id` varchar(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
*/
@Data @Data
class Message { class Message {
int account_id; int account_id;
@ -77,8 +108,16 @@ public class MessageService {
this.server_id = (String) ((Object[]) obj)[3]; this.server_id = (String) ((Object[]) obj)[3];
} }
public void setAccount_name(NicknameService nicknameService) { Message(ResultSet rs) throws SQLException {
account_id = rs.getInt("account_id");
utime = rs.getLong("utime");
message = rs.getString("message");
server_id = rs.getString("server_id");
}
public Message setAccount_name(NicknameService nicknameService) {
this.account_name = nicknameService.grabNickname(account_id, server_id); this.account_name = nicknameService.grabNickname(account_id, server_id);
return this;
} }
} }
} }

30
src/main/java/app/services/db/NicknameService.java

@ -1,31 +1,30 @@
package app.services.db; package app.services.db;
import app.entities.Stats; import app.entities.Stats;
import app.entities.other.SteamID;
import app.entities.server.Server;
import jakarta.persistence.EntityManager;
import org.apache.commons.math3.util.Pair; import org.apache.commons.math3.util.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant; import java.time.Instant;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
@Service @Service
@Transactional("RoTransactionManager")
public class NicknameService { public class NicknameService {
private EntityManager entityManager; @Autowired
@Qualifier("jt_ro")
private JdbcTemplate jdbcTemplate;
private Stats stats; private Stats stats;
private HashMap<Integer, Pair<String, Long>> nickname_cache = new HashMap<>(); private HashMap<Integer, Pair<String, Long>> nickname_cache = new HashMap<>();
private long refresh_after = 900; private long refresh_after = 900;
NicknameService(Stats stats, @Qualifier(value = "RoEntityManager") EntityManager entityManager) { NicknameService(Stats stats) {
this.entityManager = entityManager;
this.stats = stats; this.stats = stats;
} }
@ -45,8 +44,13 @@ public class NicknameService {
} }
private String grabNicknameFromDb(int account_id, String db) { private String grabNicknameFromDb(int account_id, String db) {
return (String) Optional.of(entityManager.createNativeQuery("SELECT `player_name` FROM `"+db+"`.`user_connections` WHERE `account_id` = ?1 ORDER BY `user_connections`.`id` DESC LIMIT 1;") return jdbcTemplate.query("SELECT `player_name` FROM `"+db+"`.`user_connections` WHERE `account_id` = ? ORDER BY `user_connections`.`id` DESC LIMIT 1;",
.setParameter(1, account_id) new Object[]{ account_id },
.getSingleResult()).orElse("Unknown"); new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int num) throws SQLException {
return rs.getString("player_name");
}
}).stream().findFirst().orElse("Unknown");
} }
} }

5
src/main/java/app/services/db/PermitionService.java

@ -1,18 +1,13 @@
package app.services.db; package app.services.db;
import app.entities.db.AdminInfo; import app.entities.db.AdminInfo;
import app.entities.db.Ban;
import app.entities.db.Permition; import app.entities.db.Permition;
import app.entities.other.SteamID; import app.entities.other.SteamID;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;

120
src/main/java/app/services/db/UsertimeService.java

@ -5,31 +5,31 @@ import app.entities.other.SteamID;
import app.entities.server.Server; import app.entities.server.Server;
import app.entities.Stats; import app.entities.Stats;
import app.utils.SteamIDConverter; import app.utils.SteamIDConverter;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Service @Service
@Transactional("RoTransactionManager")
public class UsertimeService { public class UsertimeService {
EntityManager entityManager; @Autowired
@Qualifier("jt_ro")
private JdbcTemplate jdbcTemplate;
//Лучше это всегда держать в true //Лучше это всегда держать в true
boolean last_map = true; private boolean last_map = true;
Stats stats; private Stats stats;
@Autowired @Autowired
public UsertimeService(Stats stats, @Qualifier(value = "RoEntityManager") EntityManager entityManager) { public UsertimeService(Stats stats) {
this.entityManager = entityManager;
this.stats = stats; this.stats = stats;
} }
@ -39,9 +39,9 @@ public class UsertimeService {
for (Map.Entry<String, Server> stringServerEntry : stats.getServers().entrySet()) { for (Map.Entry<String, Server> stringServerEntry : stats.getServers().entrySet()) {
if(last_map) { if(last_map) {
maps = getMap(stringServerEntry.getValue().getDb(), stringServerEntry.getValue().getGrab_maps_limit()).orElse(List.of()); maps = getMap(stringServerEntry.getValue().getDb(), stringServerEntry.getValue().getGrab_maps_limit());
} else { } else {
maps = getMaps(stringServerEntry.getValue().getDb()).orElse(List.of()); maps = getMaps(stringServerEntry.getValue().getDb());
} }
if(maps.size() == 0) {continue;} if(maps.size() == 0) {continue;}
@ -65,9 +65,9 @@ public class UsertimeService {
for (Map.Entry<String, Server> stringServerEntry : stats.getServers().entrySet()) { for (Map.Entry<String, Server> stringServerEntry : stats.getServers().entrySet()) {
if(last_map) { if(last_map) {
maps = getMap(stringServerEntry.getValue().getDb(), stringServerEntry.getValue().getGrab_maps_limit()).orElse(List.of()); maps = getMap(stringServerEntry.getValue().getDb(), stringServerEntry.getValue().getGrab_maps_limit());
} else { } else {
maps = getMaps(stringServerEntry.getValue().getDb()).orElse(List.of()); maps = getMaps(stringServerEntry.getValue().getDb());
} }
if(maps.size() == 0) {continue;} if(maps.size() == 0) {continue;}
@ -86,43 +86,59 @@ public class UsertimeService {
} }
public Timestamp getLastplay(String db, SteamID steamID, String map) { public Timestamp getLastplay(String db, SteamID steamID, String map) {
List<Timestamp> response = entityManager.createNativeQuery("select timestamp from `"+db+"`.`user_connections` WHERE map LIKE ?3 and connection_type LIKE ?1 AND account_id = ?2 ORDER BY `user_connections`.`id` DESC LIMIT 1") return jdbcTemplate.query("select timestamp from `"+db+"`.`user_connections` WHERE map LIKE ? and connection_type LIKE ? AND account_id = ? ORDER BY `user_connections`.`id` DESC LIMIT 1",
//.setParameter(1, db) new Object[]{ map, "disconnect", steamID.account_id},
.setParameter(1,"disconnect") new RowMapper<Timestamp>() {
.setParameter(2, steamID.account_id) @Override
.setParameter(3, map) public Timestamp mapRow(ResultSet rs, int rowNum) throws SQLException {
.getResultList(); return rs.getTimestamp("timestamp");
return response.size() > 0 ? response.get(0) : null; }
}).stream().findFirst().orElse(null);
} }
public BigDecimal getTotalPlaytime(String db, SteamID steamID, String map) { public BigDecimal getTotalPlaytime(String db, SteamID steamID, String map) {
List<BigDecimal> response = entityManager.createNativeQuery("select sum(connect_duration) total from `"+db+"`.`user_connections` WHERE map LIKE ?1 and connection_type LIKE ?2 AND account_id = ?3") return jdbcTemplate.query("select sum(connect_duration) as total from `"+db+"`.`user_connections` WHERE map LIKE ? and connection_type LIKE ? AND account_id = ?",
//.setParameter(1, db) new Object[]{ map, "disconnect", steamID.account_id },
.setParameter(1, map) new RowMapper<BigDecimal>(){
.setParameter(2, "disconnect") @Override
.setParameter(3, steamID.account_id) public BigDecimal mapRow(ResultSet rs, int rowNum) throws SQLException {
.getResultList(); return rs.getBigDecimal("total");
return response.size() > 0 ? response.get(0) : null; }
}).stream().findFirst().orElse(null);
} }
public Optional<List> getMap(String db, int limit) { public List<String> getMap(String db, int limit) {
return Optional.ofNullable(entityManager.createNativeQuery("select distinct `map` from `"+db+"`.`user_connections` WHERE 1 ORDER BY `user_connections`.`id` DESC LIMIT ?1") return jdbcTemplate.query("select distinct `map` from `"+db+"`.`user_connections` WHERE 1 ORDER BY `user_connections`.`id` DESC LIMIT ?",
.setParameter(1, limit) new Object[]{ limit },
.getResultList()); new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString("map");
}
});
} }
public Optional<List> getMaps(String db) { public List<String> getMaps(String db) {
return Optional.ofNullable(entityManager.createNativeQuery("select distinct `map` from `"+db+"`.`user_connections`") return jdbcTemplate.query("select distinct `map` from `"+db+"`.`user_connections`",
//.setParameter(1, db) new RowMapper<String>() {
.getResultList()); @Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString("map");
}
});
} }
public SteamID getSteamOnUsername(String username) { public SteamID getSteamOnUsername(String username) {
SteamID steamID; SteamID steamID;
for (Map.Entry<String, Server> stringServerEntry : stats.getServers().entrySet()) { for (Map.Entry<String, Server> stringServerEntry : stats.getServers().entrySet()) {
steamID = (SteamID) entityManager.createNativeQuery("SELECT account_id FROM `"+stringServerEntry.getValue().getDb()+"`.`user_connections` WHERE player_name LIKE ?1 ORDER BY `id` DESC LIMIT 1") steamID = jdbcTemplate.query("SELECT account_id FROM `"+stringServerEntry.getValue().getDb()+"`.`user_connections` WHERE player_name LIKE ? ORDER BY `id` DESC LIMIT 1",
.setParameter(1, username) new Object[]{ username },
.getResultStream().map(x -> SteamIDConverter.getSteamID("[U:1:%d]".formatted(x))).findFirst().orElse(null); new RowMapper<SteamID>() {
@Override
public SteamID mapRow(ResultSet rs, int rowNum) throws SQLException {
return SteamIDConverter.getSteamID("[U:1:%d]".formatted(rs.getInt("account_id")));
}
}).stream().findFirst().orElse(null);
if (steamID != null) return steamID; if (steamID != null) return steamID;
} }
return null; return null;
@ -131,21 +147,27 @@ public class UsertimeService {
public List<Gametime> getGametimeOnServer(SteamID steamID, String server, Integer limit, Integer offset) { public List<Gametime> getGametimeOnServer(SteamID steamID, String server, Integer limit, Integer offset) {
String db = stats.getServers().entrySet().stream().filter(s -> s.getKey().equals(server)).map(s -> s.getValue().getDb()).findFirst().orElse(null); String db = stats.getServers().entrySet().stream().filter(s -> s.getKey().equals(server)).map(s -> s.getValue().getDb()).findFirst().orElse(null);
if (db == null) return new ArrayList<>(); if (db == null) return new ArrayList<>();
return (List<Gametime>) entityManager.createNativeQuery("SELECT * FROM `"+db+"`.`user_connections` WHERE account_id = ?1 AND connection_type LIKE ?2 ORDER BY `"+db+"`.`user_connections`.`id` DESC LIMIT ?3 OFFSET ?4")
.setParameter(1, steamID.account_id)
.setParameter(2, "disconnect")
.setParameter(3, limit)
.setParameter(4, offset)
.getResultStream().map(obj -> new Gametime((Object[]) obj)).collect(Collectors.toList());
return jdbcTemplate.query("SELECT * FROM `" + db + "`.`user_connections` WHERE account_id = ? AND connection_type LIKE ? ORDER BY `" + db + "`.`user_connections`.`id` DESC LIMIT ? OFFSET ?",
new Object[]{steamID.account_id, "disconnect", limit, offset},
new RowMapper<Gametime>() {
@Override
public Gametime mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Gametime(rs);
}
});
} }
public Long getTotalGametimeOnServer(SteamID steamID, String server) { public Long getTotalGametimeOnServer(SteamID steamID, String server) {
String db = stats.getServers().entrySet().stream().filter(s -> s.getKey().equals(server)).map(s -> s.getValue().getDb()).findFirst().orElse(null); String db = stats.getServers().entrySet().stream().filter(s -> s.getKey().equals(server)).map(s -> s.getValue().getDb()).findFirst().orElse(null);
if (db == null) return 0L; if (db == null) return 0L;
return (Long) entityManager.createNativeQuery("SELECT count(id) FROM `"+db+"`.`user_connections` WHERE account_id = ?1 AND connection_type LIKE ?2") return jdbcTemplate.query("SELECT count(id) as c FROM `"+db+"`.`user_connections` WHERE account_id = ?1 AND connection_type LIKE ?2",
.setParameter(1, steamID.account_id) new Object[]{ steamID.account_id, "disconnect" },
.setParameter(2, "disconnect") new RowMapper<Long>() {
.getSingleResult(); @Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong("с");
}
}).stream().findFirst().orElse(0L);
} }
} }

71
src/main/java/app/services/db/VIPService.java

@ -5,24 +5,27 @@ import app.entities.db.Permition;
import app.entities.other.SteamID; import app.entities.other.SteamID;
import app.services.ServerService; import app.services.ServerService;
import app.utils.SteamIDConverter; import app.utils.SteamIDConverter;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@Service @Service
@Transactional("RwTransactionManager")
public class VIPService { public class VIPService {
EntityManager entityManager;
@Autowired
@Qualifier("jt_rw")
private JdbcTemplate jdbcTemplate;
RestTemplate restTemplate; RestTemplate restTemplate;
@ -35,42 +38,50 @@ public class VIPService {
@Autowired @Autowired
public VIPService(PermitionService permitionService, public VIPService(PermitionService permitionService,
ServerService serverService, ServerService serverService,
DonateService donateService, DonateService donateService) {
@Qualifier(value = "RwEntityManager") EntityManager entityManager) {
this.restTemplate = new RestTemplate(); this.restTemplate = new RestTemplate();
this.permitionService = permitionService; this.permitionService = permitionService;
this.serverService = serverService; this.serverService = serverService;
this.donateService = donateService; this.donateService = donateService;
this.entityManager = entityManager;
} }
// Список ид из дискорда кто имеет платную випку // Список ид из дискорда кто имеет платную випку
public List<Long> getUsersDiscordWithActiveVIP() { public List<Long> getUsersDiscordWithActiveVIP() {
return entityManager.createNativeQuery("SELECT `discord_id` FROM `sm_admins` INNER JOIN `steam2discord` ON `sm_admins`.`status` LIKE ?1 AND (`sm_admins`.`comment` LIKE ?2 OR `sm_admins`.`comment` LIKE ?3) AND `sm_admins`.`identity` = `steam2discord`.`steam_id`") return jdbcTemplate.query("SELECT `discord_id` FROM `sm_admins` INNER JOIN `steam2discord` ON `sm_admins`.`status` LIKE ? AND (`sm_admins`.`comment` LIKE ? OR `sm_admins`.`comment` LIKE ?) AND `sm_admins`.`identity` = `steam2discord`.`steam_id`",
.setParameter(1, "VIP") new Object[]{"VIP", "Donate.User", "f13bot.User"},
.setParameter(2, "Donate.User") new RowMapper<Long>() {
.setParameter(3, "f13bot.User") @Override
.getResultList(); public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong("discord_id");
}
});
} }
// Список ид из дискорда кто имеет бесплатную випку // Список ид из дискорда кто имеет бесплатную випку
public List<Long> getUsersDiscordWithActiveFreeVIP() { public List<Long> getUsersDiscordWithActiveFreeVIP() {
return entityManager.createNativeQuery("SELECT `discord_id` FROM `sm_admins` INNER JOIN `steam2discord` ON `sm_admins`.`status` LIKE ?1 AND `sm_admins`.`comment` LIKE ?2 AND `sm_admins`.`identity` = `steam2discord`.`steam_id`") return jdbcTemplate.query("SELECT `discord_id` FROM `sm_admins` INNER JOIN `steam2discord` ON `sm_admins`.`status` LIKE ? AND `sm_admins`.`comment` LIKE ? AND `sm_admins`.`identity` = `steam2discord`.`steam_id`",
.setParameter(1, "VIP") new Object[]{"VIP", "f13bot.FreeVIP"},
.setParameter(2, "f13bot.FreeVIP") new RowMapper<Long>() {
.getResultList(); @Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong("discord_id");
}
});
} }
// Транзакция, проверка и удаление випок подшедших к концу // Транзакция, проверка и удаление випок подшедших к концу
@Transactional("RwTransactionManager")
public int removeEndedVIPs() { public int removeEndedVIPs() {
List<SteamID> steamid2remove = entityManager.createNativeQuery("SELECT `identity` FROM `sm_admins` WHERE NOT UNIX_TIMESTAMP(`reg_date`) LIKE 0 AND `amount` NOT LIKE 0 AND `status` LIKE ?1 AND ((unix_timestamp(now()) - UNIX_TIMESTAMP(`reg_date`)) > `amount`)") List<SteamID> steamid2remove = jdbcTemplate.query("SELECT `identity` FROM `sm_admins` WHERE NOT UNIX_TIMESTAMP(`reg_date`) LIKE 0 AND `amount` NOT LIKE 0 AND `status` LIKE ? AND ((unix_timestamp(now()) - UNIX_TIMESTAMP(`reg_date`)) > `amount`)",
.setParameter(1, "VIP") new Object[]{"VIP"},
.getResultStream().map(identity -> SteamIDConverter.getSteamID((String) identity)).toList(); new RowMapper<SteamID>() {
@Override
int removed_vips = entityManager.createNativeQuery("DELETE FROM `sm_admins` WHERE NOT UNIX_TIMESTAMP(`reg_date`) LIKE 0 AND `amount` NOT LIKE 0 AND `status` LIKE ?1 AND ((unix_timestamp(now()) - UNIX_TIMESTAMP(`reg_date`)) > `amount`)") public SteamID mapRow(ResultSet rs, int rowNum) throws SQLException {
.setParameter(1, "VIP") return SteamIDConverter.getSteamID(rs.getString("identity"));
.executeUpdate(); }
});
int removed_vips = jdbcTemplate.update("DELETE FROM `sm_admins` WHERE NOT UNIX_TIMESTAMP(`reg_date`) LIKE 0 AND `amount` NOT LIKE 0 AND `status` LIKE ? AND ((unix_timestamp(now()) - UNIX_TIMESTAMP(`reg_date`)) > `amount`)",
"VIP");
steamid2remove.forEach(steamid -> { steamid2remove.forEach(steamid -> {
regesterGiveVIP(steamid, -1, VipGiveMethod.AFTERTIME, "check service", false); regesterGiveVIP(steamid, -1, VipGiveMethod.AFTERTIME, "check service", false);
@ -80,15 +91,9 @@ public class VIPService {
} }
// Транзакция, добавление статистики // Транзакция, добавление статистики
@Transactional("RwTransactionManager")
public int regesterGiveVIP(SteamID steamID, int amount, VipGiveMethod vipGiveMethod, String extra, boolean extend) { public int regesterGiveVIP(SteamID steamID, int amount, VipGiveMethod vipGiveMethod, String extra, boolean extend) {
return entityManager.createNativeQuery("INSERT INTO `gived_vip` (`id`, `steam2`, `amount`, `timestamp`, `givemethod`, `reserved`, `extend`) VALUES (NULL, ?1, ?2, current_timestamp(), ?3, ?4, ?5)") return jdbcTemplate.update("INSERT INTO `gived_vip` (`id`, `steam2`, `amount`, `timestamp`, `givemethod`, `reserved`, `extend`) VALUES (NULL, ?, ?, current_timestamp(), ?, ?, ?)",
.setParameter(1, steamID.steam2) steamID.steam2, amount, vipGiveMethod.ordinal(), extra, extend);
.setParameter(2, amount)
.setParameter(3, vipGiveMethod.ordinal())
.setParameter(4, extra)
.setParameter(5, extend)
.executeUpdate();
} }
// Проверка наличия прав для дочерних сервисов // Проверка наличия прав для дочерних сервисов

Loading…
Cancel
Save