diff --git a/src/main/java/app/configurations/DbRwConfigurarion.java b/src/main/java/app/configurations/DbRwConfigurarion.java index 650e6d3..c7abc1e 100644 --- a/src/main/java/app/configurations/DbRwConfigurarion.java +++ b/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.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @@ -68,6 +69,7 @@ public class DbRwConfigurarion implements DbConfiguration{ @Bean(name = "jt_rw") @Scope(value = "prototype") + @Primary public JdbcTemplate getJT() { return new JdbcTemplate(DataSource()); } diff --git a/src/main/java/app/entities/DonateStatistic.java b/src/main/java/app/entities/DonateStatistic.java index 334b3e6..91d97ff 100644 --- a/src/main/java/app/entities/DonateStatistic.java +++ b/src/main/java/app/entities/DonateStatistic.java @@ -2,20 +2,41 @@ package app.entities; 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 public class DonateStatistic { VipGiveMethod giveMethod; - Integer count; + Long count; String reserved; Integer amount; //sub public DonateStatistic(Object[] raw) { giveMethod = VipGiveMethod.values()[(int) raw[0]]; - count = ((Long) raw[1]).intValue(); + count = ((Long) raw[1]); reserved = raw[2]==null?"": (String) raw[2]; 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) { this((Object[]) o); } diff --git a/src/main/java/app/entities/db/DonateStat.java b/src/main/java/app/entities/db/DonateStat.java index 6214e47..bb5e293 100644 --- a/src/main/java/app/entities/db/DonateStat.java +++ b/src/main/java/app/entities/db/DonateStat.java @@ -1,13 +1,24 @@ package app.entities.db; -import app.entities.DonateStatistic; import app.entities.VipGiveMethod; -import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonValue; 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 public class DonateStat { @@ -34,6 +45,16 @@ public class DonateStat { 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) { //потом бля } diff --git a/src/main/java/app/entities/db/Gametime.java b/src/main/java/app/entities/db/Gametime.java index 327097f..f820561 100644 --- a/src/main/java/app/entities/db/Gametime.java +++ b/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 lombok.Data; +import java.sql.ResultSet; +import java.sql.SQLException; 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 public class Gametime { @@ -40,6 +56,19 @@ public class Gametime { 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 public String getMap() { return map.replace("workshop/","").split(".ugc", 2)[0]; diff --git a/src/main/java/app/entities/db/freevip/FreeVIP.java b/src/main/java/app/entities/db/freevip/FreeVIP.java index b6b164a..9322c0f 100644 --- a/src/main/java/app/entities/db/freevip/FreeVIP.java +++ b/src/main/java/app/entities/db/freevip/FreeVIP.java @@ -3,8 +3,19 @@ package app.entities.db.freevip; import app.entities.SocialAuth; import lombok.Data; +import java.sql.ResultSet; +import java.sql.SQLException; 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 public class FreeVIP extends SocialAuth { int id; @@ -18,4 +29,12 @@ public class FreeVIP extends SocialAuth { discord_id = (long) obj[3]; 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"); + } } diff --git a/src/main/java/app/services/db/BanService.java b/src/main/java/app/services/db/BanService.java index 4b99d60..16147a2 100644 --- a/src/main/java/app/services/db/BanService.java +++ b/src/main/java/app/services/db/BanService.java @@ -5,13 +5,11 @@ import app.entities.db.Ban; import app.entities.other.SteamID; import app.services.ServerService; import app.utils.CryptedCookie; -import jakarta.persistence.EntityManager; 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.transaction.annotation.Transactional; import java.sql.ResultSet; import java.sql.SQLException; diff --git a/src/main/java/app/services/db/CollectStatisticService.java b/src/main/java/app/services/db/CollectStatisticService.java index 584d09f..fa1272c 100644 --- a/src/main/java/app/services/db/CollectStatisticService.java +++ b/src/main/java/app/services/db/CollectStatisticService.java @@ -2,33 +2,23 @@ package app.services.db; import app.entities.db.CollectableStatistic; import app.updates.BaseUpdater; -import jakarta.annotation.PostConstruct; -import jakarta.persistence.EntityManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.jdbc.core.JdbcTemplate; 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 -@Transactional("RwTransactionManager") public class CollectStatisticService extends BaseUpdater { - private EntityManager entityManager; + @Autowired + @Qualifier("jt_rw") + private JdbcTemplate jdbcTemplate; 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) { if (collectableStatistic.isServerRequest()) return; if (collectableStatistic.isIgnoreRule()) return; @@ -36,14 +26,10 @@ public class CollectStatisticService extends BaseUpdater { if (!collectableStatistic.isStatsRequests()) logger.info(collectableStatistic.toString()); - entityManager.createNativeQuery("INSERT INTO `web_statistic` (`steam64`, `client_ip`, `method`, `path`, `query`, `useragent`) VALUES (?1, ?2, ?3, ?4, ?5, ?6)") - .setParameter(1, collectableStatistic.getSteam64()) - .setParameter(2, collectableStatistic.getClient_ip()) - .setParameter(3, collectableStatistic.getMethod()) - .setParameter(4, collectableStatistic.getPath()) - .setParameter(5, collectableStatistic.getQuery()) - .setParameter(6, collectableStatistic.getUseragent()) - .executeUpdate(); + jdbcTemplate.update("INSERT INTO `web_statistic` (`steam64`, `client_ip`, `method`, `path`, `query`, `useragent`) VALUES (?, ?, ?, ?, ?, ?)", + collectableStatistic.getSteam64(), collectableStatistic.getClient_ip(), + collectableStatistic.getMethod(), collectableStatistic.getPath(), + collectableStatistic.getQuery(), collectableStatistic.getUseragent()); } catch (Exception err) { logger.error("Ignoring add stats"); } diff --git a/src/main/java/app/services/db/DBService.java b/src/main/java/app/services/db/DBService.java index 92b9e13..4d9a4f2 100644 --- a/src/main/java/app/services/db/DBService.java +++ b/src/main/java/app/services/db/DBService.java @@ -1,7 +1,5 @@ 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.Qualifier; import org.springframework.jdbc.core.JdbcTemplate; diff --git a/src/main/java/app/services/db/DetectService.java b/src/main/java/app/services/db/DetectService.java index 6320751..9c621b8 100644 --- a/src/main/java/app/services/db/DetectService.java +++ b/src/main/java/app/services/db/DetectService.java @@ -4,44 +4,50 @@ import app.entities.Stats; import app.entities.other.SteamID; import app.entities.server.Server; import app.utils.SteamIDConverter; -import jakarta.persistence.EntityManager; 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.transaction.annotation.Transactional; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; -import java.util.stream.Collectors; @Service public class DetectService { - EntityManager entityManager_ro; - EntityManager entityManager_rw; + @Autowired + @Qualifier("jt_rw") + private JdbcTemplate jdbcTemplate_rw; + + @Autowired + @Qualifier("jt_ro") + private JdbcTemplate jdbcTemplate_ro; private Stats stats; @Autowired public DetectService( - Stats stats, - @Qualifier(value = "RoEntityManager") EntityManager entityManager_ro, - @Qualifier(value = "RwEntityManager") EntityManager entityManager_rw) { - this.entityManager_ro = entityManager_ro; - this.entityManager_rw = entityManager_rw; + Stats stats) { this.stats = stats; } - @Transactional("RoTransactionManager") public List getAccountsPerSteamID(SteamID steamID) { List founded_steamid = new ArrayList<>(); for (Map.Entry 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`") - .setParameter(1, steamID.steam2) - .getResultStream().map(String::valueOf).toList()); + 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`", + new Object[]{steamID.steam2}, + new RowMapper() { + @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`; return founded_steamid.stream().distinct().map(SteamIDConverter::getSteamID).filter(Objects::nonNull).toList(); @@ -60,15 +66,21 @@ public class DetectService { 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()) { - case 0:return entityManager_ro.createNativeQuery(sql) - .setParameter(1, steamID.steam2) - .getResultStream().map(String::valueOf).toList(); - case 1:return entityManager_rw.createNativeQuery(sql) - .setParameter(1, steamID.steam2) - .getResultStream().map(String::valueOf).toList(); + case 0:return jdbcTemplate_ro.query(sql, new Object[]{steamID.steam2}, new RowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getString("steam_id"); + } + }); + case 1:return jdbcTemplate_rw.query(sql, new Object[]{steamID.steam2}, new RowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getString("steam_id"); + } + }); default: return new ArrayList<>(); } }); @@ -76,18 +88,22 @@ public class DetectService { List founded_steamid = new ArrayList<>(); 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) { //pass } return founded_steamid.stream().distinct().map(SteamIDConverter::getSteamID).filter(Objects::nonNull).toList(); } - @Transactional("RoTransactionManager") - public List getAttachedDiscordAccountPerSteam(SteamID steamID) { - return entityManager_ro.createNativeQuery("SELECT `discord_id`, UNIX_TIMESTAMP(`timestamp`) as utime, `active` FROM `steam2discord` WHERE `steam_id` LIKE ?1 GROUP BY `discord_id`") - .setParameter(1, steamID.steam2) - .getResultStream().map(d -> Map.of("discord_id", ((Object[]) d)[0], "utime", ((Object[]) d)[1], "active", ((Object[]) d)[2])).toList(); + 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`", + new Object[]{ steamID.steam2 }, + new RowMapper>() { + @Override + public Map 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'; } diff --git a/src/main/java/app/services/db/DiscordAuthService.java b/src/main/java/app/services/db/DiscordAuthService.java index f31e311..13d9efc 100644 --- a/src/main/java/app/services/db/DiscordAuthService.java +++ b/src/main/java/app/services/db/DiscordAuthService.java @@ -2,68 +2,66 @@ package app.services.db; import app.entities.other.SteamID; 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.Qualifier; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; 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.HashMap; import java.util.List; -import java.util.Map; @Service -@Transactional("RwTransactionManager") public class DiscordAuthService { - EntityManager entityManager; - @Autowired - public DiscordAuthService(@Qualifier(value = "RwEntityManager") EntityManager entityManager) { - this.entityManager = entityManager; - } + JdbcTemplate jdbcTemplate; private HashMap> processing_accounts = new HashMap<>(); public SteamID getSteamIDofDiscordID(String discord_id) { - return (SteamID) entityManager.createNativeQuery("SELECT steam_id FROM steam2discord WHERE discord_id = ?1 AND active = 1 LIMIT 1") - .setParameter(1, discord_id) - .getResultStream() - .map(obj -> SteamIDConverter.getSteamID((String) obj)) - .findFirst() - .orElse(null); + return jdbcTemplate.query("SELECT steam_id FROM steam2discord WHERE discord_id = ? AND active = 1 LIMIT 1", + new Object[]{ discord_id }, + new RowMapper() { + @Override + public SteamID mapRow(ResultSet rs, int numRow) throws SQLException { + return SteamIDConverter.getSteamID(rs.getString("steam_id")); + } + }).stream().findFirst().orElse(null); } public String getDiscordIDofSteamID(SteamID steamID) { - return (String) entityManager.createNativeQuery("SELECT discord_id FROM steam2discord WHERE steam_id = ?1 AND active = 1 LIMIT 1") - .setParameter(1, steamID.steam2) - .getResultStream() - .map(String::valueOf) - .findFirst() - .orElse(null); + return jdbcTemplate.query("SELECT discord_id FROM steam2discord WHERE steam_id = ?1 AND active = 1 LIMIT 1", + new Object[]{ steamID.steam2 }, + new RowMapper() { + @Override + public String mapRow(ResultSet rs, int numRow) throws SQLException { + return rs.getString("discord_id"); + } + }).stream().findFirst().orElse(null); } - @Transactional("RwTransactionManager") 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')") - .setParameter(1, steamID.steam2) - .setParameter(2, discord_id) - .executeUpdate() > 0; + return jdbcTemplate.update("INSERT INTO `steam2discord` (`id`, `steam_id`, `discord_id`, `timestamp`, `active`) VALUES (NULL, ?, ?, current_timestamp(), '1')", + steamID.steam2, discord_id) > 0; } - @Transactional("RwTransactionManager") public boolean removeSteamIDofDiscordID(SteamID steamID) { - return entityManager.createNativeQuery("UPDATE `steam2discord` SET `active` = '0' WHERE `steam_id` LIKE ?1") - .setParameter(1, steamID.steam2) - .executeUpdate() > 0; + return jdbcTemplate.update("UPDATE `steam2discord` SET `active` = '0' WHERE `steam_id` LIKE ?", + steamID.steam2) > 0; } public List getAccountsNotInList(List discord_accounts) { - return entityManager.createNativeQuery("SELECT `discord_id` FROM `steam2discord` WHERE `active` = 1 AND `discord_id` in ?1") - .setParameter(1, discord_accounts) - .getResultStream().map(String::valueOf).toList(); + return jdbcTemplate.query("SELECT `discord_id` FROM `steam2discord` WHERE `active` = 1 AND `discord_id` in ?", + new Object[]{ discord_accounts }, + new RowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getString("discord_id"); + } + }); } public HashMap> getProcessing_accounts() { diff --git a/src/main/java/app/services/db/DonateService.java b/src/main/java/app/services/db/DonateService.java index e7ae6bf..f48d241 100644 --- a/src/main/java/app/services/db/DonateService.java +++ b/src/main/java/app/services/db/DonateService.java @@ -7,76 +7,86 @@ import app.entities.VipGiveMethod; import app.entities.db.DonateStat; import app.entities.other.SteamID; import jakarta.annotation.PostConstruct; -import jakarta.persistence.EntityManager; -import jakarta.persistence.PersistenceContext; import org.apache.commons.lang3.tuple.Pair; import org.springframework.beans.factory.annotation.Autowired; 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.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.List; import java.util.Map; import java.util.Optional; @Component -@Transactional("RoTransactionManager") public class DonateService { - EntityManager entityManager; + @Autowired + @Qualifier("jt_ro") + private JdbcTemplate jdbcTemplate; - Stats stats; + private Stats stats; @Autowired - public DonateService(Stats stats, @Qualifier(value = "RoEntityManager") EntityManager entityManager) { - this.entityManager = entityManager; + public DonateService(Stats stats) { this.stats = stats; } //KEY, METAL public Pair getSummarySteamDonateValue(StatisticRange statisticRange) { - List steam = entityManager.createNativeQuery( - "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 " + - "FROM `gived_vip` WHERE `givemethod` = ?1 AND `timestamp` > CAST(DATE_FORMAT(NOW() ,?2) as DATE)") - .setParameter(1, VipGiveMethod.STEAM.ordinal()) - .setParameter(2, StatisticRange.cast(statisticRange)) - .getResultList(); - int metal = 0, key = 0; - if(!steam.isEmpty()) { - metal = steam.get(0)==null||steam.get(0)[0]==null?0: Integer.parseInt(steam.get(0)[0].toString()); - key = steam.get(0)==null||steam.get(0)[1]==null?0: Integer.parseInt(steam.get(0)[1].toString()); - } - return Pair.of(key, metal); + return jdbcTemplate.query("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 " + + "FROM `gived_vip` WHERE `givemethod` = ? AND `timestamp` > CAST(DATE_FORMAT(NOW() ,?) as DATE)", + new Object[]{VipGiveMethod.STEAM.ordinal(), StatisticRange.cast(statisticRange)}, + new RowMapper>() { + @Override + public Pair mapRow(ResultSet rs, int numRow) throws SQLException { + return Pair.of( + Optional.of(rs.getInt("k")).orElse(0), + Optional.of(rs.getInt("r")).orElse(0) + ); + } + }).stream().findFirst().orElse(Pair.of(0,0)); } public Integer getSummaryQiwiDonateValue(StatisticRange statisticRange) { - List qiwi = entityManager.createNativeQuery( - "SELECT SUM(CAST(REPLACE(REPLACE(substring_index(`reserved`,';',1), 'rub=',''), ';','') as INT)) as k " + - "FROM `gived_vip` WHERE `givemethod` = ?1 AND `timestamp` > CAST(DATE_FORMAT(NOW() ,?2) as DATE)") - .setParameter(1, VipGiveMethod.QIWI.ordinal()) - .setParameter(2, StatisticRange.cast(statisticRange)) - .getResultList(); - return qiwi.get(0)==null?0: Integer.parseInt(qiwi.get(0).toString()); + return jdbcTemplate.query("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)", + new Object[]{ VipGiveMethod.QIWI.ordinal(), StatisticRange.cast(statisticRange)}, + new RowMapper() { + @Override + public Integer mapRow(ResultSet rs, int numRow) throws SQLException { + return rs.getInt("k"); + } + }).stream().findFirst().orElse(0); } //no need if use getGivedVipStatistic - public Integer 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)") - .setParameter(1, VipGiveMethod.FREE.ordinal()) - .setParameter(2, StatisticRange.cast(statisticRange)) - .getSingleResult(); - return count.intValue(); + public Long getSummaryGivedFreeVip(StatisticRange statisticRange) { + return jdbcTemplate.query("SELECT COUNT(*) as count FROM `gived_vip` WHERE `givemethod` = ? AND `timestamp` > CAST(DATE_FORMAT(NOW() ,?) as DATE)", + new Object[]{ VipGiveMethod.FREE.ordinal(), StatisticRange.cast(statisticRange) }, + new RowMapper() { + @Override + public Long mapRow(ResultSet rs, int numRow) throws SQLException { + return rs.getLong("count"); + } + }).stream().findFirst().orElse(0L); } public HashMap getGivedVipStatistic(StatisticRange statisticRange) { - List 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`") - .setParameter(1, StatisticRange.cast(statisticRange)) - .getResultList(); - List donateStatistics = raw_donateStatistics.stream().map(DonateStatistic::new).toList(); + List 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`", + new Object[]{StatisticRange.cast(statisticRange)}, + new RowMapper() { + @Override + public DonateStatistic mapRow(ResultSet rs, int rowNum) throws SQLException { + return new DonateStatistic(rs); + } + }); HashMap map = new HashMap<>(); map.put("steam", new HashMap<>()); @@ -106,9 +116,14 @@ public class DonateService { } public List getDonateStatistic(SteamID steamID) { - return entityManager.createNativeQuery("SELECT *, UNIX_TIMESTAMP(`timestamp`) as utime FROM `gived_vip` WHERE `steam2` LIKE ?1") - .setParameter(1, steamID.steam2) - .getResultStream().map(obj -> new DonateStat((Object[]) obj)).toList(); + return jdbcTemplate.query("SELECT *, UNIX_TIMESTAMP(`timestamp`) as utime FROM `gived_vip` WHERE `steam2` LIKE ?", + new Object[]{steamID.steam2}, + new RowMapper() { + @Override + public DonateStat mapRow(ResultSet rs, int rowNum) throws SQLException { + return new DonateStat(rs); + } + }); } public HashMap getDonateStatistic(StatisticRange statisticRange) { diff --git a/src/main/java/app/services/db/FreeVIPService.java b/src/main/java/app/services/db/FreeVIPService.java index ad1d7f2..7496482 100644 --- a/src/main/java/app/services/db/FreeVIPService.java +++ b/src/main/java/app/services/db/FreeVIPService.java @@ -4,55 +4,65 @@ import app.entities.SocialAuth; import app.entities.VipGiveMethod; import app.entities.db.freevip.FreeVIP; 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.Qualifier; -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.transaction.annotation.Transactional; -import org.springframework.web.client.RestTemplate; import java.math.BigDecimal; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; @Service -@Transactional("RwTransactionManager") public class FreeVIPService{ - EntityManager entityManager; + @Autowired + private JdbcTemplate jdbcTemplate; - UsertimeService usertimeService; + private UsertimeService usertimeService; - VIPService vipService; + private VIPService vipService; @Autowired public FreeVIPService(UsertimeService usertimeService, - VIPService vipService, - @Qualifier(value = "RwEntityManager") EntityManager entityManager) { - this.entityManager = entityManager; + VIPService vipService) { this.usertimeService = usertimeService; this.vipService = vipService; } public Long getDBServerUTime() { - return (Long) entityManager.createNativeQuery("SELECT UNIX_TIMESTAMP(NOW())") - .getSingleResult(); + return jdbcTemplate.query("SELECT UNIX_TIMESTAMP(NOW()) as c", + new RowMapper() { + @Override + public Long mapRow(ResultSet rs, int numRow) throws SQLException { + return rs.getLong("c"); + } + }).stream().findFirst().orElse(0L); } public List 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") - .setParameter(1, steamID.steam2) - .getResultList(); + return jdbcTemplate.query("SELECT id, steam3, vk_id, discord_id, date FROM free_vip WHERE steam3 = ? ORDER BY `free_vip`.`date` DESC", + new Object[]{steamID.steam2}, + new RowMapper() { + @Override + public FreeVIP mapRow(ResultSet rs, int rowNum) throws SQLException { + return new FreeVIP(rs); + } + }); } 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") - .setParameter(1, steamID.steam2) - .getResultStream().findFirst().orElse(0L); + return jdbcTemplate.query("SELECT UNIX_TIMESTAMP(`date`) as u_time FROM free_vip WHERE steam3 LIKE ? ORDER BY `date` DESC", + new Object[]{ steamID.steam2 }, + new RowMapper() { + @Override + public Long mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getLong("u_time"); + } + }).stream().findFirst().orElse(0L); } public Long getLastGivedFreeVIP(SocialAuth socialAuth) { @@ -60,26 +70,32 @@ public class FreeVIPService{ return 0L; } 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") - .setParameter(1, socialAuth.getVk_id()) - .getResultStream().findFirst().orElse(0L); + return jdbcTemplate.query("SELECT UNIX_TIMESTAMP(`date`) as u_time FROM free_vip WHERE vk_id = ? ORDER BY `date` DESC", + new Object[]{ socialAuth.getVk_id() }, + new RowMapper() { + @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) { - return (Long) entityManager.createNativeQuery("SELECT UNIX_TIMESTAMP(`date`) as u_time FROM free_vip WHERE discord_id = ?1 ORDER BY `date` DESC") - .setParameter(1, socialAuth.getDiscord_id()) - .getResultStream().findFirst().orElse(0L); + return jdbcTemplate.query("SELECT UNIX_TIMESTAMP(`date`) as u_time FROM free_vip WHERE discord_id = ? ORDER BY `date` DESC", + new Object[]{ socialAuth.getDiscord_id() }, + new RowMapper() { + @Override + public Long mapRow(ResultSet rs, int numRow) throws SQLException { + return rs.getLong("u_time"); + } + }).stream().findFirst().orElse(0L); } else { return 0L; } } - @Transactional("RwTransactionManager") public boolean setGivedFreeVip(SteamID steamID, SocialAuth 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())") - .setParameter(1, steamID.steam2) - .setParameter(2, socialAuth.getVk_id()) - .setParameter(3, socialAuth.getDiscord_id()) - .executeUpdate() > 0; + return jdbcTemplate.update("INSERT INTO `free_vip` (`id`, `steam3`, `vk_id`, `discord_id`, `date`) VALUES (NULL, ?, ?, ?, current_timestamp())", + steamID.steam2, socialAuth.getVk_id(), socialAuth.getDiscord_id()) > 0; } public Long addFreeVIP(SteamID steamID, SocialAuth socialAuth, Boolean test) { diff --git a/src/main/java/app/services/db/KillfeedService.java b/src/main/java/app/services/db/KillfeedService.java index 4387a22..3ffa373 100644 --- a/src/main/java/app/services/db/KillfeedService.java +++ b/src/main/java/app/services/db/KillfeedService.java @@ -2,83 +2,109 @@ package app.services.db; import app.entities.Stats; 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 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.transaction.annotation.Transactional; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; @Service -@Transactional("RoTransactionManager") public class KillfeedService { - private EntityManager entityManager; + @Autowired + @Qualifier("jt_ro") + private JdbcTemplate jdbcTemplate; private Stats stats; private NicknameService nicknameService; - KillfeedService(Stats stats, @Qualifier(value = "RoEntityManager") EntityManager entityManager, NicknameService nicknameService) { - this.entityManager = entityManager; + KillfeedService(Stats stats, NicknameService nicknameService) { this.stats = stats; this.nicknameService = nicknameService; } 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") - .setParameter(1, steamID.account_id) - .setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) - .getSingleResult(); + return jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `attacker_id` = ? AND `attacker_id` != `victim_id` AND `server_id` like ?", + new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id }, + new RowMapper() { + @Override + public Long mapRow(ResultSet rs, int numRow) throws SQLException { + return rs.getLong("c"); + } + }).stream().findFirst().orElse(0L); } public List getTopKills(String server_id) { - List 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") - .setParameter(1, server_id==null||server_id.isEmpty()?'%':server_id) - .getResultStream().map(obj -> new TopInFeed(obj)).toList(); - return result.stream().peek(kif -> kif.setNicknames(nicknameService)).toList(); + 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", + new Object[]{server_id == null || server_id.isEmpty() ? '%' : server_id}, + new RowMapper() { + @Override + public TopInFeed mapRow(ResultSet rs, int rowNum) throws SQLException { + return new TopInFeed(rs).setNicknames(nicknameService); + } + }); } 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") - .setParameter(1, steamID.account_id) - .setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) - .getSingleResult(); + return jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `victim_id` = ? AND `attacker_id` != `victim_id` AND `server_id` like ?", + new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id }, + new RowMapper() { + @Override + public Long mapRow(ResultSet rs, int numRow) throws SQLException { + return rs.getLong("rs"); + } + }).stream().findFirst().orElse(0L); } public List getTopDeads(String server_id) { - List 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") - .setParameter(1, server_id==null||server_id.isEmpty()?'%':server_id) - .getResultStream().map(obj -> new TopInFeed(obj)).toList(); - return result.stream().peek(kif -> kif.setNicknames(nicknameService)).toList(); + 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", + new Object[]{ server_id == null || server_id.isEmpty() ? '%' : server_id}, + new RowMapper() { + @Override + public TopInFeed mapRow(ResultSet rs, int rowNum) throws SQLException { + return new TopInFeed(rs).setNicknames(nicknameService); + } + }); } 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") - .setParameter(1, steamID.account_id) - .setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) - .getSingleResult(); + return jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `victim_id` = ? AND `attacker_id` = `victim_id` AND `server_id` like ?", + new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id }, + new RowMapper() { + @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) { - return (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(); + return jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `assister_id` = ? AND `server_id` like ?", + new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id}, + new RowMapper() { + @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) { - List 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") - .setParameter(1, steamID.account_id) - .setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) - .setParameter(3, limit) - .setParameter(4, offset) - .getResultStream().map(obj -> new HypeWeapons(obj)).toList(); + List 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 ?", + new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id, limit, offset }, + new RowMapper() { + @Override + public HypeWeapons mapRow(ResultSet rs, int rowNum) throws SQLException { + 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`") .setParameter(1, steamID.account_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) { - List 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") - .setParameter(1, steamID.account_id) - .setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) - .setParameter(3, limit) - .setParameter(4, offset) - .getResultStream().map(obj -> new KillsInFeed(obj)).toList(); - 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(); - return Map.of("result", result.stream().peek(kif -> kif.setNicknames(nicknameService)).toList(), "count", count, "type", FeedType.KILL.ordinal()); + List 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 ?", + new Object[]{steamID.account_id, server_id == null || server_id.isEmpty() ? '%' : server_id, limit, offset}, + new RowMapper() { + @Override + public KillsInFeed mapRow(ResultSet rs, int rowNum) throws SQLException { + return new KillsInFeed(rs).setNicknames(nicknameService); + } + }); + + Long count = jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `attacker_id` = ? AND `attacker_id` != `victim_id` AND `server_id` like ?", + new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id }, + new RowMapper() { + @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) { - List 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") - .setParameter(1, steamID.account_id) - .setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) - .setParameter(3, limit) - .setParameter(4, offset) - .getResultStream().map(obj -> new KillsInFeed(obj)).toList(); - 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(); - return Map.of("result", result.stream().peek(kif -> kif.setNicknames(nicknameService)).toList(), "count", count, "type", FeedType.DEAD.ordinal()); + List 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 ?", + new Object[]{steamID.account_id, server_id == null || server_id.isEmpty() ? '%' : server_id, limit, offset}, + new RowMapper() { + @Override + public KillsInFeed mapRow(ResultSet rs, int rowNum) throws SQLException { + return new KillsInFeed(rs).setNicknames(nicknameService); + } + }); + + Long count = jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `victim_id` = ? AND `attacker_id` != `victim_id` AND `server_id` like ?", + new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id }, + new RowMapper() { + @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) { - List 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") - .setParameter(1, steamID.account_id) - .setParameter(2, server_id==null||server_id.isEmpty()?'%':server_id) - .setParameter(3, limit) - .setParameter(4, offset) - .getResultStream().map(obj -> new KillsInFeed(obj)).toList(); - 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(); - return Map.of("result", result.stream().peek(kif -> kif.setNicknames(nicknameService)).toList(), "count", count, "type", FeedType.ASSIST.ordinal()); + List 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 ?", + new Object[]{steamID.account_id, server_id == null || server_id.isEmpty() ? '%' : server_id, limit, offset}, + new RowMapper() { + @Override + public KillsInFeed mapRow(ResultSet rs, int rowNum) throws SQLException { + return new KillsInFeed(rs).setNicknames(nicknameService); + } + }); + + Long count = jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_killfeed` WHERE `assister_id` = ? AND `server_id` like ?", + new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?'%':server_id }, + new RowMapper() { + @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 @@ -138,6 +188,12 @@ public class KillfeedService { this.name = (String) ((Object[]) obj)[1]; 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 { @@ -156,11 +212,35 @@ public class KillfeedService { 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); + 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 class KillsInFeed { int attacker_id; @@ -183,10 +263,21 @@ public class KillfeedService { 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.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); + return this; } public String getWeapon_name(){ diff --git a/src/main/java/app/services/db/MessageService.java b/src/main/java/app/services/db/MessageService.java index 86ce558..565c932 100644 --- a/src/main/java/app/services/db/MessageService.java +++ b/src/main/java/app/services/db/MessageService.java @@ -2,67 +2,98 @@ package app.services.db; import app.entities.Stats; import app.entities.other.SteamID; -import jakarta.persistence.EntityManager; import lombok.Data; +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.transaction.annotation.Transactional; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.List; import java.util.Map; @Service -@Transactional("RoTransactionManager") public class MessageService { - private EntityManager entityManager; + @Autowired + @Qualifier("jt_ro") + private JdbcTemplate jdbcTemplate; + private Stats stats; private NicknameService nicknameService; - MessageService(Stats stats, @Qualifier(value = "RoEntityManager") EntityManager entityManager, NicknameService nicknameService) { - this.entityManager = entityManager; + MessageService(Stats stats, NicknameService nicknameService) { this.stats = stats; this.nicknameService = nicknameService; } public Map getAllMessages(String server_id, String filter, int offset, int limit) { - List 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") - .setParameter(1, server_id==null||server_id.isEmpty()?"%":server_id) - .setParameter(2, filter==null||filter.isEmpty()?"%":"%" + filter + "%") - .setParameter(3, limit) - .setParameter(4, offset) - .getResultStream().map(obj -> new Message(obj)).toList(); - 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(); - return Map.of("result", result.stream().peek(message -> message.setAccount_name(nicknameService)).toList(), "count", count); + List 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 ?", + new Object[]{ server_id == null || server_id.isEmpty() ? "%" : server_id, filter == null || filter.isEmpty() ? "%" : "%" + filter + "%", limit, offset}, + new RowMapper() { + @Override + public Message mapRow(ResultSet rs, int rowNum) throws SQLException { + return new Message(rs).setAccount_name(nicknameService); + } + }); + + Long count = jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_messages` WHERE `server_id` like ? AND `message` LIKE ?", + new Object[]{ server_id==null||server_id.isEmpty()?"%":server_id, filter==null||filter.isEmpty()?"%":"%" + filter + "%" }, + new RowMapper() { + @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) { - List 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") - .setParameter(1, steamID.account_id) - .setParameter(2, server_id==null||server_id.isEmpty()?"%":server_id) - .setParameter(3, filter==null||filter.isEmpty()?"%":"%" + filter + "%") - .setParameter(4, limit) - .setParameter(5, offset) - .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) - .setParameter(3, filter==null||filter.isEmpty()?"%":"%" + filter + "%") - .getSingleResult(); + List 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 ?", + new Object[]{steamID.account_id, server_id == null || server_id.isEmpty() ? "%" : server_id, filter == null || filter.isEmpty() ? "%" : "%" + filter + "%", limit, offset}, + new RowMapper() { + @Override + public Message mapRow(ResultSet rs, int rowNum) throws SQLException { + return new Message(rs); + } + }); + + Long count = jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_messages` WHERE `account_id` = ? AND `server_id` like ? AND `message` LIKE ?", + new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?"%":server_id, filter==null||filter.isEmpty()?"%":"%" + filter + "%"}, + new RowMapper() { + @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 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") - .setParameter(1, steamID.account_id) - .setParameter(2, server_id==null||server_id.isEmpty()?"%":server_id) - .getSingleResult(); + return jdbcTemplate.query("SELECT COUNT(*) as c FROM `user_messages` WHERE `account_id` = ? AND `server_id` like ?", + new Object[]{ steamID.account_id, server_id==null||server_id.isEmpty()?"%":server_id }, + new RowMapper() { + @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 class Message { int account_id; @@ -77,8 +108,16 @@ public class MessageService { 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); + return this; } } } diff --git a/src/main/java/app/services/db/NicknameService.java b/src/main/java/app/services/db/NicknameService.java index 146cb69..90acfc1 100644 --- a/src/main/java/app/services/db/NicknameService.java +++ b/src/main/java/app/services/db/NicknameService.java @@ -1,31 +1,30 @@ package app.services.db; 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.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.transaction.annotation.Transactional; +import java.sql.ResultSet; +import java.sql.SQLException; import java.time.Instant; import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; import java.util.Optional; @Service -@Transactional("RoTransactionManager") public class NicknameService { - private EntityManager entityManager; + @Autowired + @Qualifier("jt_ro") + private JdbcTemplate jdbcTemplate; private Stats stats; private HashMap> nickname_cache = new HashMap<>(); private long refresh_after = 900; - NicknameService(Stats stats, @Qualifier(value = "RoEntityManager") EntityManager entityManager) { - this.entityManager = entityManager; + NicknameService(Stats stats) { this.stats = stats; } @@ -45,8 +44,13 @@ public class NicknameService { } 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;") - .setParameter(1, account_id) - .getSingleResult()).orElse("Unknown"); + return jdbcTemplate.query("SELECT `player_name` FROM `"+db+"`.`user_connections` WHERE `account_id` = ? ORDER BY `user_connections`.`id` DESC LIMIT 1;", + new Object[]{ account_id }, + new RowMapper() { + @Override + public String mapRow(ResultSet rs, int num) throws SQLException { + return rs.getString("player_name"); + } + }).stream().findFirst().orElse("Unknown"); } } diff --git a/src/main/java/app/services/db/PermitionService.java b/src/main/java/app/services/db/PermitionService.java index 2884f99..42dfaf6 100644 --- a/src/main/java/app/services/db/PermitionService.java +++ b/src/main/java/app/services/db/PermitionService.java @@ -1,18 +1,13 @@ package app.services.db; import app.entities.db.AdminInfo; -import app.entities.db.Ban; import app.entities.db.Permition; 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.Qualifier; -import org.springframework.context.ApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; import java.sql.ResultSet; import java.sql.SQLException; diff --git a/src/main/java/app/services/db/UsertimeService.java b/src/main/java/app/services/db/UsertimeService.java index 04c84d1..a30c4c2 100644 --- a/src/main/java/app/services/db/UsertimeService.java +++ b/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.Stats; 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.Qualifier; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; 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.sql.Timestamp; import java.util.*; import java.util.stream.Collectors; @Service -@Transactional("RoTransactionManager") public class UsertimeService { - EntityManager entityManager; - + @Autowired + @Qualifier("jt_ro") + private JdbcTemplate jdbcTemplate; //Лучше это всегда держать в true - boolean last_map = true; - Stats stats; + private boolean last_map = true; + private Stats stats; @Autowired - public UsertimeService(Stats stats, @Qualifier(value = "RoEntityManager") EntityManager entityManager) { - this.entityManager = entityManager; + public UsertimeService(Stats stats) { this.stats = stats; } @@ -39,9 +39,9 @@ public class UsertimeService { for (Map.Entry stringServerEntry : stats.getServers().entrySet()) { 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 { - maps = getMaps(stringServerEntry.getValue().getDb()).orElse(List.of()); + maps = getMaps(stringServerEntry.getValue().getDb()); } if(maps.size() == 0) {continue;} @@ -65,9 +65,9 @@ public class UsertimeService { for (Map.Entry stringServerEntry : stats.getServers().entrySet()) { 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 { - maps = getMaps(stringServerEntry.getValue().getDb()).orElse(List.of()); + maps = getMaps(stringServerEntry.getValue().getDb()); } if(maps.size() == 0) {continue;} @@ -86,43 +86,59 @@ public class UsertimeService { } public Timestamp getLastplay(String db, SteamID steamID, String map) { - List 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") - //.setParameter(1, db) - .setParameter(1,"disconnect") - .setParameter(2, steamID.account_id) - .setParameter(3, map) - .getResultList(); - return response.size() > 0 ? response.get(0) : null; + 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", + new Object[]{ map, "disconnect", steamID.account_id}, + new RowMapper() { + @Override + public Timestamp mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getTimestamp("timestamp"); + } + }).stream().findFirst().orElse(null); } public BigDecimal getTotalPlaytime(String db, SteamID steamID, String map) { - List 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") - //.setParameter(1, db) - .setParameter(1, map) - .setParameter(2, "disconnect") - .setParameter(3, steamID.account_id) - .getResultList(); - return response.size() > 0 ? response.get(0) : null; + return jdbcTemplate.query("select sum(connect_duration) as total from `"+db+"`.`user_connections` WHERE map LIKE ? and connection_type LIKE ? AND account_id = ?", + new Object[]{ map, "disconnect", steamID.account_id }, + new RowMapper(){ + @Override + public BigDecimal mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getBigDecimal("total"); + } + }).stream().findFirst().orElse(null); } - public Optional 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") - .setParameter(1, limit) - .getResultList()); + public List getMap(String db, int limit) { + return jdbcTemplate.query("select distinct `map` from `"+db+"`.`user_connections` WHERE 1 ORDER BY `user_connections`.`id` DESC LIMIT ?", + new Object[]{ limit }, + new RowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getString("map"); + } + }); } - public Optional getMaps(String db) { - return Optional.ofNullable(entityManager.createNativeQuery("select distinct `map` from `"+db+"`.`user_connections`") - //.setParameter(1, db) - .getResultList()); + public List getMaps(String db) { + return jdbcTemplate.query("select distinct `map` from `"+db+"`.`user_connections`", + new RowMapper() { + @Override + public String mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getString("map"); + } + }); } public SteamID getSteamOnUsername(String username) { SteamID steamID; for (Map.Entry 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") - .setParameter(1, username) - .getResultStream().map(x -> SteamIDConverter.getSteamID("[U:1:%d]".formatted(x))).findFirst().orElse(null); + steamID = jdbcTemplate.query("SELECT account_id FROM `"+stringServerEntry.getValue().getDb()+"`.`user_connections` WHERE player_name LIKE ? ORDER BY `id` DESC LIMIT 1", + new Object[]{ username }, + new RowMapper() { + @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; } return null; @@ -131,21 +147,27 @@ public class UsertimeService { public List 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); if (db == null) return new ArrayList<>(); - return (List) 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() { + @Override + public Gametime mapRow(ResultSet rs, int rowNum) throws SQLException { + return new Gametime(rs); + } + }); } 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); 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") - .setParameter(1, steamID.account_id) - .setParameter(2, "disconnect") - .getSingleResult(); + return jdbcTemplate.query("SELECT count(id) as c FROM `"+db+"`.`user_connections` WHERE account_id = ?1 AND connection_type LIKE ?2", + new Object[]{ steamID.account_id, "disconnect" }, + new RowMapper() { + @Override + public Long mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getLong("с"); + } + }).stream().findFirst().orElse(0L); } } diff --git a/src/main/java/app/services/db/VIPService.java b/src/main/java/app/services/db/VIPService.java index 00889ad..ee9162c 100644 --- a/src/main/java/app/services/db/VIPService.java +++ b/src/main/java/app/services/db/VIPService.java @@ -5,24 +5,27 @@ import app.entities.db.Permition; import app.entities.other.SteamID; import app.services.ServerService; 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.Qualifier; 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.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; @Service -@Transactional("RwTransactionManager") public class VIPService { - EntityManager entityManager; + + @Autowired + @Qualifier("jt_rw") + private JdbcTemplate jdbcTemplate; RestTemplate restTemplate; @@ -35,42 +38,50 @@ public class VIPService { @Autowired public VIPService(PermitionService permitionService, ServerService serverService, - DonateService donateService, - @Qualifier(value = "RwEntityManager") EntityManager entityManager) { + DonateService donateService) { this.restTemplate = new RestTemplate(); this.permitionService = permitionService; this.serverService = serverService; this.donateService = donateService; - this.entityManager = entityManager; } // Список ид из дискорда кто имеет платную випку public List 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`") - .setParameter(1, "VIP") - .setParameter(2, "Donate.User") - .setParameter(3, "f13bot.User") - .getResultList(); + 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`", + new Object[]{"VIP", "Donate.User", "f13bot.User"}, + new RowMapper() { + @Override + public Long mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getLong("discord_id"); + } + }); } // Список ид из дискорда кто имеет бесплатную випку public List 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`") - .setParameter(1, "VIP") - .setParameter(2, "f13bot.FreeVIP") - .getResultList(); + 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`", + new Object[]{"VIP", "f13bot.FreeVIP"}, + new RowMapper() { + @Override + public Long mapRow(ResultSet rs, int rowNum) throws SQLException { + return rs.getLong("discord_id"); + } + }); } // Транзакция, проверка и удаление випок подшедших к концу - @Transactional("RwTransactionManager") public int removeEndedVIPs() { - List 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`)") - .setParameter(1, "VIP") - .getResultStream().map(identity -> SteamIDConverter.getSteamID((String) identity)).toList(); - - 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`)") - .setParameter(1, "VIP") - .executeUpdate(); + List 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`)", + new Object[]{"VIP"}, + new RowMapper() { + @Override + public SteamID mapRow(ResultSet rs, int rowNum) throws SQLException { + return SteamIDConverter.getSteamID(rs.getString("identity")); + } + }); + + 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 -> { 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) { - return entityManager.createNativeQuery("INSERT INTO `gived_vip` (`id`, `steam2`, `amount`, `timestamp`, `givemethod`, `reserved`, `extend`) VALUES (NULL, ?1, ?2, current_timestamp(), ?3, ?4, ?5)") - .setParameter(1, steamID.steam2) - .setParameter(2, amount) - .setParameter(3, vipGiveMethod.ordinal()) - .setParameter(4, extra) - .setParameter(5, extend) - .executeUpdate(); + return jdbcTemplate.update("INSERT INTO `gived_vip` (`id`, `steam2`, `amount`, `timestamp`, `givemethod`, `reserved`, `extend`) VALUES (NULL, ?, ?, current_timestamp(), ?, ?, ?)", + steamID.steam2, amount, vipGiveMethod.ordinal(), extra, extend); } // Проверка наличия прав для дочерних сервисов