mirror of
https://github.com/Quackster/Havana.git
synced 2025-07-01 20:27:47 +00:00
Add source code
This commit is contained in:
parent
06f602f44e
commit
6b4d250e9c
1270 changed files with 179649 additions and 2 deletions
18
Havana-Server/.gitignore
vendored
Normal file
18
Havana-Server/.gitignore
vendored
Normal file
|
@ -0,0 +1,18 @@
|
|||
.gradle/
|
||||
.idea/
|
||||
/out/
|
||||
**.iml
|
||||
/gradle/
|
||||
/build/
|
||||
bin/
|
||||
tmp/
|
||||
|
||||
gradlew
|
||||
gradlew.bat
|
||||
|
||||
habbohotel.properties
|
||||
game.properties
|
||||
icarus.properties
|
||||
locale.ini
|
||||
log4j.properties
|
||||
error.log
|
83
Havana-Server/build.gradle
Normal file
83
Havana-Server/build.gradle
Normal file
|
@ -0,0 +1,83 @@
|
|||
apply plugin: 'java'
|
||||
apply plugin: 'application'
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.toVersion("1.11")
|
||||
targetCompatibility = JavaVersion.toVersion("1.11")
|
||||
}
|
||||
|
||||
mainClassName = 'org.alexdev.havana.Havana'
|
||||
|
||||
repositories {
|
||||
maven { url 'https://jitpack.io' }
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// https://mvnrepository.com/artifact/net.dv8tion/JDA
|
||||
implementation 'net.dv8tion:JDA:5.0.0-alpha.12'
|
||||
|
||||
// https://mvnrepository.com/artifact/com.zaxxer/HikariCP
|
||||
implementation group: 'com.zaxxer', name: 'HikariCP', version: '3.4.1'
|
||||
|
||||
// https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client
|
||||
implementation group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: '2.3.0'
|
||||
|
||||
// https://mvnrepository.com/artifact/io.netty/netty-all
|
||||
implementation group: 'io.netty', name: 'netty-all', version: '4.1.33.Final'
|
||||
|
||||
// https://mvnrepository.com/artifact/org.slf4j/slf4j-api
|
||||
implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'
|
||||
|
||||
// https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12
|
||||
implementation group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.7.25'
|
||||
|
||||
// https://mvnrepository.com/artifact/log4j/log4j/1.2.17
|
||||
implementation group: 'log4j', name: 'log4j', version: '1.2.17'
|
||||
|
||||
// https://mvnrepository.com/artifact/org.apache.commons/commons-configuration2
|
||||
implementation group: 'org.apache.commons', name: 'commons-configuration2', version: '2.2'
|
||||
|
||||
// https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
|
||||
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
|
||||
|
||||
// https://mvnrepository.com/artifact/commons-lang/commons-lang
|
||||
implementation group: 'commons-lang', name: 'commons-lang', version: '2.6'
|
||||
|
||||
// https://mvnrepository.com/artifact/commons-validator/commons-validator
|
||||
implementation group: 'commons-validator', name: 'commons-validator', version: '1.6'
|
||||
|
||||
// https://mvnrepository.com/artifact/com.google.code.gson/gson
|
||||
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.0'
|
||||
|
||||
implementation 'com.maxmind.geoip2:geoip2:2.12.0'
|
||||
implementation 'com.github.bhlangonijr:chesslib:1.1.1'
|
||||
implementation 'com.goterl:lazysodium-java:5.0.1'
|
||||
implementation "net.java.dev.jna:jna:5.8.0"
|
||||
}
|
||||
|
||||
// Create fat jar with libraries inside of it.
|
||||
task fatJar(type: Jar) {
|
||||
zip64 true
|
||||
duplicatesStrategy 'exclude'
|
||||
manifest {
|
||||
attributes 'Main-Class': mainClassName
|
||||
}
|
||||
baseName = project.name + '-all'
|
||||
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
|
||||
with jar
|
||||
}
|
||||
|
||||
// Create jar with no libraries inside of it, used when creating with "gradle distZip" and
|
||||
// libraries are then to be stored in the folder next to it called 'dependency-jars'
|
||||
// https://vocon-it.com/2016/11/15/how-to-build-a-lean-jar-file-with-gradle/
|
||||
/*jar {
|
||||
manifest {
|
||||
attributes (
|
||||
'Main-Class': mainClassName,
|
||||
"Class-Path": '. dependency-jars/' + configurations.compile.collect {
|
||||
it.getName()
|
||||
}.join(' dependency-jars/')
|
||||
)
|
||||
}
|
||||
}*/
|
356
Havana-Server/src/main/java/org/alexdev/havana/Havana.java
Normal file
356
Havana-Server/src/main/java/org/alexdev/havana/Havana.java
Normal file
|
@ -0,0 +1,356 @@
|
|||
package org.alexdev.havana;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import io.netty.util.ResourceLeakDetector;
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.dao.mysql.*;
|
||||
import org.alexdev.havana.game.GameScheduler;
|
||||
import org.alexdev.havana.game.achievements.AchievementManager;
|
||||
import org.alexdev.havana.game.ads.AdManager;
|
||||
import org.alexdev.havana.game.catalogue.CatalogueManager;
|
||||
import org.alexdev.havana.game.catalogue.collectables.CollectablesManager;
|
||||
import org.alexdev.havana.game.commands.CommandManager;
|
||||
import org.alexdev.havana.game.ecotron.EcotronManager;
|
||||
import org.alexdev.havana.game.effects.EffectsManager;
|
||||
import org.alexdev.havana.game.events.EventsManager;
|
||||
import org.alexdev.havana.game.fuserights.FuserightsManager;
|
||||
import org.alexdev.havana.game.games.GameManager;
|
||||
import org.alexdev.havana.game.games.snowstorm.SnowStormMapsManager;
|
||||
import org.alexdev.havana.game.infobus.InfobusManager;
|
||||
import org.alexdev.havana.game.item.ItemManager;
|
||||
import org.alexdev.havana.game.misc.figure.FigureManager;
|
||||
import org.alexdev.havana.game.moderation.ChatManager;
|
||||
import org.alexdev.havana.game.navigator.NavigatorManager;
|
||||
import org.alexdev.havana.game.player.PlayerManager;
|
||||
import org.alexdev.havana.game.room.RoomManager;
|
||||
import org.alexdev.havana.game.room.handlers.walkways.WalkwaysManager;
|
||||
import org.alexdev.havana.game.room.models.RoomModelManager;
|
||||
import org.alexdev.havana.game.texts.TextsManager;
|
||||
import org.alexdev.havana.game.wordfilter.WordfilterManager;
|
||||
import org.alexdev.havana.messages.MessageHandler;
|
||||
import org.alexdev.havana.server.mus.MusServer;
|
||||
import org.alexdev.havana.server.netty.NettyServer;
|
||||
import org.alexdev.havana.server.rcon.RconServer;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
import org.alexdev.havana.util.config.GameConfiguration;
|
||||
import org.alexdev.havana.util.config.LoggingConfiguration;
|
||||
import org.alexdev.havana.util.config.ServerConfiguration;
|
||||
import org.alexdev.havana.util.config.writer.DefaultConfigWriter;
|
||||
import org.alexdev.havana.util.config.writer.GameConfigWriter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.time.LocalTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Locale;
|
||||
|
||||
public class Havana {
|
||||
private static final Gson gson = new Gson();
|
||||
private static long startupTime;
|
||||
|
||||
private static String serverIP;
|
||||
private static int serverPort;
|
||||
|
||||
private static String musServerIP;
|
||||
private static int musServerPort;
|
||||
|
||||
private static String rconIP;
|
||||
private static int rconPort;
|
||||
|
||||
private static boolean isShutdown;
|
||||
|
||||
private static NettyServer server;
|
||||
private static MusServer musServer;
|
||||
private static RconServer rconServer;
|
||||
|
||||
private static Logger log;
|
||||
|
||||
/**
|
||||
* Main call of Java application
|
||||
* @param args System arguments
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
startupTime = DateUtil.getCurrentTimeSeconds();
|
||||
|
||||
try {
|
||||
LoggingConfiguration.checkLoggingConfig();
|
||||
|
||||
ServerConfiguration.setWriter(new DefaultConfigWriter());
|
||||
ServerConfiguration.load("server.ini");
|
||||
|
||||
log = LoggerFactory.getLogger(Havana.class);
|
||||
ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
|
||||
|
||||
log.info("Havana - Habbo Hotel V31 Emulation");
|
||||
|
||||
if (Storage.connect()) {
|
||||
Storage.getLogger().info("Connection to MySQL was a success");
|
||||
} else {
|
||||
Storage.getLogger().error("Could not connect");
|
||||
return;
|
||||
}
|
||||
|
||||
// Update players online back to 0
|
||||
SettingsDao.updateSetting("players.online", "0");
|
||||
|
||||
RoomDao.resetVisitors();
|
||||
ItemDao.resetTradeStates();
|
||||
PlayerDao.resetOnline();
|
||||
|
||||
/*
|
||||
var percentageCheck = 1.0
|
||||
;
|
||||
|
||||
for (int i = 0; i < 100; i++) {
|
||||
var chance = Math.random() * 100;
|
||||
|
||||
if ((100 - percentageCheck) < chance) {
|
||||
log.info("5% chance!");
|
||||
}
|
||||
}*/
|
||||
|
||||
log.info("Setting up game");
|
||||
|
||||
GameConfiguration.getInstance(new GameConfigWriter());
|
||||
InfobusManager.getInstance();
|
||||
AchievementManager.getInstance();
|
||||
AdManager.getInstance();
|
||||
WalkwaysManager.getInstance();
|
||||
ItemManager.getInstance();
|
||||
CatalogueManager.getInstance();
|
||||
EcotronManager.getInstance();
|
||||
RoomModelManager.getInstance();
|
||||
RoomManager.getInstance();
|
||||
PlayerManager.getInstance();
|
||||
FuserightsManager.getInstance();
|
||||
NavigatorManager.getInstance();
|
||||
EffectsManager.getInstance();
|
||||
EventsManager.getInstance();
|
||||
ChatManager.getInstance();
|
||||
GameScheduler.getInstance();
|
||||
SnowStormMapsManager.getInstance();
|
||||
GameManager.getInstance();
|
||||
CommandManager.getInstance();
|
||||
MessageHandler.getInstance();
|
||||
TextsManager.getInstance();
|
||||
WordfilterManager.getInstance();
|
||||
CollectablesManager.getInstance();
|
||||
FigureManager.getInstance();
|
||||
|
||||
if (GameConfiguration.getInstance().getBoolean("reset.sso.after.login")) {
|
||||
PlayerDao.resetSsoTickets();
|
||||
}
|
||||
|
||||
setupRcon();
|
||||
setupMus();
|
||||
setupServer();
|
||||
|
||||
if (GameConfiguration.getInstance().getInteger("delete.chatlogs.after.x.age") > 0) {
|
||||
LogDao.deleteChatLogs(GameConfiguration.getInstance().getInteger("delete.chatlogs.after.x.age"));
|
||||
}
|
||||
|
||||
if (GameConfiguration.getInstance().getInteger("delete.iplogs.after.x.age") > 0) {
|
||||
LogDao.deleteIpAddressLogs(GameConfiguration.getInstance().getInteger("delete.iplogs.after.x.age"));
|
||||
}
|
||||
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(Havana::dispose));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void setupServer() throws UnknownHostException {
|
||||
String serverIP = ServerConfiguration.getString("server.bind");
|
||||
|
||||
if (serverIP.length() == 0) {
|
||||
log.error("Game server bind address is not provided");
|
||||
return;
|
||||
}
|
||||
|
||||
serverPort = ServerConfiguration.getInteger("server.port");
|
||||
|
||||
if (serverPort == 0) {
|
||||
log.error("Game server port not provided");
|
||||
return;
|
||||
}
|
||||
|
||||
server = new NettyServer(serverIP, serverPort);
|
||||
server.createSocket();
|
||||
server.bind();
|
||||
}
|
||||
|
||||
private static void setupRcon() throws IOException {
|
||||
// Create the RCON instance
|
||||
rconIP = ServerConfiguration.getString("rcon.bind");
|
||||
|
||||
if (rconIP.length() == 0) {
|
||||
log.error("Remote control (RCON) server bind address is not provided");
|
||||
return;
|
||||
}
|
||||
|
||||
rconPort = ServerConfiguration.getInteger("rcon.port");
|
||||
|
||||
if (rconPort == 0) {
|
||||
log.error("Remote control (RCON) server port not provided");
|
||||
return;
|
||||
}
|
||||
|
||||
rconServer = new RconServer(rconIP, rconPort);
|
||||
rconServer.createSocket();
|
||||
rconServer.bind();
|
||||
}
|
||||
|
||||
private static void setupMus() throws UnknownHostException {
|
||||
musServerIP = ServerConfiguration.getString("mus.bind");
|
||||
|
||||
if (musServerIP.length() == 0) {
|
||||
log.error("Multi User Server (MUS) bind address is not provided");
|
||||
return;
|
||||
}
|
||||
|
||||
musServerPort = ServerConfiguration.getInteger("mus.port");
|
||||
|
||||
if (musServerPort == 0) {
|
||||
log.error("Multi User Server (MUS) port not provided");
|
||||
return;
|
||||
}
|
||||
|
||||
musServer = new MusServer(musServerIP, musServerPort);
|
||||
musServer.createSocket();
|
||||
musServer.bind();
|
||||
}
|
||||
|
||||
private static void dispose() {
|
||||
try {
|
||||
|
||||
log.info("Shutting down server!");
|
||||
isShutdown = true;
|
||||
|
||||
log.info("Saving chat!");
|
||||
ChatManager.getInstance().performChatSaving();
|
||||
|
||||
log.info("Saving item updates!");
|
||||
GameScheduler.getInstance().performItemSaving();
|
||||
|
||||
log.info("Saving item deletions!");
|
||||
GameScheduler.getInstance().performItemDeletion();
|
||||
|
||||
log.info("Disconnecting all users!");
|
||||
PlayerManager.getInstance().dispose();
|
||||
|
||||
log.info("Server disposal!");
|
||||
server.dispose(false);
|
||||
|
||||
log.info("All done!");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isHappyHour() {
|
||||
try {
|
||||
Calendar cl = Calendar.getInstance();
|
||||
|
||||
LocalTime from = null;//LocalTime.parse( "20:11:13" ) ;
|
||||
LocalTime to = null;//LocalTime.parse( "14:49:00" ) ;
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.US);
|
||||
|
||||
if (cl.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ||
|
||||
cl.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
|
||||
from = LocalTime.parse(GameConfiguration.getInstance().getString("happy.hour.weekend.start"), formatter);
|
||||
to = LocalTime.parse(GameConfiguration.getInstance().getString("happy.hour.weekend.end"), formatter);
|
||||
} else {
|
||||
from = LocalTime.parse(GameConfiguration.getInstance().getString("happy.hour.weekday.start"), formatter);
|
||||
to = LocalTime.parse(GameConfiguration.getInstance().getString("happy.hour.weekday.end"), formatter);
|
||||
}
|
||||
|
||||
LocalTime nowUtcTime = LocalTime.parse(DateUtil.getCurrentDate("HH:mm:ss"), formatter);
|
||||
return nowUtcTime.isAfter(from) && nowUtcTime.isBefore(to);
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the interface to the server handler
|
||||
*
|
||||
* @return {@link NettyServer} interface
|
||||
*/
|
||||
public static NettyServer getServer() {
|
||||
return server;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the interface to the server handler
|
||||
*
|
||||
* @return {@link NettyServer} interface
|
||||
*/
|
||||
public static RconServer getRcon() {
|
||||
return rconServer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the server IPv4 IP address it is currently (or attempting to) listen on
|
||||
* @return IP as string
|
||||
*/
|
||||
public static String getServerIP() {
|
||||
return serverIP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the server port it is currently (or attempting to) listen on
|
||||
* @return string of IP
|
||||
*/
|
||||
public static int getServerPort() {
|
||||
return serverPort;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the rcon IPv4 IP address it is currently (or attempting to) listen on
|
||||
* @return IP as string
|
||||
*/
|
||||
public static String getRconIP() {
|
||||
return rconIP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the rcon port it is currently (or attempting to) listen on
|
||||
* @return string of IP
|
||||
*/
|
||||
public static int getRconPort() {
|
||||
return rconPort;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the startup time.
|
||||
*
|
||||
* @return the startup time
|
||||
*/
|
||||
public static long getStartupTime() {
|
||||
return startupTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Are we shutting down?
|
||||
*
|
||||
* @return boolean yes/no
|
||||
*/
|
||||
public static boolean isShuttingdown() {
|
||||
return isShutdown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get gson instance.
|
||||
*
|
||||
* @return the gson instance
|
||||
*/
|
||||
public static Gson getGson() {
|
||||
return gson;
|
||||
}
|
||||
}
|
245
Havana-Server/src/main/java/org/alexdev/havana/dao/Storage.java
Normal file
245
Havana-Server/src/main/java/org/alexdev/havana/dao/Storage.java
Normal file
|
@ -0,0 +1,245 @@
|
|||
package org.alexdev.havana.dao;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import org.alexdev.havana.log.Log;
|
||||
import org.alexdev.havana.util.config.ServerConfiguration;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
|
||||
public class Storage {
|
||||
private HikariDataSource ds;
|
||||
private boolean isConnected;
|
||||
|
||||
private static Storage storage;
|
||||
private static Logger log = LoggerFactory.getLogger(Storage.class);
|
||||
|
||||
private Storage(String host, int port, String username, String password, String db) {
|
||||
try {
|
||||
HikariConfig config = new HikariConfig();
|
||||
config.setDriverClassName("org.mariadb.jdbc.Driver");
|
||||
config.setJdbcUrl("jdbc:mariadb://" + host + ":" + port + "/" + db);
|
||||
config.setUsername(username);
|
||||
config.setPassword(password);
|
||||
|
||||
config.setPoolName("processing");
|
||||
|
||||
// No martinmine/Leon/other Habbotards, you don't know better.
|
||||
// Read up on this first, before commenting dumb shit
|
||||
// https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing
|
||||
// availableProcessors() already returns thread count on hyper-threaded processors
|
||||
// Thus we don't need the * 2 described there
|
||||
config.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() + 1);
|
||||
config.setMinimumIdle(1);
|
||||
|
||||
config.addDataSourceProperty("cachePrepStmts", "true");
|
||||
config.addDataSourceProperty("prepStmtCacheSize", "250");
|
||||
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
|
||||
config.addDataSourceProperty("characterEncoding", "utf8");
|
||||
config.addDataSourceProperty("useUnicode", "true");
|
||||
config.addDataSourceProperty("useSSL", "false");
|
||||
config.addDataSourceProperty("serverTimezone", "UTC");
|
||||
config.addDataSourceProperty("sessionVariables", "sql_mode='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'");
|
||||
|
||||
this.ds = new HikariDataSource(config);
|
||||
this.isConnected = true;
|
||||
|
||||
} catch (Exception ex) {
|
||||
Storage.logError(ex);
|
||||
//Storage.logError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to connect to its data access object service
|
||||
*
|
||||
* @return boolean - if connection was successful or not
|
||||
*/
|
||||
public static boolean connect() {
|
||||
Storage.getLogger().info("Connecting to MySQL server");
|
||||
|
||||
storage = new Storage(ServerConfiguration.getString("mysql.hostname"),
|
||||
ServerConfiguration.getInteger("mysql.port"),
|
||||
ServerConfiguration.getString("mysql.username"),
|
||||
ServerConfiguration.getString("mysql.password"),
|
||||
ServerConfiguration.getString("mysql.database"));
|
||||
|
||||
return storage.isConnected();
|
||||
}
|
||||
|
||||
/**
|
||||
* Logger handler for the MySQL processing.
|
||||
*
|
||||
* @param ex the exception to log
|
||||
*/
|
||||
public static void logError(Exception ex) {
|
||||
Log.getErrorLogger().error("Error when executing MySQL query: ", ex);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare.
|
||||
*
|
||||
* @param query the query
|
||||
* @param conn the conn
|
||||
* @return the prepared statement
|
||||
* @throws SQLException the SQL exception
|
||||
*/
|
||||
public PreparedStatement prepare(String query, Connection conn) throws SQLException {
|
||||
try {
|
||||
return conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute.
|
||||
*
|
||||
* @param query the query
|
||||
*/
|
||||
public void execute(String query) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = this.getConnection();
|
||||
preparedStatement = this.prepare(query, sqlConnection);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception ex) {
|
||||
Storage.logError(ex);
|
||||
throw ex;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the string.
|
||||
*
|
||||
* @param query the query
|
||||
* @return the string
|
||||
*/
|
||||
public String getString(String query) {
|
||||
String value = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = this.getConnection();
|
||||
preparedStatement = this.prepare(query, sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
resultSet.next();
|
||||
|
||||
value = resultSet.getString(query.split(" ")[1]);
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the connection count.
|
||||
*
|
||||
* @return the connection count
|
||||
*/
|
||||
public int getConnectionCount() {
|
||||
return this.ds.getHikariPoolMXBean().getActiveConnections();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the connection.
|
||||
*
|
||||
* @return the connection
|
||||
*/
|
||||
public Connection getConnection() {
|
||||
|
||||
try {
|
||||
return this.ds.getConnection();
|
||||
} catch (SQLException e) {
|
||||
Storage.logError(e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if is connected.
|
||||
*
|
||||
* @return true, if is connected
|
||||
*/
|
||||
public boolean isConnected() {
|
||||
return this.isConnected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close silently.
|
||||
*
|
||||
* @param resultSet the result set
|
||||
*/
|
||||
public static void closeSilently(ResultSet resultSet) {
|
||||
try {
|
||||
resultSet.close();
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close silently.
|
||||
*
|
||||
* @param statement the statement
|
||||
*/
|
||||
public static void closeSilently(Statement statement) {
|
||||
try {
|
||||
statement.close();
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close silently.
|
||||
*
|
||||
* @param sqlConnection the sql connection
|
||||
*/
|
||||
public static void closeSilently(Connection sqlConnection) {
|
||||
try {
|
||||
sqlConnection.close();
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the raw access to the data access object functions
|
||||
*
|
||||
* @return {@link Storage} class
|
||||
*/
|
||||
public static Storage getStorage() {
|
||||
return storage;
|
||||
}
|
||||
|
||||
public static Logger getLogger() {
|
||||
return log;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,115 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class AchievementDao {
|
||||
public static Map<Integer, AchievementInfo> getAchievements() {
|
||||
Map<Integer, AchievementInfo> achievementsList = new HashMap<>();
|
||||
|
||||
Connection connection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
connection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM achievements WHERE disabled = 0", connection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
var info = new AchievementInfo(
|
||||
resultSet.getInt("id"), resultSet.getString("achievement"),
|
||||
resultSet.getInt("level"), resultSet.getInt("reward_pixels"),
|
||||
resultSet.getInt("progress_needed"));
|
||||
|
||||
achievementsList.put(info.getId(), info);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(connection);
|
||||
}
|
||||
|
||||
return achievementsList;
|
||||
}
|
||||
|
||||
public static List<UserAchievement> getUserAchievements(int id) {
|
||||
List<UserAchievement> achievementsList = new ArrayList<>();
|
||||
|
||||
Connection connection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
connection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users_achievements WHERE user_id = ?", connection);
|
||||
preparedStatement.setInt(1, id);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
achievementsList.add(new UserAchievement(
|
||||
resultSet.getInt("achievement_id"), resultSet.getInt("user_id"), resultSet.getInt("progress")));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(connection);
|
||||
}
|
||||
|
||||
return achievementsList;
|
||||
|
||||
}
|
||||
|
||||
public static void newUserAchievement(int userId, UserAchievement userAchievement) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_achievements (achievement_id, user_id, progress) VALUES (?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userAchievement.getAchievementInfo().getId());
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.setInt(3, userAchievement.getProgress());
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveUserAchievement(int userId, UserAchievement userAchievement) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users_achievements SET progress = ? WHERE user_id = ? AND achievement_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userAchievement.getProgress());
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.setInt(3, userAchievement.getAchievementInfo().getId());
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,132 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.ads.Advertisement;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
|
||||
public class AdvertisementsDao {
|
||||
public static Map<Integer, List<Advertisement>> getAds() {
|
||||
Map<Integer, List<Advertisement>> roomAds = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms_ads", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
int roomId = resultSet.getInt("room_id");
|
||||
String image = resultSet.getString("image");
|
||||
String url = resultSet.getString("url");
|
||||
|
||||
if (!roomAds.containsKey(roomId)) {
|
||||
roomAds.put(roomId, new ArrayList<>());
|
||||
}
|
||||
|
||||
roomAds.get(roomId).add(new Advertisement(resultSet.getInt("id"), resultSet.getBoolean("is_loading_ad"), roomId, image, url, resultSet.getBoolean("enabled")));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return roomAds;
|
||||
}
|
||||
|
||||
public static void updateAds(Collection<Advertisement> ads) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE rooms_ads SET room_id = ?, image = ?, url = ?, enabled = ?, is_loading_ad = ? WHERE id = ?", sqlConnection);
|
||||
sqlConnection.setAutoCommit(false);
|
||||
|
||||
for (var ad : ads) {
|
||||
preparedStatement.setInt(1, ad.getRoomId());
|
||||
|
||||
if (ad.getImage().isBlank()) {
|
||||
preparedStatement.setNull(2, Types.VARCHAR);
|
||||
} else {
|
||||
preparedStatement.setString(2, ad.getImage());
|
||||
}
|
||||
|
||||
if (ad.getUrl().isBlank()) {
|
||||
preparedStatement.setNull(3, Types.VARCHAR);
|
||||
} else {
|
||||
preparedStatement.setString(3, ad.getUrl());
|
||||
}
|
||||
|
||||
preparedStatement.setBoolean(4, ad.isEnabled());
|
||||
preparedStatement.setBoolean(5, ad.isLoadingAd());
|
||||
preparedStatement.setInt(6, ad.getId());
|
||||
preparedStatement.addBatch();
|
||||
}
|
||||
|
||||
preparedStatement.executeBatch();
|
||||
sqlConnection.setAutoCommit(true);
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteAd(int id) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM rooms_ads WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, id);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void create(int roomId, String url, String image, boolean isEnabled, boolean isRoomLoadingAd) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO rooms_ads (room_id, url, image, enabled, is_loading_ad) VALUES (?, ?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, roomId);
|
||||
|
||||
if (url.isBlank()) {
|
||||
preparedStatement.setNull(2, Types.VARCHAR);
|
||||
} else {
|
||||
preparedStatement.setString(2, url);
|
||||
}
|
||||
|
||||
if (image.isBlank()) {
|
||||
preparedStatement.setNull(3, Types.VARCHAR);
|
||||
} else {
|
||||
preparedStatement.setString(3, image);
|
||||
}
|
||||
|
||||
preparedStatement.setInt(4, isEnabled ? 1 : 0);
|
||||
preparedStatement.setInt(5, isRoomLoadingAd ? 1 : 0);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,191 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.alerts.AccountAlert;
|
||||
import org.alexdev.havana.game.alerts.AlertType;
|
||||
import org.alexdev.havana.game.messenger.MessengerUser;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class AlertsDao {
|
||||
public static List<AccountAlert> getAlerts(int userId) {
|
||||
List<AccountAlert> alerts = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM cms_alerts WHERE user_id = ? ORDER BY created_at DESC", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
alerts.add(fill(resultSet));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return alerts;
|
||||
}
|
||||
|
||||
public static void createAlert(int userId, AlertType alertType, String message) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO cms_alerts (user_id, alert_type, message) VALUES (?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setString(2, alertType.name());
|
||||
preparedStatement.setString(3, message);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteAlerts(int userId, AlertType alertType) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM cms_alerts WHERE user_id = ? AND alert_type = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setString(2, alertType.name());
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void disableAlerts(int userId, AlertType alertType) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE cms_alerts SET is_disabled = 1 WHERE user_id = ? AND alert_type = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setString(2, alertType.name());
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
private static AccountAlert fill(ResultSet resultSet) throws SQLException {
|
||||
return new AccountAlert(resultSet.getInt("id"), resultSet.getInt("user_id"), AlertType.valueOf(resultSet.getString("alert_type")),
|
||||
resultSet.getString("message"), resultSet.getBoolean("is_disabled"), resultSet.getTime("created_at").getTime() / 1000L);
|
||||
}
|
||||
|
||||
public static Map<Integer, MessengerUser> getOnlineFriends(int userId) {
|
||||
Map<Integer, MessengerUser> friends = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT id,username,figure,motto,last_online,sex,allow_stalking,is_online,category_id,online_status_visible FROM messenger_friends INNER JOIN users ON messenger_friends.from_id = users.id WHERE to_id = ? AND is_online = 1", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
int resultUserId = resultSet.getInt("id");
|
||||
friends.put(resultUserId, new MessengerUser(resultUserId, resultSet.getString("username"), resultSet.getString("figure"),
|
||||
resultSet.getString("sex"), resultSet.getString("motto"), resultSet.getTime("last_online").getTime() / 1000L,
|
||||
resultSet.getBoolean("allow_stalking"), resultSet.getInt("category_id"),
|
||||
resultSet.getBoolean("is_online"), resultSet.getBoolean("online_status_visible")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return friends;
|
||||
}
|
||||
|
||||
public static int countRequests(int userId) {
|
||||
int count = 0;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT COUNT(*) FROM messenger_requests WHERE to_id = " + userId, sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
count = resultSet.getInt(1);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
public static void deleteAlert(int userId, int id) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM cms_alerts WHERE user_id = ? AND id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, id);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,283 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.badges.Badge;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class BadgeDao {
|
||||
public static Map<Integer, List<String>> getRoomBadges() {
|
||||
Map<Integer, List<String>> badges = new ConcurrentHashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms_entry_badges", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
int roomId = resultSet.getInt("room_id");
|
||||
String badgeCode = resultSet.getString("badge");
|
||||
|
||||
if (!badges.containsKey(roomId)) {
|
||||
badges.put(roomId, new ArrayList<>());
|
||||
}
|
||||
|
||||
badges.get(roomId).add(badgeCode);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return badges;
|
||||
}
|
||||
|
||||
|
||||
public static void deleteRoomBadge(String roomId, String badgeCode) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM rooms_entry_badges WHERE room_id = ? AND badge = ?", sqlConnection);
|
||||
preparedStatement.setString(1, roomId);
|
||||
preparedStatement.setString(2, badgeCode);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void createEntryBadge(int roomId, String badgeCode) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO rooms_entry_badges (room_id, badge) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, roomId);
|
||||
preparedStatement.setString(2, badgeCode);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void updateBadges(Map<Integer, List<String>> badges) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM rooms_entry_badges", sqlConnection);
|
||||
preparedStatement.execute();
|
||||
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO rooms_entry_badges (room_id, badge) VALUES (?, ?)", sqlConnection);
|
||||
sqlConnection.setAutoCommit(false);
|
||||
|
||||
for (var badgeData : badges.entrySet()) {
|
||||
for (var badge : badgeData.getValue()) {
|
||||
preparedStatement.setInt(1, badgeData.getKey());
|
||||
preparedStatement.setString(2, badge);
|
||||
preparedStatement.addBatch();
|
||||
}
|
||||
}
|
||||
|
||||
preparedStatement.executeBatch();
|
||||
sqlConnection.setAutoCommit(true);
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Badge> getBadges(int userId) {
|
||||
List<Badge> ranks = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users_badges WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
ranks.add(new Badge(resultSet.getString("badge"), resultSet.getBoolean("equipped"), resultSet.getInt("slot_id")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return ranks;
|
||||
}
|
||||
|
||||
public static void newBadge(int userId, String badgeCode) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_badges (user_id, badge) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setString(2, badgeCode);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeBadge(int userId, String badgeCode) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM users_badges WHERE user_id = ? AND badge = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setString(2, badgeCode);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeBadge(String badgeCode) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM users_badges WHERE badge = ?", sqlConnection);
|
||||
preparedStatement.setString(1, badgeCode);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveBadgeChanges(int userId, String badgeCode, boolean isEquipped, int slotId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users_badges SET equipped = ?, slot_id = ? WHERE user_id = ? AND badge = ?", sqlConnection);
|
||||
preparedStatement.setBoolean(1, isEquipped);
|
||||
preparedStatement.setInt(2, slotId);
|
||||
preparedStatement.setInt(3, userId);
|
||||
preparedStatement.setString(4, badgeCode);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void saveBadgeChanges(int userId, Set<Badge> badgesToSave) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users_badges SET equipped = ?, slot_id = ? WHERE user_id = ? AND badge = ?", sqlConnection);
|
||||
sqlConnection.setAutoCommit(false);
|
||||
|
||||
for (Badge badge : badgesToSave) {
|
||||
preparedStatement.setBoolean(1, badge.isEquipped());
|
||||
preparedStatement.setInt(2, badge.getSlotId());
|
||||
preparedStatement.setInt(3, userId);
|
||||
preparedStatement.setString(4, badge.getBadgeCode());
|
||||
preparedStatement.addBatch();
|
||||
}
|
||||
|
||||
preparedStatement.executeBatch();
|
||||
sqlConnection.setAutoCommit(true);
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all rank badges
|
||||
*
|
||||
* @return list of badges
|
||||
*/
|
||||
public static List<String> getRankBadges() {
|
||||
List<String> badges = new ArrayList<>();
|
||||
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
stmt = Storage.getStorage().prepare("SELECT badge FROM rank_badges", conn);
|
||||
row = stmt.executeQuery();
|
||||
|
||||
while (row.next()) {
|
||||
badges.add(row.getString("badge"));
|
||||
}
|
||||
} catch (Exception err) {
|
||||
Storage.logError(err);
|
||||
} finally {
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(stmt);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
|
||||
return badges;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,144 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.ban.Ban;
|
||||
import org.alexdev.havana.game.ban.BanType;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class BanDao {
|
||||
public static Pair<String, Long> hasBan(BanType banType, String value) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
Pair<String, Long> banned = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users_bans WHERE banned_value = ? AND ban_type = ? AND banned_until > CURRENT_TIMESTAMP() AND is_active = 1 ORDER BY banned_until DESC LIMIT 1", sqlConnection);
|
||||
preparedStatement.setString(1, value);
|
||||
preparedStatement.setString(2, banType.name());
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
banned = Pair.of(
|
||||
resultSet.getString("message"),
|
||||
resultSet.getTime("banned_until").getTime() / 1000L
|
||||
);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return banned;
|
||||
}
|
||||
|
||||
public static String getName(String machineId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
String name = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT username FROM users WHERE machine_id = ?", sqlConnection);
|
||||
preparedStatement.setString(1, machineId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
name = resultSet.getString("username");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
public static void addBan(BanType banType, String value, long bannedUntil, String message, int bannedBy) {
|
||||
if (value.isBlank())
|
||||
return;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_bans (banned_value, ban_type, banned_until, message, banned_by) VALUES (?, ?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setString(1, value);
|
||||
preparedStatement.setString(2, banType.name());
|
||||
preparedStatement.setTimestamp(3, new java.sql.Timestamp(bannedUntil * 1000L));
|
||||
preparedStatement.setString(4, message);
|
||||
preparedStatement.setInt(5, bannedBy);
|
||||
preparedStatement.executeQuery();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeBan(BanType banType, String value) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
//preparedStatement = Storage.getStorage().prepare("DELETE FROM users_bans WHERE banned_value = ? AND ban_type = ?", sqlConnection);
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users_bans SET is_active = 0 WHERE banned_value = ? AND ban_type = ?", sqlConnection);
|
||||
preparedStatement.setString(1, value);
|
||||
preparedStatement.setString(2, banType.name());
|
||||
preparedStatement.executeQuery();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Ban> getActiveBans() {
|
||||
List<Ban> banList = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users_bans WHERE is_active = 1 ORDER BY banned_at DESC", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
banList.add(new Ban(BanType.valueOf(resultSet.getString("ban_type")), resultSet.getString("banned_value"), resultSet.getString("message"), resultSet.getTime("banned_until").getTime() / 1000L,
|
||||
resultSet.getTime("banned_at").getTime() / 1000L, resultSet.getInt("banned_by")));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return banList;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.ban.BanType;
|
||||
import org.alexdev.havana.game.bot.BotData;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class BotDao {
|
||||
public static List<BotData> getBotData(int roomId) {
|
||||
List<BotData> botData = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms_bots WHERE room_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, roomId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
//a(String name, String mission, int x, int y, String headRotation, String bodyRotation, String figure, String walkspace) {
|
||||
botData.add(new BotData(
|
||||
resultSet.getString("name"),
|
||||
resultSet.getString("mission"),
|
||||
resultSet.getInt("x"),
|
||||
resultSet.getInt("y"),
|
||||
Integer.parseInt(resultSet.getString("start_look").split(",")[0]),
|
||||
Integer.parseInt(resultSet.getString("start_look").split(",")[1]),
|
||||
resultSet.getString("figure"),
|
||||
resultSet.getString("walkspace"),
|
||||
resultSet.getString("speech"),
|
||||
resultSet.getString("response"),
|
||||
resultSet.getString("unrecognised_response"),
|
||||
resultSet.getString("hand_items")
|
||||
));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return botData;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,186 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.catalogue.CatalogueItem;
|
||||
import org.alexdev.havana.game.catalogue.CataloguePackage;
|
||||
import org.alexdev.havana.game.catalogue.CataloguePage;
|
||||
import org.alexdev.havana.game.player.PlayerRank;
|
||||
import org.alexdev.havana.util.StringUtil;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class CatalogueDao {
|
||||
|
||||
public static Map<String, List<String>> getBadgeRewards() {
|
||||
Map<String, List<String>> badges = new ConcurrentHashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM catalogue_sale_badges", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
String saleCode = resultSet.getString("sale_code");
|
||||
String badgeCode = resultSet.getString("badge_code");
|
||||
|
||||
if (!badges.containsKey(saleCode)) {
|
||||
badges.put(saleCode, new ArrayList<>());
|
||||
}
|
||||
|
||||
badges.get(saleCode).add(badgeCode);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return badges;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the catalogue pages.
|
||||
*
|
||||
* @return the list of catalogue pages
|
||||
*/
|
||||
public static List<CataloguePage> getPages() {
|
||||
List<CataloguePage> pages = new ArrayList<>();
|
||||
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
stmt = Storage.getStorage().prepare("SELECT * FROM catalogue_pages ORDER BY order_id ASC", conn);
|
||||
row = stmt.executeQuery();
|
||||
|
||||
while (row.next()) {
|
||||
CataloguePage page = new CataloguePage(row.getInt("id"), row.getInt("parent_id"), PlayerRank.getRankForId(row.getInt("min_role")),
|
||||
row.getBoolean("is_navigatable"), row.getBoolean("is_club_only"), row.getString("name"), row.getInt("icon"), row.getInt("colour"),
|
||||
row.getString("layout"),
|
||||
StringUtil.GSON.fromJson(row.getString("images"), new TypeToken<List<String>>(){}.getType()),
|
||||
StringUtil.GSON.fromJson(row.getString("texts"), new TypeToken<List<String>>(){}.getType()),
|
||||
row.getString("seasonal_start"), row.getInt("seasonal_length"));
|
||||
|
||||
pages.add(page);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(stmt);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
|
||||
return pages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the catalogue items.
|
||||
*
|
||||
* @return the list of catalogue items
|
||||
*/
|
||||
public static List<CatalogueItem> getItems() {
|
||||
List<CatalogueItem> pages = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM catalogue_items ORDER BY order_id ASC", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
CatalogueItem item = new CatalogueItem(resultSet.getInt("id"), resultSet.getString("sale_code"), resultSet.getString("page_id"),
|
||||
resultSet.getInt("order_id"), resultSet.getInt("price_coins"), resultSet.getInt("price_pixels"),
|
||||
resultSet.getInt("seasonal_coins"), resultSet.getInt("seasonal_pixels"), resultSet.getInt("amount"),
|
||||
resultSet.getBoolean("hidden"), resultSet.getInt("definition_id"), resultSet.getString("item_specialspriteid"), resultSet.getBoolean("is_package"),
|
||||
resultSet.getString("active_at"));
|
||||
|
||||
pages.add(item);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return pages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the catalogue packages.
|
||||
*
|
||||
* @return the list of catalogue packages
|
||||
*/
|
||||
public static List<CataloguePackage> getPackages() {
|
||||
List<CataloguePackage> packages = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM catalogue_packages", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
CataloguePackage cataloguePackage = new CataloguePackage(resultSet.getString("salecode"), resultSet.getInt("definition_id"),
|
||||
resultSet.getString("special_sprite_id"), resultSet.getInt("amount"));
|
||||
|
||||
packages.add(cataloguePackage);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return packages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save catalogue item price.
|
||||
*/
|
||||
public static void setPrice(String saleCode, int price) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE catalogue_items SET price = ? WHERE sale_code = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, price);
|
||||
preparedStatement.setString(2, saleCode);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,91 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class ClubGiftDao {
|
||||
public static Pair<Long, String> getLastGift(int userId) {
|
||||
Pair<Long, String> giftData = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users_club_gifts WHERE user_id = ? ORDER BY date_received DESC LIMIT 1", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
giftData = Pair.of(resultSet.getTime("date_received").getTime(), resultSet.getString("sprite"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return giftData;
|
||||
}
|
||||
|
||||
public static void incrementGiftData(long nextGiftDate) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users_statistics SET gifts_due = gifts_due + 1, club_gift_due = FROM_UNIXTIME(UNIX_TIMESTAMP() + " + nextGiftDate + ") WHERE CURRENT_TIMESTAMP() > club_gift_due;", sqlConnection);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void addGift(int userId, String sprite) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_club_gifts (user_id, sprite) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setString(2, sprite);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void clearGiftHistory(int userId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM users_club_gifts WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.catalogue.collectables.CollectableData;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class CollectablesDao {
|
||||
public static List<CollectableData> getCollectablesData() {
|
||||
List<CollectableData> collectableData = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM catalogue_collectables", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
collectableData.add(new CollectableData(resultSet.getInt("store_page"), resultSet.getInt("admin_page"), resultSet.getLong("expiry"),
|
||||
resultSet.getLong("lifetime"), resultSet.getInt("current_position"), resultSet.getString("class_names").split(",")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return collectableData;
|
||||
}
|
||||
|
||||
public static void saveData(int storePage, int currentPosition, long expiry) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE catalogue_collectables SET expiry = ?, current_position = ? WHERE store_page = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, expiry);
|
||||
preparedStatement.setInt(2, currentPosition);
|
||||
preparedStatement.setInt(3, storePage);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,757 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.games.player.GameRank;
|
||||
import org.alexdev.havana.game.player.PlayerDetails;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class CurrencyDao {
|
||||
|
||||
/**
|
||||
* Atomically increase credits.
|
||||
*/
|
||||
public static void increaseCredits(Map<PlayerDetails, Integer> playerMap) {
|
||||
Connection conn = null;
|
||||
PreparedStatement updateQuery = null;
|
||||
PreparedStatement fetchQuery = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
conn.setAutoCommit(false);
|
||||
updateQuery = Storage.getStorage().prepare("UPDATE users SET credits = credits + ? WHERE id = ?", conn);
|
||||
|
||||
// Batch increase update queries
|
||||
for (var kvp : playerMap.entrySet()) {
|
||||
PlayerDetails playerDetails = kvp.getKey();
|
||||
int increaseAmount = kvp.getValue();
|
||||
|
||||
updateQuery.setInt(1, increaseAmount);
|
||||
updateQuery.setInt(2, playerDetails.getId());
|
||||
|
||||
updateQuery.addBatch();
|
||||
}
|
||||
|
||||
updateQuery.executeBatch();
|
||||
|
||||
List<String> playerIds = new ArrayList<>();
|
||||
|
||||
for (var player : playerMap.keySet()) {
|
||||
playerIds.add(Integer.toString(player.getId()));
|
||||
}
|
||||
|
||||
String rawPlayerBind = String.join(",", playerIds);
|
||||
|
||||
// Fetch increased amount
|
||||
// TODO: find better way to write the IN clause
|
||||
// TODO: use temporary table when playerIds list is above max arguments of SQL IN function or size above max_allowed_packet MariaDB configuration setting
|
||||
fetchQuery = Storage.getStorage().prepare("SELECT id,credits FROM users WHERE id IN (" + rawPlayerBind + ")", conn);
|
||||
row = fetchQuery.executeQuery();
|
||||
|
||||
conn.commit();
|
||||
|
||||
Map<Integer, Integer> updatedAmounts = new HashMap<>();
|
||||
|
||||
while (row != null && row.next()) {
|
||||
updatedAmounts.put(row.getInt("id"), row.getInt("credits"));
|
||||
}
|
||||
|
||||
for (var kvp : updatedAmounts.entrySet()) {
|
||||
var userId = kvp.getKey();
|
||||
var amount = kvp.getValue();
|
||||
|
||||
for (var details : playerMap.keySet()) {
|
||||
if (details.getId() != userId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
details.setCredits(amount);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
// Rollback these queries
|
||||
conn.rollback();
|
||||
} catch(SQLException re) {
|
||||
Storage.logError(re);
|
||||
}
|
||||
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
try {
|
||||
conn.setAutoCommit(true);
|
||||
} catch (SQLException ce) {
|
||||
Storage.logError(ce);
|
||||
}
|
||||
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(updateQuery);
|
||||
Storage.closeSilently(fetchQuery);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically increase credits.
|
||||
*/
|
||||
public static void increasePixels(Map<PlayerDetails, Integer> playerMap) {
|
||||
Connection conn = null;
|
||||
PreparedStatement updateQuery = null;
|
||||
PreparedStatement fetchQuery = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
conn.setAutoCommit(false);
|
||||
updateQuery = Storage.getStorage().prepare("UPDATE users SET pixels = pixels + ? WHERE id = ?", conn);
|
||||
|
||||
// Batch increase update queries
|
||||
for (var kvp : playerMap.entrySet()) {
|
||||
PlayerDetails playerDetails = kvp.getKey();
|
||||
int increaseAmount = kvp.getValue();
|
||||
|
||||
updateQuery.setInt(1, increaseAmount);
|
||||
updateQuery.setInt(2, playerDetails.getId());
|
||||
|
||||
updateQuery.addBatch();
|
||||
}
|
||||
|
||||
updateQuery.executeBatch();
|
||||
|
||||
List<String> playerIds = new ArrayList<>();
|
||||
|
||||
for (var player : playerMap.keySet()) {
|
||||
playerIds.add(Integer.toString(player.getId()));
|
||||
}
|
||||
|
||||
String rawPlayerBind = String.join(",", playerIds);
|
||||
|
||||
// Fetch increased amount
|
||||
// TODO: find better way to write the IN clause
|
||||
// TODO: use temporary table when playerIds list is above max arguments of SQL IN function or size above max_allowed_packet MariaDB configuration setting
|
||||
fetchQuery = Storage.getStorage().prepare("SELECT id,pixels FROM users WHERE id IN (" + rawPlayerBind + ")", conn);
|
||||
row = fetchQuery.executeQuery();
|
||||
|
||||
conn.commit();
|
||||
|
||||
Map<Integer, Integer> updatedAmounts = new HashMap<>();
|
||||
|
||||
while (row != null && row.next()) {
|
||||
updatedAmounts.put(row.getInt("id"), row.getInt("pixels"));
|
||||
}
|
||||
|
||||
for (var kvp : updatedAmounts.entrySet()) {
|
||||
var userId = kvp.getKey();
|
||||
var amount = kvp.getValue();
|
||||
|
||||
for (var details : playerMap.keySet()) {
|
||||
if (details.getId() != userId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
details.setPixels(amount);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
// Rollback these queries
|
||||
conn.rollback();
|
||||
} catch(SQLException re) {
|
||||
Storage.logError(re);
|
||||
}
|
||||
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
try {
|
||||
conn.setAutoCommit(true);
|
||||
} catch (SQLException ce) {
|
||||
Storage.logError(ce);
|
||||
}
|
||||
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(updateQuery);
|
||||
Storage.closeSilently(fetchQuery);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically increase credits.
|
||||
*
|
||||
* @param details the player details
|
||||
*/
|
||||
public static void increaseCredits(PlayerDetails details, int amount) {
|
||||
Connection conn = null;
|
||||
PreparedStatement updateQuery = null;
|
||||
PreparedStatement fetchQuery = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
|
||||
// We disable autocommit to make sure the following queries share the same atomic transaction
|
||||
conn.setAutoCommit(false);
|
||||
|
||||
// Increase credits
|
||||
updateQuery = Storage.getStorage().prepare("UPDATE users SET credits = credits + ? WHERE id = ?", conn);
|
||||
updateQuery.setInt(1, amount);
|
||||
updateQuery.setInt(2, details.getId());
|
||||
updateQuery.execute();
|
||||
|
||||
// Fetch increased amount
|
||||
fetchQuery = Storage.getStorage().prepare("SELECT credits FROM users WHERE id = ?", conn);
|
||||
fetchQuery.setInt(1, details.getId());
|
||||
row = fetchQuery.executeQuery();
|
||||
|
||||
// Commit these queries
|
||||
conn.commit();
|
||||
|
||||
// Set amount
|
||||
if (row != null && row.next()) {
|
||||
int updatedAmount = row.getInt("credits");
|
||||
details.setCredits(updatedAmount);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
// Rollback these queries
|
||||
conn.rollback();
|
||||
} catch(SQLException re) {
|
||||
Storage.logError(re);
|
||||
}
|
||||
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
try {
|
||||
conn.setAutoCommit(true);
|
||||
} catch (SQLException ce) {
|
||||
Storage.logError(ce);
|
||||
}
|
||||
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(updateQuery);
|
||||
Storage.closeSilently(fetchQuery);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically decrease credits.
|
||||
*
|
||||
* @param details the player details
|
||||
*/
|
||||
public static void decreaseCredits(PlayerDetails details, int amount) {
|
||||
if (details.getCredits() <= 0) {
|
||||
amount = 0;
|
||||
}
|
||||
|
||||
Connection conn = null;
|
||||
PreparedStatement updateQuery = null;
|
||||
PreparedStatement fetchQuery = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
|
||||
// We disable autocommit to make sure the following queries share the same atomic transaction
|
||||
conn.setAutoCommit(false);
|
||||
|
||||
// Decrease credits
|
||||
updateQuery = Storage.getStorage().prepare("UPDATE users SET credits = credits - ? WHERE id = ?", conn);
|
||||
updateQuery.setInt(1, amount);
|
||||
updateQuery.setInt(2, details.getId());
|
||||
updateQuery.execute();
|
||||
|
||||
// Fetch increased amount
|
||||
fetchQuery = Storage.getStorage().prepare("SELECT credits FROM users WHERE id = ?", conn);
|
||||
fetchQuery.setInt(1, details.getId());
|
||||
row = fetchQuery.executeQuery();
|
||||
|
||||
// Commit these queries
|
||||
conn.commit();
|
||||
|
||||
// Set amount
|
||||
if (row != null && row.next()) {
|
||||
int updatedAmount = row.getInt("credits");
|
||||
|
||||
if (updatedAmount < 0) {
|
||||
updatedAmount = 0;
|
||||
}
|
||||
|
||||
details.setCredits(updatedAmount);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
// Rollback these queries
|
||||
conn.rollback();
|
||||
} catch(SQLException re) {
|
||||
Storage.logError(re);
|
||||
}
|
||||
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
try {
|
||||
conn.setAutoCommit(true);
|
||||
} catch (SQLException ce) {
|
||||
Storage.logError(ce);
|
||||
}
|
||||
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(updateQuery);
|
||||
Storage.closeSilently(fetchQuery);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically decrease credits.
|
||||
*
|
||||
* @param details the player details
|
||||
*/
|
||||
public static void decreasePixels(PlayerDetails details, int amount) {
|
||||
if (details.getPixels() <= 0) {
|
||||
amount = 0;
|
||||
}
|
||||
|
||||
Connection conn = null;
|
||||
PreparedStatement updateQuery = null;
|
||||
PreparedStatement fetchQuery = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
|
||||
// We disable autocommit to make sure the following queries share the same atomic transaction
|
||||
conn.setAutoCommit(false);
|
||||
|
||||
// Decrease credits
|
||||
updateQuery = Storage.getStorage().prepare("UPDATE users SET pixels = pixels - ? WHERE id = ?", conn);
|
||||
updateQuery.setInt(1, amount);
|
||||
updateQuery.setInt(2, details.getId());
|
||||
updateQuery.execute();
|
||||
|
||||
// Fetch increased amount
|
||||
fetchQuery = Storage.getStorage().prepare("SELECT pixels FROM users WHERE id = ?", conn);
|
||||
fetchQuery.setInt(1, details.getId());
|
||||
row = fetchQuery.executeQuery();
|
||||
|
||||
// Commit these queries
|
||||
conn.commit();
|
||||
|
||||
// Set amount
|
||||
if (row != null && row.next()) {
|
||||
int updatedAmount = row.getInt("pixels");
|
||||
|
||||
if (updatedAmount < 0) {
|
||||
updatedAmount = 0;
|
||||
}
|
||||
|
||||
details.setPixels(updatedAmount);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
// Rollback these queries
|
||||
conn.rollback();
|
||||
} catch(SQLException re) {
|
||||
Storage.logError(re);
|
||||
}
|
||||
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
try {
|
||||
conn.setAutoCommit(true);
|
||||
} catch (SQLException ce) {
|
||||
Storage.logError(ce);
|
||||
}
|
||||
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(updateQuery);
|
||||
Storage.closeSilently(fetchQuery);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically increase credits.
|
||||
*
|
||||
* @param details the player details
|
||||
*/
|
||||
public static void increasePixels(PlayerDetails details, int amount) {
|
||||
Connection conn = null;
|
||||
PreparedStatement updateQuery = null;
|
||||
PreparedStatement fetchQuery = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
|
||||
// We disable autocommit to make sure the following queries share the same atomic transaction
|
||||
conn.setAutoCommit(false);
|
||||
|
||||
// Increase credits
|
||||
updateQuery = Storage.getStorage().prepare("UPDATE users SET pixels = pixels + ? WHERE id = ?", conn);
|
||||
updateQuery.setInt(1, amount);
|
||||
updateQuery.setInt(2, details.getId());
|
||||
updateQuery.execute();
|
||||
|
||||
// Fetch increased amount
|
||||
fetchQuery = Storage.getStorage().prepare("SELECT pixels FROM users WHERE id = ?", conn);
|
||||
fetchQuery.setInt(1, details.getId());
|
||||
row = fetchQuery.executeQuery();
|
||||
|
||||
// Commit these queries
|
||||
conn.commit();
|
||||
|
||||
// Set amount
|
||||
if (row != null && row.next()) {
|
||||
int updatedAmount = row.getInt("pixels");
|
||||
details.setPixels(updatedAmount);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
// Rollback these queries
|
||||
conn.rollback();
|
||||
} catch(SQLException re) {
|
||||
Storage.logError(re);
|
||||
}
|
||||
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
try {
|
||||
conn.setAutoCommit(true);
|
||||
} catch (SQLException ce) {
|
||||
Storage.logError(ce);
|
||||
}
|
||||
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(updateQuery);
|
||||
Storage.closeSilently(fetchQuery);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically increase tickets.
|
||||
*
|
||||
* @param details the player details
|
||||
*/
|
||||
public static void increaseTickets(PlayerDetails details, int amount) {
|
||||
Connection conn = null;
|
||||
PreparedStatement updateQuery = null;
|
||||
PreparedStatement fetchQuery = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
|
||||
// We disable autocommit to make sure the following queries share the same atomic transaction
|
||||
conn.setAutoCommit(false);
|
||||
|
||||
// Increase credits
|
||||
updateQuery = Storage.getStorage().prepare("UPDATE users SET tickets = tickets + ? WHERE id = ?", conn);
|
||||
updateQuery.setInt(1, amount);
|
||||
updateQuery.setInt(2, details.getId());
|
||||
updateQuery.execute();
|
||||
|
||||
// Fetch increased amount
|
||||
fetchQuery = Storage.getStorage().prepare("SELECT tickets FROM users WHERE id = ?", conn);
|
||||
fetchQuery.setInt(1, details.getId());
|
||||
row = fetchQuery.executeQuery();
|
||||
|
||||
// Commit these queries
|
||||
conn.commit();
|
||||
|
||||
// Set amount
|
||||
if (row != null && row.next()) {
|
||||
int updatedAmount = row.getInt("tickets");
|
||||
details.setTickets(updatedAmount);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
// Rollback these queries
|
||||
conn.rollback();
|
||||
} catch(SQLException re) {
|
||||
Storage.logError(re);
|
||||
}
|
||||
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
try {
|
||||
conn.setAutoCommit(true);
|
||||
} catch (SQLException ce) {
|
||||
Storage.logError(ce);
|
||||
}
|
||||
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(updateQuery);
|
||||
Storage.closeSilently(fetchQuery);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically decrease tickets.
|
||||
*
|
||||
* @param details the player details
|
||||
*/
|
||||
public static void decreaseTickets(PlayerDetails details, int amount) {
|
||||
if (details.getTickets() <= 0) {
|
||||
amount = 0;
|
||||
}
|
||||
|
||||
Connection conn = null;
|
||||
PreparedStatement updateQuery = null;
|
||||
PreparedStatement fetchQuery = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
|
||||
// We disable autocommit to make sure the following queries share the same atomic transaction
|
||||
conn.setAutoCommit(false);
|
||||
|
||||
// Decrease credits
|
||||
updateQuery = Storage.getStorage().prepare("UPDATE users SET tickets = tickets - ? WHERE id = ?", conn);
|
||||
updateQuery.setInt(1, amount);
|
||||
updateQuery.setInt(2, details.getId());
|
||||
updateQuery.execute();
|
||||
|
||||
// Fetch increased amount
|
||||
fetchQuery = Storage.getStorage().prepare("SELECT tickets FROM users WHERE id = ?", conn);
|
||||
fetchQuery.setInt(1, details.getId());
|
||||
row = fetchQuery.executeQuery();
|
||||
|
||||
// Commit these queries
|
||||
conn.commit();
|
||||
|
||||
// Set amount
|
||||
if (row != null && row.next()) {
|
||||
int updatedAmount = row.getInt("tickets");
|
||||
|
||||
if (updatedAmount < 0) {
|
||||
updatedAmount = 0;
|
||||
}
|
||||
|
||||
details.setTickets(updatedAmount);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
// Rollback these queries
|
||||
if (conn != null)
|
||||
conn.rollback();
|
||||
} catch (SQLException re) {
|
||||
Storage.logError(re);
|
||||
}
|
||||
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
try {
|
||||
if (conn != null)
|
||||
conn.setAutoCommit(true);
|
||||
} catch (SQLException ce) {
|
||||
Storage.logError(ce);
|
||||
}
|
||||
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(updateQuery);
|
||||
Storage.closeSilently(fetchQuery);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically increase tickets.
|
||||
*
|
||||
* @param details the player details
|
||||
*/
|
||||
public static void increaseFilm(PlayerDetails details, int amount) {
|
||||
Connection conn = null;
|
||||
PreparedStatement updateQuery = null;
|
||||
PreparedStatement fetchQuery = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
|
||||
// We disable autocommit to make sure the following queries share the same atomic transaction
|
||||
conn.setAutoCommit(false);
|
||||
|
||||
// Increase credits
|
||||
updateQuery = Storage.getStorage().prepare("UPDATE users SET film = film + ? WHERE id = ?", conn);
|
||||
updateQuery.setInt(1, amount);
|
||||
updateQuery.setInt(2, details.getId());
|
||||
updateQuery.execute();
|
||||
|
||||
// Fetch increased amount
|
||||
fetchQuery = Storage.getStorage().prepare("SELECT film FROM users WHERE id = ?", conn);
|
||||
fetchQuery.setInt(1, details.getId());
|
||||
row = fetchQuery.executeQuery();
|
||||
|
||||
// Commit these queries
|
||||
conn.commit();
|
||||
|
||||
// Set amount
|
||||
if (row != null && row.next()) {
|
||||
int updatedAmount = row.getInt("film");
|
||||
details.setFilm(updatedAmount);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
// Rollback these queries
|
||||
if (conn != null)
|
||||
conn.rollback();
|
||||
} catch(SQLException re) {
|
||||
Storage.logError(re);
|
||||
}
|
||||
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
try {
|
||||
if (conn != null)
|
||||
conn.setAutoCommit(true);
|
||||
} catch (SQLException ce) {
|
||||
Storage.logError(ce);
|
||||
}
|
||||
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(updateQuery);
|
||||
Storage.closeSilently(fetchQuery);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically decrease film.
|
||||
*
|
||||
* @param details the player details
|
||||
*/
|
||||
public static void decreaseFilm(PlayerDetails details, int amount) {
|
||||
if (details.getFilm() <= 0) {
|
||||
amount = 0;
|
||||
}
|
||||
|
||||
Connection conn = null;
|
||||
PreparedStatement updateQuery = null;
|
||||
PreparedStatement fetchQuery = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
|
||||
// We disable autocommit to make sure the following queries share the same atomic transaction
|
||||
conn.setAutoCommit(false);
|
||||
|
||||
// Increase credits
|
||||
updateQuery = Storage.getStorage().prepare("UPDATE users SET film = film - ? WHERE id = ?", conn);
|
||||
updateQuery.setInt(1, amount);
|
||||
updateQuery.setInt(2, details.getId());
|
||||
updateQuery.execute();
|
||||
|
||||
// Fetch increased amount
|
||||
fetchQuery = Storage.getStorage().prepare("SELECT film FROM users WHERE id = ?", conn);
|
||||
fetchQuery.setInt(1, details.getId());
|
||||
row = fetchQuery.executeQuery();
|
||||
|
||||
// Commit these queries
|
||||
conn.commit();
|
||||
|
||||
// Set amount
|
||||
if (row != null && row.next()) {
|
||||
int updatedAmount = row.getInt("film");
|
||||
|
||||
if (updatedAmount < 0) {
|
||||
updatedAmount = 0;
|
||||
}
|
||||
|
||||
details.setFilm(updatedAmount);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
// Rollback these queries
|
||||
if (conn != null)
|
||||
conn.rollback();
|
||||
} catch (SQLException re) {
|
||||
Storage.logError(re);
|
||||
}
|
||||
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
try {
|
||||
if (conn != null)
|
||||
conn.setAutoCommit(true);
|
||||
} catch (SQLException ce) {
|
||||
Storage.logError(ce);
|
||||
}
|
||||
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(updateQuery);
|
||||
Storage.closeSilently(fetchQuery);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
}
|
||||
|
||||
public static int getCredits(int userId) {
|
||||
int credits = 0;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT credits FROM users WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
credits = resultSet.getInt("credits");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return credits;
|
||||
}
|
||||
|
||||
|
||||
public static void updateEligibleCredits(int userId, boolean isCreditsEarnable) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users SET daily_coins_enabled = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, isCreditsEarnable ? 1 : 0);
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,158 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.effects.Effect;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
public class EffectDao {
|
||||
public static Map<Integer, Integer> getEffectTimes() {
|
||||
Map<Integer, Integer> effectTimes = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM settings_effects", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
effectTimes.put(resultSet.getInt("effect_id"), resultSet.getInt("duration_seconds"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return effectTimes;
|
||||
}
|
||||
|
||||
public static CopyOnWriteArrayList<Effect> getEffects(int userId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
CopyOnWriteArrayList<Effect> effects = new CopyOnWriteArrayList<>();
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users_effects WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
effects.add(new Effect(resultSet.getInt("id"), resultSet.getInt("user_id"), resultSet.getInt("effect_id"),
|
||||
resultSet.getLong("expiry_date"), resultSet.getBoolean("activated")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return effects;
|
||||
}
|
||||
|
||||
public static void removeEffects(int userId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM users_effects WHERE user_id = ? AND expiry_date < ? AND activated = 1", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setLong(2, DateUtil.getCurrentTimeSeconds());
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static Effect newEffect(int userId, int effectId, long expiryDate, boolean activated) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
Effect effect = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_effects (user_id, effect_id, expiry_date, activated) VALUES (?,?,?,?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, effectId);
|
||||
preparedStatement.setLong(3, expiryDate);
|
||||
preparedStatement.setBoolean(4, activated);
|
||||
preparedStatement.executeUpdate();
|
||||
|
||||
resultSet = preparedStatement.getGeneratedKeys();
|
||||
|
||||
if (resultSet.next()) {
|
||||
effect = new Effect(resultSet.getInt("id"), userId, effectId, expiryDate, activated);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return effect;
|
||||
}
|
||||
|
||||
public static void saveEffect(Effect effect) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users_effects SET activated = ?, expiry_date = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setBoolean(1, effect.isActivated());
|
||||
preparedStatement.setLong(2, effect.getExpireDate());
|
||||
preparedStatement.setInt(3, effect.getId());
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void deleteEffect(int id) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM users_effects WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, id);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,137 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.events.Event;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
public class EventsDao {
|
||||
public static void addEvent(int roomId, int userId, int categoryId, String name, String description, long expireTime, String tags) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO rooms_events (room_id, user_id, category_id, name, description, expire_time, tags) VALUES (?, ?, ?, ?, ?, ?, ?)", sqlConnection);
|
||||
|
||||
preparedStatement.setInt(1, roomId);
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.setInt(3, categoryId);
|
||||
preparedStatement.setString(4, name);
|
||||
preparedStatement.setString(5, description);
|
||||
preparedStatement.setLong(6, expireTime);
|
||||
preparedStatement.setString(7, tags);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeEvent(Event event) {
|
||||
removeEvents(List.of(event));
|
||||
}
|
||||
|
||||
|
||||
public static void removeEvents(List<Event> eventList) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM rooms_events WHERE room_id = ?", sqlConnection);
|
||||
sqlConnection.setAutoCommit(false);
|
||||
|
||||
for (Event event : eventList) {
|
||||
preparedStatement.setInt(1, event.getRoomId());
|
||||
preparedStatement.addBatch();
|
||||
}
|
||||
|
||||
preparedStatement.executeBatch();
|
||||
sqlConnection.setAutoCommit(true);
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeExpiredEvents() {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM rooms_events WHERE expire_time < ?", sqlConnection);
|
||||
preparedStatement.setLong(1, DateUtil.getCurrentTimeSeconds());
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Event> getEvents() {
|
||||
List<Event> eventMap = new CopyOnWriteArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms_events WHERE expire_time > ?", sqlConnection);
|
||||
preparedStatement.setLong(1, DateUtil.getCurrentTimeSeconds());
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
//Event(int roomId, int userId, int categoryId, String name, String description, long started)
|
||||
while (resultSet.next()) {
|
||||
eventMap.add(new Event(
|
||||
resultSet.getInt("room_id"), resultSet.getInt("user_id"),
|
||||
resultSet.getInt("category_id"), resultSet.getString("name"),
|
||||
resultSet.getString("description"), resultSet.getLong("expire_time"),
|
||||
resultSet.getString("tags")));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return eventMap;
|
||||
}
|
||||
|
||||
public static void save(Event event) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE rooms_events SET category_id = ?, name = ?, description = ?, tags = ? WHERE room_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, event.getCategoryId());
|
||||
preparedStatement.setString(2, event.getName());
|
||||
preparedStatement.setString(3, event.getDescription());
|
||||
preparedStatement.setString(4, String.join(",", event.getTags()));
|
||||
preparedStatement.setInt(5, event.getRoomId());
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,281 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.Havana;
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.games.GameSpawn;
|
||||
import org.alexdev.havana.game.games.enums.GameType;
|
||||
import org.alexdev.havana.game.games.battleball.BattleBallMap;
|
||||
import org.alexdev.havana.game.games.history.GameHistory;
|
||||
import org.alexdev.havana.game.games.history.GameHistoryData;
|
||||
import org.alexdev.havana.game.games.player.GameRank;
|
||||
import org.alexdev.havana.game.room.models.RoomModel;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.*;
|
||||
|
||||
public class GameDao {
|
||||
public static List<GameRank> getRanks() {
|
||||
List<GameRank> ranks = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM games_ranks", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
ranks.add(new GameRank(resultSet.getInt("id"), resultSet.getString("type"),
|
||||
resultSet.getString("title"), resultSet.getInt("min_points"),
|
||||
resultSet.getInt("max_points")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return ranks;
|
||||
}
|
||||
|
||||
public static List<RoomModel> getGameMaps() {
|
||||
List<RoomModel> maps = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM games_maps", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
String modelName = "bb" + "_arena_" + resultSet.getInt("map_id");
|
||||
|
||||
if (!resultSet.getString("game_type").equals("battleball")) {
|
||||
modelName = "ss_arena_" + resultSet.getInt("map_id");
|
||||
}
|
||||
|
||||
maps.add(new RoomModel(modelName, modelName, Integer.MAX_VALUE, Integer.MAX_VALUE, Double.MAX_VALUE, 0, resultSet.getString("heightmap"), null));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
|
||||
return maps;
|
||||
}
|
||||
|
||||
public static List<BattleBallMap> getBattleballTileMaps() {
|
||||
List<BattleBallMap> maps = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM games_maps WHERE game_type = 'battleball'", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
maps.add(new BattleBallMap(resultSet.getInt("map_id"), GameType.BATTLEBALL, resultSet.getString("tile_map")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
|
||||
return maps;
|
||||
}
|
||||
|
||||
public static List<GameSpawn> getGameSpawns() {
|
||||
List<GameSpawn> spawns = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM games_player_spawns", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
spawns.add(new GameSpawn(resultSet.getInt("team_id"), resultSet.getInt("map_id"), resultSet.getString("type"),
|
||||
resultSet.getInt("x"), resultSet.getInt("y"), resultSet.getInt("rotation")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
|
||||
return spawns;
|
||||
}
|
||||
|
||||
/*public static List<GameHistory> getTopTeams() {
|
||||
List<GameHistory> teams = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM games_played_history ORDER BY team_points DESC LIMIT 3", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
String json = resultSet.getString("player_scores");
|
||||
|
||||
try {
|
||||
GameHistoryData gamePlayedHistory = Havana.getGson().fromJson(json, GameHistoryData.class);
|
||||
teams.add(new GameHistory(resultSet.getInt("team_type"), gamePlayedHistory));
|
||||
} catch (Exception ex) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
|
||||
return teams;
|
||||
}
|
||||
|
||||
public static HashMap<String, Integer> getTopPlayers() {
|
||||
LinkedHashMap<String, Integer> players = new LinkedHashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT *,(battleball_points + snowstorm_points) AS game_points FROM users INNER JOIN users_statistics ON users_statistics.user_id = users.id ORDER BY (battleball_points + snowstorm_points) DESC LIMIT 5", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
players.put(resultSet.getString("username"), resultSet.getInt("game_points"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return players;
|
||||
}*/
|
||||
|
||||
|
||||
public static void resetMonthlyXp() {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users_statistics SET battleball_score_month = 0, snowstorm_score_month = 0, wobble_squabble_score_month = 0, xp_earned_month = 0 " +
|
||||
"WHERE (battleball_score_month > 0) OR (snowstorm_score_month > 0) OR (wobble_squabble_score_month > 0) OR (xp_earned_month > 0)", sqlConnection);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveTeamHistory(String uniqueId, String gameName, int mapCreator, int mapId, int winningTeam, int winningTeamScore, String extraData, GameType gameType, String gameHistoryData) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO games_played_history (id, game_name, game_creator, game_type, map_id, winning_team, winning_team_score, extra_data, team_data) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setString(1, uniqueId);
|
||||
preparedStatement.setString(2, gameName);
|
||||
preparedStatement.setInt(3, mapCreator);
|
||||
preparedStatement.setString(4, gameType.name());
|
||||
preparedStatement.setInt(5, mapId);
|
||||
preparedStatement.setInt(6, winningTeam);
|
||||
preparedStatement.setInt(7, winningTeamScore);
|
||||
preparedStatement.setString(8, extraData);
|
||||
preparedStatement.setString(9, gameHistoryData);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<GameHistory> getLastPlayedGames(GameType gameType) {
|
||||
List<GameHistory> games = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT games_played_history.*, users.username AS game_creator_name FROM games_played_history INNER JOIN users ON users.id = games_played_history.game_creator WHERE game_type = ? ORDER BY played_at DESC LIMIT 15", sqlConnection);
|
||||
preparedStatement.setString(1, gameType.name());
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
var gameHistory = new GameHistory(Havana.getGson().fromJson(resultSet.getString("team_data"), GameHistoryData.class));
|
||||
|
||||
gameHistory.setName(resultSet.getString("game_name"));
|
||||
gameHistory.setGameCreator(resultSet.getString("game_creator_name"));
|
||||
gameHistory.setMapId(resultSet.getInt("map_id"));
|
||||
gameHistory.setGameType(GameType.valueOf(resultSet.getString("game_type")));
|
||||
gameHistory.setWinningTeam(resultSet.getInt("winning_team"));
|
||||
gameHistory.setWinningTeamScore(resultSet.getInt("winning_team_score"));
|
||||
gameHistory.setExtraData(resultSet.getString("extra_data"));
|
||||
|
||||
games.add(gameHistory);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return games;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,437 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.groups.Group;
|
||||
import org.alexdev.havana.util.config.GameConfiguration;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class GroupDao {
|
||||
public static Group getGroup(int groupId) {
|
||||
Group group = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM groups_details WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
group = fill(resultSet);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return group;
|
||||
}
|
||||
|
||||
public static Group getGroupByAlias(String groupAlias) {
|
||||
Group group = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM groups_details WHERE alias = ?", sqlConnection);
|
||||
preparedStatement.setString(1, groupAlias);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
group = fill(resultSet);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return group;
|
||||
}
|
||||
|
||||
public static List<Group> getGroups(int userId) {
|
||||
List<Group> groupList = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM groups_details WHERE owner_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
groupList.add(fill(resultSet));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return groupList;
|
||||
}
|
||||
|
||||
public static List<Group> getJoinedGroups(int userId) {
|
||||
List<Group> groupList = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT " +
|
||||
"groups_details.* " +
|
||||
"FROM groups_memberships " +
|
||||
"RIGHT JOIN " +
|
||||
"groups_details ON groups_memberships.group_id = groups_details.id " +
|
||||
"WHERE owner_id = ? " +
|
||||
"OR (groups_memberships.user_id = ? AND groups_memberships.is_pending = 0)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
int groupId = resultSet.getInt("id");
|
||||
|
||||
if (groupList.stream().noneMatch(group -> group.getId() == groupId)) {
|
||||
groupList.add(fill(resultSet));
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return groupList.stream()
|
||||
.sorted(Comparator.comparingInt((Group group) -> group.getMemberCount(false)).reversed())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static int addGroup(String name, String description, int ownerId) {
|
||||
int groupId = 0;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO groups_details (name, description, owner_id) VALUES (?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setString(1, name);
|
||||
preparedStatement.setString(2, description);
|
||||
preparedStatement.setInt(3, ownerId);
|
||||
preparedStatement.executeQuery();
|
||||
resultSet = preparedStatement.getGeneratedKeys();
|
||||
|
||||
if (resultSet.next()) {
|
||||
groupId = resultSet.getInt(1);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
}
|
||||
|
||||
return groupId;
|
||||
}
|
||||
|
||||
public static int saveGroup(Group group) {
|
||||
int groupId = 0;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE groups_details SET name = ?, description = ?, room_id = ?, badge = ?, recommended = ?, group_type = ?, forum_type = ?, forum_premission = ?, alias = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setString(1, group.getName());
|
||||
preparedStatement.setString(2, group.getDescription());
|
||||
preparedStatement.setInt(3, group.getRoomId());
|
||||
preparedStatement.setString(4, group.getBadge());
|
||||
preparedStatement.setInt(5, group.isRecommended() ? 1 : 0);
|
||||
preparedStatement.setInt(6, group.getGroupType());
|
||||
preparedStatement.setInt(7, group.getForumType().getId());
|
||||
preparedStatement.setInt(8, group.getForumPermission().getId());
|
||||
|
||||
if (group.getAlias() == null || group.getAlias().isBlank()) {
|
||||
preparedStatement.setNull(9, Types.VARCHAR);
|
||||
}
|
||||
else {
|
||||
preparedStatement.setString(9, group.getAlias());
|
||||
}
|
||||
|
||||
preparedStatement.setInt(10, group.getId());
|
||||
preparedStatement.executeQuery();
|
||||
resultSet = preparedStatement.getGeneratedKeys();
|
||||
|
||||
if (resultSet.next()) {
|
||||
groupId = resultSet.getInt(1);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
}
|
||||
|
||||
return groupId;
|
||||
}
|
||||
|
||||
public static void saveBackground(Group group) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE groups_details SET background = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setString(1, group.getBackground());
|
||||
preparedStatement.setInt(2, group.getId());
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Group> querySearch(String query) {
|
||||
List<Group> groups = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM groups_details WHERE name LIKE ? LIMIT 30", sqlConnection);
|
||||
preparedStatement.setString(1, "%" + query + "%");
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
groups.add(fill(resultSet));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return groups;
|
||||
}
|
||||
|
||||
public static void saveBadge(Group group) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE groups_details SET badge = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setString(1, group.getBadge());
|
||||
preparedStatement.setInt(2, group.getId());
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
}
|
||||
}
|
||||
|
||||
public static String getGroupBadge(int groupId) {
|
||||
String group = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT badge FROM groups_details WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
group = resultSet.getString("badge");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return group;
|
||||
}
|
||||
|
||||
public static void delete(int groupId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM groups_details WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean hasGroupByAlias(String url) {
|
||||
boolean group = false;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM groups_details WHERE alias = ?", sqlConnection);
|
||||
preparedStatement.setString(1, url);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
group = true;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return group;
|
||||
}
|
||||
|
||||
public static void deleteHomeRoom(int roomId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE groups_details SET room_id = 0 WHERE room_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, roomId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static int getGroupOwner(int groupId) {
|
||||
int ownerId = 0;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT owner_id FROM groups_details WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
ownerId = resultSet.getInt("owner_id");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return ownerId;
|
||||
}
|
||||
|
||||
public static String getGroupName(int groupId) {
|
||||
String groupName = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT name FROM groups_details WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
groupName = resultSet.getString("name");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return groupName;
|
||||
}
|
||||
|
||||
public static Group fill(ResultSet resultSet) throws SQLException {
|
||||
return new Group(resultSet.getInt("id"), resultSet.getString("name"), resultSet.getString("description"), resultSet.getInt("owner_id"),
|
||||
resultSet.getInt("room_id"), resultSet.getString("badge"), resultSet.getBoolean("recommended"), resultSet.getString("background"), resultSet.getInt("views"),
|
||||
resultSet.getInt("topics"), resultSet.getInt("group_type"), resultSet.getInt("forum_type"), resultSet.getInt("forum_premission"),
|
||||
resultSet.getString("alias"), resultSet.getTime("created_at").getTime() / 1000L);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,338 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.groups.GroupMember;
|
||||
import org.alexdev.havana.game.groups.GroupMemberRank;
|
||||
import org.alexdev.havana.game.player.PlayerDetails;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class GroupMemberDao {
|
||||
/*public static List<GroupMember> getMembers(int groupId, boolean checkPending) {
|
||||
List<GroupMember> members = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM groups_memberships WHERE group_id = ? AND is_pending = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
preparedStatement.setInt(2, checkPending ? 1 : 0);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
members.add(fill(resultSet));//.getInt("user_id"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return members;
|
||||
}*/
|
||||
|
||||
public static List<GroupMember> getMembers(int groupId, boolean checkPending, String query, int page, int itemsPerPage) {
|
||||
List<GroupMember> members = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
if (!query.isBlank()) {
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM groups_memberships INNER JOIN users ON groups_memberships.user_id = users.id WHERE group_id = ? AND is_pending = ? AND username LIKE ? LIMIT " + ((page - 1) * itemsPerPage) + "," + itemsPerPage, sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
preparedStatement.setInt(2, checkPending ? 1 : 0);
|
||||
preparedStatement.setString(3, query + "%");
|
||||
} else {
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM groups_memberships INNER JOIN users ON groups_memberships.user_id = users.id WHERE group_id = ? AND is_pending = ? LIMIT " + ((page - 1) * itemsPerPage) + "," + itemsPerPage, sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
preparedStatement.setInt(2, checkPending ? 1 : 0);
|
||||
}
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
members.add(fill(resultSet));//.getInt("user_id"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return members;
|
||||
}
|
||||
|
||||
|
||||
public static GroupMember getMember(int groupId, int userId) {
|
||||
GroupMember member = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM groups_memberships WHERE group_id = ? AND user_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
preparedStatement.setInt(2, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
member = fill(resultSet);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return member;
|
||||
}
|
||||
|
||||
public static void addMember(int userId, int groupId, boolean insertPending) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO groups_memberships (user_id, group_id, is_pending) VALUES (?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, groupId);
|
||||
preparedStatement.setLong(3, insertPending ? 1 : 0);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void updateMember(int userId, int groupId, GroupMemberRank memberRank, boolean pendingStatus) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE groups_memberships SET is_pending = ?, member_rank = ? WHERE user_id = ? AND group_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, pendingStatus ? 1 : 0);
|
||||
preparedStatement.setString(2, String.valueOf(memberRank.getRankId()));
|
||||
preparedStatement.setInt(3, userId);
|
||||
preparedStatement.setInt(4, groupId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteMember(int userId, int groupId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM groups_memberships WHERE user_id = ? AND group_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, groupId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static Pair<Integer, Map<String, String>> getPendingMembers(int userId) {
|
||||
var groupData = new HashMap<String, String>();
|
||||
var groups = new HashMap<String, String>();
|
||||
int pendingMembers = 0;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT " +
|
||||
"groups_details.id AS group_id, " +
|
||||
"groups_details.name AS group_name " +
|
||||
"FROM groups_memberships " +
|
||||
"RIGHT JOIN " +
|
||||
"groups_details ON groups_memberships.group_id = groups_details.id " +
|
||||
"WHERE owner_id = ? " +
|
||||
"OR (groups_memberships.user_id = ? AND (groups_memberships.member_rank = '2' OR groups_memberships.member_rank = '3'))", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
int groupId = resultSet.getInt("group_id");
|
||||
String groupName = resultSet.getString("group_name");
|
||||
groupData.put(String.valueOf(groupId), groupName);
|
||||
}
|
||||
|
||||
if (groupData.size() > 0) {
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT " +
|
||||
"user_id, group_id " +
|
||||
"FROM groups_memberships " +
|
||||
"WHERE group_id IN (" + String.join(",", groupData.keySet()) + ") " +
|
||||
"AND is_pending = 1 GROUP BY group_id", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
int groupId = resultSet.getInt("group_id");
|
||||
|
||||
if (!groups.containsKey(String.valueOf(groupId))) {
|
||||
groups.put(String.valueOf(groupId), groupData.get(String.valueOf(groupId)));
|
||||
}
|
||||
|
||||
pendingMembers++;
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return Pair.of(pendingMembers, groups);
|
||||
}
|
||||
|
||||
public static int countMembers(int groupId, boolean isPending) {
|
||||
int count = 0;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT COUNT(*) AS member_count FROM groups_memberships WHERE group_id = ? AND is_pending = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
preparedStatement.setInt(2, isPending ? 1 : 0);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
count = resultSet.getInt("member_count");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
public static List<PlayerDetails> getOnlineMembersByFavourite(int groupId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
List<PlayerDetails> detailsList = new ArrayList<PlayerDetails>();
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users WHERE favourite_group = ? AND is_online = 1 LIMIT 1", sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
PlayerDetails details = new PlayerDetails();
|
||||
PlayerDao.fill(details, resultSet);
|
||||
|
||||
detailsList.add(details);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return detailsList;
|
||||
}
|
||||
|
||||
public static void resetFavourites(int groupId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users SET favourite_group = 0 WHERE favourite_group = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void deleteMembers(int groupId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM groups_memberships WHERE group_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
private static GroupMember fill(ResultSet resultSet) throws SQLException {
|
||||
return new GroupMember(resultSet.getInt("user_id"), resultSet.getInt("group_id"), resultSet.getBoolean("is_pending"), Integer.parseInt(resultSet.getString("member_rank")));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.player.guides.GuidingData;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class GuideDao {
|
||||
public static List<GuidingData> getGuidedBy(int userId) {
|
||||
List<GuidingData> users = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT id, username, last_online, online_time FROM users_statistics INNER JOIN users ON users.id = users_statistics.user_id WHERE guided_by = " + userId, sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
users.add(new GuidingData(resultSet.getInt("id"), resultSet.getString("username"), resultSet.getTime("last_online").getTime() / 1000L,
|
||||
resultSet.getLong("online_time")));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return users;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,119 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.games.enums.GameType;
|
||||
import org.alexdev.havana.game.games.history.ScoreEntry;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class HighscoreDao {
|
||||
public static List<ScoreEntry> getScores(int limit, GameType gameType, int page, boolean viewMontly) {
|
||||
List<ScoreEntry> scoreEntryList = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
StringBuilder query = new StringBuilder();
|
||||
query.append("SELECT users.username AS username,users_statistics.* FROM users_statistics INNER JOIN users ON users.id = users_statistics.user_id ");
|
||||
|
||||
if (viewMontly) {
|
||||
if (gameType == GameType.BATTLEBALL) {
|
||||
query.append("WHERE battleball_score_month > 0 ");
|
||||
}
|
||||
|
||||
if (gameType == GameType.SNOWSTORM) {
|
||||
query.append("WHERE snowstorm_score_month > 0 ");
|
||||
}
|
||||
|
||||
if (gameType == GameType.WOBBLE_SQUABBLE) {
|
||||
query.append("WHERE wobble_squabble_score_month > 0 ");
|
||||
}
|
||||
} else {
|
||||
if (gameType == GameType.BATTLEBALL) {
|
||||
query.append("WHERE battleball_score_all_time > 0 ");
|
||||
}
|
||||
|
||||
if (gameType == GameType.SNOWSTORM) {
|
||||
query.append("WHERE snowstorm_score_all_time > 0 ");
|
||||
}
|
||||
|
||||
if (gameType == GameType.WOBBLE_SQUABBLE) {
|
||||
query.append("WHERE wobble_squabble_score_all_time > 0 ");
|
||||
}
|
||||
}
|
||||
|
||||
query.append("AND ((SELECT COUNT(*) FROM users_bans WHERE banned_value = users.id AND ban_type = 'USER_ID' AND NOW() > banned_until AND is_active = 1) = 0) ");
|
||||
query.append("ORDER BY ");
|
||||
|
||||
if (viewMontly) {
|
||||
if (gameType == GameType.BATTLEBALL) {
|
||||
query.append("battleball_score_month DESC ");
|
||||
}
|
||||
|
||||
if (gameType == GameType.SNOWSTORM) {
|
||||
query.append("snowstorm_score_month DESC ");
|
||||
}
|
||||
|
||||
if (gameType == GameType.WOBBLE_SQUABBLE) {
|
||||
query.append("wobble_squabble_score_month DESC ");
|
||||
}
|
||||
} else {
|
||||
if (gameType == GameType.BATTLEBALL) {
|
||||
query.append("battleball_score_all_time DESC ");
|
||||
}
|
||||
|
||||
if (gameType == GameType.SNOWSTORM) {
|
||||
query.append("snowstorm_score_all_time DESC ");
|
||||
}
|
||||
|
||||
if (gameType == GameType.WOBBLE_SQUABBLE) {
|
||||
query.append("wobble_squabble_score_all_time DESC ");
|
||||
}
|
||||
}
|
||||
|
||||
query.append( "LIMIT " + ((page - 1) * limit) + "," + limit);
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare(query.toString(), sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
int position = ((page - 1) * limit) + 1;
|
||||
|
||||
while (resultSet.next()) {
|
||||
if (viewMontly) {
|
||||
if (gameType == GameType.BATTLEBALL) {
|
||||
scoreEntryList.add(new ScoreEntry(resultSet.getString("username"), resultSet.getLong("battleball_score_month"), position));
|
||||
} else if (gameType == GameType.SNOWSTORM) {
|
||||
scoreEntryList.add(new ScoreEntry(resultSet.getString("username"), resultSet.getLong("snowstorm_score_month"), position));
|
||||
} else if (gameType == GameType.WOBBLE_SQUABBLE) {
|
||||
scoreEntryList.add(new ScoreEntry(resultSet.getString("username"), resultSet.getLong("wobble_squabble_score_month"), position));
|
||||
}
|
||||
} else {
|
||||
if (gameType == GameType.BATTLEBALL) {
|
||||
scoreEntryList.add(new ScoreEntry(resultSet.getString("username"), resultSet.getLong("battleball_score_all_time"), position));
|
||||
} else if (gameType == GameType.SNOWSTORM) {
|
||||
scoreEntryList.add(new ScoreEntry(resultSet.getString("username"), resultSet.getLong("snowstorm_score_all_time"), position));
|
||||
} else if (gameType == GameType.WOBBLE_SQUABBLE) {
|
||||
scoreEntryList.add(new ScoreEntry(resultSet.getString("username"), resultSet.getLong("wobble_squabble_score_all_time"), position));
|
||||
}
|
||||
}
|
||||
position++;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return scoreEntryList;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,237 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.Havana;
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.infobus.InfobusPoll;
|
||||
import org.alexdev.havana.game.infobus.InfobusPollData;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class InfobusDao {
|
||||
public static List<InfobusPoll> getInfobusPolls() {
|
||||
List<InfobusPoll> polls = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM infobus_polls ORDER BY created_at DESC", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
polls.add(fill(resultSet));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return polls;
|
||||
}
|
||||
|
||||
public static int createInfobusPoll(int initiatedBy, InfobusPollData pollData) {
|
||||
int pollId = -1;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO infobus_polls (initiated_by, poll_data) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, initiatedBy);
|
||||
preparedStatement.setString(2, Havana.getGson().toJson(pollData));
|
||||
preparedStatement.execute();
|
||||
resultSet = preparedStatement.getGeneratedKeys();
|
||||
|
||||
if (resultSet.next()) {
|
||||
pollId = resultSet.getInt(1);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
|
||||
return pollId;
|
||||
}
|
||||
|
||||
public static void delete(int id) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM infobus_polls WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, id);
|
||||
preparedStatement.execute();
|
||||
} catch (SQLException e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static InfobusPoll get(int id) {
|
||||
InfobusPoll infobusPoll = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM infobus_polls WHERE id = ? LIMIT 1", sqlConnection);
|
||||
preparedStatement.setInt(1, id);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
infobusPoll = fill(resultSet);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return infobusPoll;
|
||||
}
|
||||
|
||||
public static void saveInfobusPoll(int id, InfobusPollData pollData) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE infobus_polls SET poll_data = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setString(1, Havana.getGson().toJson(pollData));
|
||||
preparedStatement.setInt(2, id);
|
||||
preparedStatement.execute();
|
||||
} catch (SQLException e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void addAnswer(int pollId, int answer, int userId) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO infobus_polls_answers (user_id, poll_id, answer) VALUES (?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, pollId);
|
||||
preparedStatement.setInt(3, answer);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean hasAnswer(int pollId, int userId) {
|
||||
boolean exists = false;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM infobus_polls_answers WHERE user_id = ? AND poll_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, pollId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
exists = resultSet.next();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return exists;
|
||||
}
|
||||
|
||||
public static Map<Integer, Integer> getAnswers(int pollId) {
|
||||
Map<Integer, Integer> answers = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT COUNT(*) AS votes, answer FROM infobus_polls_answers WHERE poll_id = ? GROUP BY answer", sqlConnection);
|
||||
preparedStatement.setInt(1, pollId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
answers.put(resultSet.getInt("answer"), resultSet.getInt("votes"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return answers;
|
||||
}
|
||||
|
||||
public static void clearAnswers(int pollId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM infobus_polls_answers WHERE poll_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, pollId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
private static InfobusPoll fill(ResultSet resultSet) throws SQLException {
|
||||
return new InfobusPoll(resultSet.getInt("id"), resultSet.getInt("initiated_by"),
|
||||
Havana.getGson().fromJson(resultSet.getString("poll_data"), InfobusPollData.class),
|
||||
resultSet.getTime("created_at").getTime() / 1000L);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,655 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.ecotron.EcotronItem;
|
||||
import org.alexdev.havana.game.item.Item;
|
||||
import org.alexdev.havana.game.item.base.ItemDefinition;
|
||||
import org.alexdev.havana.game.room.RoomData;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
public class ItemDao {
|
||||
|
||||
/**
|
||||
* Get the item definitions.
|
||||
*
|
||||
* @return the list of item definitions
|
||||
*/
|
||||
public static Map<Integer, ItemDefinition> getItemDefinitions() {
|
||||
Map<Integer, ItemDefinition> definitions = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM items_definitions", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
ItemDefinition definition = new ItemDefinition(resultSet.getInt("id"), resultSet.getString("sprite"),
|
||||
resultSet.getString("name"), resultSet.getString("description"),
|
||||
resultSet.getInt("sprite_id"), resultSet.getString("behaviour"), resultSet.getDouble("top_height"),
|
||||
resultSet.getInt("length"), resultSet.getInt("width"), resultSet.getInt("max_status"),
|
||||
resultSet.getString("interactor"), resultSet.getBoolean("is_tradable"),
|
||||
resultSet.getBoolean("is_recyclable"), resultSet.getString("drink_ids"), resultSet.getInt("rental_time"),
|
||||
resultSet.getString("allowed_rotations"), resultSet.getString("heights"));
|
||||
|
||||
definitions.put(definition.getId(), definition);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return definitions;
|
||||
}
|
||||
|
||||
public static Map<String, Integer> getItemVersions() {
|
||||
Map<String, Integer> definitions = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM furniture_versions", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
definitions.put(resultSet.getString("asset_name"), resultSet.getInt("version_id"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return definitions;
|
||||
}
|
||||
|
||||
public static List<EcotronItem> getEcotronItems() {
|
||||
List<EcotronItem> itemList = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM recycler_rewards ORDER BY order_id ASC", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
EcotronItem ecotronItem = new EcotronItem(resultSet.getString("sprite"), resultSet.getInt("chance"), resultSet.getInt("chance"));
|
||||
itemList.add(ecotronItem);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return itemList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new item entry with the definition id, user id and custom data. It will
|
||||
* override the current item id with its database id.
|
||||
*
|
||||
* @param item the item to create
|
||||
*/
|
||||
public static void newItem(Item item) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet row = null;
|
||||
|
||||
long itemId = 0;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO items (user_id, definition_id, custom_data, expire_time) VALUES (?,?,?,?)", sqlConnection);
|
||||
preparedStatement.setInt(1, item.getOwnerId());
|
||||
preparedStatement.setInt(2, item.getDefinition().getId());
|
||||
preparedStatement.setString(3, item.getCustomData());
|
||||
preparedStatement.setLong(4, item.getExpireTime());
|
||||
preparedStatement.executeUpdate();
|
||||
|
||||
row = preparedStatement.getGeneratedKeys();
|
||||
|
||||
if (row != null && row.next()) {
|
||||
itemId = row.getLong(1);
|
||||
}
|
||||
|
||||
} catch (SQLException e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
item.setDatabaseId(itemId);
|
||||
item.assignVirtualId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the inventory list of items.
|
||||
*
|
||||
* @param userId the id of the user to get the inventory for
|
||||
* @return the list of items
|
||||
*/
|
||||
public static List<Item> getInventory(int userId) {
|
||||
List<Item> items = new CopyOnWriteArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM items WHERE user_id = ? AND room_id = 0 ORDER BY order_id ASC", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
Item item = new Item();
|
||||
fill(item, resultSet);
|
||||
items.add(item);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the item by item id
|
||||
*
|
||||
* @param itemId the id of the item to to get
|
||||
* @return the item
|
||||
*/
|
||||
public static Item getItem(long itemId) {
|
||||
Item item = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM vw_items WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
item = new Item();
|
||||
fill(item, resultSet);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the room list of items.
|
||||
*
|
||||
* @return the list of items
|
||||
*/
|
||||
public static List<Item> getRoomItems(RoomData roomData) {
|
||||
List<Item> items = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM items WHERE room_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, roomData.getId());
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
Item item = new Item();
|
||||
item.assignVirtualId();
|
||||
fill(item, resultSet);
|
||||
items.add(item);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get expired items
|
||||
*
|
||||
* @return the list of expired items
|
||||
*/
|
||||
public static List<Item> getExpiredItems() {
|
||||
List<Item> items = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM items WHERE expire_time <> -1 AND expire_time < ?", sqlConnection);
|
||||
preparedStatement.setLong(1, DateUtil.getCurrentTimeSeconds());
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
Item item = new Item();
|
||||
item.assignVirtualId();
|
||||
fill(item, resultSet);
|
||||
items.add(item);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Redeem credit furniture atomicly
|
||||
*
|
||||
* @param amount credit amount to increase by
|
||||
* @param userID user ID
|
||||
*/
|
||||
public static int redeemCreditItem(int amount, long itemID, int userID) {
|
||||
int updatedAmount = -1;
|
||||
Connection conn = null;
|
||||
PreparedStatement deleteQuery = null;
|
||||
PreparedStatement updateQuery = null;
|
||||
PreparedStatement fetchQuery = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
|
||||
// We disable autocommit to make sure the following queries share the same atomic transaction
|
||||
conn.setAutoCommit(false);
|
||||
|
||||
deleteQuery = Storage.getStorage().prepare("DELETE FROM items WHERE id = ?", conn);
|
||||
deleteQuery.setLong(1, itemID);
|
||||
deleteQuery.execute();
|
||||
|
||||
// Increase credits
|
||||
updateQuery = Storage.getStorage().prepare("UPDATE users SET credits = credits + ? WHERE id = ?", conn);
|
||||
updateQuery.setInt(1, amount);
|
||||
updateQuery.setInt(2, userID);
|
||||
updateQuery.execute();
|
||||
|
||||
// Fetch increased amount
|
||||
fetchQuery = Storage.getStorage().prepare("SELECT credits FROM users WHERE id = ?", conn);
|
||||
fetchQuery.setInt(1, userID);
|
||||
row = fetchQuery.executeQuery();
|
||||
|
||||
// Commit these queries
|
||||
conn.commit();
|
||||
|
||||
// Set amount
|
||||
if (row != null && row.next()) {
|
||||
updatedAmount = row.getInt("credits");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
// Reset amount
|
||||
updatedAmount = -1;
|
||||
|
||||
try {
|
||||
// Rollback these queries
|
||||
conn.rollback();
|
||||
} catch(SQLException re) {
|
||||
Storage.logError(re);
|
||||
}
|
||||
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
try {
|
||||
conn.setAutoCommit(true);
|
||||
} catch (SQLException ce) {
|
||||
Storage.logError(ce);
|
||||
}
|
||||
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(deleteQuery);
|
||||
Storage.closeSilently(updateQuery);
|
||||
Storage.closeSilently(fetchQuery);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
|
||||
return updatedAmount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update item by item instance.
|
||||
*
|
||||
* @param item the instance of the item to update it
|
||||
*/
|
||||
public static void updateItem(Item item) {
|
||||
updateItems(List.of(item));
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an entire list of items at once.
|
||||
*
|
||||
* @param items the list of items
|
||||
*/
|
||||
public static void updateItems(Collection<Item> items) {
|
||||
if (items.size() > 0) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE items SET room_id = ?, definition_id = ?, x = ?, y = ?, z = ?, rotation = ?, wall_position = ?, custom_data = ?, order_id = ?, is_hidden = ? WHERE id = ?", sqlConnection);
|
||||
sqlConnection.setAutoCommit(false);
|
||||
|
||||
for (Item item : items) {
|
||||
preparedStatement.setInt(1, item.getRoomId());
|
||||
preparedStatement.setInt(2, item.getDefinition().getId());
|
||||
preparedStatement.setInt(3, item.getPosition().getX());
|
||||
preparedStatement.setInt(4, item.getPosition().getY());
|
||||
preparedStatement.setDouble(5, item.getPosition().getZ());
|
||||
preparedStatement.setInt(6, item.getPosition().getRotation());
|
||||
preparedStatement.setString(7, item.getWallPosition());
|
||||
preparedStatement.setString(8, item.getCustomData());
|
||||
preparedStatement.setInt(9, item.getOrderId());
|
||||
preparedStatement.setInt(10, item.isHidden() ? 1 : 0);
|
||||
preparedStatement.setLong(11, item.getDatabaseId());
|
||||
preparedStatement.addBatch();
|
||||
}
|
||||
|
||||
preparedStatement.executeBatch();
|
||||
sqlConnection.setAutoCommit(true);
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update item by item instance.
|
||||
*
|
||||
* @param item the instance of the item to update it
|
||||
*/
|
||||
public static void updateItemOwnership(Item item) {
|
||||
updateItemOwnership(List.of(item));
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an entire list of items at once.
|
||||
*
|
||||
* @param items the list of items
|
||||
*/
|
||||
public static void updateItemOwnership(Collection<Item> items) {
|
||||
if (items.size() > 0) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE items SET room_id = ?, user_id = ? WHERE id = ?", sqlConnection);
|
||||
sqlConnection.setAutoCommit(false);
|
||||
|
||||
for (Item item : items) {
|
||||
preparedStatement.setInt(1, item.getRoomId());
|
||||
preparedStatement.setInt(2, item.getOwnerId());
|
||||
preparedStatement.setLong(3, item.getDatabaseId());
|
||||
preparedStatement.addBatch();
|
||||
}
|
||||
|
||||
preparedStatement.executeBatch();
|
||||
sqlConnection.setAutoCommit(true);
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update item by item instance.
|
||||
*
|
||||
* @param item the instance of the item to update it
|
||||
*/
|
||||
public static void updateTradeState(Item item, boolean inTrade) {
|
||||
updateTradeStates(List.of(item), inTrade);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an entire list of items at once.
|
||||
*
|
||||
* @param items the list of items
|
||||
*/
|
||||
public static void updateTradeStates(Collection<Item> items, boolean inTrade) {
|
||||
if (items.size() > 0) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE items SET is_trading = ? WHERE id = ?", sqlConnection);
|
||||
sqlConnection.setAutoCommit(false);
|
||||
|
||||
for (Item item : items) {
|
||||
item.setInTrade(inTrade);
|
||||
|
||||
preparedStatement.setBoolean(1, item.isInTrade());
|
||||
preparedStatement.setLong(2, item.getDatabaseId());
|
||||
preparedStatement.addBatch();
|
||||
}
|
||||
|
||||
preparedStatement.executeBatch();
|
||||
sqlConnection.setAutoCommit(true);
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteItems(List<Long> items) {
|
||||
if (items.size() > 0) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM items WHERE id = ?", sqlConnection);
|
||||
sqlConnection.setAutoCommit(false);
|
||||
|
||||
for (Long itemId : items) {
|
||||
preparedStatement.setLong(1, itemId);
|
||||
preparedStatement.addBatch();
|
||||
}
|
||||
|
||||
preparedStatement.executeBatch();
|
||||
sqlConnection.setAutoCommit(true);
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void saveTotemExpire(int userId, long totemExpiration) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users SET totem_effect_expiry = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, totemExpiration);
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveTradeBanExpire(int userId, long tradeBanExpiration) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users SET trade_ban_expiration = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, tradeBanExpiration);
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void deleteHandItems(int userId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE items WHERE is_hidden = 0 AND is_trading = 0 AND room_id = 0 AND user_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the room list of items.
|
||||
*
|
||||
* @return the list of items
|
||||
*/
|
||||
public static List<Item> getUserItemsByDefinition(int userId, ItemDefinition definition) {
|
||||
List<Item> items = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM items WHERE user_id = ? AND definition_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, definition.getId());
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
Item item = new Item();
|
||||
item.assignVirtualId();
|
||||
fill(item, resultSet);
|
||||
items.add(item);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
public static void resetTradeStates() {
|
||||
try {
|
||||
Storage.getStorage().execute("UPDATE items SET is_trading = 0 WHERE is_trading > 0");
|
||||
} catch (SQLException e) {
|
||||
Storage.logError(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill item with data retrieved from the SQL query.
|
||||
*
|
||||
* @param item the item to fill data for
|
||||
* @param resultSet the result set returned with the data
|
||||
* @throws SQLException an exception if an error happened
|
||||
*/
|
||||
public static void fill(Item item, ResultSet resultSet) throws SQLException {
|
||||
item.fill(resultSet.getLong("id"), resultSet.getInt("order_id"), resultSet.getInt("user_id"), resultSet.getInt("room_id"),
|
||||
resultSet.getInt("definition_id"), resultSet.getInt("x"), resultSet.getInt("y"),
|
||||
resultSet.getDouble("z"), resultSet.getInt("rotation"), resultSet.getString("wall_position"),
|
||||
resultSet.getString("custom_data"), resultSet.getBoolean("is_hidden"), resultSet.getBoolean("is_trading"),
|
||||
resultSet.getLong("expire_time"), resultSet.getTime("created_at").getTime() / 1000L);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,163 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.song.jukebox.BurnedDisk;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class JukeboxDao {
|
||||
public static void addDisk(long itemId, int slotId, int songId) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO soundmachine_disks (item_id, slot_id, song_id, burned_at) VALUES (?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
preparedStatement.setInt(2, slotId);
|
||||
preparedStatement.setInt(3, songId);
|
||||
preparedStatement.setLong(4, DateUtil.getCurrentTimeSeconds());
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void editDisk(long itemId, long songMachineId, int slotId) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE soundmachine_disks SET soundmachine_id = ?, slot_id = ? WHERE item_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, songMachineId);
|
||||
preparedStatement.setInt(2, slotId);
|
||||
preparedStatement.setLong(3, itemId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<BurnedDisk> getDisks(long soundmachineId) {
|
||||
List<BurnedDisk> disks = new ArrayList<BurnedDisk>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM soundmachine_disks WHERE soundmachine_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, soundmachineId);
|
||||
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
disks.add(new BurnedDisk(resultSet.getLong("item_id"), resultSet.getInt("soundmachine_id"), resultSet.getInt("slot_id"),
|
||||
resultSet.getInt("song_id"), resultSet.getLong("burned_at")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return disks;
|
||||
}
|
||||
|
||||
public static BurnedDisk getDisk(long soundmachineId, int songId) {
|
||||
BurnedDisk disk = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM soundmachine_disks WHERE slot_id = ? AND soundmachine_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, songId);
|
||||
preparedStatement.setLong(2, soundmachineId);
|
||||
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
disk = new BurnedDisk(resultSet.getLong("item_id"), resultSet.getInt("soundmachine_id"), resultSet.getInt("slot_id"),
|
||||
resultSet.getInt("song_id"), resultSet.getLong("burned_at"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return disk;
|
||||
}
|
||||
|
||||
public static int getSongIdByItem(long itemId) {
|
||||
int songId = -1;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM soundmachine_disks WHERE item_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
songId = resultSet.getInt("song_id");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return songId;
|
||||
}
|
||||
|
||||
public static void setBurned(int songId, boolean burnedState) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE soundmachine_songs SET burnt = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, burnedState ? 1 : 0);
|
||||
preparedStatement.setInt(2, songId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
|
||||
public class LogDao {
|
||||
// DELETE FROM users_ip_logs WHERE UNIX_TIMESTAMP(created_at) < (UNIX_TIMESTAMP() - 10);
|
||||
// DELETE FROM users_ip_logs WHERE UNIX_TIMESTAMP(created_at) < (UNIX_TIMESTAMP() - 10);
|
||||
|
||||
// Delete rows more than 1 month old
|
||||
// DELETE FROM users_transactions WHERE UNIX_TIMESTAMP(created_at) < (UNIX_TIMESTAMP() - 2678400)
|
||||
|
||||
public static void deleteTradeLogs(int interval) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM users_transactions WHERE UNIX_TIMESTAMP(created_at) < (UNIX_TIMESTAMP() - ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, interval);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteIpAddressLogs(int interval) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM users_ip_logs WHERE UNIX_TIMESTAMP(created_at) < (UNIX_TIMESTAMP() - ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, interval);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteChatLogs(int interval) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM room_chatlogs WHERE timestamp < (UNIX_TIMESTAMP() - ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, interval);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,624 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.messenger.MessengerCategory;
|
||||
import org.alexdev.havana.game.messenger.MessengerMessage;
|
||||
import org.alexdev.havana.game.messenger.MessengerUser;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class MessengerDao {
|
||||
|
||||
/**
|
||||
* Gets the friends.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @return the friends
|
||||
*/
|
||||
public static Map<Integer, MessengerUser> getFriends(int userId) {
|
||||
Map<Integer, MessengerUser> friends = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT id,username,figure,motto,last_online,sex,allow_stalking,is_online,category_id,online_status_visible FROM messenger_friends INNER JOIN users ON messenger_friends.from_id = users.id WHERE to_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
int resultUserId = resultSet.getInt("id");
|
||||
friends.put(resultUserId, new MessengerUser(resultUserId, resultSet.getString("username"), resultSet.getString("figure"),
|
||||
resultSet.getString("sex"), resultSet.getString("motto"), resultSet.getTime("last_online").getTime() / 1000L,
|
||||
resultSet.getBoolean("allow_stalking"), resultSet.getInt("category_id"),
|
||||
resultSet.getBoolean("is_online"), resultSet.getBoolean("online_status_visible")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return friends;
|
||||
}
|
||||
|
||||
public static Map<Integer, MessengerUser> getFriendsPage(int userId, int range, int pageSize) {
|
||||
Map<Integer, MessengerUser> friends = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT id,username,figure,motto,last_online,sex,allow_stalking,is_online,category_id,online_status_visible FROM messenger_friends INNER JOIN users ON messenger_friends.from_id = users.id WHERE to_id = ? LIMIT " + (range * pageSize) + "," + ((range * pageSize) + pageSize), sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
int resultUserId = resultSet.getInt("id");
|
||||
friends.put(resultUserId, new MessengerUser(resultUserId, resultSet.getString("username"), resultSet.getString("figure"),
|
||||
resultSet.getString("sex"), resultSet.getString("motto"), resultSet.getTime("last_online").getTime() / 1000L,
|
||||
resultSet.getBoolean("allow_stalking"), resultSet.getInt("category_id"),
|
||||
resultSet.getBoolean("is_online"), resultSet.getBoolean("online_status_visible")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return friends;
|
||||
}
|
||||
|
||||
public static int getFriendsCount(int userId) {
|
||||
int count = 0;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT COUNT(*) FROM messenger_friends INNER JOIN users ON messenger_friends.from_id = users.id WHERE to_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
count = resultSet.getInt(1);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the requests.
|
||||
*
|
||||
* @param userId the user id
|
||||
* @return the requests
|
||||
*/
|
||||
public static Map<Integer, MessengerUser> getRequests(int userId) {
|
||||
Map<Integer, MessengerUser> users = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT from_id,username,figure,sex,motto,last_online,allow_stalking,is_online,online_status_visible FROM messenger_requests INNER JOIN users ON messenger_requests.from_id = users.id WHERE to_id = " + userId, sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
int fromId = resultSet.getInt("from_id");
|
||||
users.put(fromId, new MessengerUser(fromId, resultSet.getString("username"), resultSet.getString("figure"),
|
||||
resultSet.getString("sex"), resultSet.getString("motto"), resultSet.getTime("last_online").getTime() / 1000L,
|
||||
resultSet.getBoolean("allow_stalking"), 0,
|
||||
resultSet.getBoolean("is_online"), resultSet.getBoolean("online_status_visible")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return users;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search.
|
||||
*
|
||||
* @param query the query
|
||||
* @return the list
|
||||
*/
|
||||
public static List<Integer> search(String query) {
|
||||
List<Integer> userList = new ArrayList<>();
|
||||
int userId = -1;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT id FROM users WHERE LOWER(username) LIKE ? LIMIT 30", sqlConnection);
|
||||
preparedStatement.setString(1, query + "%");
|
||||
|
||||
/* preparedStatement = Storage.getStorage().prepare("SELECT id FROM users WHERE LOWER(username) LIKE ? ORDER BY (username = ?) DESC, length(username) LIMIT 30", sqlConnection);
|
||||
preparedStatement.setString(1, query + "%");
|
||||
preparedStatement.setString(2, query);*/
|
||||
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
userList.add(resultSet.getInt("id"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return userList;
|
||||
}
|
||||
|
||||
/**
|
||||
* New request.
|
||||
*
|
||||
* @param fromId the from id
|
||||
* @param toId the to id
|
||||
*/
|
||||
public static void newRequest(int fromId, int toId) {
|
||||
if (toId == fromId) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (requestExists(fromId, toId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO messenger_requests (to_id, from_id) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, toId);
|
||||
preparedStatement.setInt(2, fromId);
|
||||
preparedStatement.execute();
|
||||
} catch (SQLException ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get if the request exists.
|
||||
*
|
||||
* @param fromId the from id
|
||||
* @param toId the to id
|
||||
*
|
||||
* @return true, if successful
|
||||
*/
|
||||
public static boolean requestExists(int fromId, int toId) {
|
||||
boolean exists = false;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM messenger_requests WHERE from_id = ? AND to_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, fromId);
|
||||
preparedStatement.setInt(2, toId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
exists = true;
|
||||
}
|
||||
|
||||
} catch (Exception ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return exists;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get if friend exists.
|
||||
*
|
||||
* @param fromId the from id
|
||||
* @param toId the to id
|
||||
*
|
||||
* @return true, if successful
|
||||
*/
|
||||
public static boolean friendExists(int fromId, int toId) {
|
||||
boolean exists = false;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM messenger_friends WHERE from_id = ? AND to_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, fromId);
|
||||
preparedStatement.setInt(2, toId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
exists = true;
|
||||
}
|
||||
|
||||
} catch (Exception ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return exists;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the request.
|
||||
*
|
||||
* @param fromId the from id
|
||||
* @param toId the to id
|
||||
*/
|
||||
public static void removeRequest(int fromId, int toId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM messenger_requests WHERE from_id = ? AND to_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, fromId);
|
||||
preparedStatement.setInt(2, toId);
|
||||
preparedStatement.execute();
|
||||
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM messenger_requests WHERE from_id = ? AND to_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, toId);
|
||||
preparedStatement.setInt(2, fromId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeAllRequests(int toId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM messenger_requests WHERE to_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, toId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the friend.
|
||||
*
|
||||
* @param toId the friend id
|
||||
* @param fromId the user id
|
||||
*/
|
||||
public static void removeFriend(int toId, int fromId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM messenger_friends WHERE from_id = ? AND to_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, fromId);
|
||||
preparedStatement.setInt(2, toId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* New friend.
|
||||
*
|
||||
* @param fromId the sender
|
||||
* @param toId the receiver
|
||||
*/
|
||||
public static void newFriend(int toId, int fromId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO messenger_friends (from_id, to_id) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, fromId);
|
||||
preparedStatement.setInt(2, toId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the friend.
|
||||
*
|
||||
* @param userId the friend id
|
||||
* @param friendId the user id
|
||||
*/
|
||||
public static void updateFriendCategory(int userId, int friendId, int categoryId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE messenger_friends SET category_id = ? WHERE from_id = ? AND to_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, categoryId);
|
||||
preparedStatement.setInt(2, friendId);
|
||||
preparedStatement.setInt(3, userId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the category from friends after it had been deleted
|
||||
*
|
||||
* @param userId the friend id
|
||||
* @param categoryId the category
|
||||
*/
|
||||
public static void resetFriendCategories(int userId, int categoryId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE messenger_friends SET category_id = 0 WHERE to_id = ? AND category_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, categoryId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a message for other people to read them later, if they're offline.
|
||||
*
|
||||
* @param fromId the id the user sending the message
|
||||
* @param toId the id of the user to receive it
|
||||
* @param message the body of the message
|
||||
* @return the id of the message
|
||||
*/
|
||||
public static int newMessage(int fromId, int toId, String message) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
int messageID = 0;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO messenger_messages (receiver_id, sender_id, unread, body, date) VALUES (?, ?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, toId);
|
||||
preparedStatement.setInt(2, fromId);
|
||||
preparedStatement.setInt(3, 1);
|
||||
preparedStatement.setString(4, message);
|
||||
preparedStatement.setLong(5, DateUtil.getCurrentTimeSeconds());
|
||||
preparedStatement.executeUpdate();
|
||||
|
||||
ResultSet row = preparedStatement.getGeneratedKeys();
|
||||
|
||||
if (row != null && row.next()) {
|
||||
messageID = row.getInt(1);
|
||||
}
|
||||
|
||||
} catch (SQLException e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return messageID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get unread messages for the user.
|
||||
*
|
||||
* @param userId the id of the user to get the offline messages for
|
||||
* @return the list of messages
|
||||
*/
|
||||
public static Map<Integer, MessengerMessage> getUnreadMessages(int userId) {
|
||||
Map<Integer, MessengerMessage> messages = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM messenger_messages WHERE receiver_id = " + userId + " AND unread = 1", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
messages.put(resultSet.getInt("id"), new MessengerMessage(
|
||||
resultSet.getInt("id"), resultSet.getInt("receiver_id"), resultSet.getInt("sender_id"),
|
||||
resultSet.getLong("date"), resultSet.getString("body")));
|
||||
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return messages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark a message as read.
|
||||
*
|
||||
* @param messageId the message id to reset
|
||||
*/
|
||||
public static void markMessageRead(int messageId) throws SQLException {
|
||||
Storage.getStorage().execute("UPDATE messenger_messages SET unread = 0 WHERE id = " + messageId);
|
||||
}
|
||||
|
||||
public static List<MessengerCategory> getCategories(int userId) {
|
||||
var categories = new ArrayList<MessengerCategory>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM messenger_categories WHERE user_id = " + userId, sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
categories.add(new MessengerCategory(resultSet.getInt("id"), resultSet.getInt("user_id"), resultSet.getString("name")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return categories;
|
||||
}
|
||||
|
||||
public static void deleteCategory(int categoryId, int userId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM messenger_categories WHERE id = ? AND user_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, categoryId);
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void addCategory(String name, int userId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO messenger_categories (user_id, name) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setString(2, name);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void updateCategory(String name, int categoryId, int userId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE messenger_categories SET name = ? WHERE id = ? AND user_id = ?", sqlConnection);
|
||||
preparedStatement.setString(1, name);
|
||||
preparedStatement.setInt(2, categoryId);
|
||||
preparedStatement.setInt(3, userId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.moderation.ModerationActionType;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
|
||||
public class ModerationDao {
|
||||
public static void addLog(ModerationActionType type, int userId, int targetId, String message, String extraNotes) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO housekeeping_audit_log (action, user_id, target_id, message, extra_notes) VALUES (?, ?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setString(1, type.name().toLowerCase());
|
||||
preparedStatement.setInt(2, targetId);
|
||||
preparedStatement.setInt(3, userId);
|
||||
preparedStatement.setString(4, message);
|
||||
preparedStatement.setString(5, extraNotes);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,147 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class MoodlightDao {
|
||||
|
||||
/**
|
||||
* Get if there's a preset row for the moodlight.
|
||||
*/
|
||||
public static boolean containsPreset(long itemId) {
|
||||
boolean hasPreset = false;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT item_id FROM items_moodlight_presets WHERE item_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
hasPreset = true;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return hasPreset;
|
||||
}
|
||||
|
||||
public static boolean createPresets(long itemId) {
|
||||
boolean hasPreset = false;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO items_moodlight_presets (item_id) VALUES (?)", sqlConnection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return hasPreset;
|
||||
}
|
||||
|
||||
public static boolean updatePresets(long itemId, int currentPreset, List<String> presetData) {
|
||||
boolean hasPreset = false;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE items_moodlight_presets SET current_preset = ?, preset_1 = ?, preset_2 = ?, preset_3 = ? WHERE item_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, currentPreset);
|
||||
preparedStatement.setString(2, presetData.get(0));
|
||||
preparedStatement.setString(3, presetData.get(1));
|
||||
preparedStatement.setString(4, presetData.get(2));
|
||||
preparedStatement.setLong(5, itemId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return hasPreset;
|
||||
}
|
||||
|
||||
public static boolean deletePresets(long itemId) {
|
||||
boolean hasPreset = false;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM items_moodlight_presets WHERE item_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return hasPreset;
|
||||
}
|
||||
|
||||
public static Pair<Integer, ArrayList<String>> getPresets(long itemId) {
|
||||
Pair<Integer, ArrayList<String>> presetData = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM items_moodlight_presets WHERE item_id = ? LIMIT 1", sqlConnection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
ArrayList<String> presets = new ArrayList<>();
|
||||
presets.add(resultSet.getString("preset_1"));
|
||||
presets.add(resultSet.getString("preset_2"));
|
||||
presets.add(resultSet.getString("preset_3"));
|
||||
|
||||
presetData = Pair.of(resultSet.getInt("current_preset"), presets);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return presetData;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,359 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.navigator.NavigatorCategory;
|
||||
import org.alexdev.havana.game.navigator.NavigatorStyle;
|
||||
import org.alexdev.havana.game.player.PlayerRank;
|
||||
import org.alexdev.havana.game.room.Room;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.*;
|
||||
|
||||
public class NavigatorDao {
|
||||
|
||||
/**
|
||||
* Get all categories from the database.
|
||||
*
|
||||
* @return map of categories
|
||||
*/
|
||||
public static HashMap<Integer, NavigatorCategory> getCategories() {
|
||||
HashMap<Integer, NavigatorCategory> categories = new HashMap<>();
|
||||
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
conn = Storage.getStorage().getConnection();
|
||||
stmt = Storage.getStorage().prepare("SELECT * FROM rooms_categories ORDER BY order_id ASC ", conn);
|
||||
row = stmt.executeQuery();
|
||||
|
||||
while (row.next()) {
|
||||
NavigatorCategory category = new NavigatorCategory(
|
||||
row.getInt("id"), row.getInt("parent_id"), row.getInt("order_id"),
|
||||
row.getString("name"),
|
||||
row.getBoolean("public_spaces"), row.getBoolean("allow_trading"),
|
||||
PlayerRank.getRankForId(row.getInt("minrole_access")),
|
||||
PlayerRank.getRankForId(row.getInt("minrole_setflatcat")),
|
||||
row.getBoolean("isnode"), row.getBoolean("club_only"));
|
||||
|
||||
categories.put(category.getId(), category);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(stmt);
|
||||
Storage.closeSilently(conn);
|
||||
}
|
||||
|
||||
return categories;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of recent rooms from database set by limit and category id.
|
||||
*
|
||||
* @param limit the maximum amount of usrs
|
||||
* @param categoryId the rooms to find under this category id
|
||||
* @return the list of recent rooms
|
||||
*/
|
||||
public static List<Room> getRecentRooms(int limit, int categoryId) {
|
||||
List<Room> rooms = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms LEFT JOIN users ON rooms.owner_id = users.id WHERE category = ? AND owner_id > 0 ORDER BY visitors_now DESC, rooms.rating DESC LIMIT ? ", sqlConnection);
|
||||
preparedStatement.setInt(1, categoryId);
|
||||
preparedStatement.setInt(2, limit);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
//public NavigatorCategory(int id, String name, boolean publicSpaces, boolean allowTrading, int minimumRoleAccess, int minimumRoleSetFlat) {
|
||||
while (resultSet.next()) {
|
||||
Room room = new Room();
|
||||
RoomDao.fill(room.getData(), resultSet);
|
||||
rooms.add(room);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return rooms;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count recent rooms by category id.
|
||||
*
|
||||
* @param limit the limit to count
|
||||
* @return the list of recent rooms
|
||||
*/
|
||||
public static Map<Integer, Integer> getPopularCategories(int limit) {
|
||||
Map<Integer, Integer> categories = new LinkedHashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT c.id AS id, c.name AS name, IFNULL((SELECT SUM(rooms.visitors_now) FROM rooms WHERE rooms.category = c.id), 0) AS room_visitors FROM rooms_categories c WHERE c.isnode = 0 AND c.public_spaces = 0 AND c.minrole_access = 1 AND id <> 2 ORDER BY room_visitors DESC LIMIT ?", sqlConnection);
|
||||
// preparedStatement.setInt(1, categoryId);
|
||||
preparedStatement.setInt(1, limit);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
categories.put(resultSet.getInt("id"), resultSet.getInt("room_visitors"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return categories;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the list of recent rooms by category id.
|
||||
*
|
||||
* @param categoryId the rooms to find under this category id
|
||||
* @return the list of recent rooms
|
||||
*/
|
||||
public static List<Room> getRoomsByCategory(int categoryId) {
|
||||
List<Room> rooms = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms LEFT JOIN users ON rooms.owner_id = users.id WHERE category = ? ORDER BY visitors_now DESC, rooms.rating DESC", sqlConnection);
|
||||
preparedStatement.setInt(1, categoryId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
//public NavigatorCategory(int id, String name, boolean publicSpaces, boolean allowTrading, int minimumRoleAccess, int minimumRoleSetFlat) {
|
||||
while (resultSet.next()) {
|
||||
Room room = new Room();
|
||||
RoomDao.fill(room.getData(), resultSet);
|
||||
rooms.add(room);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return rooms;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of most popular rooms from database set by limit
|
||||
*
|
||||
* @param limit the maximum amount of usrs
|
||||
* @return the list of recent rooms
|
||||
*/
|
||||
public static List<Room> getRopularRooms(int limit, boolean includePublicRooms) {
|
||||
List<Room> rooms = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
String excludePublicRooms = " owner_id > 0 AND";
|
||||
|
||||
if (includePublicRooms) {
|
||||
excludePublicRooms = "";
|
||||
}
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms LEFT JOIN users ON rooms.owner_id = users.id WHERE" + excludePublicRooms + " visitors_now > 0 ORDER BY visitors_now DESC, rooms.rating DESC LIMIT ? ", sqlConnection);
|
||||
|
||||
preparedStatement.setInt(1, limit);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
//public NavigatorCategory(int id, String name, boolean publicSpaces, boolean allowTrading, int minimumRoleAccess, int minimumRoleSetFlat) {
|
||||
while (resultSet.next()) {
|
||||
Room room = new Room();
|
||||
RoomDao.fill(room.getData(), resultSet);
|
||||
rooms.add(room);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return rooms;
|
||||
}
|
||||
|
||||
public static int createRoom(int ownerId, String roomName, String roomModel, boolean roomShowName, int accessType) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
int roomId = 0;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO rooms (owner_id, name, description, model, showname, password, accesstype) VALUES (?,?,?,?,?, '', ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, ownerId);
|
||||
preparedStatement.setString(2, roomName);
|
||||
preparedStatement.setString(3, "");
|
||||
preparedStatement.setString(4, roomModel);
|
||||
preparedStatement.setBoolean(5, roomShowName);
|
||||
preparedStatement.setInt(6, accessType);
|
||||
preparedStatement.executeUpdate();
|
||||
resultSet = preparedStatement.getGeneratedKeys();
|
||||
|
||||
if (resultSet.next()) {
|
||||
roomId = resultSet.getInt(1);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return roomId;
|
||||
}
|
||||
|
||||
public static int getRoomCountByCategory(int categoryId) {
|
||||
int size = 0;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT count(*) FROM rooms WHERE category = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, categoryId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
size = resultSet.getInt(1);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of rooms owned by friends, sorted by visitors and then room score
|
||||
*
|
||||
* @param limit the maximum amount of rooms
|
||||
* @param friendList the list of user ids
|
||||
* @return the list of recent rooms
|
||||
*/
|
||||
public static List<Room> getFriendRooms(int limit, List<String> friendList) {
|
||||
List<Room> rooms = new ArrayList<>();
|
||||
|
||||
if (friendList.isEmpty()) {
|
||||
return rooms;
|
||||
}
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
String friendIds = "(";
|
||||
friendIds += String.join(",", friendList);
|
||||
friendIds += ")";
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms INNER JOIN users ON rooms.owner_id = users.id WHERE owner_id IN " + friendIds + " ORDER BY visitors_now DESC, rooms.rating DESC LIMIT ? ", sqlConnection);
|
||||
preparedStatement.setInt(1, limit);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
//public NavigatorCategory(int id, String name, boolean publicSpaces, boolean allowTrading, int minimumRoleAccess, int minimumRoleSetFlat) {
|
||||
while (resultSet.next()) {
|
||||
Room room = new Room();
|
||||
RoomDao.fill(room.getData(), resultSet);
|
||||
rooms.add(room);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return rooms;
|
||||
}
|
||||
|
||||
public static List<Room> getRecentlyVisited(int limit, int userId) {
|
||||
List<Room> rooms = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT rooms.*,users.username AS username FROM room_visits " +
|
||||
"INNER JOIN rooms ON rooms.id = room_visits.room_id " +
|
||||
"INNER JOIN users ON rooms.owner_id = users.id " +
|
||||
"WHERE user_id = ? " +
|
||||
"AND owner_id > 0 " +
|
||||
"ORDER BY visited_at DESC " +
|
||||
"LIMIT ? ", sqlConnection);
|
||||
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, limit);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
//public NavigatorCategory(int id, String name, boolean publicSpaces, boolean allowTrading, int minimumRoleAccess, int minimumRoleSetFlat) {
|
||||
while (resultSet.next()) {
|
||||
Room room = new Room();
|
||||
RoomDao.fill(room.getData(), resultSet);
|
||||
rooms.add(room);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return rooms;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,124 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.navigator.NavigatorCategory;
|
||||
import org.alexdev.havana.game.pets.PetDetails;
|
||||
import org.alexdev.havana.game.player.PlayerRank;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class PetDao {
|
||||
public static void createPet(long databaseId, String name, String type, int race, String colour) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO items_pets (item_id, name, type, race, colour, nature_positive, nature_negative, born, last_kip, last_eat, last_drink, last_playtoy, last_playuser) VALUES (?, ?, ? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setLong(1, databaseId);
|
||||
preparedStatement.setString(2, name);
|
||||
preparedStatement.setString(3, type);
|
||||
preparedStatement.setInt(4, race);
|
||||
preparedStatement.setString(5, colour);
|
||||
preparedStatement.setInt(6, ThreadLocalRandom.current().nextInt(0, 7));
|
||||
preparedStatement.setInt(7, ThreadLocalRandom.current().nextInt(0, 7));
|
||||
preparedStatement.setLong(8, DateUtil.getCurrentTimeSeconds());
|
||||
preparedStatement.setLong(9, DateUtil.getCurrentTimeSeconds());
|
||||
preparedStatement.setLong(10, DateUtil.getCurrentTimeSeconds());
|
||||
preparedStatement.setLong(11, DateUtil.getCurrentTimeSeconds());
|
||||
preparedStatement.setLong(12, DateUtil.getCurrentTimeSeconds());
|
||||
preparedStatement.setLong(13, DateUtil.getCurrentTimeSeconds());
|
||||
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveCoordinates(int id, int x, int y, int rotation) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE items_pets SET x = ?, y = ?, rotation = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, x);
|
||||
preparedStatement.setInt(2, y);
|
||||
preparedStatement.setInt(3, rotation);
|
||||
preparedStatement.setInt(4, id);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveDetails(int id, PetDetails petDetails) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE items_pets SET last_kip = ?, last_eat = ?, last_drink = ?, last_playtoy = ?, last_playuser = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, petDetails.getLastKip());
|
||||
preparedStatement.setLong(2, petDetails.getLastEat());
|
||||
preparedStatement.setLong(3, petDetails.getLastDrink());
|
||||
preparedStatement.setLong(4, petDetails.getLastPlayToy());
|
||||
preparedStatement.setLong(5, petDetails.getLastPlayUser());
|
||||
preparedStatement.setInt(6, id);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static PetDetails getPetDetails(long itemId) {
|
||||
PetDetails petDetails = null;
|
||||
|
||||
Connection connection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet row = null;
|
||||
|
||||
try {
|
||||
connection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM items_pets WHERE item_id = ?", connection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
row = preparedStatement.executeQuery();
|
||||
|
||||
while (row.next()) {
|
||||
petDetails = new PetDetails(row.getInt("id"), row.getLong("item_id"), row.getString("name"),
|
||||
row.getString("type"), row.getString("race"), row.getString("colour"), row.getInt("nature_positive"),
|
||||
row.getInt("nature_negative"), row.getFloat("friendship"), row.getLong("born"), row.getLong("last_kip"),
|
||||
row.getLong("last_eat"), row.getLong("last_drink"), row.getLong("last_playtoy"), row.getLong("last_playuser"),
|
||||
row.getInt("x"), row.getInt("y"), row.getInt("rotation"));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(row);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(connection);
|
||||
}
|
||||
|
||||
return petDetails;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.item.Photo;
|
||||
|
||||
import java.sql.*;
|
||||
|
||||
public class PhotoDao {
|
||||
public static void addPhoto(long photoId, int userId, long timestamp, byte[] photo, int checksum) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO items_photos (photo_id, photo_user_id, timestamp, photo_data, photo_checksum) VALUES (?, ?, ?, ?, ?)", sqlConnection);
|
||||
|
||||
Blob photoBlob = sqlConnection.createBlob();
|
||||
photoBlob.setBytes(1, photo);
|
||||
|
||||
preparedStatement.setLong(1, photoId);
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.setLong(3, timestamp);
|
||||
preparedStatement.setBlob(4, photoBlob);
|
||||
preparedStatement.setInt(5, checksum);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static Photo getPhoto(long photoId) throws SQLException {
|
||||
Photo photo = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM items_photos WHERE photo_id = ? AND is_active = 1", sqlConnection);// (photo_id, photo_user_id, timestamp, photo_data, photo_checksum) VALUES (?, ?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setLong(1, photoId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
Blob photoBlob = resultSet.getBlob("photo_data");
|
||||
int blobLength = (int) photoBlob.length();
|
||||
|
||||
byte[] photoBlobBytes = photoBlob.getBytes(1, blobLength);
|
||||
photo = new Photo(photoId, resultSet.getInt("photo_checksum"), photoBlobBytes, resultSet.getLong("timestamp"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return photo;
|
||||
}
|
||||
|
||||
public static void deleteItem(long photoId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE items_photos SET is_active = 0 WHERE photo_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, photoId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load diff
|
@ -0,0 +1,231 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.player.statistics.PlayerStatistic;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class PlayerStatisticsDao {
|
||||
public static void updateStatistic(int userId, PlayerStatistic statistic, String value) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users_statistics SET " + statistic.getColumn() + " = ? WHERE user_id = ?", sqlConnection);
|
||||
|
||||
if (statistic.isDateTime()) {
|
||||
preparedStatement.setTimestamp(1, new Timestamp(Long.parseLong(value) * 1000L));
|
||||
} else {
|
||||
preparedStatement.setString(1, value);
|
||||
}
|
||||
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void updateStatistic(int userId, PlayerStatistic statistic, int value) {
|
||||
updateStatistic(userId, statistic, String.valueOf(value));
|
||||
}
|
||||
|
||||
public static void updateStatistic(int userId, PlayerStatistic statistic, long value) {
|
||||
updateStatistic(userId, statistic, String.valueOf(value));
|
||||
}
|
||||
|
||||
|
||||
public static void incrementStatistic(int userId, PlayerStatistic statistic, long value) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users_statistics SET " + statistic.getColumn() + " = " + statistic.getColumn() + " + ? WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, value);
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void updateStatistics(int userId, HashMap<PlayerStatistic, String> statisticMap) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
|
||||
for (var kvp : statisticMap.entrySet()) {
|
||||
var statistic = kvp.getKey();
|
||||
var value = kvp.getValue();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users_statistics SET " + statistic.getColumn() + " = ? WHERE user_id = ?", sqlConnection);
|
||||
|
||||
if (statistic.isDateTime()) {
|
||||
preparedStatement.setTimestamp(5, new Timestamp(Long.parseLong(value) * 1000L));
|
||||
} else {
|
||||
preparedStatement.setString(1, value);
|
||||
}
|
||||
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.execute();
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void incrementStatistics(int userId, HashMap<PlayerStatistic, Long> statisticMap) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
|
||||
for (var kvp : statisticMap.entrySet()) {
|
||||
var statistic = kvp.getKey();
|
||||
long value = kvp.getValue();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users_statistics SET " + statistic.getColumn() + " = " + statistic.getColumn() + " + ? WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, value);
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.execute();
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static long getStatisticLong(int userId, PlayerStatistic playerStatistic) {
|
||||
long setting = 0;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT " + playerStatistic.getColumn() + " FROM users_statistics WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
setting = resultSet.getInt(playerStatistic.getColumn());
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return setting;
|
||||
}
|
||||
|
||||
public static String getStatisticString(int userId, PlayerStatistic playerStatistic) {
|
||||
String setting = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT " + playerStatistic.getColumn() + " FROM users_statistics WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
setting = resultSet.getString(playerStatistic.getColumn());
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return setting;
|
||||
}
|
||||
|
||||
public static Map<PlayerStatistic, String> getStatistics(int userId) {
|
||||
Map<PlayerStatistic, String> values = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users_statistics WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
for (PlayerStatistic playerStatistic : PlayerStatistic.values()) {
|
||||
if (playerStatistic.isDateTime()) {
|
||||
if (resultSet.getTime(playerStatistic.getColumn()) != null) {
|
||||
values.put(playerStatistic, String.valueOf(resultSet.getTime(playerStatistic.getColumn()).getTime() / 1000L));
|
||||
} else {
|
||||
values.put(playerStatistic, null);
|
||||
}
|
||||
} else {
|
||||
values.put(playerStatistic, resultSet.getString(playerStatistic.getColumn()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
public static void newStatistics(int userId, String activationCode) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_statistics (user_id, activation_code) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setString(2, activationCode);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.item.publicrooms.PublicItemData;
|
||||
import org.alexdev.havana.game.room.handlers.walkways.WalkwaysEntrance;
|
||||
import org.alexdev.havana.game.room.handlers.walkways.WalkwaysManager;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.*;
|
||||
|
||||
public class PublicRoomsDao {
|
||||
/**
|
||||
* Get the item definitions.
|
||||
*
|
||||
* @return the list of item definitions
|
||||
*/
|
||||
public static List<PublicItemData> getPublicItemData(String roomModel) {
|
||||
List<PublicItemData> itemDataList = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM public_items WHERE room_model = ?", sqlConnection);
|
||||
preparedStatement.setString(1, roomModel);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
PublicItemData itemData = new PublicItemData(resultSet.getString("id"), resultSet.getString("room_model"),
|
||||
resultSet.getString("sprite"), resultSet.getInt("x"), resultSet.getInt("y"),
|
||||
resultSet.getDouble("z"), resultSet.getInt("rotation"), resultSet.getDouble("top_height"),
|
||||
resultSet.getInt("length"), resultSet.getInt("width"), resultSet.getString("behaviour"),
|
||||
resultSet.getString("current_program"), resultSet.getString("teleport_to"), resultSet.getString("swim_to"));
|
||||
|
||||
itemDataList.add(itemData);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return itemDataList;
|
||||
}
|
||||
|
||||
public static List<WalkwaysEntrance> getWalkways() {
|
||||
List<WalkwaysEntrance> walkwaysEntrances = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM public_roomwalkways", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
walkwaysEntrances.add(WalkwaysManager.createWalkway(resultSet.getInt("room_id"), resultSet.getInt("to_id"), resultSet.getString("coords_map"),
|
||||
resultSet.getString("door_position")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return walkwaysEntrances;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class ReferredDao {
|
||||
public static int countReferred(int id) {
|
||||
int count = 0;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT COUNT(*) FROM users_referred WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, id);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
count = resultSet.getInt(1);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
public static void addReferred(int userId, int referredId) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_referred (user_id, referred_id) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, referredId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class RoomBanDao {
|
||||
public static void addBan(int userId, int roomId, long expireTime) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM rooms_bans WHERE user_id = ? AND room_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, roomId);
|
||||
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO rooms_bans (user_id, room_id, expire_at) VALUES (?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, roomId);
|
||||
preparedStatement.setLong(3, expireTime);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean hasBan(int userId, int roomId) {
|
||||
boolean hasBan = false;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT user_id FROM rooms_bans WHERE user_id = ? AND room_id = ? AND expire_at > ? LIMIT 1", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, roomId);
|
||||
preparedStatement.setLong(3, DateUtil.getCurrentTimeSeconds());
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
hasBan = true;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return hasBan;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,532 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.moderation.ChatMessage;
|
||||
import org.alexdev.havana.game.room.Room;
|
||||
import org.alexdev.havana.game.room.RoomData;
|
||||
import org.alexdev.havana.messages.outgoing.rooms.user.CHAT_MESSAGE;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
public class RoomDao {
|
||||
public static final int FLASH_SEARCH_LIMIT = 100;
|
||||
public static final int SHOCKWAVE_SEARCH_LIMIT = 100;
|
||||
|
||||
public static void resetVisitors() {
|
||||
try {
|
||||
Storage.getStorage().execute("UPDATE rooms SET visitors_now = 0 WHERE visitors_now > 0");
|
||||
} catch (SQLException e) {
|
||||
Storage.logError(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of rooms by the owner id, use "0" for public rooms.
|
||||
*
|
||||
* @param userId the user id to get the rooms by
|
||||
* @return the list of rooms
|
||||
*/
|
||||
public static List<Room> getRoomsByUserId(int userId) {
|
||||
List<Room> rooms = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms LEFT JOIN users ON rooms.owner_id = users.id WHERE rooms.owner_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
Room room = new Room();
|
||||
fill(room.getData(), resultSet);
|
||||
rooms.add(room);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return rooms;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of recommended rooms.
|
||||
*
|
||||
* @param limit the limit of rooms
|
||||
* @return the list of rooms
|
||||
*/
|
||||
public static List<Room> getRecommendedRooms(int limit, int offset) {
|
||||
List<Room> roomList = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms LEFT JOIN users ON rooms.owner_id = users.id WHERE owner_id > 0 AND accesstype = 0 ORDER BY visitors_now DESC, rating DESC LIMIT " + limit + " OFFSET " + offset, sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
Room room = new Room();
|
||||
RoomDao.fill(room.getData(), resultSet);
|
||||
roomList.add(room);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
Storage.closeSilently(resultSet);
|
||||
}
|
||||
|
||||
return roomList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of the highest rated rooms
|
||||
*
|
||||
* @param limit the maximum amount of rooms
|
||||
* @return the list of highest rated rooms
|
||||
*/
|
||||
public static List<Room> getHighestRatedRooms(int limit, int offset) {
|
||||
List<Room> rooms = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms LEFT JOIN users ON rooms.owner_id = users.id WHERE owner_id > 0 ORDER BY rating DESC LIMIT " + limit + " OFFSET " + offset, sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
Room room = new Room();
|
||||
RoomDao.fill(room.getData(), resultSet);
|
||||
rooms.add(room);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return rooms;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the room id of a room by its model, used for walkways.
|
||||
*
|
||||
* @param model the model used to get the id for
|
||||
* @return the id, else -1
|
||||
*/
|
||||
public static int getRoomIdByModel(String model) {
|
||||
int roomId = -1;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT id FROM rooms WHERE model = ?", sqlConnection);
|
||||
preparedStatement.setString(1, model);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
roomId = resultSet.getInt("id");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return roomId;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Search query for when people use the navigator search, will search either by username or room name similarities.
|
||||
*
|
||||
* @param searchQuery the query to use
|
||||
* @return the list of possible room matches
|
||||
*/
|
||||
public static List<Room> searchRooms(String searchQuery, int roomOwner, int limit) {
|
||||
List<Room> rooms = new ArrayList<>();
|
||||
|
||||
if (searchQuery.isBlank() && roomOwner == -1) {
|
||||
return rooms;
|
||||
}
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms INNER JOIN users ON rooms.owner_id = users.id WHERE" + (roomOwner > 0 ? (" owner_id = " + roomOwner + " AND") : " LOWER(users.username) LIKE ? OR") + " LOWER(rooms.name) LIKE ? ORDER BY visitors_now DESC, rating DESC LIMIT ? ", sqlConnection);
|
||||
|
||||
if (roomOwner > 0) {
|
||||
preparedStatement.setString(1, "%" + searchQuery + "%");
|
||||
preparedStatement.setInt(2, limit);
|
||||
} else {
|
||||
preparedStatement.setString(1, "%" + searchQuery + "%");
|
||||
preparedStatement.setString(2, "%" + searchQuery + "%");
|
||||
preparedStatement.setInt(3, limit);
|
||||
}
|
||||
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
Room room = new Room();
|
||||
fill(room.getData(), resultSet);
|
||||
rooms.add(room);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return rooms;
|
||||
}
|
||||
|
||||
public static Room getRoomById(int roomId) {
|
||||
Room room = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms LEFT JOIN users ON rooms.owner_id = users.id WHERE rooms.id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, roomId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
room = new Room();
|
||||
fill(room.getData(), resultSet);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return room;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save all room information.
|
||||
*
|
||||
* @param room the room to save
|
||||
*/
|
||||
public static void saveDecorations(Room room) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE rooms SET wallpaper = ?, floor = ?, landscape = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, room.getData().getWallpaper());
|
||||
preparedStatement.setInt(2, room.getData().getFloor());
|
||||
preparedStatement.setString(3, room.getData().getLandscape());
|
||||
preparedStatement.setInt(4, room.getId());
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save all room information.
|
||||
*
|
||||
* @param room the room to save
|
||||
*/
|
||||
public static void save(Room room) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE rooms SET category = ?, name = ?, description = ?, showname = ?, superusers = ?, accesstype = ?, password = ?, visitors_max = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, room.getData().getCategoryId());
|
||||
preparedStatement.setString(2, room.getData().getName());
|
||||
preparedStatement.setString(3, room.getData().getDescription());
|
||||
preparedStatement.setBoolean(4, room.getData().showOwnerName());
|
||||
preparedStatement.setBoolean(5, room.getData().allowSuperUsers());
|
||||
preparedStatement.setInt(6, room.getData().getAccessTypeId());
|
||||
preparedStatement.setString(7, room.getData().getPassword());
|
||||
preparedStatement.setInt(8, room.getData().getVisitorsMax());
|
||||
preparedStatement.setInt(9, room.getId());
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Save visitor count of rooms
|
||||
*
|
||||
* @param id the id of room to save
|
||||
*/
|
||||
public static void saveVisitors(int id, int size) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE rooms SET visitors_now = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, size);
|
||||
preparedStatement.setInt(2, id);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save rating for the room
|
||||
*
|
||||
* @param roomId the room to save
|
||||
* @param rating the new rating
|
||||
*/
|
||||
public static void saveRating(int roomId, int rating) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE rooms SET rating = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, rating);
|
||||
preparedStatement.setInt(2, roomId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Save room icon data
|
||||
*
|
||||
* @param roomId the room id for the icon to save to
|
||||
* @param formattedIconData the formatted icon data to save
|
||||
*/
|
||||
public static void saveIcon(int roomId, String formattedIconData) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE rooms SET icon_data = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setString(1, formattedIconData);
|
||||
preparedStatement.setInt(2, roomId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete room.
|
||||
*
|
||||
* @param room the room to delete
|
||||
*/
|
||||
public static void delete(Room room) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM rooms WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, room.getId());
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save visitor count of rooms
|
||||
*
|
||||
* @param roomId the room to save
|
||||
*/
|
||||
public static void saveGroupId(int roomId, int groupId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE rooms SET group_id = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, roomId);
|
||||
preparedStatement.setInt(2, groupId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveChatLog(Collection<ChatMessage> chatMessages) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO room_chatlogs (user_id, room_id, timestamp, chat_type, message) VALUES (?, ?, ?, ?, ?)", sqlConnection);
|
||||
sqlConnection.setAutoCommit(false);
|
||||
|
||||
for (ChatMessage chatMessage : chatMessages) {
|
||||
preparedStatement.setInt(1, chatMessage.getPlayerId());
|
||||
preparedStatement.setInt(2, chatMessage.getRoomId());
|
||||
preparedStatement.setLong(3, chatMessage.getSentTime());
|
||||
|
||||
switch (chatMessage.getChatMessageType()) {
|
||||
case CHAT:
|
||||
preparedStatement.setInt(4, 0);
|
||||
break;
|
||||
case SHOUT:
|
||||
preparedStatement.setInt(4, 1);
|
||||
break;
|
||||
default:
|
||||
preparedStatement.setInt(4, 2);
|
||||
break;
|
||||
}
|
||||
|
||||
preparedStatement.setString(5, chatMessage.getMessage());
|
||||
preparedStatement.addBatch();
|
||||
}
|
||||
|
||||
preparedStatement.executeBatch();
|
||||
sqlConnection.setAutoCommit(true);
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<ChatMessage> getModChatlog(int roomId) {
|
||||
List<ChatMessage> chatHistoryList = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
//room_chatlogs (user_id, room_id, timestamp, chat_type, message)
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT rooms.owner_id AS owner_id, room_chatlogs.*,rooms.name AS room_name, users.username AS username FROM room_chatlogs " +
|
||||
"INNER JOIN rooms ON room_chatlogs.room_id = rooms.id " +
|
||||
"INNER JOIN users ON room_chatlogs.user_id = users.id " +
|
||||
"WHERE room_id = ? " +
|
||||
"ORDER BY timestamp DESC " +
|
||||
"LIMIT 150", sqlConnection);
|
||||
preparedStatement.setInt(1, roomId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
CHAT_MESSAGE.ChatMessageType chatMessageType = CHAT_MESSAGE.ChatMessageType.CHAT;
|
||||
int chatType = resultSet.getInt("chat_type");
|
||||
|
||||
if (chatType == 2) {
|
||||
chatMessageType = CHAT_MESSAGE.ChatMessageType.WHISPER;
|
||||
}
|
||||
|
||||
if (chatType == 1) {
|
||||
chatMessageType = CHAT_MESSAGE.ChatMessageType.SHOUT;
|
||||
}
|
||||
|
||||
chatHistoryList.add(new ChatMessage(resultSet.getInt("user_id"), resultSet.getString("username"),
|
||||
resultSet.getString("message"), chatMessageType,
|
||||
roomId, resultSet.getLong("timestamp")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return chatHistoryList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill room data
|
||||
*
|
||||
* @param data the room data instance
|
||||
* @param row the row
|
||||
* @throws SQLException the SQL exception
|
||||
*/
|
||||
public static void fill(RoomData data, ResultSet row) throws SQLException {
|
||||
if (data == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String ownerName = row.getString("username");
|
||||
|
||||
data.fill(row.getInt("id"), row.getInt("owner_id"), ownerName != null ? ownerName : "", row.getInt("category"),
|
||||
row.getString("name"), row.getString("description"), row.getString("model"),
|
||||
row.getString("ccts"), row.getInt("wallpaper"), row.getInt("floor"), row.getString("landscape"),
|
||||
row.getBoolean("showname"), row.getBoolean("superusers"), row.getInt("accesstype"),
|
||||
row.getString("password"), row.getInt("visitors_now"), row.getInt("visitors_max"), row.getInt("rating"),
|
||||
row.getString("icon_data"), row.getInt("group_id"), row.getBoolean("is_hidden"));
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class RoomFavouritesDao {
|
||||
public static List<Integer> getFavouriteRooms(int userId, boolean privateRoomsOnly) {
|
||||
List<Integer> roomIds = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT room_id FROM users_room_favourites INNER JOIN rooms ON rooms.id = users_room_favourites.room_id WHERE user_id = ?" + (privateRoomsOnly ? " AND owner_id > 0" : ""), sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
roomIds.add(resultSet.getInt("room_id"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return roomIds;
|
||||
}
|
||||
|
||||
public static void addFavouriteRoom(int userId, int roomId) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_room_favourites (user_id, room_id) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, roomId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeFavouriteRoom(int userId, int roomId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM users_room_favourites WHERE user_id = ? AND room_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, roomId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.room.models.RoomModel;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class RoomModelDao {
|
||||
public static ConcurrentHashMap<String, RoomModel> getModels() {
|
||||
ConcurrentHashMap<String, RoomModel> roomModels = new ConcurrentHashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM rooms_models", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
RoomModel roomModel = new RoomModel(resultSet.getString("model_id"), resultSet.getString("model_name"),
|
||||
resultSet.getInt("door_x"), resultSet.getInt("door_y"), resultSet.getDouble("door_z"),
|
||||
resultSet.getInt("door_dir"), resultSet.getString("heightmap"), resultSet.getString("trigger_class"));
|
||||
|
||||
roomModels.put(roomModel.getId(), roomModel);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return roomModels;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.player.PlayerDetails;
|
||||
import org.alexdev.havana.game.room.RoomData;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class RoomRightsDao {
|
||||
|
||||
/**
|
||||
* Get a list of users with room rights for a room
|
||||
*
|
||||
* @return the list of user ids who have room rights
|
||||
*/
|
||||
public static List<Integer> getRoomRights(RoomData room) {
|
||||
List<Integer> users = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT user_id FROM rooms_rights WHERE room_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, room.getId());
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
users.add(resultSet.getInt("user_id"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return users;
|
||||
}
|
||||
|
||||
public static void addRights(PlayerDetails user, RoomData room) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO rooms_rights (user_id, room_id) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, user.getId());
|
||||
preparedStatement.setInt(2, room.getId());
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeRights(int userId, RoomData room) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM rooms_rights WHERE user_id = ? AND room_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, room.getId());
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteRoomRights(RoomData room) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM rooms_rights WHERE room_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, room.getId());
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
|
||||
public class RoomVisitsDao {
|
||||
public static void addVisit(int userId, int roomId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("REPLACE INTO room_visits (user_id, room_id, visited_at) VALUES (?, ?, NOW())", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, roomId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static int countVisits(int userId) {
|
||||
int count = 0;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT COUNT(*) as visits FROM room_visits WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
count = resultSet.getInt("visits");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,119 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.room.managers.VoteData;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class RoomVoteDao {
|
||||
private static final long EXPIRE_SECONDS = TimeUnit.DAYS.toSeconds(30*2);
|
||||
|
||||
/**
|
||||
* Vote for a room
|
||||
*
|
||||
* @param userId the user id who is voting
|
||||
* @param roomId the room id that the user is voting for
|
||||
* @param answer the value of the vote (1 or -1)
|
||||
*/
|
||||
public static void vote(int userId, int roomId, int answer) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_room_votes (user_id, room_id, vote, expire_time) VALUES (?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, roomId);
|
||||
preparedStatement.setInt(3, answer);
|
||||
preparedStatement.setLong(4, DateUtil.getCurrentTimeSeconds() + EXPIRE_SECONDS);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vote expired votes for a room
|
||||
*/
|
||||
public static void removeExpiredVotes(int roomId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
|
||||
/*preparedStatement = Storage.getStorage().prepare("SELECT room_id FROM users_room_votes WHERE expire_time < ?", sqlConnection);
|
||||
preparedStatement.setLong(1, DateUtil.getCurrentTimeSeconds());
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
affected = true;
|
||||
}*/
|
||||
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM users_room_votes WHERE room_id = ? AND expire_time < ?", sqlConnection);
|
||||
preparedStatement.setInt(1, roomId);
|
||||
preparedStatement.setLong(2, DateUtil.getCurrentTimeSeconds());
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a map of the room ratings
|
||||
*
|
||||
* @param roomId the id of the room id to save
|
||||
* @return Map containing key userId and value voteAnswer
|
||||
*/
|
||||
public static List<VoteData> getRatings(int roomId) {
|
||||
List<VoteData> ratings = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT " +
|
||||
"users_room_votes.user_id AS user_id, room_id, vote, CONVERT(GROUP_CONCAT(ip_address SEPARATOR ',') USING 'UTF8') AS ip_addresses, machine_id " +
|
||||
"FROM " +
|
||||
"users_room_votes " +
|
||||
"INNER JOIN users_ip_logs ON users_ip_logs.user_id = users_room_votes.user_id " +
|
||||
"INNER JOIN users ON users.id = users_room_votes.user_id " +
|
||||
"WHERE " +
|
||||
"users_room_votes.room_id = ? AND users_room_votes.expire_time > ? " +
|
||||
"GROUP BY " +
|
||||
"users_room_votes.user_id", sqlConnection);
|
||||
preparedStatement.setInt(1, roomId);
|
||||
preparedStatement.setLong(2, DateUtil.getCurrentTimeSeconds());
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
ratings.add(new VoteData(resultSet.getInt("user_id"), resultSet.getInt("vote"), resultSet.getString("ip_addresses"), resultSet.getString("machine_id")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return ratings;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,179 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class SettingsDao {
|
||||
|
||||
/**
|
||||
* Update setting in the database.
|
||||
*
|
||||
* @param key the key used to set the value
|
||||
* @param value the new value to set
|
||||
*/
|
||||
public static void updateSetting(String key, String value) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE settings SET value = ? WHERE setting = ?", sqlConnection);
|
||||
preparedStatement.setString(1, value);
|
||||
preparedStatement.setString(2, key);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void updateSettings(Set<Map.Entry<String, String>> entrySet) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE settings SET value = ? WHERE setting = ?", sqlConnection);
|
||||
sqlConnection.setAutoCommit(false);
|
||||
|
||||
for (var kvp : entrySet) {
|
||||
preparedStatement.setString(1, kvp.getValue());
|
||||
preparedStatement.setString(2, kvp.getKey());
|
||||
preparedStatement.addBatch();
|
||||
}
|
||||
|
||||
preparedStatement.executeBatch();
|
||||
sqlConnection.setAutoCommit(true);
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a value from the settings table.
|
||||
*
|
||||
* @param key the key used to get the value
|
||||
* @return the value, null if no value was found
|
||||
*/
|
||||
public static String getSetting(String key) {
|
||||
String value = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT value FROM settings WHERE setting = ?", sqlConnection);
|
||||
preparedStatement.setString(1, key);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
value = resultSet.getString("value");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all settings from the settings table.
|
||||
*
|
||||
* @return a map containing key and values
|
||||
*/
|
||||
public static Map<String, String> getAllSettings() {
|
||||
Map<String, String> settings = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT setting, value FROM settings", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
settings.put(resultSet.getString("setting"), resultSet.getString("value"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new setting entry in the database using a key value lookup.
|
||||
*
|
||||
* @param key the key used for the lookup
|
||||
* @param value the value for the key
|
||||
*/
|
||||
public static void newSetting(String key, String value) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO settings (setting, value) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setString(1, key);
|
||||
preparedStatement.setString(2, value);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static Map<String, String> getTexts() {
|
||||
Map<String, String> texts = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM external_texts", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
texts.put(resultSet.getString("entry"), resultSet.getString("text"));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return texts;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,331 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.song.Song;
|
||||
import org.alexdev.havana.game.song.SongPlaylist;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class SongMachineDao {
|
||||
|
||||
/**
|
||||
* Get the song list for this machine.
|
||||
*
|
||||
* @param itemId the item id for this machine
|
||||
* @return the list of songs
|
||||
*/
|
||||
public static List<Song> getSongList(long itemId) {
|
||||
List<Song> songs = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM soundmachine_songs WHERE item_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
// (int id, String title, int itemId, int length, String data, boolean isBurnt)
|
||||
while (resultSet.next()) {
|
||||
songs.add(new Song(resultSet.getInt("id"), resultSet.getString("title"), itemId, resultSet.getInt("user_id"),
|
||||
resultSet.getInt("length"), resultSet.getString("data"), resultSet.getBoolean("burnt")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return songs;
|
||||
}
|
||||
|
||||
public static Song getSong(int songId) {
|
||||
Song song = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM soundmachine_songs WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, songId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
// (int id, String title, int itemId, int length, String data, boolean isBurnt)
|
||||
if (resultSet.next()) {
|
||||
song = new Song(resultSet.getInt("id"), resultSet.getString("title"), resultSet.getLong("item_id"), resultSet.getInt("user_id"),
|
||||
resultSet.getInt("length"), resultSet.getString("data"), resultSet.getBoolean("burnt"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return song;
|
||||
}
|
||||
|
||||
public static List<SongPlaylist> getSongPlaylist(long itemId) {
|
||||
List<SongPlaylist> songs = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM soundmachine_playlists WHERE item_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
// (int id, String title, int itemId, int length, String data, boolean isBurnt)
|
||||
while (resultSet.next()) {
|
||||
songs.add(new SongPlaylist(itemId, getSong(resultSet.getInt("song_id")), resultSet.getInt("slot_id")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return songs;
|
||||
}
|
||||
|
||||
public static void addPlaylist(long itemId, int songId, int slotId) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO soundmachine_playlists (item_id, song_id, slot_id) VALUES (?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
preparedStatement.setInt(2, songId);
|
||||
preparedStatement.setInt(3, slotId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removePlaylistSong(int songId, long itemId) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM soundmachine_playlists WHERE song_id = ? AND item_id = ? LIMIT 1", sqlConnection);
|
||||
preparedStatement.setInt(1, songId);
|
||||
preparedStatement.setLong(2, itemId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteSong(int songId) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
|
||||
// Don't actually delete, just make it invisible, this is because some burned disks might use it.
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE soundmachine_songs SET item_id = -1 WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, songId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void clearPlaylist(long itemId) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM soundmachine_playlists WHERE item_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void addSong(int userId, long soundMachineId, String title, int length, String data) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO soundmachine_songs (user_id, item_id, title, length, data) VALUES (?, ?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setLong(2, soundMachineId);
|
||||
preparedStatement.setString(3, title);
|
||||
preparedStatement.setInt(4, length);
|
||||
preparedStatement.setString(5, data);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveSong(int songId, String title, int length, String data) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE soundmachine_songs SET title = ?, length = ?, data = ? WHERE id = ?", sqlConnection);
|
||||
preparedStatement.setString(1, title);
|
||||
preparedStatement.setInt(2, length);
|
||||
preparedStatement.setString(3, data);
|
||||
preparedStatement.setInt(4, songId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static Map<Integer, Integer> getTracks(long soundMachineId) {
|
||||
Map<Integer, Integer> tracks = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT track_id, slot_id FROM soundmachine_tracks WHERE soundmachine_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, soundMachineId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
tracks.put(resultSet.getInt("slot_id"), resultSet.getInt("track_id"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return tracks;
|
||||
}
|
||||
|
||||
public static void addTrack(long soundMachineId, int trackId, int slotId) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO soundmachine_tracks (soundmachine_id, track_id, slot_id) VALUES (?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setLong(1, soundMachineId);
|
||||
preparedStatement.setInt(2, trackId);
|
||||
preparedStatement.setInt(3, slotId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeTrack(long soundMachineId, int slotId) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM soundmachine_tracks WHERE soundmachine_id = ? AND slot_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, soundMachineId);
|
||||
preparedStatement.setInt(2, slotId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Song> getSongUserList(int userId) {
|
||||
List<Song> songs = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM soundmachine_songs WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
// (int id, String title, int itemId, int length, String data, boolean isBurnt)
|
||||
while (resultSet.next()) {
|
||||
songs.add(new Song(resultSet.getInt("id"), resultSet.getString("title"), resultSet.getInt("item_id"), resultSet.getInt("user_id"),
|
||||
resultSet.getInt("length"), resultSet.getString("data"), resultSet.getBoolean("burnt")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return songs;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,381 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.room.Room;
|
||||
import org.alexdev.havana.game.tags.HabboTag;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.*;
|
||||
|
||||
public class TagDao {
|
||||
public static List<HabboTag> getTagInfoList(String tag) {
|
||||
List<HabboTag> search = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users_tags WHERE LOWER(tag) = ? AND (user_id > 0 OR group_id > 0) AND room_id = 0", sqlConnection);
|
||||
preparedStatement.setString(1, tag);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
search.add(new HabboTag(resultSet.getString("tag"), resultSet.getInt("room_id"), resultSet.getInt("user_id"), resultSet.getInt("group_id")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return search;
|
||||
}
|
||||
|
||||
public static List<Room> querySearchRooms(String searchTag) {
|
||||
List<Room> rooms = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users_tags " +
|
||||
"INNER JOIN rooms ON rooms.id = users_tags.room_id " +
|
||||
"INNER JOIN users ON rooms.owner_id = users.id " +
|
||||
"WHERE LOWER(users_tags.tag) LIKE ? LIMIT 30", sqlConnection);
|
||||
preparedStatement.setString(1, "%" + searchTag + "%");
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
Room room = new Room();
|
||||
RoomDao.fill(room.getData(), resultSet);
|
||||
rooms.add(room);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return rooms;
|
||||
}
|
||||
|
||||
public static List<Pair<String, Integer>> getPopularTags() {
|
||||
return getPopularTags(20);
|
||||
}
|
||||
|
||||
public static List<Pair<String, Integer>> getPopularTags(int num) {
|
||||
List<Pair<String, Integer>> tagList = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT tag, COUNT(*) AS quantity FROM users_tags GROUP BY tag ORDER BY quantity DESC LIMIT " + num, sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
int tags = 0;
|
||||
Map<String, Integer> temp = new HashMap<>();
|
||||
|
||||
while (resultSet.next()) {
|
||||
String tag = resultSet.getString("tag");
|
||||
int count = resultSet.getInt("quantity");
|
||||
|
||||
if (temp.containsKey(tag)) {
|
||||
count = temp.get(tag) + count;
|
||||
}
|
||||
|
||||
tags += count;
|
||||
temp.put(tag, count);
|
||||
}
|
||||
|
||||
List<Map.Entry<String, Integer> > list = new LinkedList<>(temp.entrySet());
|
||||
list.sort(Comparator.comparingInt(Map.Entry::getValue));
|
||||
|
||||
|
||||
int weight = 0;
|
||||
int[] fonts = new int[] { 10, 12, 14, 20 };//20, 14, 12, 10 };//10, 12, 14, 20};
|
||||
|
||||
if (temp.size() > 0) {
|
||||
int counter = temp.size();
|
||||
int bits = (int) Math.ceil(temp.size() / 4);
|
||||
|
||||
if (tags > 0) {
|
||||
for (var kvp : list) {
|
||||
if (counter == (bits)) {
|
||||
weight = 3;
|
||||
}
|
||||
|
||||
if (counter == (bits * 3)) {
|
||||
weight = 2;
|
||||
}
|
||||
|
||||
if (counter == (bits * 2)) {
|
||||
weight = 1;
|
||||
}
|
||||
|
||||
String key = kvp.getKey();
|
||||
|
||||
tagList.add(Pair.of(key, fonts[weight]));
|
||||
counter--;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
Collections.shuffle(tagList);
|
||||
return tagList;
|
||||
}
|
||||
|
||||
public static List<String> getUserTags(int userId) {
|
||||
List<String> roomIds = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT tag FROM users_tags WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
roomIds.add(resultSet.getString("tag"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return roomIds;
|
||||
}
|
||||
|
||||
public static List<String> getRoomTags(int roomId) {
|
||||
List<String> roomIds = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT tag FROM users_tags WHERE room_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, roomId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
roomIds.add(resultSet.getString("tag"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return roomIds;
|
||||
}
|
||||
|
||||
public static List<String> getGroupTags(int groupId) {
|
||||
List<String> roomIds = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT tag FROM users_tags WHERE group_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, groupId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
roomIds.add(resultSet.getString("tag"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return roomIds;
|
||||
}
|
||||
|
||||
public static Map<String, Integer> getRoomTagData(int num) {
|
||||
Map<String, Integer> tagList = new HashMap<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT tag, COUNT(user_id) AS quantity FROM users_tags WHERE room_id > 0 GROUP BY tag ORDER BY quantity DESC LIMIT " + num, sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
String tag = resultSet.getString("tag");
|
||||
int count = resultSet.getInt("quantity");
|
||||
|
||||
tagList.put(tag, count);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return tagList;
|
||||
}
|
||||
|
||||
public static boolean hasTag(int userId, int roomId, int groupId, String tag) {
|
||||
boolean result = false;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT tag FROM users_tags WHERE user_id = ? AND room_id = ? AND group_id = ? AND LOWER(tag) = LOWER(?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, roomId);
|
||||
preparedStatement.setInt(3, groupId);
|
||||
preparedStatement.setString(4, tag);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
result = true;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void addTag(int userId, int roomId, int groupId, String tag) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_tags (user_id, room_id, group_id, tag) VALUES (?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, roomId);
|
||||
preparedStatement.setInt(3, groupId);
|
||||
preparedStatement.setString(4, tag);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeTag(int userId, int roomId, int groupId, String tag) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM users_tags WHERE user_id = ? AND room_id = ? AND group_id = ? AND tag = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, roomId);
|
||||
preparedStatement.setInt(3, groupId);
|
||||
preparedStatement.setString(4, tag);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeTags(int userId, int roomId, int groupId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM users_tags WHERE user_id = ? AND room_id = ? AND group_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, roomId);
|
||||
preparedStatement.setInt(3, groupId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static int countTag(String tag) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
int count = 0;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT COUNT(user_id) FROM users_tags WHERE tag = ?", sqlConnection);
|
||||
preparedStatement.setString(1, tag);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
count = resultSet.getInt(1);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class TeleporterDao {
|
||||
public static long getTeleporterId(long itemId) {
|
||||
long teleporterId = -1;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT linked_id FROM items_teleporter_links WHERE item_id = ?", sqlConnection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
teleporterId = resultSet.getLong("linked_id");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return teleporterId;
|
||||
}
|
||||
|
||||
public static void addPair(long itemId, long linkedId) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO items_teleporter_links (item_id, linked_id) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setLong(1, itemId);
|
||||
preparedStatement.setLong(2, linkedId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,150 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.item.Transaction;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.List;
|
||||
|
||||
public class TransactionDao {
|
||||
public static void createTransaction(int userId, String itemId, String catalogueId, int amount, String description, int creditCost, int pixelCost, boolean visible) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_transactions (user_id, item_id, catalogue_id, amount, description, credit_cost, pixel_cost, is_visible) VALUES (?, ?, ?, ? ,?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setString(2, itemId);
|
||||
preparedStatement.setString(3, catalogueId);
|
||||
preparedStatement.setInt(4, amount);
|
||||
preparedStatement.setString(5, description);
|
||||
preparedStatement.setInt(6, creditCost);
|
||||
preparedStatement.setInt(7, pixelCost);
|
||||
preparedStatement.setInt(8, visible ? 1 : 0);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Transaction> getTransactionByItem(int itemId) {
|
||||
List<Transaction> transactions = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users_transactions WHERE item_id = ? ORDER BY users_transactions.created_at DESC", sqlConnection);
|
||||
preparedStatement.setInt(1, itemId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
transactions.add(new Transaction(resultSet.getString("item_id").split(","), resultSet.getString("description"), resultSet.getInt("credit_cost"), resultSet.getInt("pixel_cost"), resultSet.getInt("amount"),
|
||||
resultSet.getTime("created_at").getTime() / 1000L));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
public static List<Transaction> getTransactionsPastMonth(String searchQuery, boolean viewAll) {
|
||||
Calendar currentCalendar = Calendar.getInstance();
|
||||
currentCalendar.setTimeInMillis(System.currentTimeMillis());
|
||||
int month = currentCalendar.get(Calendar.MONTH) + 1;
|
||||
int year = currentCalendar.get(Calendar.YEAR);
|
||||
|
||||
List<Transaction> transactions = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users_transactions INNER JOIN users ON users.id = users_transactions.user_id WHERE MONTH(users_transactions.created_at) = ? AND YEAR(users_transactions.created_at) = ? AND user_id = ? OR username = ? ORDER BY users_transactions.created_at DESC", sqlConnection);
|
||||
preparedStatement.setInt(1, month);
|
||||
preparedStatement.setInt(2, year);
|
||||
preparedStatement.setInt(3, StringUtils.isNumeric(searchQuery) ? Integer.parseInt(searchQuery) : -1);
|
||||
preparedStatement.setString(4, searchQuery);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
boolean isVisible = resultSet.getBoolean("is_visible");
|
||||
|
||||
if (!isVisible && !viewAll) {
|
||||
continue;
|
||||
}
|
||||
|
||||
transactions.add(new Transaction(resultSet.getString("item_id").split(","), resultSet.getString("description"), resultSet.getInt("credit_cost"), resultSet.getInt("pixel_cost"), resultSet.getInt("amount"),
|
||||
resultSet.getTime("created_at").getTime() / 1000L));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
public static List<Transaction> getTransactions(int userId, int month, int year, boolean viewAll) {
|
||||
List<Transaction> transactions = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users_transactions WHERE YEAR(created_at) = ? AND MONTH(created_at) = ? AND user_id = ? ORDER BY created_at DESC", sqlConnection);
|
||||
preparedStatement.setInt(1, year);
|
||||
preparedStatement.setInt(2, month);
|
||||
preparedStatement.setInt(3, userId);
|
||||
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
boolean isVisible = resultSet.getBoolean("is_visible");
|
||||
|
||||
if (!isVisible && !viewAll) {
|
||||
continue;
|
||||
}
|
||||
|
||||
transactions.add(new Transaction(resultSet.getString("item_id").split(","), resultSet.getString("description"), resultSet.getInt("credit_cost"), resultSet.getInt("pixel_cost"), resultSet.getInt("amount"),
|
||||
resultSet.getTime("created_at").getTime() / 1000L));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return transactions;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,107 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class TutorialDao {
|
||||
public static List<Integer> getTutorialFlags(int userId) {
|
||||
List<Integer> flags = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT flags FROM users_tutorial_progress WHERE user_id = ? LIMIT 1", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
var flagResults = resultSet.getString("flags");
|
||||
|
||||
if (flagResults.length() > 0) {
|
||||
flags = Stream.of(resultSet.getString("flags").split(",")).map(Integer::parseInt).collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return flags;
|
||||
}
|
||||
|
||||
public static boolean hasTutorialFlags(int userId) {
|
||||
boolean hasFlags = false;
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT flags FROM users_tutorial_progress WHERE user_id = ? LIMIT 1", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
hasFlags = true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return hasFlags;
|
||||
}
|
||||
|
||||
public static void updateTutorialFlags(int userId, List<Integer> flags) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users_tutorial_progress SET flags = ? WHERE user_id = ? LIMIT 1", sqlConnection);
|
||||
preparedStatement.setString(1, flags.stream().map(Object::toString).collect(Collectors.joining(",")));
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void createTutorialFlags(int userId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_tutorial_progress (user_id) VALUES (?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class UsersMutesDao {
|
||||
public static List<Integer> getMutedUsers(int userId) {
|
||||
List<Integer> users = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT muted_id FROM users_mutes INNER JOIN users ON users_mutes.muted_id = users.id WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
users.add(resultSet.getInt("muted_id"));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return users;
|
||||
}
|
||||
|
||||
public static void addMuted(int userId, int mutedId) throws SQLException {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_mutes (user_id, muted_id) VALUES (?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, mutedId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
throw e;
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeMuted(int userId, int mutedId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM users_mutes WHERE user_id = ? AND muted_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, mutedId);
|
||||
preparedStatement.execute();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,136 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.catalogue.CatalogueItem;
|
||||
import org.alexdev.havana.game.misc.purse.Voucher;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Types;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class VoucherDao {
|
||||
|
||||
/**
|
||||
* Redeems a voucher.
|
||||
* Gets the voucher and then deletes it from the voucher table.
|
||||
*
|
||||
* @param voucherCode the string voucher code to redeem
|
||||
* @return the amount of credits redeemed or -1 if no voucher was found.
|
||||
*/
|
||||
public static Voucher redeemVoucher(String voucherCode, int userId) {
|
||||
Voucher voucher = null;
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
ResultSet resultSet2 = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
|
||||
//Get the voucher
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT credits,is_single_use,allow_new_users FROM vouchers WHERE voucher_code = ? " +
|
||||
"AND (expiry_date IS NULL OR (UNIX_TIMESTAMP() < UNIX_TIMESTAMP(expiry_date))) AND " +
|
||||
"NOT EXISTS (SELECT vouchers_history.user_id FROM vouchers_history WHERE vouchers_history.user_id = ? AND vouchers_history.voucher_code = ?)", sqlConnection);
|
||||
preparedStatement.setString(1, voucherCode);
|
||||
preparedStatement.setInt(2, userId);
|
||||
preparedStatement.setString(3, voucherCode);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
boolean isSingleUse = resultSet.getBoolean("is_single_use");
|
||||
voucher = new Voucher(resultSet.getInt("credits"), resultSet.getBoolean("allow_new_users"));
|
||||
|
||||
//Get related voucher items
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT catalogue_sale_code FROM vouchers_items INNER JOIN catalogue_items ON catalogue_items.sale_code = vouchers_items.catalogue_sale_code WHERE voucher_code = ?", sqlConnection);
|
||||
preparedStatement.setString(1, voucherCode);
|
||||
resultSet2 = preparedStatement.executeQuery();
|
||||
|
||||
//Find all items
|
||||
while (resultSet2.next()) {
|
||||
voucher.getItems().add(resultSet2.getString("catalogue_sale_code"));
|
||||
}
|
||||
|
||||
//Delete the voucher and related items if it's single use only
|
||||
if (isSingleUse) {
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM vouchers WHERE voucher_code = ?", sqlConnection);
|
||||
preparedStatement.setString(1, voucherCode);
|
||||
preparedStatement.executeQuery();
|
||||
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM vouchers_items WHERE voucher_code = ?", sqlConnection);
|
||||
preparedStatement.setString(1, voucherCode);
|
||||
preparedStatement.executeQuery();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
|
||||
if (resultSet2 != null)
|
||||
Storage.closeSilently(resultSet2);
|
||||
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return voucher;
|
||||
}
|
||||
|
||||
public static void logVoucher(String voucherCode, int userId, int creditsRedeemed, List<CatalogueItem> itemsRedeemed) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO vouchers_history (voucher_code, user_id, credits_redeemed, items_redeemed) VALUES (?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setString(1, voucherCode);
|
||||
preparedStatement.setInt(2, userId);
|
||||
|
||||
if (creditsRedeemed > 0) {
|
||||
preparedStatement.setInt(3, creditsRedeemed);
|
||||
} else {
|
||||
preparedStatement.setNull(3, Types.NULL);
|
||||
}
|
||||
|
||||
if (itemsRedeemed.size() > 0) {
|
||||
// Clear all duplicated items
|
||||
Map<String, Integer> distinctItems = new HashMap<>();
|
||||
|
||||
for (CatalogueItem item : itemsRedeemed) {
|
||||
if (distinctItems.containsKey(item.getSaleCode())) {
|
||||
distinctItems.put(item.getSaleCode(), distinctItems.get(item.getSaleCode()) + 1);
|
||||
} else {
|
||||
distinctItems.put(item.getSaleCode(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
|
||||
for (Map.Entry<String, Integer> kvp : distinctItems.entrySet()) {
|
||||
stringBuilder.append(kvp.getValue());
|
||||
stringBuilder.append(",");
|
||||
stringBuilder.append(kvp.getKey());
|
||||
stringBuilder.append("|");
|
||||
}
|
||||
|
||||
preparedStatement.setString(4, stringBuilder.toString().substring(0, stringBuilder.length() - 1));
|
||||
} else {
|
||||
preparedStatement.setNull(4, Types.NULL);
|
||||
}
|
||||
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.player.Wardrobe;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class WardrobeDao {
|
||||
public static List<Wardrobe> getWardrobe(int userId) {
|
||||
List<Wardrobe> wardrobeList = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM users_wardrobes WHERE user_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
wardrobeList.add(new Wardrobe(resultSet.getInt("slot_id"), resultSet.getString("sex"), resultSet.getString("figure")));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return wardrobeList;
|
||||
}
|
||||
|
||||
public static void deleteWardrobe(int userId, int slotId) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("DELETE FROM users_wardrobes WHERE user_id = ? AND slot_id = ?", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, slotId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void addWardrobe(int userId, int slotId, String figure, String sex) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("INSERT INTO users_wardrobes (user_id, slot_id, figure, sex) VALUES (?, ?, ?, ?)", sqlConnection);
|
||||
preparedStatement.setInt(1, userId);
|
||||
preparedStatement.setInt(2, slotId);
|
||||
preparedStatement.setString(3, figure);
|
||||
preparedStatement.setString(4, sex);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
|
||||
public static void updateWardrobe(int userId, int slotId, String figure, String sex) {
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("UPDATE users_wardrobes SET figure = ?, sex = ? WHERE slot_id = ? AND user_id = ?", sqlConnection);
|
||||
preparedStatement.setString(1, figure);
|
||||
preparedStatement.setString(2, sex);
|
||||
preparedStatement.setInt(3, slotId);
|
||||
preparedStatement.setInt(4, userId);
|
||||
preparedStatement.execute();
|
||||
|
||||
} catch (SQLException ex) {
|
||||
Storage.logError(ex);
|
||||
} finally {
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package org.alexdev.havana.dao.mysql;
|
||||
|
||||
import org.alexdev.havana.dao.Storage;
|
||||
import org.alexdev.havana.game.wordfilter.WordfilterWord;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class WordfilterDao {
|
||||
public static List<WordfilterWord> getBadWords() {
|
||||
List<WordfilterWord> word = new ArrayList<>();
|
||||
|
||||
Connection sqlConnection = null;
|
||||
PreparedStatement preparedStatement = null;
|
||||
ResultSet resultSet = null;
|
||||
|
||||
try {
|
||||
sqlConnection = Storage.getStorage().getConnection();
|
||||
preparedStatement = Storage.getStorage().prepare("SELECT * FROM wordfilter", sqlConnection);
|
||||
resultSet = preparedStatement.executeQuery();
|
||||
|
||||
while (resultSet.next()) {
|
||||
word.add(new WordfilterWord(resultSet.getString("word"), resultSet.getBoolean("is_bannable"), resultSet.getBoolean("is_filterable")));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Storage.logError(e);
|
||||
} finally {
|
||||
Storage.closeSilently(resultSet);
|
||||
Storage.closeSilently(preparedStatement);
|
||||
Storage.closeSilently(sqlConnection);
|
||||
}
|
||||
|
||||
return word;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,318 @@
|
|||
package org.alexdev.havana.game;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.ClubGiftDao;
|
||||
import org.alexdev.havana.dao.mysql.CurrencyDao;
|
||||
import org.alexdev.havana.dao.mysql.EffectDao;
|
||||
import org.alexdev.havana.game.catalogue.collectables.CollectablesManager;
|
||||
import org.alexdev.havana.game.club.ClubSubscription;
|
||||
import org.alexdev.havana.game.effects.Effect;
|
||||
import org.alexdev.havana.game.events.EventsManager;
|
||||
import org.alexdev.havana.game.games.GameManager;
|
||||
import org.alexdev.havana.game.item.Item;
|
||||
import org.alexdev.havana.game.item.ItemManager;
|
||||
import org.alexdev.havana.game.moderation.ChatManager;
|
||||
import org.alexdev.havana.game.moderation.cfh.CallForHelpManager;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.game.player.PlayerDetails;
|
||||
import org.alexdev.havana.game.player.PlayerManager;
|
||||
import org.alexdev.havana.log.Log;
|
||||
import org.alexdev.havana.messages.incoming.catalogue.GET_CATALOG_INDEX;
|
||||
import org.alexdev.havana.messages.outgoing.effects.AVATAR_EFFECT_EXPIRED;
|
||||
import org.alexdev.havana.messages.outgoing.user.currencies.ActivityPointNotification;
|
||||
import org.alexdev.havana.messages.outgoing.user.currencies.CREDIT_BALANCE;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
import org.alexdev.havana.util.config.GameConfiguration;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
public class GameScheduler implements Runnable {
|
||||
private AtomicLong tickRate = new AtomicLong();
|
||||
|
||||
private ScheduledExecutorService schedulerService;
|
||||
private ScheduledFuture<?> gameScheduler;
|
||||
|
||||
private BlockingQueue<Map.Entry<Player, Integer>> creditsHandoutQueue;
|
||||
private BlockingQueue<Map.Entry<Player, Integer>> pixelsHandoutQueue;
|
||||
private BlockingQueue<Item> itemSavingQueue;
|
||||
private BlockingQueue<Long> itemDeletionQueue;
|
||||
|
||||
private static GameScheduler instance;
|
||||
|
||||
private GameScheduler() {
|
||||
this.schedulerService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
|
||||
this.gameScheduler = this.schedulerService.scheduleAtFixedRate(this, 0, 1, TimeUnit.SECONDS);
|
||||
this.creditsHandoutQueue = new LinkedBlockingQueue<>();
|
||||
this.pixelsHandoutQueue = new LinkedBlockingQueue<>();
|
||||
this.itemSavingQueue = new LinkedBlockingDeque<>();
|
||||
this.itemDeletionQueue = new LinkedBlockingDeque<>();
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see java.lang.Runnable#run()
|
||||
*/
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
if (this.tickRate.get() % 10 == 0) {
|
||||
PlayerManager.getInstance().checkPlayerPeak();
|
||||
}
|
||||
|
||||
for (Player player : PlayerManager.getInstance().getPlayers()) {
|
||||
if (player.getRoomUser().getRoom() != null) {
|
||||
|
||||
// If their sleep timer is now lower than the current time, make them sleep.
|
||||
if (DateUtil.getCurrentTimeSeconds() > player.getRoomUser().getTimerManager().getSleepTimer()) {
|
||||
if (!player.getRoomUser().isSleeping()) {
|
||||
player.getRoomUser().stopCarrying();
|
||||
player.getRoomUser().sleep(true);
|
||||
}
|
||||
}
|
||||
|
||||
// If their afk timer is up, send them out.
|
||||
if (DateUtil.getCurrentTimeSeconds() > player.getRoomUser().getTimerManager().getAfkTimer()) {
|
||||
player.getRoomUser().kick(true, false);
|
||||
}
|
||||
|
||||
// If they're not sleeping (aka, active) and their next handout expired, give them their credits!
|
||||
/*if (player.getDetails().isCreditsEligible() && (DateUtil.getCurrentTimeSeconds() > player.getDetails().getNextHandout())) {
|
||||
if (!this.creditsHandoutQueue.contains(player)) {
|
||||
this.creditsHandoutQueue.put(player);
|
||||
player.getDetails().setCreditsEligible(false);
|
||||
}
|
||||
}*/
|
||||
}/* else {
|
||||
if (player.getDetails().isCreditsEligible()) {
|
||||
player.getDetails().resetNextHandout();
|
||||
}
|
||||
}*/
|
||||
|
||||
if (player.getDetails().isCreditsEligible() && (DateUtil.getCurrentTimeSeconds() > player.getDetails().getNextHandout())) {
|
||||
int credits = GameConfiguration.getInstance().getInteger("daily.credits.amount");
|
||||
|
||||
if (credits > 0) {
|
||||
if (this.creditsHandoutQueue.stream().noneMatch(entry -> entry.getKey() == player)) {
|
||||
this.queuePlayerCredits(player, credits);
|
||||
player.getDetails().setCreditsEligible(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Do pixels
|
||||
TimeUnit pixelsReceived = TimeUnit.valueOf(GameConfiguration.getInstance().getString("pixels.received.timeunit"));
|
||||
int intervalInSeconds = (int) pixelsReceived.toSeconds(GameConfiguration.getInstance().getInteger("pixels.received.interval"));
|
||||
int pixelsToGive = 15;
|
||||
|
||||
if (DateUtil.getCurrentTimeSeconds() > player.getDetails().getLastPixelsTime() && player.getRoomUser().getRoom() != null) {
|
||||
if (player.getRoomUser().getPixelAvailableTick().getAndDecrement() > 0) {
|
||||
if (this.pixelsHandoutQueue.stream().noneMatch(entry -> entry.getKey() == player)) {
|
||||
this.queuePlayerPixels(player, pixelsToGive);
|
||||
player.getDetails().setLastPixelsTime(DateUtil.getCurrentTimeSeconds() + intervalInSeconds);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check effect expiry
|
||||
List<Effect> effectsToRemove = new ArrayList<>();
|
||||
|
||||
for (Effect effect : player.getEffects()) {
|
||||
if (!effect.isActivated()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (DateUtil.getCurrentTimeSeconds() > effect.getExpireDate()) {
|
||||
effectsToRemove.add(effect);
|
||||
player.send(new AVATAR_EFFECT_EXPIRED(effect.getEffectId()));
|
||||
|
||||
if (player.getRoomUser().getRoom() != null && player.getRoomUser().isUsingEffect() && player.getRoomUser().getEffectId() == effect.getEffectId()) {
|
||||
player.getRoomUser().stopEffect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (Effect effect : effectsToRemove) {
|
||||
player.getEffects().remove(effect);
|
||||
EffectDao.deleteEffect(effect.getId());
|
||||
}
|
||||
}
|
||||
|
||||
// Resend the catalogue index every 15 minutes to clear page cache
|
||||
if (this.tickRate.get() % TimeUnit.MINUTES.toSeconds(15) == 0) {
|
||||
for (Player player : PlayerManager.getInstance().getPlayers()) {
|
||||
new GET_CATALOG_INDEX().handle(player, null);
|
||||
}
|
||||
}
|
||||
|
||||
// Save credits every 30 seconds
|
||||
//if (this.tickRate.get() % 30 == 0) {
|
||||
List<Map.Entry<Player, Integer>> creditsHandout = new ArrayList<>();
|
||||
List<Map.Entry<Player, Integer>> pixelHandout = new ArrayList<>();
|
||||
|
||||
this.creditsHandoutQueue.drainTo(creditsHandout);
|
||||
this.pixelsHandoutQueue.drainTo(pixelHandout);
|
||||
|
||||
if (creditsHandout.size() > 0) {
|
||||
Map<PlayerDetails, Integer> playerDetailsToSave = new LinkedHashMap<>();
|
||||
|
||||
for (Map.Entry<Player, Integer> entry : creditsHandout) {
|
||||
Player p = entry.getKey();
|
||||
int amount = entry.getValue();
|
||||
playerDetailsToSave.put(p.getDetails(), amount);
|
||||
}
|
||||
|
||||
CurrencyDao.increaseCredits(playerDetailsToSave);
|
||||
|
||||
for (Map.Entry<Player, Integer> entry : creditsHandout) {
|
||||
Player p = entry.getKey();
|
||||
CurrencyDao.updateEligibleCredits(p.getDetails().getId(), false);
|
||||
p.send(new CREDIT_BALANCE(p.getDetails().getCredits()));
|
||||
}
|
||||
}
|
||||
|
||||
if (pixelHandout.size() > 0) {
|
||||
Map<PlayerDetails, Integer> playerDetailsToSave = new LinkedHashMap<>();
|
||||
|
||||
for (var kvp : pixelHandout) {
|
||||
var details = kvp.getKey().getDetails();
|
||||
playerDetailsToSave.put(details, kvp.getValue());
|
||||
}
|
||||
|
||||
CurrencyDao.increasePixels(playerDetailsToSave);
|
||||
|
||||
for (var kvp : pixelHandout) {
|
||||
var p = kvp.getKey();
|
||||
//p.send(new ActivityPointNotification(p.getDetails().getPixels(), ActivityPointNotification.ActivityPointAlertType.PIXELS_SOUND)); // Alert pixel sound
|
||||
p.send(new ActivityPointNotification(p.getDetails().getPixels(), ActivityPointNotification.ActivityPointAlertType.PIXELS_RECEIVED)); // Alert pixels received
|
||||
}
|
||||
}
|
||||
//}
|
||||
|
||||
// Cycle through HC gifts
|
||||
if (this.tickRate.get() % TimeUnit.SECONDS.toSeconds(1) == 0) {
|
||||
ClubGiftDao.incrementGiftData(ClubSubscription.getClubGiftSeconds());
|
||||
}
|
||||
|
||||
// Purge expired rows
|
||||
if (this.tickRate.get() % TimeUnit.DAYS.toSeconds(1) == 0) {
|
||||
EventsManager.getInstance().removeExpiredEvents();
|
||||
}
|
||||
|
||||
// Item saving queue ticker every 10 seconds
|
||||
if (this.tickRate.get() % 10 == 0) {
|
||||
if (this.itemSavingQueue != null) {
|
||||
this.performItemSaving();
|
||||
}
|
||||
}
|
||||
|
||||
// Item deletion queue ticker every 1 second
|
||||
if (this.tickRate.get() % 5 == 0) {
|
||||
if (this.itemSavingQueue != null) {
|
||||
this.performItemDeletion();
|
||||
}
|
||||
}
|
||||
|
||||
// Check expired rentals every 60 seconds
|
||||
if (this.tickRate.get() % 60 == 0) {
|
||||
ItemManager.getInstance().checkExpiredRentals();
|
||||
}
|
||||
|
||||
// Delete expired CFH's every 60 seconds
|
||||
if (this.tickRate.get() % 60 == 0) {
|
||||
CallForHelpManager.getInstance().purgeExpiredCfh();
|
||||
}
|
||||
|
||||
// Save chat messages every 60 seconds
|
||||
if (this.tickRate.get() % 60 == 0) {
|
||||
ChatManager.getInstance().performChatSaving();
|
||||
}
|
||||
|
||||
// Call GC because why the fuck not
|
||||
if (this.tickRate.get() % 15 == 0) {
|
||||
System.gc();
|
||||
}
|
||||
|
||||
// Check xp expiry once every day
|
||||
if (this.tickRate.get() % 5 == 0) {
|
||||
GameManager.getInstance().checkXpExpiry();
|
||||
}
|
||||
|
||||
CollectablesManager.getInstance().checkExpiries();
|
||||
|
||||
} catch (Exception ex) {
|
||||
Log.getErrorLogger().error("GameScheduler crashed: ", ex);
|
||||
}
|
||||
|
||||
this.tickRate.incrementAndGet();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add player to queue to give credits to.
|
||||
*
|
||||
* @param player the player to modify
|
||||
* @param credits the credits
|
||||
*/
|
||||
public void queuePlayerCredits(Player player, int credits) {
|
||||
this.creditsHandoutQueue.add(new AbstractMap.SimpleEntry<>(player, credits));
|
||||
}
|
||||
|
||||
public void queuePlayerPixels(Player player, int pixels) {
|
||||
this.pixelsHandoutQueue.add(new AbstractMap.SimpleEntry<>(player, pixels));
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue item to be saved.
|
||||
*
|
||||
* @param item the item to save
|
||||
*/
|
||||
public void queueSaveItem(Item item) {
|
||||
this.itemSavingQueue.removeIf(i -> i.getDatabaseId() == item.getDatabaseId());
|
||||
this.itemSavingQueue.add(item);
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue item to be deleted.
|
||||
*
|
||||
* @param itemId the item to delete
|
||||
*/
|
||||
public void queueDeleteItem(Long itemId) {
|
||||
this.itemDeletionQueue.removeIf(i -> i.equals(itemId));
|
||||
this.itemDeletionQueue.add(itemId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Method to perform item saving.
|
||||
*/
|
||||
public void performItemSaving() {
|
||||
ItemManager.getInstance().performItemSaving(this.itemSavingQueue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Method to perform item deletion.
|
||||
*/
|
||||
public void performItemDeletion() {
|
||||
ItemManager.getInstance().performItemDeletion(this.itemDeletionQueue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the scheduler service.
|
||||
*
|
||||
* @return the scheduler service
|
||||
*/
|
||||
public ScheduledExecutorService getService() {
|
||||
return schedulerService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the instance
|
||||
*
|
||||
* @return the instance
|
||||
*/
|
||||
public static GameScheduler getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new GameScheduler();
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
package org.alexdev.havana.game.achievements;
|
||||
|
||||
public class AchievementInfo {
|
||||
private int id;
|
||||
private String name;
|
||||
private int level;
|
||||
private int pixelReward;
|
||||
private int progressRequired;
|
||||
|
||||
public AchievementInfo(int id, String name, int level, int pixelReward, int progressRequired) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.level = level;
|
||||
this.pixelReward = pixelReward;
|
||||
this.progressRequired = progressRequired;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the achievement id.
|
||||
*
|
||||
* @return the achievement id
|
||||
*/
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the achievement name.
|
||||
*
|
||||
* @return the achievement name
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the level of the achievement.
|
||||
*
|
||||
* @return the level
|
||||
*/
|
||||
public int getLevel() {
|
||||
return level;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the pixel reward when completing achievement.
|
||||
*
|
||||
* @return the pixel reward
|
||||
*/
|
||||
public int getPixelReward() {
|
||||
return pixelReward;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the progress required for the achievement.
|
||||
*
|
||||
* @return the progress required
|
||||
*/
|
||||
public int getProgressRequired() {
|
||||
return progressRequired;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,132 @@
|
|||
package org.alexdev.havana.game.achievements;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.AchievementDao;
|
||||
import org.alexdev.havana.dao.mysql.CurrencyDao;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.messages.outgoing.user.currencies.ActivityPointNotification;
|
||||
import org.alexdev.havana.util.StringUtil;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class AchievementManager {
|
||||
private static AchievementManager instance;
|
||||
private Map<Integer, AchievementInfo> achievements;
|
||||
|
||||
public AchievementManager() {
|
||||
this.achievements = AchievementDao.getAchievements();
|
||||
}
|
||||
|
||||
/**
|
||||
* Method for handling achievement progression.
|
||||
*
|
||||
* @param achievementType the type of achievement
|
||||
* @param player the player to handle for
|
||||
*/
|
||||
public void tryProgress(AchievementType achievementType, Player player) {
|
||||
UserAchievement userAchievement = player.getAchievementManager().locateAchievement(achievementType);
|
||||
|
||||
if (userAchievement == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (achievementType.getProgressor().tryProgress(player, userAchievement, userAchievement.getAchievementInfo())) {
|
||||
AchievementDao.saveUserAchievement(player.getDetails().getId(), userAchievement);
|
||||
}
|
||||
|
||||
if (userAchievement.getProgress() != userAchievement.getAchievementInfo().getProgressRequired()) {
|
||||
return;
|
||||
}
|
||||
|
||||
var badgeCode = userAchievement.getAchievementInfo().getName() + userAchievement.getAchievementInfo().getLevel();
|
||||
|
||||
if (userAchievement.getAchievementInfo().getName().equals("GL")) {
|
||||
badgeCode = userAchievement.getAchievementInfo().getName() + StringUtil.toAlphabetic(userAchievement.getAchievementInfo().getLevel());
|
||||
}
|
||||
|
||||
if (player.getBadgeManager().hasBadge(badgeCode)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (userAchievement.getAchievementInfo().getPixelReward() > 0) {
|
||||
CurrencyDao.increasePixels(player.getDetails(), userAchievement.getAchievementInfo().getPixelReward());
|
||||
player.send(new ActivityPointNotification(player.getDetails().getPixels(), ActivityPointNotification.ActivityPointAlertType.PIXELS_SOUND)); // Alert pixel sound
|
||||
}
|
||||
|
||||
|
||||
AchievementInfo previousAchievement = locateAchievement(achievementType, userAchievement.getAchievementInfo().getLevel() - 1);
|
||||
|
||||
if (previousAchievement != null) {
|
||||
var badgeRemoveCode = previousAchievement.getName() + previousAchievement.getLevel();
|
||||
|
||||
if (badgeRemoveCode.equals("GL")) {
|
||||
badgeRemoveCode = userAchievement.getAchievementInfo().getName() + StringUtil.toAlphabetic(userAchievement.getAchievementInfo().getLevel() - 1);
|
||||
}
|
||||
|
||||
if (!achievementType.hasRemovePreviousAchievement()) {
|
||||
badgeRemoveCode = null;
|
||||
}
|
||||
|
||||
player.getBadgeManager().tryAddBadge(badgeCode, badgeRemoveCode, 1);
|
||||
}else {
|
||||
player.getBadgeManager().tryAddBadge(badgeCode, null, userAchievement.getAchievementInfo().getLevel());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Locate achivemenet by the next level.
|
||||
*
|
||||
* @param achievementType the type of the achievement
|
||||
* @param nextLevel the next level
|
||||
* @return return the achievement found, if successful
|
||||
*/
|
||||
public AchievementInfo locateAchievement(AchievementType achievementType, int nextLevel) {
|
||||
for (AchievementInfo achievementInfo : this.achievements.values()) {
|
||||
if (achievementInfo.getName().equals(achievementType.getName()) && achievementInfo.getLevel() == nextLevel) {
|
||||
return achievementInfo;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Locate the achievement by id.
|
||||
*
|
||||
* @param achievementId the achievement id
|
||||
* @return the achievement
|
||||
*/
|
||||
public AchievementInfo getAchievement(int achievementId) {
|
||||
return this.achievements.get(achievementId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of achievements.
|
||||
*
|
||||
* @return the list of achievements
|
||||
*/
|
||||
public Map<Integer, AchievementInfo> getAchievements() {
|
||||
return achievements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the {@link AchievementManager} instance
|
||||
*
|
||||
* @return the catalogue manager instance
|
||||
*/
|
||||
public static AchievementManager getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new AchievementManager();
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the {@link AchievementManager} instance
|
||||
*/
|
||||
public static void reset() {
|
||||
instance = null;
|
||||
getInstance();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package org.alexdev.havana.game.achievements;
|
||||
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
|
||||
public interface AchievementProgress {
|
||||
boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo);
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package org.alexdev.havana.game.achievements;
|
||||
|
||||
import org.alexdev.havana.game.achievements.progressions.AchievementAIPerformanceVote;
|
||||
import org.alexdev.havana.game.achievements.progressions.*;
|
||||
|
||||
public enum AchievementType {
|
||||
ACHIEVEMENT_LOOKS("ACH_AvatarLooks", new AchievementAvatarLooks(), true),
|
||||
ACHIEVEMENT_HC("HC", new AchievementHabboClub(), true),
|
||||
ACHIEVEMENT_MOTTO("ACH_Motto", new AchievementMotto(), true),
|
||||
ACHIEVEMENT_RESPECT_GIVEN("ACH_RespectGiven", new AchievementRespectGiven(), true),
|
||||
ACHIEVEMENT_TAGS("ACH_AvatarTags", new AchievementTags(), true),
|
||||
ACHIEVEMENT_MGM("ACH_MGM", new AchievementMGM(), true),
|
||||
ACHIEVEMENT_GRADUATE("ACH_Graduate", new AchievementGraduate(), true),
|
||||
ACHIEVEMENT_HAPPYHOUR("ACH_HappyHour", new AchievementHappyHour(), true),
|
||||
ACHIEVEMENT_REGISTRATION_DURATION("ACH_RegistrationDuration", new AchievementRegistrationDuration(), true),
|
||||
ACHIEVEMENT_ROOMENTRY("ACH_RoomEntry", new AchievementRoomEntry(), true),
|
||||
ACHIEVEMENT_TRADERPASS("ACH_TraderPass", new AchievementTraderPass(), true),
|
||||
ACHIEVEMENT_AIPERFORMANCEVOTE("ACH_AIPerformanceVote", new AchievementAIPerformanceVote(), true),
|
||||
ACHIEVEMENT_RESPECT_EARNED("ACH_RespectEarned", new AchievementRespectEarned(), true),
|
||||
ACHIEVEMENT_LOGIN("ACH_Login", new AchievementLogin(), true),
|
||||
ACHIEVEMENT_ALL_TIME_HOTEL_PRESENCE("ACH_AllTimeHotelPresence", new AchievementAllTimeHotelPresence(), true),
|
||||
ACHIEVEMENT_GAME_PLAYED("ACH_GamePlayed", new AchievementGamePlayed(), true),
|
||||
ACHIEVEMENT_GUIDE("GL", new AchievementGuide(), false),
|
||||
ACHIEVEMENT_STUDENT("ACH_Student", new AchievementStudent(), true),
|
||||
ACHIEVEMENT_EMAIL_VERIFICATION("ACH_EmailVerification", new AchievementEmailVerification(), true);
|
||||
|
||||
private final String avchievementName;
|
||||
private final AchievementProgress achievementProgressor;
|
||||
private final boolean removePreviousAchievement;
|
||||
|
||||
AchievementType(String achievementName, AchievementProgress achievementProgressor, boolean removePreviousAchievement) {
|
||||
this.avchievementName = achievementName;
|
||||
this.achievementProgressor = achievementProgressor;
|
||||
this.removePreviousAchievement = removePreviousAchievement;
|
||||
}
|
||||
|
||||
public static AchievementType getByName(String name) {
|
||||
for (AchievementType achievementType : values()) {
|
||||
if (achievementType.getName().equals(name)) {
|
||||
return achievementType;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return avchievementName;
|
||||
}
|
||||
|
||||
public AchievementProgress getProgressor() {
|
||||
return achievementProgressor;
|
||||
}
|
||||
|
||||
public boolean hasRemovePreviousAchievement() {
|
||||
return removePreviousAchievement;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
|
||||
public class AchievementAIPerformanceVote implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
int progress = userAchievement.getProgress() + 1;
|
||||
|
||||
if (progress > achievementInfo.getProgressRequired()) {
|
||||
progress = achievementInfo.getProgressRequired();
|
||||
}
|
||||
|
||||
userAchievement.setProgress(progress);
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.game.player.statistics.PlayerStatistic;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class AchievementAllTimeHotelPresence implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
int daysSince = (int) Math.floor(TimeUnit.SECONDS.toHours(player.getStatisticManager().getIntValue(PlayerStatistic.ONLINE_TIME)));//AchievementDao.getOnlineTime(player.getDetails().getId()))));
|
||||
|
||||
if (daysSince >= achievementInfo.getProgressRequired()) {
|
||||
userAchievement.setProgress(achievementInfo.getProgressRequired());
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
|
||||
public class AchievementAvatarLooks implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
userAchievement.setProgress(achievementInfo.getProgressRequired());
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
|
||||
public class AchievementEmailVerification implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.game.player.statistics.PlayerStatistic;
|
||||
|
||||
public class AchievementGamePlayed implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
int progress = player.getStatisticManager().getIntValue(PlayerStatistic.BATTLEBALL_GAMES_WON) + player.getStatisticManager().getIntValue(PlayerStatistic.SNOWSTORM_GAMES_WON);
|
||||
|
||||
if (progress >= userAchievement.getProgress()) {
|
||||
if (progress > achievementInfo.getProgressRequired()) {
|
||||
progress = achievementInfo.getProgressRequired();
|
||||
}
|
||||
|
||||
userAchievement.setProgress(progress);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.util.config.GameConfiguration;
|
||||
|
||||
public class AchievementGraduate implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
if (!GameConfiguration.getInstance().getBoolean("tutorial.enabled")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
//if (!player.getDetails().getTutorialFlags().contains(1)) {
|
||||
userAchievement.setProgress(achievementInfo.getProgressRequired());
|
||||
return true;
|
||||
//}
|
||||
|
||||
//return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.game.player.statistics.PlayerStatistic;
|
||||
|
||||
public class AchievementGuide implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
int progress = player.getStatisticManager().getIntValue(PlayerStatistic.PLAYERS_GUIDED);
|
||||
|
||||
if (progress >= userAchievement.getProgress()) {
|
||||
userAchievement.setProgress(progress);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.club.ClubSubscription;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
|
||||
public class AchievementHabboClub implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
boolean canProgress = false;
|
||||
|
||||
if (achievementInfo.getLevel() == 1) {
|
||||
if (player.getDetails().hasClubSubscription()) {
|
||||
canProgress = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (achievementInfo.getLevel() == 2) {
|
||||
if (ClubSubscription.hasGoldClubSubscription(player)) {
|
||||
canProgress = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (achievementInfo.getLevel() == 3) {
|
||||
if (ClubSubscription.hasPlatinumClubSubscription(player)) {
|
||||
canProgress = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (canProgress) {
|
||||
userAchievement.setProgress(achievementInfo.getProgressRequired());
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.Havana;
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
|
||||
public class AchievementHappyHour implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
if (Havana.isHappyHour()) {
|
||||
userAchievement.setProgress(achievementInfo.getProgressRequired());
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.game.player.statistics.PlayerStatistic;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class AchievementLogin implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
int progress = 0;
|
||||
|
||||
if (!player.getDetails().getPreviousRespectDay().equals(DateUtil.getCurrentDate(DateUtil.SHORT_DATE))) {
|
||||
String yesterday = DateUtil.getDate(DateUtil.getCurrentTimeSeconds() - TimeUnit.DAYS.toSeconds(1), DateUtil.SHORT_DATE);
|
||||
|
||||
if (yesterday.equals(player.getDetails().getPreviousRespectDay())) {
|
||||
progress++;
|
||||
} else {
|
||||
player.getStatisticManager().setLongValue(PlayerStatistic.DAYS_LOGGED_IN_ROW, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/*PlayerStatisticsDao.getStatistic(player.getDetails().getId(), PlayerStatistic.DAYS_LOGGED_IN_ROW);
|
||||
if (TimeUnit.SECONDS.toDays(daysBtwLastLogin) > 1) {
|
||||
progress = 0;
|
||||
}
|
||||
else if (TimeUnit.SECONDS.toDays(daysBtwLastLogin) == 1) {
|
||||
progress++;
|
||||
}*/
|
||||
|
||||
if (progress > 0) {
|
||||
player.getStatisticManager().incrementValue(PlayerStatistic.DAYS_LOGGED_IN_ROW, progress);
|
||||
progress = player.getStatisticManager().getIntValue(PlayerStatistic.DAYS_LOGGED_IN_ROW);
|
||||
}
|
||||
|
||||
if (progress > achievementInfo.getProgressRequired()) {
|
||||
progress = achievementInfo.getProgressRequired();
|
||||
}
|
||||
|
||||
if (progress > 0) {
|
||||
userAchievement.setProgress(progress);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.ReferredDao;
|
||||
import org.alexdev.havana.dao.mysql.TagDao;
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
|
||||
public class AchievementMGM implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
int progress = ReferredDao.countReferred(player.getDetails().getId());
|
||||
|
||||
if (progress > achievementInfo.getProgressRequired()) {
|
||||
progress = achievementInfo.getProgressRequired();
|
||||
}
|
||||
|
||||
if (progress != userAchievement.getProgress()) {
|
||||
userAchievement.setProgress(progress);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
|
||||
public class AchievementMotto implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
userAchievement.setProgress(achievementInfo.getProgressRequired());
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.Havana;
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class AchievementRegistrationDuration implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
int daysSinceJoined = (int) Math.floor(TimeUnit.SECONDS.toDays((long) (DateUtil.getCurrentTimeSeconds() - Math.floor(player.getDetails().getJoinDate()))));
|
||||
|
||||
if (daysSinceJoined >= achievementInfo.getProgressRequired()) {
|
||||
userAchievement.setProgress(achievementInfo.getProgressRequired());
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.AchievementDao;
|
||||
import org.alexdev.havana.dao.mysql.PlayerDao;
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementManager;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.AchievementType;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.messages.outgoing.rooms.user.RESPECT_NOTIFICATION;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class AchievementRespectEarned implements AchievementProgress {
|
||||
public static void convertOldPoints(Player player) {
|
||||
if (!(player.getDetails().getRespectPoints() > 0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 1; i < 11; i++) {
|
||||
if (!(player.getDetails().getRespectPoints() > 0)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
AchievementInfo achievementInfo = AchievementManager.getInstance().locateAchievement(AchievementType.ACHIEVEMENT_RESPECT_EARNED, i);
|
||||
|
||||
if (player.getDetails().getRespectPoints() >= achievementInfo.getProgressRequired()) {
|
||||
player.getDetails().setRespectPoints(player.getDetails().getRespectPoints() - achievementInfo.getProgressRequired());
|
||||
|
||||
var achievement = player.getAchievementManager().locateAchievement(AchievementType.ACHIEVEMENT_RESPECT_EARNED);
|
||||
achievement.setProgress(achievementInfo.getProgressRequired() - 1);
|
||||
AchievementDao.saveUserAchievement(player.getDetails().getId(), achievement);
|
||||
} else {
|
||||
int currentPoints = player.getDetails().getRespectPoints();
|
||||
player.getDetails().setRespectPoints(0);
|
||||
|
||||
var achievement = player.getAchievementManager().locateAchievement(AchievementType.ACHIEVEMENT_RESPECT_EARNED);
|
||||
achievement.setProgress(currentPoints - 1);
|
||||
AchievementDao.saveUserAchievement(player.getDetails().getId(), achievement);
|
||||
}
|
||||
|
||||
AchievementManager.getInstance().tryProgress(AchievementType.ACHIEVEMENT_RESPECT_EARNED, player);
|
||||
}
|
||||
|
||||
if (player.getDetails().getRespectPoints() > 0) {
|
||||
player.getDetails().setRespectPoints(0);
|
||||
}
|
||||
|
||||
PlayerDao.saveRespect(player.getDetails().getId(), player.getDetails().getDailyRespectPoints(), player.getDetails().getRespectPoints(), player.getDetails().getRespectDay(), player.getDetails().getRespectGiven());
|
||||
}
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
int progress = userAchievement.getProgress() + 1;
|
||||
|
||||
if (progress > achievementInfo.getProgressRequired()) {
|
||||
progress = achievementInfo.getProgressRequired();
|
||||
}
|
||||
|
||||
if (progress != userAchievement.getProgress()) {
|
||||
userAchievement.setProgress(progress);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
|
||||
public class AchievementRespectGiven implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
userAchievement.setProgress(userAchievement.getProgress() + 1);
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.RoomVisitsDao;
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
|
||||
public class AchievementRoomEntry implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
int progress = RoomVisitsDao.countVisits(player.getDetails().getId());
|
||||
|
||||
if (progress > achievementInfo.getProgressRequired()) {
|
||||
progress = achievementInfo.getProgressRequired();
|
||||
}
|
||||
|
||||
if (progress != userAchievement.getProgress()) {
|
||||
userAchievement.setProgress(progress);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
|
||||
public class AchievementStudent implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
userAchievement.setProgress(achievementInfo.getProgressRequired());
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.TagDao;
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
|
||||
public class AchievementTags implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
var tagList = TagDao.getUserTags(player.getDetails().getId());
|
||||
|
||||
int progress = tagList.size();
|
||||
|
||||
if (progress >= 5) {
|
||||
progress = achievementInfo.getProgressRequired();
|
||||
}
|
||||
|
||||
if (progress >= achievementInfo.getProgressRequired()) {
|
||||
userAchievement.setProgress(progress);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package org.alexdev.havana.game.achievements.progressions;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementProgress;
|
||||
import org.alexdev.havana.game.achievements.user.UserAchievement;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.util.config.GameConfiguration;
|
||||
|
||||
public class AchievementTraderPass implements AchievementProgress {
|
||||
@Override
|
||||
public boolean tryProgress(Player player, UserAchievement userAchievement, AchievementInfo achievementInfo) {
|
||||
/*var canUseTrade = true;TimeUnit.SECONDS.toDays(DateUtil.getCurrentTimeSeconds() - player.getDetails().getJoinDate()) >= 3 &&
|
||||
player.getStatisticManager().getIntValue(PlayerStatistic.ONLINE_TIME) >= TimeUnit.MINUTES.toHours(60) && player.getDetails().isTradeEnabled();*/
|
||||
|
||||
if (player.getDetails().isTradeEnabled()/* && isActivated(player.getStatisticManager().getValue(PlayerStatistic.ACTIVATION_CODE))*/) {
|
||||
userAchievement.setProgress(achievementInfo.getProgressRequired());
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean isActivated(String activationCode) {
|
||||
if (!GameConfiguration.getInstance().getBoolean("email.smtp.enable")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return activationCode == null;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package org.alexdev.havana.game.achievements.user;
|
||||
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementManager;
|
||||
|
||||
public class UserAchievement {
|
||||
private int achievementId;
|
||||
private int userId;
|
||||
private int progress;
|
||||
|
||||
public UserAchievement(int achievementId, int userId, int progress) {
|
||||
this.achievementId = achievementId;
|
||||
this.userId = userId;
|
||||
this.progress = progress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the achievement information.
|
||||
*
|
||||
* @return the achievement information
|
||||
*/
|
||||
public AchievementInfo getAchievementInfo() {
|
||||
return AchievementManager.getInstance().getAchievement(this.achievementId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the user id who has this achievement.
|
||||
*
|
||||
* @return the user id
|
||||
*/
|
||||
public int getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current progress of the achievement.
|
||||
*
|
||||
* @return the progress
|
||||
*/
|
||||
public int getProgress() {
|
||||
return progress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the current progress of the achievement.
|
||||
*
|
||||
* @param progress the current progress
|
||||
*/
|
||||
public void setProgress(int progress) {
|
||||
this.progress = progress;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,260 @@
|
|||
package org.alexdev.havana.game.achievements.user;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.AchievementDao;
|
||||
import org.alexdev.havana.game.achievements.AchievementInfo;
|
||||
import org.alexdev.havana.game.achievements.AchievementManager;
|
||||
import org.alexdev.havana.game.achievements.AchievementType;
|
||||
import org.alexdev.havana.game.club.ClubSubscription;
|
||||
import org.alexdev.havana.game.groups.GroupMemberRank;
|
||||
import org.alexdev.havana.game.guides.GuideManager;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
import org.alexdev.havana.util.config.GameConfiguration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class UserAchievementManager {
|
||||
private int playerId;
|
||||
private List<UserAchievement> userAchievements;
|
||||
|
||||
/**
|
||||
* Load the user achievements by the player.
|
||||
*
|
||||
* @param playerId the player to load
|
||||
*/
|
||||
public void loadAchievements(int playerId) {
|
||||
this.playerId = playerId;
|
||||
this.userAchievements = AchievementDao.getUserAchievements(playerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find user achievement by given name.
|
||||
*
|
||||
* @param achievementType the achievement type
|
||||
* @return the user achievement
|
||||
*/
|
||||
public UserAchievement locateAchievement(AchievementType achievementType) {
|
||||
if (this.userAchievements == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var optional = this.userAchievements.stream()
|
||||
.filter(ach -> ach.getAchievementInfo().getName().equals(achievementType.getName()))
|
||||
.sorted(Comparator.comparingInt(ach -> ach.getAchievementInfo().getLevel()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
UserAchievement latestAchievement = null;
|
||||
|
||||
if (optional.size() > 0) {
|
||||
latestAchievement = optional.get(optional.size() - 1);
|
||||
}
|
||||
|
||||
if (latestAchievement != null) {
|
||||
// User has already completed the achievement? Try add the next achievement else return nothing
|
||||
if (latestAchievement.getProgress() >= latestAchievement.getAchievementInfo().getProgressRequired()) {
|
||||
var nextAchievement = AchievementManager.getInstance().locateAchievement(achievementType, latestAchievement.getAchievementInfo().getLevel() + 1);
|
||||
|
||||
if (nextAchievement != null) {
|
||||
var userAchievement = new UserAchievement(nextAchievement.getId(), playerId, 0);
|
||||
AchievementDao.newUserAchievement(playerId, userAchievement);
|
||||
|
||||
this.userAchievements.add(userAchievement);
|
||||
return userAchievement;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return latestAchievement;
|
||||
}
|
||||
|
||||
} else {
|
||||
int achievementId = AchievementManager.getInstance().locateAchievement(achievementType, 1).getId();
|
||||
|
||||
var userAchievement = new UserAchievement(achievementId, playerId, 0);
|
||||
AchievementDao.newUserAchievement(playerId, userAchievement);
|
||||
|
||||
this.userAchievements.add(userAchievement);
|
||||
return userAchievement;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the list of possible achievements a user can get.
|
||||
*
|
||||
* @return the list of possible achievements
|
||||
*/
|
||||
public List<AchievementInfo> getPossibleAchievements() {
|
||||
List<AchievementInfo> possibleAchievements = new ArrayList<>();
|
||||
|
||||
for (var achievementInfo : AchievementManager.getInstance().getAchievements().values()) {
|
||||
if (this.userAchievements.stream().anyMatch(userAchievement ->
|
||||
userAchievement.getAchievementInfo().getName().equals(achievementInfo.getName()) &&
|
||||
userAchievement.getProgress() >= achievementInfo.getProgressRequired())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
long badgeCount = possibleAchievements.stream().filter(userAchievement -> userAchievement.getName().equals(achievementInfo.getName())).count();
|
||||
|
||||
if (badgeCount >= 5) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.userAchievements.stream().anyMatch(userAchievement -> userAchievement.getAchievementInfo().getName().equals(achievementInfo.getName()) && userAchievement.getProgress() >= achievementInfo.getProgressRequired())) {
|
||||
var optionalUserAchievement = this.userAchievements.stream().filter(userAchievement -> userAchievement.getAchievementInfo().getName().equals(achievementInfo.getName())).findFirst();
|
||||
|
||||
if (optionalUserAchievement.isPresent()) {
|
||||
var foundAchievement = optionalUserAchievement.get();
|
||||
var newAchievement = AchievementManager.getInstance().locateAchievement(AchievementType.getByName(achievementInfo.getName()), foundAchievement.getAchievementInfo().getLevel() + 1);
|
||||
|
||||
if (newAchievement != null) {
|
||||
possibleAchievements.add(newAchievement);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
possibleAchievements.add(achievementInfo);
|
||||
}
|
||||
}
|
||||
|
||||
possibleAchievements.sort(Comparator.comparing(achievementInfo -> (achievementInfo.getName() + achievementInfo.getLevel())));
|
||||
return possibleAchievements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the user achievements.
|
||||
*
|
||||
* @return the user achievements
|
||||
*/
|
||||
public List<UserAchievement> getUserAchievements() {
|
||||
return userAchievements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the achievement by level.
|
||||
*/
|
||||
public UserAchievement getAchievement(AchievementType achievementType, int level) {
|
||||
for (var achievement : userAchievements) {
|
||||
if (achievement.getAchievementInfo().getName().equals(achievementType.getName())) {
|
||||
if (achievement.getAchievementInfo().getLevel() == level) {
|
||||
return achievement;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the max completed achievement the user has by achievement name
|
||||
*/
|
||||
public UserAchievement getLatestAchievement(AchievementType achievementType) {
|
||||
List<UserAchievement> achievements = this.userAchievements.stream().filter(achievement -> achievement.getAchievementInfo().getName().equals(achievementType.getName()))
|
||||
.sorted(Comparator.comparingInt((UserAchievement achievement) -> achievement.getAchievementInfo().getLevel()).reversed())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
achievements.removeIf(achievement -> achievement.getAchievementInfo().getProgressRequired() > achievement.getProgress());
|
||||
return achievements.size() > 0 ? achievements.get(0) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process any achievements when user logs in again.
|
||||
*/
|
||||
public void processAchievements(Player player, boolean isLogin) {
|
||||
if (isLogin) {
|
||||
AchievementManager.getInstance().tryProgress(AchievementType.ACHIEVEMENT_TAGS, player);
|
||||
AchievementManager.getInstance().tryProgress(AchievementType.ACHIEVEMENT_LOGIN, player);
|
||||
}
|
||||
|
||||
AchievementManager.getInstance().tryProgress(AchievementType.ACHIEVEMENT_HC, player);
|
||||
AchievementManager.getInstance().tryProgress(AchievementType.ACHIEVEMENT_MGM, player);
|
||||
AchievementManager.getInstance().tryProgress(AchievementType.ACHIEVEMENT_HAPPYHOUR, player);
|
||||
AchievementManager.getInstance().tryProgress(AchievementType.ACHIEVEMENT_REGISTRATION_DURATION, player);
|
||||
AchievementManager.getInstance().tryProgress(AchievementType.ACHIEVEMENT_HC, player);
|
||||
AchievementManager.getInstance().tryProgress(AchievementType.ACHIEVEMENT_ALL_TIME_HOTEL_PRESENCE, player);
|
||||
AchievementManager.getInstance().tryProgress(AchievementType.ACHIEVEMENT_GUIDE, player);
|
||||
AchievementManager.getInstance().tryProgress(AchievementType.ACHIEVEMENT_TRADERPASS, player);
|
||||
AchievementManager.getInstance().tryProgress(AchievementType.ACHIEVEMENT_EMAIL_VERIFICATION, player);
|
||||
|
||||
GuideManager.getInstance().tryProgress(player);
|
||||
GuideManager.getInstance().checkGuidingFriends(player);
|
||||
|
||||
ClubSubscription.checkBadges(player);
|
||||
|
||||
// Habbo Guide admins
|
||||
if (player.getGuideManager().isGuide()) {
|
||||
if (!player.getBadgeManager().hasBadge("GLK")) {
|
||||
int guideGroupId = GameConfiguration.getInstance().getInteger("guides.group.id");
|
||||
var groupMember = player.getJoinedGroup(guideGroupId).getMember(player.getDetails().getId());
|
||||
|
||||
if (groupMember != null &&
|
||||
(groupMember.getMemberRank() == GroupMemberRank.ADMINISTRATOR ||
|
||||
groupMember.getMemberRank() == GroupMemberRank.OWNER)) {
|
||||
player.getBadgeManager().tryAddBadge("GLK", null);
|
||||
} else {
|
||||
player.getGuideManager().setGuide(GuideManager.getInstance().isGuide(player));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Habbo eXperts
|
||||
if (GameConfiguration.getInstance().getInteger("habbo.experts.group.id") > 0) {
|
||||
if (!player.getBadgeManager().hasBadge("XXX")) {
|
||||
int expertsGroupId = GameConfiguration.getInstance().getInteger("habbo.experts.group.id");
|
||||
var group = player.getJoinedGroup(expertsGroupId);
|
||||
|
||||
if (group != null) {
|
||||
var expertsMember = group.getMember(player.getDetails().getId());
|
||||
|
||||
if (expertsMember != null) {
|
||||
player.getBadgeManager().tryAddBadge("XXX", null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ChildLine
|
||||
if (GameConfiguration.getInstance().getInteger("childline.group.id") > 0) {
|
||||
if (!player.getBadgeManager().hasBadge("UK176")) {
|
||||
int expertsGroupId = GameConfiguration.getInstance().getInteger("childline.group.id");
|
||||
var group = player.getJoinedGroup(expertsGroupId);
|
||||
|
||||
if (group != null) {
|
||||
var expertsMember = group.getMember(player.getDetails().getId());
|
||||
|
||||
if (expertsMember != null) {
|
||||
player.getBadgeManager().tryAddBadge("UK176", null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Calendar currentCalendar = Calendar.getInstance();
|
||||
currentCalendar.setTimeInMillis(player.getDetails().getJoinDate() * 1000);
|
||||
|
||||
//System.out.println("Join date: " + currentCalendar.get(Calendar.YEAR) + " / " + currentCalendar.get(Calendar.MONTH) + " / " + currentCalendar.get(Calendar.DAY_OF_MONTH));
|
||||
|
||||
long currentTime = DateUtil.getCurrentTimeSeconds();
|
||||
//long time = DateUtil.getFromFormat(DateUtil.SHORT_DATE, "11-11-2019");
|
||||
|
||||
if ((currentTime > DateUtil.getFromFormat(DateUtil.SHORT_DATE, "1-12-2019")) && (currentTime < DateUtil.getFromFormat(DateUtil.SHORT_DATE, "31-12-2019"))) {
|
||||
player.getBadgeManager().tryAddBadge("XM19", null);
|
||||
}
|
||||
|
||||
long joinDate = player.getDetails().getJoinDate();
|
||||
|
||||
if ((joinDate > DateUtil.getFromFormat(DateUtil.SHORT_DATE, "10-12-2019")) && (joinDate < DateUtil.getFromFormat(DateUtil.SHORT_DATE, "18-12-2019"))) {
|
||||
player.getBadgeManager().tryAddBadge("MRG00", null);
|
||||
}
|
||||
|
||||
// If joined opening day
|
||||
if ((joinDate > DateUtil.getFromFormat(DateUtil.SHORT_DATE, "10-12-2019")) && (joinDate <= DateUtil.getFromFormat(DateUtil.SHORT_DATE, "12-12-2019"))) {
|
||||
player.getBadgeManager().tryAddBadge("Z64", null);
|
||||
}
|
||||
|
||||
// Remove special badge.
|
||||
//player.getBadgeManager().tryAddBadge("Z64", null);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,97 @@
|
|||
package org.alexdev.havana.game.ads;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.AdvertisementsDao;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class AdManager {
|
||||
private static AdManager instance;
|
||||
private final Map<Integer, List<Advertisement>> ads;
|
||||
|
||||
public AdManager() {
|
||||
this.ads = AdvertisementsDao.getAds();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the {@link AdManager} instance
|
||||
*
|
||||
* @return the item manager instance
|
||||
*/
|
||||
public static AdManager getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new AdManager();
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the item manager singleton.
|
||||
*/
|
||||
public void reset() {
|
||||
instance = null;
|
||||
AdManager.getInstance();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the collection of ads to use.
|
||||
*
|
||||
* @return the list of ads
|
||||
*/
|
||||
public Advertisement getRandomAd(int roomId) {
|
||||
if (this.ads.containsKey(roomId)) {
|
||||
List<Advertisement> advertisements = this.ads.get(roomId).stream().filter(ad -> ad.isEnabled() && !ad.isLoadingAd()).collect(Collectors.toList());
|
||||
return advertisements.get(ThreadLocalRandom.current().nextInt(advertisements.size()));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the collection of ads to use.
|
||||
*
|
||||
* @return the list of ads
|
||||
*/
|
||||
public Advertisement getRandomLoadingAd() {
|
||||
List<Advertisement> advertisements = this.ads.containsKey(-1) ? this.ads.get(-1).stream().filter(ad -> ad.isEnabled() && ad.isLoadingAd()).collect(Collectors.toList()) : List.of();
|
||||
|
||||
if (advertisements.size() > 0) {
|
||||
return advertisements.get(ThreadLocalRandom.current().nextInt(advertisements.size()));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the collection of ads to use.
|
||||
*
|
||||
* @return the list of ads
|
||||
*/
|
||||
public Advertisement getAd(int id) {
|
||||
for (var kvp : this.ads.values()) {
|
||||
for (Advertisement advertisement : kvp) {
|
||||
if (advertisement.getId() == id) {
|
||||
return advertisement;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<Advertisement> getAds() {
|
||||
List<Advertisement> advertisementList = new ArrayList<>();
|
||||
|
||||
for (var roomAds : ads.values()) {
|
||||
for (var ad : roomAds) {
|
||||
advertisementList.add(ad);
|
||||
}
|
||||
}
|
||||
|
||||
return advertisementList;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package org.alexdev.havana.game.ads;
|
||||
|
||||
public class Advertisement {
|
||||
private int id;
|
||||
private int roomId;
|
||||
private boolean isLoadingAd;
|
||||
private String image;
|
||||
private String url;
|
||||
private boolean enabled;
|
||||
|
||||
public Advertisement(int id, boolean isLoadingAd, int roomId, String image, String url, boolean enabled) {
|
||||
this.id = id;
|
||||
this.isLoadingAd = isLoadingAd;
|
||||
this.roomId = roomId;
|
||||
this.image = image;
|
||||
this.url = url;
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public boolean isLoadingAd() {
|
||||
return isLoadingAd;
|
||||
}
|
||||
|
||||
public int getRoomId() {
|
||||
return roomId;
|
||||
}
|
||||
|
||||
public String getImage() {
|
||||
return image;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package org.alexdev.havana.game.alerts;
|
||||
|
||||
public class AccountAlert {
|
||||
private final int id;
|
||||
private final int userId;
|
||||
private final AlertType alertType;
|
||||
private final String message;
|
||||
private final boolean isDisabled;
|
||||
private final long createdAt;
|
||||
|
||||
public AccountAlert(int id, int userId, AlertType alertType, String message, boolean isDisabled, long createdAt) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
this.alertType = alertType;
|
||||
this.message = message;
|
||||
this.isDisabled = isDisabled;
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public int getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public AlertType getAlertType() {
|
||||
return alertType;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public boolean isDisabled() {
|
||||
return isDisabled;
|
||||
}
|
||||
|
||||
public long getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package org.alexdev.havana.game.alerts;
|
||||
|
||||
public enum AlertType {
|
||||
HC_EXPIRED,
|
||||
PRESENT,
|
||||
TUTOR_SCORE,
|
||||
CREDIT_DONATION
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package org.alexdev.havana.game.badges;
|
||||
|
||||
public class Badge {
|
||||
private String badgeCode;
|
||||
private boolean equipped;
|
||||
private int slotId;
|
||||
|
||||
public Badge(String badgeCode, boolean equipped, int slotId) {
|
||||
this.badgeCode = badgeCode;
|
||||
this.equipped = equipped;
|
||||
this.slotId = slotId;
|
||||
}
|
||||
|
||||
public String getBadgeCode() {
|
||||
return badgeCode;
|
||||
}
|
||||
|
||||
public boolean isEquipped() {
|
||||
return equipped;
|
||||
}
|
||||
|
||||
public void setEquipped(boolean equipped) {
|
||||
this.equipped = equipped;
|
||||
}
|
||||
|
||||
public int getSlotId() {
|
||||
return slotId;
|
||||
}
|
||||
|
||||
public void setSlotId(int slotId) {
|
||||
this.slotId = slotId;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,195 @@
|
|||
package org.alexdev.havana.game.badges;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.BadgeDao;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.messages.outgoing.user.badges.ACHIEVEMENT_NOTIFICATION;
|
||||
import org.alexdev.havana.messages.outgoing.user.badges.AVAILABLE_BADGES;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class BadgeManager {
|
||||
private int userId;
|
||||
private Player player;
|
||||
|
||||
private List<Badge> badges;
|
||||
private Set<Badge> badgesToSave;
|
||||
|
||||
public BadgeManager() {
|
||||
this.badgesToSave = new HashSet<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load badges by constructor, the player will be null.
|
||||
*
|
||||
* @param userId the user id
|
||||
*/
|
||||
public BadgeManager(int userId) {
|
||||
super();
|
||||
this.userId = userId;
|
||||
this.badges = BadgeDao.getBadges(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load players used when client logs into server.
|
||||
*
|
||||
* @param player the player instance
|
||||
*/
|
||||
public void loadBadges(Player player) {
|
||||
this.player = player;
|
||||
this.userId = player.getDetails().getId();
|
||||
this.badges = BadgeDao.getBadges(this.userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh badges, will also try and see if it can progress any achievements.
|
||||
*/
|
||||
public void refreshBadges() {
|
||||
this.player.send(new AVAILABLE_BADGES(this.getBadges(), this.getEquippedBadges()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get if the user has a badge.
|
||||
*
|
||||
* @param badgeCode the badge code to check
|
||||
* @return true, if they do
|
||||
*/
|
||||
public boolean hasBadge(String badgeCode) {
|
||||
for (Badge badge : this.badges) {
|
||||
if (badge.getBadgeCode().toLowerCase().equals(badgeCode.toLowerCase())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the badge instance by badge code.
|
||||
*
|
||||
* @param badgeCode the badge code to check for.
|
||||
* @return the badge instance, if found
|
||||
*/
|
||||
public Badge getBadge(String badgeCode) {
|
||||
for (Badge badge : this.badges) {
|
||||
if (badge.getBadgeCode().toLowerCase().equals(badgeCode.toLowerCase())) {
|
||||
return badge;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the badge, by setting it as equipped or not, slot id or not, by the badge code.
|
||||
*
|
||||
* @param badgeCode the badge code of the badge to edit
|
||||
* @param equipped whether it's equipped
|
||||
* @param slotId the badge slot id (1-5)
|
||||
*/
|
||||
public void changeBadge(String badgeCode, boolean equipped, int slotId) {
|
||||
if (!this.hasBadge(badgeCode)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Badge badge = this.getBadge(badgeCode);
|
||||
badge.setEquipped(equipped);
|
||||
badge.setSlotId(slotId);
|
||||
|
||||
this.badgesToSave.add(badge);
|
||||
}
|
||||
|
||||
/**
|
||||
* Try and add badge to player, if successful, will send a notification that a badge has been added.
|
||||
*
|
||||
* @param badgeCode the code of the badge to add
|
||||
* @param badgeRemove the badge to remove (such as achievements replacing the lower level)
|
||||
* @return the badge instance, if successfully added
|
||||
*/
|
||||
public Badge tryAddBadge(String badgeCode, String badgeRemove) {
|
||||
return tryAddBadge(badgeCode, badgeRemove, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Try and add badge to player, if successful, will send a notification that a badge has been added.
|
||||
*
|
||||
* @param badgeCode the code of the badge to add
|
||||
* @param badgeRemove the badge to remove (such as achievements replacing the lower level)
|
||||
* @param level the level to add
|
||||
* @return the badge instance, if successfully added
|
||||
*/
|
||||
public Badge tryAddBadge(String badgeCode, String badgeRemove, int level) {
|
||||
if (this.hasBadge(badgeCode)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (badgeRemove != null) {
|
||||
this.removeBadge(badgeRemove);
|
||||
}
|
||||
|
||||
Badge badge = new Badge(badgeCode, false, 0);
|
||||
this.badges.add(badge);
|
||||
|
||||
BadgeDao.newBadge(this.userId, badgeCode);
|
||||
|
||||
if (this.player != null) {
|
||||
this.player.send(new ACHIEVEMENT_NOTIFICATION(badgeCode, badgeRemove, level));
|
||||
}
|
||||
return badge;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the badge by badge code.
|
||||
*
|
||||
* @param badgeCode the badge code to add
|
||||
* @return the instance of the badge removed.
|
||||
*/
|
||||
public Badge removeBadge(String badgeCode) {
|
||||
if (!this.hasBadge(badgeCode)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Badge badge = this.getBadge(badgeCode);
|
||||
this.badges.remove(badge);
|
||||
|
||||
BadgeDao.removeBadge(this.userId, badge.getBadgeCode());
|
||||
return badge;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save badges that have been queued to save.
|
||||
*/
|
||||
public void saveQueuedBadges() {
|
||||
BadgeDao.saveBadgeChanges(this.userId, this.badgesToSave);
|
||||
this.badgesToSave.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of all unequipped badges.
|
||||
*
|
||||
* @return the list of all unequipped badges
|
||||
*/
|
||||
public List<Badge> getUnequippedBadges() {
|
||||
return badges.stream().filter(badge -> !badge.isEquipped()).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of all equipped badges.
|
||||
*
|
||||
* @return the list of equipped badges
|
||||
*/
|
||||
public List<Badge> getEquippedBadges() {
|
||||
return badges.stream().filter(Badge::isEquipped).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all badges.
|
||||
*
|
||||
* @return the list of all badges
|
||||
*/
|
||||
public List<Badge> getBadges() {
|
||||
return badges;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package org.alexdev.havana.game.ban;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.BanDao;
|
||||
import org.alexdev.havana.dao.mysql.PlayerDao;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
|
||||
public class Ban {
|
||||
private final BanType banType;
|
||||
private final String value;
|
||||
private final String message;
|
||||
private final long bannedUtil;
|
||||
private final long bannedAt;
|
||||
private final int bannedBy;
|
||||
|
||||
public Ban(BanType banType, String value, String message, long bannedUntil, long bannedAt, int bannedBy) {
|
||||
this.banType = banType;
|
||||
this.value = value;
|
||||
this.message = message;
|
||||
this.bannedUtil = bannedUntil;
|
||||
this.bannedAt = bannedAt;
|
||||
this.bannedBy = bannedBy;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
if (this.banType == BanType.MACHINE_ID) {
|
||||
return BanDao.getName(this.value);
|
||||
}
|
||||
|
||||
if (this.banType == BanType.USER_ID) {
|
||||
var name = PlayerDao.getName(Integer.parseInt(this.value));
|
||||
return name != null ? name : "";
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
public String getBannedBy() {
|
||||
if (this.bannedBy == -1) {
|
||||
return "Triggered spam filter";
|
||||
}
|
||||
|
||||
if (this.bannedBy > 0) {
|
||||
var name = PlayerDao.getName(this.bannedBy);
|
||||
return name != null ? name : "";
|
||||
}
|
||||
|
||||
return "Legacy Banned";
|
||||
}
|
||||
|
||||
public BanType getBanType() {
|
||||
return banType;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public String getBannedUtil() {
|
||||
return DateUtil.getDate(bannedUtil, DateUtil.LONG_DATE);
|
||||
}
|
||||
|
||||
public String getBannedAt() {
|
||||
return DateUtil.getDate(bannedAt, DateUtil.LONG_DATE);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package org.alexdev.havana.game.ban;
|
||||
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.game.player.PlayerManager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
|
||||
public class BanManager {
|
||||
private static BanManager instance;
|
||||
|
||||
/**
|
||||
* Disconnect ban accounts based on the following ban criteria.
|
||||
*
|
||||
* @param criteria the criteria to ban
|
||||
*/
|
||||
public void disconnectBanAccounts(Map<BanType, String> criteria) {
|
||||
for (Player player : new ArrayList<>(PlayerManager.getInstance().getPlayers())) {
|
||||
if (criteria.containsKey(BanType.USER_ID)) {
|
||||
if (player.getDetails().getId() == Integer.parseInt(criteria.get(BanType.USER_ID))) {
|
||||
player.getNetwork().getChannel().close();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (criteria.containsKey(BanType.MACHINE_ID)) {
|
||||
if (player.getDetails().getMachineId() != null && player.getDetails().getMachineId().equals(criteria.get(BanType.MACHINE_ID))) {
|
||||
player.getNetwork().getChannel().close();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/*if (criteria.containsKey(BanType.IP_ADDRESS)) {
|
||||
if (NettyPlayerNetwork.getIpAddress(player.getNetwork().getChannel()).equals(criteria.get(BanType.IP_ADDRESS))) {
|
||||
player.getNetwork().getChannel().close();
|
||||
break;
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the instance
|
||||
*
|
||||
* @return the instance
|
||||
*/
|
||||
public static BanManager getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new BanManager();
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package org.alexdev.havana.game.ban;
|
||||
|
||||
public enum BanType {
|
||||
USER_ID,
|
||||
MACHINE_ID,
|
||||
IP_ADDRESS;
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
package org.alexdev.havana.game.bot;
|
||||
|
||||
import org.alexdev.havana.game.entity.Entity;
|
||||
import org.alexdev.havana.game.entity.EntityType;
|
||||
import org.alexdev.havana.game.fuserights.Fuseright;
|
||||
import org.alexdev.havana.game.player.PlayerDetails;
|
||||
import org.alexdev.havana.game.room.entities.RoomBot;
|
||||
import org.alexdev.havana.game.room.entities.RoomEntity;
|
||||
|
||||
public class Bot extends Entity {
|
||||
private PlayerDetails playerDetails;
|
||||
private RoomBot roomUser;
|
||||
private BotData botData;
|
||||
private long nextWalkTime;
|
||||
private long nextSpeechTime;
|
||||
|
||||
public Bot() {
|
||||
this.playerDetails = new PlayerDetails();
|
||||
this.roomUser = new RoomBot(this);
|
||||
}
|
||||
|
||||
public Bot(BotData botData) {
|
||||
this.playerDetails = new PlayerDetails();
|
||||
this.roomUser = new RoomBot(this);
|
||||
this.botData = botData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasFuse(Fuseright permission) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerDetails getDetails() {
|
||||
return this.playerDetails;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RoomEntity getRoomUser() {
|
||||
return this.roomUser;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityType getType() {
|
||||
return EntityType.BOT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dispose() { }
|
||||
|
||||
public BotData getBotData() {
|
||||
return botData;
|
||||
}
|
||||
|
||||
public long getNextWalkTime() {
|
||||
return nextWalkTime;
|
||||
}
|
||||
|
||||
public void setNextWalkTime(long nextWalkTime) {
|
||||
this.nextWalkTime = nextWalkTime;
|
||||
}
|
||||
|
||||
public long getNextSpeechTime() {
|
||||
return nextSpeechTime;
|
||||
}
|
||||
|
||||
public void setNextSpeechTime(long nextSpeechTime) {
|
||||
this.nextSpeechTime = nextSpeechTime;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,109 @@
|
|||
package org.alexdev.havana.game.bot;
|
||||
|
||||
import org.alexdev.havana.game.pathfinder.Position;
|
||||
import org.alexdev.havana.util.StringUtil;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class BotData {
|
||||
private String name;
|
||||
private String mission;
|
||||
private Position startPosition;
|
||||
private String figure;
|
||||
|
||||
private List<Position> walkspace;
|
||||
private List<BotSpeech> speeches;
|
||||
private List<BotSpeech> responses;
|
||||
private List<BotSpeech> unrecognisedSpeech;
|
||||
private List<String> drinks;
|
||||
|
||||
public BotData(String name, String mission, String figure) {
|
||||
this.name = name;
|
||||
this.mission = mission;
|
||||
this.figure = figure;
|
||||
this.startPosition = new Position();
|
||||
this.walkspace = new ArrayList<>();
|
||||
this.speeches = new ArrayList<>();
|
||||
this.responses = new ArrayList<>();
|
||||
this.unrecognisedSpeech = new ArrayList<>();
|
||||
this.drinks = new ArrayList<>();
|
||||
}
|
||||
|
||||
public BotData(String name, String mission, int x, int y, int headRotation, int bodyRotation, String figure, String walkspaceData,
|
||||
String speech, String responses, String unrecognisedResponses, String drinks) {
|
||||
this.name = name;
|
||||
this.mission = mission;
|
||||
this.startPosition = new Position(x, y, 0, headRotation, bodyRotation);
|
||||
this.figure = figure;
|
||||
this.walkspace = new ArrayList<>();
|
||||
|
||||
for (String positionDatas : walkspaceData.split(" ")) {
|
||||
String[] positionData = positionDatas.split(",");
|
||||
this.walkspace.add(new Position(Integer.parseInt(positionData[0]), Integer.parseInt(positionData[1])));
|
||||
}
|
||||
|
||||
if (this.walkspace.stream().noneMatch(position -> position.getX() == this.startPosition.getX() && position.getY() == this.startPosition.getY())) {
|
||||
this.walkspace.add(new Position(this.startPosition.getX(), this.startPosition.getY()));
|
||||
}
|
||||
|
||||
this.speeches = this.parseSpeech(speech);
|
||||
this.responses = this.parseSpeech(responses);
|
||||
this.unrecognisedSpeech = this.parseSpeech(unrecognisedResponses);
|
||||
this.drinks = drinks.length() > 0 ? Arrays.asList(drinks.split(",")) : new ArrayList<>();
|
||||
}
|
||||
|
||||
private List<BotSpeech> parseSpeech(String responses) {
|
||||
var botSpeech = new ArrayList<BotSpeech>();
|
||||
|
||||
for (String sentence : responses.split(Pattern.quote("|"))) {
|
||||
String text = StringUtil.filterInput(sentence, true);
|
||||
|
||||
if (text.isBlank())
|
||||
continue;
|
||||
|
||||
botSpeech.add(new BotSpeech(sentence));
|
||||
}
|
||||
|
||||
return botSpeech;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
|
||||
public String getMission() {
|
||||
return mission;
|
||||
}
|
||||
|
||||
public Position getStartPosition() {
|
||||
return startPosition;
|
||||
}
|
||||
|
||||
public String getFigure() {
|
||||
return figure;
|
||||
}
|
||||
|
||||
public List<Position> getWalkspace() {
|
||||
return walkspace;
|
||||
}
|
||||
|
||||
public List<BotSpeech> getSpeeches() {
|
||||
return speeches;
|
||||
}
|
||||
|
||||
public List<BotSpeech> getResponses() {
|
||||
return responses;
|
||||
}
|
||||
|
||||
public List<BotSpeech> getUnrecognisedSpeech() {
|
||||
return unrecognisedSpeech;
|
||||
}
|
||||
|
||||
public List<String> getDrinks() {
|
||||
return drinks;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,125 @@
|
|||
package org.alexdev.havana.game.bot;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.BotDao;
|
||||
import org.alexdev.havana.game.pathfinder.Position;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.game.room.Room;
|
||||
import org.alexdev.havana.game.room.tasks.BotTask;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class BotManager {
|
||||
private static BotManager instance;
|
||||
|
||||
public BotManager() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Called upon initial room entry to load room bots.
|
||||
*
|
||||
* @param room the room to add the bots to
|
||||
*/
|
||||
public void addBots(Room room) {
|
||||
List<BotData> botDataList = BotDao.getBotData(room.getId());
|
||||
|
||||
for (BotData botData : botDataList) {
|
||||
Bot bot = new Bot(botData);
|
||||
bot.getDetails().fill(0, botData.getName(), botData.getFigure(), botData.getMission(), "M");
|
||||
|
||||
Position startPosition = botData.getStartPosition();
|
||||
startPosition.setZ(room.getMapping().getTile(botData.getStartPosition().getX(), botData.getStartPosition().getY()).getWalkingHeight());
|
||||
|
||||
room.getEntityManager().enterRoom(bot, startPosition);
|
||||
}
|
||||
|
||||
if (botDataList.size() > 0) {
|
||||
room.getTaskManager().scheduleTask("BotCommandTask", new BotTask(room), 0, 1, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the speech called upon the bots.
|
||||
*
|
||||
* @param player the player speaking
|
||||
* @param room the room speaking in
|
||||
* @param message the message spoken
|
||||
*/
|
||||
public void handleSpeech(Player player, Room room, String message) {
|
||||
List<Bot> bots = new ArrayList<>();
|
||||
|
||||
for (Bot bot : room.getEntityManager().getEntitiesByClass(Bot.class)) {
|
||||
if (bot.getRoomUser().getPosition().getDistanceSquared(player.getRoomUser().getPosition()) > 14) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (bot.getBotData() == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
bots.add(bot);
|
||||
}
|
||||
|
||||
for (Bot bot : bots) {
|
||||
String drink = HasRequestedDrink(player, bot, message);
|
||||
|
||||
if (drink != null) {
|
||||
if (bot.getBotData().getResponses().size() > 0) {
|
||||
var botSpeech = bot.getBotData().getResponses().get(ThreadLocalRandom.current().nextInt(bot.getBotData().getResponses().size()));
|
||||
var chatMessage = botSpeech.getSpeech();
|
||||
|
||||
chatMessage = chatMessage.replace("%lowercaseDrink%", drink.toLowerCase());
|
||||
chatMessage = chatMessage.replace("%drink%", drink);
|
||||
|
||||
bot.getRoomUser().talk(chatMessage, botSpeech.getChatMessageType());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (message.toLowerCase().contains(bot.getDetails().getName().toLowerCase())) {
|
||||
if (bot.getBotData().getUnrecognisedSpeech().size()>0) {
|
||||
var botSpeech = bot.getBotData().getUnrecognisedSpeech().get(ThreadLocalRandom.current().nextInt(bot.getBotData().getUnrecognisedSpeech().size()));
|
||||
bot.getRoomUser().talk(botSpeech.getSpeech(), botSpeech.getChatMessageType());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String HasRequestedDrink(Player player, Bot bot, String message) {
|
||||
if (bot.getBotData().getDrinks().isEmpty())
|
||||
return null;
|
||||
|
||||
for (String drink : bot.getBotData().getDrinks()) {
|
||||
if (message.toLowerCase().contains(drink.toLowerCase())) {
|
||||
player.getRoomUser().carryItem(-1, drink);
|
||||
return drink;
|
||||
}
|
||||
}
|
||||
|
||||
if (message.toLowerCase().contains("drink please") ||
|
||||
message.toLowerCase().contains("can i have") ||
|
||||
message.toLowerCase().contains("i'll have")) {
|
||||
String drink = bot.getBotData().getDrinks().get(ThreadLocalRandom.current().nextInt(bot.getBotData().getDrinks().size()));
|
||||
player.getRoomUser().carryItem(-1, drink);
|
||||
return drink;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the {@link BotManager} instance
|
||||
*
|
||||
* @return the catalogue manager instance
|
||||
*/
|
||||
public static BotManager getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new BotManager();
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package org.alexdev.havana.game.bot;
|
||||
|
||||
import org.alexdev.havana.game.item.Item;
|
||||
import org.alexdev.havana.messages.outgoing.rooms.user.CHAT_MESSAGE;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class BotSpeech {
|
||||
private String speech;
|
||||
private CHAT_MESSAGE.ChatMessageType chatMessageType;
|
||||
|
||||
public BotSpeech(String speech) {
|
||||
if (speech.contains("#")) {
|
||||
this.speech = speech.split(Pattern.quote("#"))[0];
|
||||
this.chatMessageType = CHAT_MESSAGE.ChatMessageType.valueOf(speech.split(Pattern.quote("#"))[1]);
|
||||
} else {
|
||||
this.speech = speech;
|
||||
this.chatMessageType = CHAT_MESSAGE.ChatMessageType.CHAT;
|
||||
}
|
||||
}
|
||||
|
||||
public String getSpeech() {
|
||||
return speech;
|
||||
}
|
||||
|
||||
public CHAT_MESSAGE.ChatMessageType getChatMessageType() {
|
||||
return chatMessageType;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,198 @@
|
|||
package org.alexdev.havana.game.catalogue;
|
||||
|
||||
import org.alexdev.havana.game.item.base.ItemBehaviour;
|
||||
import org.alexdev.havana.game.item.base.ItemDefinition;
|
||||
import org.alexdev.havana.game.item.ItemManager;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class CatalogueItem {
|
||||
private int id;
|
||||
private String saleCode;
|
||||
private int[] pages;
|
||||
private int orderId;
|
||||
private int priceCoins;
|
||||
private int pricePixels;
|
||||
private int seasonalCoins;
|
||||
private int seasonalPixels;
|
||||
private int amount;
|
||||
private boolean hidden;
|
||||
private ItemDefinition definition;
|
||||
private String itemSpecialId;
|
||||
private boolean isPackage;
|
||||
private List<CataloguePackage> packages;
|
||||
private int definitionId;
|
||||
private String activeAt;
|
||||
|
||||
public CatalogueItem(int id, String saleCode, String pageId, int orderId, int price, int pricePixels, int seasonalCoins, int seasonalPixels, int amount, boolean hidden, int definitionId, String itemSpecialId, boolean isPackage, String activeAt) {
|
||||
int[] pages = new int[pageId.split(",").length];
|
||||
|
||||
int i = 0;
|
||||
if (pageId.length() > 0) {
|
||||
for (String data : pageId.split(",")) {
|
||||
pages[i++] = Integer.parseInt(data);
|
||||
}
|
||||
}
|
||||
|
||||
this.setPageData(id, saleCode, pages, orderId, price, pricePixels, seasonalCoins, seasonalPixels, amount, hidden, definitionId, itemSpecialId, isPackage, activeAt);
|
||||
}
|
||||
|
||||
|
||||
public CatalogueItem(int id, String saleCode, int[] pages, int orderId, int price, int pricePixels, int seasonalCoins, int seasonalPixels, int amount, boolean hidden, int definitionId, String itemSpecialId, boolean isPackage, String activeAt) {
|
||||
this.setPageData(id, saleCode, pages, orderId, price, pricePixels, seasonalCoins, seasonalPixels, amount, hidden, definitionId, itemSpecialId, isPackage, activeAt);
|
||||
}
|
||||
|
||||
private void setPageData(int id, String saleCode, int[] pages, int orderId, int price, int pricePixels, int seasonalCoins, int seasonalPixels, int amount, boolean hidden, int definitionId, String itemSpecialId, boolean isPackage, String activeAt) {
|
||||
this.id = id;
|
||||
this.saleCode = saleCode;
|
||||
this.orderId = orderId;
|
||||
this.priceCoins = price;
|
||||
this.pricePixels = pricePixels;
|
||||
this.seasonalCoins = seasonalCoins;
|
||||
this.seasonalPixels = seasonalPixels;
|
||||
this.amount = amount;
|
||||
this.hidden = hidden;
|
||||
this.definitionId = definitionId;
|
||||
this.definition = ItemManager.getInstance().getDefinition(definitionId);
|
||||
this.itemSpecialId = itemSpecialId;
|
||||
this.isPackage = isPackage;
|
||||
this.packages = new ArrayList<>();
|
||||
this.pages = pages;
|
||||
this.activeAt = activeAt;
|
||||
|
||||
if (this.definition == null && !this.isPackage) {
|
||||
System.out.println("Item " + this.id + " (" + this.saleCode + ") has an invalid definition id: " + definitionId);
|
||||
}
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
if (this.isPackage) {
|
||||
return "d";
|
||||
} else {
|
||||
if (this.definition.hasBehaviour(ItemBehaviour.WALL_ITEM)) {
|
||||
return "i";
|
||||
} else if (this.definition.hasBehaviour(ItemBehaviour.EFFECT)) {
|
||||
return "e";
|
||||
} else {
|
||||
return "s";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String getSaleCode() {
|
||||
return saleCode;
|
||||
}
|
||||
|
||||
public int[] getPages() {
|
||||
return pages;
|
||||
}
|
||||
|
||||
public boolean hasPage(int pageId) {
|
||||
for (int page : this.pages) {
|
||||
if (page == pageId) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public ItemDefinition getDefinition() {
|
||||
return definition;
|
||||
}
|
||||
|
||||
public int getPriceCoins() {
|
||||
return priceCoins;
|
||||
}
|
||||
|
||||
public int getPricePixels() {
|
||||
return pricePixels;
|
||||
}
|
||||
|
||||
public int getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setPriceCoins(int priceCoins) {
|
||||
this.priceCoins = priceCoins;
|
||||
}
|
||||
|
||||
public void setPricePixels(int pricePixels) {
|
||||
this.pricePixels = pricePixels;
|
||||
}
|
||||
|
||||
public int getSeasonalCoins() {
|
||||
return seasonalCoins;
|
||||
}
|
||||
|
||||
public void setSeasonalCoins(int seasonalCoins) {
|
||||
this.seasonalCoins = seasonalCoins;
|
||||
}
|
||||
|
||||
public int getSeasonalPixels() {
|
||||
return seasonalPixels;
|
||||
}
|
||||
|
||||
public void setSeasonalPixels(int seasonalPixels) {
|
||||
this.seasonalPixels = seasonalPixels;
|
||||
}
|
||||
|
||||
public String getItemSpecialId() {
|
||||
return itemSpecialId;
|
||||
}
|
||||
|
||||
public boolean isPackage() {
|
||||
return isPackage;
|
||||
}
|
||||
|
||||
public List<CataloguePackage> getPackages() {
|
||||
if (this.isPackage) {
|
||||
return packages;
|
||||
}
|
||||
|
||||
List<CataloguePackage> items = new ArrayList<>();
|
||||
items.add(new CataloguePackage(this.saleCode, this.definition.getId(), this.itemSpecialId, this.amount));
|
||||
|
||||
return items;
|
||||
|
||||
}
|
||||
|
||||
public String getActiveAt() {
|
||||
return activeAt;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
if (activeAt == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return this.activeAt.equalsIgnoreCase(DateUtil.getDate(DateUtil.getCurrentTimeSeconds(), "MM-dd"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy the catalogue item instance so we can set prices that won't affect the main instance.
|
||||
*
|
||||
* @return the new catalogue item instance
|
||||
*/
|
||||
public CatalogueItem copy() {
|
||||
return new CatalogueItem(this.id, this.saleCode, this.pages, this.orderId, this.priceCoins, this.pricePixels, this.seasonalCoins, this.seasonalPixels, this.amount, this.hidden, this.definition.getId(), this.itemSpecialId, this.isPackage, this.activeAt);
|
||||
}
|
||||
|
||||
public boolean isHidden() {
|
||||
return hidden;
|
||||
}
|
||||
|
||||
public int getDefinitionId() {
|
||||
return definitionId;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,518 @@
|
|||
package org.alexdev.havana.game.catalogue;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.*;
|
||||
import org.alexdev.havana.game.catalogue.collectables.CollectableData;
|
||||
import org.alexdev.havana.game.catalogue.collectables.CollectablesManager;
|
||||
import org.alexdev.havana.game.effects.Effect;
|
||||
import org.alexdev.havana.game.item.Item;
|
||||
import org.alexdev.havana.game.item.base.ItemBehaviour;
|
||||
import org.alexdev.havana.game.item.base.ItemDefinition;
|
||||
import org.alexdev.havana.game.item.extradata.ExtraDataManager;
|
||||
import org.alexdev.havana.game.item.extradata.types.TrophyExtraData;
|
||||
import org.alexdev.havana.game.item.interactors.InteractionType;
|
||||
import org.alexdev.havana.game.pets.PetManager;
|
||||
import org.alexdev.havana.game.player.Player;
|
||||
import org.alexdev.havana.game.player.PlayerDetails;
|
||||
import org.alexdev.havana.game.player.PlayerManager;
|
||||
import org.alexdev.havana.game.player.PlayerRank;
|
||||
import org.alexdev.havana.game.player.statistics.PlayerStatistic;
|
||||
import org.alexdev.havana.game.player.statistics.PlayerStatisticManager;
|
||||
import org.alexdev.havana.game.room.mapping.RoomMapping;
|
||||
import org.alexdev.havana.messages.outgoing.effects.AVATAR_EFFECTS;
|
||||
import org.alexdev.havana.messages.outgoing.effects.AVATAR_EFFECT_ADDED;
|
||||
import org.alexdev.havana.messages.outgoing.user.currencies.FILM;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
import org.alexdev.havana.util.HexValidator;
|
||||
import org.alexdev.havana.util.StringUtil;
|
||||
import org.alexdev.havana.util.config.GameConfiguration;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class CatalogueManager {
|
||||
public static final int XP_BOX_COST = 100;
|
||||
public static final int DAILY_LIMIT_XP = 300;//150;
|
||||
|
||||
private static CatalogueManager instance;
|
||||
|
||||
private List<CataloguePage> cataloguePageList;
|
||||
private List<CatalogueItem> catalogueItemList;
|
||||
private List<CataloguePackage> cataloguePackageList;
|
||||
|
||||
private Map<String, List<String>> badgeRewards;
|
||||
|
||||
public CatalogueManager() {
|
||||
this.cataloguePageList = CatalogueDao.getPages();
|
||||
this.cataloguePackageList = CatalogueDao.getPackages();
|
||||
this.catalogueItemList = CatalogueDao.getItems();
|
||||
this.loadPackages();
|
||||
this.reloadBadgeRewards();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the badge rewards upon purchasing an item
|
||||
*/
|
||||
public void reloadBadgeRewards() {
|
||||
this.badgeRewards = CatalogueDao.getBadgeRewards();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the child tabs.
|
||||
*
|
||||
* @param parentId the parent id
|
||||
* @param rank the rank
|
||||
* @return the child tabs
|
||||
*/
|
||||
public List<CataloguePage> getChildPages(int parentId, int rank, boolean hasClub) {
|
||||
List<CataloguePage> pageList = new ArrayList<>();
|
||||
|
||||
for (var page : this.cataloguePageList) {
|
||||
if (page.getParentId() != parentId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (page.getMinRole().getRankId() > rank) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (page.isClubOnly() && !hasClub) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!page.isValidSeasonal()) {
|
||||
if (PlayerRank.COMMUNITY_MANAGER.getRankId() > rank) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
pageList.add(page);
|
||||
}
|
||||
|
||||
return pageList;
|
||||
|
||||
|
||||
/*try {
|
||||
var pageList = this.cataloguePageList.stream().filter(tab -> (tab.getMinRole().getRankId() <= rank) && tab.getParentId() == parentId && tab.isValidSeasonal()).collect(Collectors.toList());
|
||||
pageList.removeIf(tab -> tab.isClubOnly() && !hasClub);
|
||||
|
||||
return pageList;
|
||||
} catch (Exception ex) {
|
||||
return new ArrayList<>();
|
||||
}*/
|
||||
}
|
||||
|
||||
/**
|
||||
* Load catalogue packages for all catalogue items.
|
||||
*/
|
||||
private void loadPackages() {
|
||||
for (CatalogueItem catalogueItem : this.catalogueItemList) {
|
||||
if (!catalogueItem.isPackage()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (CataloguePackage cataloguePackage : this.cataloguePackageList) {
|
||||
if (catalogueItem.getSaleCode().equals(cataloguePackage.getSaleCode())) {
|
||||
catalogueItem.getPackages().add(cataloguePackage);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a page by the page index
|
||||
*
|
||||
* @param pageIndex the index of the page to get for
|
||||
* @return the catalogue page
|
||||
*/
|
||||
public CataloguePage getCataloguePage(int pageIndex) {
|
||||
for (CataloguePage cataloguePage : this.cataloguePageList) {
|
||||
if (cataloguePage.getId() == pageIndex) {
|
||||
return cataloguePage;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an item by it's sale code.
|
||||
*
|
||||
* @param saleCode the item sale code identifier
|
||||
* @return the item, if successful
|
||||
*/
|
||||
public CatalogueItem getCatalogueItem(String saleCode) {
|
||||
for (CatalogueItem catalogueItem : this.catalogueItemList) {
|
||||
if (catalogueItem.getSaleCode().equals(saleCode)) {
|
||||
return catalogueItem;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an item by its catalogue item id.
|
||||
*
|
||||
* @return the item, if successful
|
||||
*/
|
||||
public CatalogueItem getCatalogueItem(int itemId) {
|
||||
for (CatalogueItem catalogueItem : this.catalogueItemList) {
|
||||
if (catalogueItem.getId() == itemId) {
|
||||
return catalogueItem;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an item by its catalogue sprite id.
|
||||
*
|
||||
* @return the item, if successful
|
||||
*/
|
||||
public CatalogueItem getCatalogueBySprite(int spriteId) {
|
||||
for (CatalogueItem catalogueItem : this.catalogueItemList) {
|
||||
if (catalogueItem == null || catalogueItem.getDefinition() == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (catalogueItem.getDefinition().getSpriteId() == spriteId) {
|
||||
return catalogueItem;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get catalogue page list for a certain rank
|
||||
*
|
||||
* @return the list of catalogue pages
|
||||
*/
|
||||
public List<CatalogueItem> getSeasonalItems() {
|
||||
List<CatalogueItem> itemList = new ArrayList<>();
|
||||
|
||||
for (CatalogueItem catalogueItem : this.catalogueItemList) {
|
||||
if (catalogueItem.isActive()) {
|
||||
var item = catalogueItem.copy();
|
||||
item.setPriceCoins(item.getSeasonalCoins());
|
||||
item.setPricePixels(item.getSeasonalPixels());
|
||||
itemList.add(item);
|
||||
}
|
||||
}
|
||||
|
||||
return itemList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of items for the catalogue page.
|
||||
*
|
||||
* @param pageId the id of the page to get the items for
|
||||
* @param rawItems if this is set to true, pages like the rares page and collectables page will not return any items
|
||||
* @return the list of items
|
||||
*/
|
||||
public List<CatalogueItem> getCataloguePageItems(int pageId, boolean rawItems) {
|
||||
List<CatalogueItem> items = new ArrayList<>();
|
||||
|
||||
// Ignore any game logic checks when requesting catalogue pages
|
||||
if (!rawItems) {
|
||||
if (pageId == GameConfiguration.getInstance().getInteger("rare.cycle.page.id")) {
|
||||
var itemList = getSeasonalItems();
|
||||
|
||||
if (itemList.size() > 0) {
|
||||
return itemList;
|
||||
}
|
||||
}
|
||||
|
||||
// Do collectables
|
||||
CollectableData collectableData = CollectablesManager.getInstance().getCollectableDataByPage(pageId);
|
||||
|
||||
if (collectableData != null) {
|
||||
CatalogueItem catalogueItem = collectableData.getActiveItem();
|
||||
return List.of(catalogueItem);
|
||||
}
|
||||
}
|
||||
|
||||
for (CatalogueItem catalogueItem : this.catalogueItemList) {
|
||||
if (catalogueItem.isHidden()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (catalogueItem.hasPage(pageId)) {
|
||||
items.add(catalogueItem);
|
||||
}
|
||||
}
|
||||
|
||||
items.sort(Comparator.comparingInt(CatalogueItem::getOrderId));
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Purchase handler for player details.
|
||||
*
|
||||
* @param playerDetails the details for player
|
||||
* @param item the item the user is buying
|
||||
* @param extraData the extra data attached to item
|
||||
* @param overrideName the override name (used for trophies)
|
||||
* @param timestamp the time of purchase
|
||||
* @return the list of items bought
|
||||
* @throws SQLException the sql exception
|
||||
*/
|
||||
public List<Item> purchase(PlayerDetails playerDetails, CatalogueItem item, String extraData, String overrideName, long timestamp) throws SQLException {
|
||||
List<Item> itemsBought = new ArrayList<>();
|
||||
|
||||
if (!item.isPackage()) {
|
||||
for (int i = 0; i < item.getAmount(); i++) {
|
||||
Item newItem = purchase(playerDetails, item.getDefinition(), extraData, item.getItemSpecialId(), overrideName, timestamp);
|
||||
|
||||
if (newItem != null) {
|
||||
itemsBought.add(newItem);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (CataloguePackage cataloguePackage : item.getPackages()) {
|
||||
for (int i = 0; i < cataloguePackage.getAmount(); i++) {
|
||||
Item newItem = purchase(playerDetails, cataloguePackage.getDefinition(), null, cataloguePackage.getSpecialSpriteId(), overrideName, timestamp);
|
||||
|
||||
if (newItem != null) {
|
||||
itemsBought.add(newItem);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return itemsBought;
|
||||
}
|
||||
|
||||
/**
|
||||
* The player purchase handler but purchase single item.
|
||||
*
|
||||
* @param playerDetails the details of the player
|
||||
* @param def the definition of the item
|
||||
* @param extraData the extra data attached to the item
|
||||
* @param specialSpriteId the special sprite id used for posters
|
||||
* @param overrideName the override name - used for trophies
|
||||
* @param timestamp the time of purchase
|
||||
* @return the item bought
|
||||
* @throws SQLException the sql exception
|
||||
*/
|
||||
public Item purchase(PlayerDetails playerDetails, ItemDefinition def, String extraData, String specialSpriteId, String overrideName, long timestamp) throws SQLException {
|
||||
Player player = PlayerManager.getInstance().getPlayerById(playerDetails.getId());
|
||||
|
||||
if (def.hasBehaviour(ItemBehaviour.EFFECT)) {
|
||||
return purchaseEffect(playerDetails, Integer.parseInt(specialSpriteId));
|
||||
}
|
||||
|
||||
// If the item is film, just give the user film
|
||||
if (def.getSprite().equals("film")) {
|
||||
CurrencyDao.increaseFilm(playerDetails, 5);
|
||||
|
||||
if (player != null) {
|
||||
player.send(new FILM(playerDetails));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String customData = "";
|
||||
|
||||
if (extraData != null) {
|
||||
if (def.hasBehaviour(ItemBehaviour.DECORATION)) {
|
||||
customData = extraData;
|
||||
} else {
|
||||
if (specialSpriteId.length() > 0) {
|
||||
customData = specialSpriteId;
|
||||
}
|
||||
}
|
||||
|
||||
if (def.hasBehaviour(ItemBehaviour.POST_IT)) {
|
||||
customData = "20";
|
||||
}
|
||||
|
||||
if (def.getInteractionType() == InteractionType.SCOREBOARD) {
|
||||
customData = "x";
|
||||
}
|
||||
|
||||
if (def.hasBehaviour(ItemBehaviour.PRIZE_TROPHY)) {
|
||||
var trophyName = (overrideName != null ? overrideName : playerDetails.getName());
|
||||
var trophyUserData = PlayerManager.getInstance().getPlayerData(trophyName);
|
||||
|
||||
var jsonInstance = new TrophyExtraData(trophyUserData.getId(), StringUtil.filterInput(extraData, true), timestamp);
|
||||
customData = ExtraDataManager.getGson().toJson(jsonInstance);
|
||||
}
|
||||
|
||||
if (def.hasBehaviour(ItemBehaviour.ROOMDIMMER)) {
|
||||
customData = Item.DEFAULT_ROOMDIMMER_CUSTOM_DATA;
|
||||
}
|
||||
}
|
||||
|
||||
if (customData.isEmpty()) {
|
||||
customData = "0";
|
||||
}
|
||||
|
||||
Item item = new Item();
|
||||
item.setOwnerId(playerDetails.getId());
|
||||
item.setDefinitionId(def.getId());
|
||||
item.setCustomData(customData);
|
||||
|
||||
RoomMapping.resetExtraData(item, false);
|
||||
|
||||
if (item.getDefinition().getRentalTime() > 0) {
|
||||
item.setExpireTime(DateUtil.getCurrentTimeSeconds() + item.getDefinition().getRentalTime());
|
||||
}
|
||||
|
||||
// If the item is a camera, give them 2 free film.
|
||||
if (def.getSprite().equals("camera")) {
|
||||
CurrencyDao.increaseFilm(playerDetails, 2);
|
||||
|
||||
if (player != null) {
|
||||
player.send(new FILM(playerDetails));
|
||||
}
|
||||
}
|
||||
|
||||
if (def.getInteractionType() == InteractionType.PET_NEST) {
|
||||
if (extraData != null) {
|
||||
|
||||
if (!extraData.contains(Character.toString((char) 10))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String[] petData = extraData.split(Character.toString((char) 10));
|
||||
|
||||
if (petData.length != 3 || !StringUtils.isNumeric(petData[1])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String name = StringUtil.filterInput(petData[0], true);
|
||||
String type = def.getSprite().replace("pets", "");
|
||||
int race = Integer.parseInt(petData[1]);
|
||||
String color = StringUtil.filterInput(petData[2], true);
|
||||
|
||||
if (HexValidator.validate(color) && !color.startsWith("#")) {
|
||||
|
||||
if (PetManager.getInstance().isValidName(playerDetails.getName(), name) < 1) {
|
||||
ItemDao.newItem(item);
|
||||
PetDao.createPet(item.getDatabaseId(), name, type, race, color);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
ItemDao.newItem(item);
|
||||
}
|
||||
|
||||
if (def.hasBehaviour(ItemBehaviour.TELEPORTER)) {
|
||||
Item linkedTeleporterItem = new Item();
|
||||
linkedTeleporterItem.setOwnerId(playerDetails.getId());
|
||||
linkedTeleporterItem.setDefinitionId(def.getId());
|
||||
linkedTeleporterItem.setCustomData(customData);
|
||||
|
||||
if (linkedTeleporterItem.getDefinition().getRentalTime() > 0) {
|
||||
linkedTeleporterItem.setExpireTime(DateUtil.getCurrentTimeSeconds() + item.getDefinition().getRentalTime());
|
||||
}
|
||||
|
||||
ItemDao.newItem(linkedTeleporterItem);
|
||||
|
||||
if (player != null) {
|
||||
player.getInventory().addItem(linkedTeleporterItem);
|
||||
}
|
||||
|
||||
TeleporterDao.addPair(linkedTeleporterItem.getDatabaseId(), item.getDatabaseId());
|
||||
TeleporterDao.addPair(item.getDatabaseId(), linkedTeleporterItem.getDatabaseId());
|
||||
}
|
||||
|
||||
if (player != null) {
|
||||
player.getInventory().addItem(item);
|
||||
}
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
private static Item purchaseEffect(PlayerDetails playerDetails, int specialSpriteId) {
|
||||
Effect effect = EffectDao.newEffect(playerDetails.getId(), specialSpriteId, -1, false);
|
||||
|
||||
if (effect == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Player player = PlayerManager.getInstance().getPlayerById(playerDetails.getId());
|
||||
|
||||
if (player != null) {
|
||||
player.getEffects().add(effect);
|
||||
|
||||
player.send(new AVATAR_EFFECT_ADDED(effect));
|
||||
player.send(new AVATAR_EFFECTS(player.getEffects()));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get catalogue page list.
|
||||
*
|
||||
* @return the list of catalogue pages
|
||||
*/
|
||||
public List<CataloguePage> getCataloguePages() {
|
||||
return this.cataloguePageList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get catalogue page list for a certain rank
|
||||
*
|
||||
* @return the list of catalogue pages
|
||||
*/
|
||||
public List<CataloguePage> getPagesForRank(PlayerRank minimumRank) {
|
||||
List<CataloguePage> cataloguePagesForRank = new ArrayList<>();
|
||||
|
||||
for (CataloguePage page : this.cataloguePageList) {
|
||||
if (minimumRank.getRankId() >= page.getMinRole().getRankId()) {
|
||||
cataloguePagesForRank.add(page);
|
||||
}
|
||||
}
|
||||
|
||||
return cataloguePagesForRank;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get catalogue items list.
|
||||
*
|
||||
* @return the list of items packages
|
||||
*/
|
||||
public List<CatalogueItem> getCatalogueItems() {
|
||||
return catalogueItemList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the {@link CatalogueManager} instance
|
||||
*
|
||||
* @return the catalogue manager instance
|
||||
*/
|
||||
public static CatalogueManager getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new CatalogueManager();
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the catalogue manager singleton.
|
||||
*/
|
||||
public static void reset() {
|
||||
instance = null;
|
||||
CatalogueManager.getInstance();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the badge reward list
|
||||
* @return the list of badge rewards
|
||||
*/
|
||||
public Map<String, List<String>> getBadgeRewards() {
|
||||
return badgeRewards;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package org.alexdev.havana.game.catalogue;
|
||||
|
||||
import org.alexdev.havana.game.item.base.ItemDefinition;
|
||||
import org.alexdev.havana.game.item.ItemManager;
|
||||
|
||||
public class CataloguePackage {
|
||||
private String saleCode;
|
||||
private int definitionId;
|
||||
private String specialSpriteId;
|
||||
private int amount;
|
||||
|
||||
public CataloguePackage(String saleCode, int definitionId, String specialSpriteId, int amount) {
|
||||
this.saleCode = saleCode;
|
||||
this.definitionId = definitionId;
|
||||
this.specialSpriteId = specialSpriteId;
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
public String getSaleCode() {
|
||||
return saleCode;
|
||||
}
|
||||
|
||||
public int getDefinitionId() {
|
||||
return definitionId;
|
||||
}
|
||||
|
||||
public ItemDefinition getDefinition() {
|
||||
return ItemManager.getInstance().getDefinition(this.definitionId);
|
||||
}
|
||||
|
||||
public String getSpecialSpriteId() {
|
||||
return specialSpriteId;
|
||||
}
|
||||
|
||||
public int getAmount() {
|
||||
return amount;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,210 @@
|
|||
package org.alexdev.havana.game.catalogue;
|
||||
|
||||
import org.alexdev.havana.game.player.PlayerRank;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
import org.alexdev.havana.util.EasterUtil;
|
||||
import org.alexdev.havana.util.config.GameConfiguration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class CataloguePage {
|
||||
private int id;
|
||||
private int parentId;
|
||||
private PlayerRank minRole;
|
||||
private boolean isNavigatable;
|
||||
private boolean isClubOnly;
|
||||
private String name;
|
||||
private int icon;
|
||||
private int colour;
|
||||
private String layout;
|
||||
private List<String> images;
|
||||
private List<String> texts;
|
||||
private String seasonalStartDate;
|
||||
private int seasonalLength;
|
||||
|
||||
public CataloguePage(int id, int parentId, PlayerRank minRole, boolean isNavigatable, boolean isClubOnly, String name, int icon, int colour, String layout, List<String> images, List<String> texts,
|
||||
String seasonalStartDate, int seasonalLength) {
|
||||
this.id = id;
|
||||
this.parentId = parentId;
|
||||
this.minRole = minRole;
|
||||
this.isNavigatable = isNavigatable;
|
||||
this.isClubOnly = isClubOnly;
|
||||
this.name = name;
|
||||
this.icon = icon;
|
||||
this.colour = colour;
|
||||
this.layout = layout;
|
||||
this.images = images;
|
||||
this.texts = texts;
|
||||
//this.images = StringUtil.GSON.fromJson(images, new TypeToken<List<String>>(){}.getType());
|
||||
//this.texts = StringUtil.GSON.fromJson(texts, new TypeToken<List<String>>(){}.getType());
|
||||
this.seasonalStartDate = seasonalStartDate;
|
||||
this.seasonalLength = seasonalLength;
|
||||
|
||||
if (this.minRole == null) {
|
||||
this.minRole = PlayerRank.ADMINISTRATOR;
|
||||
}
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setLayout(String layout) {
|
||||
this.layout = layout;
|
||||
}
|
||||
|
||||
public PlayerRank getMinRole() {
|
||||
return minRole;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getLayout() {
|
||||
return layout;
|
||||
}
|
||||
|
||||
|
||||
/*public String getBody() {
|
||||
if (RareManager.getInstance().getCurrentRare() != null &&
|
||||
this.getId() == GameConfiguration.getInstance().getInteger("rare.cycle.page.id")) {
|
||||
|
||||
TimeUnit rareManagerUnit = TimeUnit.valueOf(GameConfiguration.getInstance().getString("rare.cycle.refresh.timeunit"));
|
||||
|
||||
long interval = rareManagerUnit.toSeconds(GameConfiguration.getInstance().getInteger("rare.cycle.refresh.interval"));
|
||||
long currentTick = RareManager.getInstance().getTick().get();
|
||||
long timeUntil = interval - currentTick;
|
||||
|
||||
return (this.body + " The time until the next rare is " + DateUtil.getReadableSeconds(timeUntil) + "!");
|
||||
}
|
||||
|
||||
return body;
|
||||
}*/
|
||||
|
||||
public int getParentId() {
|
||||
return parentId;
|
||||
}
|
||||
|
||||
public int getIcon() {
|
||||
return icon;
|
||||
}
|
||||
|
||||
public int getColour() {
|
||||
return colour;
|
||||
}
|
||||
|
||||
public boolean isNavigatable() {
|
||||
return isNavigatable;
|
||||
}
|
||||
|
||||
public boolean isClubOnly() {
|
||||
return isClubOnly;
|
||||
}
|
||||
|
||||
public List<String> getImages() {
|
||||
if (this.layout.equalsIgnoreCase("frontpage3")) {
|
||||
List<String> imageList = new ArrayList<>();
|
||||
|
||||
for (var image : images) {
|
||||
String text = image;
|
||||
|
||||
for (int i = 1; i < 5; i++) {
|
||||
if (i == 1) {
|
||||
// FilenameUtils.removeExtension(client.post().getString("catalogue.frontpage.input.1"))
|
||||
var fileName = GameConfiguration.getInstance().getString("catalogue.frontpage.input." + i);
|
||||
fileName = fileName.substring(0, fileName.lastIndexOf("."));
|
||||
|
||||
text = text.replace("{input" + i + "}", fileName);
|
||||
} else {
|
||||
text = text.replace("{input" + i + "}", GameConfiguration.getInstance().getString("catalogue.frontpage.input." + i));
|
||||
}
|
||||
}
|
||||
|
||||
imageList.add(text);
|
||||
}
|
||||
|
||||
return imageList;
|
||||
}
|
||||
|
||||
return images;
|
||||
}
|
||||
|
||||
public List<String> getTexts() {
|
||||
if (this.layout.equalsIgnoreCase("frontpage3")) {
|
||||
List<String> textList = new ArrayList<>();
|
||||
|
||||
for (var image : texts) {
|
||||
String text = image;
|
||||
|
||||
for (int i = 1; i < 5; i++) {
|
||||
text = text.replace("{input" + i + "}", GameConfiguration.getInstance().getString("catalogue.frontpage.input." + i));
|
||||
}
|
||||
|
||||
textList.add(text);
|
||||
}
|
||||
|
||||
return textList;
|
||||
}
|
||||
|
||||
return texts;
|
||||
}
|
||||
|
||||
public String getSeasonalStartDate() {
|
||||
return seasonalStartDate;
|
||||
}
|
||||
|
||||
public int getSeasonalLength() {
|
||||
return seasonalLength;
|
||||
}
|
||||
|
||||
public boolean isValidSeasonal() {
|
||||
if (!GameConfiguration.getInstance().getBoolean("seasonal.items")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.seasonalStartDate == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.seasonalStartDate.equals("EASTER")) {
|
||||
return EasterUtil.isEasterMonday();
|
||||
}
|
||||
|
||||
var currentTime = DateUtil.getCurrentTimeSeconds();
|
||||
var currentYear = DateUtil.getDate(currentTime, "yyyy");
|
||||
|
||||
var startTime = DateUtil.getFromFormat("yyyy-MM-dd", currentYear + "-" +this.seasonalStartDate);
|
||||
var endTime = startTime + this.seasonalLength;
|
||||
|
||||
return (currentTime > startTime) && (endTime > DateUtil.getCurrentTimeSeconds());
|
||||
}
|
||||
|
||||
public CataloguePage copy() {
|
||||
/*
|
||||
private int id;
|
||||
private int parentId;
|
||||
private PlayerRank minRole;
|
||||
private boolean isNavigatable;
|
||||
private boolean isClubOnly;
|
||||
private String name;
|
||||
private int icon;
|
||||
private int colour;
|
||||
private String layout;
|
||||
private List<String> images;
|
||||
private List<String> texts;
|
||||
private String seasonalStartDate;
|
||||
private int seasonalLength;
|
||||
*/
|
||||
return new CataloguePage(id, parentId, minRole, isNavigatable, isClubOnly, name, icon, colour, layout, images, texts, seasonalStartDate, seasonalLength);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
package org.alexdev.havana.game.catalogue.collectables;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.CollectablesDao;
|
||||
import org.alexdev.havana.game.catalogue.CatalogueItem;
|
||||
import org.alexdev.havana.game.catalogue.CatalogueManager;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
|
||||
public class CollectableData {
|
||||
private int currentPosition;
|
||||
private long expiry;
|
||||
private final long lifetime;
|
||||
|
||||
private int collectablesStorePage;
|
||||
private int collectablesAdminPage;
|
||||
|
||||
private final String[] classNames;
|
||||
|
||||
public CollectableData(int collectablesStorePage, int collectablesAdminPage, long expiry, long lifetime, int currentPosition, String[] classNames) {
|
||||
this.collectablesStorePage = collectablesStorePage;
|
||||
this.collectablesAdminPage = collectablesAdminPage;
|
||||
this.expiry = expiry;
|
||||
this.lifetime = lifetime;
|
||||
this.currentPosition = currentPosition;
|
||||
this.classNames = classNames;
|
||||
}
|
||||
|
||||
/**
|
||||
* The method for checking if the next collectable is due.
|
||||
*/
|
||||
public void checkCycle() {
|
||||
if (!(DateUtil.getCurrentTimeSeconds() > this.expiry)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.currentPosition++;
|
||||
|
||||
if (this.currentPosition >= this.classNames.length) {
|
||||
this.currentPosition = 0;
|
||||
}
|
||||
|
||||
this.expiry = DateUtil.getCurrentTimeSeconds() + this.lifetime;
|
||||
CollectablesDao.saveData(this.collectablesStorePage, this.currentPosition, this.expiry);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the catalogue item of the active collectable.
|
||||
*
|
||||
* @return the catalogue item
|
||||
*/
|
||||
public CatalogueItem getActiveItem() {
|
||||
String className = this.classNames[this.currentPosition];
|
||||
|
||||
for (CatalogueItem item : CatalogueManager.getInstance().getCataloguePageItems(this.collectablesAdminPage, true)) {
|
||||
if (item.getDefinition().getSprite().equals(className)) {
|
||||
var collectable = item.copy();
|
||||
return collectable;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public String[] getSprites() {
|
||||
return this.classNames;
|
||||
}
|
||||
|
||||
public long getExpiry() {
|
||||
return expiry;
|
||||
}
|
||||
|
||||
public int getCollectablesStorePage() {
|
||||
return collectablesStorePage;
|
||||
}
|
||||
|
||||
public int getCollectablesAdminPage() {
|
||||
return collectablesAdminPage;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,96 @@
|
|||
package org.alexdev.havana.game.catalogue.collectables;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.CollectablesDao;
|
||||
import org.alexdev.havana.game.catalogue.CatalogueItem;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class CollectablesManager {
|
||||
private static CollectablesManager instance;
|
||||
private List<CollectableData> collectableDataList;
|
||||
|
||||
public CollectablesManager() {
|
||||
this.collectableDataList = CollectablesDao.getCollectablesData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks all the collectable pages for expired items and cycles to the next item if required.
|
||||
*/
|
||||
public void checkExpiries() {
|
||||
for (CollectableData collectableData : this.collectableDataList) {
|
||||
collectableData.checkCycle();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets if the item is currently on sale as a collectable.
|
||||
*
|
||||
* @param item the item to check
|
||||
* @return true, if successful
|
||||
*/
|
||||
public boolean isCollectable(CatalogueItem item) {
|
||||
for (CollectableData collectableData : this.collectableDataList) {
|
||||
CatalogueItem collectableItem = collectableData.getActiveItem();
|
||||
|
||||
if (collectableItem != null && collectableItem.getId() == item.getId()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get collectable data by the page id.
|
||||
*
|
||||
* @param pageId the page id to get data for
|
||||
* @return the collectable data instance
|
||||
*/
|
||||
public CollectableData getCollectableDataByPage(int pageId) {
|
||||
for (CollectableData collectableData : this.collectableDataList) {
|
||||
if (collectableData.getCollectablesStorePage() == pageId || collectableData.getCollectablesAdminPage() == pageId) {
|
||||
return collectableData;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get collectable data by the page id.
|
||||
*
|
||||
* @param itemId the page id to get data for
|
||||
* @return the collectable data instance
|
||||
*/
|
||||
public CollectableData getCollectableDataByItem(int itemId) {
|
||||
for (CollectableData collectableData : this.collectableDataList) {
|
||||
if (collectableData.getActiveItem().getId() == itemId) {
|
||||
return collectableData;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the {@link CollectablesManager} instance
|
||||
*
|
||||
* @return the collectables manager instance
|
||||
*/
|
||||
public static CollectablesManager getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new CollectablesManager();
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Resets the catalogue manager singleton.
|
||||
*/
|
||||
public static void reset() {
|
||||
instance = null;
|
||||
CollectablesManager.getInstance();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,104 @@
|
|||
package org.alexdev.havana.game.catalogue.voucher;
|
||||
|
||||
import org.alexdev.havana.dao.mysql.CurrencyDao;
|
||||
import org.alexdev.havana.dao.mysql.PlayerStatisticsDao;
|
||||
import org.alexdev.havana.dao.mysql.VoucherDao;
|
||||
import org.alexdev.havana.game.catalogue.CatalogueItem;
|
||||
import org.alexdev.havana.game.catalogue.CatalogueManager;
|
||||
import org.alexdev.havana.game.item.Item;
|
||||
import org.alexdev.havana.game.misc.purse.Voucher;
|
||||
import org.alexdev.havana.game.player.PlayerDetails;
|
||||
import org.alexdev.havana.game.player.statistics.PlayerStatistic;
|
||||
import org.alexdev.havana.log.Log;
|
||||
import org.alexdev.havana.util.DateUtil;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class VoucherManager {
|
||||
private static VoucherManager instance;
|
||||
|
||||
public VoucherManager() {
|
||||
|
||||
}
|
||||
|
||||
public VoucherRedeemStatus redeem(PlayerDetails playerDetails, VoucherRedeemMode voucherRedeemMode, String voucherCode, List<CatalogueItem> redeemedItems, AtomicInteger redeemedCredits) {
|
||||
//Check and get voucher
|
||||
Voucher voucher = VoucherDao.redeemVoucher(voucherCode, playerDetails.getId());
|
||||
|
||||
//No voucher was found
|
||||
if (voucher == null) {
|
||||
return VoucherRedeemStatus.FAILURE;
|
||||
}
|
||||
|
||||
if (!voucher.isAllowNewUsers()) {
|
||||
int daysSince = (int) Math.floor(TimeUnit.SECONDS.toHours(PlayerStatisticsDao.getStatisticLong(playerDetails.getId(), PlayerStatistic.ONLINE_TIME)));
|
||||
|
||||
if (daysSince < 1) {
|
||||
return VoucherRedeemStatus.FAILURE_NEW_ACCOUNT;
|
||||
}
|
||||
}
|
||||
|
||||
//Redeem items
|
||||
List<Item> items = new ArrayList<>();
|
||||
|
||||
for (String catalogueSaleCode : voucher.getItems()) {
|
||||
var catalogueItem = CatalogueManager.getInstance().getCatalogueItem(catalogueSaleCode);
|
||||
|
||||
if (catalogueItem == null) {
|
||||
Log.getErrorLogger().error("Could not redeem voucher " + voucherCode + " with sale code: " + catalogueSaleCode);
|
||||
continue;
|
||||
}
|
||||
|
||||
redeemedItems.add(catalogueItem);
|
||||
|
||||
try {
|
||||
items.addAll(CatalogueManager.getInstance().purchase(playerDetails, catalogueItem, "", null, DateUtil.getCurrentTimeSeconds()));
|
||||
} catch (Exception ex) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/*if (items.size() > 0) {
|
||||
if (voucherRedeemMode == VoucherRedeemMode.IN_GAME) {
|
||||
if (player != null) {
|
||||
player.getInventory().getView("new");
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
VoucherDao.logVoucher(voucherCode, playerDetails.getId(), voucher.getCredits(), redeemedItems);
|
||||
|
||||
//This voucher gives credits, so increase credits balance
|
||||
if (voucher.getCredits() > 0) {
|
||||
CurrencyDao.increaseCredits(playerDetails, voucher.getCredits());
|
||||
redeemedCredits.set(voucher.getCredits());
|
||||
}
|
||||
|
||||
return VoucherRedeemStatus.SUCCESS;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the {@link VoucherManager} instance
|
||||
*
|
||||
* @return the catalogue manager instance
|
||||
*/
|
||||
public static VoucherManager getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new VoucherManager();
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the catalogue manager singleton.
|
||||
*/
|
||||
public static void reset() {
|
||||
instance = null;
|
||||
VoucherManager.getInstance();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
package org.alexdev.havana.game.catalogue.voucher;
|
||||
|
||||
public enum VoucherRedeemMode {
|
||||
WEBSITE,
|
||||
IN_GAME
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package org.alexdev.havana.game.catalogue.voucher;
|
||||
|
||||
public enum VoucherRedeemStatus {
|
||||
SUCCESS,
|
||||
FAILURE,
|
||||
FAILURE_NEW_ACCOUNT;
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue