Merge branch 'dev' into 'master'

2.1.0 Stable

See merge request morningstar/Arcturus-Community!45
This commit is contained in:
Harmonic 2019-07-05 09:18:57 -04:00
commit 9bdbf7d19a
1728 changed files with 22275 additions and 38513 deletions

10
pom.xml
View File

@ -6,7 +6,7 @@
<groupId>com.eu.habbo</groupId> <groupId>com.eu.habbo</groupId>
<artifactId>Habbo</artifactId> <artifactId>Habbo</artifactId>
<version>2.0.0</version> <version>2.1.0</version>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -88,27 +88,27 @@
<dependency> <dependency>
<groupId>io.netty</groupId> <groupId>io.netty</groupId>
<artifactId>netty-all</artifactId> <artifactId>netty-all</artifactId>
<version>4.1.24.Final</version> <version>4.1.36.Final</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.netty</groupId> <groupId>io.netty</groupId>
<artifactId>netty-codec-http</artifactId> <artifactId>netty-codec-http</artifactId>
<version>4.1.24.Final</version> <version>4.1.36.Final</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.netty</groupId> <groupId>io.netty</groupId>
<artifactId>netty-codec-http2</artifactId> <artifactId>netty-codec-http2</artifactId>
<version>4.1.24.Final</version> <version>4.1.36.Final</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.netty</groupId> <groupId>io.netty</groupId>
<artifactId>netty-handler</artifactId> <artifactId>netty-handler</artifactId>
<version>4.1.24.Final</version> <version>4.1.36.Final</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>

View File

@ -0,0 +1,126 @@
CREATE TABLE `users_saved_searches` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`search_code` varchar(255) NOT NULL,
`filter` varchar(255) NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
ALTER TABLE `users_settings`
ADD COLUMN `ui_flags` int(11) NOT NULL DEFAULT 1 AFTER `forums_post_count`;
ALTER TABLE `users_settings`
ADD COLUMN `has_gotten_default_saved_searches` tinyint(1) NOT NULL DEFAULT 0 AFTER `ui_flags`;
ALTER TABLE `support_tickets`
ADD COLUMN `group_id` int(11) NOT NULL AFTER `category`,
ADD COLUMN `thread_id` int(11) NOT NULL AFTER `group_id`,
ADD COLUMN `comment_id` int(11) NOT NULL AFTER `thread_id`;
ALTER TABLE `pet_actions`
ADD COLUMN `can_swim` enum('1','0') NULL DEFAULT '0' AFTER `random_actions`;
UPDATE `pet_actions` SET `can_swim` = '1' WHERE `pet_type` = 9 OR `pet_type` = 14 OR `pet_type` = 23 OR `pet_type` = 24 OR `pet_type` = 25 OR `pet_type` = 28 OR `pet_type` = 29 OR `pet_type` = 30 OR `pet_type` = 32;
UPDATE `items_base` SET `customparams` = '30,60,120,180,300,600', `interaction_type` = 'game_timer', `interaction_modes_count` = 1 WHERE `item_name` IN ('fball_counter','bb_counter','es_counter');
ALTER TABLE `youtube_playlists`
CHANGE COLUMN `video_id` `playlist_id` varchar(255) NOT NULL COMMENT 'YouTube playlist ID' AFTER `item_id`;
DROP TABLE `youtube_items`;
TRUNCATE TABLE `youtube_playlists`;
DROP PROCEDURE IF EXISTS DEFAULT_YTTV_PLAYLISTS;
DELIMITER ;;
CREATE PROCEDURE DEFAULT_YTTV_PLAYLISTS()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE a INT DEFAULT 0;
DECLARE itemId INT default 0;
SELECT COUNT(*) FROM `items_base` WHERE `interaction_type` = 'youtube' INTO n;
SET i=0;
SET @defaultPlaylistIds = '["PL4YfV2mXS8WXOkxFly7YsGL8cKtqp873p","PL4F5KzcUTpEdux38c8CYunT9uNh_k2NPt","PL4F5KzcUTpEcO-1iw3P6gavJ_ALTxqNHn","PL4F5KzcUTpEfpHad_B7j_MulB3-cwtLFh","PL4F5KzcUTpEekJPbcVOaNYVV6VLSo9zRB","PL80F08DAE1B614BA9","PL4F5KzcUTpEfeS5t7EiEIYbpplZivDZTL","PL4ACB18CA629E650A","PL4F5KzcUTpEfyRBCOVKQ4qxlSoHsGDZ82","PL4F5KzcUTpEet7EMwhw0ge5n2oNMr7JY8","PL4F5KzcUTpEfTW4fkX9vrt497MEvWorwK","PL4F5KzcUTpEcit3i1q55-IFFndmo_dsR8","PL4F5KzcUTpEeJleVUhO1MWRJyYDWWp9Do","PL4F5KzcUTpEcFzCpH2_EXtwzKQH8mJGd9","PL4F5KzcUTpEcIiSOH2x3sg2jwACNbSIm9","PL4F5KzcUTpEfRxBiXwTBA7oiybPqoZD_j","PL4YfV2mXS8WUo09aevZX-b47k4PD08-i8","PL4F5KzcUTpEcFzCpH2_EXtwzKQH8mJGd9"]';
WHILE i < n DO
SET itemId = (SELECT id FROM `items_base` WHERE `interaction_type` = 'youtube' LIMIT i, 1);
WHILE a<JSON_LENGTH(@defaultPlaylistIds) DO
INSERT IGNORE INTO `youtube_playlists` (item_id, playlist_id) VALUES (itemId, TRIM(BOTH '"' FROM JSON_EXTRACT(@defaultPlaylistIds, CONCAT('$[',a,']'))));
SET a = a + 1;
END WHILE;
SET a = 0;
SET i = i + 1;
END WHILE;
END;
;;
DELIMITER ;
CALL DEFAULT_YTTV_PLAYLISTS();
DROP PROCEDURE IF EXISTS DEFAULT_YTTV_PLAYLISTS;
ALTER TABLE `permissions`
ADD COLUMN `cmd_update_youtube_playlists` enum('0','1') NOT NULL DEFAULT '0';
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.keys.cmd_update_youtube_playlists', 'update_youtube;update_youtube_playlists');
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.succes.cmd_update_youtube_playlists', 'YouTube playlists have been refreshed!');
DROP PROCEDURE IF EXISTS UPDATE_TEAM_WIREDS;
DELIMITER ;;
CREATE PROCEDURE UPDATE_TEAM_WIREDS()
BEGIN
IF (SELECT COUNT(*) FROM emulator_settings WHERE `key` = 'team.wired.update.rc-1') = 0 THEN
INSERT INTO emulator_settings (`key`, `value`) VALUES ('team.wired.update.rc-1', 'DO NOT REMOVE THIS SETTING!');
UPDATE
items
INNER JOIN
items_base
ON
items.item_id = items_base.id
SET items.wired_data = CONCAT(
SUBSTRING_INDEX(items.wired_data, ';', 2),
';',
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(items.wired_data, ';', 3), ';', -1) AS SIGNED INTEGER) + 1,
';',
SUBSTRING_INDEX(SUBSTRING_INDEX(items.wired_data, ';', 4), ';', -1)
)
WHERE
items_base.interaction_type = 'wf_act_give_score_tm';
UPDATE
items
INNER JOIN
items_base
ON
items.item_id = items_base.id
SET items.wired_data = CONCAT(
SUBSTRING_INDEX(items.wired_data, '\t', 1),
'\t',
CAST(SUBSTRING_INDEX(items.wired_data, '\t', -1) AS SIGNED INTEGER) + 1
)
WHERE
items_base.interaction_type = 'wf_act_join_team';
UPDATE
items
INNER JOIN
items_base
ON
items.item_id = items_base.id
SET items.wired_data = CAST(items.wired_data AS SIGNED INTEGER) + 1
WHERE
items_base.interaction_type = 'wf_cnd_actor_in_team' OR items_base.interaction_type = 'wf_cnd_not_in_team';
END IF;
END;
;;
DELIMITER ;
CALL UPDATE_TEAM_WIREDS();
DROP PROCEDURE IF EXISTS UPDATE_TEAM_WIREDS;

View File

@ -0,0 +1,10 @@
ALTER TABLE `permissions`
ADD COLUMN `cmd_add_youtube_playlist` enum('0','1') NOT NULL DEFAULT '0';
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.keys.cmd_add_youtube_playlist', 'add_youtube;add_playlist;add_youtube_playlist');
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.error.cmd_add_youtube_playlist.usage', 'Usage: base_item_id youtube_playlist_id');
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.error.cmd_add_youtube_playlist.no_base_item', 'A base item with that ID could not be found.');
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.error.cmd_add_youtube_playlist.failed_playlist', 'Error: unable to fetch the given YouTube playlist.');
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.succes.cmd_add_youtube_playlist', 'The playlist has been added successfully!');
UPDATE `emulator_texts` SET `value` = 'Superwired Usage Information. Possible reward types:<br/>badge: BADGE CODE<br/>Credits: credits#amount<br/>Pixels: pixels#amount<br/>Points: points#amount<br/>Respect: respect#amount<br/>Furniture: furni#FurnitureID<br/>Catalog Item: cata#CatalogItemID' WHERE `key` = 'hotel.wired.superwired.info';

View File

@ -7,7 +7,6 @@ import com.eu.habbo.core.TextsManager;
import com.eu.habbo.core.consolecommands.ConsoleCommand; import com.eu.habbo.core.consolecommands.ConsoleCommand;
import com.eu.habbo.database.Database; import com.eu.habbo.database.Database;
import com.eu.habbo.habbohotel.GameEnvironment; import com.eu.habbo.habbohotel.GameEnvironment;
import com.eu.habbo.habbohotel.messenger.MessengerBuddy;
import com.eu.habbo.networking.camera.CameraClient; import com.eu.habbo.networking.camera.CameraClient;
import com.eu.habbo.networking.gameserver.GameServer; import com.eu.habbo.networking.gameserver.GameServer;
import com.eu.habbo.networking.rconserver.RCONServer; import com.eu.habbo.networking.rconserver.RCONServer;
@ -17,7 +16,6 @@ import com.eu.habbo.plugin.events.emulator.EmulatorLoadedEvent;
import com.eu.habbo.plugin.events.emulator.EmulatorStartShutdownEvent; import com.eu.habbo.plugin.events.emulator.EmulatorStartShutdownEvent;
import com.eu.habbo.plugin.events.emulator.EmulatorStoppedEvent; import com.eu.habbo.plugin.events.emulator.EmulatorStoppedEvent;
import com.eu.habbo.threading.ThreadPooling; import com.eu.habbo.threading.ThreadPooling;
import com.eu.habbo.threading.runnables.CameraClientAutoReconnect;
import com.eu.habbo.util.imager.badges.BadgeImager; import com.eu.habbo.util.imager.badges.BadgeImager;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -30,34 +28,35 @@ import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.Locale; import java.util.Locale;
import java.util.Random; import java.util.Random;
import java.util.zip.Checksum;
public final class Emulator public final class Emulator {
{
public final static int MAJOR = 2; public final static int MAJOR = 2;
public final static int MINOR = 0; public final static int MINOR = 1;
public final static int BUILD = 0; public final static int BUILD = 0;
public final static String PREVIEW = ""; public final static String PREVIEW = "Stable";
public static final String version = "Arcturus Morningstar"+ " " + MAJOR + "." + MINOR + "." + BUILD; public static final String version = "Arcturus Morningstar" + " " + MAJOR + "." + MINOR + "." + BUILD + " " + PREVIEW;
private static final String logo =
" \n" +
" __ ___ _ A R C T U R U S __ \n" +
" / |/ /___ _________ (_)___ ____ ______/ /_____ ______ \n" +
" / /|_/ / __ \\/ ___/ __ \\/ / __ \\/ __ `/ ___/ __/ __ `/ ___/ \n" +
" / / / / /_/ / / / / / / / / / / /_/ (__ ) /_/ /_/ / / \n" +
"/_/ /_/\\____/_/ /_/ /_/_/_/ /_/\\__, /____/\\__/\\__,_/_/ \n" +
" /____/ \n";
public static String build = ""; public static String build = "";
public static boolean isReady = false; public static boolean isReady = false;
public static boolean isShuttingDown = false; public static boolean isShuttingDown = false;
public static boolean stopped = false; public static boolean stopped = false;
public static boolean debugging = false; public static boolean debugging = false;
private static int timeStarted = 0; private static int timeStarted = 0;
private static Runtime runtime; private static Runtime runtime;
private static ConfigurationManager config; private static ConfigurationManager config;
@ -73,12 +72,9 @@ public final class Emulator
private static Random random; private static Random random;
private static BadgeImager badgeImager; private static BadgeImager badgeImager;
static static {
{ Thread hook = new Thread(new Runnable() {
Thread hook = new Thread(new Runnable() public synchronized void run() {
{
public synchronized void run()
{
Emulator.dispose(); Emulator.dispose();
} }
}); });
@ -86,11 +82,8 @@ public final class Emulator
Runtime.getRuntime().addShutdownHook(hook); Runtime.getRuntime().addShutdownHook(hook);
} }
public static void main(String[] args) throws Exception {
public static void main(String[] args) throws Exception try {
{
try
{
Locale.setDefault(new Locale("en")); Locale.setDefault(new Locale("en"));
setBuild(); setBuild();
@ -104,13 +97,6 @@ public final class Emulator
Emulator.runtime = Runtime.getRuntime(); Emulator.runtime = Runtime.getRuntime();
Emulator.config = new ConfigurationManager("config.ini"); Emulator.config = new ConfigurationManager("config.ini");
if (Emulator.getConfig().getValue("username").isEmpty())
{
Emulator.getLogging().logErrorLine("Please make sure you enter your forum login details!");
Thread.sleep(2000);
}
Emulator.database = new Database(Emulator.getConfig()); Emulator.database = new Database(Emulator.getConfig());
Emulator.config.loaded = true; Emulator.config.loaded = true;
Emulator.config.loadFromDatabase(); Emulator.config.loadFromDatabase();
@ -131,12 +117,6 @@ public final class Emulator
Emulator.rconServer.initializePipeline(); Emulator.rconServer.initializePipeline();
Emulator.rconServer.connect(); Emulator.rconServer.connect();
Emulator.badgeImager = new BadgeImager(); Emulator.badgeImager = new BadgeImager();
// Removed Wesleys Camera Server lol.
/* if (Emulator.getConfig().getBoolean("camera.enabled"))
{
Emulator.getThreading().run(new CameraClientAutoReconnect());
}
*/
Emulator.getLogging().logStart("Habbo Hotel Emulator has succesfully loaded."); Emulator.getLogging().logStart("Habbo Hotel Emulator has succesfully loaded.");
Emulator.getLogging().logStart("You're running: " + Emulator.version); Emulator.getLogging().logStart("You're running: " + Emulator.version);
Emulator.getLogging().logStart("System launched in: " + (System.nanoTime() - startTime) / 1e6 + "ms. Using: " + (Runtime.getRuntime().availableProcessors() * 2) + " threads!"); Emulator.getLogging().logStart("System launched in: " + (System.nanoTime() - startTime) / 1e6 + "ms. Using: " + (Runtime.getRuntime().availableProcessors() * 2) + " threads!");
@ -144,8 +124,7 @@ public final class Emulator
Emulator.debugging = Emulator.getConfig().getBoolean("debug.mode"); Emulator.debugging = Emulator.getConfig().getBoolean("debug.mode");
if (debugging) if (debugging) {
{
Emulator.getLogging().logDebugLine("Debugging Enabled!"); Emulator.getLogging().logDebugLine("Debugging Enabled!");
} }
@ -153,18 +132,15 @@ public final class Emulator
Emulator.isReady = true; Emulator.isReady = true;
Emulator.timeStarted = getIntUnixTimestamp(); Emulator.timeStarted = getIntUnixTimestamp();
if (Emulator.getConfig().getInt("runtime.threads") < (Runtime.getRuntime().availableProcessors() * 2)) if (Emulator.getConfig().getInt("runtime.threads") < (Runtime.getRuntime().availableProcessors() * 2)) {
{
Emulator.getLogging().logStart("Emulator settings runtime.threads (" + Emulator.getConfig().getInt("runtime.threads") + ") can be increased to " + (Runtime.getRuntime().availableProcessors() * 2) + " to possibly increase performance."); Emulator.getLogging().logStart("Emulator settings runtime.threads (" + Emulator.getConfig().getInt("runtime.threads") + ") can be increased to " + (Runtime.getRuntime().availableProcessors() * 2) + " to possibly increase performance.");
} }
Emulator.getThreading().run(new Runnable() Emulator.getThreading().run(new Runnable() {
{
@Override @Override
public void run() public void run() {
{ Emulator.getLogging().logStart("Thankyou for downloading Arcturus Morningstar! This is a stable 2.1.0 build, it should be more than stable for daily use on hotels, if you find any bugs please place them on our git repository.");
Emulator.getLogging().logStart("Thankyou for downloading Arcturus Morningstar! This is a Release Candidate for 2.0.0, if you find any bugs please place them on our git repository.");
Emulator.getLogging().logStart("Please note, Arcturus Emulator is a project by TheGeneral, we take no credit for the original work, and only the work we have continued. If you'd like to support the project, join our discord at: "); Emulator.getLogging().logStart("Please note, Arcturus Emulator is a project by TheGeneral, we take no credit for the original work, and only the work we have continued. If you'd like to support the project, join our discord at: ");
Emulator.getLogging().logStart("https://discord.gg/syuqgN"); Emulator.getLogging().logStart("https://discord.gg/syuqgN");
System.out.println("Waiting for commands: "); System.out.println("Waiting for commands: ");
@ -173,27 +149,20 @@ public final class Emulator
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (!isShuttingDown && isReady) while (!isShuttingDown && isReady && reader.ready()) {
{ try {
try
{
String line = reader.readLine(); String line = reader.readLine();
if (line != null) if (line != null) {
{
ConsoleCommand.handle(line); ConsoleCommand.handle(line);
} }
System.out.println("Waiting for command: "); System.out.println("Waiting for command: ");
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
} }
} }
} } catch (Exception e) {
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -205,8 +174,7 @@ public final class Emulator
} }
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
try try {
{
String filepath = new File(Emulator.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getAbsolutePath(); String filepath = new File(Emulator.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getAbsolutePath();
MessageDigest md = MessageDigest.getInstance("MD5");// MD5 MessageDigest md = MessageDigest.getInstance("MD5");// MD5
FileInputStream fis = new FileInputStream(filepath); FileInputStream fis = new FileInputStream(filepath);
@ -220,9 +188,7 @@ public final class Emulator
for (int i = 0; i < mdbytes.length; i++) for (int i = 0; i < mdbytes.length; i++)
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
} } catch (Exception e) {
catch(Exception e)
{
build = "UNKNOWN"; build = "UNKNOWN";
return; return;
} }
@ -230,193 +196,147 @@ public final class Emulator
build = sb.toString(); build = sb.toString();
} }
private static void dispose() {
private static void dispose()
{
Emulator.getThreading().setCanAdd(false); Emulator.getThreading().setCanAdd(false);
Emulator.isShuttingDown = true; Emulator.isShuttingDown = true;
Emulator.isReady = false; Emulator.isReady = false;
Emulator.getLogging().logShutdownLine("Stopping Arcturus Emulator " + version + "..."); Emulator.getLogging().logShutdownLine("Stopping Arcturus Emulator " + version + "...");
try try {
{
if (Emulator.getPluginManager() != null) if (Emulator.getPluginManager() != null)
Emulator.getPluginManager().fireEvent(new EmulatorStartShutdownEvent()); Emulator.getPluginManager().fireEvent(new EmulatorStartShutdownEvent());
} catch (Exception e) {
} }
catch (Exception e) {}
try try {
{
if (Emulator.cameraClient != null) if (Emulator.cameraClient != null)
Emulator.cameraClient.disconnect(); Emulator.cameraClient.disconnect();
} catch (Exception e) {
} }
catch (Exception e) {}
try try {
{
if (Emulator.rconServer != null) if (Emulator.rconServer != null)
Emulator.rconServer.stop(); Emulator.rconServer.stop();
} catch (Exception e) {
} }
catch (Exception e) {}
try try {
{
if (Emulator.gameEnvironment != null) if (Emulator.gameEnvironment != null)
Emulator.gameEnvironment.dispose(); Emulator.gameEnvironment.dispose();
} catch (Exception e) {
} }
catch (Exception e) {}
try try {
{
if (Emulator.getPluginManager() != null) if (Emulator.getPluginManager() != null)
Emulator.getPluginManager().fireEvent(new EmulatorStoppedEvent()); Emulator.getPluginManager().fireEvent(new EmulatorStoppedEvent());
} catch (Exception e) {
} }
catch (Exception e) {}
try try {
{
if (Emulator.pluginManager != null) if (Emulator.pluginManager != null)
Emulator.pluginManager.dispose(); Emulator.pluginManager.dispose();
} catch (Exception e) {
} }
catch (Exception e) {}
Emulator.getLogging().saveLogs(); Emulator.getLogging().saveLogs();
try try {
{ if (Emulator.config != null) {
if (Emulator.config != null)
{
Emulator.config.saveToDatabase(); Emulator.config.saveToDatabase();
} }
} catch (Exception e) {
} }
catch (Exception e) {}
try try {
{
if (Emulator.gameServer != null) if (Emulator.gameServer != null)
Emulator.gameServer.stop(); Emulator.gameServer.stop();
} catch (Exception e) {
} }
catch (Exception e) {}
Emulator.getLogging().logShutdownLine("Stopped Arcturus Emulator " + version + "..."); Emulator.getLogging().logShutdownLine("Stopped Arcturus Emulator " + version + "...");
if (Emulator.database != null) if (Emulator.database != null) {
{
Emulator.getDatabase().dispose(); Emulator.getDatabase().dispose();
} }
Emulator.stopped = true; Emulator.stopped = true;
try try {
{
if (Emulator.threading != null) if (Emulator.threading != null)
Emulator.threading.shutDown(); Emulator.threading.shutDown();
} catch (Exception e) {
} }
catch (Exception e) {}
} }
public static ConfigurationManager getConfig() {
public static ConfigurationManager getConfig()
{
return config; return config;
} }
public static TextsManager getTexts() {
public static TextsManager getTexts()
{
return texts; return texts;
} }
public static Database getDatabase() {
public static Database getDatabase()
{
return database; return database;
} }
public static Runtime getRuntime() {
public static Runtime getRuntime()
{
return runtime; return runtime;
} }
public static GameServer getGameServer() {
public static GameServer getGameServer()
{
return gameServer; return gameServer;
} }
public static RCONServer getRconServer() {
public static RCONServer getRconServer()
{
return rconServer; return rconServer;
} }
public static Logging getLogging() {
public static Logging getLogging()
{
return logging; return logging;
} }
public static ThreadPooling getThreading() {
public static ThreadPooling getThreading()
{
return threading; return threading;
} }
public static GameEnvironment getGameEnvironment() {
public static GameEnvironment getGameEnvironment()
{
return gameEnvironment; return gameEnvironment;
} }
public static PluginManager getPluginManager() {
public static PluginManager getPluginManager()
{
return pluginManager; return pluginManager;
} }
public static Random getRandom() {
public static Random getRandom()
{
return random; return random;
} }
public static BadgeImager getBadgeImager() {
public static BadgeImager getBadgeImager()
{
return badgeImager; return badgeImager;
} }
public static CameraClient getCameraClient() public static CameraClient getCameraClient() {
{
return cameraClient; return cameraClient;
} }
public static synchronized void setCameraClient(CameraClient client) public static synchronized void setCameraClient(CameraClient client) {
{
cameraClient = client; cameraClient = client;
} }
public static int getTimeStarted() {
public static int getTimeStarted()
{
return timeStarted; return timeStarted;
} }
public static int getOnlineTime() {
public static int getOnlineTime()
{
return getIntUnixTimestamp() - timeStarted; return getIntUnixTimestamp() - timeStarted;
} }
public static void prepareShutdown() public static void prepareShutdown() {
{
System.exit(0); System.exit(0);
} }
private static String dateToUnixTimestamp(Date date) {
private static String dateToUnixTimestamp(Date date)
{
String res = ""; String res = "";
Date aux = stringToDate("1970-01-01 00:00:00"); Date aux = stringToDate("1970-01-01 00:00:00");
Timestamp aux1 = dateToTimeStamp(aux); Timestamp aux1 = dateToTimeStamp(aux);
@ -426,55 +346,42 @@ public final class Emulator
return res + seconds; return res + seconds;
} }
private static Date stringToDate(String date) {
private static Date stringToDate(String date)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date res = null; Date res = null;
try try {
{
res = format.parse(date); res = format.parse(date);
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
} }
return res; return res;
} }
public static Timestamp dateToTimeStamp(Date date) public static Timestamp dateToTimeStamp(Date date) {
{
return new Timestamp(date.getTime()); return new Timestamp(date.getTime());
} }
public static Date getDate() public static Date getDate() {
{
return new Date(System.currentTimeMillis()); return new Date(System.currentTimeMillis());
} }
public static String getUnixTimestamp() public static String getUnixTimestamp() {
{
return dateToUnixTimestamp(getDate()); return dateToUnixTimestamp(getDate());
} }
public static int getIntUnixTimestamp() public static int getIntUnixTimestamp() {
{
return (int) (System.currentTimeMillis() / 1000); return (int) (System.currentTimeMillis() / 1000);
} }
public static boolean isNumeric(String string) public static boolean isNumeric(String string)
throws IllegalArgumentException throws IllegalArgumentException {
{
boolean isnumeric = false; boolean isnumeric = false;
if ((string != null) && (!string.equals(""))) if ((string != null) && (!string.equals(""))) {
{
isnumeric = true; isnumeric = true;
char[] chars = string.toCharArray(); char[] chars = string.toCharArray();
for (char aChar : chars) for (char aChar : chars) {
{
isnumeric = Character.isDigit(aChar); isnumeric = Character.isDigit(aChar);
if (!isnumeric) if (!isnumeric) {
{
break; break;
} }
} }
@ -482,23 +389,11 @@ public final class Emulator
return isnumeric; return isnumeric;
} }
public int getUserCount() public int getUserCount() {
{
return gameEnvironment.getHabboManager().getOnlineCount(); return gameEnvironment.getHabboManager().getOnlineCount();
} }
public int getRoomCount() public int getRoomCount() {
{
return gameEnvironment.getRoomManager().getActiveRooms().size(); return gameEnvironment.getRoomManager().getActiveRooms().size();
} }
private static final String logo =
" \n" +
" __ ___ _ A R C T U R U S __ \n" +
" / |/ /___ _________ (_)___ ____ ______/ /_____ ______ \n" +
" / /|_/ / __ \\/ ___/ __ \\/ / __ \\/ __ `/ ___/ __/ __ `/ ___/ \n" +
" / / / / /_/ / / / / / / / / / / /_/ (__ ) /_/ /_/ / / \n" +
"/_/ /_/\\____/_/ /_/ /_/_/_/ /_/\\__, /____/\\__/\\__,_/_/ \n" +
" /____/ \n";
} }

View File

@ -7,7 +7,6 @@ import com.eu.habbo.messages.incoming.friends.SearchUserEvent;
import com.eu.habbo.messages.incoming.navigator.SearchRoomsEvent; import com.eu.habbo.messages.incoming.navigator.SearchRoomsEvent;
import com.eu.habbo.threading.runnables.AchievementUpdater; import com.eu.habbo.threading.runnables.AchievementUpdater;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
@ -44,7 +43,6 @@ public class CleanerThread implements Runnable {
private static final int CALLBACK_TIME = 60 * 15; private static final int CALLBACK_TIME = 60 * 15;
private static int LAST_HOF_RELOAD = Emulator.getIntUnixTimestamp(); private static int LAST_HOF_RELOAD = Emulator.getIntUnixTimestamp();
@ -70,8 +68,7 @@ public class CleanerThread implements Runnable {
private static int LAST_HABBO_CACHE_CLEARED = Emulator.getIntUnixTimestamp(); private static int LAST_HABBO_CACHE_CLEARED = Emulator.getIntUnixTimestamp();
public CleanerThread() public CleanerThread() {
{
this.databaseCleanup(); this.databaseCleanup();
Emulator.getThreading().run(this, DELAY); Emulator.getThreading().run(this, DELAY);
@ -81,63 +78,53 @@ public class CleanerThread implements Runnable {
} }
@Override @Override
public void run() public void run() {
{
Emulator.getThreading().run(this, DELAY); Emulator.getThreading().run(this, DELAY);
int time = Emulator.getIntUnixTimestamp(); int time = Emulator.getIntUnixTimestamp();
if (time - LAST_HOF_RELOAD > RELOAD_HALL_OF_FAME) if (time - LAST_HOF_RELOAD > RELOAD_HALL_OF_FAME) {
{
Emulator.getGameEnvironment().getHotelViewManager().getHallOfFame().reload(); Emulator.getGameEnvironment().getHotelViewManager().getHallOfFame().reload();
LAST_HOF_RELOAD = time; LAST_HOF_RELOAD = time;
} }
if (time - LAST_NL_RELOAD > RELOAD_NEWS_LIST) if (time - LAST_NL_RELOAD > RELOAD_NEWS_LIST) {
{
Emulator.getGameEnvironment().getHotelViewManager().getNewsList().reload(); Emulator.getGameEnvironment().getHotelViewManager().getNewsList().reload();
LAST_NL_RELOAD = time; LAST_NL_RELOAD = time;
} }
if (time - LAST_INACTIVE_ROOMS_CLEARED > REMOVE_INACTIVE_ROOMS) if (time - LAST_INACTIVE_ROOMS_CLEARED > REMOVE_INACTIVE_ROOMS) {
{
Emulator.getGameEnvironment().getRoomManager().clearInactiveRooms(); Emulator.getGameEnvironment().getRoomManager().clearInactiveRooms();
LAST_INACTIVE_ROOMS_CLEARED = time; LAST_INACTIVE_ROOMS_CLEARED = time;
} }
if (time - LAST_INACTIVE_GUILDS_CLEARED > REMOVE_INACTIVE_GUILDS) if (time - LAST_INACTIVE_GUILDS_CLEARED > REMOVE_INACTIVE_GUILDS) {
{
Emulator.getGameEnvironment().getGuildManager().clearInactiveGuilds(); Emulator.getGameEnvironment().getGuildManager().clearInactiveGuilds();
ForumThread.clearCache(); ForumThread.clearCache();
LAST_INACTIVE_GUILDS_CLEARED = time; LAST_INACTIVE_GUILDS_CLEARED = time;
} }
if (time - LAST_INACTIVE_TOURS_CLEARED > REMOVE_INACTIVE_TOURS) if (time - LAST_INACTIVE_TOURS_CLEARED > REMOVE_INACTIVE_TOURS) {
{
Emulator.getGameEnvironment().getGuideManager().cleanup(); Emulator.getGameEnvironment().getGuideManager().cleanup();
LAST_INACTIVE_TOURS_CLEARED = time; LAST_INACTIVE_TOURS_CLEARED = time;
} }
if (time - LAST_ERROR_LOGS_SAVED > SAVE_ERROR_LOGS) if (time - LAST_ERROR_LOGS_SAVED > SAVE_ERROR_LOGS) {
{
Emulator.getLogging().saveLogs(); Emulator.getLogging().saveLogs();
LAST_ERROR_LOGS_SAVED = time; LAST_ERROR_LOGS_SAVED = time;
} }
if (time - LAST_CALLBACK > CALLBACK_TIME) if (time - LAST_CALLBACK > CALLBACK_TIME) {
{
// Emulator.getThreading().run(new HTTPPostStatus()); // Emulator.getThreading().run(new HTTPPostStatus());
LAST_CALLBACK = time; LAST_CALLBACK = time;
} }
if (time - LAST_DAILY_REFILL > Emulator.getConfig().getInt("hotel.refill.daily")) if (time - LAST_DAILY_REFILL > Emulator.getConfig().getInt("hotel.refill.daily")) {
{
this.refillDailyRespects(); this.refillDailyRespects();
LAST_DAILY_REFILL = time; LAST_DAILY_REFILL = time;
} }
if (time - LAST_HABBO_CACHE_CLEARED > CLEAR_CACHED_VALUES) if (time - LAST_HABBO_CACHE_CLEARED > CLEAR_CACHED_VALUES) {
{
this.clearCachedValues(); this.clearCachedValues();
LAST_HABBO_CACHE_CLEARED = time; LAST_HABBO_CACHE_CLEARED = time;
} }
@ -147,15 +134,12 @@ public class CleanerThread implements Runnable {
} }
void databaseCleanup() void databaseCleanup() {
{
this.refillDailyRespects(); this.refillDailyRespects();
int time = Emulator.getIntUnixTimestamp(); int time = Emulator.getIntUnixTimestamp();
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
{ try (Statement statement = connection.createStatement()) {
try (Statement statement = connection.createStatement())
{
statement.execute("UPDATE users SET online = '0' WHERE online = '1'"); statement.execute("UPDATE users SET online = '0' WHERE online = '1'");
statement.execute("UPDATE rooms SET users = '0' WHERE users > 0"); statement.execute("UPDATE rooms SET users = '0' WHERE users > 0");
statement.execute("DELETE FROM room_mutes WHERE ends < " + time); statement.execute("DELETE FROM room_mutes WHERE ends < " + time);
@ -163,63 +147,47 @@ public class CleanerThread implements Runnable {
statement.execute("DELETE users_favorite_rooms FROM users_favorite_rooms LEFT JOIN rooms ON room_id = rooms.id WHERE rooms.id IS NULL"); statement.execute("DELETE users_favorite_rooms FROM users_favorite_rooms LEFT JOIN rooms ON room_id = rooms.id WHERE rooms.id IS NULL");
} }
try (PreparedStatement statement = connection.prepareStatement("UPDATE users_effects SET total = total - 1 WHERE activation_timestamp < ? AND activation_timestamp != 0")) try (PreparedStatement statement = connection.prepareStatement("UPDATE users_effects SET total = total - 1 WHERE activation_timestamp < ? AND activation_timestamp != 0")) {
{
statement.setInt(1, Emulator.getIntUnixTimestamp() - 86400); statement.setInt(1, Emulator.getIntUnixTimestamp() - 86400);
statement.execute(); statement.execute();
} }
try (Statement statement = connection.createStatement()) try (Statement statement = connection.createStatement()) {
{
statement.execute("DELETE FROM users_effects WHERE total <= 0"); statement.execute("DELETE FROM users_effects WHERE total <= 0");
} }
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
Emulator.getLogging().logStart("Database -> Cleaned!"); Emulator.getLogging().logStart("Database -> Cleaned!");
} }
public void refillDailyRespects() public void refillDailyRespects() {
{ try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE users_settings SET daily_respect_points = ?, daily_pet_respect_points = ?")) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE users_settings SET daily_respect_points = ?, daily_pet_respect_points = ?"))
{
statement.setInt(1, Emulator.getConfig().getInt("hotel.daily.respect")); statement.setInt(1, Emulator.getConfig().getInt("hotel.daily.respect"));
statement.setInt(2, Emulator.getConfig().getInt("hotel.daily.respect.pets")); statement.setInt(2, Emulator.getConfig().getInt("hotel.daily.respect.pets"));
statement.executeUpdate(); statement.executeUpdate();
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
if (Emulator.isReady) if (Emulator.isReady) {
{ for (Habbo habbo : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().values()) {
for (Habbo habbo : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().values())
{
habbo.getHabboStats().petRespectPointsToGive = Emulator.getConfig().getInt("hotel.daily.respect"); habbo.getHabboStats().petRespectPointsToGive = Emulator.getConfig().getInt("hotel.daily.respect");
habbo.getHabboStats().respectPointsToGive = Emulator.getConfig().getInt("hotel.daily.respect.pets"); habbo.getHabboStats().respectPointsToGive = Emulator.getConfig().getInt("hotel.daily.respect.pets");
} }
} }
} }
private void clearCachedValues() private void clearCachedValues() {
{
Habbo habbo; Habbo habbo;
for(Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) for (Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) {
{
habbo = map.getValue(); habbo = map.getValue();
try try {
{ if (habbo != null) {
if (habbo != null)
{
habbo.clearCaches(); habbo.clearCaches();
} }
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
} }
} }

View File

@ -6,8 +6,7 @@ import com.eu.habbo.habbohotel.commands.Command;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
public class CommandLog implements Loggable public class CommandLog implements Loggable {
{
public static final String insertQuery = "INSERT INTO commandlogs (`user_id`, `timestamp`, `command`, `params`, `succes`) VALUES (?, ?, ?, ?, ?)"; public static final String insertQuery = "INSERT INTO commandlogs (`user_id`, `timestamp`, `command`, `params`, `succes`) VALUES (?, ?, ?, ?, ?)";
private final int userId; private final int userId;
@ -17,8 +16,7 @@ public class CommandLog implements Loggable
private final boolean succes; private final boolean succes;
public CommandLog(int userId, Command command, String params, boolean succes) public CommandLog(int userId, Command command, String params, boolean succes) {
{
this.userId = userId; this.userId = userId;
this.command = command; this.command = command;
this.params = params; this.params = params;
@ -26,8 +24,7 @@ public class CommandLog implements Loggable
} }
@Override @Override
public void log(PreparedStatement statement) throws SQLException public void log(PreparedStatement statement) throws SQLException {
{
statement.setInt(1, this.userId); statement.setInt(1, this.userId);
statement.setInt(2, this.timestamp); statement.setInt(2, this.timestamp);
statement.setString(3, this.command.getClass().getSimpleName()); statement.setString(3, this.command.getClass().getSimpleName());

View File

@ -11,128 +11,95 @@ import java.sql.*;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
public class ConfigurationManager public class ConfigurationManager {
{
public boolean loaded = false;
public boolean isLoading = false;
private final Properties properties; private final Properties properties;
private final String configurationPath; private final String configurationPath;
public boolean loaded = false;
public boolean isLoading = false;
public ConfigurationManager(String configurationPath) throws Exception public ConfigurationManager(String configurationPath) throws Exception {
{
this.properties = new Properties(); this.properties = new Properties();
this.configurationPath = configurationPath; this.configurationPath = configurationPath;
this.reload(); this.reload();
} }
public void reload() public void reload() {
{
this.isLoading = true; this.isLoading = true;
this.properties.clear(); this.properties.clear();
InputStream input = null; InputStream input = null;
try try {
{
File f = new File(this.configurationPath); File f = new File(this.configurationPath);
input = new FileInputStream(f); input = new FileInputStream(f);
this.properties.load(input); this.properties.load(input);
} } catch (IOException ex) {
catch (IOException ex)
{
Emulator.getLogging().logErrorLine("[CRITICAL] FAILED TO LOAD CONFIG FILE! (" + this.configurationPath + ")"); Emulator.getLogging().logErrorLine("[CRITICAL] FAILED TO LOAD CONFIG FILE! (" + this.configurationPath + ")");
ex.printStackTrace(); ex.printStackTrace();
} } finally {
finally if (input != null) {
{ try {
if (input != null)
{
try
{
input.close(); input.close();
} } catch (IOException e) {
catch (IOException e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
if(this.loaded) if (this.loaded) {
{
this.loadFromDatabase(); this.loadFromDatabase();
} }
this.isLoading = false; this.isLoading = false;
Emulator.getLogging().logStart("Configuration Manager -> Loaded!"); Emulator.getLogging().logStart("Configuration Manager -> Loaded!");
if (Emulator.getPluginManager() != null) if (Emulator.getPluginManager() != null) {
{
Emulator.getPluginManager().fireEvent(new EmulatorConfigUpdatedEvent()); Emulator.getPluginManager().fireEvent(new EmulatorConfigUpdatedEvent());
} }
} }
public void loadFromDatabase() public void loadFromDatabase() {
{
Emulator.getLogging().logStart("Loading configuration from database..."); Emulator.getLogging().logStart("Loading configuration from database...");
long millis = System.currentTimeMillis(); long millis = System.currentTimeMillis();
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement()) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement()) {
{ if (statement.execute("SELECT * FROM emulator_settings")) {
if (statement.execute("SELECT * FROM emulator_settings")) try (ResultSet set = statement.getResultSet()) {
{ while (set.next()) {
try (ResultSet set = statement.getResultSet())
{
while (set.next())
{
this.properties.put(set.getString("key"), set.getString("value")); this.properties.put(set.getString("key"), set.getString("value"));
} }
} }
} }
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
Emulator.getLogging().logStart("Configuration -> loaded! (" + (System.currentTimeMillis() - millis) + " MS)"); Emulator.getLogging().logStart("Configuration -> loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
} }
public void saveToDatabase() public void saveToDatabase() {
{ try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE emulator_settings SET `value` = ? WHERE `key` = ? LIMIT 1")) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE emulator_settings SET `value` = ? WHERE `key` = ? LIMIT 1")) for (Map.Entry<Object, Object> entry : this.properties.entrySet()) {
{
for (Map.Entry<Object, Object> entry : this.properties.entrySet())
{
statement.setString(1, entry.getValue().toString()); statement.setString(1, entry.getValue().toString());
statement.setString(2, entry.getKey().toString()); statement.setString(2, entry.getKey().toString());
statement.executeUpdate(); statement.executeUpdate();
} }
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
public String getValue(String key) public String getValue(String key) {
{
return this.getValue(key, ""); return this.getValue(key, "");
} }
public String getValue(String key, String defaultValue) public String getValue(String key, String defaultValue) {
{
if (this.isLoading) if (this.isLoading)
return defaultValue; return defaultValue;
@ -143,68 +110,54 @@ public class ConfigurationManager
} }
public boolean getBoolean(String key) public boolean getBoolean(String key) {
{
return this.getBoolean(key, false); return this.getBoolean(key, false);
} }
public boolean getBoolean(String key, boolean defaultValue) public boolean getBoolean(String key, boolean defaultValue) {
{
if (this.isLoading) if (this.isLoading)
return defaultValue; return defaultValue;
try try {
{
return (this.getValue(key, "0").equals("1")) || (this.getValue(key, "false").equals("true")); return (this.getValue(key, "0").equals("1")) || (this.getValue(key, "false").equals("true"));
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logErrorLine("Failed to parse key " + key + " with value " + this.getValue(key) + " to type boolean."); Emulator.getLogging().logErrorLine("Failed to parse key " + key + " with value " + this.getValue(key) + " to type boolean.");
} }
return defaultValue; return defaultValue;
} }
public int getInt(String key) public int getInt(String key) {
{
return this.getInt(key, 0); return this.getInt(key, 0);
} }
public int getInt(String key, Integer defaultValue) public int getInt(String key, Integer defaultValue) {
{
if (this.isLoading) if (this.isLoading)
return defaultValue; return defaultValue;
try try {
{
return Integer.parseInt(this.getValue(key, defaultValue.toString())); return Integer.parseInt(this.getValue(key, defaultValue.toString()));
} catch (Exception e) } catch (Exception e) {
{
Emulator.getLogging().logErrorLine("Failed to parse key " + key + " with value " + this.getValue(key) + " to type integer."); Emulator.getLogging().logErrorLine("Failed to parse key " + key + " with value " + this.getValue(key) + " to type integer.");
} }
return defaultValue; return defaultValue;
} }
public double getDouble(String key) public double getDouble(String key) {
{
return this.getDouble(key, 0.0); return this.getDouble(key, 0.0);
} }
public double getDouble(String key, Double defaultValue) public double getDouble(String key, Double defaultValue) {
{
if (this.isLoading) if (this.isLoading)
return defaultValue; return defaultValue;
try try {
{
return Double.parseDouble(this.getValue(key, defaultValue.toString())); return Double.parseDouble(this.getValue(key, defaultValue.toString()));
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logErrorLine("Failed to parse key " + key + " with value " + this.getValue(key) + " to type double."); Emulator.getLogging().logErrorLine("Failed to parse key " + key + " with value " + this.getValue(key) + " to type double.");
} }
@ -212,24 +165,19 @@ public class ConfigurationManager
} }
public void update(String key, String value) public void update(String key, String value) {
{
this.properties.setProperty(key, value); this.properties.setProperty(key, value);
} }
public void register(String key, String value) public void register(String key, String value) {
{
if (this.properties.getProperty(key, null) != null) if (this.properties.getProperty(key, null) != null)
return; return;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO emulator_settings VALUES (?, ?)")) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO emulator_settings VALUES (?, ?)")) {
{
statement.setString(1, key); statement.setString(1, key);
statement.setString(2, value); statement.setString(2, value);
statement.execute(); statement.execute();
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }

View File

@ -5,8 +5,7 @@ import com.eu.habbo.habbohotel.users.Habbo;
import java.util.Map; import java.util.Map;
public class CreditsScheduler extends Scheduler public class CreditsScheduler extends Scheduler {
{
public static boolean IGNORE_HOTEL_VIEW; public static boolean IGNORE_HOTEL_VIEW;
@ -22,8 +21,7 @@ public class CreditsScheduler extends Scheduler
} }
public void reloadConfig() { public void reloadConfig() {
if(Emulator.getConfig().getBoolean("hotel.auto.credits.enabled")) if (Emulator.getConfig().getBoolean("hotel.auto.credits.enabled")) {
{
IGNORE_HOTEL_VIEW = Emulator.getConfig().getBoolean("hotel.auto.credits.ignore.hotelview"); IGNORE_HOTEL_VIEW = Emulator.getConfig().getBoolean("hotel.auto.credits.ignore.hotelview");
IGNORE_IDLED = Emulator.getConfig().getBoolean("hotel.auto.credits.ignore.idled"); IGNORE_IDLED = Emulator.getConfig().getBoolean("hotel.auto.credits.ignore.idled");
CREDITS = Emulator.getConfig().getInt("hotel.auto.credits.amount"); CREDITS = Emulator.getConfig().getInt("hotel.auto.credits.amount");
@ -31,27 +29,21 @@ public class CreditsScheduler extends Scheduler
this.disposed = false; this.disposed = false;
this.run(); this.run();
} }
} } else {
else
{
this.disposed = true; this.disposed = true;
} }
} }
@Override @Override
public void run() public void run() {
{
super.run(); super.run();
Habbo habbo; Habbo habbo;
for(Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) for (Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) {
{
habbo = map.getValue(); habbo = map.getValue();
try try {
{ if (habbo != null) {
if (habbo != null)
{
if (habbo.getHabboInfo().getCurrentRoom() == null && IGNORE_HOTEL_VIEW) if (habbo.getHabboInfo().getCurrentRoom() == null && IGNORE_HOTEL_VIEW)
continue; continue;
@ -60,21 +52,17 @@ public class CreditsScheduler extends Scheduler
habbo.giveCredits(CREDITS); habbo.giveCredits(CREDITS);
} }
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
} }
} }
} }
public boolean isDisposed() public boolean isDisposed() {
{
return this.disposed; return this.disposed;
} }
public void setDisposed(boolean disposed) public void setDisposed(boolean disposed) {
{
this.disposed = disposed; this.disposed = disposed;
} }
} }

View File

@ -1,7 +1,7 @@
package com.eu.habbo.core; package com.eu.habbo.core;
public interface Disposable public interface Disposable {
{
void dispose(); void dispose();
boolean disposed(); boolean disposed();
} }

View File

@ -8,13 +8,10 @@ import com.eu.habbo.messages.outgoing.rooms.users.RoomUserWhisperComposer;
import com.eu.habbo.plugin.EventHandler; import com.eu.habbo.plugin.EventHandler;
import com.eu.habbo.plugin.events.users.UserSavedMottoEvent; import com.eu.habbo.plugin.events.users.UserSavedMottoEvent;
public class Easter public class Easter {
{
@EventHandler @EventHandler
public static void onUserChangeMotto(UserSavedMottoEvent event) public static void onUserChangeMotto(UserSavedMottoEvent event) {
{ if (event.newMotto.equalsIgnoreCase("crickey!")) {
if(event.newMotto.equalsIgnoreCase("crickey!"))
{
event.habbo.getClient().sendResponse(new RoomUserWhisperComposer(new RoomChatMessage(event.newMotto, event.habbo, event.habbo, RoomChatMessageBubbles.ALERT))); event.habbo.getClient().sendResponse(new RoomUserWhisperComposer(new RoomChatMessage(event.newMotto, event.habbo, event.habbo, RoomChatMessageBubbles.ALERT)));
Room room = event.habbo.getHabboInfo().getCurrentRoom(); Room room = event.habbo.getHabboInfo().getCurrentRoom();

View File

@ -9,8 +9,7 @@ import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
public class ErrorLog implements Loggable public class ErrorLog implements Loggable {
{
public final static String insertQuery = "INSERT INTO emulator_errors (timestamp, version, build_hash, type, stacktrace) VALUES (?, ?, ?, ?, ?)"; public final static String insertQuery = "INSERT INTO emulator_errors (timestamp, version, build_hash, type, stacktrace) VALUES (?, ?, ?, ?, ?)";
public final String version; public final String version;
public final String buildHash; public final String buildHash;
@ -19,8 +18,7 @@ public class ErrorLog implements Loggable
public final String type; public final String type;
public final String stackTrace; public final String stackTrace;
public ErrorLog(String type, Throwable e) public ErrorLog(String type, Throwable e) {
{
this.version = Emulator.version; this.version = Emulator.version;
this.buildHash = Emulator.version; this.buildHash = Emulator.version;
@ -33,18 +31,15 @@ public class ErrorLog implements Loggable
e.printStackTrace(pw); e.printStackTrace(pw);
this.stackTrace = sw.toString(); this.stackTrace = sw.toString();
try try {
{
pw.close(); pw.close();
sw.close(); sw.close();
} catch (IOException e1) } catch (IOException e1) {
{
Emulator.getLogging().logErrorLine(e1); Emulator.getLogging().logErrorLine(e1);
} }
} }
public ErrorLog(String type, String message) public ErrorLog(String type, String message) {
{
this.version = Emulator.version; this.version = Emulator.version;
this.buildHash = Emulator.build; this.buildHash = Emulator.build;
@ -54,8 +49,7 @@ public class ErrorLog implements Loggable
} }
@Override @Override
public void log(PreparedStatement statement) throws SQLException public void log(PreparedStatement statement) throws SQLException {
{
statement.setInt(1, this.timeStamp); statement.setInt(1, this.timeStamp);
statement.setString(2, this.version); statement.setString(2, this.version);
statement.setString(3, this.buildHash); statement.setString(3, this.buildHash);

View File

@ -3,7 +3,6 @@ package com.eu.habbo.core;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
public interface Loggable public interface Loggable {
{
void log(PreparedStatement statement) throws SQLException; void log(PreparedStatement statement) throws SQLException;
} }

View File

@ -13,28 +13,12 @@ import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
public class Logging public class Logging {
{
private static PrintWriter packetsWriter;
private static PrintWriter packetsUndefinedWriter;
private static PrintWriter errorsPacketsWriter;
private static PrintWriter errorsSQLWriter;
private static PrintWriter errorsRuntimeWriter;
private static PrintWriter debugFileWriter;
public static final String ANSI_BRIGHT = "\u001B[1m"; public static final String ANSI_BRIGHT = "\u001B[1m";
public static final String ANSI_ITALICS = "\u001B[3m"; public static final String ANSI_ITALICS = "\u001B[3m";
public static final String ANSI_UNDERLINE = "\u001B[4m"; public static final String ANSI_UNDERLINE = "\u001B[4m";
public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m"; public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m"; public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m"; public static final String ANSI_GREEN = "\u001B[32m";
@ -43,8 +27,12 @@ public class Logging
public static final String ANSI_PURPLE = "\u001B[35m"; public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m"; public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m"; public static final String ANSI_WHITE = "\u001B[37m";
private static PrintWriter packetsWriter;
private static PrintWriter packetsUndefinedWriter;
private static PrintWriter errorsPacketsWriter;
private static PrintWriter errorsSQLWriter;
private static PrintWriter errorsRuntimeWriter;
private static PrintWriter debugFileWriter;
private final THashSet<Loggable> errorLogs = new THashSet<>(100); private final THashSet<Loggable> errorLogs = new THashSet<>(100);
@ -52,8 +40,7 @@ public class Logging
private ConcurrentSet<Loggable> chatLogs = new ConcurrentSet<>(); private ConcurrentSet<Loggable> chatLogs = new ConcurrentSet<>();
public Logging() public Logging() {
{
File packets = new File("logging//packets//defined.txt"); File packets = new File("logging//packets//defined.txt");
@ -67,121 +54,101 @@ public class Logging
File debugFile = new File("logging//debug.txt"); File debugFile = new File("logging//debug.txt");
try try {
{ if (!packets.exists()) {
if (!packets.exists()) if (!packets.getParentFile().exists()) {
{
if (!packets.getParentFile().exists())
{
packets.getParentFile().mkdirs(); packets.getParentFile().mkdirs();
} }
packets.createNewFile(); packets.createNewFile();
} }
if (!packetsUndefined.exists()) if (!packetsUndefined.exists()) {
{ if (!packetsUndefined.getParentFile().exists()) {
if (!packetsUndefined.getParentFile().exists())
{
packetsUndefined.getParentFile().mkdirs(); packetsUndefined.getParentFile().mkdirs();
} }
packetsUndefined.createNewFile(); packetsUndefined.createNewFile();
} }
if (!errorsPackets.exists()) if (!errorsPackets.exists()) {
{ if (!errorsPackets.getParentFile().exists()) {
if (!errorsPackets.getParentFile().exists())
{
errorsPackets.getParentFile().mkdirs(); errorsPackets.getParentFile().mkdirs();
} }
errorsPackets.createNewFile(); errorsPackets.createNewFile();
} }
if (!errorsSQL.exists()) if (!errorsSQL.exists()) {
{ if (!errorsSQL.getParentFile().exists()) {
if (!errorsSQL.getParentFile().exists())
{
errorsSQL.getParentFile().mkdirs(); errorsSQL.getParentFile().mkdirs();
} }
errorsSQL.createNewFile(); errorsSQL.createNewFile();
} }
if (!errorsRuntime.exists()) if (!errorsRuntime.exists()) {
{ if (!errorsRuntime.getParentFile().exists()) {
if (!errorsRuntime.getParentFile().exists())
{
errorsRuntime.getParentFile().mkdirs(); errorsRuntime.getParentFile().mkdirs();
} }
errorsRuntime.createNewFile(); errorsRuntime.createNewFile();
} }
if (!debugFile.exists()) if (!debugFile.exists()) {
{ if (!debugFile.getParentFile().exists()) {
if (!debugFile.getParentFile().exists())
{
debugFile.getParentFile().mkdirs(); debugFile.getParentFile().mkdirs();
} }
debugFile.createNewFile(); debugFile.createNewFile();
} }
} } catch (Exception e) {
catch(Exception e)
{
e.printStackTrace(); e.printStackTrace();
} }
try try {
{
packetsWriter = new PrintWriter(new FileWriter(packets, true)); packetsWriter = new PrintWriter(new FileWriter(packets, true));
packetsUndefinedWriter = new PrintWriter(new FileWriter(packetsUndefined, true)); packetsUndefinedWriter = new PrintWriter(new FileWriter(packetsUndefined, true));
errorsPacketsWriter = new PrintWriter(new FileWriter(errorsPackets, true)); errorsPacketsWriter = new PrintWriter(new FileWriter(errorsPackets, true));
errorsSQLWriter = new PrintWriter(new FileWriter(errorsSQL, true)); errorsSQLWriter = new PrintWriter(new FileWriter(errorsSQL, true));
errorsRuntimeWriter = new PrintWriter(new FileWriter(errorsRuntime, true)); errorsRuntimeWriter = new PrintWriter(new FileWriter(errorsRuntime, true));
debugFileWriter = new PrintWriter(new FileWriter(debugFile, true)); debugFileWriter = new PrintWriter(new FileWriter(debugFile, true));
} } catch (IOException e) {
catch (IOException e)
{
System.out.println("[CRITICAL] FAILED TO LOAD LOGGING COMPONENT!"); System.out.println("[CRITICAL] FAILED TO LOAD LOGGING COMPONENT!");
} }
} }
public static PrintWriter getPacketsWriter() {
return packetsWriter;
}
public void logStart(Object line) public static PrintWriter getPacketsUndefinedWriter() {
{ return packetsUndefinedWriter;
}
public void logStart(Object line) {
System.out.println("[" + Logging.ANSI_BRIGHT + Logging.ANSI_GREEN + "LOADING" + Logging.ANSI_RESET + "] " + line.toString()); System.out.println("[" + Logging.ANSI_BRIGHT + Logging.ANSI_GREEN + "LOADING" + Logging.ANSI_RESET + "] " + line.toString());
} }
public void logShutdownLine(Object line) {
public void logShutdownLine(Object line) if (Emulator.getConfig().getBoolean("logging.debug")) {
{
if(Emulator.getConfig().getBoolean("logging.debug"))
{
this.write(debugFileWriter, line.toString()); this.write(debugFileWriter, line.toString());
} }
System.out.println("[" + Logging.ANSI_BRIGHT + Logging.ANSI_GREEN + "SHUTDOWN" + Logging.ANSI_RESET + "] " + line.toString()); System.out.println("[" + Logging.ANSI_BRIGHT + Logging.ANSI_GREEN + "SHUTDOWN" + Logging.ANSI_RESET + "] " + line.toString());
} }
public void logUserLine(Object line) public void logUserLine(Object line) {
{ if (Emulator.getConfig().getBoolean("logging.debug")) {
if(Emulator.getConfig().getBoolean("logging.debug"))
{
this.write(debugFileWriter, line.toString()); this.write(debugFileWriter, line.toString());
} }
if (Emulator.getConfig().getBoolean("debug.show.users")) if (Emulator.getConfig().getBoolean("debug.show.users")) {
{
System.out.println("[USER] " + line.toString()); System.out.println("[USER] " + line.toString());
} }
} }
public synchronized void logDebugLine(Object line) public synchronized void logDebugLine(Object line) {
{ if (line instanceof Throwable) {
if (line instanceof Throwable)
{
this.logErrorLine(line); this.logErrorLine(line);
return; return;
} }
@ -189,54 +156,43 @@ public class Logging
System.out.println("[DEBUG] " + line.toString()); System.out.println("[DEBUG] " + line.toString());
} }
if(Emulator.getConfig().getBoolean("logging.debug")) if (Emulator.getConfig().getBoolean("logging.debug")) {
{
this.write(debugFileWriter, line.toString()); this.write(debugFileWriter, line.toString());
} }
} }
public synchronized void logPacketLine(Object line) public synchronized void logPacketLine(Object line) {
{
if (Emulator.getConfig().getBoolean("debug.show.packets")) { if (Emulator.getConfig().getBoolean("debug.show.packets")) {
System.out.println("[" + Logging.ANSI_BLUE + "PACKET" + Logging.ANSI_RESET + "]" + line.toString()); System.out.println("[" + Logging.ANSI_BLUE + "PACKET" + Logging.ANSI_RESET + "]" + line.toString());
} }
if(Emulator.getConfig().getBoolean("logging.packets")) if (Emulator.getConfig().getBoolean("logging.packets")) {
{
this.write(packetsWriter, line.toString()); this.write(packetsWriter, line.toString());
} }
} }
public synchronized void logUndefinedPacketLine(Object line) public synchronized void logUndefinedPacketLine(Object line) {
{ if (Emulator.getConfig().getBoolean("debug.show.packets.undefined")) {
if (Emulator.getConfig().getBoolean("debug.show.packets.undefined"))
{
System.out.println("[PACKET] [UNDEFINED] " + line.toString()); System.out.println("[PACKET] [UNDEFINED] " + line.toString());
} }
if (Emulator.getConfig().getBoolean("logging.packets.undefined")) if (Emulator.getConfig().getBoolean("logging.packets.undefined")) {
{
this.write(packetsUndefinedWriter, line.toString()); this.write(packetsUndefinedWriter, line.toString());
} }
} }
public synchronized void logErrorLine(Object line) public synchronized void logErrorLine(Object line) {
{ if (Emulator.isReady && Emulator.getConfig().getBoolean("debug.show.errors")) {
if (Emulator.isReady && Emulator.getConfig().getBoolean("debug.show.errors"))
{
System.err.println("[ERROR] " + line.toString()); System.err.println("[ERROR] " + line.toString());
} }
if (Emulator.getConfig().loaded && Emulator.getConfig().getBoolean("logging.errors.runtime")) if (Emulator.getConfig().loaded && Emulator.getConfig().getBoolean("logging.errors.runtime")) {
{
this.write(errorsRuntimeWriter, line); this.write(errorsRuntimeWriter, line);
} }
if(line instanceof Throwable) if (line instanceof Throwable) {
{
((Throwable) line).printStackTrace(); ((Throwable) line).printStackTrace();
if (line instanceof SQLException) if (line instanceof SQLException) {
{
this.logSQLException((SQLException) line); this.logSQLException((SQLException) line);
return; return;
} }
@ -250,10 +206,8 @@ public class Logging
this.errorLogs.add(new ErrorLog("Emulator", line.toString())); this.errorLogs.add(new ErrorLog("Emulator", line.toString()));
} }
public void logSQLException(SQLException e) public void logSQLException(SQLException e) {
{ if (Emulator.getConfig().getBoolean("logging.errors.sql")) {
if(Emulator.getConfig().getBoolean("logging.errors.sql"))
{
e.printStackTrace(); e.printStackTrace();
this.write(errorsSQLWriter, e); this.write(errorsSQLWriter, e);
@ -261,21 +215,17 @@ public class Logging
} }
} }
public void logPacketError(Object e) public void logPacketError(Object e) {
{ if (Emulator.getConfig().getBoolean("logging.errors.packets")) {
if(Emulator.getConfig().getBoolean("logging.errors.packets"))
{
if (e instanceof Throwable) if (e instanceof Throwable)
((Exception) e).printStackTrace(); ((Exception) e).printStackTrace();
this.write(errorsPacketsWriter, e); this.write(errorsPacketsWriter, e);
} }
if(e instanceof Throwable) if (e instanceof Throwable) {
{
((Throwable) e).printStackTrace(); ((Throwable) e).printStackTrace();
if (e instanceof SQLException) if (e instanceof SQLException) {
{
this.logSQLException((SQLException) e); this.logSQLException((SQLException) e);
return; return;
} }
@ -284,21 +234,15 @@ public class Logging
} }
} }
public void handleException(Exception e) public void handleException(Exception e) {
{
e.printStackTrace(); e.printStackTrace();
} }
private synchronized void write(PrintWriter printWriter, Object message) private synchronized void write(PrintWriter printWriter, Object message) {
{ if (printWriter != null && message != null) {
if(printWriter != null && message != null) if (message instanceof Throwable) {
{
if(message instanceof Throwable)
{
((Exception) message).printStackTrace(printWriter); ((Exception) message).printStackTrace(printWriter);
} } else {
else
{
printWriter.write("MSG: " + message.toString() + "\r\n"); printWriter.write("MSG: " + message.toString() + "\r\n");
} }
@ -306,45 +250,30 @@ public class Logging
} }
} }
public void addLog(Loggable log) public void addLog(Loggable log) {
{ if (log instanceof ErrorLog) {
if (log instanceof ErrorLog) synchronized (this.errorLogs) {
{
synchronized (this.errorLogs)
{
this.errorLogs.add(log); this.errorLogs.add(log);
} }
} } else if (log instanceof CommandLog) {
else if (log instanceof CommandLog) synchronized (this.commandLogs) {
{
synchronized (this.commandLogs)
{
this.commandLogs.add(log); this.commandLogs.add(log);
} }
} }
} }
public void addChatLog(Loggable chatLog) public void addChatLog(Loggable chatLog) {
{
this.chatLogs.add(chatLog); this.chatLogs.add(chatLog);
} }
public void saveLogs() public void saveLogs() {
{ if (Emulator.getDatabase() != null && Emulator.getDatabase().getDataSource() != null) {
if (Emulator.getDatabase() != null && Emulator.getDatabase().getDataSource() != null) if (!this.errorLogs.isEmpty() || !this.commandLogs.isEmpty() || !this.chatLogs.isEmpty()) {
{ try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
if (!this.errorLogs.isEmpty() || !this.commandLogs.isEmpty() || !this.chatLogs.isEmpty()) if (!this.errorLogs.isEmpty()) {
{ synchronized (this.errorLogs) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) try (PreparedStatement statement = connection.prepareStatement(ErrorLog.insertQuery)) {
{ for (Loggable log : this.errorLogs) {
if (!this.errorLogs.isEmpty())
{
synchronized (this.errorLogs)
{
try (PreparedStatement statement = connection.prepareStatement(ErrorLog.insertQuery))
{
for (Loggable log : this.errorLogs)
{
log.log(statement); log.log(statement);
} }
statement.executeBatch(); statement.executeBatch();
@ -353,14 +282,10 @@ public class Logging
} }
} }
if (!this.commandLogs.isEmpty()) if (!this.commandLogs.isEmpty()) {
{ synchronized (this.commandLogs) {
synchronized (this.commandLogs) try (PreparedStatement statement = connection.prepareStatement(CommandLog.insertQuery)) {
{ for (Loggable log : this.commandLogs) {
try (PreparedStatement statement = connection.prepareStatement(CommandLog.insertQuery))
{
for (Loggable log : this.commandLogs)
{
log.log(statement); log.log(statement);
} }
@ -370,15 +295,12 @@ public class Logging
} }
} }
if (!this.chatLogs.isEmpty()) if (!this.chatLogs.isEmpty()) {
{
ConcurrentSet<Loggable> chatLogs = this.chatLogs; ConcurrentSet<Loggable> chatLogs = this.chatLogs;
this.chatLogs = new ConcurrentSet<>(); this.chatLogs = new ConcurrentSet<>();
try (PreparedStatement statement = connection.prepareStatement(RoomChatMessage.insertQuery)) try (PreparedStatement statement = connection.prepareStatement(RoomChatMessage.insertQuery)) {
{ for (Loggable log : chatLogs) {
for (Loggable log : chatLogs)
{
log.log(statement); log.log(statement);
} }
@ -386,24 +308,12 @@ public class Logging
} }
chatLogs.clear(); chatLogs.clear();
} }
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
} }
} }
public static PrintWriter getPacketsWriter()
{
return packetsWriter;
}
public static PrintWriter getPacketsUndefinedWriter()
{
return packetsUndefinedWriter;
}
/* /*
public static PrintWriter getErrorsPacketsWriter() public static PrintWriter getErrorsPacketsWriter()
{ {

View File

@ -5,8 +5,7 @@ import com.eu.habbo.habbohotel.users.Habbo;
import java.util.Map; import java.util.Map;
public class PixelScheduler extends Scheduler public class PixelScheduler extends Scheduler {
{
public static boolean IGNORE_HOTEL_VIEW; public static boolean IGNORE_HOTEL_VIEW;
@ -16,15 +15,37 @@ public class PixelScheduler extends Scheduler
private static int PIXELS; private static int PIXELS;
public PixelScheduler() public PixelScheduler() {
{
super(Emulator.getConfig().getInt("hotel.auto.pixels.interval")); super(Emulator.getConfig().getInt("hotel.auto.pixels.interval"));
this.reloadConfig(); this.reloadConfig();
} }
public static boolean isIgnoreHotelView() {
return IGNORE_HOTEL_VIEW;
}
public static void setIgnoreHotelView(boolean ignoreHotelView) {
IGNORE_HOTEL_VIEW = ignoreHotelView;
}
public static boolean isIgnoreIdled() {
return IGNORE_IDLED;
}
public static void setIgnoreIdled(boolean ignoreIdled) {
IGNORE_IDLED = ignoreIdled;
}
public static int getPIXELS() {
return PIXELS;
}
public static void setPIXELS(int PIXELS) {
PixelScheduler.PIXELS = PIXELS;
}
public void reloadConfig() { public void reloadConfig() {
if(Emulator.getConfig().getBoolean("hotel.auto.pixels.enabled")) if (Emulator.getConfig().getBoolean("hotel.auto.pixels.enabled")) {
{
IGNORE_HOTEL_VIEW = Emulator.getConfig().getBoolean("hotel.auto.pixels.ignore.hotelview"); IGNORE_HOTEL_VIEW = Emulator.getConfig().getBoolean("hotel.auto.pixels.ignore.hotelview");
IGNORE_IDLED = Emulator.getConfig().getBoolean("hotel.auto.pixels.ignore.idled"); IGNORE_IDLED = Emulator.getConfig().getBoolean("hotel.auto.pixels.ignore.idled");
PIXELS = Emulator.getConfig().getInt("hotel.auto.pixels.amount"); PIXELS = Emulator.getConfig().getInt("hotel.auto.pixels.amount");
@ -32,27 +53,21 @@ public class PixelScheduler extends Scheduler
this.disposed = false; this.disposed = false;
this.run(); this.run();
} }
} } else {
else
{
this.disposed = true; this.disposed = true;
} }
} }
@Override @Override
public void run() public void run() {
{
super.run(); super.run();
Habbo habbo; Habbo habbo;
for(Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) for (Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) {
{
habbo = map.getValue(); habbo = map.getValue();
try try {
{ if (habbo != null) {
if (habbo != null)
{
if (habbo.getHabboInfo().getCurrentRoom() == null && IGNORE_HOTEL_VIEW) if (habbo.getHabboInfo().getCurrentRoom() == null && IGNORE_HOTEL_VIEW)
continue; continue;
@ -61,51 +76,17 @@ public class PixelScheduler extends Scheduler
habbo.givePixels(PIXELS); habbo.givePixels(PIXELS);
} }
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
} }
} }
} }
public static boolean isIgnoreHotelView() public boolean isDisposed() {
{
return IGNORE_HOTEL_VIEW;
}
public static void setIgnoreHotelView(boolean ignoreHotelView)
{
IGNORE_HOTEL_VIEW = ignoreHotelView;
}
public static boolean isIgnoreIdled()
{
return IGNORE_IDLED;
}
public static void setIgnoreIdled(boolean ignoreIdled)
{
IGNORE_IDLED = ignoreIdled;
}
public static int getPIXELS()
{
return PIXELS;
}
public static void setPIXELS(int PIXELS)
{
PixelScheduler.PIXELS = PIXELS;
}
public boolean isDisposed()
{
return this.disposed; return this.disposed;
} }
public void setDisposed(boolean disposed) public void setDisposed(boolean disposed) {
{
this.disposed = disposed; this.disposed = disposed;
} }
} }

View File

@ -5,8 +5,7 @@ import com.eu.habbo.habbohotel.users.Habbo;
import java.util.Map; import java.util.Map;
public class PointsScheduler extends Scheduler public class PointsScheduler extends Scheduler {
{
public static boolean IGNORE_HOTEL_VIEW; public static boolean IGNORE_HOTEL_VIEW;
@ -16,15 +15,37 @@ public class PointsScheduler extends Scheduler
private static int POINTS; private static int POINTS;
public PointsScheduler() public PointsScheduler() {
{
super(Emulator.getConfig().getInt("hotel.auto.points.interval")); super(Emulator.getConfig().getInt("hotel.auto.points.interval"));
this.reloadConfig(); this.reloadConfig();
} }
public static boolean isIgnoreHotelView() {
return IGNORE_HOTEL_VIEW;
}
public static void setIgnoreHotelView(boolean ignoreHotelView) {
IGNORE_HOTEL_VIEW = ignoreHotelView;
}
public static boolean isIgnoreIdled() {
return IGNORE_IDLED;
}
public static void setIgnoreIdled(boolean ignoreIdled) {
IGNORE_IDLED = ignoreIdled;
}
public static int getPOINTS() {
return POINTS;
}
public static void setPOINTS(int POINTS) {
PointsScheduler.POINTS = POINTS;
}
public void reloadConfig() { public void reloadConfig() {
if(Emulator.getConfig().getBoolean("hotel.auto.points.enabled")) if (Emulator.getConfig().getBoolean("hotel.auto.points.enabled")) {
{
IGNORE_HOTEL_VIEW = Emulator.getConfig().getBoolean("hotel.auto.points.ignore.hotelview"); IGNORE_HOTEL_VIEW = Emulator.getConfig().getBoolean("hotel.auto.points.ignore.hotelview");
IGNORE_IDLED = Emulator.getConfig().getBoolean("hotel.auto.points.ignore.idled"); IGNORE_IDLED = Emulator.getConfig().getBoolean("hotel.auto.points.ignore.idled");
POINTS = Emulator.getConfig().getInt("hotel.auto.points.amount"); POINTS = Emulator.getConfig().getInt("hotel.auto.points.amount");
@ -32,27 +53,21 @@ public class PointsScheduler extends Scheduler
this.disposed = false; this.disposed = false;
this.run(); this.run();
} }
} } else {
else
{
this.disposed = true; this.disposed = true;
} }
} }
@Override @Override
public void run() public void run() {
{
super.run(); super.run();
Habbo habbo; Habbo habbo;
for(Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) for (Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) {
{
habbo = map.getValue(); habbo = map.getValue();
try try {
{ if (habbo != null) {
if (habbo != null)
{
if (habbo.getHabboInfo().getCurrentRoom() == null && IGNORE_HOTEL_VIEW) if (habbo.getHabboInfo().getCurrentRoom() == null && IGNORE_HOTEL_VIEW)
continue; continue;
@ -61,51 +76,17 @@ public class PointsScheduler extends Scheduler
habbo.givePoints(POINTS); habbo.givePoints(POINTS);
} }
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
} }
} }
} }
public static boolean isIgnoreHotelView() public boolean isDisposed() {
{
return IGNORE_HOTEL_VIEW;
}
public static void setIgnoreHotelView(boolean ignoreHotelView)
{
IGNORE_HOTEL_VIEW = ignoreHotelView;
}
public static boolean isIgnoreIdled()
{
return IGNORE_IDLED;
}
public static void setIgnoreIdled(boolean ignoreIdled)
{
IGNORE_IDLED = ignoreIdled;
}
public static int getPOINTS()
{
return POINTS;
}
public static void setPOINTS(int POINTS)
{
PointsScheduler.POINTS = POINTS;
}
public boolean isDisposed()
{
return this.disposed; return this.disposed;
} }
public void setDisposed(boolean disposed) public void setDisposed(boolean disposed) {
{
this.disposed = disposed; this.disposed = disposed;
} }
} }

View File

@ -5,15 +5,13 @@ import com.eu.habbo.messages.ServerMessage;
import com.eu.habbo.messages.outgoing.MessageComposer; import com.eu.habbo.messages.outgoing.MessageComposer;
import com.eu.habbo.messages.outgoing.Outgoing; import com.eu.habbo.messages.outgoing.Outgoing;
public class RoomUserPetComposer extends MessageComposer public class RoomUserPetComposer extends MessageComposer {
{
private final int petType; private final int petType;
private final int race; private final int race;
private final String color; private final String color;
private final Habbo habbo; private final Habbo habbo;
public RoomUserPetComposer(int petType, int race, String color, Habbo habbo) public RoomUserPetComposer(int petType, int race, String color, Habbo habbo) {
{
this.petType = petType; this.petType = petType;
this.race = race; this.race = race;
this.color = color; this.color = color;
@ -21,8 +19,7 @@ public class RoomUserPetComposer extends MessageComposer
} }
@Override @Override
public ServerMessage compose() public ServerMessage compose() {
{
this.response.init(Outgoing.RoomUsersComposer); this.response.init(Outgoing.RoomUsersComposer);
this.response.appendInt(1); this.response.appendInt(1);
this.response.appendInt(this.habbo.getHabboInfo().getId()); this.response.appendInt(this.habbo.getHabboInfo().getId());

View File

@ -2,39 +2,32 @@ package com.eu.habbo.core;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
public class Scheduler implements Runnable public class Scheduler implements Runnable {
{
protected boolean disposed; protected boolean disposed;
protected int interval; protected int interval;
public Scheduler(int interval) public Scheduler(int interval) {
{
this.interval = interval; this.interval = interval;
} }
public boolean isDisposed() public boolean isDisposed() {
{
return this.disposed; return this.disposed;
} }
public void setDisposed(boolean disposed) public void setDisposed(boolean disposed) {
{
this.disposed = disposed; this.disposed = disposed;
} }
public int getInterval() public int getInterval() {
{
return this.interval; return this.interval;
} }
public void setInterval(int interval) public void setInterval(int interval) {
{
this.interval = interval; this.interval = interval;
} }
@Override @Override
public void run() public void run() {
{
if (this.disposed) if (this.disposed)
return; return;

View File

@ -5,62 +5,47 @@ import com.eu.habbo.Emulator;
import java.sql.*; import java.sql.*;
import java.util.Properties; import java.util.Properties;
public class TextsManager public class TextsManager {
{
private final Properties texts; private final Properties texts;
public TextsManager() public TextsManager() {
{
long millis = System.currentTimeMillis(); long millis = System.currentTimeMillis();
this.texts = new Properties(); this.texts = new Properties();
try try {
{
this.reload(); this.reload();
Emulator.getLogging().logStart("Texts Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)"); Emulator.getLogging().logStart("Texts Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
} } catch (Exception e) {
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }
public void reload() throws Exception public void reload() throws Exception {
{ try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM emulator_texts")) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM emulator_texts")) while (set.next()) {
{ if (this.texts.containsKey(set.getString("key"))) {
while(set.next())
{
if(this.texts.containsKey(set.getString("key")))
{
this.texts.setProperty(set.getString("key"), set.getString("value")); this.texts.setProperty(set.getString("key"), set.getString("value"));
} } else {
else
{
this.texts.put(set.getString("key"), set.getString("value")); this.texts.put(set.getString("key"), set.getString("value"));
} }
} }
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
public String getValue(String key) public String getValue(String key) {
{
return this.getValue(key, ""); return this.getValue(key, "");
} }
public String getValue(String key, String defaultValue) public String getValue(String key, String defaultValue) {
{
if (!this.texts.containsKey(key)) { if (!this.texts.containsKey(key)) {
Emulator.getLogging().logErrorLine("[TEXTS] Text key not found: " + key); Emulator.getLogging().logErrorLine("[TEXTS] Text key not found: " + key);
} }
@ -68,64 +53,49 @@ public class TextsManager
} }
public boolean getBoolean(String key) public boolean getBoolean(String key) {
{
return this.getBoolean(key, false); return this.getBoolean(key, false);
} }
public boolean getBoolean(String key, Boolean defaultValue) public boolean getBoolean(String key, Boolean defaultValue) {
{ try {
try
{
return (this.getValue(key, "0").equals("1")) || (this.getValue(key, "false").equals("true")); return (this.getValue(key, "0").equals("1")) || (this.getValue(key, "false").equals("true"));
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
} }
return defaultValue; return defaultValue;
} }
public int getInt(String key) public int getInt(String key) {
{
return this.getInt(key, 0); return this.getInt(key, 0);
} }
public int getInt(String key, Integer defaultValue) public int getInt(String key, Integer defaultValue) {
{ try {
try
{
return Integer.parseInt(this.getValue(key, defaultValue.toString())); return Integer.parseInt(this.getValue(key, defaultValue.toString()));
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
} }
return defaultValue; return defaultValue;
} }
public void update(String key, String value) public void update(String key, String value) {
{
this.texts.setProperty(key, value); this.texts.setProperty(key, value);
} }
public void register(String key, String value) public void register(String key, String value) {
{
if (this.texts.getProperty(key, null) != null) if (this.texts.getProperty(key, null) != null)
return; return;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO emulator_texts VALUES (?, ?)")) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO emulator_texts VALUES (?, ?)")) {
{
statement.setString(1, key); statement.setString(1, key);
statement.setString(2, value); statement.setString(2, value);
statement.execute(); statement.execute();
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }

View File

@ -3,8 +3,7 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
public abstract class ConsoleCommand public abstract class ConsoleCommand {
{
private static final THashMap<String, ConsoleCommand> commands = new THashMap<>(); private static final THashMap<String, ConsoleCommand> commands = new THashMap<>();
@ -15,15 +14,13 @@ public abstract class ConsoleCommand
public final String usage; public final String usage;
public ConsoleCommand(String key, String usage) public ConsoleCommand(String key, String usage) {
{
this.key = key; this.key = key;
this.usage = usage; this.usage = usage;
} }
public static void load() public static void load() {
{
addCommand(new ConsoleShutdownCommand()); addCommand(new ConsoleShutdownCommand());
addCommand(new ConsoleInfoCommand()); addCommand(new ConsoleInfoCommand());
addCommand(new ConsoleTestCommand()); addCommand(new ConsoleTestCommand());
@ -32,49 +29,32 @@ public abstract class ConsoleCommand
addCommand(new ShowRCONCommands()); addCommand(new ShowRCONCommands());
} }
public static void addCommand(ConsoleCommand command) {
public abstract void handle(String[] args) throws Exception;
public static void addCommand(ConsoleCommand command)
{
commands.put(command.key, command); commands.put(command.key, command);
} }
public static ConsoleCommand findCommand(String key) {
public static ConsoleCommand findCommand(String key)
{
return commands.get(key); return commands.get(key);
} }
public static boolean handle(String line) {
public static boolean handle(String line)
{
String[] message = line.split(" "); String[] message = line.split(" ");
if (message.length > 0) if (message.length > 0) {
{
ConsoleCommand command = ConsoleCommand.findCommand(message[0]); ConsoleCommand command = ConsoleCommand.findCommand(message[0]);
if (command != null) if (command != null) {
{ try {
try
{
command.handle(message); command.handle(message);
return true; return true;
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
} }
} } else {
else
{
System.out.println("Unknown Console Command " + message[0]); System.out.println("Unknown Console Command " + message[0]);
System.out.println("Commands Available (" + commands.size() + "): "); System.out.println("Commands Available (" + commands.size() + "): ");
for (ConsoleCommand c : commands.values()) for (ConsoleCommand c : commands.values()) {
{
System.out.println(c.key + " - " + c.usage); System.out.println(c.key + " - " + c.usage);
} }
} }
@ -82,4 +62,6 @@ public abstract class ConsoleCommand
return false; return false;
} }
public abstract void handle(String[] args) throws Exception;
} }

View File

@ -5,16 +5,13 @@ import com.eu.habbo.habbohotel.catalog.CatalogManager;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
public class ConsoleInfoCommand extends ConsoleCommand public class ConsoleInfoCommand extends ConsoleCommand {
{ public ConsoleInfoCommand() {
public ConsoleInfoCommand()
{
super("info", "Show current statistics."); super("info", "Show current statistics.");
} }
@Override @Override
public void handle(String[] args) throws Exception public void handle(String[] args) throws Exception {
{
int seconds = Emulator.getIntUnixTimestamp() - Emulator.getTimeStarted(); int seconds = Emulator.getIntUnixTimestamp() - Emulator.getTimeStarted();
int day = (int) TimeUnit.SECONDS.toDays(seconds); int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - (day * 24); long hours = TimeUnit.SECONDS.toHours(seconds) - (day * 24);

View File

@ -2,16 +2,13 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.networking.camera.CameraClient; import com.eu.habbo.networking.camera.CameraClient;
public class ConsoleReconnectCameraCommand extends ConsoleCommand public class ConsoleReconnectCameraCommand extends ConsoleCommand {
{ public ConsoleReconnectCameraCommand() {
public ConsoleReconnectCameraCommand()
{
super("camera", "Attempt to reconnect to the camera server."); super("camera", "Attempt to reconnect to the camera server.");
} }
@Override @Override
public void handle(String[] args) throws Exception public void handle(String[] args) throws Exception {
{
System.out.println("Connecting to the camera..."); System.out.println("Connecting to the camera...");
CameraClient.attemptReconnect = true; CameraClient.attemptReconnect = true;
} }

View File

@ -2,16 +2,13 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.habbohotel.commands.ShutdownCommand; import com.eu.habbo.habbohotel.commands.ShutdownCommand;
public class ConsoleShutdownCommand extends ConsoleCommand public class ConsoleShutdownCommand extends ConsoleCommand {
{ public ConsoleShutdownCommand() {
public ConsoleShutdownCommand()
{
super("stop", "Stop the emulator."); super("stop", "Stop the emulator.");
} }
@Override @Override
public void handle(String[] args) throws Exception public void handle(String[] args) throws Exception {
{
new ShutdownCommand().handle(null, args); new ShutdownCommand().handle(null, args);
} }
} }

View File

@ -4,23 +4,17 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
public class ConsoleTestCommand extends ConsoleCommand public class ConsoleTestCommand extends ConsoleCommand {
{ public ConsoleTestCommand() {
public ConsoleTestCommand()
{
super("test", "This is just a test."); super("test", "This is just a test.");
} }
@Override @Override
public void handle(String[] args) throws Exception public void handle(String[] args) throws Exception {
{ if (Emulator.debugging) {
if (Emulator.debugging)
{
System.out.println("This is a test command for live debugging."); System.out.println("This is a test command for live debugging.");
//AchievementManager.progressAchievement(4, Emulator.getGameEnvironment().getAchievementManager().getAchievement("AllTimeHotelPresence"), 30); //AchievementManager.progressAchievement(4, Emulator.getGameEnvironment().getAchievementManager().getAchievement("AllTimeHotelPresence"), 30);
Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(1); Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(1);
habbo.getHabboInfo().getMachineID(); habbo.getHabboInfo().getMachineID();

View File

@ -2,18 +2,14 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
public class ShowInteractionsCommand extends ConsoleCommand public class ShowInteractionsCommand extends ConsoleCommand {
{ public ShowInteractionsCommand() {
public ShowInteractionsCommand()
{
super("interactions", "Show a list of available furniture interactions."); super("interactions", "Show a list of available furniture interactions.");
} }
@Override @Override
public void handle(String[] args) throws Exception public void handle(String[] args) throws Exception {
{ for (String interaction : Emulator.getGameEnvironment().getItemManager().getInteractionList()) {
for (String interaction : Emulator.getGameEnvironment().getItemManager().getInteractionList())
{
System.out.println(interaction); System.out.println(interaction);
} }
} }

View File

@ -2,18 +2,14 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
public class ShowRCONCommands extends ConsoleCommand public class ShowRCONCommands extends ConsoleCommand {
{ public ShowRCONCommands() {
public ShowRCONCommands()
{
super("rconcommands", "Show a list of all RCON commands"); super("rconcommands", "Show a list of all RCON commands");
} }
@Override @Override
public void handle(String[] args) throws Exception public void handle(String[] args) throws Exception {
{ for (String command : Emulator.getRconServer().getCommands()) {
for (String command : Emulator.getRconServer().getCommands())
{
System.out.println(command); System.out.println(command);
} }
} }

View File

@ -4,41 +4,33 @@ import com.eu.habbo.Emulator;
import com.eu.habbo.core.ConfigurationManager; import com.eu.habbo.core.ConfigurationManager;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
public class Database public class Database {
{
private HikariDataSource dataSource; private HikariDataSource dataSource;
private DatabasePool databasePool; private DatabasePool databasePool;
public Database(ConfigurationManager config) public Database(ConfigurationManager config) {
{
long millis = System.currentTimeMillis(); long millis = System.currentTimeMillis();
boolean SQLException = false; boolean SQLException = false;
try try {
{
this.databasePool = new DatabasePool(); this.databasePool = new DatabasePool();
if (!this.databasePool.getStoragePooling(config)) if (!this.databasePool.getStoragePooling(config)) {
{
Emulator.getLogging().logStart("Failed to connect to the database. Please check config.ini and make sure the MySQL process is running. Shutting down..."); Emulator.getLogging().logStart("Failed to connect to the database. Please check config.ini and make sure the MySQL process is running. Shutting down...");
SQLException = true; SQLException = true;
return; return;
} }
this.dataSource = this.databasePool.getDatabase(); this.dataSource = this.databasePool.getDatabase();
} } catch (Exception e) {
catch (Exception e)
{
SQLException = true; SQLException = true;
e.printStackTrace(); e.printStackTrace();
Emulator.getLogging().logStart("Failed to connect to your database."); Emulator.getLogging().logStart("Failed to connect to your database.");
Emulator.getLogging().logStart(e.getMessage()); Emulator.getLogging().logStart(e.getMessage());
} } finally {
finally
{
if (SQLException) if (SQLException)
Emulator.prepareShutdown(); Emulator.prepareShutdown();
} }
@ -47,23 +39,19 @@ public class Database
} }
public void dispose() public void dispose() {
{ if (this.databasePool != null) {
if (this.databasePool != null)
{
this.databasePool.getDatabase().close(); this.databasePool.getDatabase().close();
} }
this.dataSource.close(); this.dataSource.close();
} }
public HikariDataSource getDataSource() public HikariDataSource getDataSource() {
{
return this.dataSource; return this.dataSource;
} }
public DatabasePool getDatabasePool() public DatabasePool getDatabasePool() {
{
return this.databasePool; return this.databasePool;
} }
} }

View File

@ -1,21 +1,17 @@
package com.eu.habbo.database; package com.eu.habbo.database;
import com.eu.habbo.core.ConfigurationManager; import com.eu.habbo.core.ConfigurationManager;
import com.eu.habbo.core.Logging;
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
class DatabasePool class DatabasePool {
{
private final Logger log = LoggerFactory.getLogger(DatabasePool.class); private final Logger log = LoggerFactory.getLogger(DatabasePool.class);
private HikariDataSource database; private HikariDataSource database;
public boolean getStoragePooling(ConfigurationManager config) public boolean getStoragePooling(ConfigurationManager config) {
{ try {
try
{
HikariConfig databaseConfiguration = new HikariConfig(); HikariConfig databaseConfiguration = new HikariConfig();
databaseConfiguration.setMaximumPoolSize(config.getInt("db.pool.maxsize", 50)); databaseConfiguration.setMaximumPoolSize(config.getInt("db.pool.maxsize", 50));
databaseConfiguration.setMinimumIdle(config.getInt("db.pool.minsize", 10)); databaseConfiguration.setMinimumIdle(config.getInt("db.pool.minsize", 10));
@ -43,16 +39,13 @@ class DatabasePool
databaseConfiguration.setIdleTimeout(600000L); databaseConfiguration.setIdleTimeout(600000L);
//databaseConfiguration.setDriverClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"); //databaseConfiguration.setDriverClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
this.database = new HikariDataSource(databaseConfiguration); this.database = new HikariDataSource(databaseConfiguration);
} } catch (Exception e) {
catch (Exception e)
{
return false; return false;
} }
return true; return true;
} }
public HikariDataSource getDatabase() public HikariDataSource getDatabase() {
{
return this.database; return this.database;
} }
} }

View File

@ -22,8 +22,10 @@ import com.eu.habbo.habbohotel.polls.PollManager;
import com.eu.habbo.habbohotel.rooms.RoomManager; import com.eu.habbo.habbohotel.rooms.RoomManager;
import com.eu.habbo.habbohotel.users.HabboManager; import com.eu.habbo.habbohotel.users.HabboManager;
public class GameEnvironment public class GameEnvironment {
{ public CreditsScheduler creditsScheduler;
public PixelScheduler pixelScheduler;
public PointsScheduler pointsScheduler;
private HabboManager habboManager; private HabboManager habboManager;
private NavigatorManager navigatorManager; private NavigatorManager navigatorManager;
private GuildManager guildManager; private GuildManager guildManager;
@ -42,12 +44,7 @@ public class GameEnvironment
private CraftingManager craftingManager; private CraftingManager craftingManager;
private PollManager pollManager; private PollManager pollManager;
public CreditsScheduler creditsScheduler; public void load() throws Exception {
public PixelScheduler pixelScheduler;
public PointsScheduler pointsScheduler;
public void load() throws Exception
{
Emulator.getLogging().logStart("GameEnvironment -> Loading..."); Emulator.getLogging().logStart("GameEnvironment -> Loading...");
this.permissionsManager = new PermissionsManager(); this.permissionsManager = new PermissionsManager();
@ -83,8 +80,7 @@ public class GameEnvironment
Emulator.getLogging().logStart("GameEnvironment -> Loaded!"); Emulator.getLogging().logStart("GameEnvironment -> Loaded!");
} }
public void dispose() public void dispose() {
{
this.pointsScheduler.setDisposed(true); this.pointsScheduler.setDisposed(true);
this.pixelScheduler.setDisposed(true); this.pixelScheduler.setDisposed(true);
this.creditsScheduler.setDisposed(true); this.creditsScheduler.setDisposed(true);
@ -99,88 +95,71 @@ public class GameEnvironment
Emulator.getLogging().logShutdownLine("GameEnvironment -> Disposed!"); Emulator.getLogging().logShutdownLine("GameEnvironment -> Disposed!");
} }
public HabboManager getHabboManager() public HabboManager getHabboManager() {
{
return this.habboManager; return this.habboManager;
} }
public NavigatorManager getNavigatorManager() public NavigatorManager getNavigatorManager() {
{
return this.navigatorManager; return this.navigatorManager;
} }
public GuildManager getGuildManager() public GuildManager getGuildManager() {
{
return this.guildManager; return this.guildManager;
} }
public ItemManager getItemManager() public ItemManager getItemManager() {
{
return this.itemManager; return this.itemManager;
} }
public CatalogManager getCatalogManager() public CatalogManager getCatalogManager() {
{
return this.catalogManager; return this.catalogManager;
} }
public HotelViewManager getHotelViewManager() public HotelViewManager getHotelViewManager() {
{
return this.hotelViewManager; return this.hotelViewManager;
} }
public RoomManager getRoomManager() public RoomManager getRoomManager() {
{
return this.roomManager; return this.roomManager;
} }
public CommandHandler getCommandHandler() public CommandHandler getCommandHandler() {
{
return this.commandHandler; return this.commandHandler;
} }
public PermissionsManager getPermissionsManager() public PermissionsManager getPermissionsManager() {
{
return this.permissionsManager; return this.permissionsManager;
} }
public BotManager getBotManager() public BotManager getBotManager() {
{
return this.botManager; return this.botManager;
} }
public ModToolManager getModToolManager() public ModToolManager getModToolManager() {
{
return this.modToolManager; return this.modToolManager;
} }
public PetManager getPetManager() public PetManager getPetManager() {
{
return this.petManager; return this.petManager;
} }
public AchievementManager getAchievementManager() public AchievementManager getAchievementManager() {
{
return this.achievementManager; return this.achievementManager;
} }
public GuideManager getGuideManager() public GuideManager getGuideManager() {
{
return this.guideManager; return this.guideManager;
} }
public WordFilter getWordFilter() public WordFilter getWordFilter() {
{
return this.wordFilter; return this.wordFilter;
} }
public CraftingManager getCraftingManager() public CraftingManager getCraftingManager() {
{
return this.craftingManager; return this.craftingManager;
} }
public PollManager getPollManager() public PollManager getPollManager() {
{
return this.pollManager; return this.pollManager;
} }

View File

@ -5,8 +5,7 @@ import gnu.trove.map.hash.THashMap;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class Achievement public class Achievement {
{
public final int id; public final int id;
@ -20,8 +19,7 @@ public class Achievement
public final THashMap<Integer, AchievementLevel> levels; public final THashMap<Integer, AchievementLevel> levels;
public Achievement(ResultSet set) throws SQLException public Achievement(ResultSet set) throws SQLException {
{
this.levels = new THashMap<>(); this.levels = new THashMap<>();
this.id = set.getInt("id"); this.id = set.getInt("id");
@ -32,28 +30,20 @@ public class Achievement
} }
public void addLevel(AchievementLevel level) public void addLevel(AchievementLevel level) {
{ synchronized (this.levels) {
synchronized (this.levels)
{
this.levels.put(level.level, level); this.levels.put(level.level, level);
} }
} }
public AchievementLevel getLevelForProgress(int progress) public AchievementLevel getLevelForProgress(int progress) {
{
AchievementLevel l = null; AchievementLevel l = null;
if (progress > 0) if (progress > 0) {
{ for (AchievementLevel level : this.levels.values()) {
for (AchievementLevel level : this.levels.values()) if (progress >= level.progress) {
{ if (l != null) {
if (progress >= level.progress) if (l.level > level.level) {
{
if (l != null)
{
if (l.level > level.level)
{
continue; continue;
} }
} }
@ -66,12 +56,10 @@ public class Achievement
} }
public AchievementLevel getNextLevel(int currentLevel) public AchievementLevel getNextLevel(int currentLevel) {
{
AchievementLevel l = null; AchievementLevel l = null;
for(AchievementLevel level : this.levels.values()) for (AchievementLevel level : this.levels.values()) {
{
if (level.level == (currentLevel + 1)) if (level.level == (currentLevel + 1))
return level; return level;
} }
@ -79,13 +67,11 @@ public class Achievement
return null; return null;
} }
public AchievementLevel firstLevel() public AchievementLevel firstLevel() {
{
return this.levels.get(1); return this.levels.get(1);
} }
public void clearLevels() public void clearLevels() {
{
this.levels.clear(); this.levels.clear();
} }
} }

View File

@ -1,7 +1,6 @@
package com.eu.habbo.habbohotel.achievements; package com.eu.habbo.habbohotel.achievements;
public enum AchievementCategories public enum AchievementCategories {
{
IDENTITY, IDENTITY,

View File

@ -3,8 +3,7 @@ package com.eu.habbo.habbohotel.achievements;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class AchievementLevel public class AchievementLevel {
{
public final int level; public final int level;
@ -20,8 +19,7 @@ public class AchievementLevel
public final int progress; public final int progress;
public AchievementLevel(ResultSet set) throws SQLException public AchievementLevel(ResultSet set) throws SQLException {
{
this.level = set.getInt("level"); this.level = set.getInt("level");
this.rewardAmount = set.getInt("reward_amount"); this.rewardAmount = set.getInt("reward_amount");
this.rewardType = set.getInt("reward_type"); this.rewardType = set.getInt("reward_type");

View File

@ -23,8 +23,7 @@ import java.sql.*;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
public class AchievementManager public class AchievementManager {
{
public static boolean TALENTTRACK_ENABLED = false; public static boolean TALENTTRACK_ENABLED = false;
@ -33,154 +32,43 @@ public class AchievementManager
private final THashMap<TalentTrackType, LinkedHashMap<Integer, TalentTrackLevel>> talentTrackLevels; private final THashMap<TalentTrackType, LinkedHashMap<Integer, TalentTrackLevel>> talentTrackLevels;
public AchievementManager() public AchievementManager() {
{
this.achievements = new THashMap<>(); this.achievements = new THashMap<>();
this.talentTrackLevels = new THashMap<>(); this.talentTrackLevels = new THashMap<>();
} }
public static void progressAchievement(int habboId, Achievement achievement) {
public void reload()
{
long millis = System.currentTimeMillis();
synchronized (this.achievements)
{
for (Achievement achievement : this.achievements.values())
{
achievement.clearLevels();
}
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection())
{
try (Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM achievements"))
{
while (set.next())
{
if (!this.achievements.containsKey(set.getString("name")))
{
this.achievements.put(set.getString("name"), new Achievement(set));
}
else
{
this.achievements.get(set.getString("name")).addLevel(new AchievementLevel(set));
}
}
}
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e);
}
catch (Exception e)
{
Emulator.getLogging().logErrorLine(e);
}
synchronized (this.talentTrackLevels)
{
this.talentTrackLevels.clear();
try (Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM achievements_talents ORDER BY level ASC"))
{
while (set.next())
{
TalentTrackLevel level = new TalentTrackLevel(set);
if (!this.talentTrackLevels.containsKey(level.type))
{
this.talentTrackLevels.put(level.type, new LinkedHashMap<>());
}
this.talentTrackLevels.get(level.type).put(level.level, level);
}
}
}
}
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e);
Emulator.getLogging().logErrorLine("Achievement Manager -> Failed to load!");
return;
}
}
Emulator.getLogging().logStart("Achievement Manager -> Loaded! ("+(System.currentTimeMillis() - millis)+" MS)");
}
public Achievement getAchievement(String name)
{
return this.achievements.get(name);
}
public Achievement getAchievement(int id)
{
synchronized (this.achievements)
{
for (Map.Entry<String, Achievement> set : this.achievements.entrySet())
{
if (set.getValue().id == id)
{
return set.getValue();
}
}
}
return null;
}
public THashMap<String, Achievement> getAchievements()
{
return this.achievements;
}
public static void progressAchievement(int habboId, Achievement achievement)
{
progressAchievement(habboId, achievement, 1); progressAchievement(habboId, achievement, 1);
} }
public static void progressAchievement(int habboId, Achievement achievement, int amount) public static void progressAchievement(int habboId, Achievement achievement, int amount) {
{ if (achievement != null) {
if (achievement != null)
{
Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(habboId); Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(habboId);
if (habbo != null) if (habbo != null) {
{
progressAchievement(habbo, achievement, amount); progressAchievement(habbo, achievement, amount);
} } else {
else
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); try (Connection connection = Emulator.getDatabase().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("" + PreparedStatement statement = connection.prepareStatement("" +
"INSERT INTO users_achievements_queue (user_id, achievement_id, amount) VALUES (?, ?, ?) " + "INSERT INTO users_achievements_queue (user_id, achievement_id, amount) VALUES (?, ?, ?) " +
"ON DUPLICATE KEY UPDATE amount = amount + ?")) "ON DUPLICATE KEY UPDATE amount = amount + ?")) {
{
statement.setInt(1, habboId); statement.setInt(1, habboId);
statement.setInt(2, achievement.id); statement.setInt(2, achievement.id);
statement.setInt(3, amount); statement.setInt(3, amount);
statement.setInt(4, amount); statement.setInt(4, amount);
statement.execute(); statement.execute();
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
} }
} }
public static void progressAchievement(Habbo habbo, Achievement achievement) {
public static void progressAchievement(Habbo habbo, Achievement achievement)
{
progressAchievement(habbo, achievement, 1); progressAchievement(habbo, achievement, 1);
} }
public static void progressAchievement(Habbo habbo, Achievement achievement, int amount) {
public static void progressAchievement(Habbo habbo, Achievement achievement, int amount)
{
if (achievement == null) if (achievement == null)
return; return;
@ -192,15 +80,13 @@ public class AchievementManager
int currentProgress = habbo.getHabboStats().getAchievementProgress(achievement); int currentProgress = habbo.getHabboStats().getAchievementProgress(achievement);
if(currentProgress == -1) if (currentProgress == -1) {
{
currentProgress = 0; currentProgress = 0;
createUserEntry(habbo, achievement); createUserEntry(habbo, achievement);
habbo.getHabboStats().setProgress(achievement, 0); habbo.getHabboStats().setProgress(achievement, 0);
} }
if(Emulator.getPluginManager().isRegistered(UserAchievementProgressEvent.class, true)) if (Emulator.getPluginManager().isRegistered(UserAchievementProgressEvent.class, true)) {
{
Event userAchievementProgressedEvent = new UserAchievementProgressEvent(habbo, achievement, amount); Event userAchievementProgressedEvent = new UserAchievementProgressEvent(habbo, achievement, amount);
Emulator.getPluginManager().fireEvent(userAchievementProgressedEvent); Emulator.getPluginManager().fireEvent(userAchievementProgressedEvent);
@ -217,16 +103,11 @@ public class AchievementManager
AchievementLevel newLevel = achievement.getLevelForProgress(currentProgress + amount); AchievementLevel newLevel = achievement.getLevelForProgress(currentProgress + amount);
if (AchievementManager.TALENTTRACK_ENABLED) if (AchievementManager.TALENTTRACK_ENABLED) {
{ for (TalentTrackType type : TalentTrackType.values()) {
for (TalentTrackType type : TalentTrackType.values()) if (Emulator.getGameEnvironment().getAchievementManager().talentTrackLevels.containsKey(type)) {
{ for (Map.Entry<Integer, TalentTrackLevel> entry : Emulator.getGameEnvironment().getAchievementManager().talentTrackLevels.get(type).entrySet()) {
if (Emulator.getGameEnvironment().getAchievementManager().talentTrackLevels.containsKey(type)) if (entry.getValue().achievements.containsKey(achievement)) {
{
for (Map.Entry<Integer, TalentTrackLevel> entry : Emulator.getGameEnvironment().getAchievementManager().talentTrackLevels.get(type).entrySet())
{
if (entry.getValue().achievements.containsKey(achievement))
{
Emulator.getGameEnvironment().getAchievementManager().handleTalentTrackAchievement(habbo, type, achievement); Emulator.getGameEnvironment().getAchievementManager().handleTalentTrackAchievement(habbo, type, achievement);
break; break;
} }
@ -236,14 +117,10 @@ public class AchievementManager
} }
if (newLevel == null || if (newLevel == null ||
(oldLevel != null &&(oldLevel.level == newLevel.level && newLevel.level < achievement.levels.size()))) (oldLevel != null && (oldLevel.level == newLevel.level && newLevel.level < achievement.levels.size()))) {
{
habbo.getClient().sendResponse(new AchievementProgressComposer(habbo, achievement)); habbo.getClient().sendResponse(new AchievementProgressComposer(habbo, achievement));
} } else {
else if (Emulator.getPluginManager().isRegistered(UserAchievementLeveledEvent.class, true)) {
{
if(Emulator.getPluginManager().isRegistered(UserAchievementLeveledEvent.class, true))
{
Event userAchievementLeveledEvent = new UserAchievementLeveledEvent(habbo, achievement, oldLevel, newLevel); Event userAchievementLeveledEvent = new UserAchievementLeveledEvent(habbo, achievement, oldLevel, newLevel);
Emulator.getPluginManager().fireEvent(userAchievementLeveledEvent); Emulator.getPluginManager().fireEvent(userAchievementLeveledEvent);
@ -259,25 +136,20 @@ public class AchievementManager
//the badge would result in an nullpointer exception. This is normal behaviour. //the badge would result in an nullpointer exception. This is normal behaviour.
HabboBadge badge = null; HabboBadge badge = null;
if (oldLevel != null) if (oldLevel != null) {
{ try {
try
{
badge = habbo.getInventory().getBadgesComponent().getBadge(("ACH_" + achievement.name + oldLevel.level).toLowerCase()); badge = habbo.getInventory().getBadgesComponent().getBadge(("ACH_" + achievement.name + oldLevel.level).toLowerCase());
} catch (Exception e) } catch (Exception e) {
{
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
return; return;
} }
} }
if (badge != null) if (badge != null) {
{
badge.setCode("ACH_" + achievement.name + newLevel.level); badge.setCode("ACH_" + achievement.name + newLevel.level);
badge.needsInsert(false); badge.needsInsert(false);
badge.needsUpdate(true); badge.needsUpdate(true);
} else } else {
{
badge = new HabboBadge(0, "ACH_" + achievement.name + newLevel.level, 0, habbo); badge = new HabboBadge(0, "ACH_" + achievement.name + newLevel.level, 0, habbo);
habbo.getClient().sendResponse(new AddUserBadgeComposer(badge)); habbo.getClient().sendResponse(new AddUserBadgeComposer(badge));
badge.needsInsert(true); badge.needsInsert(true);
@ -287,10 +159,8 @@ public class AchievementManager
Emulator.getThreading().run(badge); Emulator.getThreading().run(badge);
if(badge.getSlot() > 0) if (badge.getSlot() > 0) {
{ if (habbo.getHabboInfo().getCurrentRoom() != null) {
if(habbo.getHabboInfo().getCurrentRoom() != null)
{
habbo.getHabboInfo().getCurrentRoom().sendComposer(new UserBadgesComposer(habbo.getInventory().getBadgesComponent().getWearingBadges(), habbo.getHabboInfo().getId()).compose()); habbo.getHabboInfo().getCurrentRoom().sendComposer(new UserBadgesComposer(habbo.getInventory().getBadgesComponent().getWearingBadges(), habbo.getHabboInfo().getId()).compose());
} }
} }
@ -299,25 +169,20 @@ public class AchievementManager
habbo.getHabboStats().addAchievementScore(newLevel.points); habbo.getHabboStats().addAchievementScore(newLevel.points);
if (newLevel.rewardAmount > 0) if (newLevel.rewardAmount > 0) {
{
habbo.givePoints(newLevel.rewardType, newLevel.rewardAmount); habbo.givePoints(newLevel.rewardType, newLevel.rewardAmount);
} }
if (habbo.getHabboInfo().getCurrentRoom() != null) if (habbo.getHabboInfo().getCurrentRoom() != null) {
{
habbo.getHabboInfo().getCurrentRoom().sendComposer(new RoomUserDataComposer(habbo).compose()); habbo.getHabboInfo().getCurrentRoom().sendComposer(new RoomUserDataComposer(habbo).compose());
} }
} }
} }
public static boolean hasAchieved(Habbo habbo, Achievement achievement) {
public static boolean hasAchieved(Habbo habbo, Achievement achievement)
{
int currentProgress = habbo.getHabboStats().getAchievementProgress(achievement); int currentProgress = habbo.getHabboStats().getAchievementProgress(achievement);
if(currentProgress == -1) if (currentProgress == -1) {
{
return false; return false;
} }
@ -331,83 +196,128 @@ public class AchievementManager
return nextLevel == null && currentProgress >= level.progress; return nextLevel == null && currentProgress >= level.progress;
} }
public static void createUserEntry(Habbo habbo, Achievement achievement) {
public static void createUserEntry(Habbo habbo, Achievement achievement) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO users_achievements (user_id, achievement_name, progress) VALUES (?, ?, ?)")) {
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO users_achievements (user_id, achievement_name, progress) VALUES (?, ?, ?)"))
{
statement.setInt(1, habbo.getHabboInfo().getId()); statement.setInt(1, habbo.getHabboInfo().getId());
statement.setString(2, achievement.name); statement.setString(2, achievement.name);
statement.setInt(3, 1); statement.setInt(3, 1);
statement.execute(); statement.execute();
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
public static void saveAchievements(Habbo habbo) {
public static void saveAchievements(Habbo habbo) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE users_achievements SET progress = ? WHERE achievement_name = ? AND user_id = ? LIMIT 1")) {
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE users_achievements SET progress = ? WHERE achievement_name = ? AND user_id = ? LIMIT 1"))
{
statement.setInt(3, habbo.getHabboInfo().getId()); statement.setInt(3, habbo.getHabboInfo().getId());
for(Map.Entry<Achievement, Integer> map : habbo.getHabboStats().getAchievementProgress().entrySet()) for (Map.Entry<Achievement, Integer> map : habbo.getHabboStats().getAchievementProgress().entrySet()) {
{
statement.setInt(1, map.getValue()); statement.setInt(1, map.getValue());
statement.setString(2, map.getKey().name); statement.setString(2, map.getKey().name);
statement.addBatch(); statement.addBatch();
} }
statement.executeBatch(); statement.executeBatch();
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
public static int getAchievementProgressForHabbo(int userId, Achievement achievement) public static int getAchievementProgressForHabbo(int userId, Achievement achievement) {
{ try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT progress FROM users_achievements WHERE user_id = ? AND achievement_name = ? LIMIT 1")) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT progress FROM users_achievements WHERE user_id = ? AND achievement_name = ? LIMIT 1"))
{
statement.setInt(1, userId); statement.setInt(1, userId);
statement.setString(2, achievement.name); statement.setString(2, achievement.name);
try (ResultSet set = statement.executeQuery()) try (ResultSet set = statement.executeQuery()) {
{ if (set.next()) {
if (set.next())
{
return set.getInt("progress"); return set.getInt("progress");
} }
} }
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
return 0; return 0;
} }
public LinkedHashMap<Integer, TalentTrackLevel> getTalenTrackLevels(TalentTrackType type) public void reload() {
{ long millis = System.currentTimeMillis();
synchronized (this.achievements) {
for (Achievement achievement : this.achievements.values()) {
achievement.clearLevels();
}
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
try (Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM achievements")) {
while (set.next()) {
if (!this.achievements.containsKey(set.getString("name"))) {
this.achievements.put(set.getString("name"), new Achievement(set));
} else {
this.achievements.get(set.getString("name")).addLevel(new AchievementLevel(set));
}
}
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
}
synchronized (this.talentTrackLevels) {
this.talentTrackLevels.clear();
try (Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM achievements_talents ORDER BY level ASC")) {
while (set.next()) {
TalentTrackLevel level = new TalentTrackLevel(set);
if (!this.talentTrackLevels.containsKey(level.type)) {
this.talentTrackLevels.put(level.type, new LinkedHashMap<>());
}
this.talentTrackLevels.get(level.type).put(level.level, level);
}
}
}
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
Emulator.getLogging().logErrorLine("Achievement Manager -> Failed to load!");
return;
}
}
Emulator.getLogging().logStart("Achievement Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
}
public Achievement getAchievement(String name) {
return this.achievements.get(name);
}
public Achievement getAchievement(int id) {
synchronized (this.achievements) {
for (Map.Entry<String, Achievement> set : this.achievements.entrySet()) {
if (set.getValue().id == id) {
return set.getValue();
}
}
}
return null;
}
public THashMap<String, Achievement> getAchievements() {
return this.achievements;
}
public LinkedHashMap<Integer, TalentTrackLevel> getTalenTrackLevels(TalentTrackType type) {
return this.talentTrackLevels.get(type); return this.talentTrackLevels.get(type);
} }
public TalentTrackLevel calculateTalenTrackLevel(Habbo habbo, TalentTrackType type) public TalentTrackLevel calculateTalenTrackLevel(Habbo habbo, TalentTrackType type) {
{
TalentTrackLevel level = null; TalentTrackLevel level = null;
for (Map.Entry<Integer, TalentTrackLevel> entry : this.talentTrackLevels.get(type).entrySet()) for (Map.Entry<Integer, TalentTrackLevel> entry : this.talentTrackLevels.get(type).entrySet()) {
{
final boolean[] allCompleted = {true}; final boolean[] allCompleted = {true};
entry.getValue().achievements.forEachEntry(new TObjectIntProcedure<Achievement>() entry.getValue().achievements.forEachEntry(new TObjectIntProcedure<Achievement>() {
{
@Override @Override
public boolean execute(Achievement a, int b) public boolean execute(Achievement a, int b) {
{ if (habbo.getHabboStats().getAchievementProgress(a) < b) {
if (habbo.getHabboStats().getAchievementProgress(a) < b)
{
allCompleted[0] = false; allCompleted[0] = false;
} }
@ -415,15 +325,11 @@ public class AchievementManager
} }
}); });
if (allCompleted[0]) if (allCompleted[0]) {
{ if (level == null || level.level < entry.getValue().level) {
if (level == null || level.level < entry.getValue().level)
{
level = entry.getValue(); level = entry.getValue();
} }
} } else {
else
{
break; break;
} }
} }
@ -431,24 +337,17 @@ public class AchievementManager
return level; return level;
} }
public void handleTalentTrackAchievement(Habbo habbo, TalentTrackType type, Achievement achievement) public void handleTalentTrackAchievement(Habbo habbo, TalentTrackType type, Achievement achievement) {
{
TalentTrackLevel currentLevel = this.calculateTalenTrackLevel(habbo, type); TalentTrackLevel currentLevel = this.calculateTalenTrackLevel(habbo, type);
if (currentLevel != null) if (currentLevel != null) {
{ if (currentLevel.level > habbo.getHabboStats().talentTrackLevel(type)) {
if (currentLevel.level > habbo.getHabboStats().talentTrackLevel(type)) for (int i = habbo.getHabboStats().talentTrackLevel(type); i <= currentLevel.level; i++) {
{
for (int i = habbo.getHabboStats().talentTrackLevel(type); i <= currentLevel.level; i++)
{
TalentTrackLevel level = this.getTalentTrackLevel(type, i); TalentTrackLevel level = this.getTalentTrackLevel(type, i);
if (level != null) if (level != null) {
{ if (level.items != null && !level.items.isEmpty()) {
if (level.items != null && !level.items.isEmpty()) for (Item item : level.items) {
{
for (Item item : level.items)
{
HabboItem rewardItem = Emulator.getGameEnvironment().getItemManager().createItem(habbo.getHabboInfo().getId(), item, 0, 0, ""); HabboItem rewardItem = Emulator.getGameEnvironment().getItemManager().createItem(habbo.getHabboInfo().getId(), item, 0, 0, "");
habbo.getInventory().getItemsComponent().addItem(rewardItem); habbo.getInventory().getItemsComponent().addItem(rewardItem);
habbo.getClient().sendResponse(new AddHabboItemComposer(rewardItem)); habbo.getClient().sendResponse(new AddHabboItemComposer(rewardItem));
@ -456,12 +355,9 @@ public class AchievementManager
} }
} }
if (level.badges != null && level.badges.length > 0 ) if (level.badges != null && level.badges.length > 0) {
{ for (String badge : level.badges) {
for (String badge : level.badges) if (!badge.isEmpty()) {
{
if (!badge.isEmpty())
{
HabboBadge b = new HabboBadge(0, badge, 0, habbo); HabboBadge b = new HabboBadge(0, badge, 0, habbo);
Emulator.getThreading().run(b); Emulator.getThreading().run(b);
habbo.getInventory().getBadgesComponent().addBadge(b); habbo.getInventory().getBadgesComponent().addBadge(b);
@ -470,12 +366,9 @@ public class AchievementManager
} }
} }
if (level.perks != null && level.perks.length > 0 ) if (level.perks != null && level.perks.length > 0) {
{ for (String perk : level.perks) {
for (String perk : level.perks) if (perk.equalsIgnoreCase("TRADE")) {
{
if (perk.equalsIgnoreCase("TRADE"))
{
habbo.getHabboStats().perkTrade = true; habbo.getHabboStats().perkTrade = true;
} }
} }
@ -489,8 +382,7 @@ public class AchievementManager
} }
} }
public TalentTrackLevel getTalentTrackLevel(TalentTrackType type, int level) public TalentTrackLevel getTalentTrackLevel(TalentTrackType type, int level) {
{
return this.talentTrackLevels.get(type).get(level); return this.talentTrackLevels.get(type).get(level);
} }
} }

View File

@ -9,8 +9,7 @@ import gnu.trove.set.hash.THashSet;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class TalentTrackLevel public class TalentTrackLevel {
{
public TalentTrackType type; public TalentTrackType type;
@ -29,8 +28,7 @@ public class TalentTrackLevel
public String[] badges; public String[] badges;
public TalentTrackLevel(ResultSet set) throws SQLException public TalentTrackLevel(ResultSet set) throws SQLException {
{
this.type = TalentTrackType.valueOf(set.getString("type").toUpperCase()); this.type = TalentTrackType.valueOf(set.getString("type").toUpperCase());
this.level = set.getInt("level"); this.level = set.getInt("level");
this.achievements = new TObjectIntHashMap<>(); this.achievements = new TObjectIntHashMap<>();
@ -38,47 +36,36 @@ public class TalentTrackLevel
String[] achievements = set.getString("achievement_ids").split(","); String[] achievements = set.getString("achievement_ids").split(",");
String[] achievementLevels = set.getString("achievement_levels").split(","); String[] achievementLevels = set.getString("achievement_levels").split(",");
if (achievementLevels.length == achievements.length) if (achievementLevels.length == achievements.length) {
{ for (int i = 0; i < achievements.length; i++) {
for (int i = 0; i < achievements.length; i++)
{
if (achievements[i].isEmpty() || achievementLevels[i].isEmpty()) if (achievements[i].isEmpty() || achievementLevels[i].isEmpty())
continue; continue;
Achievement achievement = Emulator.getGameEnvironment().getAchievementManager().getAchievement(Integer.valueOf(achievements[i])); Achievement achievement = Emulator.getGameEnvironment().getAchievementManager().getAchievement(Integer.valueOf(achievements[i]));
if (achievement != null) if (achievement != null) {
{
this.achievements.put(achievement, Integer.valueOf(achievementLevels[i])); this.achievements.put(achievement, Integer.valueOf(achievementLevels[i]));
} } else {
else
{
Emulator.getLogging().logErrorLine("Could not find achievement with ID " + achievements[i] + " for talenttrack level " + this.level + " of type " + this.type); Emulator.getLogging().logErrorLine("Could not find achievement with ID " + achievements[i] + " for talenttrack level " + this.level + " of type " + this.type);
} }
} }
} }
for (String s : set.getString("reward_furni").split(",")) for (String s : set.getString("reward_furni").split(",")) {
{
Item item = Emulator.getGameEnvironment().getItemManager().getItem(Integer.valueOf(s)); Item item = Emulator.getGameEnvironment().getItemManager().getItem(Integer.valueOf(s));
if (item != null) if (item != null) {
{
this.items.add(item); this.items.add(item);
} } else {
else
{
Emulator.getLogging().logStart("Incorrect reward furni (ID: " + s + ") for talent track level " + this.level); Emulator.getLogging().logStart("Incorrect reward furni (ID: " + s + ") for talent track level " + this.level);
} }
} }
if (!set.getString("reward_perks").isEmpty()) if (!set.getString("reward_perks").isEmpty()) {
{
this.perks = set.getString("reward_perks").split(","); this.perks = set.getString("reward_perks").split(",");
} }
if (!set.getString("reward_badges").isEmpty()) if (!set.getString("reward_badges").isEmpty()) {
{
this.badges = set.getString("reward_badges").split(","); this.badges = set.getString("reward_badges").split(",");
} }
} }

View File

@ -1,7 +1,6 @@
package com.eu.habbo.habbohotel.achievements; package com.eu.habbo.habbohotel.achievements;
public enum TalentTrackType public enum TalentTrackType {
{
CITIZENSHIP, CITIZENSHIP,

View File

@ -6,10 +6,7 @@ import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.habbohotel.users.HabboGender; import com.eu.habbo.habbohotel.users.HabboGender;
import com.eu.habbo.habbohotel.wired.WiredHandler; import com.eu.habbo.habbohotel.wired.WiredHandler;
import com.eu.habbo.habbohotel.wired.WiredTriggerType; import com.eu.habbo.habbohotel.wired.WiredTriggerType;
import com.eu.habbo.messages.outgoing.rooms.users.RoomUserShoutComposer; import com.eu.habbo.messages.outgoing.rooms.users.*;
import com.eu.habbo.messages.outgoing.rooms.users.RoomUserTalkComposer;
import com.eu.habbo.messages.outgoing.rooms.users.RoomUserWhisperComposer;
import com.eu.habbo.messages.outgoing.rooms.users.RoomUsersComposer;
import com.eu.habbo.plugin.events.bots.BotChatEvent; import com.eu.habbo.plugin.events.bots.BotChatEvent;
import com.eu.habbo.plugin.events.bots.BotShoutEvent; import com.eu.habbo.plugin.events.bots.BotShoutEvent;
import com.eu.habbo.plugin.events.bots.BotTalkEvent; import com.eu.habbo.plugin.events.bots.BotTalkEvent;
@ -23,55 +20,23 @@ import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
public class Bot implements Runnable public class Bot implements Runnable {
{
public static final String NO_CHAT_SET = "${bot.skill.chatter.configuration.text.placeholder}"; public static final String NO_CHAT_SET = "${bot.skill.chatter.configuration.text.placeholder}";
private transient int id;
private String name;
private String motto;
private String figure;
private HabboGender gender;
private int ownerId;
private String ownerName;
private Room room;
private RoomUnit roomUnit;
private boolean chatAuto;
private boolean chatRandom;
private short chatDelay;
private int chatTimeOut;
private int chatTimestamp;
private final ArrayList<String> chatLines; private final ArrayList<String> chatLines;
private transient int id;
private String name;
private String motto;
private String figure;
private HabboGender gender;
private int ownerId;
private String ownerName;
private Room room;
private RoomUnit roomUnit;
private boolean chatAuto;
private boolean chatRandom;
private short chatDelay;
private int chatTimeOut;
private int chatTimestamp;
private short lastChatIndex; private short lastChatIndex;
@ -88,8 +53,7 @@ public class Bot implements Runnable
private transient int followingHabboId; private transient int followingHabboId;
public Bot(int id, String name, String motto, String figure, HabboGender gender, int ownerId, String ownerName) public Bot(int id, String name, String motto, String figure, HabboGender gender, int ownerId, String ownerName) {
{
this.id = id; this.id = id;
this.name = name; this.name = name;
this.motto = motto; this.motto = motto;
@ -105,8 +69,7 @@ public class Bot implements Runnable
this.room = null; this.room = null;
} }
public Bot(ResultSet set) throws SQLException public Bot(ResultSet set) throws SQLException {
{
this.id = set.getInt("id"); this.id = set.getInt("id");
this.name = set.getString("name"); this.name = set.getString("name");
this.motto = set.getString("motto"); this.motto = set.getString("motto");
@ -127,8 +90,7 @@ public class Bot implements Runnable
this.needsUpdate = false; this.needsUpdate = false;
} }
public Bot(Bot bot) public Bot(Bot bot) {
{
this.name = bot.getName(); this.name = bot.getName();
this.motto = bot.getMotto(); this.motto = bot.getMotto();
this.figure = bot.getFigure(); this.figure = bot.getFigure();
@ -146,25 +108,26 @@ public class Bot implements Runnable
this.needsUpdate = false; this.needsUpdate = false;
} }
public static void initialise() {
public void needsUpdate(boolean needsUpdate) }
{
public static void dispose() {
}
public void needsUpdate(boolean needsUpdate) {
this.needsUpdate = needsUpdate; this.needsUpdate = needsUpdate;
} }
public boolean needsUpdate() {
public boolean needsUpdate()
{
return this.needsUpdate; return this.needsUpdate;
} }
@Override @Override
public void run() public void run() {
{ if (this.needsUpdate) {
if(this.needsUpdate) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE bots SET name = ?, motto = ?, figure = ?, gender = ?, user_id = ?, room_id = ?, x = ?, y = ?, z = ?, rot = ?, dance = ?, freeroam = ?, chat_lines = ?, chat_auto = ?, chat_random = ?, chat_delay = ?, effect = ? WHERE id = ?")) {
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE bots SET name = ?, motto = ?, figure = ?, gender = ?, user_id = ?, room_id = ?, x = ?, y = ?, z = ?, rot = ?, dance = ?, freeroam = ?, chat_lines = ?, chat_auto = ?, chat_random = ?, chat_delay = ?, effect = ? WHERE id = ?"))
{
statement.setString(1, this.name); statement.setString(1, this.name);
statement.setString(2, this.motto); statement.setString(2, this.motto);
statement.setString(3, this.figure); statement.setString(3, this.figure);
@ -178,8 +141,7 @@ public class Bot implements Runnable
statement.setInt(11, this.roomUnit == null ? 0 : this.roomUnit.getDanceType().getType()); statement.setInt(11, this.roomUnit == null ? 0 : this.roomUnit.getDanceType().getType());
statement.setString(12, this.canWalk ? "1" : "0"); statement.setString(12, this.canWalk ? "1" : "0");
StringBuilder text = new StringBuilder(); StringBuilder text = new StringBuilder();
for(String s : this.chatLines) for (String s : this.chatLines) {
{
text.append(s).append("\r"); text.append(s).append("\r");
} }
statement.setString(13, text.toString()); statement.setString(13, text.toString());
@ -190,46 +152,33 @@ public class Bot implements Runnable
statement.setInt(18, this.id); statement.setInt(18, this.id);
statement.execute(); statement.execute();
this.needsUpdate = false; this.needsUpdate = false;
} } catch (SQLException e) {
catch(SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
} }
public void cycle(boolean allowBotsWalk) {
public void cycle(boolean allowBotsWalk) if (this.roomUnit != null) {
{ if (allowBotsWalk && this.canWalk) {
if(this.roomUnit != null) if (!this.roomUnit.isWalking()) {
{ if (this.roomUnit.getWalkTimeOut() < Emulator.getIntUnixTimestamp() && this.followingHabboId == 0) {
if(allowBotsWalk && this.canWalk)
{
if (!this.roomUnit.isWalking())
{
if (this.roomUnit.getWalkTimeOut() < Emulator.getIntUnixTimestamp() && this.followingHabboId == 0)
{
this.roomUnit.setGoalLocation(this.room.getRandomWalkableTile()); this.roomUnit.setGoalLocation(this.room.getRandomWalkableTile());
int timeOut = Emulator.getRandom().nextInt(20) * 2; int timeOut = Emulator.getRandom().nextInt(20) * 2;
this.roomUnit.setWalkTimeOut((timeOut < 10 ? 5 : timeOut) + Emulator.getIntUnixTimestamp()); this.roomUnit.setWalkTimeOut((timeOut < 10 ? 5 : timeOut) + Emulator.getIntUnixTimestamp());
} }
} else } else {
{ for (RoomTile t : this.room.getLayout().getTilesAround(this.room.getLayout().getTile(this.getRoomUnit().getX(), this.getRoomUnit().getY()))) {
for (RoomTile t : this.room.getLayout().getTilesAround(this.room.getLayout().getTile(this.getRoomUnit().getX(), this.getRoomUnit().getY())))
{
WiredHandler.handle(WiredTriggerType.BOT_REACHED_STF, this.roomUnit, this.room, this.room.getItemsAt(t).toArray()); WiredHandler.handle(WiredTriggerType.BOT_REACHED_STF, this.roomUnit, this.room, this.room.getItemsAt(t).toArray());
} }
} }
} }
if(!this.chatLines.isEmpty() && this.chatTimeOut <= Emulator.getIntUnixTimestamp() && this.chatAuto) if (!this.chatLines.isEmpty() && this.chatTimeOut <= Emulator.getIntUnixTimestamp() && this.chatAuto) {
{ if (this.room != null) {
if(this.room != null)
{
this.lastChatIndex = (this.chatRandom ? (short) Emulator.getRandom().nextInt(this.chatLines.size()) : (this.lastChatIndex == (this.chatLines.size() - 1) ? 0 : this.lastChatIndex++)); this.lastChatIndex = (this.chatRandom ? (short) Emulator.getRandom().nextInt(this.chatLines.size()) : (this.lastChatIndex == (this.chatLines.size() - 1) ? 0 : this.lastChatIndex++));
if (this.lastChatIndex >= this.chatLines.size()) if (this.lastChatIndex >= this.chatLines.size()) {
{
this.lastChatIndex = 0; this.lastChatIndex = 0;
} }
@ -246,39 +195,38 @@ public class Bot implements Runnable
} }
} }
public void talk(String message) {
public void talk(String message) if (this.room != null) {
{
if(this.room != null)
{
BotChatEvent event = new BotTalkEvent(this, message); BotChatEvent event = new BotTalkEvent(this, message);
if (Emulator.getPluginManager().fireEvent(event).isCancelled()) if (Emulator.getPluginManager().fireEvent(event).isCancelled())
return; return;
this.chatTimestamp = Emulator.getIntUnixTimestamp(); this.chatTimestamp = Emulator.getIntUnixTimestamp();
this.room.botChat(new RoomUserTalkComposer(new RoomChatMessage(event.message, this.roomUnit, RoomChatMessageBubbles.BOT_RENTABLE)).compose()); this.room.botChat(new RoomUserTalkComposer(new RoomChatMessage(event.message, this.roomUnit, RoomChatMessageBubbles.BOT_RENTABLE)).compose());
if (message.equals("o/") || message.equals("_o/")) {
this.room.sendComposer(new RoomUserActionComposer(this.roomUnit, RoomUserAction.WAVE).compose());
}
} }
} }
public void shout(String message) {
public void shout(String message) if (this.room != null) {
{
if(this.room != null)
{
BotChatEvent event = new BotShoutEvent(this, message); BotChatEvent event = new BotShoutEvent(this, message);
if (Emulator.getPluginManager().fireEvent(event).isCancelled()) if (Emulator.getPluginManager().fireEvent(event).isCancelled())
return; return;
this.chatTimestamp = Emulator.getIntUnixTimestamp(); this.chatTimestamp = Emulator.getIntUnixTimestamp();
this.room.botChat(new RoomUserShoutComposer(new RoomChatMessage(event.message, this.roomUnit, RoomChatMessageBubbles.BOT_RENTABLE)).compose()); this.room.botChat(new RoomUserShoutComposer(new RoomChatMessage(event.message, this.roomUnit, RoomChatMessageBubbles.BOT_RENTABLE)).compose());
if (message.equals("o/") || message.equals("_o/")) {
this.room.sendComposer(new RoomUserActionComposer(this.roomUnit, RoomUserAction.WAVE).compose());
}
} }
} }
public void whisper(String message, Habbo habbo) {
public void whisper(String message, Habbo habbo) if (this.room != null && habbo != null) {
{
if(this.room != null && habbo != null)
{
BotWhisperEvent event = new BotWhisperEvent(this, message, habbo); BotWhisperEvent event = new BotWhisperEvent(this, message, habbo);
if (Emulator.getPluginManager().fireEvent(event).isCancelled()) if (Emulator.getPluginManager().fireEvent(event).isCancelled())
return; return;
@ -288,48 +236,33 @@ public class Bot implements Runnable
} }
} }
public void onPlace(Habbo habbo, Room room) {
public void onPlace(Habbo habbo, Room room) if (this.roomUnit != null) {
{
if (this.roomUnit != null)
{
room.giveEffect(this.roomUnit, this.effect, -1); room.giveEffect(this.roomUnit, this.effect, -1);
} }
} }
public void onPickUp(Habbo habbo, Room room) {
public void onPickUp(Habbo habbo, Room room)
{
} }
public void onUserSay(final RoomChatMessage message) {
public void onUserSay(final RoomChatMessage message)
{
} }
public int getId() {
public int getId()
{
return this.id; return this.id;
} }
public void setId(int id) {
public void setId(int id)
{
this.id = id; this.id = id;
} }
public String getName() {
public String getName()
{
return this.name; return this.name;
} }
public void setName(String name) {
public void setName(String name)
{
this.name = name; this.name = name;
this.needsUpdate = true; this.needsUpdate = true;
@ -337,28 +270,20 @@ public class Bot implements Runnable
//this.room.sendComposer(new ChangeNameUpdatedComposer(this.getRoomUnit(), this.getName()).compose()); //this.room.sendComposer(new ChangeNameUpdatedComposer(this.getRoomUnit(), this.getName()).compose());
} }
public String getMotto() {
public String getMotto()
{
return this.motto; return this.motto;
} }
public void setMotto(String motto) {
public void setMotto(String motto)
{
this.motto = motto; this.motto = motto;
this.needsUpdate = true; this.needsUpdate = true;
} }
public String getFigure() {
public String getFigure()
{
return this.figure; return this.figure;
} }
public void setFigure(String figure) {
public void setFigure(String figure)
{
this.figure = figure; this.figure = figure;
this.needsUpdate = true; this.needsUpdate = true;
@ -366,15 +291,11 @@ public class Bot implements Runnable
this.room.sendComposer(new RoomUsersComposer(this).compose()); this.room.sendComposer(new RoomUsersComposer(this).compose());
} }
public HabboGender getGender() {
public HabboGender getGender()
{
return this.gender; return this.gender;
} }
public void setGender(HabboGender gender) {
public void setGender(HabboGender gender)
{
this.gender = gender; this.gender = gender;
this.needsUpdate = true; this.needsUpdate = true;
@ -382,15 +303,11 @@ public class Bot implements Runnable
this.room.sendComposer(new RoomUsersComposer(this).compose()); this.room.sendComposer(new RoomUsersComposer(this).compose());
} }
public int getOwnerId() {
public int getOwnerId()
{
return this.ownerId; return this.ownerId;
} }
public void setOwnerId(int ownerId) {
public void setOwnerId(int ownerId)
{
this.ownerId = ownerId; this.ownerId = ownerId;
this.needsUpdate = true; this.needsUpdate = true;
@ -398,15 +315,11 @@ public class Bot implements Runnable
this.room.sendComposer(new RoomUsersComposer(this).compose()); this.room.sendComposer(new RoomUsersComposer(this).compose());
} }
public String getOwnerName() {
public String getOwnerName()
{
return this.ownerName; return this.ownerName;
} }
public void setOwnerName(String ownerName) {
public void setOwnerName(String ownerName)
{
this.ownerName = ownerName; this.ownerName = ownerName;
this.needsUpdate = true; this.needsUpdate = true;
@ -414,182 +327,121 @@ public class Bot implements Runnable
this.room.sendComposer(new RoomUsersComposer(this).compose()); this.room.sendComposer(new RoomUsersComposer(this).compose());
} }
public Room getRoom() {
public Room getRoom()
{
return this.room; return this.room;
} }
public void setRoom(Room room) {
public void setRoom(Room room)
{
this.room = room; this.room = room;
} }
public RoomUnit getRoomUnit() {
public RoomUnit getRoomUnit()
{
return this.roomUnit; return this.roomUnit;
} }
public void setRoomUnit(RoomUnit roomUnit) {
public void setRoomUnit(RoomUnit roomUnit)
{
this.roomUnit = roomUnit; this.roomUnit = roomUnit;
} }
public boolean isChatAuto() {
public boolean isChatAuto()
{
return this.chatAuto; return this.chatAuto;
} }
public void setChatAuto(boolean chatAuto) {
public void setChatAuto(boolean chatAuto)
{
this.chatAuto = chatAuto; this.chatAuto = chatAuto;
this.needsUpdate = true; this.needsUpdate = true;
} }
public boolean isChatRandom() {
public boolean isChatRandom()
{
return this.chatRandom; return this.chatRandom;
} }
public void setChatRandom(boolean chatRandom) {
public boolean hasChat()
{
return !this.chatLines.isEmpty();
}
public void setChatRandom(boolean chatRandom)
{
this.chatRandom = chatRandom; this.chatRandom = chatRandom;
this.needsUpdate = true; this.needsUpdate = true;
} }
public boolean hasChat() {
return !this.chatLines.isEmpty();
}
public int getChatDelay() public int getChatDelay() {
{
return this.chatDelay; return this.chatDelay;
} }
public void setChatDelay(short chatDelay) {
public void setChatDelay(short chatDelay)
{
this.chatDelay = (short) Math.min(Math.max(chatDelay, BotManager.MINIMUM_CHAT_SPEED), BotManager.MAXIMUM_CHAT_SPEED); this.chatDelay = (short) Math.min(Math.max(chatDelay, BotManager.MINIMUM_CHAT_SPEED), BotManager.MAXIMUM_CHAT_SPEED);
this.needsUpdate = true; this.needsUpdate = true;
this.chatTimeOut = Emulator.getIntUnixTimestamp() + this.chatDelay; this.chatTimeOut = Emulator.getIntUnixTimestamp() + this.chatDelay;
} }
public int getChatTimestamp() {
public int getChatTimestamp()
{
return this.chatTimestamp; return this.chatTimestamp;
} }
public void clearChat() public void clearChat() {
{ synchronized (this.chatLines) {
synchronized (this.chatLines)
{
this.chatLines.clear(); this.chatLines.clear();
this.needsUpdate = true; this.needsUpdate = true;
} }
} }
public String getType() {
public String getType()
{
return this.type; return this.type;
} }
public int getEffect() {
public int getEffect()
{
return this.effect; return this.effect;
} }
public void setEffect(int effect, int duration) {
public void setEffect(int effect, int duration)
{
this.effect = effect; this.effect = effect;
this.needsUpdate = true; this.needsUpdate = true;
if (this.roomUnit != null) if (this.roomUnit != null) {
{ if (this.room != null) {
if (this.room != null)
{
this.room.giveEffect(this.roomUnit, this.effect, duration); this.room.giveEffect(this.roomUnit, this.effect, duration);
} }
} }
} }
public void addChatLines(ArrayList<String> chatLines) {
public void addChatLines(ArrayList<String> chatLines) synchronized (this.chatLines) {
{
synchronized (this.chatLines)
{
this.chatLines.addAll(chatLines); this.chatLines.addAll(chatLines);
this.needsUpdate = true; this.needsUpdate = true;
} }
} }
public void addChatLine(String chatLine) {
public void addChatLine(String chatLine) synchronized (this.chatLines) {
{
synchronized (this.chatLines)
{
this.chatLines.add(chatLine); this.chatLines.add(chatLine);
this.needsUpdate = true; this.needsUpdate = true;
} }
} }
public ArrayList<String> getChatLines() {
public ArrayList<String> getChatLines()
{
return this.chatLines; return this.chatLines;
} }
public int getFollowingHabboId() {
public int getFollowingHabboId()
{
return this.followingHabboId; return this.followingHabboId;
} }
public void startFollowingHabbo(Habbo habbo) {
public void startFollowingHabbo(Habbo habbo)
{
this.followingHabboId = habbo.getHabboInfo().getId(); this.followingHabboId = habbo.getHabboInfo().getId();
Emulator.getThreading().run(new BotFollowHabbo(this, habbo, habbo.getHabboInfo().getCurrentRoom())); Emulator.getThreading().run(new BotFollowHabbo(this, habbo, habbo.getHabboInfo().getCurrentRoom()));
} }
public void stopFollowingHabbo() public void stopFollowingHabbo() {
{
this.followingHabboId = 0; this.followingHabboId = 0;
} }
public boolean canWalk() {
public static void initialise()
{
}
public static void dispose()
{
}
public boolean canWalk()
{
return this.canWalk; return this.canWalk;
} }
public void setCanWalk(boolean canWalk) public void setCanWalk(boolean canWalk) {
{
this.canWalk = canWalk; this.canWalk = canWalk;
} }

View File

@ -20,25 +20,16 @@ import java.lang.reflect.Method;
import java.sql.*; import java.sql.*;
import java.util.Map; import java.util.Map;
public class BotManager public class BotManager {
{
public static int MINIMUM_CHAT_SPEED = 7;
public static int MAXIMUM_CHAT_SPEED = 604800;
public static int MAXIMUM_CHAT_LENGTH = 120;
public static int MAXIMUM_NAME_LENGTH = 15;
final private static THashMap<String, Class<? extends Bot>> botDefenitions = new THashMap<>(); final private static THashMap<String, Class<? extends Bot>> botDefenitions = new THashMap<>();
public static int MINIMUM_CHAT_SPEED = 7;
public static int MAXIMUM_CHAT_SPEED = 604800;
public static int MAXIMUM_CHAT_LENGTH = 120;
public static int MAXIMUM_NAME_LENGTH = 15;
public BotManager() throws Exception public BotManager() throws Exception {
{
long millis = System.currentTimeMillis(); long millis = System.currentTimeMillis();
addBotDefinition("generic", Bot.class); addBotDefinition("generic", Bot.class);
@ -50,24 +41,26 @@ public class BotManager
Emulator.getLogging().logStart("Bot Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)"); Emulator.getLogging().logStart("Bot Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
} }
public static void addBotDefinition(String type, Class<? extends Bot> botClazz) throws Exception {
if (botClazz.getDeclaredConstructor(ResultSet.class) == null) {
throw new Exception("Missing Bot(ResultSet) constructor!");
} else {
botClazz.getDeclaredConstructor(ResultSet.class).setAccessible(true);
public boolean reload() botDefenitions.put(type, botClazz);
{ }
for(Map.Entry<String, Class<? extends Bot>> set : botDefenitions.entrySet()) }
{
try public boolean reload() {
{ for (Map.Entry<String, Class<? extends Bot>> set : botDefenitions.entrySet()) {
try {
Method m = set.getValue().getMethod("initialise"); Method m = set.getValue().getMethod("initialise");
m.setAccessible(true); m.setAccessible(true);
m.invoke(null); m.invoke(null);
} } catch (NoSuchMethodException e) {
catch (NoSuchMethodException e)
{
Emulator.getLogging().logStart("Bot Manager -> Failed to execute initialise method upon bot type '" + set.getKey() + "'. No Such Method!"); Emulator.getLogging().logStart("Bot Manager -> Failed to execute initialise method upon bot type '" + set.getKey() + "'. No Such Method!");
return false; return false;
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logStart("Bot Manager -> Failed to execute initialise method upon bot type '" + set.getKey() + "'. Error: " + e.getMessage()); Emulator.getLogging().logStart("Bot Manager -> Failed to execute initialise method upon bot type '" + set.getKey() + "'. Error: " + e.getMessage());
return false; return false;
} }
@ -76,63 +69,46 @@ public class BotManager
return true; return true;
} }
public Bot createBot(THashMap<String, String> data, String type) {
public Bot createBot(THashMap<String, String> data, String type)
{
Bot bot = null; Bot bot = null;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO bots (user_id, room_id, name, motto, figure, gender, type) VALUES (0, 0, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO bots (user_id, room_id, name, motto, figure, gender, type) VALUES (0, 0, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
{
statement.setString(1, data.get("name")); statement.setString(1, data.get("name"));
statement.setString(2, data.get("motto")); statement.setString(2, data.get("motto"));
statement.setString(3, data.get("figure")); statement.setString(3, data.get("figure"));
statement.setString(4, data.get("gender").toUpperCase()); statement.setString(4, data.get("gender").toUpperCase());
statement.setString(5, type); statement.setString(5, type);
statement.execute(); statement.execute();
try (ResultSet set = statement.getGeneratedKeys()) try (ResultSet set = statement.getGeneratedKeys()) {
{ if (set.next()) {
if (set.next()) try (PreparedStatement stmt = connection.prepareStatement("SELECT users.username AS owner_name, bots.* FROM bots LEFT JOIN users ON bots.user_id = users.id WHERE bots.id = ? LIMIT 1")) {
{
try (PreparedStatement stmt = connection.prepareStatement("SELECT users.username AS owner_name, bots.* FROM bots LEFT JOIN users ON bots.user_id = users.id WHERE bots.id = ? LIMIT 1"))
{
stmt.setInt(1, set.getInt(1)); stmt.setInt(1, set.getInt(1));
try (ResultSet resultSet = stmt.executeQuery()) try (ResultSet resultSet = stmt.executeQuery()) {
{ if (resultSet.next()) {
if (resultSet.next())
{
bot = this.loadBot(resultSet); bot = this.loadBot(resultSet);
} }
} }
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
} }
} } catch (SQLException e) {
catch(SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
return bot; return bot;
} }
public void placeBot(Bot bot, Habbo habbo, Room room, RoomTile location) {
public void placeBot(Bot bot, Habbo habbo, Room room, RoomTile location)
{
BotPlacedEvent event = new BotPlacedEvent(bot, location, habbo); BotPlacedEvent event = new BotPlacedEvent(bot, location, habbo);
Emulator.getPluginManager().fireEvent(event); Emulator.getPluginManager().fireEvent(event);
if (event.isCancelled()) if (event.isCancelled())
return; return;
if(room != null && bot != null && habbo != null) if (room != null && bot != null && habbo != null) {
{ if (room.getOwnerId() == habbo.getHabboInfo().getId() || habbo.hasPermission(Permission.ACC_ANYROOMOWNER) || habbo.hasPermission("acc_placefurni")) {
if (room.getOwnerId() == habbo.getHabboInfo().getId() || habbo.hasPermission(Permission.ACC_ANYROOMOWNER) || habbo.hasPermission("acc_placefurni")) if (room.getCurrentBots().size() >= Room.MAXIMUM_BOTS && !habbo.hasPermission("acc_unlimited_bots")) {
{
if (room.getCurrentBots().size() >= Room.MAXIMUM_BOTS && !habbo.hasPermission("acc_unlimited_bots"))
{
habbo.getClient().sendResponse(new BotErrorComposer(BotErrorComposer.ROOM_ERROR_MAX_BOTS)); habbo.getClient().sendResponse(new BotErrorComposer(BotErrorComposer.ROOM_ERROR_MAX_BOTS));
return; return;
} }
@ -159,48 +135,36 @@ public class BotManager
habbo.getClient().sendResponse(new RemoveBotComposer(bot)); habbo.getClient().sendResponse(new RemoveBotComposer(bot));
bot.onPlace(habbo, room); bot.onPlace(habbo, room);
if (topItem != null) if (topItem != null) {
{
roomUnit.setZ(topItem.getBaseItem().allowSit() ? topItem.getZ() : topItem.getZ() + Item.getCurrentHeight(topItem)); roomUnit.setZ(topItem.getBaseItem().allowSit() ? topItem.getZ() : topItem.getZ() + Item.getCurrentHeight(topItem));
try try {
{
topItem.onWalkOn(bot.getRoomUnit(), room, null); topItem.onWalkOn(bot.getRoomUnit(), room, null);
} catch (Exception e) } catch (Exception e) {
{
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
} }
} }
bot.cycle(false); bot.cycle(false);
} } else {
else
{
habbo.getClient().sendResponse(new BubbleAlertComposer(BubbleAlertKeys.FURNITURE_PLACEMENT_ERROR.key, FurnitureMovementError.NO_RIGHTS.errorCode)); habbo.getClient().sendResponse(new BubbleAlertComposer(BubbleAlertKeys.FURNITURE_PLACEMENT_ERROR.key, FurnitureMovementError.NO_RIGHTS.errorCode));
} }
} }
} }
public void pickUpBot(int botId, Habbo habbo) {
public void pickUpBot(int botId, Habbo habbo) if (habbo.getHabboInfo().getCurrentRoom() != null) {
{
if(habbo.getHabboInfo().getCurrentRoom() != null)
{
this.pickUpBot(habbo.getHabboInfo().getCurrentRoom().getBot(Math.abs(botId)), habbo); this.pickUpBot(habbo.getHabboInfo().getCurrentRoom().getBot(Math.abs(botId)), habbo);
} }
} }
public void pickUpBot(Bot bot, Habbo habbo) {
public void pickUpBot(Bot bot, Habbo habbo) if (bot != null && habbo != null) {
{
if(bot != null && habbo != null)
{
BotPickUpEvent pickedUpEvent = new BotPickUpEvent(bot, habbo); BotPickUpEvent pickedUpEvent = new BotPickUpEvent(bot, habbo);
Emulator.getPluginManager().fireEvent(pickedUpEvent); Emulator.getPluginManager().fireEvent(pickedUpEvent);
if (pickedUpEvent.isCancelled()) if (pickedUpEvent.isCancelled())
return; return;
if (bot.getOwnerId() == habbo.getHabboInfo().getId() || habbo.hasPermission(Permission.ACC_ANYROOMOWNER)) if (bot.getOwnerId() == habbo.getHabboInfo().getId() || habbo.hasPermission(Permission.ACC_ANYROOMOWNER)) {
{
if (!habbo.hasPermission("acc_unlimited_bots") && habbo.getInventory().getBotsComponent().getBots().size() >= 15) if (!habbo.hasPermission("acc_unlimited_bots") && habbo.getInventory().getBotsComponent().getBots().size() >= 15)
return; return;
@ -218,11 +182,8 @@ public class BotManager
} }
} }
public Bot loadBot(ResultSet set) {
public Bot loadBot(ResultSet set) try {
{
try
{
String type = set.getString("type"); String type = set.getString("type");
Class<? extends Bot> botClazz = botDefenitions.get(type); Class<? extends Bot> botClazz = botDefenitions.get(type);
@ -230,67 +191,35 @@ public class BotManager
return botClazz.getDeclaredConstructor(ResultSet.class).newInstance(set); return botClazz.getDeclaredConstructor(ResultSet.class).newInstance(set);
else else
Emulator.getLogging().logErrorLine("Unknown Bot Type: " + type); Emulator.getLogging().logErrorLine("Unknown Bot Type: " + type);
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
} }
return null; return null;
} }
public boolean deleteBot(Bot bot) {
public boolean deleteBot(Bot bot) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("DELETE FROM bots WHERE id = ? LIMIT 1")) {
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("DELETE FROM bots WHERE id = ? LIMIT 1"))
{
statement.setInt(1, bot.getId()); statement.setInt(1, bot.getId());
return statement.execute(); return statement.execute();
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
return false; return false;
} }
public void dispose() {
public static void addBotDefinition(String type, Class<? extends Bot> botClazz) throws Exception for (Map.Entry<String, Class<? extends Bot>> set : botDefenitions.entrySet()) {
{ try {
if(botClazz.getDeclaredConstructor(ResultSet.class) == null)
{
throw new Exception("Missing Bot(ResultSet) constructor!");
}
else
{
botClazz.getDeclaredConstructor(ResultSet.class).setAccessible(true);
botDefenitions.put(type, botClazz);
}
}
public void dispose()
{
for(Map.Entry<String, Class<? extends Bot>> set : botDefenitions.entrySet())
{
try
{
Method m = set.getValue().getMethod("dispose"); Method m = set.getValue().getMethod("dispose");
m.setAccessible(true); m.setAccessible(true);
m.invoke(null); m.invoke(null);
} } catch (NoSuchMethodException e) {
catch (NoSuchMethodException e)
{
Emulator.getLogging().logStart("Bot Manager -> Failed to execute dispose method upon bot type '" + set.getKey() + "'. No Such Method!"); Emulator.getLogging().logStart("Bot Manager -> Failed to execute dispose method upon bot type '" + set.getKey() + "'. No Such Method!");
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logStart("Bot Manager -> Failed to execute dispose method upon bot type '" + set.getKey() + "'. Error: " + e.getMessage()); Emulator.getLogging().logStart("Bot Manager -> Failed to execute dispose method upon bot type '" + set.getKey() + "'. Error: " + e.getMessage());
} }
} }

View File

@ -18,71 +18,55 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
public class ButlerBot extends Bot public class ButlerBot extends Bot {
{
public static THashMap<THashSet<String>, Integer> serveItems = new THashMap<>(); public static THashMap<THashSet<String>, Integer> serveItems = new THashMap<>();
public ButlerBot(ResultSet set) throws SQLException public ButlerBot(ResultSet set) throws SQLException {
{
super(set); super(set);
} }
public ButlerBot(Bot bot) public ButlerBot(Bot bot) {
{
super(bot); super(bot);
} }
public static void initialise() public static void initialise() {
{
if (serveItems == null) if (serveItems == null)
serveItems = new THashMap<>(); serveItems = new THashMap<>();
serveItems.clear(); serveItems.clear();
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM bot_serves")) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM bot_serves")) {
{ while (set.next()) {
while (set.next())
{
String[] keys = set.getString("keys").split(";"); String[] keys = set.getString("keys").split(";");
THashSet<String> ks = new THashSet<>(); THashSet<String> ks = new THashSet<>();
Collections.addAll(ks, keys); Collections.addAll(ks, keys);
serveItems.put(ks, set.getInt("item")); serveItems.put(ks, set.getInt("item"));
} }
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
public static void dispose() public static void dispose() {
{
serveItems.clear(); serveItems.clear();
} }
@Override @Override
public void onUserSay(final RoomChatMessage message) public void onUserSay(final RoomChatMessage message) {
{
if (this.getRoomUnit().hasStatus(RoomUnitStatus.MOVE)) if (this.getRoomUnit().hasStatus(RoomUnitStatus.MOVE))
return; return;
if (this.getRoomUnit().getCurrentLocation().distance(message.getHabbo().getRoomUnit().getCurrentLocation()) <= Emulator.getConfig().getInt("hotel.bot.butler.commanddistance")) if (this.getRoomUnit().getCurrentLocation().distance(message.getHabbo().getRoomUnit().getCurrentLocation()) <= Emulator.getConfig().getInt("hotel.bot.butler.commanddistance"))
if(message.getUnfilteredMessage() != null) if (message.getUnfilteredMessage() != null) {
{ for (Map.Entry<THashSet<String>, Integer> set : serveItems.entrySet()) {
for(Map.Entry<THashSet<String>, Integer> set : serveItems.entrySet()) for (String s : set.getKey()) {
{ if (message.getUnfilteredMessage().toLowerCase().contains(s)) {
for(String s : set.getKey())
{
if(message.getUnfilteredMessage().toLowerCase().contains(s))
{
BotServerItemEvent serveEvent = new BotServerItemEvent(this, message.getHabbo(), set.getValue()); BotServerItemEvent serveEvent = new BotServerItemEvent(this, message.getHabbo(), set.getValue());
if (Emulator.getPluginManager().fireEvent(serveEvent).isCancelled()) if (Emulator.getPluginManager().fireEvent(serveEvent).isCancelled()) {
{
return; return;
} }
if (this.getRoomUnit().canWalk()) if (this.getRoomUnit().canWalk()) {
{
final String key = s; final String key = s;
final Bot b = this; final Bot b = this;
b.lookAt(serveEvent.habbo); b.lookAt(serveEvent.habbo);
@ -91,20 +75,16 @@ public class ButlerBot extends Bot
tasks.add(new RoomUnitGiveHanditem(serveEvent.habbo.getRoomUnit(), serveEvent.habbo.getHabboInfo().getCurrentRoom(), serveEvent.itemId)); tasks.add(new RoomUnitGiveHanditem(serveEvent.habbo.getRoomUnit(), serveEvent.habbo.getHabboInfo().getCurrentRoom(), serveEvent.itemId));
tasks.add(new RoomUnitGiveHanditem(this.getRoomUnit(), serveEvent.habbo.getHabboInfo().getCurrentRoom(), 0)); tasks.add(new RoomUnitGiveHanditem(this.getRoomUnit(), serveEvent.habbo.getHabboInfo().getCurrentRoom(), 0));
tasks.add(new Runnable() tasks.add(new Runnable() {
{
@Override @Override
public void run() public void run() {
{
b.talk(Emulator.getTexts().getValue("bots.butler.given").replace("%key%", key).replace("%username%", serveEvent.habbo.getHabboInfo().getUsername())); b.talk(Emulator.getTexts().getValue("bots.butler.given").replace("%key%", key).replace("%username%", serveEvent.habbo.getHabboInfo().getUsername()));
} }
}); });
List<Runnable> failedReached = new ArrayList(); List<Runnable> failedReached = new ArrayList();
failedReached.add(new Runnable() failedReached.add(new Runnable() {
{ public void run() {
public void run()
{
if (b.getRoomUnit().getCurrentLocation().distance(serveEvent.habbo.getRoomUnit().getCurrentLocation()) <= Emulator.getConfig().getInt("hotel.bot.butler.servedistance", 8)) { if (b.getRoomUnit().getCurrentLocation().distance(serveEvent.habbo.getRoomUnit().getCurrentLocation()) <= Emulator.getConfig().getInt("hotel.bot.butler.servedistance", 8)) {
for (Runnable t : tasks) { for (Runnable t : tasks) {
t.run(); t.run();
@ -117,13 +97,10 @@ public class ButlerBot extends Bot
if (b.getRoomUnit().getCurrentLocation().distance(serveEvent.habbo.getRoomUnit().getCurrentLocation()) > Emulator.getConfig().getInt("hotel.bot.butler.reachdistance", 3)) { if (b.getRoomUnit().getCurrentLocation().distance(serveEvent.habbo.getRoomUnit().getCurrentLocation()) > Emulator.getConfig().getInt("hotel.bot.butler.reachdistance", 3)) {
Emulator.getThreading().run(new RoomUnitWalkToRoomUnit(this.getRoomUnit(), serveEvent.habbo.getRoomUnit(), serveEvent.habbo.getHabboInfo().getCurrentRoom(), tasks, failedReached, Emulator.getConfig().getInt("hotel.bot.butler.reachdistance", 3))); Emulator.getThreading().run(new RoomUnitWalkToRoomUnit(this.getRoomUnit(), serveEvent.habbo.getRoomUnit(), serveEvent.habbo.getHabboInfo().getCurrentRoom(), tasks, failedReached, Emulator.getConfig().getInt("hotel.bot.butler.reachdistance", 3)));
} } else {
else {
Emulator.getThreading().run(failedReached.get(0), 1000); Emulator.getThreading().run(failedReached.get(0), 1000);
} }
} } else {
else
{
this.getRoom().giveHandItem(serveEvent.habbo, serveEvent.itemId); this.getRoom().giveHandItem(serveEvent.habbo, serveEvent.itemId);
this.talk(Emulator.getTexts().getValue("bots.butler.given").replace("%key%", s).replace("%username%", serveEvent.habbo.getHabboInfo().getUsername())); this.talk(Emulator.getTexts().getValue("bots.butler.given").replace("%key%", s).replace("%username%", serveEvent.habbo.getHabboInfo().getUsername()));
} }

View File

@ -11,36 +11,33 @@ import java.sql.SQLException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
public class VisitorBot extends Bot public class VisitorBot extends Bot {
{
private static SimpleDateFormat DATE_FORMAT; private static SimpleDateFormat DATE_FORMAT;
private boolean showedLog = false; private boolean showedLog = false;
private THashSet<ModToolRoomVisit> visits = new THashSet<>(3); private THashSet<ModToolRoomVisit> visits = new THashSet<>(3);
public VisitorBot(ResultSet set) throws SQLException public VisitorBot(ResultSet set) throws SQLException {
{
super(set); super(set);
} }
public VisitorBot(Bot bot) public VisitorBot(Bot bot) {
{
super(bot); super(bot);
} }
public static void initialise() {
DATE_FORMAT = new SimpleDateFormat(Emulator.getConfig().getValue("bots.visitor.dateformat"));
}
@Override @Override
public void onUserSay(final RoomChatMessage message) public void onUserSay(final RoomChatMessage message) {
{ if (!this.showedLog) {
if(!this.showedLog) if (message.getMessage().equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes"))) {
{
if(message.getMessage().equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes")))
{
this.showedLog = true; this.showedLog = true;
String visitMessage = Emulator.getTexts().getValue("bots.visitor.list").replace("%count%", this.visits.size() + ""); String visitMessage = Emulator.getTexts().getValue("bots.visitor.list").replace("%count%", this.visits.size() + "");
StringBuilder list = new StringBuilder(); StringBuilder list = new StringBuilder();
for(ModToolRoomVisit visit : this.visits) for (ModToolRoomVisit visit : this.visits) {
{
list.append("\r"); list.append("\r");
list.append(visit.roomName).append(" "); list.append(visit.roomName).append(" ");
list.append(Emulator.getTexts().getValue("generic.time.at")).append(" "); list.append(Emulator.getTexts().getValue("generic.time.at")).append(" ");
@ -56,29 +53,18 @@ public class VisitorBot extends Bot
} }
} }
public void onUserEnter(Habbo habbo) public void onUserEnter(Habbo habbo) {
{ if (!this.showedLog) {
if(!this.showedLog) if (habbo.getHabboInfo().getCurrentRoom() != null) {
{
if(habbo.getHabboInfo().getCurrentRoom() != null)
{
this.visits = Emulator.getGameEnvironment().getModToolManager().getVisitsForRoom(habbo.getHabboInfo().getCurrentRoom(), 10, true, habbo.getHabboInfo().getLastOnline(), Emulator.getIntUnixTimestamp()); this.visits = Emulator.getGameEnvironment().getModToolManager().getVisitsForRoom(habbo.getHabboInfo().getCurrentRoom(), 10, true, habbo.getHabboInfo().getLastOnline(), Emulator.getIntUnixTimestamp());
if(this.visits.isEmpty()) if (this.visits.isEmpty()) {
{
this.talk(Emulator.getTexts().getValue("bots.visitor.no_visits")); this.talk(Emulator.getTexts().getValue("bots.visitor.no_visits"));
} } else {
else
{
this.talk(Emulator.getTexts().getValue("bots.visitor.visits").replace("%count%", this.visits.size() + "").replace("%positive%", Emulator.getTexts().getValue("generic.yes"))); this.talk(Emulator.getTexts().getValue("bots.visitor.visits").replace("%count%", this.visits.size() + "").replace("%positive%", Emulator.getTexts().getValue("generic.yes")));
} }
} }
} }
} }
public static void initialise()
{
DATE_FORMAT = new SimpleDateFormat(Emulator.getConfig().getValue("bots.visitor.dateformat"));
}
} }

View File

@ -6,8 +6,7 @@ import com.eu.habbo.habbohotel.users.Habbo;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class CalendarRewardObject public class CalendarRewardObject {
{
private final int id; private final int id;
private final String name; private final String name;
private final String customImage; private final String customImage;
@ -17,8 +16,7 @@ public class CalendarRewardObject
private final String badge; private final String badge;
private final int catalogItemId; private final int catalogItemId;
public CalendarRewardObject(ResultSet set) throws SQLException public CalendarRewardObject(ResultSet set) throws SQLException {
{
this.id = set.getInt("id"); this.id = set.getInt("id");
this.name = set.getString("name"); this.name = set.getString("name");
this.customImage = set.getString("custom_image"); this.customImage = set.getString("custom_image");
@ -29,71 +27,57 @@ public class CalendarRewardObject
this.catalogItemId = set.getInt("catalog_item_id"); this.catalogItemId = set.getInt("catalog_item_id");
} }
public void give(Habbo habbo) public void give(Habbo habbo) {
{ if (this.credits > 0) {
if (this.credits > 0)
{
habbo.giveCredits(this.credits); habbo.giveCredits(this.credits);
} }
if (this.points > 0) if (this.points > 0) {
{
habbo.givePoints(this.pointsType, this.points); habbo.givePoints(this.pointsType, this.points);
} }
if (!this.badge.isEmpty()) if (!this.badge.isEmpty()) {
{
habbo.addBadge(this.badge); habbo.addBadge(this.badge);
} }
if (this.catalogItemId > 0) if (this.catalogItemId > 0) {
{
CatalogItem item = this.getCatalogItem(); CatalogItem item = this.getCatalogItem();
if (item != null) if (item != null) {
{
Emulator.getGameEnvironment().getCatalogManager().purchaseItem(null, item, habbo, 1, "", true); Emulator.getGameEnvironment().getCatalogManager().purchaseItem(null, item, habbo, 1, "", true);
} }
} }
} }
public int getId() public int getId() {
{
return this.id; return this.id;
} }
public String getName() public String getName() {
{
return this.name; return this.name;
} }
public String getCustomImage() public String getCustomImage() {
{
return this.customImage; return this.customImage;
} }
public int getCredits() public int getCredits() {
{
return this.credits; return this.credits;
} }
public int getPoints() public int getPoints() {
{
return this.points; return this.points;
} }
public int getPointsType() public int getPointsType() {
{
return this.pointsType; return this.pointsType;
} }
public String getBadge() public String getBadge() {
{
return this.badge; return this.badge;
} }
public CatalogItem getCatalogItem() public CatalogItem getCatalogItem() {
{
return Emulator.getGameEnvironment().getCatalogManager().getCatalogItem(this.catalogItemId); return Emulator.getGameEnvironment().getCatalogManager().getCatalogItem(this.catalogItemId);
} }
} }

View File

@ -4,21 +4,7 @@ import com.eu.habbo.Emulator;
import com.eu.habbo.messages.ISerialize; import com.eu.habbo.messages.ISerialize;
import com.eu.habbo.messages.ServerMessage; import com.eu.habbo.messages.ServerMessage;
public class CatalogFeaturedPage implements ISerialize public class CatalogFeaturedPage implements ISerialize {
{
public enum Type
{
PAGE_NAME(0),
PAGE_ID(1),
PRODUCT_NAME(2);
public final int type;
Type(int type)
{
this.type = type;
}
}
private final int slotId; private final int slotId;
private final String caption; private final String caption;
private final String image; private final String image;
@ -27,9 +13,7 @@ public class CatalogFeaturedPage implements ISerialize
private final String pageName; private final String pageName;
private final int pageId; private final int pageId;
private final String productName; private final String productName;
public CatalogFeaturedPage(int slotId, String caption, String image, Type type, int expireTimestamp, String pageName, int pageId, String productName) {
public CatalogFeaturedPage(int slotId, String caption, String image, Type type, int expireTimestamp, String pageName, int pageId, String productName)
{
this.slotId = slotId; this.slotId = slotId;
this.caption = caption; this.caption = caption;
this.image = image; this.image = image;
@ -41,21 +25,34 @@ public class CatalogFeaturedPage implements ISerialize
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendInt(this.slotId); message.appendInt(this.slotId);
message.appendString(this.caption); message.appendString(this.caption);
message.appendString(this.image); message.appendString(this.image);
message.appendInt(this.type.type); message.appendInt(this.type.type);
switch (this.type) switch (this.type) {
{
case PAGE_NAME: case PAGE_NAME:
message.appendString(this.pageName); break; message.appendString(this.pageName);
break;
case PAGE_ID: case PAGE_ID:
message.appendInt(this.pageId); break; message.appendInt(this.pageId);
break;
case PRODUCT_NAME: case PRODUCT_NAME:
message.appendString(this.productName); break; message.appendString(this.productName);
break;
} }
message.appendInt(Emulator.getIntUnixTimestamp() - this.expireTimestamp); message.appendInt(Emulator.getIntUnixTimestamp() - this.expireTimestamp);
} }
public enum Type {
PAGE_NAME(0),
PAGE_ID(1),
PRODUCT_NAME(2);
public final int type;
Type(int type) {
this.type = type;
}
}
} }

View File

@ -13,39 +13,18 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem> public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem> {
{
int id; int id;
private int pageId;
private String itemId;
private String name;
private int credits;
private int points;
private short pointsType;
private int amount;
private boolean allowGift = false;
int limitedStack; int limitedStack;
private int pageId;
private String itemId;
private String name;
private int credits;
private int points;
private short pointsType;
private int amount;
private boolean allowGift = false;
private int limitedSells; private int limitedSells;
@ -69,20 +48,40 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
private HashMap<Integer, Integer> bundle; private HashMap<Integer, Integer> bundle;
public CatalogItem(ResultSet set) throws SQLException public CatalogItem(ResultSet set) throws SQLException {
{
this.load(set); this.load(set);
this.needsUpdate = false; this.needsUpdate = false;
} }
public static boolean haveOffer(CatalogItem item) {
if (!item.haveOffer)
return false;
public void update(ResultSet set) throws SQLException if (item.getAmount() != 1)
{ return false;
if (item.isLimited())
return false;
if (item.bundle.size() > 1)
return false;
if (item.getName().toLowerCase().startsWith("cf_") || item.getName().toLowerCase().startsWith("cfc_"))
return false;
for (Item i : item.getBaseItems()) {
if (i.getName().toLowerCase().startsWith("cf_") || i.getName().toLowerCase().startsWith("cfc_") || i.getName().toLowerCase().startsWith("rentable_bot"))
return false;
}
return !item.getName().toLowerCase().startsWith("rentable_bot_");
}
public void update(ResultSet set) throws SQLException {
this.load(set); this.load(set);
} }
private void load(ResultSet set) throws SQLException private void load(ResultSet set) throws SQLException {
{
this.id = set.getInt("id"); this.id = set.getInt("id");
this.pageId = set.getInt("page_id"); this.pageId = set.getInt("page_id");
this.itemId = set.getString("item_Ids"); this.itemId = set.getString("item_Ids");
@ -103,168 +102,119 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
this.loadBundle(); this.loadBundle();
} }
public int getId() {
public int getId()
{
return this.id; return this.id;
} }
public int getPageId() {
public int getPageId()
{
return this.pageId; return this.pageId;
} }
public void setPageId(int pageId) {
public void setPageId(int pageId)
{
this.pageId = pageId; this.pageId = pageId;
} }
public String getItemId() {
public String getItemId()
{
return this.itemId; return this.itemId;
} }
public void setItemId(String itemId) {
public void setItemId(String itemId)
{
this.itemId = itemId; this.itemId = itemId;
} }
public String getName() {
public String getName()
{
return this.name; return this.name;
} }
public int getCredits() {
public int getCredits()
{
return this.credits; return this.credits;
} }
public int getPoints() {
public int getPoints()
{
return this.points; return this.points;
} }
public int getPointsType() {
public int getPointsType()
{
return this.pointsType; return this.pointsType;
} }
public int getAmount() {
public int getAmount()
{
return this.amount; return this.amount;
} }
public int getLimitedStack() {
public int getLimitedStack()
{
return this.limitedStack; return this.limitedStack;
} }
public int getLimitedSells() {
public int getLimitedSells()
{
CatalogLimitedConfiguration ltdConfig = Emulator.getGameEnvironment().getCatalogManager().getLimitedConfig(this); CatalogLimitedConfiguration ltdConfig = Emulator.getGameEnvironment().getCatalogManager().getLimitedConfig(this);
if (ltdConfig != null) if (ltdConfig != null) {
{
return this.limitedStack - ltdConfig.available(); return this.limitedStack - ltdConfig.available();
} }
return this.limitedStack; return this.limitedStack;
} }
public String getExtradata() {
public String getExtradata()
{
return this.extradata; return this.extradata;
} }
public boolean isClubOnly() {
public boolean isClubOnly()
{
return this.clubOnly; return this.clubOnly;
} }
public boolean isHaveOffer() {
public boolean isHaveOffer()
{
return this.haveOffer; return this.haveOffer;
} }
public int getOfferId() {
public int getOfferId()
{
return this.offerId; return this.offerId;
} }
public boolean isLimited() {
public boolean isLimited()
{
return this.limitedStack > 0; return this.limitedStack > 0;
} }
private int getOrderNumber() {
private int getOrderNumber()
{
return this.orderNumber; return this.orderNumber;
} }
public synchronized void sellRare() {
public synchronized void sellRare()
{
this.limitedSells++; this.limitedSells++;
this.needsUpdate = true; this.needsUpdate = true;
if(this.limitedSells == this.limitedStack) if (this.limitedSells == this.limitedStack) {
{
Emulator.getGameEnvironment().getCatalogManager().moveCatalogItem(this, Emulator.getConfig().getInt("catalog.ltd.page.soldout")); Emulator.getGameEnvironment().getCatalogManager().moveCatalogItem(this, Emulator.getConfig().getInt("catalog.ltd.page.soldout"));
} }
Emulator.getThreading().run(this); Emulator.getThreading().run(this);
} }
public THashSet<Item> getBaseItems() {
public THashSet<Item> getBaseItems()
{
THashSet<Item> items = new THashSet<>(); THashSet<Item> items = new THashSet<>();
if(!this.itemId.isEmpty()) if (!this.itemId.isEmpty()) {
{
String[] itemIds = this.itemId.split(";"); String[] itemIds = this.itemId.split(";");
for (String itemId : itemIds) for (String itemId : itemIds) {
{
if (itemId.isEmpty()) if (itemId.isEmpty())
continue; continue;
if (itemId.contains(":")) if (itemId.contains(":")) {
{
itemId = itemId.split(":")[0]; itemId = itemId.split(":")[0];
} }
int identifier; int identifier;
try try {
{
identifier = Integer.parseInt(itemId); identifier = Integer.parseInt(itemId);
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logStart("Invalid value (" + itemId + ") for items_base column for catalog_item id (" + this.id + "). Value must be integer or of the format of integer:amount;integer:amount"); Emulator.getLogging().logStart("Invalid value (" + itemId + ") for items_base column for catalog_item id (" + this.id + "). Value must be integer or of the format of integer:amount;integer:amount");
continue; continue;
} }
if (identifier > 0) if (identifier > 0) {
{
Item item = Emulator.getGameEnvironment().getItemManager().getItem(identifier); Item item = Emulator.getGameEnvironment().getItemManager().getItem(identifier);
if (item != null) if (item != null)
@ -276,76 +226,55 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
return items; return items;
} }
public int getItemAmount(int id) {
public int getItemAmount(int id)
{
if (this.bundle.containsKey(id)) if (this.bundle.containsKey(id))
return this.bundle.get(id); return this.bundle.get(id);
else else
return this.amount; return this.amount;
} }
public HashMap<Integer, Integer> getBundle() {
public HashMap<Integer, Integer> getBundle()
{
return this.bundle; return this.bundle;
} }
public void loadBundle() {
public void loadBundle()
{
int intItemId; int intItemId;
if(this.itemId.contains(";")) if (this.itemId.contains(";")) {
{ try {
try
{
String[] itemIds = this.itemId.split(";"); String[] itemIds = this.itemId.split(";");
for (String itemId : itemIds) for (String itemId : itemIds) {
{ if (itemId.contains(":")) {
if (itemId.contains(":"))
{
String[] data = itemId.split(":"); String[] data = itemId.split(":");
if (data.length > 1 && Integer.parseInt(data[0]) > 0 && Integer.parseInt(data[1]) > 0) if (data.length > 1 && Integer.parseInt(data[0]) > 0 && Integer.parseInt(data[1]) > 0) {
{
this.bundle.put(Integer.parseInt(data[0]), Integer.parseInt(data[1])); this.bundle.put(Integer.parseInt(data[0]), Integer.parseInt(data[1]));
} }
} else } else {
{ if (!itemId.isEmpty()) {
if (!itemId.isEmpty())
{
intItemId = (Integer.parseInt(itemId)); intItemId = (Integer.parseInt(itemId));
this.bundle.put(intItemId, 1); this.bundle.put(intItemId, 1);
} }
} }
} }
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logDebugLine("Failed to load " + this.itemId); Emulator.getLogging().logDebugLine("Failed to load " + this.itemId);
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
} }
} } else {
else try {
{
try
{
Item item = Emulator.getGameEnvironment().getItemManager().getItem(Integer.valueOf(this.itemId)); Item item = Emulator.getGameEnvironment().getItemManager().getItem(Integer.valueOf(this.itemId));
if (item != null) if (item != null) {
{
this.allowGift = item.allowGift(); this.allowGift = item.allowGift();
} }
} catch (Exception e) {
} }
catch (Exception e)
{}
} }
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendInt(this.getId()); message.appendInt(this.getId());
message.appendString(this.getName()); message.appendString(this.getName());
message.appendBoolean(false); message.appendBoolean(false);
@ -358,60 +287,41 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
message.appendInt(items.size()); message.appendInt(items.size());
for(Item item : items) for (Item item : items) {
{
message.appendString(item.getType().code.toLowerCase()); message.appendString(item.getType().code.toLowerCase());
if(item.getType() == FurnitureType.BADGE) if (item.getType() == FurnitureType.BADGE) {
{
message.appendString(item.getName()); message.appendString(item.getName());
} } else {
else
{
message.appendInt(item.getSpriteId()); message.appendInt(item.getSpriteId());
if(this.getName().contains("wallpaper_single") || this.getName().contains("floor_single") || this.getName().contains("landscape_single")) if (this.getName().contains("wallpaper_single") || this.getName().contains("floor_single") || this.getName().contains("landscape_single")) {
{
message.appendString(this.getName().split("_")[2]); message.appendString(this.getName().split("_")[2]);
} } else if (item.getName().contains("bot") && item.getType() == FurnitureType.ROBOT) {
else if(item.getName().contains("bot") && item.getType() == FurnitureType.ROBOT)
{
boolean lookFound = false; boolean lookFound = false;
for (String s : this.getExtradata().split(";")) for (String s : this.getExtradata().split(";")) {
{ if (s.startsWith("figure:")) {
if (s.startsWith("figure:"))
{
lookFound = true; lookFound = true;
message.appendString(s.replace("figure:", "")); message.appendString(s.replace("figure:", ""));
break; break;
} }
} }
if (!lookFound) if (!lookFound) {
{
message.appendString(this.getExtradata()); message.appendString(this.getExtradata());
} }
} } else if (item.getType() == FurnitureType.ROBOT) {
else if(item.getType() == FurnitureType.ROBOT)
{
message.appendString(this.getExtradata()); message.appendString(this.getExtradata());
} } else if (item.getName().equalsIgnoreCase("poster")) {
else if(item.getName().equalsIgnoreCase("poster"))
{
message.appendString(this.getExtradata()); message.appendString(this.getExtradata());
} } else if (this.getName().startsWith("SONG ")) {
else if(this.getName().startsWith("SONG "))
{
message.appendString(this.getExtradata()); message.appendString(this.getExtradata());
} } else {
else
{
message.appendString(""); message.appendString("");
} }
message.appendInt(this.getItemAmount(item.getId())); message.appendInt(this.getItemAmount(item.getId()));
message.appendBoolean(this.isLimited()); message.appendBoolean(this.isLimited());
if(this.isLimited()) if (this.isLimited()) {
{
message.appendInt(this.getLimitedStack()); message.appendInt(this.getLimitedStack());
message.appendInt(this.getLimitedStack() - this.getLimitedSells()); message.appendInt(this.getLimitedStack() - this.getLimitedSells());
} }
@ -425,19 +335,14 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
} }
@Override @Override
public void run() public void run() {
{ if (this.needsUpdate) {
if(this.needsUpdate) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE catalog_items SET limited_sells = ?, page_id = ? WHERE id = ?")) {
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE catalog_items SET limited_sells = ?, page_id = ? WHERE id = ?"))
{
statement.setInt(1, this.getLimitedSells()); statement.setInt(1, this.getLimitedSells());
statement.setInt(2, this.pageId); statement.setInt(2, this.pageId);
statement.setInt(3, this.getId()); statement.setInt(3, this.getId());
statement.execute(); statement.execute();
} } catch (SQLException e) {
catch(SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
@ -447,42 +352,11 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
@SuppressWarnings("NullableProblems") @SuppressWarnings("NullableProblems")
@Override @Override
public int compareTo(CatalogItem catalogItem) public int compareTo(CatalogItem catalogItem) {
{ if (CatalogManager.SORT_USING_ORDERNUM) {
if (CatalogManager.SORT_USING_ORDERNUM)
{
return this.getOrderNumber() - catalogItem.getOrderNumber(); return this.getOrderNumber() - catalogItem.getOrderNumber();
} } else {
else
{
return this.getId() - catalogItem.getId(); return this.getId() - catalogItem.getId();
} }
} }
public static boolean haveOffer(CatalogItem item)
{
if(!item.haveOffer)
return false;
if(item.getAmount() != 1)
return false;
if(item.isLimited())
return false;
if (item.bundle.size() > 1)
return false;
if(item.getName().toLowerCase().startsWith("cf_") || item.getName().toLowerCase().startsWith("cfc_"))
return false;
for(Item i : item.getBaseItems())
{
if(i.getName().toLowerCase().startsWith("cf_") || i.getName().toLowerCase().startsWith("cfc_") || i.getName().toLowerCase().startsWith("rentable_bot"))
return false;
}
return !item.getName().toLowerCase().startsWith("rentable_bot_");
}
} }

View File

@ -10,78 +10,61 @@ import java.sql.SQLException;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedList; import java.util.LinkedList;
public class CatalogLimitedConfiguration implements Runnable public class CatalogLimitedConfiguration implements Runnable {
{
private final int itemId; private final int itemId;
private int totalSet;
private final LinkedList<Integer> limitedNumbers; private final LinkedList<Integer> limitedNumbers;
private int totalSet;
public CatalogLimitedConfiguration(int itemId, LinkedList<Integer> availableNumbers, int totalSet) public CatalogLimitedConfiguration(int itemId, LinkedList<Integer> availableNumbers, int totalSet) {
{
this.itemId = itemId; this.itemId = itemId;
this.totalSet = totalSet; this.totalSet = totalSet;
this.limitedNumbers = availableNumbers; this.limitedNumbers = availableNumbers;
if (Emulator.getConfig().getBoolean("catalog.ltd.random", true)) { if (Emulator.getConfig().getBoolean("catalog.ltd.random", true)) {
Collections.shuffle(this.limitedNumbers); Collections.shuffle(this.limitedNumbers);
} } else {
else {
Collections.reverse(this.limitedNumbers); Collections.reverse(this.limitedNumbers);
} }
} }
public int getNumber() public int getNumber() {
{ synchronized (this.limitedNumbers) {
synchronized (this.limitedNumbers)
{
int num = this.limitedNumbers.pop(); int num = this.limitedNumbers.pop();
if(this.limitedNumbers.isEmpty()) if (this.limitedNumbers.isEmpty()) {
{
Emulator.getGameEnvironment().getCatalogManager().moveCatalogItem(Emulator.getGameEnvironment().getCatalogManager().getCatalogItem(this.itemId), Emulator.getConfig().getInt("catalog.ltd.page.soldout")); Emulator.getGameEnvironment().getCatalogManager().moveCatalogItem(Emulator.getGameEnvironment().getCatalogManager().getCatalogItem(this.itemId), Emulator.getConfig().getInt("catalog.ltd.page.soldout"));
} }
return num; return num;
} }
} }
public void limitedSold(int catalogItemId, Habbo habbo, HabboItem item) public void limitedSold(int catalogItemId, Habbo habbo, HabboItem item) {
{ synchronized (this.limitedNumbers) {
synchronized (this.limitedNumbers) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE catalog_items_limited SET user_id = ?, timestamp = ?, item_id = ? WHERE catalog_item_id = ? AND number = ? AND user_id = 0 LIMIT 1")) {
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE catalog_items_limited SET user_id = ?, timestamp = ?, item_id = ? WHERE catalog_item_id = ? AND number = ? AND user_id = 0 LIMIT 1"))
{
statement.setInt(1, habbo.getHabboInfo().getId()); statement.setInt(1, habbo.getHabboInfo().getId());
statement.setInt(2, Emulator.getIntUnixTimestamp()); statement.setInt(2, Emulator.getIntUnixTimestamp());
statement.setInt(3, item.getId()); statement.setInt(3, item.getId());
statement.setInt(4, catalogItemId); statement.setInt(4, catalogItemId);
statement.setInt(5, item.getLimitedSells()); statement.setInt(5, item.getLimitedSells());
statement.execute(); statement.execute();
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
} }
public void generateNumbers(int starting, int amount) public void generateNumbers(int starting, int amount) {
{ synchronized (this.limitedNumbers) {
synchronized (this.limitedNumbers) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO catalog_items_limited (catalog_item_id, number) VALUES (?, ?)")) {
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO catalog_items_limited (catalog_item_id, number) VALUES (?, ?)"))
{
statement.setInt(1, this.itemId); statement.setInt(1, this.itemId);
for (int i = starting; i <= amount; i++) for (int i = starting; i <= amount; i++) {
{
statement.setInt(2, i); statement.setInt(2, i);
statement.addBatch(); statement.addBatch();
this.limitedNumbers.push(i); this.limitedNumbers.push(i);
} }
statement.executeBatch(); statement.executeBatch();
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
@ -89,40 +72,32 @@ public class CatalogLimitedConfiguration implements Runnable
if (Emulator.getConfig().getBoolean("catalog.ltd.random", true)) { if (Emulator.getConfig().getBoolean("catalog.ltd.random", true)) {
Collections.shuffle(this.limitedNumbers); Collections.shuffle(this.limitedNumbers);
} } else {
else {
Collections.reverse(this.limitedNumbers); Collections.reverse(this.limitedNumbers);
} }
} }
} }
public int available() public int available() {
{
return this.limitedNumbers.size(); return this.limitedNumbers.size();
} }
public int getTotalSet() public int getTotalSet() {
{
return this.totalSet; return this.totalSet;
} }
public void setTotalSet(int totalSet) public void setTotalSet(int totalSet) {
{
this.totalSet = totalSet; this.totalSet = totalSet;
} }
@Override @Override
public void run() public void run() {
{ try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE catalog_items SET limited_stack = ?, limited_sells = ? WHERE id = ?")) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE catalog_items SET limited_stack = ?, limited_sells = ? WHERE id = ?"))
{
statement.setInt(1, this.totalSet); statement.setInt(1, this.totalSet);
statement.setInt(2, this.totalSet - this.available()); statement.setInt(2, this.totalSet - this.available());
statement.setInt(3, this.itemId); statement.setInt(3, this.itemId);
statement.execute(); statement.execute();
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }

View File

@ -13,8 +13,11 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
public abstract class CatalogPage implements Comparable<CatalogPage>, ISerialize public abstract class CatalogPage implements Comparable<CatalogPage>, ISerialize {
{ protected final TIntArrayList offerIds = new TIntArrayList();
protected final THashMap<Integer, CatalogPage> childPages = new THashMap<>();
private final TIntObjectMap<CatalogItem> catalogItems = TCollections.synchronizedMap(new TIntObjectHashMap<>());
private final ArrayList<Integer> included = new ArrayList<>();
protected int id; protected int id;
protected int parentId; protected int parentId;
protected int rank; protected int rank;
@ -34,13 +37,11 @@ public abstract class CatalogPage implements Comparable<CatalogPage>, ISerialize
protected String textTwo; protected String textTwo;
protected String textDetails; protected String textDetails;
protected String textTeaser; protected String textTeaser;
protected final TIntArrayList offerIds = new TIntArrayList();
protected final THashMap<Integer, CatalogPage> childPages = new THashMap<>();
private final TIntObjectMap<CatalogItem> catalogItems = TCollections.synchronizedMap(new TIntObjectHashMap<>());
private final ArrayList<Integer> included = new ArrayList<>();
public CatalogPage(ResultSet set) throws SQLException public CatalogPage() {
{ }
public CatalogPage(ResultSet set) throws SQLException {
if (set == null) if (set == null)
return; return;
@ -64,16 +65,11 @@ public abstract class CatalogPage implements Comparable<CatalogPage>, ISerialize
this.textDetails = set.getString("page_text_details"); this.textDetails = set.getString("page_text_details");
this.textTeaser = set.getString("page_text_teaser"); this.textTeaser = set.getString("page_text_teaser");
if (!set.getString("includes").isEmpty()) if (!set.getString("includes").isEmpty()) {
{ for (String id : set.getString("includes").split(";")) {
for (String id : set.getString("includes").split(";")) try {
{
try
{
this.included.add(Integer.valueOf(id)); this.included.add(Integer.valueOf(id));
} } catch (Exception e) {
catch (Exception e)
{
Emulator.getLogging().logErrorLine(e); Emulator.getLogging().logErrorLine(e);
Emulator.getLogging().logErrorLine("Failed to parse includes column value of (" + id + ") for catalog page (" + this.id + ")"); Emulator.getLogging().logErrorLine("Failed to parse includes column value of (" + id + ") for catalog page (" + this.id + ")");
} }
@ -81,147 +77,118 @@ public abstract class CatalogPage implements Comparable<CatalogPage>, ISerialize
} }
} }
public int getId() public int getId() {
{
return this.id; return this.id;
} }
public int getParentId() public int getParentId() {
{
return this.parentId; return this.parentId;
} }
public int getRank() public int getRank() {
{
return this.rank; return this.rank;
} }
public void setRank(int rank) public void setRank(int rank) {
{
this.rank = rank; this.rank = rank;
} }
public String getCaption() public String getCaption() {
{
return this.caption; return this.caption;
} }
public String getPageName() public String getPageName() {
{
return this.pageName; return this.pageName;
} }
public int getIconColor() public int getIconColor() {
{
return this.iconColor; return this.iconColor;
} }
public int getIconImage() public int getIconImage() {
{
return this.iconImage; return this.iconImage;
} }
public int getOrderNum() public int getOrderNum() {
{
return this.orderNum; return this.orderNum;
} }
public boolean isVisible() public boolean isVisible() {
{
return this.visible; return this.visible;
} }
public boolean isEnabled() public boolean isEnabled() {
{
return this.enabled; return this.enabled;
} }
public boolean isClubOnly() public boolean isClubOnly() {
{
return this.clubOnly; return this.clubOnly;
} }
public String getLayout() public String getLayout() {
{
return this.layout; return this.layout;
} }
public String getHeaderImage() public String getHeaderImage() {
{
return this.headerImage; return this.headerImage;
} }
public String getTeaserImage() public String getTeaserImage() {
{
return this.teaserImage; return this.teaserImage;
} }
public String getSpecialImage() public String getSpecialImage() {
{
return this.specialImage; return this.specialImage;
} }
public String getTextOne() public String getTextOne() {
{
return this.textOne; return this.textOne;
} }
public String getTextTwo() public String getTextTwo() {
{
return this.textTwo; return this.textTwo;
} }
public String getTextDetails() public String getTextDetails() {
{
return this.textDetails; return this.textDetails;
} }
public String getTextTeaser() public String getTextTeaser() {
{
return this.textTeaser; return this.textTeaser;
} }
public TIntArrayList getOfferIds() public TIntArrayList getOfferIds() {
{
return this.offerIds; return this.offerIds;
} }
public void addOfferId(int offerId) public void addOfferId(int offerId) {
{
this.offerIds.add(offerId); this.offerIds.add(offerId);
} }
public void addItem(CatalogItem item) public void addItem(CatalogItem item) {
{
this.catalogItems.put(item.getId(), item); this.catalogItems.put(item.getId(), item);
} }
public TIntObjectMap<CatalogItem> getCatalogItems() public TIntObjectMap<CatalogItem> getCatalogItems() {
{
return this.catalogItems; return this.catalogItems;
} }
public CatalogItem getCatalogItem(int id) public CatalogItem getCatalogItem(int id) {
{
return this.catalogItems.get(id); return this.catalogItems.get(id);
} }
public ArrayList<Integer> getIncluded() public ArrayList<Integer> getIncluded() {
{
return this.included; return this.included;
} }
public THashMap<Integer, CatalogPage> getChildPages() public THashMap<Integer, CatalogPage> getChildPages() {
{
return this.childPages; return this.childPages;
} }
public void addChildPage(CatalogPage page) public void addChildPage(CatalogPage page) {
{
this.childPages.put(page.getId(), page); this.childPages.put(page.getId(), page);
if (page.getRank() < this.getRank()) if (page.getRank() < this.getRank()) {
{
page.setRank(this.getRank()); page.setRank(this.getRank());
} }
} }

View File

@ -1,7 +1,6 @@
package com.eu.habbo.habbohotel.catalog; package com.eu.habbo.habbohotel.catalog;
public enum CatalogPageLayouts public enum CatalogPageLayouts {
{
default_3x3, default_3x3,

View File

@ -1,7 +1,6 @@
package com.eu.habbo.habbohotel.catalog; package com.eu.habbo.habbohotel.catalog;
public enum CatalogPageType public enum CatalogPageType {
{
NORMAL, NORMAL,

View File

@ -3,8 +3,7 @@ package com.eu.habbo.habbohotel.catalog;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class ClothItem public class ClothItem {
{
public int id; public int id;
@ -14,15 +13,13 @@ public class ClothItem
public int[] setId; public int[] setId;
public ClothItem(ResultSet set) throws SQLException public ClothItem(ResultSet set) throws SQLException {
{
this.id = set.getInt("id"); this.id = set.getInt("id");
this.name = set.getString("name"); this.name = set.getString("name");
String[] parts = set.getString("setid").split(","); String[] parts = set.getString("setid").split(",");
this.setId = new int[parts.length]; this.setId = new int[parts.length];
for (int i = 0; i < this.setId.length; i++) for (int i = 0; i < this.setId.length; i++) {
{
this.setId[i] = Integer.valueOf(parts[i]); this.setId[i] = Integer.valueOf(parts[i]);
} }
} }

View File

@ -3,8 +3,7 @@ package com.eu.habbo.habbohotel.catalog;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class ClubOffer public class ClubOffer {
{
private final int id; private final int id;
@ -29,8 +28,7 @@ public class ClubOffer
private final boolean deal; private final boolean deal;
public ClubOffer(ResultSet set) throws SQLException public ClubOffer(ResultSet set) throws SQLException {
{
this.id = set.getInt("id"); this.id = set.getInt("id");
this.name = set.getString("name"); this.name = set.getString("name");
this.days = set.getInt("days"); this.days = set.getInt("days");
@ -41,43 +39,35 @@ public class ClubOffer
this.deal = set.getString("deal").equals("1"); this.deal = set.getString("deal").equals("1");
} }
public int getId() public int getId() {
{
return this.id; return this.id;
} }
public String getName() public String getName() {
{
return this.name; return this.name;
} }
public int getDays() public int getDays() {
{
return this.days; return this.days;
} }
public int getCredits() public int getCredits() {
{
return this.credits; return this.credits;
} }
public int getPoints() public int getPoints() {
{
return this.points; return this.points;
} }
public int getPointsType() public int getPointsType() {
{
return this.pointsType; return this.pointsType;
} }
public boolean isVip() public boolean isVip() {
{
return this.vip; return this.vip;
} }
public boolean isDeal() public boolean isDeal() {
{
return this.deal; return this.deal;
} }
} }

View File

@ -8,8 +8,7 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class TargetOffer public class TargetOffer {
{
public static int ACTIVE_TARGET_OFFER_ID = 0; public static int ACTIVE_TARGET_OFFER_ID = 0;
private final int id; private final int id;
@ -26,8 +25,7 @@ public class TargetOffer
private final String icon; private final String icon;
private final String[] vars; private final String[] vars;
public TargetOffer(ResultSet set) throws SQLException public TargetOffer(ResultSet set) throws SQLException {
{
this.id = set.getInt("id"); this.id = set.getInt("id");
this.identifier = set.getString("offer_code"); this.identifier = set.getString("offer_code");
this.priceInCredits = set.getInt("credits"); this.priceInCredits = set.getInt("credits");
@ -43,8 +41,7 @@ public class TargetOffer
this.catalogItem = set.getInt("catalog_item"); this.catalogItem = set.getInt("catalog_item");
} }
public void serialize(ServerMessage message, HabboOfferPurchase purchase) public void serialize(ServerMessage message, HabboOfferPurchase purchase) {
{
message.appendInt(purchase.getState()); message.appendInt(purchase.getState());
message.appendInt(this.id); message.appendInt(this.id);
message.appendString(this.identifier); message.appendString(this.identifier);
@ -60,74 +57,60 @@ public class TargetOffer
message.appendString(this.icon); message.appendString(this.icon);
message.appendInt(0); message.appendInt(0);
message.appendInt(this.vars.length); message.appendInt(this.vars.length);
for (String variable : this.vars) for (String variable : this.vars) {
{
message.appendString(variable); message.appendString(variable);
} }
} }
public int getId() public int getId() {
{
return this.id; return this.id;
} }
public String getIdentifier() public String getIdentifier() {
{
return this.identifier; return this.identifier;
} }
public int getPriceInCredits() public int getPriceInCredits() {
{
return this.priceInCredits; return this.priceInCredits;
} }
public int getPriceInActivityPoints() public int getPriceInActivityPoints() {
{
return this.priceInActivityPoints; return this.priceInActivityPoints;
} }
public int getActivityPointsType() public int getActivityPointsType() {
{
return this.activityPointsType; return this.activityPointsType;
} }
public int getPurchaseLimit() public int getPurchaseLimit() {
{
return this.purchaseLimit; return this.purchaseLimit;
} }
public int getExpirationTime() public int getExpirationTime() {
{
return this.expirationTime; return this.expirationTime;
} }
public String getTitle() public String getTitle() {
{
return this.title; return this.title;
} }
public String getDescription() public String getDescription() {
{
return this.description; return this.description;
} }
public String getImageUrl() public String getImageUrl() {
{
return this.imageUrl; return this.imageUrl;
} }
public String getIcon() public String getIcon() {
{
return this.icon; return this.icon;
} }
public String[] getVars() public String[] getVars() {
{
return this.vars; return this.vars;
} }
public int getCatalogItem() public int getCatalogItem() {
{
return this.catalogItem; return this.catalogItem;
} }
} }

View File

@ -3,8 +3,7 @@ package com.eu.habbo.habbohotel.catalog;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class Voucher public class Voucher {
{
public final int id; public final int id;
@ -24,8 +23,7 @@ public class Voucher
public final int catalogItemId; public final int catalogItemId;
public Voucher(ResultSet set) throws SQLException public Voucher(ResultSet set) throws SQLException {
{
this.id = set.getInt("id"); this.id = set.getInt("id");
this.code = set.getString("code"); this.code = set.getString("code");
this.credits = set.getInt("credits"); this.credits = set.getInt("credits");

View File

@ -7,10 +7,8 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class BadgeDisplayLayout extends CatalogPage public class BadgeDisplayLayout extends CatalogPage {
{ public BadgeDisplayLayout(ResultSet set) throws SQLException {
public BadgeDisplayLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }

View File

@ -7,16 +7,13 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class BotsLayout extends CatalogPage public class BotsLayout extends CatalogPage {
{ public BotsLayout(ResultSet set) throws SQLException {
public BotsLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("bots"); message.appendString("bots");
message.appendInt(2); message.appendInt(2);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -7,16 +7,13 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class BuildersClubAddonsLayout extends CatalogPage public class BuildersClubAddonsLayout extends CatalogPage {
{ public BuildersClubAddonsLayout(ResultSet set) throws SQLException {
public BuildersClubAddonsLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("builders_club_addons"); message.appendString("builders_club_addons");
message.appendInt(3); message.appendInt(3);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -7,16 +7,13 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class BuildersClubFrontPageLayout extends CatalogPage public class BuildersClubFrontPageLayout extends CatalogPage {
{ public BuildersClubFrontPageLayout(ResultSet set) throws SQLException {
public BuildersClubFrontPageLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("builders_club_frontpage"); message.appendString("builders_club_frontpage");
message.appendInt(3); message.appendInt(3);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -7,16 +7,13 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class BuildersClubLoyaltyLayout extends CatalogPage public class BuildersClubLoyaltyLayout extends CatalogPage {
{ public BuildersClubLoyaltyLayout(ResultSet set) throws SQLException {
public BuildersClubLoyaltyLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("builders_club_loyalty"); message.appendString("builders_club_loyalty");
message.appendInt(3); message.appendInt(3);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,10 +6,12 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class CatalogRootLayout extends CatalogPage public class CatalogRootLayout extends CatalogPage {
{ public CatalogRootLayout() {
public CatalogRootLayout(ResultSet set) throws SQLException super();
{ }
public CatalogRootLayout(ResultSet set) throws SQLException {
super(null); super(null);
this.id = -1; this.id = -1;
@ -25,8 +27,7 @@ public class CatalogRootLayout extends CatalogPage
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
} }
} }

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class ClubBuyLayout extends CatalogPage public class ClubBuyLayout extends CatalogPage {
{ public ClubBuyLayout(ResultSet set) throws SQLException {
public ClubBuyLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("club_buy"); message.appendString("club_buy");
message.appendInt(2); message.appendInt(2);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class ClubGiftsLayout extends CatalogPage public class ClubGiftsLayout extends CatalogPage {
{ public ClubGiftsLayout(ResultSet set) throws SQLException {
public ClubGiftsLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("club_gifts"); message.appendString("club_gifts");
message.appendInt(1); message.appendInt(1);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,10 +6,8 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class ColorGroupingLayout extends CatalogPage public class ColorGroupingLayout extends CatalogPage {
{ public ColorGroupingLayout(ResultSet set) throws SQLException {
public ColorGroupingLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }

View File

@ -8,14 +8,12 @@ import java.sql.SQLException;
public class Default_3x3Layout extends CatalogPage { public class Default_3x3Layout extends CatalogPage {
public Default_3x3Layout(ResultSet set) throws SQLException public Default_3x3Layout(ResultSet set) throws SQLException {
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("default_3x3"); message.appendString("default_3x3");
message.appendInt(3); message.appendInt(3);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -8,29 +8,24 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class FrontPageFeaturedLayout extends CatalogPage public class FrontPageFeaturedLayout extends CatalogPage {
{ public FrontPageFeaturedLayout(ResultSet set) throws SQLException {
public FrontPageFeaturedLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("frontpage_featured"); message.appendString("frontpage_featured");
String[] teaserImages = super.getTeaserImage().split(";"); String[] teaserImages = super.getTeaserImage().split(";");
String[] specialImages = super.getSpecialImage().split(";"); String[] specialImages = super.getSpecialImage().split(";");
message.appendInt(1 + teaserImages.length + specialImages.length); message.appendInt(1 + teaserImages.length + specialImages.length);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());
for (String s : teaserImages) for (String s : teaserImages) {
{
message.appendString(s); message.appendString(s);
} }
for (String s : specialImages) for (String s : specialImages) {
{
message.appendString(s); message.appendString(s);
} }
message.appendInt(3); message.appendInt(3);
@ -39,13 +34,11 @@ public class FrontPageFeaturedLayout extends CatalogPage
message.appendString(super.getTextTeaser()); message.appendString(super.getTextTeaser());
} }
public void serializeExtra(ServerMessage message) public void serializeExtra(ServerMessage message) {
{
message.appendInt(Emulator.getGameEnvironment().getCatalogManager().getCatalogFeaturedPages().size()); message.appendInt(Emulator.getGameEnvironment().getCatalogManager().getCatalogFeaturedPages().size());
for (CatalogFeaturedPage page : Emulator.getGameEnvironment().getCatalogManager().getCatalogFeaturedPages().valueCollection()) for (CatalogFeaturedPage page : Emulator.getGameEnvironment().getCatalogManager().getCatalogFeaturedPages().valueCollection()) {
{
page.serialize(message); page.serialize(message);
} }
message.appendInt(1); //Position message.appendInt(1); //Position

View File

@ -8,8 +8,7 @@ import java.sql.SQLException;
public class FrontpageLayout extends CatalogPage { public class FrontpageLayout extends CatalogPage {
public FrontpageLayout(ResultSet set) throws SQLException public FrontpageLayout(ResultSet set) throws SQLException {
{
super(set); super(set);
} }

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class GuildForumLayout extends CatalogPage public class GuildForumLayout extends CatalogPage {
{ public GuildForumLayout(ResultSet set) throws SQLException {
public GuildForumLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("guild_forum"); message.appendString("guild_forum");
message.appendInt(2); message.appendInt(2);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class GuildFrontpageLayout extends CatalogPage public class GuildFrontpageLayout extends CatalogPage {
{ public GuildFrontpageLayout(ResultSet set) throws SQLException {
public GuildFrontpageLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("guild_frontpage"); message.appendString("guild_frontpage");
message.appendInt(2); message.appendInt(2);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class GuildFurnitureLayout extends CatalogPage public class GuildFurnitureLayout extends CatalogPage {
{ public GuildFurnitureLayout(ResultSet set) throws SQLException {
public GuildFurnitureLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("guild_custom_furni"); message.appendString("guild_custom_furni");
message.appendInt(2); message.appendInt(2);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class InfoDucketsLayout extends CatalogPage public class InfoDucketsLayout extends CatalogPage {
{ public InfoDucketsLayout(ResultSet set) throws SQLException {
public InfoDucketsLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("info_duckets"); message.appendString("info_duckets");
message.appendInt(1); message.appendInt(1);
message.appendString(this.getHeaderImage()); message.appendString(this.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class InfoLoyaltyLayout extends CatalogPage public class InfoLoyaltyLayout extends CatalogPage {
{ public InfoLoyaltyLayout(ResultSet set) throws SQLException {
public InfoLoyaltyLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("info_loyalty"); message.appendString("info_loyalty");
message.appendInt(1); message.appendInt(1);
message.appendString(this.getHeaderImage()); message.appendString(this.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class InfoPetsLayout extends CatalogPage public class InfoPetsLayout extends CatalogPage {
{ public InfoPetsLayout(ResultSet set) throws SQLException {
public InfoPetsLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("info_pets"); message.appendString("info_pets");
message.appendInt(2); message.appendInt(2);
message.appendString(this.getHeaderImage()); message.appendString(this.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class InfoRentablesLayout extends CatalogPage public class InfoRentablesLayout extends CatalogPage {
{ public InfoRentablesLayout(ResultSet set) throws SQLException {
public InfoRentablesLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
String[] data = this.getTextOne().split("\\|\\|"); String[] data = this.getTextOne().split("\\|\\|");
message.appendString("info_rentables"); message.appendString("info_rentables");
message.appendInt(1); message.appendInt(1);

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class LoyaltyVipBuyLayout extends CatalogPage public class LoyaltyVipBuyLayout extends CatalogPage {
{ public LoyaltyVipBuyLayout(ResultSet set) throws SQLException {
public LoyaltyVipBuyLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("loyalty_vip_buy"); message.appendString("loyalty_vip_buy");
message.appendInt(3); message.appendInt(3);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class MarketplaceLayout extends CatalogPage public class MarketplaceLayout extends CatalogPage {
{ public MarketplaceLayout(ResultSet set) throws SQLException {
public MarketplaceLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("marketplace"); message.appendString("marketplace");
message.appendInt(0); message.appendInt(0);
message.appendInt(0); message.appendInt(0);

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class MarketplaceOwnItems extends CatalogPage public class MarketplaceOwnItems extends CatalogPage {
{ public MarketplaceOwnItems(ResultSet set) throws SQLException {
public MarketplaceOwnItems(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("marketplace_own_items"); message.appendString("marketplace_own_items");
message.appendInt(0); message.appendInt(0);
message.appendInt(0); message.appendInt(0);

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class PetCustomizationLayout extends CatalogPage public class PetCustomizationLayout extends CatalogPage {
{ public PetCustomizationLayout(ResultSet set) throws SQLException {
public PetCustomizationLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("petcustomization"); message.appendString("petcustomization");
message.appendInt(3); message.appendInt(3);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class Pets2Layout extends CatalogPage public class Pets2Layout extends CatalogPage {
{ public Pets2Layout(ResultSet set) throws SQLException {
public Pets2Layout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("pets2"); message.appendString("pets2");
message.appendInt(2); message.appendInt(2);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class Pets3Layout extends CatalogPage public class Pets3Layout extends CatalogPage {
{ public Pets3Layout(ResultSet set) throws SQLException {
public Pets3Layout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("pets3"); message.appendString("pets3");
message.appendInt(2); message.appendInt(2);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class PetsLayout extends CatalogPage public class PetsLayout extends CatalogPage {
{ public PetsLayout(ResultSet set) throws SQLException {
public PetsLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("pets"); message.appendString("pets");
message.appendInt(2); message.appendInt(2);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class ProductPage1Layout extends CatalogPage public class ProductPage1Layout extends CatalogPage {
{ public ProductPage1Layout(ResultSet set) throws SQLException {
public ProductPage1Layout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("productpage1"); message.appendString("productpage1");
message.appendInt(2); message.appendInt(2);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,10 +6,8 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class RecentPurchasesLayout extends CatalogPage public class RecentPurchasesLayout extends CatalogPage {
{ public RecentPurchasesLayout(ResultSet set) throws SQLException {
public RecentPurchasesLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class RecyclerInfoLayout extends CatalogPage public class RecyclerInfoLayout extends CatalogPage {
{ public RecyclerInfoLayout(ResultSet set) throws SQLException {
public RecyclerInfoLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("recycler_info"); message.appendString("recycler_info");
message.appendInt(3); message.appendInt(3);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class RecyclerLayout extends CatalogPage public class RecyclerLayout extends CatalogPage {
{ public RecyclerLayout(ResultSet set) throws SQLException {
public RecyclerLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("recycler"); message.appendString("recycler");
message.appendInt(2); message.appendInt(2);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class RecyclerPrizesLayout extends CatalogPage public class RecyclerPrizesLayout extends CatalogPage {
{ public RecyclerPrizesLayout(ResultSet set) throws SQLException {
public RecyclerPrizesLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("recycler_prizes"); message.appendString("recycler_prizes");
message.appendInt(3); message.appendInt(3);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class RoomAdsLayout extends CatalogPage public class RoomAdsLayout extends CatalogPage {
{ public RoomAdsLayout(ResultSet set) throws SQLException {
public RoomAdsLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("roomads"); message.appendString("roomads");
message.appendInt(2); message.appendInt(2);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -17,56 +17,45 @@ import gnu.trove.procedure.TObjectProcedure;
import java.sql.*; import java.sql.*;
import java.util.Map; import java.util.Map;
public class RoomBundleLayout extends SingleBundle public class RoomBundleLayout extends SingleBundle {
{
public int roomId; public int roomId;
public Room room; public Room room;
private int lastUpdate = 0; private int lastUpdate = 0;
private boolean loaded = false; private boolean loaded = false;
public RoomBundleLayout(ResultSet set) throws SQLException public RoomBundleLayout(ResultSet set) throws SQLException {
{
super(set); super(set);
this.roomId = set.getInt("room_id"); this.roomId = set.getInt("room_id");
} }
@Override @Override
public TIntObjectMap<CatalogItem> getCatalogItems() public TIntObjectMap<CatalogItem> getCatalogItems() {
{ if (Emulator.getIntUnixTimestamp() - this.lastUpdate < 120) {
if(Emulator.getIntUnixTimestamp() - this.lastUpdate < 120)
{
this.lastUpdate = Emulator.getIntUnixTimestamp(); this.lastUpdate = Emulator.getIntUnixTimestamp();
return super.getCatalogItems(); return super.getCatalogItems();
} }
if(this.room == null) if (this.room == null) {
{ if (this.roomId > 0) {
if (this.roomId > 0)
{
this.room = Emulator.getGameEnvironment().getRoomManager().loadRoom(this.roomId); this.room = Emulator.getGameEnvironment().getRoomManager().loadRoom(this.roomId);
if (this.room != null) if (this.room != null)
this.room.preventUnloading = true; this.room.preventUnloading = true;
} } else {
else
{
Emulator.getLogging().logErrorLine("No room id specified for room bundle " + this.getPageName() + "(" + this.getId() + ")"); Emulator.getLogging().logErrorLine("No room id specified for room bundle " + this.getPageName() + "(" + this.getId() + ")");
} }
} }
if(this.room == null) if (this.room == null) {
{
return super.getCatalogItems(); return super.getCatalogItems();
} }
final CatalogItem[] item = {null}; final CatalogItem[] item = {null};
super.getCatalogItems().forEachValue(new TObjectProcedure<CatalogItem>() super.getCatalogItems().forEachValue(new TObjectProcedure<CatalogItem>() {
{
@Override @Override
public boolean execute(CatalogItem object) public boolean execute(CatalogItem object) {
{
if (object == null) if (object == null)
return true; return true;
@ -75,47 +64,39 @@ public class RoomBundleLayout extends SingleBundle
} }
}); });
if (this.room.isPreLoaded()) if (this.room.isPreLoaded()) {
{
this.room.loadData(); this.room.loadData();
this.room.preventUncaching = true; this.room.preventUncaching = true;
this.room.preventUnloading = true; this.room.preventUnloading = true;
} }
if(item[0] != null) if (item[0] != null) {
{
item[0].getBundle().clear(); item[0].getBundle().clear();
THashMap<Item, Integer> items = new THashMap<>(); THashMap<Item, Integer> items = new THashMap<>();
for(HabboItem i : this.room.getFloorItems()) for (HabboItem i : this.room.getFloorItems()) {
{ if (!items.contains(i.getBaseItem())) {
if(!items.contains(i.getBaseItem()))
{
items.put(i.getBaseItem(), 0); items.put(i.getBaseItem(), 0);
} }
items.put(i.getBaseItem(), items.get(i.getBaseItem()) + 1); items.put(i.getBaseItem(), items.get(i.getBaseItem()) + 1);
} }
for(HabboItem i : this.room.getWallItems()) for (HabboItem i : this.room.getWallItems()) {
{ if (!items.contains(i.getBaseItem())) {
if(!items.contains(i.getBaseItem()))
{
items.put(i.getBaseItem(), 0); items.put(i.getBaseItem(), 0);
} }
items.put(i.getBaseItem(), items.get(i.getBaseItem()) + 1); items.put(i.getBaseItem(), items.get(i.getBaseItem()) + 1);
} }
if (!item[0].getExtradata().isEmpty()) if (!item[0].getExtradata().isEmpty()) {
{
items.put(Emulator.getGameEnvironment().getItemManager().getItem(Integer.valueOf(item[0].getExtradata())), 1); items.put(Emulator.getGameEnvironment().getItemManager().getItem(Integer.valueOf(item[0].getExtradata())), 1);
} }
StringBuilder data = new StringBuilder(); StringBuilder data = new StringBuilder();
for(Map.Entry<Item, Integer> set : items.entrySet()) for (Map.Entry<Item, Integer> set : items.entrySet()) {
{
data.append(set.getKey().getId()).append(":").append(set.getValue()).append(";"); data.append(set.getKey().getId()).append(":").append(set.getValue()).append(";");
} }
@ -126,10 +107,8 @@ public class RoomBundleLayout extends SingleBundle
return super.getCatalogItems(); return super.getCatalogItems();
} }
public void loadItems(Room room) public void loadItems(Room room) {
{ if (this.room != null) {
if(this.room != null)
{
this.room.preventUnloading = false; this.room.preventUnloading = false;
} }
@ -139,25 +118,20 @@ public class RoomBundleLayout extends SingleBundle
this.loaded = true; this.loaded = true;
} }
public void buyRoom(Habbo habbo) public void buyRoom(Habbo habbo) {
{
this.buyRoom(habbo, habbo.getHabboInfo().getId(), habbo.getHabboInfo().getUsername()); this.buyRoom(habbo, habbo.getHabboInfo().getId(), habbo.getHabboInfo().getUsername());
} }
public void buyRoom(Habbo habbo, int userId, String userName) public void buyRoom(Habbo habbo, int userId, String userName) {
{ if (!this.loaded) {
if (!this.loaded)
{
this.loadItems(Emulator.getGameEnvironment().getRoomManager().loadRoom(this.roomId)); this.loadItems(Emulator.getGameEnvironment().getRoomManager().loadRoom(this.roomId));
} }
if (habbo != null) if (habbo != null) {
{
int count = Emulator.getGameEnvironment().getRoomManager().getRoomsForHabbo(habbo).size(); int count = Emulator.getGameEnvironment().getRoomManager().getRoomsForHabbo(habbo).size();
int max = habbo.getHabboStats().hasActiveClub() ? Emulator.getConfig().getInt("hotel.max.rooms.vip") : Emulator.getConfig().getInt("hotel.max.rooms.user"); int max = habbo.getHabboStats().hasActiveClub() ? Emulator.getConfig().getInt("hotel.max.rooms.vip") : Emulator.getConfig().getInt("hotel.max.rooms.user");
if (count >= max) if (count >= max) {
{
habbo.getClient().sendResponse(new CanCreateRoomComposer(count, max)); habbo.getClient().sendResponse(new CanCreateRoomComposer(count, max));
return; return;
} }
@ -168,31 +142,25 @@ public class RoomBundleLayout extends SingleBundle
this.room.save(); this.room.save();
for(HabboItem item : this.room.getFloorItems()) for (HabboItem item : this.room.getFloorItems()) {
{
item.run(); item.run();
} }
for(HabboItem item : this.room.getWallItems()) for (HabboItem item : this.room.getWallItems()) {
{
item.run(); item.run();
} }
this.getCatalogItems(); this.getCatalogItems();
int roomId = 0; int roomId = 0;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
{ try (PreparedStatement statement = connection.prepareStatement("INSERT INTO rooms (owner_id, owner_name, name, description, model, password, state, users_max, category, paper_floor, paper_wall, paper_landscape, thickness_wall, thickness_floor, moodlight_data, override_model) (SELECT ?, ?, name, description, model, password, state, users_max, category, paper_floor, paper_wall, paper_landscape, thickness_wall, thickness_floor, moodlight_data, override_model FROM rooms WHERE id = ?)", Statement.RETURN_GENERATED_KEYS)) {
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO rooms (owner_id, owner_name, name, description, model, password, state, users_max, category, paper_floor, paper_wall, paper_landscape, thickness_wall, thickness_floor, moodlight_data, override_model) (SELECT ?, ?, name, description, model, password, state, users_max, category, paper_floor, paper_wall, paper_landscape, thickness_wall, thickness_floor, moodlight_data, override_model FROM rooms WHERE id = ?)", Statement.RETURN_GENERATED_KEYS))
{
statement.setInt(1, userId); statement.setInt(1, userId);
statement.setString(2, userName); statement.setString(2, userName);
statement.setInt(3, this.room.getId()); statement.setInt(3, this.room.getId());
statement.execute(); statement.execute();
try (ResultSet set = statement.getGeneratedKeys()) try (ResultSet set = statement.getGeneratedKeys()) {
{ if (set.next()) {
if (set.next())
{
roomId = set.getInt(1); roomId = set.getInt(1);
} }
} }
@ -201,8 +169,7 @@ public class RoomBundleLayout extends SingleBundle
if (roomId == 0) if (roomId == 0)
return; return;
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO items (user_id, room_id, item_id, wall_pos, x, y, z, rot, extra_data, wired_data, limited_data, guild_id) (SELECT ?, ?, item_id, wall_pos, x, y, z, rot, extra_data, wired_data, ?, ? FROM items WHERE room_id = ?)", Statement.RETURN_GENERATED_KEYS)) try (PreparedStatement statement = connection.prepareStatement("INSERT INTO items (user_id, room_id, item_id, wall_pos, x, y, z, rot, extra_data, wired_data, limited_data, guild_id) (SELECT ?, ?, item_id, wall_pos, x, y, z, rot, extra_data, wired_data, ?, ? FROM items WHERE room_id = ?)", Statement.RETURN_GENERATED_KEYS)) {
{
statement.setInt(1, userId); statement.setInt(1, userId);
statement.setInt(2, roomId); statement.setInt(2, roomId);
statement.setString(3, "0:0"); statement.setString(3, "0:0");
@ -211,31 +178,23 @@ public class RoomBundleLayout extends SingleBundle
statement.execute(); statement.execute();
} }
if (this.room.hasCustomLayout()) if (this.room.hasCustomLayout()) {
{ try (PreparedStatement statement = connection.prepareStatement("INSERT INTO room_models_custom (id, name, door_x, door_y, door_dir, heightmap) (SELECT ?, ?, door_x, door_y, door_dir, heightmap FROM room_models_custom WHERE id = ? LIMIT 1)", Statement.RETURN_GENERATED_KEYS)) {
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO room_models_custom (id, name, door_x, door_y, door_dir, heightmap) (SELECT ?, ?, door_x, door_y, door_dir, heightmap FROM room_models_custom WHERE id = ? LIMIT 1)", Statement.RETURN_GENERATED_KEYS))
{
statement.setInt(1, roomId); statement.setInt(1, roomId);
statement.setString(2, "custom_" + roomId); statement.setString(2, "custom_" + roomId);
statement.setInt(3, this.room.getId()); statement.setInt(3, this.room.getId());
statement.execute(); statement.execute();
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
if (Emulator.getConfig().getBoolean("bundle.bots.enabled")) if (Emulator.getConfig().getBoolean("bundle.bots.enabled")) {
{ try (PreparedStatement statement = connection.prepareStatement("INSERT INTO bots (user_id, room_id, name, motto, figure, gender, x, y, z, chat_lines, chat_auto, chat_random, chat_delay, dance, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO bots (user_id, room_id, name, motto, figure, gender, x, y, z, chat_lines, chat_auto, chat_random, chat_delay, dance, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) synchronized (this.room.getCurrentBots()) {
{
synchronized (this.room.getCurrentBots())
{
statement.setInt(1, userId); statement.setInt(1, userId);
statement.setInt(2, roomId); statement.setInt(2, roomId);
for (Bot bot : this.room.getCurrentBots().valueCollection()) for (Bot bot : this.room.getCurrentBots().valueCollection()) {
{
statement.setString(3, bot.getName()); statement.setString(3, bot.getName());
statement.setString(4, bot.getMotto()); statement.setString(4, bot.getMotto());
statement.setString(5, bot.getFigure()); statement.setString(5, bot.getFigure());
@ -244,8 +203,7 @@ public class RoomBundleLayout extends SingleBundle
statement.setInt(8, bot.getRoomUnit().getY()); statement.setInt(8, bot.getRoomUnit().getY());
statement.setDouble(9, bot.getRoomUnit().getZ()); statement.setDouble(9, bot.getRoomUnit().getZ());
StringBuilder text = new StringBuilder(); StringBuilder text = new StringBuilder();
for (String s : bot.getChatLines()) for (String s : bot.getChatLines()) {
{
text.append(s).append("\r"); text.append(s).append("\r");
} }
statement.setString(10, text.toString()); statement.setString(10, text.toString());
@ -260,9 +218,7 @@ public class RoomBundleLayout extends SingleBundle
statement.executeBatch(); statement.executeBatch();
} }
} }
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
@ -279,8 +235,7 @@ public class RoomBundleLayout extends SingleBundle
keys.put("OWNER", r.getOwnerName()); keys.put("OWNER", r.getOwnerName());
keys.put("image", "${image.library.url}/notifications/room_bundle_" + this.getId() + ".png"); keys.put("image", "${image.library.url}/notifications/room_bundle_" + this.getId() + ".png");
if (habbo != null) if (habbo != null) {
{
habbo.getClient().sendResponse(new BubbleAlertComposer(BubbleAlertKeys.PURCHASING_ROOM.key, keys)); habbo.getClient().sendResponse(new BubbleAlertComposer(BubbleAlertKeys.PURCHASING_ROOM.key, keys));
} }
} }

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class SingleBundle extends CatalogPage public class SingleBundle extends CatalogPage {
{ public SingleBundle(ResultSet set) throws SQLException {
public SingleBundle(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("single_bundle"); message.appendString("single_bundle");
message.appendInt(3); message.appendInt(3);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class SoldLTDItemsLayout extends CatalogPage public class SoldLTDItemsLayout extends CatalogPage {
{ public SoldLTDItemsLayout(ResultSet set) throws SQLException {
public SoldLTDItemsLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("sold_ltd_items"); message.appendString("sold_ltd_items");
message.appendInt(3); message.appendInt(3);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -8,14 +8,12 @@ import java.sql.SQLException;
public class SpacesLayout extends CatalogPage { public class SpacesLayout extends CatalogPage {
public SpacesLayout(ResultSet set) throws SQLException public SpacesLayout(ResultSet set) throws SQLException {
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("spaces_new"); message.appendString("spaces_new");
message.appendInt(3); message.appendInt(3);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class TraxLayout extends CatalogPage public class TraxLayout extends CatalogPage {
{ public TraxLayout(ResultSet set) throws SQLException {
public TraxLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("soundmachine"); message.appendString("soundmachine");
message.appendInt(2); message.appendInt(2);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -8,14 +8,12 @@ import java.sql.SQLException;
public class TrophiesLayout extends CatalogPage { public class TrophiesLayout extends CatalogPage {
public TrophiesLayout(ResultSet set) throws SQLException public TrophiesLayout(ResultSet set) throws SQLException {
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("trophies"); message.appendString("trophies");
message.appendInt(3); message.appendInt(3);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class VipBuyLayout extends CatalogPage public class VipBuyLayout extends CatalogPage {
{ public VipBuyLayout(ResultSet set) throws SQLException {
public VipBuyLayout(ResultSet set) throws SQLException
{
super(set); super(set);
} }
@Override @Override
public void serialize(ServerMessage message) public void serialize(ServerMessage message) {
{
message.appendString("vip_buy"); message.appendString("vip_buy");
message.appendInt(3); message.appendInt(3);
message.appendString(super.getHeaderImage()); message.appendString(super.getHeaderImage());

View File

@ -25,8 +25,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class MarketPlace public class MarketPlace {
{
//Configuration. Loaded from database & updated accordingly. //Configuration. Loaded from database & updated accordingly.
public static boolean MARKETPLACE_ENABLED = true; public static boolean MARKETPLACE_ENABLED = true;
@ -34,22 +33,16 @@ public class MarketPlace
public static int MARKETPLACE_CURRENCY = 0; public static int MARKETPLACE_CURRENCY = 0;
public static THashSet<MarketPlaceOffer> getOwnOffers(Habbo habbo) public static THashSet<MarketPlaceOffer> getOwnOffers(Habbo habbo) {
{
THashSet<MarketPlaceOffer> offers = new THashSet<>(); THashSet<MarketPlaceOffer> offers = new THashSet<>();
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT items_base.type AS type, items.item_id AS base_item_id, items.limited_data AS ltd_data, marketplace_items.* FROM marketplace_items INNER JOIN items ON marketplace_items.item_id = items.id INNER JOIN items_base ON items.item_id = items_base.id WHERE marketplace_items.user_id = ?")) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT items_base.type AS type, items.item_id AS base_item_id, items.limited_data AS ltd_data, marketplace_items.* FROM marketplace_items INNER JOIN items ON marketplace_items.item_id = items.id INNER JOIN items_base ON items.item_id = items_base.id WHERE marketplace_items.user_id = ?")) {
{
statement.setInt(1, habbo.getHabboInfo().getId()); statement.setInt(1, habbo.getHabboInfo().getId());
try (ResultSet set = statement.executeQuery()) try (ResultSet set = statement.executeQuery()) {
{ while (set.next()) {
while (set.next())
{
offers.add(new MarketPlaceOffer(set, true)); offers.add(new MarketPlaceOffer(set, true));
} }
} }
} } catch (SQLException e) {
catch(SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
@ -57,57 +50,43 @@ public class MarketPlace
} }
public static void takeBackItem(Habbo habbo, int offerId) public static void takeBackItem(Habbo habbo, int offerId) {
{
MarketPlaceOffer offer = habbo.getInventory().getOffer(offerId); MarketPlaceOffer offer = habbo.getInventory().getOffer(offerId);
if (!Emulator.getPluginManager().fireEvent(new MarketPlaceItemCancelledEvent(offer)).isCancelled()) if (!Emulator.getPluginManager().fireEvent(new MarketPlaceItemCancelledEvent(offer)).isCancelled()) {
{
takeBackItem(habbo, offer); takeBackItem(habbo, offer);
} }
} }
private static void takeBackItem(Habbo habbo, MarketPlaceOffer offer) private static void takeBackItem(Habbo habbo, MarketPlaceOffer offer) {
{ if (offer != null && habbo.getInventory().getMarketplaceItems().contains(offer)) {
if(offer != null && habbo.getInventory().getMarketplaceItems().contains(offer))
{
RequestOffersEvent.cachedResults.clear(); RequestOffersEvent.cachedResults.clear();
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
{ try (PreparedStatement ownerCheck = connection.prepareStatement("SELECT user_id FROM marketplace_items WHERE id = ?")) {
try (PreparedStatement ownerCheck = connection.prepareStatement("SELECT user_id FROM marketplace_items WHERE id = ?"))
{
ownerCheck.setInt(1, offer.getOfferId()); ownerCheck.setInt(1, offer.getOfferId());
try (ResultSet ownerSet = ownerCheck.executeQuery()) try (ResultSet ownerSet = ownerCheck.executeQuery()) {
{
ownerSet.last(); ownerSet.last();
if (ownerSet.getRow() == 0) if (ownerSet.getRow() == 0) {
{
return; return;
} }
try (PreparedStatement statement = connection.prepareStatement("DELETE FROM marketplace_items WHERE id = ? AND state != 2")) try (PreparedStatement statement = connection.prepareStatement("DELETE FROM marketplace_items WHERE id = ? AND state != 2")) {
{
statement.setInt(1, offer.getOfferId()); statement.setInt(1, offer.getOfferId());
int count = statement.executeUpdate(); int count = statement.executeUpdate();
if (count != 0) if (count != 0) {
{
habbo.getInventory().removeMarketplaceOffer(offer); habbo.getInventory().removeMarketplaceOffer(offer);
try (PreparedStatement updateItems = connection.prepareStatement("UPDATE items SET user_id = ? WHERE id = ? LIMIT 1")) try (PreparedStatement updateItems = connection.prepareStatement("UPDATE items SET user_id = ? WHERE id = ? LIMIT 1")) {
{
updateItems.setInt(1, habbo.getHabboInfo().getId()); updateItems.setInt(1, habbo.getHabboInfo().getId());
updateItems.setInt(2, offer.getSoldItemId()); updateItems.setInt(2, offer.getSoldItemId());
updateItems.execute(); updateItems.execute();
try (PreparedStatement selectItem = connection.prepareStatement("SELECT * FROM items WHERE id = ? LIMIT 1")) try (PreparedStatement selectItem = connection.prepareStatement("SELECT * FROM items WHERE id = ? LIMIT 1")) {
{
selectItem.setInt(1, offer.getSoldItemId()); selectItem.setInt(1, offer.getSoldItemId());
try (ResultSet set = selectItem.executeQuery()) try (ResultSet set = selectItem.executeQuery()) {
{ while (set.next()) {
while (set.next())
{
HabboItem item = Emulator.getGameEnvironment().getItemManager().loadHabboItem(set); HabboItem item = Emulator.getGameEnvironment().getItemManager().loadHabboItem(set);
habbo.getInventory().getItemsComponent().addItem(item); habbo.getInventory().getItemsComponent().addItem(item);
habbo.getClient().sendResponse(new MarketplaceCancelSaleComposer(offer, true)); habbo.getClient().sendResponse(new MarketplaceCancelSaleComposer(offer, true));
@ -121,9 +100,7 @@ public class MarketPlace
} }
} }
} }
} } catch (SQLException e) {
catch(SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
habbo.getClient().sendResponse(new MarketplaceCancelSaleComposer(offer, false)); habbo.getClient().sendResponse(new MarketplaceCancelSaleComposer(offer, false));
} }
@ -134,23 +111,19 @@ public class MarketPlace
public static List<MarketPlaceOffer> getOffers(int minPrice, int maxPrice, String search, int sort) { public static List<MarketPlaceOffer> getOffers(int minPrice, int maxPrice, String search, int sort) {
List<MarketPlaceOffer> offers = new ArrayList<>(10); List<MarketPlaceOffer> offers = new ArrayList<>(10);
String query = "SELECT B.* FROM marketplace_items a INNER JOIN (SELECT b.item_id AS base_item_id, b.limited_data AS ltd_data, marketplace_items.*, AVG(price) as avg, MIN(marketplace_items.price) as minPrice, MAX(marketplace_items.price) as maxPrice, COUNT(*) as number, (SELECT COUNT(*) FROM marketplace_items c INNER JOIN items as items_b ON c.item_id = items_b.id WHERE state = 2 AND items_b.item_id = base_item_id AND DATE(from_unixtime(sold_timestamp)) = CURDATE()) as sold_count_today FROM marketplace_items INNER JOIN items b ON marketplace_items.item_id = b.id INNER JOIN items_base bi ON b.item_id = bi.id WHERE price = (SELECT MIN(e.price) FROM marketplace_items e, items d WHERE e.item_id = d.id AND d.item_id = b.item_id AND e.state = 1 AND e.timestamp > ? GROUP BY d.item_id) AND state = 1 AND timestamp > ?"; String query = "SELECT B.* FROM marketplace_items a INNER JOIN (SELECT b.item_id AS base_item_id, b.limited_data AS ltd_data, marketplace_items.*, AVG(price) as avg, MIN(marketplace_items.price) as minPrice, MAX(marketplace_items.price) as maxPrice, COUNT(*) as number, (SELECT COUNT(*) FROM marketplace_items c INNER JOIN items as items_b ON c.item_id = items_b.id WHERE state = 2 AND items_b.item_id = base_item_id AND DATE(from_unixtime(sold_timestamp)) = CURDATE()) as sold_count_today FROM marketplace_items INNER JOIN items b ON marketplace_items.item_id = b.id INNER JOIN items_base bi ON b.item_id = bi.id WHERE price = (SELECT MIN(e.price) FROM marketplace_items e, items d WHERE e.item_id = d.id AND d.item_id = b.item_id AND e.state = 1 AND e.timestamp > ? GROUP BY d.item_id) AND state = 1 AND timestamp > ?";
if (minPrice > 0) if (minPrice > 0) {
{
query += " AND CEIL(price + (price / 100)) >= " + minPrice; query += " AND CEIL(price + (price / 100)) >= " + minPrice;
} }
if(maxPrice > 0 && maxPrice > minPrice) if (maxPrice > 0 && maxPrice > minPrice) {
{
query += " AND CEIL(price + (price / 100)) <= " + maxPrice; query += " AND CEIL(price + (price / 100)) <= " + maxPrice;
} }
if(search.length() > 0) if (search.length() > 0) {
{
query += " AND bi.public_name LIKE ?"; query += " AND bi.public_name LIKE ?";
} }
query += " GROUP BY base_item_id, ltd_data"; query += " GROUP BY base_item_id, ltd_data";
switch (sort) switch (sort) {
{
case 6: case 6:
query += " ORDER BY number ASC"; query += " ORDER BY number ASC";
break; break;
@ -178,23 +151,18 @@ public class MarketPlace
query += " LIMIT 100"; query += " LIMIT 100";
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement(query)) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement(query)) {
{
statement.setInt(1, Emulator.getIntUnixTimestamp() - 172800); statement.setInt(1, Emulator.getIntUnixTimestamp() - 172800);
statement.setInt(2, Emulator.getIntUnixTimestamp() - 172800); statement.setInt(2, Emulator.getIntUnixTimestamp() - 172800);
if (search.length() > 0) if (search.length() > 0)
statement.setString(3, "%" + search + "%"); statement.setString(3, "%" + search + "%");
try (ResultSet set = statement.executeQuery()) try (ResultSet set = statement.executeQuery()) {
{ while (set.next()) {
while (set.next())
{
offers.add(new MarketPlaceOffer(set, false)); offers.add(new MarketPlaceOffer(set, false));
} }
} }
} } catch (SQLException e) {
catch(SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
@ -202,24 +170,20 @@ public class MarketPlace
} }
public static void serializeItemInfo(int itemId, ServerMessage message) public static void serializeItemInfo(int itemId, ServerMessage message) {
{ try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT avg(price) as price, COUNT(*) as sold, (datediff(NOW(), DATE(from_unixtime(timestamp)))) as day FROM marketplace_items INNER JOIN items ON items.id = marketplace_items.item_id INNER JOIN items_base ON items.item_id = items_base.id WHERE items.limited_data = '0:0' AND state = 2 AND items_base.sprite_id = ? AND DATE(from_unixtime(timestamp)) >= NOW() - INTERVAL 30 DAY GROUP BY DATE(from_unixtime(timestamp))")) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT avg(price) as price, COUNT(*) as sold, (datediff(NOW(), DATE(from_unixtime(timestamp)))) as day FROM marketplace_items INNER JOIN items ON items.id = marketplace_items.item_id INNER JOIN items_base ON items.item_id = items_base.id WHERE items.limited_data = '0:0' AND state = 2 AND items_base.sprite_id = ? AND DATE(from_unixtime(timestamp)) >= NOW() - INTERVAL 30 DAY GROUP BY DATE(from_unixtime(timestamp))"))
{
statement.setInt(1, itemId); statement.setInt(1, itemId);
message.appendInt(avarageLastXDays(itemId, 7)); message.appendInt(avarageLastXDays(itemId, 7));
message.appendInt(itemsOnSale(itemId)); message.appendInt(itemsOnSale(itemId));
message.appendInt(30); message.appendInt(30);
try (ResultSet set = statement.executeQuery()) try (ResultSet set = statement.executeQuery()) {
{
set.last(); set.last();
message.appendInt(set.getRow()); message.appendInt(set.getRow());
set.beforeFirst(); set.beforeFirst();
while (set.next()) while (set.next()) {
{
message.appendInt(-set.getInt("day")); message.appendInt(-set.getInt("day"));
message.appendInt(MarketPlace.calculateCommision(set.getInt("price"))); message.appendInt(MarketPlace.calculateCommision(set.getInt("price")));
message.appendInt(set.getInt("sold")); message.appendInt(set.getInt("sold"));
@ -228,29 +192,22 @@ public class MarketPlace
message.appendInt(1); message.appendInt(1);
message.appendInt(itemId); message.appendInt(itemId);
} } catch (SQLException e) {
catch(SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
public static int itemsOnSale(int baseItemId) public static int itemsOnSale(int baseItemId) {
{
int number = 0; int number = 0;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) as number, AVG(price) as avg FROM marketplace_items INNER JOIN items ON marketplace_items.item_id = items.id INNER JOIN items_base ON items.item_id = items_base.id WHERE state = 1 AND timestamp >= ? AND items_base.sprite_id = ?")) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) as number, AVG(price) as avg FROM marketplace_items INNER JOIN items ON marketplace_items.item_id = items.id INNER JOIN items_base ON items.item_id = items_base.id WHERE state = 1 AND timestamp >= ? AND items_base.sprite_id = ?")) {
{
statement.setInt(1, Emulator.getIntUnixTimestamp() - 172800); statement.setInt(1, Emulator.getIntUnixTimestamp() - 172800);
statement.setInt(2, baseItemId); statement.setInt(2, baseItemId);
try (ResultSet set = statement.executeQuery()) try (ResultSet set = statement.executeQuery()) {
{
set.first(); set.first();
number = set.getInt("number"); number = set.getInt("number");
} }
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
@ -258,22 +215,17 @@ public class MarketPlace
} }
private static int avarageLastXDays(int baseItemId, int days) private static int avarageLastXDays(int baseItemId, int days) {
{
int avg = 0; int avg = 0;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT AVG(price) as avg FROM marketplace_items INNER JOIN items ON marketplace_items.item_id = items.id INNER JOIN items_base ON items.item_id = items_base.id WHERE state = 2 AND DATE(from_unixtime(timestamp)) >= NOW() - INTERVAL ? DAY AND items_base.sprite_id = ?")) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT AVG(price) as avg FROM marketplace_items INNER JOIN items ON marketplace_items.item_id = items.id INNER JOIN items_base ON items.item_id = items_base.id WHERE state = 2 AND DATE(from_unixtime(timestamp)) >= NOW() - INTERVAL ? DAY AND items_base.sprite_id = ?")) {
{
statement.setInt(1, days); statement.setInt(1, days);
statement.setInt(2, baseItemId); statement.setInt(2, baseItemId);
try (ResultSet set = statement.executeQuery()) try (ResultSet set = statement.executeQuery()) {
{
set.first(); set.first();
avg = set.getInt("avg"); avg = set.getInt("avg");
} }
} } catch (SQLException e) {
catch(SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
@ -281,40 +233,26 @@ public class MarketPlace
} }
public static void buyItem(int offerId, GameClient client) public static void buyItem(int offerId, GameClient client) {
{
RequestOffersEvent.cachedResults.clear(); RequestOffersEvent.cachedResults.clear();
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
{ try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM marketplace_items WHERE id = ? LIMIT 1")) {
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM marketplace_items WHERE id = ? LIMIT 1"))
{
statement.setInt(1, offerId); statement.setInt(1, offerId);
try (ResultSet set = statement.executeQuery()) try (ResultSet set = statement.executeQuery()) {
{ if (set.next()) {
if (set.next()) try (PreparedStatement itemStatement = connection.prepareStatement("SELECT * FROM items WHERE id = ? LIMIT 1")) {
{
try (PreparedStatement itemStatement = connection.prepareStatement("SELECT * FROM items WHERE id = ? LIMIT 1"))
{
itemStatement.setInt(1, set.getInt("item_id")); itemStatement.setInt(1, set.getInt("item_id"));
try (ResultSet itemSet = itemStatement.executeQuery()) try (ResultSet itemSet = itemStatement.executeQuery()) {
{
itemSet.first(); itemSet.first();
if (itemSet.getRow() > 0) if (itemSet.getRow() > 0) {
{
int price = MarketPlace.calculateCommision(set.getInt("price")); int price = MarketPlace.calculateCommision(set.getInt("price"));
if (set.getInt("state") != 1) if (set.getInt("state") != 1) {
{
sendErrorMessage(client, set.getInt("item_id"), offerId); sendErrorMessage(client, set.getInt("item_id"), offerId);
} } else if ((MARKETPLACE_CURRENCY == 0 && price > client.getHabbo().getHabboInfo().getCredits()) || (MARKETPLACE_CURRENCY > 0 && price > client.getHabbo().getHabboInfo().getCurrencyAmount(MARKETPLACE_CURRENCY))) {
else if ((MARKETPLACE_CURRENCY == 0 && price > client.getHabbo().getHabboInfo().getCredits()) || (MARKETPLACE_CURRENCY > 0 && price > client.getHabbo().getHabboInfo().getCurrencyAmount(MARKETPLACE_CURRENCY)))
{
client.sendResponse(new MarketplaceBuyErrorComposer(MarketplaceBuyErrorComposer.NOT_ENOUGH_CREDITS, 0, offerId, price)); client.sendResponse(new MarketplaceBuyErrorComposer(MarketplaceBuyErrorComposer.NOT_ENOUGH_CREDITS, 0, offerId, price));
} } else {
else try (PreparedStatement updateOffer = connection.prepareStatement("UPDATE marketplace_items SET state = 2, sold_timestamp = ? WHERE id = ?")) {
{
try (PreparedStatement updateOffer = connection.prepareStatement("UPDATE marketplace_items SET state = 2, sold_timestamp = ? WHERE id = ?"))
{
updateOffer.setInt(1, Emulator.getIntUnixTimestamp()); updateOffer.setInt(1, Emulator.getIntUnixTimestamp());
updateOffer.setInt(2, offerId); updateOffer.setInt(2, offerId);
updateOffer.execute(); updateOffer.execute();
@ -323,8 +261,7 @@ public class MarketPlace
HabboItem item = Emulator.getGameEnvironment().getItemManager().loadHabboItem(itemSet); HabboItem item = Emulator.getGameEnvironment().getItemManager().loadHabboItem(itemSet);
MarketPlaceItemSoldEvent event = new MarketPlaceItemSoldEvent(habbo, client.getHabbo(), item, set.getInt("price")); MarketPlaceItemSoldEvent event = new MarketPlaceItemSoldEvent(habbo, client.getHabbo(), item, set.getInt("price"));
if (Emulator.getPluginManager().fireEvent(event).isCancelled()) if (Emulator.getPluginManager().fireEvent(event).isCancelled()) {
{
return; return;
} }
event.price = calculateCommision(event.price); event.price = calculateCommision(event.price);
@ -335,12 +272,9 @@ public class MarketPlace
client.getHabbo().getInventory().getItemsComponent().addItem(item); client.getHabbo().getInventory().getItemsComponent().addItem(item);
if (MARKETPLACE_CURRENCY == 0) if (MARKETPLACE_CURRENCY == 0) {
{
client.getHabbo().getHabboInfo().addCredits(-event.price); client.getHabbo().getHabboInfo().addCredits(-event.price);
} } else {
else
{
client.getHabbo().givePoints(MARKETPLACE_CURRENCY, -event.price); client.getHabbo().givePoints(MARKETPLACE_CURRENCY, -event.price);
} }
@ -349,8 +283,7 @@ public class MarketPlace
client.sendResponse(new InventoryRefreshComposer()); client.sendResponse(new InventoryRefreshComposer());
client.sendResponse(new MarketplaceBuyErrorComposer(MarketplaceBuyErrorComposer.REFRESH, 0, offerId, price)); client.sendResponse(new MarketplaceBuyErrorComposer(MarketplaceBuyErrorComposer.REFRESH, 0, offerId, price));
if (habbo != null) if (habbo != null) {
{
habbo.getInventory().getOffer(offerId).setState(MarketPlaceState.SOLD); habbo.getInventory().getOffer(offerId).setState(MarketPlaceState.SOLD);
} }
} }
@ -360,16 +293,13 @@ public class MarketPlace
} }
} }
} }
} } catch (SQLException e) {
catch(SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
public static void sendErrorMessage(GameClient client, int baseItemId, int offerId) throws SQLException public static void sendErrorMessage(GameClient client, int baseItemId, int offerId) {
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT marketplace_items.*, COUNT( * ) AS count\n" + try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT marketplace_items.*, COUNT( * ) AS count\n" +
"FROM marketplace_items\n" + "FROM marketplace_items\n" +
"INNER JOIN items ON marketplace_items.item_id = items.id\n" + "INNER JOIN items ON marketplace_items.item_id = items.id\n" +
@ -379,26 +309,24 @@ public class MarketPlace
"FROM items_base\n" + "FROM items_base\n" +
"WHERE items_base.id = ? LIMIT 1)\n" + "WHERE items_base.id = ? LIMIT 1)\n" +
"ORDER BY price ASC\n" + "ORDER BY price ASC\n" +
"LIMIT 1")) "LIMIT 1")) {
{
statement.setInt(1, baseItemId); statement.setInt(1, baseItemId);
try (ResultSet countSet = statement.executeQuery()) try (ResultSet countSet = statement.executeQuery()) {
{
countSet.last(); countSet.last();
if (countSet.getRow() == 0) if (countSet.getRow() == 0)
client.sendResponse(new MarketplaceBuyErrorComposer(MarketplaceBuyErrorComposer.SOLD_OUT, 0, offerId, 0)); client.sendResponse(new MarketplaceBuyErrorComposer(MarketplaceBuyErrorComposer.SOLD_OUT, 0, offerId, 0));
else else {
{
countSet.first(); countSet.first();
client.sendResponse(new MarketplaceBuyErrorComposer(MarketplaceBuyErrorComposer.UPDATES, countSet.getInt("count"), countSet.getInt("id"), MarketPlace.calculateCommision(countSet.getInt("price")))); client.sendResponse(new MarketplaceBuyErrorComposer(MarketplaceBuyErrorComposer.UPDATES, countSet.getInt("count"), countSet.getInt("id"), MarketPlace.calculateCommision(countSet.getInt("price"))));
} }
} }
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
} }
} }
public static boolean sellItem(GameClient client, HabboItem item, int price) public static boolean sellItem(GameClient client, HabboItem item, int price) {
{
if (item == null || client == null) if (item == null || client == null)
return false; return false;
@ -406,14 +334,12 @@ public class MarketPlace
return false; return false;
MarketPlaceItemOfferedEvent event = new MarketPlaceItemOfferedEvent(client.getHabbo(), item, price); MarketPlaceItemOfferedEvent event = new MarketPlaceItemOfferedEvent(client.getHabbo(), item, price);
if (Emulator.getPluginManager().fireEvent(event).isCancelled()) if (Emulator.getPluginManager().fireEvent(event).isCancelled()) {
{
return false; return false;
} }
RequestOffersEvent.cachedResults.clear(); RequestOffersEvent.cachedResults.clear();
try
{
client.sendResponse(new RemoveHabboItemComposer(event.item.getGiftAdjustedId())); client.sendResponse(new RemoveHabboItemComposer(event.item.getGiftAdjustedId()));
client.sendResponse(new InventoryRefreshComposer()); client.sendResponse(new InventoryRefreshComposer());
@ -425,27 +351,19 @@ public class MarketPlace
item.setUserId(-1); item.setUserId(-1);
item.needsUpdate(true); item.needsUpdate(true);
Emulator.getThreading().run(item); Emulator.getThreading().run(item);
}
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e);
}
return true; return true;
} }
public static void getCredits(GameClient client) public static void getCredits(GameClient client) {
{
int credits = 0; int credits = 0;
THashSet<MarketPlaceOffer> offers = new THashSet<>(); THashSet<MarketPlaceOffer> offers = new THashSet<>();
offers.addAll(client.getHabbo().getInventory().getMarketplaceItems()); offers.addAll(client.getHabbo().getInventory().getMarketplaceItems());
for(MarketPlaceOffer offer : offers) for (MarketPlaceOffer offer : offers) {
{ if (offer.getState().equals(MarketPlaceState.SOLD)) {
if(offer.getState().equals(MarketPlaceState.SOLD))
{
client.getHabbo().getInventory().removeMarketplaceOffer(offer); client.getHabbo().getInventory().removeMarketplaceOffer(offer);
credits += offer.getPrice(); credits += offer.getPrice();
removeUser(offer); removeUser(offer);
@ -456,34 +374,26 @@ public class MarketPlace
offers.clear(); offers.clear();
if (MARKETPLACE_CURRENCY == 0) if (MARKETPLACE_CURRENCY == 0) {
{
client.getHabbo().getHabboInfo().addCredits(credits); client.getHabbo().getHabboInfo().addCredits(credits);
} } else {
else
{
client.getHabbo().givePoints(MARKETPLACE_CURRENCY, credits); client.getHabbo().givePoints(MARKETPLACE_CURRENCY, credits);
} }
client.sendResponse(new UserCreditsComposer(client.getHabbo())); client.sendResponse(new UserCreditsComposer(client.getHabbo()));
} }
private static void removeUser(MarketPlaceOffer offer) private static void removeUser(MarketPlaceOffer offer) {
{ try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE marketplace_items SET user_id = ? WHERE id = ?")) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE marketplace_items SET user_id = ? WHERE id = ?"))
{
statement.setInt(1, -1); statement.setInt(1, -1);
statement.setInt(2, offer.getOfferId()); statement.setInt(2, offer.getOfferId());
statement.execute(); statement.execute();
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
public static int calculateCommision(int price) public static int calculateCommision(int price) {
{
return price + (int) Math.ceil(price / 100.0); return price + (int) Math.ceil(price / 100.0);
} }
} }

View File

@ -8,8 +8,9 @@ import com.eu.habbo.habbohotel.users.HabboItem;
import java.sql.*; import java.sql.*;
public class MarketPlaceOffer implements Runnable public class MarketPlaceOffer implements Runnable {
{ public int avarage;
public int count;
private int offerId; private int offerId;
private Item baseItem; private Item baseItem;
private int itemId; private int itemId;
@ -21,11 +22,7 @@ public class MarketPlaceOffer implements Runnable
private MarketPlaceState state = MarketPlaceState.OPEN; private MarketPlaceState state = MarketPlaceState.OPEN;
private boolean needsUpdate = false; private boolean needsUpdate = false;
public int avarage; public MarketPlaceOffer(ResultSet set, boolean privateOffer) throws SQLException {
public int count;
public MarketPlaceOffer(ResultSet set, boolean privateOffer) throws SQLException
{
this.offerId = set.getInt("id"); this.offerId = set.getInt("id");
this.price = set.getInt("price"); this.price = set.getInt("price");
this.timestamp = set.getInt("timestamp"); this.timestamp = set.getInt("timestamp");
@ -34,33 +31,28 @@ public class MarketPlaceOffer implements Runnable
this.state = MarketPlaceState.getType(set.getInt("state")); this.state = MarketPlaceState.getType(set.getInt("state"));
this.itemId = set.getInt("item_id"); this.itemId = set.getInt("item_id");
if(!set.getString("ltd_data").split(":")[1].equals("0")) if (!set.getString("ltd_data").split(":")[1].equals("0")) {
{
this.limitedStack = Integer.valueOf(set.getString("ltd_data").split(":")[0]); this.limitedStack = Integer.valueOf(set.getString("ltd_data").split(":")[0]);
this.limitedNumber = Integer.valueOf(set.getString("ltd_data").split(":")[1]); this.limitedNumber = Integer.valueOf(set.getString("ltd_data").split(":")[1]);
} }
if(!privateOffer) if (!privateOffer) {
{
this.avarage = set.getInt("avg"); this.avarage = set.getInt("avg");
this.count = set.getInt("number"); this.count = set.getInt("number");
this.price = set.getInt("minPrice"); this.price = set.getInt("minPrice");
} }
} }
public MarketPlaceOffer(HabboItem item, int price, Habbo habbo) throws SQLException public MarketPlaceOffer(HabboItem item, int price, Habbo habbo) {
{
this.price = price; this.price = price;
this.baseItem = item.getBaseItem(); this.baseItem = item.getBaseItem();
this.itemId = item.getId(); this.itemId = item.getId();
if(item.getLimitedSells() > 0) if (item.getLimitedSells() > 0) {
{
this.limitedNumber = item.getLimitedSells(); this.limitedNumber = item.getLimitedSells();
this.limitedStack = item.getLimitedStack(); this.limitedStack = item.getLimitedStack();
} }
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO marketplace_items (item_id, user_id, price, timestamp, state) VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO marketplace_items (item_id, user_id, price, timestamp, state) VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
{
statement.setInt(1, item.getId()); statement.setInt(1, item.getId());
statement.setInt(2, habbo.getHabboInfo().getId()); statement.setInt(2, habbo.getHabboInfo().getId());
statement.setInt(3, this.price); statement.setInt(3, this.price);
@ -68,115 +60,18 @@ public class MarketPlaceOffer implements Runnable
statement.setString(5, this.state.getState() + ""); statement.setString(5, this.state.getState() + "");
statement.execute(); statement.execute();
try (ResultSet id = statement.getGeneratedKeys()) try (ResultSet id = statement.getGeneratedKeys()) {
{ while (id.next()) {
while (id.next())
{
this.offerId = id.getInt(1); this.offerId = id.getInt(1);
} }
} }
} } catch (SQLException e) {
}
public int getOfferId()
{
return this.offerId;
}
public void setOfferId(int offerId)
{
this.offerId = offerId;
}
public int getItemId()
{
return this.baseItem.getSpriteId();
}
public int getPrice()
{
return this.price;
}
public MarketPlaceState getState()
{
return this.state;
}
public void setState(MarketPlaceState state)
{
this.state = state;
}
public int getTimestamp()
{
return this.timestamp;
}
public int getSoldTimestamp()
{
return this.soldTimestamp;
}
public void setSoldTimestamp(int soldTimestamp)
{
this.soldTimestamp = soldTimestamp;
}
public int getLimitedStack()
{
return this.limitedStack;
}
public int getLimitedNumber()
{
return this.limitedNumber;
}
public int getSoldItemId()
{
return this.itemId;
}
public void needsUpdate(boolean value)
{
this.needsUpdate = value;
}
public int getType()
{
if (this.limitedStack > 0)
{
return 3;
}
return this.baseItem.getType().equals(FurnitureType.WALL) ? 2 : 1;
}
@Override
public void run()
{
if(this.needsUpdate)
{
this.needsUpdate = false;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE marketplace_items SET state = ?, sold_timestamp = ? WHERE id = ?"))
{
statement.setInt(1, this.state.getState());
statement.setInt(2, this.soldTimestamp);
statement.setInt(3, this.offerId);
statement.execute();
}
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
}
public static void insert(MarketPlaceOffer offer, Habbo habbo) public static void insert(MarketPlaceOffer offer, Habbo habbo) {
{ try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO marketplace_items VALUES (?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO marketplace_items VALUES (?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS))
{
statement.setInt(1, offer.getItemId()); statement.setInt(1, offer.getItemId());
statement.setInt(2, habbo.getHabboInfo().getId()); statement.setInt(2, habbo.getHabboInfo().getId());
statement.setInt(3, offer.getPrice()); statement.setInt(3, offer.getPrice());
@ -185,17 +80,88 @@ public class MarketPlaceOffer implements Runnable
statement.setString(6, offer.getState().getState() + ""); statement.setString(6, offer.getState().getState() + "");
statement.execute(); statement.execute();
try (ResultSet id = statement.getGeneratedKeys()) try (ResultSet id = statement.getGeneratedKeys()) {
{ while (id.next()) {
while (id.next())
{
offer.setOfferId(id.getInt(1)); offer.setOfferId(id.getInt(1));
} }
} }
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
} }
catch (SQLException e) }
{
public int getOfferId() {
return this.offerId;
}
public void setOfferId(int offerId) {
this.offerId = offerId;
}
public int getItemId() {
return this.baseItem.getSpriteId();
}
public int getPrice() {
return this.price;
}
public MarketPlaceState getState() {
return this.state;
}
public void setState(MarketPlaceState state) {
this.state = state;
}
public int getTimestamp() {
return this.timestamp;
}
public int getSoldTimestamp() {
return this.soldTimestamp;
}
public void setSoldTimestamp(int soldTimestamp) {
this.soldTimestamp = soldTimestamp;
}
public int getLimitedStack() {
return this.limitedStack;
}
public int getLimitedNumber() {
return this.limitedNumber;
}
public int getSoldItemId() {
return this.itemId;
}
public void needsUpdate(boolean value) {
this.needsUpdate = value;
}
public int getType() {
if (this.limitedStack > 0) {
return 3;
}
return this.baseItem.getType().equals(FurnitureType.WALL) ? 2 : 1;
}
@Override
public void run() {
if (this.needsUpdate) {
this.needsUpdate = false;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE marketplace_items SET state = ?, sold_timestamp = ? WHERE id = ?")) {
statement.setInt(1, this.state.getState());
statement.setInt(2, this.soldTimestamp);
statement.setInt(3, this.offerId);
statement.execute();
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }
} }
}

View File

@ -1,7 +1,6 @@
package com.eu.habbo.habbohotel.catalog.marketplace; package com.eu.habbo.habbohotel.catalog.marketplace;
public enum MarketPlaceState public enum MarketPlaceState {
{
OPEN(1), OPEN(1),
@ -13,27 +12,25 @@ public enum MarketPlaceState
private final int state; private final int state;
MarketPlaceState(int state) MarketPlaceState(int state) {
{
this.state = state; this.state = state;
} }
public int getState() public static MarketPlaceState getType(int type) {
{ switch (type) {
return this.state; case 1:
} return OPEN;
case 2:
return SOLD;
public static MarketPlaceState getType(int type) case 3:
{ return CLOSED;
switch(type)
{
case 1: return OPEN;
case 2: return SOLD;
case 3: return CLOSED;
} }
return CLOSED; return CLOSED;
} }
public int getState() {
return this.state;
}
} }

View File

@ -3,15 +3,12 @@ package com.eu.habbo.habbohotel.commands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.catalog.CatalogManager; import com.eu.habbo.habbohotel.catalog.CatalogManager;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.messages.outgoing.generic.alerts.GenericAlertComposer;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
public class AboutCommand extends Command public class AboutCommand extends Command {
{ public AboutCommand() {
public AboutCommand()
{
super(null, new String[]{"about", "info", "online", "server"}); super(null, new String[]{"about", "info", "online", "server"});
} }
@ -27,8 +24,7 @@ public class AboutCommand extends Command
String message = "<b>" + Emulator.version + "</b>\r\n"; String message = "<b>" + Emulator.version + "</b>\r\n";
if (Emulator.getConfig().getBoolean("info.shown", true)) if (Emulator.getConfig().getBoolean("info.shown", true)) {
{
message += "<b>Hotel Statistics</b>\r" + message += "<b>Hotel Statistics</b>\r" +
"- Online Users: " + Emulator.getGameEnvironment().getHabboManager().getOnlineCount() + "\r" + "- Online Users: " + Emulator.getGameEnvironment().getHabboManager().getOnlineCount() + "\r" +
"- Active Rooms: " + Emulator.getGameEnvironment().getRoomManager().getActiveRooms().size() + "\r" + "- Active Rooms: " + Emulator.getGameEnvironment().getRoomManager().getActiveRooms().size() + "\r" +

View File

@ -0,0 +1,59 @@
package com.eu.habbo.habbohotel.commands;
import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.items.YoutubeManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class AddYoutubePlaylistCommand extends Command {
public AddYoutubePlaylistCommand() {
super("cmd_add_youtube_playlist", Emulator.getTexts().getValue("commands.keys.cmd_add_youtube_playlist").split(";"));
}
@Override
public boolean handle(GameClient gameClient, String[] params) throws Exception {
if (params.length < 3) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_add_youtube_playlist.usage"));
return true;
}
int itemId;
try {
itemId = Integer.valueOf(params[1]);
} catch (NumberFormatException e) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_add_youtube_playlist.no_base_item"));
return true;
}
if (Emulator.getGameEnvironment().getItemManager().getItem(itemId) == null) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_add_youtube_playlist.no_base_item"));
return true;
}
YoutubeManager.YoutubePlaylist playlist = Emulator.getGameEnvironment().getItemManager().getYoutubeManager().getPlaylistDataById(params[2]);
if (playlist == null) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_add_youtube_playlist.failed_playlist"));
return true;
}
Emulator.getGameEnvironment().getItemManager().getYoutubeManager().addPlaylistToItem(Integer.valueOf(params[1]), playlist);
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO `youtube_playlists` (`item_id`, `playlist_id`) VALUES (?, ?)")) {
statement.setInt(1, itemId);
statement.setString(2, params[2]);
statement.execute();
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_add_youtube_playlist"));
return true;
}
}

View File

@ -4,25 +4,20 @@ import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles; import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.messages.outgoing.generic.alerts.GenericAlertComposer;
public class AlertCommand extends Command { public class AlertCommand extends Command {
public AlertCommand() public AlertCommand() {
{
super("cmd_alert", Emulator.getTexts().getValue("commands.keys.cmd_alert").split(";")); super("cmd_alert", Emulator.getTexts().getValue("commands.keys.cmd_alert").split(";"));
} }
@Override @Override
public boolean handle(GameClient gameClient, String[] params) public boolean handle(GameClient gameClient, String[] params) {
{ if (params.length < 2) {
if(params.length < 2)
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_alert.forgot_username"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_alert.forgot_username"), RoomChatMessageBubbles.ALERT);
return true; return true;
} }
if(params.length < 3) if (params.length < 3) {
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_alert.forgot_message"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_alert.forgot_message"), RoomChatMessageBubbles.ALERT);
return true; return true;
} }
@ -30,8 +25,7 @@ public class AlertCommand extends Command {
String targetUsername = params[1]; String targetUsername = params[1];
StringBuilder message = new StringBuilder(); StringBuilder message = new StringBuilder();
for(int i = 2; i < params.length; i++) for (int i = 2; i < params.length; i++) {
{
message.append(params[i]).append(" "); message.append(params[i]).append(" ");
} }

View File

@ -8,63 +8,50 @@ import com.eu.habbo.messages.outgoing.users.UserPerksComposer;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
public class AllowTradingCommand extends Command public class AllowTradingCommand extends Command {
{ public AllowTradingCommand() {
public AllowTradingCommand()
{
super("cmd_allow_trading", Emulator.getTexts().getValue("commands.keys.cmd_allow_trading").split(";")); super("cmd_allow_trading", Emulator.getTexts().getValue("commands.keys.cmd_allow_trading").split(";"));
} }
@Override @Override
public boolean handle(GameClient gameClient, String[] params) throws Exception public boolean handle(GameClient gameClient, String[] params) throws Exception {
{ if (params.length == 1) {
if (params.length == 1)
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_allow_trading.forgot_username")); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_allow_trading.forgot_username"));
return true; return true;
} }
if (params.length == 2) if (params.length == 2) {
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_allow_trading.forgot_trade").replace("%username%", params[1])); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_allow_trading.forgot_trade").replace("%username%", params[1]));
return true; return true;
} }
if (params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes")) || params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.no"))) if (params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes")) || params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.no"))) {
{
String username = params[1]; String username = params[1];
boolean enabled = params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes")); boolean enabled = params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes"));
Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(username); Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(username);
if (habbo != null) if (habbo != null) {
{
habbo.getHabboStats().setAllowTrade(enabled); habbo.getHabboStats().setAllowTrade(enabled);
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_allow_trading." + (enabled ? "enabled" : "disabled")).replace("%username%", params[1])); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_allow_trading." + (enabled ? "enabled" : "disabled")).replace("%username%", params[1]));
habbo.getClient().sendResponse(new UserPerksComposer(habbo)); habbo.getClient().sendResponse(new UserPerksComposer(habbo));
return true; return true;
} } else {
else
{
boolean found; boolean found;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE users_settings INNER JOIN users ON users.id = users_settings.id SET can_trade = ? WHERE users.username LIKE ?")) try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE users_settings INNER JOIN users ON users.id = users_settings.id SET can_trade = ? WHERE users.username LIKE ?")) {
{
statement.setString(1, enabled ? "1" : "0"); statement.setString(1, enabled ? "1" : "0");
statement.setString(2, username); statement.setString(2, username);
found = statement.executeUpdate() > 0; found = statement.executeUpdate() > 0;
} }
if (!found) if (!found) {
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_allow_trading.user_not_found").replace("%username%", params[1])); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_allow_trading.user_not_found").replace("%username%", params[1]));
return true; return true;
} }
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_allow_trading." + (enabled ? "enabled" : "disabled")).replace("%username%", params[1])); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_allow_trading." + (enabled ? "enabled" : "disabled")).replace("%username%", params[1]));
} }
} } else {
else
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_allow_trading.incorrect_setting").replace("%enabled%", Emulator.getTexts().getValue("generic.yes")).replace("%disabled%", Emulator.getTexts().getValue("generic.no"))); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_allow_trading.incorrect_setting").replace("%enabled%", Emulator.getTexts().getValue("generic.yes")).replace("%disabled%", Emulator.getTexts().getValue("generic.no")));
} }
return true; return true;

View File

@ -3,17 +3,14 @@ package com.eu.habbo.habbohotel.commands;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles; import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
public class ArcturusCommand extends Command public class ArcturusCommand extends Command {
{ public ArcturusCommand() {
public ArcturusCommand()
{
super(null, new String[]{"arcturus", "emulator"}); super(null, new String[]{"arcturus", "emulator"});
} }
@Override @Override
public boolean handle(GameClient gameClient, String[] params) throws Exception public boolean handle(GameClient gameClient, String[] params) throws Exception {
{ if (gameClient.getHabbo().getHabboInfo().getCurrentRoom() != null) {
if(gameClient.getHabbo().getHabboInfo().getCurrentRoom() != null)
{
gameClient.getHabbo().whisper("This hotel is powered by Arcturus Emulator! \r" + gameClient.getHabbo().whisper("This hotel is powered by Arcturus Emulator! \r" +
"Cet hôtel est alimenté par Arcturus émulateur! \r" + "Cet hôtel est alimenté par Arcturus émulateur! \r" +
"Dit hotel draait op Arcturus Emulator! \r" + "Dit hotel draait op Arcturus Emulator! \r" +

View File

@ -10,69 +10,50 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class BadgeCommand extends Command public class BadgeCommand extends Command {
{ public BadgeCommand() {
public BadgeCommand()
{
super("cmd_badge", Emulator.getTexts().getValue("commands.keys.cmd_badge").split(";")); super("cmd_badge", Emulator.getTexts().getValue("commands.keys.cmd_badge").split(";"));
} }
@Override @Override
public boolean handle(GameClient gameClient, String[] params) throws Exception public boolean handle(GameClient gameClient, String[] params) throws Exception {
{ if (params.length == 1) {
if(params.length == 1)
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_badge.forgot_username"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_badge.forgot_username"), RoomChatMessageBubbles.ALERT);
return true; return true;
} }
if(params.length == 2) if (params.length == 2) {
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_badge.forgot_badge").replace("%user%", params[1]), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_badge.forgot_badge").replace("%user%", params[1]), RoomChatMessageBubbles.ALERT);
return true; return true;
} }
if(params.length == 3) if (params.length == 3) {
{
Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(params[1]); Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(params[1]);
if(habbo != null) if (habbo != null) {
{ if (habbo.addBadge(params[2])) {
if (habbo.addBadge(params[2]))
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_badge.given").replace("%user%", params[1]).replace("%badge%", params[2]), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_badge.given").replace("%user%", params[1]).replace("%badge%", params[2]), RoomChatMessageBubbles.ALERT);
} } else {
else
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_badge.already_owned").replace("%user%", params[1]).replace("%badge%", params[2]), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_badge.already_owned").replace("%user%", params[1]).replace("%badge%", params[2]), RoomChatMessageBubbles.ALERT);
} }
return true; return true;
} } else {
else try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection())
{
boolean found; boolean found;
try (PreparedStatement statement = connection.prepareStatement("SELECT `badge_code` FROM `users_badges` INNER JOIN `users` ON `users`.`id` = `user_id` WHERE `users`.`username` = ? AND `badge_code` = ? LIMIT 1")) try (PreparedStatement statement = connection.prepareStatement("SELECT `badge_code` FROM `users_badges` INNER JOIN `users` ON `users`.`id` = `user_id` WHERE `users`.`username` = ? AND `badge_code` = ? LIMIT 1")) {
{
statement.setString(1, params[1]); statement.setString(1, params[1]);
statement.setString(2, params[2]); statement.setString(2, params[2]);
try (ResultSet set = statement.executeQuery()) try (ResultSet set = statement.executeQuery()) {
{
found = set.next(); found = set.next();
} }
} }
if(found) if (found) {
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_badge.already_owns").replace("%user%", params[1]).replace("%badge%", params[2]), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_badge.already_owns").replace("%user%", params[1]).replace("%badge%", params[2]), RoomChatMessageBubbles.ALERT);
return true; return true;
} } else {
else try (PreparedStatement statement = connection.prepareStatement("INSERT INTO users_badges (`id`, `user_id`, `slot_id`, `badge_code`) VALUES (null, (SELECT `id` FROM `users` WHERE `username` = ? LIMIT 1), 0, ?)")) {
{
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO users_badges (`id`, `user_id`, `slot_id`, `badge_code`) VALUES (null, (SELECT `id` FROM `users` WHERE `username` = ? LIMIT 1), 0, ?)"))
{
statement.setString(1, params[1]); statement.setString(1, params[1]);
statement.setString(2, params[2]); statement.setString(2, params[2]);
statement.execute(); statement.execute();
@ -81,9 +62,7 @@ public class BadgeCommand extends Command
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_badge.given").replace("%user%", params[1]).replace("%badge%", params[2]), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_badge.given").replace("%user%", params[1]).replace("%badge%", params[2]), RoomChatMessageBubbles.ALERT);
return true; return true;
} }
} } catch (SQLException e) {
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e); Emulator.getLogging().logSQLException(e);
} }
} }

View File

@ -9,47 +9,37 @@ import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.habbohotel.users.HabboInfo; import com.eu.habbo.habbohotel.users.HabboInfo;
import com.eu.habbo.habbohotel.users.HabboManager; import com.eu.habbo.habbohotel.users.HabboManager;
public class BanCommand extends Command public class BanCommand extends Command {
{ public BanCommand() {
public BanCommand()
{
super("cmd_ban", Emulator.getTexts().getValue("commands.keys.cmd_ban").split(";")); super("cmd_ban", Emulator.getTexts().getValue("commands.keys.cmd_ban").split(";"));
} }
@Override @Override
public boolean handle(GameClient gameClient, String[] params) throws Exception public boolean handle(GameClient gameClient, String[] params) throws Exception {
{ if (params.length < 2) {
if(params.length < 2)
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.forgot_user"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.forgot_user"), RoomChatMessageBubbles.ALERT);
return true; return true;
} }
if(params.length < 3) if (params.length < 3) {
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.forgot_time"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.forgot_time"), RoomChatMessageBubbles.ALERT);
return true; return true;
} }
int banTime; int banTime;
try try {
{
banTime = Integer.valueOf(params[2]); banTime = Integer.valueOf(params[2]);
} } catch (Exception e) {
catch (Exception e)
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.invalid_time"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.invalid_time"), RoomChatMessageBubbles.ALERT);
return true; return true;
} }
if(banTime < 600) if (banTime < 600) {
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.time_to_short"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.time_to_short"), RoomChatMessageBubbles.ALERT);
return true; return true;
} }
if(params[1].toLowerCase().equals(gameClient.getHabbo().getHabboInfo().getUsername().toLowerCase())) if (params[1].toLowerCase().equals(gameClient.getHabbo().getHabboInfo().getUsername().toLowerCase())) {
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.ban_self"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.ban_self"), RoomChatMessageBubbles.ALERT);
return true; return true;
} }
@ -57,23 +47,18 @@ public class BanCommand extends Command
Habbo t = Emulator.getGameEnvironment().getHabboManager().getHabbo(params[1]); Habbo t = Emulator.getGameEnvironment().getHabboManager().getHabbo(params[1]);
HabboInfo target; HabboInfo target;
if (t != null) if (t != null) {
{
target = t.getHabboInfo(); target = t.getHabboInfo();
} } else {
else
{
target = HabboManager.getOfflineHabboInfo(params[1]); target = HabboManager.getOfflineHabboInfo(params[1]);
} }
if (target == null) if (target == null) {
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.user_offline"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.user_offline"), RoomChatMessageBubbles.ALERT);
return true; return true;
} }
if (target.getRank().getId() >= gameClient.getHabbo().getHabboInfo().getRank().getId()) if (target.getRank().getId() >= gameClient.getHabbo().getHabboInfo().getRank().getId()) {
{
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.target_rank_higher"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.target_rank_higher"), RoomChatMessageBubbles.ALERT);
return true; return true;
} }
@ -81,10 +66,8 @@ public class BanCommand extends Command
StringBuilder reason = new StringBuilder(); StringBuilder reason = new StringBuilder();
if(params.length > 3) if (params.length > 3) {
{ for (int i = 3; i < params.length; i++) {
for(int i = 3; i < params.length; i++)
{
reason.append(params[i]).append(" "); reason.append(params[i]).append(" ");
} }
} }

View File

@ -4,18 +4,14 @@ import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles; import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
public class BlockAlertCommand extends Command public class BlockAlertCommand extends Command {
{ public BlockAlertCommand() {
public BlockAlertCommand()
{
super("cmd_blockalert", Emulator.getTexts().getValue("commands.keys.cmd_blockalert").split(";")); super("cmd_blockalert", Emulator.getTexts().getValue("commands.keys.cmd_blockalert").split(";"));
} }
@Override @Override
public boolean handle(GameClient gameClient, String[] params) throws Exception public boolean handle(GameClient gameClient, String[] params) throws Exception {
{ if (gameClient.getHabbo().getHabboInfo().getCurrentRoom() != null) {
if(gameClient.getHabbo().getHabboInfo().getCurrentRoom() != null)
{
gameClient.getHabbo().getHabboStats().blockStaffAlerts = !gameClient.getHabbo().getHabboStats().blockStaffAlerts; gameClient.getHabbo().getHabboStats().blockStaffAlerts = !gameClient.getHabbo().getHabboStats().blockStaffAlerts;
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_blockalert").replace("%state%", (gameClient.getHabbo().getHabboStats().blockStaffAlerts ? Emulator.getTexts().getValue("generic.on") : Emulator.getTexts().getValue("generic.off"))), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_blockalert").replace("%state%", (gameClient.getHabbo().getHabboStats().blockStaffAlerts ? Emulator.getTexts().getValue("generic.on") : Emulator.getTexts().getValue("generic.off"))), RoomChatMessageBubbles.ALERT);

Some files were not shown because too many files have changed in this diff Show More